Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: d4e054262a1d7051f975e12f9aefda4f1c93be05 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
/*******************************************************************************
 * Copyright (c) 2012 protos software gmbh (http://www.protos.de).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * CONTRIBUTORS:
 * 		Henrik Rentz-Reichert (initial contribution)
 * 
 *******************************************************************************/

package org.eclipse.etrice.generator.generic

import com.google.inject.Inject
import java.util.ArrayList
import java.util.List
import org.eclipse.etrice.core.room.ActorCommunicationType
import org.eclipse.etrice.core.room.State
import org.eclipse.etrice.core.room.Transition
import org.eclipse.etrice.core.room.GuardedTransition
import org.eclipse.etrice.core.room.TriggeredTransition
import org.eclipse.etrice.core.room.NonInitialTransition
import org.eclipse.etrice.core.genmodel.etricegen.ExpandedActorClass
import org.eclipse.etrice.core.genmodel.etricegen.ExpandedRefinedState
import org.eclipse.etrice.core.genmodel.etricegen.ActiveTrigger
import org.eclipse.etrice.generator.generic.RoomExtensions
import org.eclipse.etrice.generator.base.AbstractGenerator
import org.eclipse.xtext.util.Pair
import org.eclipse.etrice.generator.generic.TransitionChainGenerator
import org.eclipse.etrice.core.room.TransitionPoint

import static org.eclipse.xtext.util.Tuples.*

import static extension org.eclipse.etrice.generator.base.CodegenHelpers.*
import static extension org.eclipse.etrice.core.room.util.RoomHelpers.*
import static extension org.eclipse.etrice.core.genmodel.etricegen.util.ETriceGenUtil.*

/**
 * A target language independent generator of the state machine implementation-
 */
class GenericStateMachineGenerator {

	@Inject protected extension RoomExtensions
	@Inject protected ILanguageExtension langExt
	@Inject protected GenericProtocolClassGenerator pcGen
	@Inject protected TransitionChainGenerator transitionChainGenerator

	/**
	 * generates state ID constants.
	 * Inheritance (if available) is used for base class IDs.
	 * 
	 * @param xpac the {@link ExpandedActorClass}
	 * @return the generated code
	 */
	def protected genStateIdConstants(ExpandedActorClass xpac) {
		val ac = xpac.actorClass
		// with inheritance we exclude inherited base states
		var offset = 2 + if (langExt.usesInheritance)
			ac.getNumberOfInheritedBaseStates() else 0
		var baseStates = if (langExt.usesInheritance)
			ac.stateMachine.getBaseStateList else xpac.stateMachine.getBaseStateList
		
		baseStates = baseStates.leafStatesLast
		
		var list = new ArrayList<Pair<String, String>>()
		if (!langExt.usesInheritance) {
			list.add(pair("NO_STATE","0"))
			list.add(pair("STATE_TOP","1"))
		}
		for (state : baseStates) {
			list.add(pair(state.getGenStateId, offset.toString))
			offset = offset+1;
		}
		list.add(pair("STATE_MAX", offset.toString))
		
		return langExt.genEnumeration("state_ids", list)
	}
	
	/**
	 * generates transition chain ID constants.
	 * Inheritance (if available) is used for base class IDs.
	 * 
	 * @param xpac the {@link ExpandedActorClass}
	 * @return the generated code
	 */
	def protected genTransitionChainConstants(ExpandedActorClass xpac) {
		var chains = if (langExt.usesInheritance)
			xpac.getOwnTransitionChains() else xpac.transitionChains
		var offset = if (langExt.usesInheritance)
			xpac.getTransitionChains().size-chains.size else 0

		var list = new ArrayList<Pair<String, String>>()
		for (chain : chains) {
			offset = offset+1;
			list.add(pair(chain.genChainId, offset.toString))
		}
		
		return langExt.genEnumeration("chain_ids", list)
	}
	
	/**
	 * generates trigger IDs.
	 * Inheritance (if available) is used for base class IDs.
	 * 
	 * @param xpac the {@link ExpandedActorClass}
	 * @return the generated code
	 */
	def protected genTriggerConstants(ExpandedActorClass xpac) {
		val triggers = if (langExt.usesInheritance)
					xpac.actorClass.ownMessagesFromInterfaces
					else xpac.actorClass.allMessagesFromInterfaces
		
		val list = new ArrayList<Pair<String, String>>()
		list.add(pair("POLLING", "0"));
		for (mif : triggers) {
			list.add(pair(xpac.getTriggerCodeName(mif), "IFITEM_"+mif.from.name+" + EVT_SHIFT*"+pcGen.getMessageID(mif)))
		}
		
		return langExt.genEnumeration("triggers", list)
	}
	
	/**
	 * generates the code of the whole state machine
	 * 
	 * @param xpac the {@link ExpandedActorClass}
	 * @return the generated code
	 * 
	 * @see {@link #genStateMachine}
	 */
	def genStateMachine(ExpandedActorClass xpac) {
		xpac.genStateMachine(true)
	}
	
	/**
	 * generates the code of the whole state machine
	 * 
	 * @param xpac the {@link ExpandedActorClass}
	 * @param shallGenerateOneFile if <code>true</code> the generation of state IDs and
	 * 		other constants is skipped (and left for the header file)
	 * @return the generated code
	 */
	def genStateMachine(ExpandedActorClass xpac, boolean shallGenerateOneFile) {
		val ac = xpac.actorClass
		val async = ac.commType==ActorCommunicationType::ASYNCHRONOUS
		val eventDriven = ac.commType==ActorCommunicationType::EVENT_DRIVEN
		val handleEvents = async || eventDriven
		val opScope = langExt.operationScope(ac.name, false)
		val opScopePriv = if (langExt.usesInheritance)
							opScope
						else
							""
		val publicIf = if (langExt.usesInheritance)
				langExt.accessLevelPublic
			else
				langExt.accessLevelPrivate
		val privAccess = langExt.accessLevelPrivate
		val self = langExt.selfPointer(ac.name, true)
		val selfOnly = langExt.selfPointer(ac.name, false)
		val getLocalId = 	if (langExt.usesInheritance) {
								if (langExt.usesPointers)
									"->getLocalId()"
								else
									".getLocalId()"
							}
							else
								"->localId"
		val ifItemPtr = "InterfaceItemBase"+langExt.pointerLiteral()
		val constIfItemPtr = if (langExt.usesPointers)
								"const "+ifItemPtr
							else
								ifItemPtr
		val usesHdlr = usesHandlerTrPoints(xpac)
		
	'''
		«IF shallGenerateOneFile»
		/* state IDs */
		«xpac.genStateIdConstants»
		
		/* transition chains */
		«xpac.genTransitionChainConstants»
		
		/* triggers */
		«xpac.genTriggerConstants»
		«ENDIF»

		«genExtra(xpac)»
		
		/* Entry and Exit Codes */
		«FOR state : xpac.stateMachine.getStateList()»
			«IF !langExt.usesInheritance || xpac.isOwnObject(state)»
				«xpac.genActionCodeMethods(state)»
			«ENDIF»
		«ENDFOR»
		
		/* Action Codes */
		«FOR tr : xpac.stateMachine.allTransitionsRecursive»
			«IF (!langExt.usesInheritance || xpac.isOwnObject(tr)) && tr.action.hasDetailCode»
				«var start = xpac.getChain(tr)?.transition»
				«var hasArgs = start instanceof NonInitialTransition && !(start instanceof GuardedTransition)»
				«langExt.accessLevelProtected»void «opScopePriv»«tr.getActionCodeOperationName()»(«langExt.selfPointer(ac.name, hasArgs)»«IF hasArgs»«constIfItemPtr» ifitem«transitionChainGenerator.generateArgumentList(xpac, tr)»«ENDIF») {
					«AbstractGenerator::getInstance().getTranslatedCode(tr.action)»
				}
			«ENDIF»
		«ENDFOR»
		
		/**
		 * calls exit codes while exiting from the current state to one of its
		 * parent states while remembering the history
		 * @param current - the current state
		 * @param to - the final parent state
		 «IF usesHdlr»
		 * @param handler - entry and exit codes are called only if not handler (for handler TransitionPoints)
		 «ENDIF»
		 */
		«privAccess»void «opScopePriv»exitTo(«self»«stateType» current, «stateType» to«IF usesHdlr», «boolType» handler«ENDIF») {
			while (current!=to) {
				switch (current) {
					«FOR state : xpac.stateMachine.getBaseStateList()»
						case «state.getGenStateId()»:
							«IF state.hasExitCode(true)»«IF usesHdlr»if (!handler) «ENDIF»«state.getExitCodeOperationName()»(«langExt.selfPointer(false)»);«ENDIF»
							«setHistory(state.getParentStateId(), state.getGenStateId())»;
							current = «state.getParentStateId()»;
							break;
					«ENDFOR»
					default:
						/* should not occur */
						break;
				}
			}
		}
		
		/**
		 * calls action, entry and exit codes along a transition chain. The generic data are cast to typed data
		 * matching the trigger of this chain. The ID of the final state is returned
		 * @param chain - the chain ID
		 * @param generic_data - the generic data pointer
		 * @return the +/- ID of the final state either with a positive sign, that indicates to execute the state's entry code, or a negative sign vice versa
		 */
		«privAccess»«stateType» «opScopePriv»executeTransitionChain(«self»int chain«IF handleEvents», «constIfItemPtr» ifitem, «langExt.voidPointer» generic_data«ENDIF») {
			switch (chain) {
				«var allchains = xpac.getTransitionChains()»
				«FOR tc : allchains»
					case «tc.genChainId»:
					{
						«transitionChainGenerator.generateExecuteChain(xpac, tc)»
					}
				«ENDFOR»
					default:
						/* should not occur */
						break;
			}
			return NO_STATE;
		}
		
		/**
		 * calls entry codes while entering a state's history. The ID of the final leaf state is returned
		 * @param state - the state which is entered
		 «IF usesHdlr»
		 * @param handler - entry code is executed if not handler
		 «ENDIF»
		 * @return - the ID of the final leaf state
		 */
		«privAccess»«stateType» «opScopePriv»enterHistory(«self»«stateType» state«IF usesHdlr», «boolType» handler«ENDIF») {
			«boolType» skip_entry = «langExt.booleanConstant(false)»;
			if (state >= STATE_MAX) {
				state = «IF !langExt.usesInheritance»(«stateType»)«ENDIF» (state - STATE_MAX);
				skip_entry = «langExt.booleanConstant(true)»;
			}
			while («langExt.booleanConstant(true)») {
				switch (state) {
					«FOR state : xpac.stateMachine.getBaseStateList()»
					case «state.getGenStateId()»:
						«IF state.hasEntryCode(true)»if (!(skip_entry«IF usesHdlr» || handler«ENDIF»)) «state.getEntryCodeOperationName()»(«langExt.selfPointer(false)»);«ENDIF»
						«IF state.isLeaf()»
							/* in leaf state: return state id */
							return «state.getGenStateId()»;
						«ELSE»
							/* state has a sub graph */
							«IF state.subgraph.hasInitTransition()»
								/* with init transition */
								if («getHistory(state.getGenStateId())»==NO_STATE) {
									«var sub_initt = state.subgraph.getInitTransition()»
									state = executeTransitionChain(«langExt.selfPointer(true)»«xpac.getChain(sub_initt).genChainId»«IF handleEvents», «langExt.nullPointer», «langExt.nullPointer»«ENDIF»);
								}
								else {
									state = «getHistory(state.getGenStateId())»;
								}
							«ELSE»
								/* without init transition */
								state = «getHistory(state.getGenStateId())»;
							«ENDIF»
							break;
						«ENDIF»
					«ENDFOR»
					case STATE_TOP:
						state = «getHistory("STATE_TOP")»;
						break;
					default:
						/* should not occur */
						break;
				}
				skip_entry = «langExt.booleanConstant(false)»;
			}
			«unreachableReturn»
		}
		
		«publicIf»void «opScope»executeInitTransition(«selfOnly») {
			«var initt = xpac.stateMachine.getInitTransition()»
			int chain = «xpac.getChain(initt).genChainId»;
			«stateType» next = «opScopePriv»executeTransitionChain(«langExt.selfPointer(true)»chain«IF handleEvents», «langExt.nullPointer», «langExt.nullPointer»«ENDIF»);
			next = «opScopePriv»enterHistory(«langExt.selfPointer(true)»next«IF usesHdlr», «langExt.booleanConstant(false)»«ENDIF»);
			setState(«langExt.selfPointer(true)»next);
		}
		
		/* receiveEvent contains the main implementation of the FSM */
		«publicIf»void «opScope»receiveEvent(«langExt.selfPointer(ac.name, handleEvents)»«IF handleEvents»«ifItemPtr» ifitem, int evt, «langExt.voidPointer» generic_data«ENDIF») {
			«IF async»
				int trigger = (ifitem==«langExt.nullPointer»)? POLLING : ifitem«getLocalId» + EVT_SHIFT*evt;
			«ELSEIF eventDriven»
				int trigger = ifitem«getLocalId» + EVT_SHIFT*evt;
			«ENDIF»
			int chain = NOT_CAUGHT;
			«stateType» catching_state = NO_STATE;
			«IF usesHdlr»
			«boolType» is_handler = «langExt.booleanConstant(false)»;
			«ENDIF»
			
			«IF handleEvents»
				if (!handleSystemEvent(ifitem, evt, generic_data)) {
					«genStateSwitch(xpac, usesHdlr)»
				}
			«ELSE»
				«genStateSwitch(xpac, usesHdlr)»
			«ENDIF»
			if (chain != NOT_CAUGHT) {
				«opScopePriv»exitTo(«langExt.selfPointer(true)»getState(«langExt.selfPointer(false)»), catching_state«IF usesHdlr», is_handler«ENDIF»);
				{
					«stateType» next = «opScopePriv»executeTransitionChain(«langExt.selfPointer(true)»chain«IF handleEvents», ifitem, generic_data«ENDIF»);
					next = «opScopePriv»enterHistory(«langExt.selfPointer(true)»next«IF usesHdlr», is_handler«ENDIF»);
					setState(«langExt.selfPointer(true)»next);
					«finalAction()»
				}
			}
		}
	'''}
	
	/**
	 * empty, but may be overridden
	 */
	def finalAction() {
		''''''
	}

	
	/**
	 * helper method which generates the state switch.
	 * Asynchronous, data driven and event driven state machines are distinguished
	 * 
	 * @param xpac the {@link ExpandedActorClass}
	 * @param usesHdlr if the state machine uses no handler {@link TransitionPoints}
	 * 		at all then unused variables can be avoided by passing <code>true</code> 
	 * @return the generated code
	 */
	def protected genStateSwitch(ExpandedActorClass xpac, boolean usesHdlr) {
		var async = xpac.actorClass.commType==ActorCommunicationType::ASYNCHRONOUS
		var eventDriven = xpac.actorClass.commType==ActorCommunicationType::EVENT_DRIVEN
		var dataDriven = xpac.actorClass.commType==ActorCommunicationType::DATA_DRIVEN
		'''
			switch (getState(«langExt.selfPointer(false)»)) {
				«FOR state : xpac.stateMachine.getLeafStateList()»
				case «state.getGenStateId()»:
					«IF async»
						«var atlist =  xpac.getActiveTriggers(state)»
						«IF !atlist.isEmpty»
							switch(trigger) {
								case POLLING:
									«genDataDrivenTriggers(xpac, state, usesHdlr)»
									break;
								«genEventDrivenTriggers(xpac, state, atlist, usesHdlr)»
							}
						«ELSE»
								«genDataDrivenTriggers(xpac, state, usesHdlr)»
						«ENDIF»
					«ELSEIF dataDriven»
							«genDataDrivenTriggers(xpac, state, usesHdlr)»
					«ELSEIF eventDriven»
						«var atlist =  xpac.getActiveTriggers(state)»
						«IF !atlist.isEmpty»
							switch(trigger) {
									«genEventDrivenTriggers(xpac, state, atlist, usesHdlr)»
							}
						«ENDIF»
					«ENDIF»
					break;
				«ENDFOR»
				default:
					/* should not occur */
					break;
			}
		'''
	}
	
	/**
	 * helper method which generates the data driven triggers
	 * 
	 * @param xpac the {@link ExpandedActorClass}
	 * @param state the {@link State} for which the trigger if-else switch should be generated
	 * @param usesHdlr if the state machine uses no handler {@link TransitionPoints}
	 * 		at all then unused variables can be avoided by passing <code>true</code> 
	 * @return the generated code
	 */
	def protected genDataDrivenTriggers(ExpandedActorClass xpac, State state, boolean usesHdlr) {
		'''
			«genDoCodes(state)»
			«var transitions = xpac.getOutgoingTransitionsHierarchical(state).filter(t|t instanceof GuardedTransition)»
			«FOR tr : transitions»
				if («AbstractGenerator::getInstance().getTranslatedCode((tr as GuardedTransition).guard)»)
				{
					«var chain = xpac.getChain(tr)»
					chain = «chain.genChainId»;
					catching_state = «chain.stateContext.genStateId»;
					«IF chain.isHandler() && usesHdlr»
						is_handler = TRUE;
					«ENDIF»
				}
				«IF tr!=transitions.last»
					else 
				«ENDIF»
			«ENDFOR»
		'''
	}
	
	/**
	 * helper method which generates the event driven triggers
	 * 
	 * @param xpac the {@link ExpandedActorClass}
	 * @param state the {@link State} for which the trigger switch should be generated
	 * @param atlist the list of {@link ActiveTrigger}s of this state
	 * @param usesHdlr if the state machine uses no handler {@link TransitionPoints}
	 * 		at all then unused variables can be avoided by passing <code>true</code> 
	 * @return the generated code
	 */
	def protected genEventDrivenTriggers(ExpandedActorClass xpac, State state, List<ActiveTrigger> atlist, boolean usesHdlr) {
		'''
			«FOR at : atlist»
				case «xpac.getTriggerCodeName(at)»:
					«var needData = at.hasGuard»
					«IF needData»{ «langExt.getTypedDataDefinition(at.msg)»«ENDIF»
					«FOR tt : at.transitions SEPARATOR " else "»
						«var chain = xpac.getChain(tt)»
						«guard(chain.transition, at.trigger, xpac)»
						{
							chain = «chain.genChainId»;
							catching_state = «chain.stateContext.genStateId»;
							«IF chain.isHandler() && usesHdlr»
								is_handler = «langExt.booleanConstant(true)»;
							«ENDIF»
						}
					«ENDFOR»
					«IF needData»}«ENDIF»
				break;
			«ENDFOR»
			default:
				/* should not occur */
				break;
		'''
	}
	
	/**
	 * getter for history array
	 * 
	 * @param state the ID of the history state
	 * @return the generated code
	 */
	def protected getHistory(String state) {
		langExt.memberAccess+"history["+state+"]"
	}

	/**
	 * setter for history array
	 * 
	 * @param the ID of the state whose history should be set
	 * @param the ID of the state that should be assigned
	 * @return the generated code
	 */
	def protected setHistory(String state, String historyState) {
		langExt.memberAccess+"history["+state+"] = "+historyState
	}
	
	/**
	 * @return the type of (temporary) state variables (defaults to "int")
	 * and has to be signed
	 */
	def protected stateType() {
		"int"
	}

	/**
	 * allow target language dependent generation of unreachable return in generated enterHistory method.
	 * The default is just a comment.
	 * @return the generated code
	 */	
	def protected unreachableReturn() {
		"/* return NO_STATE; // required by CDT but detected as unreachable by JDT because of while (true) */"
	}

	/**
	 * type of (temporary) boolean variables (defaults to "boolean")
	 * @return the generated code
	 */
	def protected boolType() {
		return "boolean"
	}
	
	/**
	 * let derived class add extra code after definition of constants
	 * 
	 * @param xpac an expanded actor class
	 * @return the generated code
	 */
	def protected genExtra(ExpandedActorClass xpac) {''''''}
	
	/**
	 * let derived class add extra code after definition of constants in header (if applicable)
	 * 
	 * @param xpac an expanded actor class
	 * @return the generated code
	 */
	def protected genExtraDecl(ExpandedActorClass xpac) {''''''}

	/**
	 * generate a transition guard if applicable
	 * 
	 * @param tt a {@link TriggeredTransition}
	 * @param trigger a trigger string
	 * @param xpac an expanded actor class
	 * @return the generated code
	 */	
	def protected dispatch guard(TriggeredTransition tt, String trigger, ExpandedActorClass ac) {
		val tr = tt.triggers.findFirst(e|ac.isMatching(e, trigger))
	'''
		«IF tr.hasGuard()»
			if («AbstractGenerator::getInstance().getTranslatedCode(tr.guard.guard)»)
		«ENDIF»
	'''
	}

	/**
	 * (necessary for completeness of the dispatching, never called)
	 */
	def protected dispatch guard(Transition t, String trigger, ExpandedActorClass ac) {
	'''
		/* error */
	'''
	}
	
	/**
	 * generate the do code calls for a given state
	 * 
	 * @param state the {@link State}
	 * @return the generated code
	 */
	def protected String genDoCodes(State state) {'''
		«IF state.hasDoCode(true)»
			«state.getDoCodeOperationName()»(«langExt.selfPointer(false)»);
		«ENDIF»
		«IF state.eContainer.eContainer instanceof State»
			«genDoCodes(state.eContainer.eContainer as State)»
		«ENDIF»
	'''}
	
	/**
	 * generate action code method implementations
	 * 
	 * @param xpax the {@link ExpandedActorClass}
	 * @param state the {@link State}
	 * @return the generated code
	 */
	def protected genActionCodeMethods(ExpandedActorClass xpac, State state) {
		genActionCodeMethods(xpac, state, true);
	}

	/**
	 * generate action code method implementations or declarations
	 * 
	 * @param xpax the {@link ExpandedActorClass}
	 * @param state the {@link State}
	 * @param generateImplementation if only declarations should be generated then <code>false</code> has to be passed
	 * @return the generated code
	 */
	def protected genActionCodeMethods(ExpandedActorClass xpac, State state, boolean generateImplementation) {
		val ac = xpac.actorClass
		val selfPtr = langExt.selfPointer(xpac.actorClass.name, false)
		val opScope = langExt.operationScope(ac.name, false)
		val opScopePriv = if (langExt.usesInheritance)
							opScope
						else
							""
		val entryOp = state.getEntryCodeOperationName()
		val exitOp = state.getExitCodeOperationName()
		val doOp = state.getDoCodeOperationName()
		var entry = AbstractGenerator::getInstance().getTranslatedCode(state.entryCode)
		var exit = AbstractGenerator::getInstance().getTranslatedCode(state.exitCode)
		var docode = AbstractGenerator::getInstance().getTranslatedCode(state.doCode)
		if (state instanceof ExpandedRefinedState) {
			val rs = state as ExpandedRefinedState
			val inhEntry = AbstractGenerator::getInstance().getTranslatedCode(rs.inheritedEntry)
			val inhExit = AbstractGenerator::getInstance().getTranslatedCode(rs.inheritedExit)
			val inhDo = AbstractGenerator::getInstance().getTranslatedCode(rs.inheritedDo)
			if (langExt.usesInheritance) {
				// we call the super method in the generated code
				val baseName = xpac.actorClass.base.name
				if (rs.inheritedEntry.hasDetailCode)
					entry = langExt.superCall(baseName, entryOp, "") + entry
				if (rs.inheritedExit.hasDetailCode)
					exit = exit + langExt.superCall(baseName, exitOp, "")
				if (rs.inheritedDo.hasDetailCode)
					docode = langExt.superCall(baseName, doOp, "") + docode
			}
			else {
				// the inherited code is added directly
				entry = inhEntry + entry
				exit = exit + inhExit
				docode = inhDo + docode
			}
		}
		'''
		«IF !entry.empty»
			«IF generateImplementation»
			«langExt.accessLevelProtected»void «opScopePriv»«entryOp»(«selfPtr») {
				«entry»
			}
			«ELSE»
			«langExt.accessLevelProtected»void «entryOp»(«selfPtr»);
			«ENDIF»
		«ENDIF»
		«IF !exit.empty»
			«IF generateImplementation»
			«langExt.accessLevelProtected»void «opScopePriv»«exitOp»(«selfPtr») {
				«exit»
			}
			«ELSE»
			«langExt.accessLevelProtected»void «exitOp»(«selfPtr»);
			«ENDIF»
		«ENDIF»
		«IF !docode.empty»
			«IF generateImplementation»
			«langExt.accessLevelProtected» void «opScopePriv»«doOp»(«selfPtr») {
				«docode»
			}
			«ELSE»
			«langExt.accessLevelProtected»void «doOp»(«selfPtr»);
			«ENDIF»
		«ENDIF»
		'''
	}
	
	// TODO: move the next two methods to the C++ generator
	
	/**
	 * @param classname the name of the type
	 * @return the type name for a constant pointer
	 */
	def protected constPointer(String classname) {
		return classname	
	}

	/**
	 * generate all method declarations
	 * 
	 * @param xpax the {@link ExpandedActorClass}
	 * @return the generated code
	 */
	def genStateMachineMethodDeclarations(ExpandedActorClass xpac)
	{
		val ac = xpac.actorClass
		val async = ac.commType==ActorCommunicationType::ASYNCHRONOUS
		val eventDriven = ac.commType==ActorCommunicationType::EVENT_DRIVEN
		val handleEvents = async || eventDriven
		val self = langExt.selfPointer(ac.name, true)
		val usesHdlr = usesHandlerTrPoints(xpac)
		
	'''
		
		/* state IDs */
		«xpac.genStateIdConstants»
		
		/* transition chains */
		«xpac.genTransitionChainConstants»
		
		/* triggers */
		«xpac.genTriggerConstants»

		«genExtraDecl(xpac)»
		
		/* Entry and Exit Codes */
		«FOR state : xpac.stateMachine.getStateList()»
			«IF !langExt.usesInheritance || xpac.isOwnObject(state)»
				«xpac.genActionCodeMethods(state, false)»
			«ENDIF»
		«ENDFOR»
		
		/* Action Codes */
		«FOR tr : xpac.stateMachine.allTransitionsRecursive»
			«IF (!langExt.usesInheritance || xpac.isOwnObject(tr)) && tr.action.hasDetailCode»
				«var start = xpac.getChain(tr).transition»
				«var hasArgs = start instanceof NonInitialTransition && !(start instanceof GuardedTransition)»
				«langExt.accessLevelProtected»void «tr.getActionCodeOperationName()»(«langExt.selfPointer(ac.name, hasArgs)»«IF hasArgs»«constPointer("etRuntime::InterfaceItemBase")» ifitem«transitionChainGenerator.generateArgumentList(xpac, tr)»«ENDIF»);
			«ENDIF»
		«ENDFOR»
		
		private:
			/**
			 * calls exit codes while exiting from the current state to one of its
			 * parent states while remembering the history
			 * @param current - the current state
			 * @param to - the final parent state
			 «IF usesHdlr»
			 * @param handler - entry and exit codes are called only if not handler (for handler TransitionPoints)
			 «ENDIF»
			 */
			void exitTo(«self»int current, int to«IF usesHdlr», «boolType» handler«ENDIF»);
			
			/**
			 * calls action, entry and exit codes along a transition chain. The generic data are cast to typed data
			 * matching the trigger of this chain. The ID of the final state is returned
			 * @param chain - the chain ID
			 * @param generic_data - the generic data pointer
			 * @return the ID of the final state
			 */
			int executeTransitionChain(«self»int chain«IF handleEvents», «constPointer("etRuntime::InterfaceItemBase")» ifitem, «langExt.voidPointer» generic_data«ENDIF»);
			
			/**
			 * calls entry codes while entering a state's history. The ID of the final leaf state is returned
			 * @param state - the state which is entered
			 «IF usesHdlr»
			 * @param handler - entry code is executed if not handler
			 «ENDIF»
			 * @return - the ID of the final leaf state
			 */
			int enterHistory(«self»int state«IF usesHdlr», «boolType» handler«ENDIF»);
		
		public:

			void executeInitTransition(«langExt.selfPointer(ac.name, false)»);
			
			/* receiveEvent contains the main implementation of the FSM */
			void receiveEvent(«langExt.selfPointer(ac.name, handleEvents)»«IF handleEvents»etRuntime::InterfaceItemBase* ifitem, int evt, «langExt.voidPointer» generic_data«ENDIF»);
	'''
	}
	
	/**
	 * helper method to determine whether this state machine uses handler transitions
	 * points at all
	 * 
	 * @param xpax the {@link ExpandedActorClass}
	 * @return <code>true</code> if the state machine uses handler transition points
	 */
	def private usesHandlerTrPoints(ExpandedActorClass xpac) {
		if (xpac.stateMachine.empty)
			return false
		!xpac.stateMachine.allTrPointsRecursive.filter(t|t instanceof TransitionPoint && ((t as TransitionPoint).handler)).empty
	}
}

Back to the top