rust.py 42 KB

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