generic_generator.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. # Generic Generator by Joeri Exelmans
  2. #
  3. # Visits SCCD-domain constructs (see sccd_constructs.py) and converts them
  4. # to a generic language AST (see generic_language_constructs.py), that can
  5. # then be visited by a target language writer.
  6. import traceback
  7. import time
  8. from utils import Enum, Logger
  9. from visitor import Visitor
  10. from sccd_constructs import FormalParameter
  11. from stateful_writer import StatefulWriter
  12. import generic_language_constructs as GLC
  13. Platforms = Enum("Threads","GameLoop","EventLoop")
  14. class GenericGenerator(Visitor):
  15. def __init__(self, platform):
  16. self.platform = platform
  17. self.writer = StatefulWriter()
  18. def generic_visit(self, node):
  19. Logger.showWarning("GenericGenerator has no visit method for node of type '" + str(type(node)) + "'.")
  20. def get(self):
  21. return self.writer.get()
  22. def visit_ClassDiagram(self, class_diagram):
  23. header = ("Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)\n"
  24. "\n"
  25. "Date: " + time.asctime() + "\n")
  26. if class_diagram.name or class_diagram.author or class_diagram.description:
  27. header += "\n"
  28. if class_diagram.author:
  29. header += "Model author: " + class_diagram.author + "\n"
  30. if class_diagram.name:
  31. header += "Model name: " + class_diagram.name + "\n"
  32. if class_diagram.description.strip():
  33. header += "Model description:\n"
  34. header += class_diagram.description.strip()
  35. self.writer.addMultiLineComment(header)
  36. self.writer.addVSpace()
  37. self.writer.addInclude(([GLC.RuntimeModuleIdentifier(), "statecharts_core"]))
  38. if class_diagram.top.strip():
  39. self.writer.addRawCode(class_diagram.top)
  40. self.writer.addVSpace()
  41. self.writer.beginPackage(class_diagram.name)
  42. # visit children
  43. for c in class_diagram.classes :
  44. c.accept(self)
  45. self.writer.beginClass("ObjectManager", ["ObjectManagerBase"])
  46. self.writer.beginConstructor()
  47. self.writer.addFormalParameter("controller")
  48. self.writer.beginMethodBody()
  49. self.writer.beginSuperClassConstructorCall("ObjectManagerBase")
  50. self.writer.addActualParameter("controller")
  51. self.writer.endSuperClassConstructorCall()
  52. self.writer.endMethodBody()
  53. self.writer.endConstructor()
  54. self.writer.beginMethod("instantiate")
  55. self.writer.addFormalParameter("class_name")
  56. self.writer.addFormalParameter("construct_params")
  57. self.writer.beginMethodBody()
  58. for index,c in enumerate(class_diagram.classes):
  59. self.writer.beginElseIf(GLC.EqualsExpression("class_name", GLC.String(c.name)))
  60. if c.isAbstract():
  61. # cannot instantiate abstract class
  62. self.writer.add(GLC.ThrowExceptionStatement(GLC.String("Cannot instantiate abstract class \"" + c.name + "\" with unimplemented methods \"" + "\", \"".join(c.abstract_method_names) + "\".")))
  63. else:
  64. new_expr = GLC.NewExpression(c.name, [GLC.SelfProperty("controller")])
  65. param_count = 0
  66. for p in c.constructors[0].parameters:
  67. new_expr.getActualParameters().add(GLC.ArrayIndexedExpression("construct_params", str(param_count)))
  68. param_count += 1
  69. self.writer.addAssignment(
  70. GLC.LocalVariableDeclaration("instance"),
  71. new_expr)
  72. self.writer.addAssignment(
  73. GLC.Property("instance", "associations"),
  74. GLC.MapExpression())
  75. for a in c.associations:
  76. a.accept(self)
  77. self.writer.endElseIf()
  78. self.writer.add(GLC.ReturnStatement("instance"))
  79. self.writer.endMethodBody()
  80. self.writer.endMethod()
  81. self.writer.endClass() # ObjectManager
  82. if self.platform == Platforms.Threads:
  83. controller_sub_class = "ThreadsControllerBase"
  84. if self.platform == Platforms.EventLoop :
  85. controller_sub_class = "EventLoopControllerBase"
  86. elif self.platform == Platforms.GameLoop :
  87. controller_sub_class = "GameLoopControllerBase"
  88. self.writer.beginClass("Controller", [controller_sub_class])
  89. self.writer.beginConstructor()
  90. for p in class_diagram.default_class.constructors[0].parameters:
  91. p.accept(self)
  92. if self.platform == Platforms.EventLoop:
  93. self.writer.addFormalParameter("event_loop_callbacks")
  94. self.writer.addFormalParameter("finished_callback", GLC.NoneExpression())
  95. elif self.platform == Platforms.Threads:
  96. self.writer.addFormalParameter("keep_running", GLC.TrueExpression())
  97. self.writer.beginMethodBody()
  98. self.writer.beginSuperClassConstructorCall(controller_sub_class)
  99. self.writer.addActualParameter(GLC.NewExpression("ObjectManager", [GLC.SelfExpression()]))
  100. if self.platform == Platforms.EventLoop:
  101. self.writer.addActualParameter("event_loop_callbacks")
  102. self.writer.addActualParameter("finished_callback")
  103. elif self.platform == Platforms.Threads:
  104. self.writer.addActualParameter("keep_running")
  105. self.writer.endSuperClassConstructorCall()
  106. for i in class_diagram.inports:
  107. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("addInputPort"), [GLC.String(i)]))
  108. for o in class_diagram.outports:
  109. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("addOutputPort"), [GLC.String(o)]))
  110. actual_parameters = [p.getIdent() for p in class_diagram.default_class.constructors[0].parameters]
  111. self.writer.add(GLC.FunctionCall(GLC.Property(GLC.SelfProperty("object_manager"), "createInstance"), [GLC.String(class_diagram.default_class.name), GLC.ArrayExpression(actual_parameters)]))
  112. self.writer.endMethodBody()
  113. self.writer.endConstructor()
  114. self.writer.endClass() # Controller
  115. # visit test node if there is one
  116. if class_diagram.test:
  117. class_diagram.test.accept(self)
  118. self.writer.endPackage()
  119. ### TESTS
  120. def visit_DiagramTest(self, test):
  121. # helper class
  122. self.writer.beginClass("InputEvent")
  123. self.writer.beginConstructor()
  124. self.writer.addFormalParameter("name")
  125. self.writer.addFormalParameter("port")
  126. self.writer.addFormalParameter("parameters")
  127. self.writer.addFormalParameter("time_offset")
  128. self.writer.beginMethodBody()
  129. self.writer.addAssignment(GLC.SelfProperty("name"), "name")
  130. self.writer.addAssignment(GLC.SelfProperty("port"), "port")
  131. self.writer.addAssignment(GLC.SelfProperty("parameters"), "parameters")
  132. self.writer.addAssignment(GLC.SelfProperty("time_offset"), "time_offset")
  133. self.writer.endMethodBody()
  134. self.writer.endConstructor()
  135. self.writer.endClass()
  136. self.writer.beginClass("Test")
  137. if test.input:
  138. test.input.accept(self)
  139. else:
  140. self.writer.addStaticAttribute("input_events", GLC.ArrayExpression())
  141. if test.expected:
  142. test.expected.accept(self)
  143. else:
  144. self.writer.addStaticAttribute("expected_events", GLC.ArrayExpression())
  145. self.writer.endClass()
  146. def visit_DiagramTestInput(self, test_input):
  147. # write array of input events
  148. self.writer.startRecordingExpression()
  149. self.writer.beginArray()
  150. for e in test_input.input_events:
  151. e.accept(self)
  152. self.writer.endArray()
  153. array_expr = self.writer.stopRecordingExpression()
  154. self.writer.addStaticAttribute("input_events", array_expr)
  155. def visit_DiagramTestInputEvent(self, event):
  156. self.writer.add(GLC.NewExpression("InputEvent", [GLC.String(event.name), GLC.String(event.port), GLC.ArrayExpression(event.parameters), event.time]))
  157. def visit_DiagramTestExpected(self, test_expected):
  158. # write array of slots containing expected events
  159. self.writer.startRecordingExpression()
  160. self.writer.beginArray()
  161. for s in test_expected.slots:
  162. s.accept(self)
  163. self.writer.endArray()
  164. array_expr = self.writer.stopRecordingExpression()
  165. self.writer.addStaticAttribute("expected_events", array_expr)
  166. def visit_DiagramTestExpectedSlot(self, slot):
  167. # write slot
  168. self.writer.beginArray()
  169. for e in slot.expected_events:
  170. e.accept(self)
  171. self.writer.endArray()
  172. def visit_DiagramTestEvent(self, event):
  173. self.writer.add(GLC.NewExpression("Event", [GLC.String(event.name), GLC.String(event.port), GLC.ArrayExpression(event.parameters)]))
  174. ### CLASS
  175. def visit_Class(self, class_node):
  176. """
  177. Generate code for Class construct
  178. """
  179. super_classes = []
  180. if not class_node.super_class_objs:
  181. # if none of the class' super classes is defined in the diagram,
  182. # we have to inherit RuntimeClassBase
  183. if class_node.statechart:
  184. # only inherit RuntimeClassBase if class has a statechart
  185. super_classes.append("RuntimeClassBase")
  186. if class_node.super_classes:
  187. for super_class in class_node.super_classes:
  188. super_classes.append(super_class)
  189. self.writer.beginClass(class_node.name, super_classes)
  190. # visit constructor
  191. class_node.constructors[0].accept(self)
  192. # visit destructor
  193. class_node.destructors[0].accept(self)
  194. # visit methods
  195. for i in class_node.methods:
  196. i.accept(self)
  197. # compile and initialize Statechart
  198. if class_node.statechart:
  199. class_node.statechart.accept(self)
  200. self.writer.beginMethod("initializeStatechart")
  201. self.writer.beginMethodBody()
  202. self.writer.addComment("enter default state")
  203. # get effective target of initial transition
  204. self.writer.addAssignment(
  205. GLC.LocalVariableDeclaration("states"),
  206. GLC.FunctionCall(
  207. GLC.Property(
  208. GLC.MapIndexedExpression(
  209. GLC.SelfProperty("states"),
  210. GLC.String(class_node.statechart.root.initial)
  211. ),
  212. "getEffectiveTargetStates"
  213. )
  214. )
  215. )
  216. # update state configuration
  217. self.writer.add(
  218. GLC.FunctionCall(
  219. GLC.SelfProperty("updateConfiguration"),
  220. ["states"]
  221. )
  222. )
  223. # call enter action of states to enter, if present
  224. self.writer.beginForLoopIterateArray("states", "state")
  225. self.writer.beginElseIf(
  226. GLC.Property(
  227. "state",
  228. "enter"
  229. )
  230. )
  231. self.writer.add(
  232. GLC.FunctionCall(
  233. GLC.Property(
  234. "state",
  235. "enter"
  236. )
  237. )
  238. )
  239. self.writer.endElseIf()
  240. self.writer.endForLoopIterateArray()
  241. self.writer.endMethodBody()
  242. self.writer.endMethod()
  243. self.writer.endClass()
  244. ### CLASS -- CONSTRUCTOR
  245. def visit_Constructor(self, constructor):
  246. self.writer.beginConstructor()
  247. if constructor.parent_class.statechart:
  248. self.writer.addFormalParameter("controller")
  249. for p in constructor.getParams():
  250. self.writer.addFormalParameter(p.getIdent(), p.getDefault())
  251. self.writer.beginMethodBody() # constructor body
  252. if constructor.parent_class.statechart:
  253. self.writer.beginSuperClassConstructorCall("RuntimeClassBase")
  254. self.writer.addActualParameter("controller")
  255. self.writer.endSuperClassConstructorCall()
  256. self.writer.addVSpace()
  257. if constructor.parent_class.statechart.big_step_maximality == "take_one":
  258. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "big_step_maximality"), GLC.Property("StatechartSemantics", "TakeOne"))
  259. elif constructor.parent_class.statechart.big_step_maximality == "take_many":
  260. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "big_step_maximality"), GLC.Property("StatechartSemantics", "TakeMany"))
  261. if constructor.parent_class.statechart.internal_event_lifeline == "queue":
  262. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "internal_event_lifeline"), GLC.Property("StatechartSemantics", "Queue"))
  263. elif constructor.parent_class.statechart.internal_event_lifeline == "next_small_step":
  264. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "internal_event_lifeline"), GLC.Property("StatechartSemantics", "NextSmallStep"))
  265. elif constructor.parent_class.statechart.internal_event_lifeline == "next_combo_step":
  266. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "internal_event_lifeline"), GLC.Property("StatechartSemantics", "NextComboStep"))
  267. if constructor.parent_class.statechart.input_event_lifeline == "first_small_step":
  268. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "input_event_lifeline"), GLC.Property("StatechartSemantics", "FirstSmallStep"))
  269. elif constructor.parent_class.statechart.input_event_lifeline == "first_combo_step":
  270. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "input_event_lifeline"), GLC.Property("StatechartSemantics", "FirstComboStep"))
  271. elif constructor.parent_class.statechart.input_event_lifeline == "whole":
  272. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "input_event_lifeline"), GLC.Property("StatechartSemantics", "Whole"))
  273. if constructor.parent_class.statechart.priority == "source_parent":
  274. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "priority"), GLC.Property("StatechartSemantics", "SourceParent"))
  275. elif constructor.parent_class.statechart.priority == "source_child":
  276. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "priority"), GLC.Property("StatechartSemantics", "SourceChild"))
  277. if constructor.parent_class.statechart.concurrency == "single":
  278. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "concurrency"), GLC.Property("StatechartSemantics", "Single"))
  279. elif constructor.parent_class.statechart.concurrency == "many":
  280. self.writer.addAssignment(GLC.Property(GLC.SelfProperty("semantics"), "concurrency"), GLC.Property("StatechartSemantics", "Many"))
  281. self.writer.addVSpace()
  282. self.writer.addComment("build Statechart structure")
  283. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("build_statechart_structure"), []))
  284. for p in constructor.parent_class.inports:
  285. self.writer.addAssignment(
  286. GLC.MapIndexedExpression(GLC.SelfProperty("inports"), GLC.String(p)),
  287. GLC.FunctionCall(GLC.Property("controller", "addInputPort"), [GLC.String(p), GLC.SelfExpression()]))
  288. if constructor.parent_class.attributes:
  289. self.writer.addVSpace()
  290. self.writer.addComment("user defined attributes")
  291. for attribute in constructor.parent_class.attributes:
  292. if attribute.init_value is None :
  293. self.writer.addAssignment(GLC.SelfProperty(attribute.name), GLC.NoneExpression())
  294. else :
  295. self.writer.addAssignment(GLC.SelfProperty(attribute.name), attribute.init_value)
  296. self.writer.addVSpace()
  297. self.writer.addComment("call user defined constructor")
  298. self.writer.beginSuperClassMethodCall(constructor.parent_class.name, "user_defined_constructor")
  299. for p in constructor.getParams():
  300. # we can't do p.accept(self) here because 'p' is a FormalParameter
  301. # and we want to write it as an actual parameter
  302. self.writer.addActualParameter(p.getIdent())
  303. self.writer.endSuperClassMethodCall()
  304. self.writer.endMethodBody()
  305. self.writer.endConstructor()
  306. # user defined constructor
  307. self.writer.beginMethod("user_defined_constructor")
  308. for p in constructor.getParams():
  309. p.accept(self)
  310. self.writer.beginMethodBody()
  311. for super_class in constructor.parent_class.super_classes:
  312. # begin call
  313. if super_class in constructor.parent_class.super_class_objs:
  314. self.writer.beginSuperClassMethodCall(super_class, "user_defined_constructor")
  315. else:
  316. self.writer.beginSuperClassConstructorCall(super_class)
  317. # write actual parameters
  318. if super_class in constructor.super_class_parameters:
  319. for p in constructor.super_class_parameters[super_class]:
  320. self.writer.addActualParameter(p)
  321. # end call
  322. if super_class in constructor.parent_class.super_class_objs:
  323. self.writer.endSuperClassMethodCall()
  324. else:
  325. self.writer.endSuperClassConstructorCall()
  326. self.writer.addRawCode(constructor.body)
  327. self.writer.endMethodBody()
  328. self.writer.endMethod()
  329. def visit_FormalParameter(self, formal_parameter):
  330. self.writer.addFormalParameter(formal_parameter.getIdent(), formal_parameter.getDefault())
  331. ### CLASS -- DESTRUCTOR
  332. def visit_Destructor(self, destructor):
  333. self.writer.beginMethod("user_defined_destructor")
  334. self.writer.beginMethodBody()
  335. if destructor.body.strip():
  336. self.writer.addRawCode(destructor.body)
  337. if destructor.parent_class.super_classes:
  338. self.writer.addComment("call super class destructors")
  339. for super_class in destructor.parent_class.super_classes:
  340. # begin call
  341. if super_class in destructor.parent_class.super_class_objs:
  342. self.writer.beginSuperClassMethodCall(super_class, "user_defined_destructor")
  343. self.writer.endSuperClassMethodCall()
  344. else:
  345. self.writer.beginSuperClassDestructorCall(super_class)
  346. self.writer.endSuperClassDestructorCall()
  347. pass
  348. # self.writer.beginSuperClassMethodCall(super_class, "user_defined_destructor")
  349. # self.writer.endSuperClassMethodCall()
  350. self.writer.endMethodBody()
  351. self.writer.endMethod()
  352. ### CLASS -- METHOD
  353. def visit_Method(self, method):
  354. self.writer.addVSpace()
  355. self.writer.beginMethod(method.name, "user defined method")
  356. for p in method.parameters:
  357. p.accept(self)
  358. self.writer.beginMethodBody()
  359. self.writer.addRawCode(method.body)
  360. self.writer.endMethodBody()
  361. self.writer.endMethod()
  362. ### CLASS -- ASSOCIATION
  363. def visit_Association(self, association):
  364. self.writer.addAssignment(
  365. GLC.MapIndexedExpression(
  366. GLC.Property("instance", "associations"),
  367. GLC.String(association.name)),
  368. GLC.NewExpression("Association", [GLC.String(association.to_class), str(association.min), str(association.max)]))
  369. ### CLASS -- STATECHART
  370. def visit_StateChart(self, statechart):
  371. self.writer.addVSpace()
  372. self.writer.beginMethod("build_statechart_structure", "builds Statechart structure")
  373. self.writer.beginMethodBody()
  374. def writeState(s, i):
  375. self.writer.addVSpace()
  376. self.writer.addComment("state %s" % ("<root>" if s.is_root else s.new_full_name))
  377. index_expr = GLC.MapIndexedExpression(GLC.SelfProperty("states"), GLC.String(s.new_full_name))
  378. clazz = "State"
  379. if s.is_parallel_state:
  380. clazz = "ParallelState"
  381. elif s.is_history:
  382. if s.is_history_deep:
  383. clazz = "DeepHistoryState"
  384. else:
  385. clazz = "ShallowHistoryState"
  386. self.writer.addAssignment(
  387. index_expr,
  388. GLC.NewExpression(clazz, [str(i), GLC.SelfExpression()])
  389. )
  390. if not s.is_root:
  391. if s.enter_action.action or s.has_timers:
  392. self.writer.add(
  393. GLC.FunctionCall(
  394. GLC.Property(
  395. index_expr,
  396. "setEnter"
  397. ),
  398. [GLC.SelfProperty(s.friendly_name + "_enter")]
  399. )
  400. )
  401. if s.exit_action.action or s.has_timers:
  402. self.writer.add(
  403. GLC.FunctionCall(
  404. GLC.Property(
  405. index_expr,
  406. "setExit"
  407. ),
  408. [GLC.SelfProperty(s.friendly_name + "_exit")]
  409. )
  410. )
  411. # write all states
  412. for (i, s) in enumerate(statechart.states):
  413. writeState(s, i)
  414. # add children to composite states
  415. self.writer.addVSpace()
  416. self.writer.addComment("add children")
  417. for (i, s) in enumerate(statechart.composites):
  418. for c in s.children:
  419. self.writer.add(
  420. GLC.FunctionCall(
  421. GLC.Property(
  422. GLC.MapIndexedExpression(
  423. GLC.SelfProperty("states"),
  424. GLC.String(s.new_full_name)
  425. ),
  426. "addChild"),
  427. [GLC.MapIndexedExpression(GLC.SelfProperty("states"), GLC.String(c.new_full_name))]
  428. )
  429. )
  430. # fix tree at root, such that 'descendants' and 'ancestors' fields are filled in
  431. self.writer.add(
  432. GLC.FunctionCall(
  433. GLC.Property(
  434. GLC.MapIndexedExpression(
  435. GLC.SelfProperty("states"),
  436. GLC.String("")
  437. ),
  438. "fixTree"
  439. )
  440. )
  441. )
  442. # defaults
  443. for (i, s) in enumerate(statechart.composites):
  444. if not s.is_parallel_state:
  445. self.writer.addAssignment(
  446. GLC.Property(
  447. GLC.MapIndexedExpression(
  448. GLC.SelfProperty("states"),
  449. GLC.String(s.new_full_name)
  450. ),
  451. "default_state"
  452. ),
  453. GLC.MapIndexedExpression(
  454. GLC.SelfProperty("states"),
  455. GLC.String(s.initial)
  456. )
  457. )
  458. # transitions
  459. for s in statechart.basics + statechart.composites:
  460. if s.transitions:
  461. self.writer.addVSpace()
  462. self.writer.addComment("transition %s" % s.new_full_name)
  463. for (i, t) in enumerate(s.transitions):
  464. # instantiate new Transition instance
  465. self.writer.addAssignment(
  466. GLC.LocalVariableDeclaration(
  467. "%s_%i" % (s.friendly_name, i)
  468. ),
  469. GLC.NewExpression(
  470. "Transition",
  471. [
  472. GLC.SelfExpression(),
  473. GLC.MapIndexedExpression(
  474. GLC.SelfProperty("states"),
  475. GLC.String(s.new_full_name),
  476. ),
  477. GLC.ArrayExpression(
  478. [
  479. GLC.MapIndexedExpression(
  480. GLC.SelfProperty("states"),
  481. GLC.String(target_node.new_full_name)
  482. )
  483. for target_node in t.target.target_nodes
  484. ]
  485. )
  486. ]
  487. )
  488. )
  489. # if any action associated with transition: set executable_content to correct function (generated later)
  490. if t.action.sub_actions:
  491. self.writer.add(
  492. GLC.FunctionCall(
  493. GLC.Property(
  494. "%s_%i" % (s.friendly_name, i),
  495. "setAction"
  496. ),
  497. [GLC.SelfProperty("%s_%i_exec" % (s.friendly_name, i))]
  498. )
  499. )
  500. # if any trigger associated with transition: instantiate correct Event instance
  501. trigger = None
  502. if t.trigger.is_after:
  503. trigger = GLC.NewExpression("Event", [GLC.String("_%iafter" % (t.trigger.getAfterIndex()))])
  504. elif t.trigger.event:
  505. trigger = GLC.NewExpression("Event", [GLC.String(t.trigger.event), GLC.NoneExpression() if t.trigger.port is None else GLC.String(t.trigger.port)])
  506. if trigger:
  507. self.writer.addAssignment(
  508. GLC.Property(
  509. "%s_%i" % (s.friendly_name, i),
  510. "trigger"
  511. ),
  512. trigger
  513. )
  514. # if any guard associated with transition: set guard to correct function (generated later)
  515. if t.guard:
  516. self.writer.add(
  517. GLC.FunctionCall(
  518. GLC.Property(
  519. "%s_%i" % (s.friendly_name, i),
  520. "setGuard"
  521. ),
  522. [GLC.SelfProperty("%s_%i_guard" % (s.friendly_name, i))]
  523. )
  524. )
  525. self.writer.add(
  526. GLC.FunctionCall(
  527. GLC.Property(
  528. GLC.MapIndexedExpression(
  529. GLC.SelfProperty("states"),
  530. GLC.String(s.new_full_name)
  531. ),
  532. "addTransition"
  533. ),
  534. ["%s_%i" % (s.friendly_name, i)]
  535. )
  536. )
  537. self.writer.endMethodBody()
  538. self.writer.endMethod()
  539. # enter/exit actions
  540. for (i, s) in enumerate(statechart.composites + statechart.basics):
  541. if not s.is_root:
  542. if s.enter_action.action or s.has_timers:
  543. s.enter_action.accept(self)
  544. if s.exit_action.action or s.has_timers:
  545. s.exit_action.accept(self)
  546. # transition actions and guards
  547. for s in statechart.composites + statechart.basics:
  548. for (i, t) in enumerate(s.transitions):
  549. if t.action.sub_actions:
  550. self.writeTransitionAction(t, i)
  551. if t.hasGuard():
  552. self.writeTransitionGuard(t, i)
  553. def visit_FormalEventParameter(self, formal_event_parameter):
  554. self.writer.add(formal_event_parameter.name)
  555. def writeFormalEventParameters(self, transition):
  556. parameters = transition.getTrigger().getParameters()
  557. if(len(parameters) > 0) :
  558. for index, parameter in enumerate(parameters):
  559. self.writer.startRecordingExpression()
  560. parameter.accept(self)
  561. parameter_expr = self.writer.stopRecordingExpression()
  562. self.writer.addAssignment(
  563. GLC.LocalVariableDeclaration(parameter_expr),
  564. GLC.ArrayIndexedExpression("parameters", str(index)))
  565. def writeTransitionAction(self, transition, index):
  566. self.writer.beginMethod("%s_%i_exec" % (transition.parent_node.friendly_name, index))
  567. # parameters, start method
  568. self.writer.addFormalParameter("parameters")
  569. self.writer.beginMethodBody()
  570. # handle parameters to actually use them
  571. self.writeFormalEventParameters(transition)
  572. # write action
  573. transition.getAction().accept(self)
  574. # end method
  575. self.writer.endMethodBody()
  576. self.writer.endMethod()
  577. def writeTransitionGuard(self, transition, index):
  578. self.writer.beginMethod("%s_%i_guard" % (transition.parent_node.friendly_name, index))
  579. # parameters, start method
  580. self.writer.addFormalParameter("parameters")
  581. self.writer.beginMethodBody()
  582. # handle parameters to actually use them
  583. self.writeFormalEventParameters(transition)
  584. # get guard condition
  585. self.writer.startRecordingExpression()
  586. transition.getGuard().accept(self) # --> visit_Expression
  587. expr = self.writer.stopRecordingExpression()
  588. # return statement, end method
  589. self.writer.add(GLC.ReturnStatement(expr))
  590. self.writer.endMethodBody()
  591. self.writer.endMethod()
  592. def visit_EnterAction(self, enter_method):
  593. parent_node = enter_method.parent_node
  594. self.writer.beginMethod(parent_node.friendly_name + "_enter")
  595. self.writer.beginMethodBody()
  596. # take care of any AFTER events
  597. for transition in parent_node.transitions :
  598. trigger = transition.getTrigger()
  599. if trigger.isAfter() :
  600. self.writer.startRecordingExpression()
  601. trigger.after.accept(self)
  602. after = self.writer.stopRecordingExpression()
  603. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("addTimer"), [str(trigger.getAfterIndex()), after]))
  604. if enter_method.action:
  605. enter_method.action.accept(self)
  606. self.writer.endMethodBody()
  607. self.writer.endMethod()
  608. def visit_ExitAction(self, exit_method):
  609. parent_node = exit_method.parent_node
  610. self.writer.beginMethod(parent_node.friendly_name + "_exit")
  611. self.writer.beginMethodBody()
  612. # take care of any AFTER events
  613. for transition in parent_node.transitions:
  614. trigger = transition.getTrigger()
  615. if trigger.isAfter():
  616. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("removeTimer"), [str(trigger.getAfterIndex())]))
  617. # execute user-defined exit action if present
  618. if exit_method.action:
  619. exit_method.action.accept(self)
  620. self.writer.endMethodBody()
  621. self.writer.endMethod()
  622. # helper method
  623. def writeEnterHistory(self, entered_node, is_deep):
  624. ### OLD CODE (TODO)
  625. self.writer.beginMethod("enterHistory" + ("Deep" if is_deep else "Shallow") + "_" + entered_node.full_name)
  626. self.writer.beginMethodBody()
  627. self.writer.beginIf(GLC.EqualsExpression(
  628. GLC.ArrayLength(
  629. GLC.MapIndexedExpression(
  630. GLC.SelfProperty("history_state"),
  631. GLC.SelfProperty(entered_node.full_name))),
  632. "0"))
  633. defaults = entered_node.defaults
  634. for node in defaults:
  635. if node.is_basic :
  636. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("enter_"+node.full_name)))
  637. elif node.is_composite :
  638. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("enterDefault_"+node.full_name)))
  639. self.writer.endIf()
  640. self.writer.beginElse()
  641. children = entered_node.children
  642. if entered_node.is_parallel_state:
  643. for child in children:
  644. if not child.is_history :
  645. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("enter_"+child.full_name)))
  646. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("enterHistory"+("Deep" if is_deep else "Shallow")+"_"+child.full_name)))
  647. else:
  648. for child in children:
  649. if not child.is_history :
  650. self.writer.beginIf(GLC.ArrayContains(
  651. GLC.MapIndexedExpression(
  652. GLC.SelfProperty("history_state"),
  653. GLC.SelfProperty(entered_node.full_name)),
  654. GLC.SelfProperty(child.full_name)))
  655. if child.is_composite:
  656. if is_deep :
  657. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("enter_"+child.full_name)))
  658. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("enterHistoryDeep_"+child.full_name)))
  659. else :
  660. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("enterDefault_"+child.full_name)))
  661. else:
  662. self.writer.add(GLC.FunctionCall(GLC.SelfProperty("enter_"+child.full_name)))
  663. self.writer.endIf()
  664. self.writer.endElse()
  665. self.writer.endMethodBody()
  666. self.writer.endMethod()
  667. def visit_SelfReference(self, self_reference):
  668. self.writer.add(GLC.SelfExpression())
  669. def visit_StateReference(self, state_ref):
  670. self.writer.beginArray()
  671. for node in state_ref.getNodes():
  672. self.writer.add(GLC.SelfProperty(node.full_name))
  673. self.writer.endArray()
  674. def visit_InStateCall(self, in_state_call):
  675. self.writer.add(
  676. GLC.FunctionCall(
  677. GLC.SelfProperty("inState"),
  678. [
  679. GLC.ArrayExpression(
  680. [GLC.String(state_string) for state_string in in_state_call.state_strings]
  681. )
  682. ]
  683. )
  684. )
  685. def visit_Expression(self, expression):
  686. self.writer.startRecordingExpression()
  687. self.writer.beginGlue()
  688. for part in expression.expression_parts:
  689. part.accept(self)
  690. self.writer.endGlue()
  691. expr = self.writer.stopRecordingExpression()
  692. self.writer.add(expr)
  693. def visit_ExpressionPartString(self, e):
  694. self.writer.add(e.string)
  695. def visit_RaiseEvent(self, raise_event):
  696. self.writer.startRecordingExpression()
  697. self.writer.begin(GLC.NewExpression("Event"))
  698. self.writer.addActualParameter(GLC.String(raise_event.getEventName()))
  699. if raise_event.isOutput():
  700. self.writer.addActualParameter(GLC.String(raise_event.getPort()))
  701. else:
  702. self.writer.addActualParameter(GLC.NoneExpression())
  703. self.writer.end()
  704. new_event_expr = self.writer.stopRecordingExpression()
  705. self.writer.startRecordingExpression()
  706. self.writer.beginArray()
  707. if raise_event.isCD():
  708. self.writer.add(GLC.SelfExpression())
  709. for param in raise_event.getParameters() :
  710. param.accept(self) # -> visit_Expression will cause expressions to be added to array
  711. self.writer.endArray()
  712. parameters_array_expr = self.writer.stopRecordingExpression()
  713. new_event_expr.getActualParameters().add(parameters_array_expr)
  714. if raise_event.isNarrow():
  715. self.writer.add(GLC.FunctionCall(
  716. GLC.Property(GLC.SelfProperty("big_step"), "outputEventOM"), [
  717. GLC.NewExpression("Event", [
  718. GLC.String("narrow_cast"),
  719. GLC.NoneExpression(),
  720. GLC.ArrayExpression([
  721. GLC.SelfExpression(),
  722. raise_event.getTarget(),
  723. new_event_expr])])]))
  724. elif raise_event.isLocal():
  725. self.writer.add(GLC.FunctionCall(
  726. GLC.SelfProperty("raiseInternalEvent"),
  727. [new_event_expr]))
  728. elif raise_event.isOutput():
  729. self.writer.add(GLC.FunctionCall(
  730. GLC.Property(GLC.SelfProperty("big_step"), "outputEvent"),
  731. [new_event_expr]))
  732. elif raise_event.isCD():
  733. self.writer.add(GLC.FunctionCall(
  734. GLC.Property(GLC.SelfProperty("big_step"), "outputEventOM"),
  735. [new_event_expr]))
  736. elif raise_event.isBroad():
  737. self.writer.add(GLC.FunctionCall(
  738. GLC.Property(GLC.SelfProperty("big_step"), "outputEventOM"),
  739. [GLC.NewExpression("Event", [
  740. GLC.String("broad_cast"),
  741. GLC.NoneExpression(),
  742. GLC.ArrayExpression([
  743. new_event_expr])])]))
  744. def visit_Script(self, script):
  745. self.writer.addRawCode(script.code)
  746. def visit_Log(self, log):
  747. self.writer.add(GLC.LogStatement(log.message))
  748. def visit_Assign(self, assign):
  749. self.writer.startRecordingExpression()
  750. assign.lvalue.accept(self) # --> visit_Expression
  751. lvalue = self.writer.stopRecordingExpression()
  752. self.writer.startRecordingExpression()
  753. assign.expression.accept(self) # --> visit_Expression
  754. rvalue = self.writer.stopRecordingExpression()
  755. self.writer.addAssignment(lvalue, rvalue)