SCCD_execute.alc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. include "primitives.alh"
  2. include "modelling.alh"
  3. include "object_operations.alh"
  4. include "utils.alh"
  5. include "random.alh"
  6. include "library.alh"
  7. Void function print_states(model : Element, data : Element):
  8. Element classes
  9. Element states
  10. Element class
  11. String state
  12. log("Current states:")
  13. classes = set_copy(data["classes"])
  14. while (read_nr_out(classes) > 0):
  15. class = set_pop(classes)
  16. log(string_join(string_join(string_join(" ", class["ID"]), " : "), read_attribute(model, class["type"], "name")))
  17. log(" Attributes: " + dict_to_string(class["attributes"]))
  18. states = set_copy(class["states"])
  19. log(" States:")
  20. while (read_nr_out(states) > 0):
  21. state = set_pop(states)
  22. log(string_join(" ", read_attribute(model, state, "name")))
  23. return!
  24. Element function filter(model : Element, set : Element, attribute_name : String, attribute_value : Element):
  25. Element keys
  26. String key
  27. Element result
  28. result = create_node()
  29. while (read_nr_out(set) > 0):
  30. key = set_pop(set)
  31. if (value_eq(read_attribute(model, key, attribute_name), attribute_value)):
  32. set_add(result, key)
  33. return result!
  34. Element function filter_exists(model : Element, set : Element, attribute_name : String):
  35. Element keys
  36. String key
  37. Element result
  38. result = create_node()
  39. while (read_nr_out(set) > 0):
  40. key = set_pop(set)
  41. if (element_neq(read_attribute(model, key, attribute_name), read_root())):
  42. set_add(result, key)
  43. return result!
  44. Element function expand_current_state(model : Element, state : String, current_states : Element):
  45. // Find the hierarchy of all current states, and select those that contain the currently selected state
  46. Element result
  47. result = create_node()
  48. current_states = set_copy(current_states)
  49. Element hierarchy
  50. String deep_state
  51. while (read_nr_out(current_states) > 0):
  52. deep_state = set_pop(current_states)
  53. hierarchy = find_hierarchy(model, deep_state)
  54. // Got the hierarchy of one of the states
  55. if (set_in(hierarchy, state)):
  56. // This hierarchy contains the root state we are checking for, so add to set
  57. set_add(result, deep_state)
  58. return result!
  59. Element function expand_initial_state(model : Element, state : String):
  60. String t
  61. t = read_type(model, state)
  62. if (t == "SCCD/CompositeState"):
  63. // Recurse further in the composite
  64. return expand_composite_state(model, state)!
  65. elif (t == "SCCD/ParallelState"):
  66. // Split up all components
  67. return expand_parallel_state(model, state)!
  68. else:
  69. // Probably just an atomic, so return this one only
  70. Element result
  71. result = create_node()
  72. set_add(result, state)
  73. return result!
  74. Element function expand_composite_state(model : Element, composite_state : String):
  75. // Resolve all initial states from a single composite state
  76. String initial
  77. // Fetch the initial state
  78. initial = set_pop(filter(model, allAssociationDestinations(model, composite_state, "SCCD/composite_children"), "isInitial", True))
  79. // Expand the initial state, depending on what it is
  80. return expand_initial_state(model, initial)!
  81. Element function expand_parallel_state(model : Element, parallel_state : String):
  82. // Resolve all initial states from a single parallel state
  83. Element children
  84. Element result
  85. Element expanded_children
  86. children = allAssociationDestinations(model, parallel_state, "SCCD/parallel_children")
  87. result = create_node()
  88. while (read_nr_out(children) > 0):
  89. set_merge(result, expand_initial_state(model, set_pop(children)))
  90. return result!
  91. Void function delete_class(model : Element, data : Element, identifier : String):
  92. // Stop a specific class instance, with attached statechart, from executing
  93. dict_delete(data["classes"], identifier)
  94. Void function start_class(model : Element, data : Element, class : String, identifier : String, parameters : Element):
  95. // Start up the class and assign its initial state to it
  96. // Create the data structure for a running class
  97. Element class_handle
  98. class_handle = create_node()
  99. dict_add(class_handle, "type", class)
  100. dict_add(class_handle, "ID", identifier)
  101. dict_add(class_handle, "timers", create_node())
  102. // Add the current state of the class
  103. String initial_state
  104. // Should only be one behaviour linked to it!
  105. initial_state = set_pop(allAssociationDestinations(model, class, "SCCD/behaviour"))
  106. dict_add(class_handle, "states", expand_initial_state(model, initial_state))
  107. // Initialize history for all composite states
  108. Element history
  109. Element cstates
  110. String cstate
  111. history = create_node()
  112. dict_add(class_handle, "history", history)
  113. cstates = allInstances(model, "SCCD/CompositeState")
  114. while (read_nr_out(cstates) > 0):
  115. cstate = set_pop(cstates)
  116. dict_add(history, cstate, expand_initial_state(model, cstate))
  117. // Add all attributes
  118. Element attributes
  119. attributes = create_node()
  120. Element attrs
  121. attrs = allAssociationDestinations(model, class, "SCCD/class_attributes")
  122. while (read_nr_out(attrs) > 0):
  123. dict_add(attributes, read_attribute(model, set_pop(attrs), "name"), read_root())
  124. dict_add(class_handle, "attributes", attributes)
  125. // Invoke constructor
  126. Element constructor
  127. constructor = read_attribute(model, class, "constructor_body")
  128. if (element_neq(constructor, read_root())):
  129. // Constructor, so execute
  130. constructor = get_func_AL_model(import_node(constructor))
  131. constructor(attributes, parameters)
  132. // Execute all entry actions
  133. Element init
  134. init = create_node()
  135. set_add(init, "")
  136. // Initial state before initialization is the set with an empty hierarchy
  137. // Empty set would not find any difference between the source and target
  138. execute_actions(model, init, set_copy(class_handle["states"]), attributes)
  139. dict_add(data["classes"], class_handle["ID"], class_handle)
  140. return!
  141. Element function get_enabled_transitions(model : Element, state : String, data : Element, class : String):
  142. // Returns all enabled transitions
  143. Element result
  144. Element to_filter
  145. String attr
  146. String transition
  147. Element cond
  148. String evt_name
  149. Element evt
  150. Element events
  151. Element event_names
  152. Element event_parameters
  153. result = create_node()
  154. to_filter = allOutgoingAssociationInstances(model, state, "SCCD/transition")
  155. event_names = create_node()
  156. event_parameters = create_node()
  157. events = set_copy(data["events"])
  158. while (read_nr_out(events) > 0):
  159. evt = set_pop(events)
  160. evt_name = list_read(evt, 0)
  161. if (bool_not(set_in(event_names, evt_name))):
  162. // Not yet registered the event
  163. set_add(event_names, evt_name)
  164. dict_add(event_parameters, evt_name, create_node())
  165. // Add event parameters
  166. set_add(event_parameters[evt_name], list_read(evt, 1))
  167. while (read_nr_out(to_filter) > 0):
  168. transition = set_pop(to_filter)
  169. // Check event
  170. attr = read_attribute(model, transition, "event")
  171. if (bool_not(bool_or(element_eq(attr, read_root()), set_in(event_names, attr)))):
  172. // At least one enabled event is found
  173. continue!
  174. // Check after
  175. // Only an after if there was no event!
  176. if (bool_and(element_eq(attr, read_root()), read_attribute(model, transition, "after"))):
  177. if (dict_in(data["classes"][class]["timers"], transition)):
  178. // Registered timer already, let's check if it has expired
  179. if (float_gt(data["classes"][class]["timers"][transition], time())):
  180. // Not enabled yet
  181. continue!
  182. else:
  183. // Not registered even, so not enabled either
  184. continue!
  185. // Check condition, but depends on whether there was an event or not
  186. cond = read_attribute(model, transition, "cond")
  187. if (element_neq(cond, read_root())):
  188. // Got a condition, so resolve
  189. cond = get_func_AL_model(import_node(cond))
  190. if (element_neq(attr, read_root())):
  191. // We have an event to take into account!
  192. Element params
  193. Element param
  194. params = set_copy(event_parameters[attr])
  195. while (read_nr_out(params) > 0):
  196. param = set_pop(params)
  197. if (element_neq(cond, read_root())):
  198. // Got a condition to check first
  199. if (bool_not(cond(data["classes"][class]["attributes"], param))):
  200. // Condition failed, so skip
  201. continue!
  202. // Fine to add this one with the specified parameters
  203. set_add(result, create_tuple(transition, param))
  204. else:
  205. // No event to think about, just add the transition
  206. if (element_neq(cond, read_root())):
  207. // Check the condition first
  208. if (bool_not(cond(data["classes"][class]["attributes"], read_root()))):
  209. // Condition false, so skip
  210. continue!
  211. // Fine to add this one without event parameters (no event)
  212. set_add(result, create_tuple(transition, read_root()))
  213. return result!
  214. Void function execute_actions(model : Element, source_states : Element, target_states : Element, class_data : Element):
  215. Element actions
  216. actions = get_actions_to_execute(model, source_states, target_states, class_data)
  217. while (read_nr_out(actions) > 0):
  218. Element action
  219. action = list_pop(actions, 0)
  220. action(class_data["attributes"])
  221. return!
  222. Element function execute_transition(model : Element, data : Element, class : String, transition_tuple : Element):
  223. // Execute the script (if any)
  224. Element script
  225. String transition
  226. Element event_parameter
  227. transition = list_read(transition_tuple, 0)
  228. event_parameter = list_read(transition_tuple, 1)
  229. script = read_attribute(model, transition, "script")
  230. if (element_neq(script, read_root())):
  231. script = get_func_AL_model(import_node(script))
  232. script(data["classes"][class]["attributes"], event_parameter)
  233. // Raise events (if any)
  234. Element events
  235. String event
  236. events = allAssociationDestinations(model, transition, "SCCD/transition_raises")
  237. while (read_nr_out(events) > 0):
  238. event = set_pop(events)
  239. Element parameter_action
  240. parameter_action = read_attribute(model, event, "parameter")
  241. if (element_neq(parameter_action, read_root())):
  242. // Got a parameter to evaluate
  243. parameter_action = get_func_AL_model(import_node(parameter_action))
  244. parameter_action = parameter_action(data["classes"][class]["attributes"], event_parameter)
  245. String scope
  246. scope = read_attribute(model, event, "scope")
  247. if (scope == "cd"):
  248. // Is an event for us internally, so don't append
  249. // Instead, we process it directly
  250. String operation
  251. operation = read_attribute(model, event, "event")
  252. if (operation == "create_instance"):
  253. // Start up a new class of the desired type
  254. // Parameters of this call:
  255. // class -- type of the class to instantiate
  256. // identifier -- name of this instance, for future reference
  257. // parameters -- parameters for constructor
  258. String class
  259. String identifier
  260. Element parameters
  261. class = set_pop(filter(model, allInstances(model, "SCCD/Class"), "name", list_read(parameter_action, 0)))
  262. identifier = list_read(parameter_action, 1)
  263. parameters = list_read(parameter_action, 2)
  264. start_class(model, data, class, identifier, parameters)
  265. elif (operation == "delete_instance"):
  266. // Delete the requested class
  267. String identifier
  268. identifier = list_read(parameter_action, 0)
  269. delete_class(model, data, identifier)
  270. else:
  271. set_add(data["events"], create_tuple(read_attribute(model, event, "event"), parameter_action))
  272. // Find new set of states
  273. Element target_states
  274. Element source_states
  275. source_states = expand_current_state(model, readAssociationSource(model, transition), data["classes"][class]["states"])
  276. target_states = expand_initial_state(model, readAssociationDestination(model, transition))
  277. execute_actions(model, source_states, target_states, data["classes"][class])
  278. return target_states!
  279. Boolean function step_class(model : Element, data : Element, class : String):
  280. // Find enabled transitions in a class and execute it, updating the state
  281. // Iterate over all current states, searching for enabled transitions
  282. // Search for enabled transitions in higher levels as well!
  283. Element states
  284. Element new_states
  285. String state
  286. Element transitions
  287. String transition
  288. Boolean transitioned
  289. Element hierarchy
  290. String current_state
  291. Boolean found
  292. states = set_copy(data["classes"][class]["states"])
  293. new_states = create_node()
  294. transitioned = False
  295. while (read_nr_out(states) > 0):
  296. state = set_pop(states)
  297. found = False
  298. // Loop over the hierarchy of this state and try to apply transitions
  299. hierarchy = find_hierarchy(model, state)
  300. while (read_nr_out(hierarchy) > 0):
  301. current_state = list_pop(hierarchy, 0)
  302. transitions = get_enabled_transitions(model, current_state, data, class)
  303. if (read_nr_out(transitions) > 0):
  304. // Found an enabled transition, so store that one
  305. transition = random_choice(transitions)
  306. // Execute transition
  307. set_merge(new_states, execute_transition(model, data, class, transition))
  308. // When leaving an orthogonal component, we must also pop all related states that might be processed in the future!
  309. Element leaving
  310. leaving = expand_current_state(model, current_state, data["classes"][class]["states"])
  311. set_difference(states, leaving)
  312. transitioned = True
  313. found = True
  314. break!
  315. if (bool_not(found)):
  316. // Nothing found, so stay in the current state
  317. set_add(new_states, state)
  318. // Update states
  319. dict_overwrite(data["classes"][class], "states", new_states)
  320. reschedule_timeouts(model, data, class)
  321. return transitioned!
  322. Void function reschedule_timeouts(model : Element, data : Element, class : String):
  323. Element timed_transitions
  324. Element old_timed_transitions
  325. String transition
  326. Element states
  327. String state
  328. timed_transitions = create_node()
  329. states = set_copy(data["classes"][class]["states"])
  330. // Collect all timed transitions that are currently active
  331. while (read_nr_out(states) > 0):
  332. state = set_pop(states)
  333. // NOTE this set_merge does not eliminate duplicates, though this should happen later on when adding the timer (see other NOTE)
  334. set_merge(timed_transitions, filter_exists(model, allOutgoingAssociationInstances(model, state, "SCCD/transition"), "after"))
  335. // Remove timers that no longer exist
  336. old_timed_transitions = dict_keys(data["classes"][class]["timers"])
  337. while (read_nr_out(old_timed_transitions) > 0):
  338. transition = set_pop(old_timed_transitions)
  339. if (bool_not(set_in(timed_transitions, transition))):
  340. // Transition is no longer scheduled for any state, so remove
  341. dict_delete(data["classes"][class]["timers"], transition)
  342. // Schedule timers that are not already scheduled
  343. while (read_nr_out(timed_transitions) > 0):
  344. transition = set_pop(timed_transitions)
  345. // NOTE Normally, a timer will not be added twice here, as the previous occurence will already find it
  346. if (bool_not(dict_in(data["classes"][class]["timers"], transition))):
  347. // Not yet scheduled this transition: do so now
  348. Element after
  349. Float after_duration
  350. after = read_attribute(model, transition, "after")
  351. after = get_func_AL_model(import_node(after))
  352. after_duration = after(data["classes"][class]["attributes"])
  353. dict_add(data["classes"][class]["timers"], transition, float_addition(data["start_time"], after_duration))
  354. return !
  355. String function get_parent(model : Element, state : String):
  356. Element tmp_set
  357. tmp_set = allAssociationOrigins(model, state, "SCCD/composite_children")
  358. set_merge(tmp_set, allAssociationOrigins(model, state, "SCCD/parallel_children"))
  359. if (read_nr_out(tmp_set) > 0):
  360. return set_pop(tmp_set)!
  361. else:
  362. return ""!
  363. Element function find_hierarchy(model : Element, state : String):
  364. if (state == ""):
  365. return create_node()!
  366. else:
  367. Element result
  368. String parent
  369. parent = get_parent(model, state)
  370. // We have a parent, so take the parent list first
  371. result = find_hierarchy(model, parent)
  372. list_append(result, state)
  373. return result!
  374. Element function get_actions_to_execute(model : Element, source_states : Element, target_states : Element, class_data : Element):
  375. Element result
  376. result = create_node()
  377. source_states = set_copy(source_states)
  378. target_states = set_copy(target_states)
  379. // Add all exit and entry actions to the list of actions to execute
  380. // Do this by finding the common parent, and then doing all exit actions up to that node, and all entry actions up to the target_state
  381. // First, find the hierarchy!
  382. Element hierarchy_sources
  383. Element hierarchy_targets
  384. Element all_hierarchies
  385. hierarchy_sources = create_node()
  386. while (read_nr_out(source_states) > 0):
  387. set_add(hierarchy_sources, find_hierarchy(model, set_pop(source_states)))
  388. hierarchy_targets = create_node()
  389. while (read_nr_out(target_states) > 0):
  390. set_add(hierarchy_targets, find_hierarchy(model, set_pop(target_states)))
  391. all_hierarchies = set_copy(hierarchy_sources)
  392. set_merge(all_hierarchies, hierarchy_targets)
  393. // Difference these all lists, finding the first common entry
  394. Element iter_hierarchies
  395. Integer i
  396. String current
  397. Element hierarchy
  398. Boolean finished
  399. i = 0
  400. finished = False
  401. while (bool_not(finished)):
  402. // Check the i-th element in both and see if they are equal
  403. current = ""
  404. iter_hierarchies = set_copy(all_hierarchies)
  405. while (read_nr_out(iter_hierarchies) > 0):
  406. hierarchy = set_pop(iter_hierarchies)
  407. // Exhausted one of the lists
  408. if (i >= list_len(hierarchy)):
  409. finished = True
  410. break!
  411. // First entry, so read out value as reference
  412. if (current == ""):
  413. current = list_read(hierarchy, i)
  414. // Check with reference element
  415. if (bool_not(value_eq(list_read(hierarchy, i), current))):
  416. finished = True
  417. break!
  418. // i-th element equal for all hierarchies, so go to next element
  419. if (bool_not(finished)):
  420. i = i + 1
  421. // Found the first differing element at position i
  422. // All elements remaining in hierarchy_source are to be traversed in REVERSE order for the exit actions
  423. // All elements remaining in hierarchy_target are to be traversed in NORMAL order for the entry actions
  424. // This is not that simple either, as we need to consider that some actions might already have been added to the list...
  425. // Add hierarchy_sources actions
  426. String state
  427. Element visited
  428. Element action
  429. Element spliced_hierarchy
  430. Element hierarchy_source
  431. Element hierarchy_target
  432. visited = create_node()
  433. while (read_nr_out(hierarchy_sources) > 0):
  434. // Get one of these hierarchies
  435. hierarchy_source = set_pop(hierarchy_sources)
  436. spliced_hierarchy = list_splice(hierarchy_source, i, list_len(hierarchy_source))
  437. while (list_len(spliced_hierarchy) > 0):
  438. state = list_pop(spliced_hierarchy, list_len(spliced_hierarchy) - 1)
  439. if (set_in(visited, state)):
  440. // Already added this state, so don't bother
  441. continue!
  442. else:
  443. // New state, so prepend it to the list
  444. // Prepend, instead of append, as we want to do these operations in reverse order!
  445. // First check if there is any exit action at all
  446. action = read_attribute(model, state, "onExitScript")
  447. if (element_neq(action, read_root())):
  448. // An exit action is found!
  449. list_insert(result, get_func_AL_model(import_node(action)), 0)
  450. // Add this state as visited, even though there might not have been an associated action
  451. set_add(visited, state)
  452. // Also update the history of this state, which will be important if we have a history state later on
  453. if (read_type(model, state) == "SCCD/CompositeState"):
  454. dict_overwrite(class_data["history"], state, expand_current_state(model, state, class_data["states"]))
  455. // Add hierarchy_targets actions
  456. // Clear visited, just to be safe, though it should not matter
  457. visited = create_node()
  458. while (read_nr_out(hierarchy_targets) > 0):
  459. // Get one of these hierarchies
  460. hierarchy_target = set_pop(hierarchy_targets)
  461. spliced_hierarchy = list_splice(hierarchy_target, i, list_len(hierarchy_target))
  462. while (list_len(spliced_hierarchy) > 0):
  463. state = list_pop(spliced_hierarchy, list_len(spliced_hierarchy) - 1)
  464. if (set_in(visited, state)):
  465. // Already added this state, so don't bother
  466. continue!
  467. else:
  468. // New state, so append it to the list
  469. // Append, instead of prepend, as we want to do these operations in normal order!
  470. // First check if there is any entry action at all
  471. action = read_attribute(model, state, "onEntryScript")
  472. if (element_neq(action, read_root())):
  473. // An entry action is found!
  474. list_append(result, get_func_AL_model(import_node(action)))
  475. // Add this state as visited, even though there might not have been an associated action
  476. set_add(visited, state)
  477. return result!
  478. Float function step(model : Element, data : Element):
  479. // Step through all classes
  480. Element classes
  481. Element class
  482. Float t_min
  483. Float t_current
  484. Boolean transitioned
  485. Element keys
  486. String key
  487. t_min = time() + 99999.0
  488. classes = dict_keys(data["classes"])
  489. // TODO this should use simulated time or something
  490. dict_overwrite(data, "start_time", time())
  491. transitioned = False
  492. while (read_nr_out(classes) > 0):
  493. class = set_pop(classes)
  494. if (step_class(model, data, class)):
  495. transitioned = True
  496. if (bool_not(transitioned)):
  497. // Find minimum timer for this class, and store that
  498. keys = dict_keys(data["classes"][class]["timers"])
  499. while (read_nr_out(keys) > 0):
  500. key = set_pop(keys)
  501. t_current = data["classes"][class]["timers"][key]
  502. if (t_current < t_min):
  503. t_min = t_current
  504. if (transitioned):
  505. // Do another step, as we can transition
  506. return 0.0!
  507. else:
  508. return float_subtraction(t_min, data["start_time"])!
  509. Boolean function main(model : Element):
  510. // Executes the provided SCCD model
  511. Element data
  512. data = create_node()
  513. dict_add(data, "classes", create_node())
  514. // Prepare for input
  515. output("Ready for input!")
  516. // Find initial
  517. String default_class
  518. default_class = set_pop(filter(model, allInstances(model, "SCCD/Class"), "default", True))
  519. // Start up the default class
  520. start_class(model, data, default_class, "main", read_root())
  521. Float timeout
  522. Element interrupt
  523. timeout = 0.0
  524. while (True):
  525. print_states(model, data)
  526. interrupt = input_timeout(timeout)
  527. if (value_eq(interrupt, "#EXIT#")):
  528. // Stop execution
  529. return True!
  530. dict_overwrite(data, "events", create_node())
  531. if (element_neq(interrupt, read_root())):
  532. // Got interrupt
  533. log("Got event: " + cast_v2s(interrupt))
  534. set_add(data["events"], create_tuple(interrupt, read_root()))
  535. output("Processed event, ready for more!")
  536. timeout = step(model, data)
  537. if (read_nr_out(data["classes"]) == 0):
  538. // No more active classes left: terminate!
  539. log("Finished SCCD execution")
  540. break!
  541. log("Pausing for " + cast_v2s(timeout))
  542. // We should never get here!
  543. return False!