rust.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. from typing import *
  2. import io
  3. import itertools
  4. from sccd.action_lang.codegen.rust import *
  5. from sccd.statechart.static.tree import *
  6. from sccd.util.visit_tree import *
  7. from sccd.statechart.static.statechart import *
  8. from sccd.statechart.static.globals import *
  9. from sccd.statechart.static import priority
  10. from sccd.util.indenting_writer import *
  11. # Hardcoded limit on number of sub-rounds of combo and big step to detect never-ending superrounds.
  12. # TODO: make this a model parameter, also allowing for +infinity
  13. LIMIT = 1000
  14. # Conversion functions from abstract syntax elements to identifiers in Rust
  15. def snake_case(state: State) -> str:
  16. return state.full_name.replace('/', '_');
  17. def ident_var(state: State) -> str:
  18. if state.full_name == "/":
  19. return "root" # no technical reason, it's just clearer than "s_"
  20. else:
  21. return "s" + snake_case(state)
  22. def ident_type(state: State) -> str:
  23. if state.full_name == "/":
  24. return "Root" # no technical reason, it's just clearer than "State_"
  25. else:
  26. return "State" + snake_case(state)
  27. def ident_enum_variant(state: State) -> str:
  28. # We know the direct children of a state must have unique names relative to each other,
  29. # and enum variants are scoped locally, so we can use the short name here.
  30. # Furthermore, the XML parser asserts that state ids are valid identifiers in Rust.
  31. return "S_" + state.short_name
  32. def ident_field(state: State) -> str:
  33. return "s" + snake_case(state)
  34. def ident_source_target(state: State) -> str:
  35. # drop the first '_' (this is safe, the root state itself can never be source or target)
  36. return snake_case(state)[1:]
  37. def ident_arena_label(state: State) -> str:
  38. if state.full_name == "/":
  39. return "arena_root"
  40. else:
  41. return "arena" + snake_case(state)
  42. def ident_arena_const(state: State) -> str:
  43. if state.full_name == "/":
  44. return "ARENA_ROOT"
  45. else:
  46. return "ARENA" + snake_case(state)
  47. def ident_history_field(state: HistoryState) -> str:
  48. return "history" + snake_case(state.parent) # A history state records history value for its parent
  49. def ident_event_type(event_name: str) -> str:
  50. if event_name[0] == '+':
  51. return "After" + event_name.replace('+', '')
  52. else:
  53. return "Event_" + event_name
  54. def ident_event_enum_variant(event_name: str) -> str:
  55. if event_name[0] == '+':
  56. return "A" + event_name[1:]
  57. else:
  58. return "E_" + event_name
  59. def ident_event_field(event_name: str) -> str:
  60. if event_name[0] == '+':
  61. return "a" + event_name[1:]
  62. else:
  63. return "e_" + event_name
  64. class StatechartRustGenerator(ActionLangRustGenerator):
  65. def __init__(self, w, globals):
  66. super().__init__(w)
  67. self.globals = globals
  68. self.parallel_state_cache = {}
  69. self.tree = None
  70. self.state_stack = []
  71. self.trigger = None
  72. def get_parallel_states(self, state):
  73. try:
  74. return self.parallel_state_cache[state]
  75. except KeyError:
  76. parallel_states = []
  77. while state.parent is not None:
  78. if isinstance(state.parent.type, AndState):
  79. for sibling in state.parent.children:
  80. if sibling is not state:
  81. parallel_states.append(sibling)
  82. state = state.parent
  83. self.parallel_state_cache[state] = parallel_states
  84. return parallel_states
  85. def get_parallel_states_tuple(self, state):
  86. parallel_states = self.get_parallel_states(state)
  87. if len(parallel_states) > 0:
  88. return "(" + ", ".join("*"+ident_var(s) for s in parallel_states) + ", )"
  89. else:
  90. return "()"
  91. def get_parallel_states_tuple_type(self, state):
  92. parallel_states = self.get_parallel_states(state)
  93. if len(parallel_states) > 0:
  94. return "(%s, )" % ", ".join(ident_type(s) for s in parallel_states)
  95. else:
  96. return "()"
  97. def get_parallel_states_pattern_matched(self, state):
  98. parallel_states = self.get_parallel_states(state)
  99. if len(parallel_states) > 0:
  100. return "(%s, )" % ", ".join("%s: %s" % (ident_var(s), ident_type(s)) for s in parallel_states)
  101. else:
  102. return "()"
  103. def visit_InStateMacroExpansion(self, instate):
  104. source = instate.ref.source
  105. target = instate.ref.target
  106. self.w.writeln("{ // macro expansion for @in(\"%s\")" % target.full_name)
  107. self.w.indent()
  108. # Non-exhaustive set of current states, given that 'source' is a current state
  109. parents = self.get_parallel_states(source)
  110. # Deconstruct state configuration tuple
  111. self.w.write("let (")
  112. for parent in parents:
  113. self.w.write("ref ")
  114. self.w.write(ident_var(parent))
  115. self.w.write(", ")
  116. self.w.write(") = ")
  117. self.scope.write_rvalue("@conf", instate.offset, self.w)
  118. self.w.writeln(";")
  119. for parent in parents + [source]:
  120. if is_ancestor(parent=target, child=parent):
  121. # Special case: target is parent of a current state
  122. self.w.writeln("true") # Always a current state
  123. return
  124. if not is_ancestor(parent=parent, child=target):
  125. continue # Skip
  126. # Sequence of states. First is parent. Next is the child of parent on the path to target. Last item is target.
  127. path = list(self.tree.bitmap_to_states((parent.state_id_bitmap | parent.descendants) & (target.ancestors | target.state_id_bitmap)))
  128. def write_path(path, target):
  129. parent = path[0];
  130. if parent is target:
  131. self.w.writeln("true")
  132. else:
  133. child = path[1]
  134. if isinstance(parent.type, OrState):
  135. self.w.writeln("if let %s::%s(ref %s) = %s {" % (ident_type(parent), ident_enum_variant(child), ident_var(child), ident_var(parent)))
  136. self.w.indent()
  137. write_path(path[1:], target)
  138. self.w.dedent()
  139. self.w.writeln("} else { false }")
  140. elif isinstance(parent.type, AndState):
  141. self.w.writeln("let ref %s = %s.%s;" % (ident_var(child), ident_var(parent), ident_field(child)))
  142. write_path(path[1:], target)
  143. else:
  144. raise Exception("The impossible has happened")
  145. write_path(path, target)
  146. self.w.dedent()
  147. self.w.write("}")
  148. def visit_SCCDStateConfiguration(self, type):
  149. self.w.write(self.get_parallel_states_tuple_type(type.state))
  150. def write_event_params(self, event):
  151. for param_eval_func in event.params:
  152. param_eval_func.accept(self) # param eval is a function
  153. self.w.write("(")
  154. if self.trigger is not None:
  155. self.w.write("%s, " % (self.get_parallel_states_tuple(self.state_stack[-1])))
  156. self.write_trigger_params()
  157. self.write_parent_call_params(param_eval_func.scope, skip=0) # call it!
  158. self.w.write("), ")
  159. def write_trigger_params(self):
  160. for e in self.trigger.enabling:
  161. for p in e.params_decl:
  162. self.w.write("*%s, " % p.name)
  163. def visit_RaiseOutputEvent(self, raise_event):
  164. if DEBUG:
  165. self.w.writeln("eprintln!(\"raise out %s\");" % (raise_event.name))
  166. self.w.write("(output)(OutEvent::%s(" % (ident_event_enum_variant(raise_event.name)))
  167. self.write_event_params(raise_event)
  168. self.w.writeln("));")
  169. def visit_RaiseInternalEvent(self, raise_event):
  170. if DEBUG:
  171. self.w.writeln("eprintln!(\"raise internal %s\");" % (raise_event.name))
  172. if self.internal_queue:
  173. self.w.write("sched.set_timeout(%d, InEvent::%s(" % (0, ident_event_enum_variant(raise_event.name)))
  174. self.write_event_params(raise_event)
  175. self.w.writeln("));")
  176. else:
  177. self.w.write("internal.raise().%s = Some(%s(" % (ident_event_field(raise_event.name), (ident_event_type(raise_event.name))))
  178. self.write_event_params(raise_event)
  179. self.w.writeln("));")
  180. def visit_Code(self, a):
  181. self.w.write()
  182. a.block.accept(self) # block is a function
  183. self.w.write("(") # call it...
  184. if self.trigger is not None:
  185. self.w.write("%s, " % self.get_parallel_states_tuple(self.state_stack[-1]))
  186. self.write_trigger_params()
  187. self.write_parent_call_params(a.block.scope, skip=0) # call it!
  188. self.w.writeln(");")
  189. def visit_State(self, state):
  190. self.state_stack.append(state)
  191. # visit children first
  192. for c in state.real_children:
  193. c.accept(self)
  194. # Write 'current state' types
  195. if isinstance(state.type, AndState):
  196. self.w.writeln("// And-state")
  197. # We need Copy for states that will be recorded as history.
  198. self.w.writeln("#[derive(Default, Copy, Clone)]")
  199. self.w.writeln("struct %s {" % ident_type(state))
  200. for child in state.real_children:
  201. self.w.writeln(" %s: %s," % (ident_field(child), ident_type(child)))
  202. self.w.writeln("}")
  203. elif isinstance(state.type, OrState):
  204. self.w.writeln("// Or-state")
  205. self.w.writeln("#[derive(Copy, Clone)]")
  206. self.w.writeln("enum %s {" % ident_type(state))
  207. for child in state.real_children:
  208. self.w.writeln(" %s(%s)," % (ident_enum_variant(child), ident_type(child)))
  209. self.w.writeln("}")
  210. # Write "default" constructor
  211. # We use Rust's Default-trait to record default states,
  212. # this way, constructing a state instance without parameters will initialize it as the default state.
  213. if isinstance(state.type, OrState):
  214. self.w.writeln("impl Default for %s {" % ident_type(state))
  215. self.w.writeln(" fn default() -> Self {")
  216. self.w.writeln(" Self::%s(Default::default())" % (ident_enum_variant(state.type.default_state)))
  217. self.w.writeln(" }")
  218. self.w.writeln("}")
  219. # Implement trait 'State': enter/exit
  220. self.w.writeln("impl %s {" % ident_type(state))
  221. # Enter actions: Executes enter actions of only this state
  222. self.w.writeln(" fn enter_actions<Sched: statechart::Scheduler<InEvent=InEvent>>(timers: &mut Timers<Sched::TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut impl FnMut(OutEvent)) {")
  223. if DEBUG:
  224. self.w.writeln(" eprintln!(\"enter %s\");" % state.full_name);
  225. self.w.writeln(" let mut scope = data;")
  226. self.w.indent(); self.w.indent()
  227. for a in state.enter:
  228. a.accept(self)
  229. self.w.dedent(); self.w.dedent()
  230. for a in state.after_triggers:
  231. self.w.writeln(" timers[%d] = sched.set_timeout(%d, InEvent::%s());" % (a.after_id, a.delay.opt, ident_event_enum_variant(a.enabling[0].name)))
  232. self.w.writeln(" }")
  233. # Enter actions: Executes exit actions of only this state
  234. self.w.writeln(" fn exit_actions<Sched: statechart::Scheduler<InEvent=InEvent>>(timers: &mut Timers<Sched::TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut impl FnMut(OutEvent)) {")
  235. self.w.writeln(" let mut scope = data;")
  236. for a in state.after_triggers:
  237. self.w.writeln(" sched.unset_timeout(&timers[%d]);" % (a.after_id))
  238. self.w.indent(); self.w.indent()
  239. for a in state.exit:
  240. a.accept(self)
  241. if DEBUG:
  242. self.w.writeln(" eprintln!(\"exit %s\");" % state.full_name);
  243. self.w.dedent(); self.w.dedent()
  244. self.w.writeln(" }")
  245. # Enter default: Executes enter actions of entering this state and its default substates, recursively
  246. self.w.writeln(" fn enter_default<Sched: statechart::Scheduler<InEvent=InEvent>>(timers: &mut Timers<Sched::TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut impl FnMut(OutEvent)) {")
  247. self.w.writeln(" %s::enter_actions(timers, data, internal, sched, output);" % (ident_type(state)))
  248. if isinstance(state.type, AndState):
  249. for child in state.real_children:
  250. self.w.writeln(" %s::enter_default(timers, data, internal, sched, output);" % (ident_type(child)))
  251. elif isinstance(state.type, OrState):
  252. self.w.writeln(" %s::enter_default(timers, data, internal, sched, output);" % (ident_type(state.type.default_state)))
  253. self.w.writeln(" }")
  254. # Exit current: Executes exit actions of this state and current children, recursively
  255. self.w.writeln(" fn exit_current<Sched: statechart::Scheduler<InEvent=InEvent>>(&self, timers: &mut Timers<Sched::TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut impl FnMut(OutEvent)) {")
  256. # first, children (recursion):
  257. if isinstance(state.type, AndState):
  258. for child in state.real_children:
  259. self.w.writeln(" self.%s.exit_current(timers, data, internal, sched, output);" % (ident_field(child)))
  260. elif isinstance(state.type, OrState):
  261. self.w.writeln(" match self {")
  262. for child in state.real_children:
  263. self.w.writeln(" Self::%s(s) => { s.exit_current(timers, data, internal, sched, output); }," % (ident_enum_variant(child)))
  264. self.w.writeln(" }")
  265. # then, parent:
  266. self.w.writeln(" %s::exit_actions(timers, data, internal, sched, output);" % (ident_type(state)))
  267. self.w.writeln(" }")
  268. # Exit current: Executes enter actions of this state and current children, recursively
  269. self.w.writeln(" fn enter_current<Sched: statechart::Scheduler<InEvent=InEvent>>(&self, timers: &mut Timers<Sched::TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut impl FnMut(OutEvent)) {")
  270. # first, parent:
  271. self.w.writeln(" %s::enter_actions(timers, data, internal, sched, output);" % (ident_type(state)))
  272. # then, children (recursion):
  273. if isinstance(state.type, AndState):
  274. for child in state.real_children:
  275. self.w.writeln(" self.%s.enter_current(timers, data, internal, sched, output);" % (ident_field(child)))
  276. elif isinstance(state.type, OrState):
  277. self.w.writeln(" match self {")
  278. for child in state.real_children:
  279. self.w.writeln(" Self::%s(s) => { s.enter_current(timers, data, internal, sched, output); }," % (ident_enum_variant(child)))
  280. self.w.writeln(" }")
  281. self.w.writeln(" }")
  282. self.w.writeln("}")
  283. self.w.writeln()
  284. self.state_stack.pop()
  285. def visit_Statechart(self, sc):
  286. self.scope.push(sc.scope)
  287. self.w.writeln("use std::ops::Deref;")
  288. self.w.writeln("use std::ops::DerefMut;")
  289. self.w.writeln();
  290. self.w.writeln("use sccd::action_lang;")
  291. self.w.writeln("use sccd::inherit_struct;")
  292. self.w.writeln("use sccd::call_closure;")
  293. self.w.writeln("use sccd::statechart;")
  294. self.w.writeln("use sccd::statechart::EventLifeline;")
  295. self.w.writeln();
  296. if sc.semantics.concurrency == Concurrency.MANY:
  297. raise UnsupportedFeature("concurrency")
  298. priority_ordered_transitions = priority.priority_and_concurrency(sc) # may raise error
  299. tree = sc.tree
  300. self.tree = tree
  301. self.w.writeln("type Timers<TimerId> = [TimerId; %d];" % tree.timer_count)
  302. self.w.writeln()
  303. self.internal_queue = sc.semantics.internal_event_lifeline == InternalEventLifeline.QUEUE
  304. # Write event types
  305. if self.internal_queue:
  306. input_events = {key: val for key,val in itertools.chain(sc.in_events.items(), sc.internal_events.items())}
  307. internal_events = {}
  308. else:
  309. input_events = sc.in_events
  310. internal_events = sc.internal_events
  311. internal_same_round = (
  312. sc.semantics.internal_event_lifeline == InternalEventLifeline.REMAINDER or
  313. sc.semantics.internal_event_lifeline == InternalEventLifeline.SAME)
  314. self.w.writeln("// Input Events")
  315. self.w.writeln("#[cfg_attr(target_arch = \"wasm32\", wasm_bindgen)]")
  316. self.w.writeln("#[derive(Copy, Clone, Debug)]")
  317. self.w.writeln("pub enum InEvent {")
  318. for event_name in input_events:
  319. self.w.write(" %s(" % (ident_event_enum_variant(event_name)))
  320. for param_type in input_events[event_name]:
  321. param_type.accept(self)
  322. self.w.write(", ")
  323. self.w.writeln("),")
  324. self.w.writeln("}")
  325. self.w.writeln()
  326. self.w.writeln("// Internal Events")
  327. for event_name in internal_events:
  328. self.w.write("struct %s(" % ident_event_type(event_name))
  329. for param_type in internal_events[event_name]:
  330. param_type.accept(self)
  331. self.w.write(", ")
  332. self.w.writeln(");")
  333. # Implement internal events as a set
  334. self.w.writeln("#[derive(Default)]")
  335. self.w.writeln("struct Internal {")
  336. for event_name in internal_events:
  337. self.w.writeln(" %s: Option<%s>," % (ident_event_field(event_name), ident_event_type(event_name)))
  338. self.w.writeln("}")
  339. if self.internal_queue:
  340. # Treat internal events like input events
  341. self.w.writeln("type InternalLifeline = ();") # Unit type
  342. else:
  343. if internal_same_round:
  344. self.w.writeln("type InternalLifeline = statechart::SameRoundLifeline<Internal>;")
  345. else:
  346. self.w.writeln("type InternalLifeline = statechart::NextRoundLifeline<Internal>;")
  347. self.w.writeln()
  348. # Output events
  349. # output_event_names = self.globals.out_events.names
  350. self.w.writeln("// Output Events")
  351. self.w.writeln("#[cfg_attr(target_arch = \"wasm32\", wasm_bindgen)]")
  352. self.w.writeln("#[derive(Copy, Clone, Debug, PartialEq, Eq)]")
  353. self.w.writeln("pub enum OutEvent {")
  354. for event_name in sc.out_events:
  355. self.w.write(" %s(" % (ident_event_enum_variant(event_name)))
  356. for param_type in sc.out_events[event_name]:
  357. param_type.accept(self)
  358. self.w.write(", ")
  359. self.w.writeln("),")
  360. self.w.writeln("}")
  361. self.w.writeln()
  362. syntactic_maximality = (
  363. sc.semantics.big_step_maximality == Maximality.SYNTACTIC
  364. or sc.semantics.combo_step_maximality == Maximality.SYNTACTIC)
  365. # Write arena type
  366. arenas = {}
  367. for t in tree.transition_list:
  368. arenas.setdefault(t.arena, 2**len(arenas))
  369. for arena, bm in arenas.items():
  370. for d in tree.bitmap_to_states(arena.descendants):
  371. bm |= arenas.get(d, 0)
  372. arenas[arena] = bm
  373. self.w.writeln("// Transition arenas (bitmap type)")
  374. for size, typ in [(8, 'u8'), (16, 'u16'), (32, 'u32'), (64, 'u64'), (128, 'u128')]:
  375. if len(arenas) + 1 <= size:
  376. self.w.writeln("type Arenas = %s;" % typ)
  377. break
  378. else:
  379. raise UnsupportedFeature("Too many arenas! Cannot fit into an unsigned int.")
  380. self.w.writeln("const ARENA_NONE: Arenas = 0;")
  381. for arena, bm in arenas.items():
  382. self.w.writeln("const %s: Arenas = %s;" % (ident_arena_const(arena), bin(bm)))
  383. self.w.writeln("const ARENA_UNSTABLE: Arenas = %s; // indicates any transition fired with an unstable target" % bin(2**len(arenas.items())))
  384. self.w.writeln()
  385. # Write statechart type
  386. self.w.writeln("impl<Sched: statechart::Scheduler> Default for Statechart<Sched> {")
  387. self.w.writeln(" fn default() -> Self {")
  388. self.w.writeln(" // Initialize data model")
  389. self.w.writeln(" let scope = action_lang::Empty{};")
  390. self.w.indent(); self.w.indent();
  391. if sc.datamodel is not None:
  392. sc.datamodel.accept(self)
  393. datamodel_type = self.scope.commit(sc.scope.size(), self.w)
  394. self.w.dedent(); self.w.dedent();
  395. self.w.writeln(" Self {")
  396. self.w.writeln(" configuration: Default::default(),")
  397. for h in tree.history_states:
  398. self.w.writeln(" %s: Default::default()," % (ident_history_field(h)))
  399. self.w.writeln(" timers: Default::default(),")
  400. self.w.writeln(" data: scope,")
  401. self.w.writeln(" }")
  402. self.w.writeln(" }")
  403. self.w.writeln("}")
  404. self.w.writeln("type DataModel = %s;" % datamodel_type)
  405. self.w.writeln("pub struct Statechart<Sched: statechart::Scheduler> {")
  406. self.w.writeln(" configuration: %s," % ident_type(tree.root))
  407. # We always store a history value as 'deep' (also for shallow history).
  408. # TODO: We may save a tiny bit of space in some rare cases by storing shallow history as only the exited child of the Or-state.
  409. for h in tree.history_states:
  410. self.w.writeln(" %s: %s," % (ident_history_field(h), ident_type(h.parent)))
  411. self.w.writeln(" timers: Timers<Sched::TimerId>,")
  412. self.w.writeln(" data: DataModel,")
  413. self.w.writeln("}")
  414. self.w.writeln()
  415. # Function fair_step: a single "Take One" Maximality 'round' (= nonoverlapping arenas allowed to fire 1 transition)
  416. self.w.writeln("fn fair_step<Sched: statechart::Scheduler<InEvent=InEvent>>(sc: &mut Statechart<Sched>, input: &mut Option<InEvent>, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut impl FnMut(OutEvent), dirty: Arenas) -> Arenas {")
  417. self.w.writeln(" let mut fired: Arenas = ARENA_NONE;")
  418. self.w.writeln(" let mut scope = &mut sc.data;")
  419. self.w.writeln(" let %s = &mut sc.configuration;" % ident_var(tree.root))
  420. self.w.indent()
  421. transitions_written = []
  422. def write_transitions(state: State):
  423. self.state_stack.append(state)
  424. # Many of the states to exit can be computed statically (i.e. they are always the same)
  425. # The one we cannot compute statically are:
  426. #
  427. # (1) The descendants of S2, S3, etc. if S1 is part of the "exit path":
  428. #
  429. # A ---> And-state on exit path
  430. # / \ \
  431. # S1 S2 S3 ...
  432. #
  433. # |
  434. # +--> S1 also on exit path
  435. #
  436. # (2) The descendants of S, if S is the transition target
  437. #
  438. # The same applies to entering states.
  439. # Writes statements that perform exit actions
  440. # in the correct order (children (last to first), then parent) for given 'exit path'.
  441. def write_exit(exit_path: List[State]):
  442. if len(exit_path) > 0:
  443. s = exit_path[0] # state to exit
  444. if len(exit_path) == 1:
  445. # Exit s:
  446. self.w.writeln("%s.exit_current(&mut sc.timers, scope, internal, sched, output);" % (ident_var(s)))
  447. else:
  448. # Exit children:
  449. if isinstance(s.type, AndState):
  450. for c in reversed(s.children):
  451. if exit_path[1] is c:
  452. write_exit(exit_path[1:]) # continue recursively
  453. else:
  454. self.w.writeln("%s.exit_current(&mut sc.timers, scope, internal, sched, output);" % (ident_var(c)))
  455. elif isinstance(s.type, OrState):
  456. write_exit(exit_path[1:]) # continue recursively with the next child on the exit path
  457. # Exit s:
  458. self.w.writeln("%s::exit_actions(&mut sc.timers, scope, internal, sched, output);" % (ident_type(s)))
  459. # Store history
  460. if s.deep_history:
  461. _, _, h = s.deep_history
  462. self.w.writeln("sc.%s = *%s; // Store deep history" % (ident_history_field(h), ident_var(s)))
  463. if s.shallow_history:
  464. _, h = s.shallow_history
  465. if isinstance(s.type, AndState):
  466. raise Exception("Shallow history makes no sense for And-state!")
  467. # Or-state:
  468. self.w.writeln("sc.%s = match %s { // Store shallow history" % (ident_history_field(h), ident_var(s)))
  469. for c in s.real_children:
  470. self.w.writeln(" %s::%s(_) => %s::%s(%s::default())," % (ident_type(s), ident_enum_variant(c), ident_type(s), ident_enum_variant(c), ident_type(c)))
  471. self.w.writeln("};")
  472. # Writes statements that perform enter actions
  473. # in the correct order (parent, children (first to last)) for given 'enter path'.
  474. def write_enter(enter_path: List[State]):
  475. if len(enter_path) > 0:
  476. s = enter_path[0] # state to enter
  477. if len(enter_path) == 1:
  478. # Target state.
  479. if isinstance(s, HistoryState):
  480. self.w.writeln("sc.%s.enter_current(&mut sc.timers, scope, internal, sched, output); // Enter actions for history state" %(ident_history_field(s)))
  481. else:
  482. self.w.writeln("%s::enter_default(&mut sc.timers, scope, internal, sched, output);" % (ident_type(s)))
  483. else:
  484. # Enter s:
  485. self.w.writeln("%s::enter_actions(&mut sc.timers, scope, internal, sched, output);" % (ident_type(s)))
  486. # Enter children:
  487. if isinstance(s.type, AndState):
  488. for c in s.children:
  489. if enter_path[1] is c:
  490. write_enter(enter_path[1:]) # continue recursively
  491. else:
  492. self.w.writeln("%s::enter_default(&mut sc.timers, scope, internal, sched, output);" % (ident_type(c)))
  493. elif isinstance(s.type, OrState):
  494. if len(s.children) > 0:
  495. write_enter(enter_path[1:]) # continue recursively with the next child on the enter path
  496. else:
  497. # If the following occurs, there's a bug in this source file
  498. raise Exception("Basic state in the middle of enter path")
  499. # The 'state' of a state is just a value in our compiled code.
  500. # When executing a transition, the value of the transition's arena changes.
  501. # This function writes statements that build a new value that can be assigned to the arena.
  502. def write_new_configuration(enter_path: List[State]):
  503. if len(enter_path) > 0:
  504. s = enter_path[0]
  505. if len(enter_path) == 1:
  506. # Construct target state.
  507. # And/Or/Basic state: Just construct the default value:
  508. self.w.writeln("let new_%s: %s = Default::default();" % (ident_var(s), ident_type(s)))
  509. else:
  510. next_child = enter_path[1]
  511. if isinstance(next_child, HistoryState):
  512. # No recursion
  513. self.w.writeln("let new_%s = sc.%s; // Restore history value" % (ident_var(s), ident_history_field(next_child)))
  514. else:
  515. if isinstance(s.type, AndState):
  516. for c in s.children:
  517. if next_child is c:
  518. write_new_configuration(enter_path[1:]) # recurse
  519. else:
  520. # Other children's default states are constructed
  521. self.w.writeln("let new_%s: %s = Default::default();" % (ident_var(c), ident_type(c)))
  522. # Construct struct
  523. self.w.writeln("let new_%s = %s{%s:new_%s, ..Default::default()};" % (ident_var(s), ident_type(s), ident_field(next_child), ident_var(next_child)))
  524. elif isinstance(s.type, OrState):
  525. if len(s.children) > 0:
  526. # Or-state
  527. write_new_configuration(enter_path[1:]) # recurse
  528. # Construct enum value
  529. self.w.writeln("let new_%s = %s::%s(new_%s);" % (ident_var(s), ident_type(s), ident_enum_variant(next_child), ident_var(next_child)))
  530. else:
  531. # If the following occurs, there's a bug in this source file
  532. raise Exception("Basic state in the middle of enter path")
  533. def parent():
  534. for i, t in enumerate(state.transitions):
  535. self.trigger = t.trigger
  536. self.w.writeln("// Outgoing transition %d" % i)
  537. # If a transition with an overlapping arena that is an ancestor of ours, we wouldn't arrive here because of the "break 'arena_label" statements.
  538. # However, an overlapping arena that is a descendant of ours will not have been detected.
  539. # Therefore, we must add an addition check in some cases:
  540. arenas_to_check = set()
  541. for earlier in transitions_written:
  542. if is_ancestor(parent=t.arena, child=earlier.arena):
  543. arenas_to_check.add(t.arena)
  544. if len(arenas_to_check) > 0:
  545. self.w.writeln("// A transition may have fired earlier that overlaps with our arena:")
  546. self.w.writeln("if fired & (%s) == ARENA_NONE {" % " | ".join(ident_arena_const(a) for a in arenas_to_check))
  547. self.w.indent()
  548. if t.trigger is not EMPTY_TRIGGER:
  549. condition = []
  550. for e in t.trigger.enabling:
  551. if e.name in input_events:
  552. condition.append("let Some(InEvent::%s(%s)) = &input" % (ident_event_enum_variant(e.name), ", ".join(p.name for p in e.params_decl)))
  553. elif e.name in internal_events:
  554. condition.append("let Some(%s(%s)) = &internal.current().%s" % (ident_event_type(e.name), ", ".join(p.name for p in e.params_decl), ident_event_field(e.name)))
  555. else:
  556. print(e.name)
  557. print(input_events)
  558. print(internal_events)
  559. raise Exception("Illegal event ID - Bug in SCCD :(")
  560. self.w.writeln("if %s {" % " && ".join(condition))
  561. self.w.indent()
  562. if t.guard is not None:
  563. self.w.write("if ")
  564. t.guard.accept(self) # guard is a function...
  565. self.w.write("(") # call it!
  566. self.w.write(self.get_parallel_states_tuple(t.source))
  567. self.w.write(", ")
  568. self.write_trigger_params()
  569. self.write_parent_call_params(t.guard.scope)
  570. self.w.write(")")
  571. self.w.writeln(" {")
  572. self.w.indent()
  573. # 1. Execute transition's actions
  574. # Path from arena to source, including source but not including arena
  575. exit_path_bm = t.arena.descendants & (t.source.state_id_bitmap | t.source.ancestors) # bitmap
  576. exit_path = list(tree.bitmap_to_states(exit_path_bm)) # list of states
  577. # Path from arena to target, including target but not including arena
  578. enter_path_bm = t.arena.descendants & (t.target.state_id_bitmap | t.target.ancestors) # bitmap
  579. enter_path = list(tree.bitmap_to_states(enter_path_bm)) # list of states
  580. if DEBUG:
  581. self.w.writeln("eprintln!(\"fire %s\");" % str(t))
  582. self.w.writeln("// Exit actions")
  583. write_exit(exit_path)
  584. if len(t.actions) > 0:
  585. self.w.writeln("// Transition's actions")
  586. for a in t.actions:
  587. a.accept(self)
  588. self.w.writeln("// Enter actions")
  589. write_enter(enter_path)
  590. # 2. Update state
  591. # A state configuration is just a value
  592. self.w.writeln("// Build new state configuration")
  593. write_new_configuration([t.arena] + enter_path)
  594. self.w.writeln("// Update arena configuration")
  595. self.w.writeln("*%s = new_%s;" % (ident_var(t.arena), ident_var(t.arena)))
  596. if not syntactic_maximality or t.target.stable:
  597. self.w.writeln("fired |= %s; // Stable target" % ident_arena_const(t.arena))
  598. else:
  599. self.w.writeln("fired |= ARENA_UNSTABLE; // Unstable target")
  600. if sc.semantics.input_event_lifeline == InputEventLifeline.FIRST_SMALL_STEP:
  601. self.w.writeln("// Input Event Lifeline: First Small Step")
  602. self.w.writeln("*input = Option::None;")
  603. if sc.semantics.internal_event_lifeline == InternalEventLifeline.NEXT_SMALL_STEP:
  604. self.w.writeln("// Internal Event Lifeline: Next Small Step")
  605. self.w.writeln("internal.cycle();")
  606. # This arena is done:
  607. self.w.writeln("break '%s;" % (ident_arena_label(t.arena)))
  608. if t.guard is not None:
  609. self.w.dedent()
  610. self.w.writeln("}")
  611. if t.trigger is not EMPTY_TRIGGER:
  612. self.w.dedent()
  613. self.w.writeln("}")
  614. if len(arenas_to_check) > 0:
  615. self.w.dedent()
  616. self.w.writeln("}")
  617. transitions_written.append(t)
  618. self.trigger = None
  619. def child():
  620. # Here is were we recurse and write the transition code for the children of our 'state'.
  621. if isinstance(state.type, AndState):
  622. for child in state.real_children:
  623. self.w.writeln("let %s = &mut %s.%s;" % (ident_var(child), ident_var(state), ident_field(child)))
  624. for child in state.real_children:
  625. self.w.writeln("// Orthogonal region")
  626. write_transitions(child)
  627. elif isinstance(state.type, OrState):
  628. if state.type.default_state is not None:
  629. if state in arenas:
  630. self.w.writeln("if (fired | dirty) & %s == ARENA_NONE {" % ident_arena_const(state))
  631. self.w.indent()
  632. self.w.writeln("'%s: loop {" % ident_arena_label(state))
  633. self.w.indent()
  634. self.w.writeln("match *%s {" % ident_var(state))
  635. for child in state.real_children:
  636. self.w.indent()
  637. self.w.writeln("%s::%s(ref mut %s) => {" % (ident_type(state), ident_enum_variant(child), ident_var(child)))
  638. self.w.indent()
  639. write_transitions(child)
  640. self.w.dedent()
  641. self.w.writeln("},")
  642. self.w.dedent()
  643. self.w.writeln("};")
  644. self.w.writeln("break;")
  645. self.w.dedent()
  646. self.w.writeln("}")
  647. if state in arenas:
  648. self.w.dedent()
  649. self.w.writeln("}")
  650. if sc.semantics.hierarchical_priority == HierarchicalPriority.SOURCE_PARENT:
  651. parent()
  652. child()
  653. elif sc.semantics.hierarchical_priority == HierarchicalPriority.SOURCE_CHILD:
  654. child()
  655. parent()
  656. elif sc.semantics.hierarchical_priority == HierarchicalPriority.NONE:
  657. # We're free to pick any semantics here, but let's not go too wild
  658. parent()
  659. child()
  660. else:
  661. raise UnsupportedFeature("Priority semantics %s" % sc.semantics.hierarchical_priority)
  662. self.state_stack.pop()
  663. write_transitions(tree.root)
  664. self.w.dedent()
  665. if DEBUG:
  666. self.w.writeln(" eprintln!(\"completed fair_step\");")
  667. self.w.writeln(" fired")
  668. self.w.writeln("}")
  669. # Write combo step and big step function
  670. def write_stepping_function(name: str, title: str, maximality: Maximality, substep: str, cycle_input: bool, cycle_internal: bool):
  671. self.w.writeln("fn %s<Sched: statechart::Scheduler<InEvent=InEvent>>(sc: &mut Statechart<Sched>, input: &mut Option<InEvent>, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut impl FnMut(OutEvent), dirty: Arenas) -> Arenas {" % (name))
  672. self.w.writeln(" // %s Maximality: %s" % (title, maximality))
  673. if maximality == Maximality.TAKE_ONE:
  674. self.w.writeln(" %s(sc, input, internal, sched, output, dirty)" % (substep))
  675. else:
  676. self.w.writeln(" let mut fired: Arenas = dirty;")
  677. # self.w.writeln(" let mut e = input;")
  678. self.w.writeln(" let mut ctr: u16 = 0;")
  679. self.w.writeln(" loop {")
  680. if maximality == Maximality.TAKE_MANY:
  681. self.w.writeln(" let just_fired = %s(sc, input, internal, sched, output, ARENA_NONE);" % (substep))
  682. elif maximality == Maximality.SYNTACTIC:
  683. self.w.writeln(" let just_fired = %s(sc, input, internal, sched, output, fired);" % (substep))
  684. self.w.writeln(" if just_fired == ARENA_NONE { // did any transition fire? (incl. unstable)")
  685. self.w.writeln(" break;")
  686. self.w.writeln(" }")
  687. self.w.writeln(" ctr += 1;")
  688. self.w.writeln(" assert_ne!(ctr, %d, \"too many steps (limit reached)\");" % LIMIT)
  689. self.w.writeln(" fired |= just_fired;")
  690. if cycle_input:
  691. self.w.writeln(" // Input Event Lifeline: %s" % sc.semantics.input_event_lifeline)
  692. self.w.writeln(" *input = Option::None;")
  693. if cycle_internal:
  694. self.w.writeln(" // Internal Event Lifeline: %s" % sc.semantics.internal_event_lifeline)
  695. self.w.writeln(" internal.cycle();")
  696. self.w.writeln(" }")
  697. if DEBUG:
  698. self.w.writeln(" eprintln!(\"completed %s\");" % name)
  699. self.w.writeln(" fired")
  700. self.w.writeln("}")
  701. write_stepping_function("combo_step", "Combo-Step",
  702. maximality = sc.semantics.combo_step_maximality,
  703. substep = "fair_step",
  704. cycle_input = False,
  705. cycle_internal = False)
  706. write_stepping_function("big_step", "Big-Step",
  707. maximality = sc.semantics.big_step_maximality,
  708. substep = "combo_step",
  709. cycle_input = sc.semantics.input_event_lifeline == InputEventLifeline.FIRST_COMBO_STEP,
  710. cycle_internal = sc.semantics.internal_event_lifeline == InternalEventLifeline.NEXT_COMBO_STEP)
  711. self.w.writeln()
  712. # Implement 'SC' trait
  713. self.w.writeln("impl<Sched: statechart::Scheduler<InEvent=InEvent>> statechart::SC for Statechart<Sched> {")
  714. self.w.writeln(" type InEvent = InEvent;")
  715. self.w.writeln(" type OutEvent = OutEvent;")
  716. self.w.writeln(" type Sched = Sched;")
  717. self.w.writeln()
  718. self.w.writeln(" fn init(&mut self, sched: &mut Self::Sched, output: &mut impl FnMut(Self::OutEvent)) {")
  719. self.w.writeln(" %s::enter_default(&mut self.timers, &mut self.data, &mut Default::default(), sched, output)" % (ident_type(tree.root)))
  720. self.w.writeln(" }")
  721. self.w.writeln(" fn big_step(&mut self, mut input: Option<InEvent>, sched: &mut Self::Sched, output: &mut impl FnMut(Self::OutEvent)) {")
  722. self.w.writeln(" let mut internal: InternalLifeline = Default::default();")
  723. self.w.writeln(" big_step(self, &mut input, &mut internal, sched, output, ARENA_NONE);")
  724. self.w.writeln(" }")
  725. self.w.writeln("}")
  726. self.w.writeln()
  727. # Write state types
  728. tree.root.accept(self)
  729. self.write_decls()
  730. if DEBUG:
  731. self.w.writeln("use std::mem::size_of;")
  732. self.w.writeln("fn debug_print_sizes<Sched: statechart::Scheduler>() {")
  733. self.w.writeln(" eprintln!(\"------------------------\");")
  734. self.w.writeln(" eprintln!(\"Semantics: %s\");" % sc.semantics)
  735. self.w.writeln(" eprintln!(\"------------------------\");")
  736. self.w.writeln(" eprintln!(\"info: Statechart: {} bytes\", size_of::<Statechart<Sched>>());")
  737. self.w.writeln(" eprintln!(\"info: DataModel: {} bytes\", size_of::<DataModel>());")
  738. self.w.writeln(" eprintln!(\"info: Timers: {} bytes\", size_of::<Timers<Sched::TimerId>>());")
  739. self.w.writeln(" eprintln!(\"info: History: {} bytes\", %s);" % " + ".join(["0"] + list("size_of::<%s>()" % ident_type(h.parent) for h in tree.history_states)))
  740. def write_state_size(state, indent=0):
  741. self.w.writeln(" eprintln!(\"info: %sState %s: {} bytes\", size_of::<%s>());" % (" "*indent, state.full_name, ident_type(state)))
  742. for child in state.real_children:
  743. write_state_size(child, indent+1)
  744. write_state_size(tree.root)
  745. self.w.writeln(" eprintln!(\"info: InEvent: {} bytes\", size_of::<InEvent>());")
  746. self.w.writeln(" eprintln!(\"info: OutEvent: {} bytes\", size_of::<OutEvent>());")
  747. self.w.writeln(" eprintln!(\"info: Arenas: {} bytes\", size_of::<Arenas>());")
  748. self.w.writeln(" eprintln!(\"------------------------\");")
  749. self.w.writeln("}")
  750. self.w.writeln()
  751. self.tree = None