SCCD_execute.alc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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. include "io.alh"
  8. Boolean afap = False
  9. Element function resolve_function(location : String, data : Element):
  10. if (bool_not(dict_in(data["cache_operations"], location))):
  11. dict_add(data["cache_operations"], location, get_func_AL_model(import_node(location)))
  12. return data["cache_operations"][location]!
  13. Void function print_states(model : Element, data : Element):
  14. Element classes
  15. Element states
  16. Element class
  17. String state
  18. log("Current states:")
  19. classes = dict_keys(data["classes"])
  20. while (set_len(classes) > 0):
  21. class = set_pop(classes)
  22. class = data["classes"][class]
  23. log(string_join(string_join(string_join(" ", class["ID"]), " : "), read_attribute(model, class["type"], "name")))
  24. log(" Attributes: " + dict_to_string(class["attributes"]))
  25. states = set_copy(class["states"])
  26. log(" States:")
  27. while (set_len(states) > 0):
  28. state = set_pop(states)
  29. log(string_join(" ", read_attribute(model, state, "name")))
  30. return!
  31. Element function filter(model : Element, set : Element, attribute_name : String, attribute_value : Element):
  32. Element keys
  33. String key
  34. Element result
  35. result = set_create()
  36. while (set_len(set) > 0):
  37. key = set_pop(set)
  38. if (value_eq(read_attribute(model, key, attribute_name), attribute_value)):
  39. set_add(result, key)
  40. return result!
  41. Element function filter_exists(model : Element, set : Element, attribute_name : String):
  42. Element keys
  43. String key
  44. Element result
  45. result = set_create()
  46. while (set_len(set) > 0):
  47. key = set_pop(set)
  48. if (element_neq(read_attribute(model, key, attribute_name), read_root())):
  49. set_add(result, key)
  50. return result!
  51. Element function expand_current_state(model : Element, state : String, data : Element):
  52. // Find the hierarchy of all current states, and select those that contain the currently selected state
  53. Element result
  54. Element current_states
  55. result = set_create()
  56. current_states = set_copy(data["current_class_handle"]["states"])
  57. Element hierarchy
  58. String deep_state
  59. while (set_len(current_states) > 0):
  60. deep_state = set_pop(current_states)
  61. hierarchy = find_hierarchy(model, deep_state, data)
  62. // Got the hierarchy of one of the states
  63. if (list_in(hierarchy, state)):
  64. // This hierarchy contains the root state we are checking for, so add to set
  65. set_add(result, deep_state)
  66. return result!
  67. Element function expand_initial_state(model : Element, state : String, data : Element):
  68. String t
  69. t = read_type(model, state)
  70. if (t == "SCCD/CompositeState"):
  71. // Recurse further in the composite
  72. return expand_composite_state(model, state, data)!
  73. elif (t == "SCCD/ParallelState"):
  74. // Split up all components
  75. return expand_parallel_state(model, state, data)!
  76. elif (t == "SCCD/HistoryState"):
  77. // Reset the history
  78. // This is not really an initial state, but it is called in exactly the same places
  79. return data["current_class_handle"]["history"][get_parent(model, state)]!
  80. else:
  81. // Probably just an atomic, so return this one only
  82. Element result
  83. result = set_create()
  84. set_add(result, state)
  85. return result!
  86. Element function expand_composite_state(model : Element, composite_state : String, data : Element):
  87. // Resolve all initial states from a single composite state
  88. String initial
  89. // Fetch the initial state
  90. initial = set_pop(filter(model, allAssociationDestinations(model, composite_state, "SCCD/composite_children"), "isInitial", True))
  91. // Expand the initial state, depending on what it is
  92. return expand_initial_state(model, initial, data)!
  93. Element function expand_parallel_state(model : Element, parallel_state : String, data : Element):
  94. // Resolve all initial states from a single parallel state
  95. Element children
  96. Element result
  97. Element expanded_children
  98. children = allAssociationDestinations(model, parallel_state, "SCCD/parallel_children")
  99. result = set_create()
  100. while (set_len(children) > 0):
  101. set_merge(result, expand_initial_state(model, set_pop(children), data))
  102. return result!
  103. Void function delete_class(model : Element, data : Element, identifier : String):
  104. // Stop a specific class instance, with attached statechart, from executing
  105. dict_delete(data["classes"], identifier)
  106. String function start_class(model : Element, data : Element, class : String, parameters : Element):
  107. // Start up the class and assign its initial state to it
  108. // First find an empty identifier
  109. String identifier
  110. identifier = cast_i2s(dict_len(data["classes"]))
  111. // Create the data structure for a running class
  112. Element class_handle
  113. class_handle = dict_create()
  114. dict_add(class_handle, "type", class)
  115. dict_add(class_handle, "ID", identifier)
  116. dict_add(class_handle, "events", set_create())
  117. dict_add(class_handle, "new_events", set_create())
  118. dict_add(class_handle, "timers", dict_create())
  119. dict_add(data["classes"], class_handle["ID"], class_handle)
  120. String prev_class
  121. prev_class = data["current_class"]
  122. dict_overwrite(data, "current_class", identifier)
  123. dict_overwrite(data, "current_class_handle", data["classes"][identifier])
  124. // Add the current state of the class
  125. String initial_state
  126. // Should only be one behaviour linked to it!
  127. initial_state = set_pop(allAssociationDestinations(model, class, "SCCD/behaviour"))
  128. dict_add(class_handle, "states", expand_initial_state(model, initial_state, class_handle))
  129. // Initialize history for all composite states
  130. Element history
  131. Element cstates
  132. String cstate
  133. history = dict_create()
  134. dict_add(class_handle, "history", history)
  135. cstates = allInstances(model, "SCCD/CompositeState")
  136. while (set_len(cstates) > 0):
  137. cstate = set_pop(cstates)
  138. dict_add(history, cstate, expand_initial_state(model, cstate, class_handle))
  139. // Add all attributes
  140. Element attributes
  141. attributes = dict_create()
  142. Element attrs
  143. attrs = allAssociationDestinations(model, class, "SCCD/class_attributes")
  144. while (set_len(attrs) > 0):
  145. dict_add(attributes, read_attribute(model, set_pop(attrs), "name"), read_root())
  146. dict_add(class_handle, "attributes", attributes)
  147. // Invoke constructor
  148. Element constructor
  149. constructor = read_attribute(model, class, "constructor_body")
  150. if (element_neq(constructor, read_root())):
  151. // Constructor, so execute
  152. constructor = resolve_function(constructor, data)
  153. constructor(attributes, parameters)
  154. // Execute all entry actions
  155. Element init
  156. init = set_create()
  157. set_add(init, "")
  158. // Initial state before initialization is the set with an empty hierarchy
  159. // Empty set would not find any difference between the source and target
  160. execute_actions(model, init, set_copy(class_handle["states"]), data, "")
  161. // Notify this class itself of its ID
  162. Element lst
  163. lst = list_create()
  164. list_append(lst, identifier)
  165. set_add_node(data["current_class_handle"]["new_events"], create_tuple("instance_created", lst))
  166. dict_overwrite(data, "current_class", prev_class)
  167. dict_overwrite(data, "current_class_handle", data["classes"][prev_class])
  168. return identifier!
  169. Element function get_enabled_transitions(model : Element, state : String, data : Element):
  170. // Returns all enabled transitions
  171. Element result
  172. Element to_filter
  173. String attr
  174. String transition
  175. Element cond
  176. String evt_name
  177. Element evt
  178. Element events
  179. Element event_names
  180. Element event_parameters
  181. result = set_create()
  182. to_filter = allOutgoingAssociationInstances(model, state, "SCCD/transition")
  183. event_names = set_create()
  184. event_parameters = set_create()
  185. events = set_copy(data["current_class_handle"]["events"])
  186. while (set_len(events) > 0):
  187. evt = set_pop(events)
  188. evt_name = list_read(evt, 0)
  189. if (bool_not(set_in(event_names, evt_name))):
  190. // Not yet registered the event
  191. set_add(event_names, evt_name)
  192. dict_add(event_parameters, evt_name, set_create())
  193. // Add event parameters
  194. set_add_node(event_parameters[evt_name], list_read(evt, 1))
  195. while (set_len(to_filter) > 0):
  196. transition = set_pop(to_filter)
  197. // Check event
  198. attr = read_attribute(model, transition, "event")
  199. if (bool_not(bool_or(element_eq(attr, read_root()), set_in(event_names, attr)))):
  200. // At least one enabled event is found
  201. continue!
  202. // Check after
  203. // Only an after if there was no event!
  204. if (bool_and(element_eq(attr, read_root()), read_attribute(model, transition, "after"))):
  205. if (dict_in(data["current_class_handle"]["timers"], transition)):
  206. // Registered timer already, let's check if it has expired
  207. if (float_gt(data["current_class_handle"]["timers"][transition], data["time_sim"])):
  208. // Not enabled yet
  209. continue!
  210. else:
  211. // Not registered even, so not enabled either
  212. continue!
  213. // Check condition, but depends on whether there was an event or not
  214. cond = read_attribute(model, transition, "cond")
  215. if (element_neq(cond, read_root())):
  216. // Got a condition, so resolve
  217. cond = resolve_function(cond, data)
  218. if (element_neq(attr, read_root())):
  219. // We have an event to take into account!
  220. Element params
  221. Element param
  222. params = set_copy(event_parameters[attr])
  223. while (set_len(params) > 0):
  224. param = set_pop(params)
  225. if (element_neq(cond, read_root())):
  226. // Got a condition to check first
  227. if (bool_not(cond(data["current_class_handle"]["attributes"], param))):
  228. // Condition failed, so skip
  229. continue!
  230. // Fine to add this one with the specified parameters
  231. set_add_node(result, create_tuple(transition, param))
  232. else:
  233. // No event to think about, just add the transition
  234. if (element_neq(cond, read_root())):
  235. // Check the condition first
  236. if (bool_not(cond(data["current_class_handle"]["attributes"], read_root()))):
  237. // Condition false, so skip
  238. continue!
  239. // Fine to add this one without event parameters (no event)
  240. set_add_node(result, create_tuple(transition, read_root()))
  241. return result!
  242. Void function process_raised_event(model : Element, event : Element, parameter_action : Element, data : Element):
  243. String scope
  244. scope = read_attribute(model, event, "scope")
  245. if (scope == "cd"):
  246. // Is an event for us internally, so don't append
  247. // Instead, we process it directly
  248. String operation
  249. operation = read_attribute(model, event, "event")
  250. if (operation == "create_instance"):
  251. // Start up a new class of the desired type
  252. // Parameters of this call:
  253. // class -- type of the class to instantiate
  254. // identifier -- name of this instance, for future reference
  255. // parameters -- parameters for constructor
  256. String class
  257. String identifier
  258. Element parameters
  259. class = set_pop(filter(model, allInstances(model, "SCCD/Class"), "name", list_read(parameter_action, 1)))
  260. parameters = list_read(parameter_action, 2)
  261. identifier = start_class(model, data, class, parameters)
  262. // Notify the creator of the ID of the created instance
  263. Element lst
  264. lst = list_create()
  265. list_append(lst, identifier)
  266. set_add_node(data["current_class_handle"]["new_events"], create_tuple("instance_created", lst))
  267. elif (operation == "delete_instance"):
  268. // Delete the requested class
  269. String identifier
  270. identifier = list_read(parameter_action, 0)
  271. delete_class(model, data, identifier)
  272. set_add_node(data["current_class_handle"]["new_events"], create_tuple("instance_deleted", parameter_action))
  273. elif (scope == "broad"):
  274. // Send to all classes
  275. Element classes
  276. classes = dict_keys(data["classes"])
  277. while(set_len(classes) > 0):
  278. set_add_node(data["classes"][set_pop(classes)]["new_events"], create_tuple(read_attribute(model, event, "event"), parameter_action))
  279. elif (scope == "narrow"):
  280. // Send to the specified class only
  281. Element func
  282. func = resolve_function(read_attribute(model, event, "target"), data)
  283. String dest
  284. dest = func(data["current_class_handle"]["attributes"])
  285. set_add_node(data["classes"][dest]["new_events"], create_tuple(read_attribute(model, event, "event"), parameter_action))
  286. elif (scope == "output"):
  287. // Store it in the output event model
  288. String evt
  289. if (bool_not(afap)):
  290. Element val
  291. val = dict_create()
  292. dict_add(val, "timestamp", data["time_sim"])
  293. dict_add(val, "name", read_attribute(model, event, "event"))
  294. dict_add(val, "parameter", parameter_action)
  295. output("EVENT: " + dict_to_string(val))
  296. evt = instantiate_node(model, "trace/Event", "")
  297. instantiate_attribute(model, evt, "timestamp", data["time_sim"])
  298. instantiate_attribute(model, evt, "name", read_attribute(model, event, "event"))
  299. instantiate_attribute(model, evt, "parameter", parameter_action)
  300. else:
  301. // Same as local
  302. set_add_node(data["current_class_handle"]["new_events"], create_tuple(read_attribute(model, event, "event"), parameter_action))
  303. return !
  304. Element function execute_transition(model : Element, data : Element, transition_tuple : Element):
  305. // Execute the script (if any)
  306. Element script
  307. String transition
  308. Element event_parameter
  309. transition = list_read(transition_tuple, 0)
  310. event_parameter = list_read(transition_tuple, 1)
  311. script = read_attribute(model, transition, "script")
  312. if (element_neq(script, read_root())):
  313. script = resolve_function(script, data)
  314. script(data["current_class_handle"]["attributes"], event_parameter)
  315. // Raise events (if any)
  316. Element events
  317. String event
  318. events = allAssociationDestinations(model, transition, "SCCD/transition_raises")
  319. while (set_len(events) > 0):
  320. event = set_pop(events)
  321. Element parameter_action
  322. parameter_action = read_attribute(model, event, "parameter")
  323. if (element_neq(parameter_action, read_root())):
  324. // Got a parameter to evaluate
  325. parameter_action = resolve_function(parameter_action, data)
  326. parameter_action = parameter_action(data["current_class_handle"]["attributes"], event_parameter)
  327. process_raised_event(model, event, parameter_action, data)
  328. // Find new set of states
  329. Element target_states
  330. Element source_states
  331. source_states = expand_current_state(model, readAssociationSource(model, transition), data)
  332. target_states = expand_initial_state(model, readAssociationDestination(model, transition), data)
  333. execute_actions(model, source_states, target_states, data, readAssociationSource(model, transition))
  334. return target_states!
  335. Boolean function step_class(model : Element, data : Element, class : String):
  336. // Find enabled transitions in a class and execute it, updating the state
  337. // Iterate over all current states, searching for enabled transitions
  338. // Search for enabled transitions in higher levels as well!
  339. Element states
  340. Element new_states
  341. String state
  342. Element transitions
  343. String transition
  344. Boolean transitioned
  345. Element hierarchy
  346. String current_state
  347. Boolean found
  348. if (bool_not(dict_in(data["classes"], class))):
  349. // Seems like this class was removed, so stop execution
  350. return False!
  351. // Notify everyone of the current class
  352. dict_overwrite(data, "current_class", class)
  353. dict_overwrite(data, "current_class_handle", data["classes"][class])
  354. states = set_copy(data["current_class_handle"]["states"])
  355. new_states = set_create()
  356. transitioned = False
  357. while (set_len(states) > 0):
  358. state = set_pop(states)
  359. found = False
  360. // Loop over the hierarchy of this state and try to apply transitions
  361. hierarchy = find_hierarchy(model, state, data)
  362. while (list_len(hierarchy) > 0):
  363. current_state = list_pop(hierarchy, 0)
  364. transitions = get_enabled_transitions(model, current_state, data)
  365. if (set_len(transitions) > 0):
  366. // Found an enabled transition, so store that one
  367. transition = random_choice(set_to_list(transitions))
  368. // Execute transition
  369. set_merge(new_states, execute_transition(model, data, transition))
  370. // When leaving an orthogonal component, we must also pop all related states that might be processed in the future!
  371. Element leaving
  372. leaving = expand_current_state(model, current_state, data)
  373. set_difference(states, leaving)
  374. transitioned = True
  375. found = True
  376. break!
  377. if (bool_not(found)):
  378. // Nothing found, so stay in the current state
  379. set_add(new_states, state)
  380. // Update states
  381. dict_overwrite(data["current_class_handle"], "states", new_states)
  382. return transitioned!
  383. String function get_parent(model : Element, state : String):
  384. Element tmp_set
  385. tmp_set = allAssociationOrigins(model, state, "SCCD/composite_children")
  386. set_merge(tmp_set, allAssociationOrigins(model, state, "SCCD/parallel_children"))
  387. if (set_len(tmp_set) > 0):
  388. return set_pop(tmp_set)!
  389. else:
  390. return ""!
  391. Element function find_hierarchy(model : Element, state : String, data : Element):
  392. // Try to cache as much as possible!
  393. if (bool_not(dict_in(data["cache_hierarchy"], state))):
  394. Element result
  395. if (state == ""):
  396. result = list_create()
  397. else:
  398. String parent
  399. parent = get_parent(model, state)
  400. // We have a parent, so take the parent list first
  401. result = find_hierarchy(model, parent, data)
  402. list_append(result, state)
  403. dict_add(data["cache_hierarchy"], state, result)
  404. return dict_copy(data["cache_hierarchy"][state])!
  405. Void function execute_actions(model : Element, source_states : Element, target_states : Element, data : Element, transition_source : String):
  406. Element exit
  407. Element entry
  408. exit = list_create()
  409. entry = list_create()
  410. source_states = set_copy(source_states)
  411. target_states = set_copy(target_states)
  412. // Add all exit and entry actions to the list of actions to execute
  413. // 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
  414. // First, find the hierarchy!
  415. Element hierarchy_sources
  416. Element hierarchy_targets
  417. Element all_hierarchies
  418. hierarchy_sources = set_create()
  419. while (set_len(source_states) > 0):
  420. set_add_node(hierarchy_sources, find_hierarchy(model, set_pop(source_states), data))
  421. hierarchy_targets = set_create()
  422. while (set_len(target_states) > 0):
  423. set_add_node(hierarchy_targets, find_hierarchy(model, set_pop(target_states), data))
  424. all_hierarchies = set_copy(hierarchy_sources)
  425. set_merge(all_hierarchies, hierarchy_targets)
  426. // Difference these all lists, finding the first common entry
  427. Element iter_hierarchies
  428. Integer i
  429. String current
  430. Element hierarchy
  431. Boolean finished
  432. Integer transition_depth
  433. Integer lca_depth
  434. lca_depth = 0
  435. finished = False
  436. if (transition_source != ""):
  437. // Find out the level of the transition_source by fetching its hierarchy
  438. transition_depth = list_len(find_hierarchy(model, transition_source, data)) - 1
  439. // Now check for the least common ancestor
  440. while (bool_not(finished)):
  441. // Check the i-th element in both and see if they are equal
  442. current = ""
  443. iter_hierarchies = set_copy(all_hierarchies)
  444. while (set_len(iter_hierarchies) > 0):
  445. hierarchy = set_pop(iter_hierarchies)
  446. // Exhausted one of the lists
  447. if (lca_depth >= list_len(hierarchy)):
  448. finished = True
  449. break!
  450. // Reached the same level as transition depth already, so no need to increase
  451. if (lca_depth == transition_depth):
  452. finished = True
  453. break!
  454. // First entry, so read out value as reference
  455. if (current == ""):
  456. current = list_read(hierarchy, lca_depth)
  457. // Check with reference element
  458. if (bool_not(value_eq(list_read(hierarchy, lca_depth), current))):
  459. finished = True
  460. break!
  461. // i-th element equal for all hierarchies, so go to next element
  462. if (bool_not(finished)):
  463. lca_depth = lca_depth + 1
  464. if (lca_depth < transition_depth):
  465. i = lca_depth
  466. else:
  467. i = transition_depth
  468. else:
  469. // Initial, so just set i to zero
  470. i = 0
  471. // Found the first differing element at position i
  472. // All elements remaining in hierarchy_source are to be traversed in REVERSE order for the exit actions
  473. // All elements remaining in hierarchy_target are to be traversed in NORMAL order for the entry actions
  474. // This is not that simple either, as we need to consider that some actions might already have been added to the list...
  475. // Add hierarchy_sources actions
  476. String state
  477. Element visited
  478. Element action
  479. Element spliced_hierarchy
  480. Element hierarchy_source
  481. Element hierarchy_target
  482. visited = set_create()
  483. while (set_len(hierarchy_sources) > 0):
  484. // Get one of these hierarchies
  485. hierarchy_source = set_pop(hierarchy_sources)
  486. spliced_hierarchy = list_splice(hierarchy_source, i, list_len(hierarchy_source))
  487. while (list_len(spliced_hierarchy) > 0):
  488. state = list_pop(spliced_hierarchy, list_len(spliced_hierarchy) - 1)
  489. if (set_in(visited, state)):
  490. // Already added this state, so don't bother
  491. continue!
  492. else:
  493. // New state, so prepend it to the list
  494. // Prepend, instead of append, as we want to do these operations in reverse order!
  495. list_insert(exit, state, 0)
  496. // Add this state as visited
  497. set_add(visited, state)
  498. // Add hierarchy_targets actions
  499. // Clear visited, just to be safe, though it should not matter
  500. visited = set_create()
  501. while (set_len(hierarchy_targets) > 0):
  502. // Get one of these hierarchies
  503. hierarchy_target = set_pop(hierarchy_targets)
  504. spliced_hierarchy = list_splice(hierarchy_target, i, list_len(hierarchy_target))
  505. while (list_len(spliced_hierarchy) > 0):
  506. state = list_pop(spliced_hierarchy, list_len(spliced_hierarchy) - 1)
  507. if (set_in(visited, state)):
  508. // Already added this state, so don't bother
  509. continue!
  510. else:
  511. // New state, so append it to the list
  512. // Append, instead of prepend, as we want to do these operations in normal order!
  513. list_append(entry, state)
  514. // Add this state as visited, even though there might not have been an associated action
  515. set_add(visited, state)
  516. // Now we have a list of traversed states!
  517. // Start executing all their operations in order
  518. Element events
  519. String event
  520. // First do exit actions
  521. while (list_len(exit) > 0):
  522. state = list_pop(exit, 0)
  523. // Set history when leaving
  524. if (read_type(model, state) == "SCCD/CompositeState"):
  525. dict_overwrite(data["current_class_handle"]["history"], state, expand_current_state(model, state, data))
  526. // Do exit actions
  527. action = read_attribute(model, state, "onExitScript")
  528. if (element_neq(action, read_root())):
  529. // Got a script, so execute!
  530. action = resolve_function(action, data)
  531. action(data["current_class_handle"]["attributes"])
  532. // Raise events
  533. events = allAssociationDestinations(model, state, "SCCD/onExitRaise")
  534. while (set_len(events) > 0):
  535. event = set_pop(events)
  536. Element parameter_action
  537. parameter_action = read_attribute(model, event, "parameter")
  538. if (element_neq(parameter_action, read_root())):
  539. // Got a parameter to evaluate
  540. parameter_action = resolve_function(parameter_action, data)
  541. parameter_action = parameter_action(data["current_class_handle"]["attributes"])
  542. process_raised_event(model, event, parameter_action, data)
  543. // Unschedule after events
  544. Element timed_transitions
  545. timed_transitions = filter_exists(model, allOutgoingAssociationInstances(model, state, "SCCD/transition"), "after")
  546. while (set_len(timed_transitions) > 0):
  547. dict_delete(data["current_class_handle"]["timers"], set_pop(timed_transitions))
  548. // Then do entry actions
  549. while (list_len(entry) > 0):
  550. state = list_pop(entry, 0)
  551. // Do entry actions
  552. action = read_attribute(model, state, "onEntryScript")
  553. if (element_neq(action, read_root())):
  554. // Got a script, so execute!
  555. action = resolve_function(action, data)
  556. action(data["current_class_handle"]["attributes"])
  557. // Raise events
  558. events = allAssociationDestinations(model, state, "SCCD/onEntryRaise")
  559. while (set_len(events) > 0):
  560. event = set_pop(events)
  561. Element parameter_action
  562. parameter_action = read_attribute(model, event, "parameter")
  563. if (element_neq(parameter_action, read_root())):
  564. // Got a parameter to evaluate
  565. parameter_action = resolve_function(parameter_action, data)
  566. parameter_action = parameter_action(data["current_class_handle"]["attributes"])
  567. process_raised_event(model, event, parameter_action, data)
  568. // Schedule after events
  569. Element timed_transitions
  570. String transition
  571. Element after
  572. timed_transitions = filter_exists(model, allOutgoingAssociationInstances(model, state, "SCCD/transition"), "after")
  573. while (set_len(timed_transitions) > 0):
  574. transition = set_pop(timed_transitions)
  575. after = resolve_function(read_attribute(model, transition, "after"), data)
  576. dict_add(data["current_class_handle"]["timers"], transition, float_addition(data["time_sim"], after(data["current_class_handle"]["attributes"])))
  577. return !
  578. Float function step(model : Element, data : Element):
  579. // Step through all classes
  580. Element classes
  581. Element class
  582. Float t_min
  583. Float t_current
  584. Boolean transitioned
  585. Element keys
  586. String key
  587. t_min = 999999.0
  588. classes = dict_keys(data["classes"])
  589. transitioned = False
  590. while (set_len(classes) > 0):
  591. class = set_pop(classes)
  592. if (step_class(model, data, class)):
  593. transitioned = True
  594. if (bool_not(transitioned)):
  595. // Find minimum timer for this class, and store that
  596. keys = dict_keys(data["classes"][class]["timers"])
  597. while (set_len(keys) > 0):
  598. key = set_pop(keys)
  599. t_current = data["classes"][class]["timers"][key]
  600. if (t_current < t_min):
  601. t_min = t_current
  602. if (transitioned):
  603. // Do another step, as we can transition
  604. return data["time_sim"]!
  605. else:
  606. return t_min!
  607. Boolean function main(model : Element):
  608. // Executes the provided SCCD model
  609. Element data
  610. data = dict_create()
  611. dict_add(data, "classes", dict_create())
  612. dict_add(data, "cache_operations", dict_create())
  613. dict_add(data, "cache_hierarchy", dict_create())
  614. dict_add(data, "current_class", "")
  615. Float time_0
  616. Float time_sim
  617. Float time_wallclock
  618. time_0 = time()
  619. time_sim = 0.0
  620. dict_add(data, "time_sim", 0.0)
  621. // Prepare for input
  622. output("Ready for input!")
  623. // Find initial
  624. String default_class
  625. default_class = set_pop(filter(model, allInstances(model, "SCCD/Class"), "default", True))
  626. // Start up the default class
  627. start_class(model, data, default_class, read_root())
  628. Float timeout
  629. Element interrupt
  630. timeout = 0.0
  631. while (True):
  632. if (afap):
  633. timeout = 0.0
  634. interrupt = input_timeout(timeout)
  635. if (value_eq(interrupt, "#EXIT#")):
  636. // Stop execution
  637. return True!
  638. if (element_neq(interrupt, read_root())):
  639. // Send out, as otherwise the client doesn't get a dialog
  640. output("Processed event, ready for more!")
  641. // Update the simulated time to the time of interrupt
  642. time_sim = time() - time_0
  643. dict_overwrite(data, "new_events", set_create())
  644. Element classes
  645. classes = dict_keys(data["classes"])
  646. while(set_len(classes) > 0):
  647. String class
  648. class = set_pop(classes)
  649. dict_overwrite(data["classes"][class], "events", data["classes"][class]["new_events"])
  650. dict_overwrite(data["classes"][class], "new_events", set_create())
  651. if (element_neq(interrupt, read_root())):
  652. // Got interrupt, so append it already
  653. set_add_node(data["classes"][class]["events"], create_tuple(interrupt, read_root()))
  654. // Else we timeout, and thus keep the time_sim
  655. dict_overwrite(data, "time_sim", time_sim)
  656. time_sim = step(model, data)
  657. if (float_gt(time_sim, data["time_sim"])):
  658. print_states(model, data)
  659. if (dict_len(data["classes"]) == 0):
  660. // No more active classes left: terminate!
  661. log("Finished SCCD execution")
  662. break!
  663. time_wallclock = time() - time_0
  664. timeout = time_sim - time_wallclock
  665. // We have finished without error
  666. return True!