rust.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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
  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. # after event
  51. return "After" + event_name.replace('+', '')
  52. else:
  53. return "Event_" + event_name
  54. def ident_event_field(event_name: str) -> str:
  55. return "e_" + event_name
  56. class StatechartRustGenerator(ActionLangRustGenerator):
  57. def __init__(self, w, globals):
  58. super().__init__(w)
  59. self.globals = globals
  60. def visit_RaiseOutputEvent(self, a):
  61. # TODO: evaluate event parameters
  62. self.w.writeln("(ctrl.output)(OutEvent{port:\"%s\", event:\"%s\"});" % (a.outport, a.name))
  63. def visit_RaiseInternalEvent(self, a):
  64. self.w.writeln("internal.raise().%s = Some(%s{});" % (ident_event_field(a.name), (ident_event_type(a.name))))
  65. def visit_Code(self, a):
  66. a.block.accept(self)
  67. def visit_State(self, state):
  68. # visit children first
  69. for c in state.real_children:
  70. c.accept(self)
  71. # Write 'current state' types
  72. if isinstance(state.type, AndState):
  73. self.w.writeln("// And-state")
  74. # TODO: Only annotate Copy for states that will be recorded by deep history.
  75. self.w.writeln("#[derive(Default, Copy, Clone)]")
  76. self.w.writeln("struct %s {" % ident_type(state))
  77. for child in state.real_children:
  78. self.w.writeln(" %s: %s," % (ident_field(child), ident_type(child)))
  79. self.w.writeln("}")
  80. elif isinstance(state.type, OrState):
  81. self.w.writeln("// Or-state")
  82. self.w.writeln("#[derive(Copy, Clone)]")
  83. self.w.writeln("enum %s {" % ident_type(state))
  84. for child in state.real_children:
  85. self.w.writeln(" %s(%s)," % (ident_enum_variant(child), ident_type(child)))
  86. self.w.writeln("}")
  87. # Write "default" constructor
  88. # We use Rust's Default-trait to record default states,
  89. # this way, constructing a state instance without parameters will initialize it as the default state.
  90. if isinstance(state.type, OrState):
  91. self.w.writeln("impl Default for %s {" % ident_type(state))
  92. self.w.writeln(" fn default() -> Self {")
  93. self.w.writeln(" Self::%s(Default::default())" % (ident_enum_variant(state.type.default_state)))
  94. self.w.writeln(" }")
  95. self.w.writeln("}")
  96. # Implement trait 'State': enter/exit
  97. # self.w.writeln("impl<'a, OutputCallback: FnMut(OutEvent)> State<Timers, Controller<InEvent, OutputCallback>> for %s {" % ident_type(state))
  98. # self.w.writeln("impl<'a, OutputCallback: FnMut(OutEvent)> %s {" % ident_type(state))
  99. self.w.writeln("impl %s {" % ident_type(state))
  100. # Enter actions: Executes enter actions of only this state
  101. # self.w.writeln(" fn enter_actions(timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  102. self.w.writeln(" fn enter_actions<OutputCallback: FnMut(OutEvent)>(timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  103. self.w.writeln(" eprintln!(\"enter %s\");" % state.full_name);
  104. self.w.indent(); self.w.indent()
  105. for a in state.enter:
  106. a.accept(self)
  107. # compile_actions(state.enter, w)
  108. self.w.dedent(); self.w.dedent()
  109. for a in state.after_triggers:
  110. self.w.writeln(" timers[%d] = ctrl.set_timeout(%d, InEvent::%s);" % (a.after_id, a.delay.opt, ident_event_type(a.enabling[0].name)))
  111. self.w.writeln(" }")
  112. # Enter actions: Executes exit actions of only this state
  113. # self.w.writeln(" fn exit_actions(timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  114. self.w.writeln(" fn exit_actions<OutputCallback: FnMut(OutEvent)>(timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  115. self.w.writeln(" eprintln!(\"exit %s\");" % state.full_name);
  116. for a in state.after_triggers:
  117. self.w.writeln(" ctrl.unset_timeout(timers[%d]);" % (a.after_id))
  118. self.w.indent(); self.w.indent()
  119. for a in state.exit:
  120. a.accept(self)
  121. # compile_actions(state.exit, w)
  122. self.w.dedent(); self.w.dedent()
  123. self.w.writeln(" }")
  124. # Enter default: Executes enter actions of entering this state and its default substates, recursively
  125. # self.w.writeln(" fn enter_default(timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  126. self.w.writeln(" fn enter_default<OutputCallback: FnMut(OutEvent)>(timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  127. self.w.writeln(" %s::enter_actions(timers, internal, ctrl);" % (ident_type(state)))
  128. if isinstance(state.type, AndState):
  129. for child in state.real_children:
  130. self.w.writeln(" %s::enter_default(timers, internal, ctrl);" % (ident_type(child)))
  131. elif isinstance(state.type, OrState):
  132. self.w.writeln(" %s::enter_default(timers, internal, ctrl);" % (ident_type(state.type.default_state)))
  133. self.w.writeln(" }")
  134. # Exit current: Executes exit actions of this state and current children, recursively
  135. # self.w.writeln(" fn exit_current(&self, timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  136. self.w.writeln(" fn exit_current<OutputCallback: FnMut(OutEvent)>(&self, timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  137. # first, children (recursion):
  138. if isinstance(state.type, AndState):
  139. for child in state.real_children:
  140. self.w.writeln(" self.%s.exit_current(timers, internal, ctrl);" % (ident_field(child)))
  141. elif isinstance(state.type, OrState):
  142. self.w.writeln(" match self {")
  143. for child in state.real_children:
  144. self.w.writeln(" Self::%s(s) => { s.exit_current(timers, internal, ctrl); }," % (ident_enum_variant(child)))
  145. self.w.writeln(" }")
  146. # then, parent:
  147. self.w.writeln(" %s::exit_actions(timers, internal, ctrl);" % (ident_type(state)))
  148. self.w.writeln(" }")
  149. # Exit current: Executes enter actions of this state and current children, recursively
  150. # self.w.writeln(" fn enter_current(&self, timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  151. self.w.writeln(" fn enter_current<OutputCallback: FnMut(OutEvent)>(&self, timers: &mut Timers, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  152. # first, parent:
  153. self.w.writeln(" %s::enter_actions(timers, internal, ctrl);" % (ident_type(state)))
  154. # then, children (recursion):
  155. if isinstance(state.type, AndState):
  156. for child in state.real_children:
  157. self.w.writeln(" self.%s.enter_current(timers, internal, ctrl);" % (ident_field(child)))
  158. elif isinstance(state.type, OrState):
  159. self.w.writeln(" match self {")
  160. for child in state.real_children:
  161. self.w.writeln(" Self::%s(s) => { s.enter_current(timers, internal, ctrl); }," % (ident_enum_variant(child)))
  162. self.w.writeln(" }")
  163. self.w.writeln(" }")
  164. self.w.writeln("}")
  165. self.w.writeln()
  166. def visit_Statechart(self, sc):
  167. if sc.semantics.concurrency == Concurrency.MANY:
  168. raise UnsupportedFeature("concurrency")
  169. priority_ordered_transitions = priority.priority_and_concurrency(sc) # may raise error
  170. tree = sc.tree
  171. self.w.writeln("type Timers = [EntryId; %d];" % tree.timer_count)
  172. self.w.writeln()
  173. # Write event types
  174. input_events = sc.internal_events & ~sc.internally_raised_events
  175. internal_events = sc.internally_raised_events
  176. internal_queue = sc.semantics.internal_event_lifeline == InternalEventLifeline.QUEUE
  177. if internal_queue:
  178. raise UnsupportedFeature("queue-like internal event semantics")
  179. internal_same_round = (
  180. sc.semantics.internal_event_lifeline == InternalEventLifeline.REMAINDER or
  181. sc.semantics.internal_event_lifeline == InternalEventLifeline.SAME)
  182. self.w.writeln("// Input Events")
  183. self.w.writeln("#[derive(Copy, Clone)]")
  184. self.w.writeln("enum InEvent {")
  185. for event_name in (self.globals.events.names[i] for i in bm_items(input_events)):
  186. self.w.writeln(" %s," % ident_event_type(event_name))
  187. self.w.writeln("}")
  188. for event_name in (self.globals.events.names[i] for i in bm_items(internal_events)):
  189. self.w.writeln("// Internal Event")
  190. self.w.writeln("struct %s {" % ident_event_type(event_name))
  191. self.w.writeln(" // TODO: event parameters")
  192. self.w.writeln("}")
  193. if not internal_queue:
  194. # Implement internal events as a set
  195. self.w.writeln("// Set of (raised) internal events")
  196. self.w.writeln("#[derive(Default)]")
  197. # Bitmap would be more efficient, but for now struct will do:
  198. self.w.writeln("struct Internal {")
  199. for event_name in (self.globals.events.names[i] for i in bm_items(internal_events)):
  200. self.w.writeln(" %s: Option<%s>," % (ident_event_field(event_name), ident_event_type(event_name)))
  201. self.w.writeln("}")
  202. if internal_same_round:
  203. self.w.writeln("type InternalLifeline = SameRoundLifeline<Internal>;")
  204. else:
  205. self.w.writeln("type InternalLifeline = NextRoundLifeline<Internal>;")
  206. elif internal_type == "queue":
  207. pass
  208. # self.w.writeln("#[derive(Copy, Clone)]")
  209. # self.w.writeln("enum Internal {")
  210. # for event_name in (self.globals.events.names[i] for i in bm_items(internal_events)):
  211. # self.w.writeln(" %s," % ident_event_type(event_name))
  212. # self.w.writeln("}")
  213. self.w.writeln()
  214. # Write state types
  215. tree.root.accept(self)
  216. syntactic_maximality = (
  217. sc.semantics.big_step_maximality == Maximality.SYNTACTIC
  218. or sc.semantics.combo_step_maximality == Maximality.SYNTACTIC)
  219. # Write arena type
  220. arenas = {}
  221. for t in tree.transition_list:
  222. arenas.setdefault(t.arena, 2**len(arenas))
  223. for arena, bm in arenas.items():
  224. for d in tree.bitmap_to_states(arena.descendants):
  225. bm |= arenas.get(d, 0)
  226. arenas[arena] = bm
  227. self.w.writeln("// Transition arenas (bitmap type)")
  228. # if syntactic_maximality:
  229. for size, typ in [(8, 'u8'), (16, 'u16'), (32, 'u32'), (64, 'u64'), (128, 'u128')]:
  230. if len(arenas) + 1 <= size:
  231. self.w.writeln("type Arenas = %s;" % typ)
  232. break
  233. else:
  234. raise UnsupportedFeature("Too many arenas! Cannot fit into an unsigned int.")
  235. self.w.writeln("const ARENA_NONE: Arenas = 0;")
  236. for arena, bm in arenas.items():
  237. self.w.writeln("const %s: Arenas = %s;" % (ident_arena_const(arena), bin(bm)))
  238. self.w.writeln("const ARENA_UNSTABLE: Arenas = %s; // indicates any transition fired with an unstable target" % bin(2**len(arenas.items())))
  239. # else:
  240. # self.w.writeln("type Arenas = bool;")
  241. # self.w.writeln("const ARENA_NONE: Arenas = false;")
  242. # for arena, bm in arenas.items():
  243. # self.w.writeln("const %s: Arenas = true;" % ident_arena_const(arena))
  244. # self.w.writeln("const ARENA_UNSTABLE: Arenas = false; // inapplicable to chosen semantics - all transition targets considered stable")
  245. self.w.writeln()
  246. # Write datamodel type
  247. # sc.scope.accept(self)
  248. # RustGenerator(w).visit_Scope(sc.scope)
  249. # self.w.writeln("struct DataModel {")
  250. # self.w.writeln(" ")
  251. # self.w.writeln(")")
  252. # Write statechart type
  253. self.w.writeln("pub struct Statechart {")
  254. self.w.writeln(" current_state: %s," % ident_type(tree.root))
  255. # We always store a history value as 'deep' (also for shallow history).
  256. # 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.
  257. for h in tree.history_states:
  258. self.w.writeln(" %s: %s," % (ident_history_field(h), ident_type(h.parent)))
  259. self.w.writeln(" timers: Timers,")
  260. self.w.writeln(" data: Scope_instance,")
  261. self.w.writeln("}")
  262. self.w.writeln("impl Default for Statechart {")
  263. self.w.writeln(" fn default() -> Self {")
  264. self.w.writeln(" Self {")
  265. self.w.writeln(" current_state: Default::default(),")
  266. for h in tree.history_states:
  267. self.w.writeln(" %s: Default::default()," % (ident_history_field(h)))
  268. self.w.writeln(" timers: Default::default(),")
  269. self.w.writeln(" data: Default::default(),")
  270. self.w.writeln(" }")
  271. self.w.writeln(" }")
  272. self.w.writeln("}")
  273. self.w.writeln()
  274. # Function fair_step: a single "Take One" Maximality 'round' (= nonoverlapping arenas allowed to fire 1 transition)
  275. self.w.writeln("fn fair_step<OutputCallback: FnMut(OutEvent)>(sc: &mut Statechart, input: Option<InEvent>, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>, dirty: Arenas) -> Arenas {")
  276. self.w.writeln(" let mut fired: Arenas = ARENA_NONE;")
  277. self.w.writeln(" let scope = &mut sc.data;")
  278. self.w.writeln(" let %s = &mut sc.current_state;" % ident_var(tree.root))
  279. self.w.indent()
  280. transitions_written = []
  281. def write_transitions(state: State):
  282. # Many of the states to exit can be computed statically (i.e. they are always the same)
  283. # The one we cannot compute statically are:
  284. #
  285. # (1) The descendants of S2, S3, etc. if S1 is part of the "exit path":
  286. #
  287. # A ---> And-state on exit path
  288. # / \ \
  289. # S1 S2 S3 ...
  290. #
  291. # |
  292. # +--> S1 also on exit path
  293. #
  294. # (2) The descendants of S, if S is the transition target
  295. #
  296. # The same applies to entering states.
  297. # Writes statements that perform exit actions
  298. # in the correct order (children (last to first), then parent) for given 'exit path'.
  299. def write_exit(exit_path: List[State]):
  300. if len(exit_path) > 0:
  301. s = exit_path[0] # state to exit
  302. if len(exit_path) == 1:
  303. # Exit s:
  304. self.w.writeln("%s.exit_current(&mut sc.timers, internal, ctrl);" % (ident_var(s)))
  305. else:
  306. # Exit children:
  307. if isinstance(s.type, AndState):
  308. for c in reversed(s.children):
  309. if exit_path[1] is c:
  310. write_exit(exit_path[1:]) # continue recursively
  311. else:
  312. self.w.writeln("%s.exit_current(&mut sc.timers, internal, ctrl);" % (ident_var(c)))
  313. elif isinstance(s.type, OrState):
  314. write_exit(exit_path[1:]) # continue recursively with the next child on the exit path
  315. # Exit s:
  316. self.w.writeln("%s::exit_actions(&mut sc.timers, internal, ctrl);" % (ident_type(s)))
  317. # Store history
  318. if s.deep_history:
  319. _, _, h = s.deep_history
  320. self.w.writeln("sc.%s = *%s; // Store deep history" % (ident_history_field(h), ident_var(s)))
  321. if s.shallow_history:
  322. _, h = s.shallow_history
  323. if isinstance(s.type, AndState):
  324. raise Exception("Shallow history makes no sense for And-state!")
  325. # Or-state:
  326. self.w.writeln("sc.%s = match %s { // Store shallow history" % (ident_history_field(h), ident_var(s)))
  327. for c in s.real_children:
  328. 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)))
  329. self.w.writeln("};")
  330. # Writes statements that perform enter actions
  331. # in the correct order (parent, children (first to last)) for given 'enter path'.
  332. def write_enter(enter_path: List[State]):
  333. if len(enter_path) > 0:
  334. s = enter_path[0] # state to enter
  335. if len(enter_path) == 1:
  336. # Target state.
  337. if isinstance(s, HistoryState):
  338. self.w.writeln("sc.%s.enter_current(&mut sc.timers, internal, ctrl); // Enter actions for history state" %(ident_history_field(s)))
  339. else:
  340. self.w.writeln("%s::enter_default(&mut sc.timers, internal, ctrl);" % (ident_type(s)))
  341. else:
  342. # Enter s:
  343. self.w.writeln("%s::enter_actions(&mut sc.timers, internal, ctrl);" % (ident_type(s)))
  344. # Enter children:
  345. if isinstance(s.type, AndState):
  346. for c in s.children:
  347. if enter_path[1] is c:
  348. write_enter(enter_path[1:]) # continue recursively
  349. else:
  350. self.w.writeln("%s::enter_default(&mut sc.timers, internal, ctrl);" % (ident_type(c)))
  351. elif isinstance(s.type, OrState):
  352. if len(s.children) > 0:
  353. write_enter(enter_path[1:]) # continue recursively with the next child on the enter path
  354. else:
  355. # If the following occurs, there's a bug in this source file
  356. raise Exception("Basic state in the middle of enter path")
  357. # The 'state' of a state is just a value in our compiled code.
  358. # When executing a transition, the value of the transition's arena changes.
  359. # This function writes statements that build a new value that can be assigned to the arena.
  360. def write_new_configuration(enter_path: List[State]):
  361. if len(enter_path) > 0:
  362. s = enter_path[0]
  363. if len(enter_path) == 1:
  364. # Construct target state.
  365. # And/Or/Basic state: Just construct the default value:
  366. self.w.writeln("let new_%s: %s = Default::default();" % (ident_var(s), ident_type(s)))
  367. else:
  368. next_child = enter_path[1]
  369. if isinstance(next_child, HistoryState):
  370. # No recursion
  371. self.w.writeln("let new_%s = sc.%s; // Restore history value" % (ident_var(s), ident_history_field(next_child)))
  372. else:
  373. if isinstance(s.type, AndState):
  374. for c in s.children:
  375. if next_child is c:
  376. write_new_configuration(enter_path[1:]) # recurse
  377. else:
  378. # Other children's default states are constructed
  379. self.w.writeln("let new_%s: %s = Default::default();" % (ident_var(c), ident_type(c)))
  380. # Construct struct
  381. 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)))
  382. elif isinstance(s.type, OrState):
  383. if len(s.children) > 0:
  384. # Or-state
  385. write_new_configuration(enter_path[1:]) # recurse
  386. # Construct enum value
  387. 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)))
  388. else:
  389. # If the following occurs, there's a bug in this source file
  390. raise Exception("Basic state in the middle of enter path")
  391. def parent():
  392. for i, t in enumerate(state.transitions):
  393. self.w.writeln("// Outgoing transition %d" % i)
  394. # 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.
  395. # However, an overlapping arena that is a descendant of ours will not have been detected.
  396. # Therefore, we must add an addition check in some cases:
  397. arenas_to_check = set()
  398. for earlier in transitions_written:
  399. if is_ancestor(parent=t.arena, child=earlier.arena):
  400. arenas_to_check.add(t.arena)
  401. if len(arenas_to_check) > 0:
  402. self.w.writeln("// A transition may have fired earlier that overlaps with our arena:")
  403. self.w.writeln("if fired & (%s) == ARENA_NONE {" % " | ".join(ident_arena_const(a) for a in arenas_to_check))
  404. self.w.indent()
  405. if t.trigger is not EMPTY_TRIGGER:
  406. condition = []
  407. for e in t.trigger.enabling:
  408. if bit(e.id) & input_events:
  409. condition.append("let Some(InEvent::%s) = &input" % ident_event_type(e.name))
  410. elif bit(e.id) & internal_events:
  411. condition.append("let Some(%s) = &internal.current().%s" % (ident_event_type(e.name), ident_event_field(e.name)))
  412. else:
  413. # Bug in SCCD :(
  414. raise Exception("Illegal event ID")
  415. self.w.writeln("if %s {" % " && ".join(condition))
  416. self.w.indent()
  417. if t.guard is not None:
  418. self.w.write("if ")
  419. t.guard.accept(self)
  420. self.w.wnoln(" {")
  421. self.w.indent()
  422. # 1. Execute transition's actions
  423. # Path from arena to source, including source but not including arena
  424. exit_path_bm = t.arena.descendants & (t.source.state_id_bitmap | t.source.ancestors) # bitmap
  425. exit_path = list(tree.bitmap_to_states(exit_path_bm)) # list of states
  426. # Path from arena to target, including target but not including arena
  427. enter_path_bm = t.arena.descendants & (t.target.state_id_bitmap | t.target.ancestors) # bitmap
  428. enter_path = list(tree.bitmap_to_states(enter_path_bm)) # list of states
  429. self.w.writeln("eprintln!(\"fire %s\");" % str(t))
  430. self.w.writeln("// Exit actions")
  431. write_exit(exit_path)
  432. if len(t.actions) > 0:
  433. self.w.writeln("// Transition's actions")
  434. for a in t.actions:
  435. a.accept(self)
  436. # compile_actions(t.actions, w)
  437. self.w.writeln("// Enter actions")
  438. write_enter(enter_path)
  439. # 2. Update state
  440. # A state configuration is just a value
  441. self.w.writeln("// Build new state configuration")
  442. write_new_configuration([t.arena] + enter_path)
  443. self.w.writeln("// Update arena configuration")
  444. self.w.writeln("*%s = new_%s;" % (ident_var(t.arena), ident_var(t.arena)))
  445. if not syntactic_maximality or t.target.stable:
  446. self.w.writeln("fired |= %s; // Stable target" % ident_arena_const(t.arena))
  447. else:
  448. self.w.writeln("fired |= ARENA_UNSTABLE; // Unstable target")
  449. if sc.semantics.internal_event_lifeline == InternalEventLifeline.NEXT_SMALL_STEP:
  450. self.w.writeln("// Internal Event Lifeline: Next Small Step")
  451. self.w.writeln("internal.cycle();")
  452. # This arena is done:
  453. self.w.writeln("break '%s;" % (ident_arena_label(t.arena)))
  454. if t.guard is not None:
  455. self.w.dedent()
  456. self.w.writeln("}")
  457. if t.trigger is not EMPTY_TRIGGER:
  458. self.w.dedent()
  459. self.w.writeln("}")
  460. if len(arenas_to_check) > 0:
  461. self.w.dedent()
  462. self.w.writeln("}")
  463. transitions_written.append(t)
  464. def child():
  465. # Here is were we recurse and write the transition code for the children of our 'state'.
  466. if isinstance(state.type, AndState):
  467. for child in state.real_children:
  468. self.w.writeln("let %s = &mut %s.%s;" % (ident_var(child), ident_var(state), ident_field(child)))
  469. for child in state.real_children:
  470. self.w.writeln("// Orthogonal region")
  471. write_transitions(child)
  472. elif isinstance(state.type, OrState):
  473. if state.type.default_state is not None:
  474. if state in arenas:
  475. self.w.writeln("if (fired | dirty) & %s == ARENA_NONE {" % ident_arena_const(state))
  476. self.w.indent()
  477. self.w.writeln("'%s: loop {" % ident_arena_label(state))
  478. self.w.indent()
  479. self.w.writeln("match %s {" % ident_var(state))
  480. for child in state.real_children:
  481. self.w.indent()
  482. self.w.writeln("%s::%s(%s) => {" % (ident_type(state), ident_enum_variant(child), ident_var(child)))
  483. self.w.indent()
  484. write_transitions(child)
  485. self.w.dedent()
  486. self.w.writeln("},")
  487. self.w.dedent()
  488. self.w.writeln("};")
  489. self.w.writeln("break;")
  490. self.w.dedent()
  491. self.w.writeln("}")
  492. if state in arenas:
  493. self.w.dedent()
  494. self.w.writeln("}")
  495. if sc.semantics.hierarchical_priority == HierarchicalPriority.SOURCE_PARENT:
  496. parent()
  497. child()
  498. elif sc.semantics.hierarchical_priority == HierarchicalPriority.SOURCE_CHILD:
  499. child()
  500. parent()
  501. elif sc.semantics.hierarchical_priority == HierarchicalPriority.NONE:
  502. # We're free to pick any semantics here, but let's not go too wild
  503. parent()
  504. child()
  505. else:
  506. raise UnsupportedFeature("Priority semantics %s" % sc.semantics.hierarchical_priority)
  507. write_transitions(tree.root)
  508. self.w.dedent()
  509. self.w.writeln(" fired")
  510. self.w.writeln("}")
  511. # Write combo step and big step function
  512. def write_stepping_function(name: str, title: str, maximality: Maximality, substep: str, cycle_input: bool, cycle_internal: bool):
  513. self.w.writeln("fn %s<OutputCallback: FnMut(OutEvent)>(sc: &mut Statechart, input: Option<InEvent>, internal: &mut InternalLifeline, ctrl: &mut Controller<InEvent, OutputCallback>, dirty: Arenas) -> Arenas {" % (name))
  514. self.w.writeln(" // %s Maximality: %s" % (title, maximality))
  515. if maximality == Maximality.TAKE_ONE:
  516. self.w.writeln(" %s(sc, input, internal, ctrl, dirty)" % (substep))
  517. else:
  518. self.w.writeln(" let mut fired: Arenas = dirty;")
  519. self.w.writeln(" let mut e = input;")
  520. self.w.writeln(" let mut ctr: u16 = 0;")
  521. self.w.writeln(" loop {")
  522. if maximality == Maximality.TAKE_MANY:
  523. self.w.writeln(" let just_fired = %s(sc, e, internal, ctrl, ARENA_NONE);" % (substep))
  524. elif maximality == Maximality.SYNTACTIC:
  525. self.w.writeln(" let just_fired = %s(sc, e, internal, ctrl, fired);" % (substep))
  526. self.w.writeln(" if just_fired == ARENA_NONE { // did any transition fire? (incl. unstable)")
  527. self.w.writeln(" break;")
  528. self.w.writeln(" }")
  529. self.w.writeln(" ctr += 1;")
  530. self.w.writeln(" assert_ne!(ctr, %d, \"too many steps (limit reached)\");" % LIMIT)
  531. self.w.writeln(" fired |= just_fired & !ARENA_UNSTABLE; // only record stable arenas")
  532. if cycle_input:
  533. self.w.writeln(" // Input Event Lifeline: %s" % sc.semantics.input_event_lifeline)
  534. self.w.writeln(" e = None;")
  535. if cycle_internal:
  536. self.w.writeln(" // Internal Event Lifeline: %s" % sc.semantics.internal_event_lifeline)
  537. self.w.writeln(" internal.cycle();")
  538. self.w.writeln(" }")
  539. self.w.writeln(" fired")
  540. self.w.writeln("}")
  541. write_stepping_function("combo_step", "Combo-Step",
  542. maximality = sc.semantics.combo_step_maximality,
  543. substep = "fair_step",
  544. cycle_input = False,
  545. cycle_internal = False)
  546. write_stepping_function("big_step", "Big-Step",
  547. maximality = sc.semantics.big_step_maximality,
  548. substep = "combo_step",
  549. cycle_input = sc.semantics.input_event_lifeline == InputEventLifeline.FIRST_COMBO_STEP,
  550. cycle_internal = sc.semantics.internal_event_lifeline == InternalEventLifeline.NEXT_COMBO_STEP)
  551. self.w.writeln()
  552. # Implement 'SC' trait
  553. self.w.writeln("impl<OutputCallback: FnMut(OutEvent)> SC<InEvent, Controller<InEvent, OutputCallback>> for Statechart {")
  554. self.w.writeln(" fn init(&mut self, ctrl: &mut Controller<InEvent, OutputCallback>) {")
  555. if sc.datamodel is not None:
  556. self.w.indent(); self.w.indent();
  557. self.w.writeln("let scope = &mut self.data;")
  558. sc.datamodel.accept(self)
  559. self.w.dedent(); self.w.dedent();
  560. self.scopes.append(sc.scope)
  561. self.w.writeln(" %s::enter_default(&mut self.timers, &mut Default::default(), ctrl)" % (ident_type(tree.root)))
  562. self.w.writeln(" }")
  563. self.w.writeln(" fn big_step(&mut self, input: Option<InEvent>, c: &mut Controller<InEvent, OutputCallback>) {")
  564. self.w.writeln(" let mut internal: InternalLifeline = Default::default();")
  565. self.w.writeln(" big_step(self, input, &mut internal, c, ARENA_NONE);")
  566. self.w.writeln(" }")
  567. self.w.writeln("}")
  568. self.w.writeln()
  569. for scope in self.scopes:
  570. scope.accept(self)
  571. self.w.writeln()
  572. if DEBUG:
  573. self.w.writeln("use std::mem::size_of;")
  574. self.w.writeln("fn debug_print_sizes() {")
  575. self.w.writeln(" eprintln!(\"------------------------\");")
  576. self.w.writeln(" eprintln!(\"info: Statechart: {} bytes\", size_of::<Statechart>());")
  577. self.w.writeln(" eprintln!(\"info: Timers: {} bytes\", size_of::<Timers>());")
  578. def write_state_size(state):
  579. self.w.writeln(" eprintln!(\"info: State %s: {} bytes\", size_of::<%s>());" % (state.full_name, ident_type(state)))
  580. for child in state.real_children:
  581. write_state_size(child)
  582. write_state_size(tree.root)
  583. self.w.writeln(" eprintln!(\"info: InEvent: {} bytes\", size_of::<InEvent>());")
  584. self.w.writeln(" eprintln!(\"info: OutEvent: {} bytes\", size_of::<OutEvent>());")
  585. self.w.writeln(" eprintln!(\"info: Arenas: {} bytes\", size_of::<Arenas>());")
  586. self.w.writeln(" eprintln!(\"------------------------\");")
  587. self.w.writeln("}")
  588. self.w.writeln()