rust.py 35 KB

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