@sccharts-lab/engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/LICENSE +277 -0
  2. package/README.md +125 -2
  3. package/dist/codegen/expr.d.ts +36 -0
  4. package/dist/codegen/expr.js +252 -0
  5. package/dist/codegen/expr.js.map +1 -0
  6. package/dist/codegen/index.d.ts +4 -0
  7. package/dist/codegen/index.js +238 -0
  8. package/dist/codegen/index.js.map +1 -0
  9. package/dist/codegen/layout.d.ts +57 -0
  10. package/dist/codegen/layout.js +306 -0
  11. package/dist/codegen/layout.js.map +1 -0
  12. package/dist/codegen/logic.d.ts +31 -0
  13. package/dist/codegen/logic.js +258 -0
  14. package/dist/codegen/logic.js.map +1 -0
  15. package/dist/codegen/methods.d.ts +17 -0
  16. package/dist/codegen/methods.js +242 -0
  17. package/dist/codegen/methods.js.map +1 -0
  18. package/dist/codegen/reset.d.ts +6 -0
  19. package/dist/codegen/reset.js +110 -0
  20. package/dist/codegen/reset.js.map +1 -0
  21. package/dist/codegen/types.d.ts +81 -0
  22. package/dist/codegen/types.js +3 -0
  23. package/dist/codegen/types.js.map +1 -0
  24. package/dist/format.d.ts +136 -0
  25. package/dist/format.js +872 -0
  26. package/dist/format.js.map +1 -0
  27. package/dist/index.d.ts +120 -0
  28. package/dist/index.js +507 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/internal.d.ts +1 -0
  31. package/dist/internal.js +4 -0
  32. package/dist/internal.js.map +1 -0
  33. package/dist/parser/ids.d.ts +4 -0
  34. package/dist/parser/ids.js +172 -0
  35. package/dist/parser/ids.js.map +1 -0
  36. package/dist/parser/imports.d.ts +2 -0
  37. package/dist/parser/imports.js +28 -0
  38. package/dist/parser/imports.js.map +1 -0
  39. package/dist/parser/interface.d.ts +10 -0
  40. package/dist/parser/interface.js +93 -0
  41. package/dist/parser/interface.js.map +1 -0
  42. package/dist/parser/kielerWording.d.ts +2 -0
  43. package/dist/parser/kielerWording.js +196 -0
  44. package/dist/parser/kielerWording.js.map +1 -0
  45. package/dist/parser/lexer.d.ts +25 -0
  46. package/dist/parser/lexer.js +334 -0
  47. package/dist/parser/lexer.js.map +1 -0
  48. package/dist/parser/parser.d.ts +29 -0
  49. package/dist/parser/parser.js +3249 -0
  50. package/dist/parser/parser.js.map +1 -0
  51. package/dist/parser/resolve.d.ts +46 -0
  52. package/dist/parser/resolve.js +919 -0
  53. package/dist/parser/resolve.js.map +1 -0
  54. package/dist/parser/source.d.ts +15 -0
  55. package/dist/parser/source.js +42 -0
  56. package/dist/parser/source.js.map +1 -0
  57. package/dist/parser/validate.d.ts +5 -0
  58. package/dist/parser/validate.js +1430 -0
  59. package/dist/parser/validate.js.map +1 -0
  60. package/dist/sim/abortRegions.d.ts +9 -0
  61. package/dist/sim/abortRegions.js +192 -0
  62. package/dist/sim/abortRegions.js.map +1 -0
  63. package/dist/sim/analysis.d.ts +113 -0
  64. package/dist/sim/analysis.js +1104 -0
  65. package/dist/sim/analysis.js.map +1 -0
  66. package/dist/sim/codegen.d.ts +30 -0
  67. package/dist/sim/codegen.js +730 -0
  68. package/dist/sim/codegen.js.map +1 -0
  69. package/dist/sim/compile.d.ts +43 -0
  70. package/dist/sim/compile.js +1062 -0
  71. package/dist/sim/compile.js.map +1 -0
  72. package/dist/sim/deps.d.ts +73 -0
  73. package/dist/sim/deps.js +481 -0
  74. package/dist/sim/deps.js.map +1 -0
  75. package/dist/sim/describe.d.ts +22 -0
  76. package/dist/sim/describe.js +272 -0
  77. package/dist/sim/describe.js.map +1 -0
  78. package/dist/sim/describePreemption.d.ts +22 -0
  79. package/dist/sim/describePreemption.js +90 -0
  80. package/dist/sim/describePreemption.js.map +1 -0
  81. package/dist/sim/describeStructure.d.ts +75 -0
  82. package/dist/sim/describeStructure.js +293 -0
  83. package/dist/sim/describeStructure.js.map +1 -0
  84. package/dist/sim/eval.d.ts +99 -0
  85. package/dist/sim/eval.js +644 -0
  86. package/dist/sim/eval.js.map +1 -0
  87. package/dist/sim/exec.d.ts +212 -0
  88. package/dist/sim/exec.js +874 -0
  89. package/dist/sim/exec.js.map +1 -0
  90. package/dist/sim/fold.d.ts +2 -0
  91. package/dist/sim/fold.js +40 -0
  92. package/dist/sim/fold.js.map +1 -0
  93. package/dist/sim/goblock.d.ts +16 -0
  94. package/dist/sim/goblock.js +171 -0
  95. package/dist/sim/goblock.js.map +1 -0
  96. package/dist/sim/guardIndices.d.ts +13 -0
  97. package/dist/sim/guardIndices.js +137 -0
  98. package/dist/sim/guardIndices.js.map +1 -0
  99. package/dist/sim/index.d.ts +43 -0
  100. package/dist/sim/index.js +138 -0
  101. package/dist/sim/index.js.map +1 -0
  102. package/dist/sim/lower.d.ts +33 -0
  103. package/dist/sim/lower.js +716 -0
  104. package/dist/sim/lower.js.map +1 -0
  105. package/dist/sim/memory.d.ts +47 -0
  106. package/dist/sim/memory.js +328 -0
  107. package/dist/sim/memory.js.map +1 -0
  108. package/dist/sim/model.d.ts +487 -0
  109. package/dist/sim/model.js +772 -0
  110. package/dist/sim/model.js.map +1 -0
  111. package/dist/sim/passes/abort.d.ts +2 -0
  112. package/dist/sim/passes/abort.js +269 -0
  113. package/dist/sim/passes/abort.js.map +1 -0
  114. package/dist/sim/passes/abortRegion.d.ts +10 -0
  115. package/dist/sim/passes/abortRegion.js +62 -0
  116. package/dist/sim/passes/abortRegion.js.map +1 -0
  117. package/dist/sim/passes/arrayAssignment.d.ts +2 -0
  118. package/dist/sim/passes/arrayAssignment.js +147 -0
  119. package/dist/sim/passes/arrayAssignment.js.map +1 -0
  120. package/dist/sim/passes/codeEffects.d.ts +2 -0
  121. package/dist/sim/passes/codeEffects.js +14 -0
  122. package/dist/sim/passes/codeEffects.js.map +1 -0
  123. package/dist/sim/passes/complexFinalState.d.ts +4 -0
  124. package/dist/sim/passes/complexFinalState.js +77 -0
  125. package/dist/sim/passes/complexFinalState.js.map +1 -0
  126. package/dist/sim/passes/connector.d.ts +2 -0
  127. package/dist/sim/passes/connector.js +18 -0
  128. package/dist/sim/passes/connector.js.map +1 -0
  129. package/dist/sim/passes/contained.d.ts +37 -0
  130. package/dist/sim/passes/contained.js +198 -0
  131. package/dist/sim/passes/contained.js.map +1 -0
  132. package/dist/sim/passes/context.d.ts +39 -0
  133. package/dist/sim/passes/context.js +3 -0
  134. package/dist/sim/passes/context.js.map +1 -0
  135. package/dist/sim/passes/countDelay.d.ts +2 -0
  136. package/dist/sim/passes/countDelay.js +51 -0
  137. package/dist/sim/passes/countDelay.js.map +1 -0
  138. package/dist/sim/passes/dataflow.d.ts +11 -0
  139. package/dist/sim/passes/dataflow.js +319 -0
  140. package/dist/sim/passes/dataflow.js.map +1 -0
  141. package/dist/sim/passes/deferred.d.ts +2 -0
  142. package/dist/sim/passes/deferred.js +345 -0
  143. package/dist/sim/passes/deferred.js.map +1 -0
  144. package/dist/sim/passes/detect.d.ts +10 -0
  145. package/dist/sim/passes/detect.js +33 -0
  146. package/dist/sim/passes/detect.js.map +1 -0
  147. package/dist/sim/passes/during.d.ts +2 -0
  148. package/dist/sim/passes/during.js +67 -0
  149. package/dist/sim/passes/during.js.map +1 -0
  150. package/dist/sim/passes/entry.d.ts +5 -0
  151. package/dist/sim/passes/entry.js +93 -0
  152. package/dist/sim/passes/entry.js.map +1 -0
  153. package/dist/sim/passes/enum.d.ts +2 -0
  154. package/dist/sim/passes/enum.js +22 -0
  155. package/dist/sim/passes/enum.js.map +1 -0
  156. package/dist/sim/passes/exit.d.ts +4 -0
  157. package/dist/sim/passes/exit.js +120 -0
  158. package/dist/sim/passes/exit.js.map +1 -0
  159. package/dist/sim/passes/finalRegion.d.ts +2 -0
  160. package/dist/sim/passes/finalRegion.js +21 -0
  161. package/dist/sim/passes/finalRegion.js.map +1 -0
  162. package/dist/sim/passes/followedBy.d.ts +2 -0
  163. package/dist/sim/passes/followedBy.js +78 -0
  164. package/dist/sim/passes/followedBy.js.map +1 -0
  165. package/dist/sim/passes/forRegion.d.ts +9 -0
  166. package/dist/sim/passes/forRegion.js +230 -0
  167. package/dist/sim/passes/forRegion.js.map +1 -0
  168. package/dist/sim/passes/history.d.ts +12 -0
  169. package/dist/sim/passes/history.js +115 -0
  170. package/dist/sim/passes/history.js.map +1 -0
  171. package/dist/sim/passes/hostCode.d.ts +2 -0
  172. package/dist/sim/passes/hostCode.js +152 -0
  173. package/dist/sim/passes/hostCode.js.map +1 -0
  174. package/dist/sim/passes/index.d.ts +4 -0
  175. package/dist/sim/passes/index.js +84 -0
  176. package/dist/sim/passes/index.js.map +1 -0
  177. package/dist/sim/passes/inheritance.d.ts +8 -0
  178. package/dist/sim/passes/inheritance.js +233 -0
  179. package/dist/sim/passes/inheritance.js.map +1 -0
  180. package/dist/sim/passes/initOperator.d.ts +2 -0
  181. package/dist/sim/passes/initOperator.js +68 -0
  182. package/dist/sim/passes/initOperator.js.map +1 -0
  183. package/dist/sim/passes/initialization.d.ts +2 -0
  184. package/dist/sim/passes/initialization.js +69 -0
  185. package/dist/sim/passes/initialization.js.map +1 -0
  186. package/dist/sim/passes/ode.d.ts +2 -0
  187. package/dist/sim/passes/ode.js +14 -0
  188. package/dist/sim/passes/ode.js.map +1 -0
  189. package/dist/sim/passes/period.d.ts +2 -0
  190. package/dist/sim/passes/period.js +106 -0
  191. package/dist/sim/passes/period.js.map +1 -0
  192. package/dist/sim/passes/prTransitions.d.ts +2 -0
  193. package/dist/sim/passes/prTransitions.js +12 -0
  194. package/dist/sim/passes/prTransitions.js.map +1 -0
  195. package/dist/sim/passes/pre.d.ts +4 -0
  196. package/dist/sim/passes/pre.js +326 -0
  197. package/dist/sim/passes/pre.js.map +1 -0
  198. package/dist/sim/passes/quirks.d.ts +2 -0
  199. package/dist/sim/passes/quirks.js +169 -0
  200. package/dist/sim/passes/quirks.js.map +1 -0
  201. package/dist/sim/passes/reference.d.ts +60 -0
  202. package/dist/sim/passes/reference.js +386 -0
  203. package/dist/sim/passes/reference.js.map +1 -0
  204. package/dist/sim/passes/regionActions.d.ts +2 -0
  205. package/dist/sim/passes/regionActions.js +56 -0
  206. package/dist/sim/passes/regionActions.js.map +1 -0
  207. package/dist/sim/passes/sequentialFollowedBy.d.ts +2 -0
  208. package/dist/sim/passes/sequentialFollowedBy.js +72 -0
  209. package/dist/sim/passes/sequentialFollowedBy.js.map +1 -0
  210. package/dist/sim/passes/signal.d.ts +2 -0
  211. package/dist/sim/passes/signal.js +230 -0
  212. package/dist/sim/passes/signal.js.map +1 -0
  213. package/dist/sim/passes/static.d.ts +5 -0
  214. package/dist/sim/passes/static.js +67 -0
  215. package/dist/sim/passes/static.js.map +1 -0
  216. package/dist/sim/passes/suspend.d.ts +10 -0
  217. package/dist/sim/passes/suspend.js +71 -0
  218. package/dist/sim/passes/suspend.js.map +1 -0
  219. package/dist/sim/passes/termination.d.ts +9 -0
  220. package/dist/sim/passes/termination.js +69 -0
  221. package/dist/sim/passes/termination.js.map +1 -0
  222. package/dist/sim/passes/timedAutomata.d.ts +10 -0
  223. package/dist/sim/passes/timedAutomata.js +437 -0
  224. package/dist/sim/passes/timedAutomata.js.map +1 -0
  225. package/dist/sim/passes/unpackClasses.d.ts +2 -0
  226. package/dist/sim/passes/unpackClasses.js +54 -0
  227. package/dist/sim/passes/unpackClasses.js.map +1 -0
  228. package/dist/sim/passes/userSchedule.d.ts +2 -0
  229. package/dist/sim/passes/userSchedule.js +43 -0
  230. package/dist/sim/passes/userSchedule.js.map +1 -0
  231. package/dist/sim/passes/weakSuspend.d.ts +2 -0
  232. package/dist/sim/passes/weakSuspend.js +145 -0
  233. package/dist/sim/passes/weakSuspend.js.map +1 -0
  234. package/dist/sim/preemptionLog.d.ts +41 -0
  235. package/dist/sim/preemptionLog.js +133 -0
  236. package/dist/sim/preemptionLog.js.map +1 -0
  237. package/dist/sim/random.d.ts +12 -0
  238. package/dist/sim/random.js +40 -0
  239. package/dist/sim/random.js.map +1 -0
  240. package/dist/sim/reasons.d.ts +29 -0
  241. package/dist/sim/reasons.js +168 -0
  242. package/dist/sim/reasons.js.map +1 -0
  243. package/dist/sim/scg.d.ts +124 -0
  244. package/dist/sim/scg.js +723 -0
  245. package/dist/sim/scg.js.map +1 -0
  246. package/dist/sim/sfr.d.ts +4 -0
  247. package/dist/sim/sfr.js +264 -0
  248. package/dist/sim/sfr.js.map +1 -0
  249. package/dist/sim/stringConditions.d.ts +3 -0
  250. package/dist/sim/stringConditions.js +42 -0
  251. package/dist/sim/stringConditions.js.map +1 -0
  252. package/dist/sim/structure/copy.d.ts +4 -0
  253. package/dist/sim/structure/copy.js +140 -0
  254. package/dist/sim/structure/copy.js.map +1 -0
  255. package/dist/sim/structure/delays.d.ts +30 -0
  256. package/dist/sim/structure/delays.js +127 -0
  257. package/dist/sim/structure/delays.js.map +1 -0
  258. package/dist/sim/structure/instance.d.ts +15 -0
  259. package/dist/sim/structure/instance.js +69 -0
  260. package/dist/sim/structure/instance.js.map +1 -0
  261. package/dist/sim/structure/methods.d.ts +19 -0
  262. package/dist/sim/structure/methods.js +550 -0
  263. package/dist/sim/structure/methods.js.map +1 -0
  264. package/dist/sim/structure/rewrite.d.ts +20 -0
  265. package/dist/sim/structure/rewrite.js +113 -0
  266. package/dist/sim/structure/rewrite.js.map +1 -0
  267. package/dist/sim/structure/track.d.ts +22 -0
  268. package/dist/sim/structure/track.js +123 -0
  269. package/dist/sim/structure/track.js.map +1 -0
  270. package/dist/sim/tracker.d.ts +77 -0
  271. package/dist/sim/tracker.js +265 -0
  272. package/dist/sim/tracker.js.map +1 -0
  273. package/dist/sim/values.d.ts +31 -0
  274. package/dist/sim/values.js +103 -0
  275. package/dist/sim/values.js.map +1 -0
  276. package/dist/types.d.ts +670 -0
  277. package/dist/types.js +9 -0
  278. package/dist/types.js.map +1 -0
  279. package/package.json +58 -3
@@ -0,0 +1,874 @@
1
+ // Tick execution, netlist style: every tick visits the SCG's nodes in the static schedule of analysis.ts, each
2
+ // at most once, and a node runs if control reached it in this tick (or, for a depth, if its pause was reached
3
+ // in the previous tick). Joins fire by KIELER's synchronizer rules. Everything a node does is recorded in
4
+ // source terms for TickResult.
5
+ import { compileEffect, ExprCompiler, SimError } from "./eval.js";
6
+ import { Memory } from "./memory.js";
7
+ import { addressOf, droppedIndexRefs, withAddresses } from "./guardIndices.js";
8
+ import { threadNodes } from "./analysis.js";
9
+ import { allScopes, walkExpr } from "./model.js";
10
+ import { cloneRandState, newRandState } from "./random.js";
11
+ import { Tracker } from "./tracker.js";
12
+ import { copyNotes, copyStates, trackView } from "./structure/track.js";
13
+ import { historyRecordReader, hookEvents, isHook, StateNames, suspendEvents, takeNotes, takeOptions } from "./preemptionLog.js";
14
+ import { lookupSource, readProbes, seenText, sourceElements, triggerProbes } from "./reasons.js";
15
+ import { cloneValue, convert, ctypeOf, defaultValue, doubleToInt, freshString, INT_MAX, INT_MIN, isCString, makeArray, toChar, } from "./values.js";
16
+ /** Node kinds of the executable schedule (also read by the C code generator, ../codegen). */
17
+ export var K;
18
+ (function (K) {
19
+ K[K["Entry"] = 0] = "Entry";
20
+ K[K["Exit"] = 1] = "Exit";
21
+ K[K["Assign"] = 2] = "Assign";
22
+ K[K["Cond"] = 3] = "Cond";
23
+ K[K["Fork"] = 4] = "Fork";
24
+ K[K["Join"] = 5] = "Join";
25
+ K[K["Surface"] = 6] = "Surface";
26
+ K[K["Depth"] = 7] = "Depth";
27
+ })(K || (K = {}));
28
+ export class ExecutableChart {
29
+ compiled;
30
+ iface;
31
+ nodes = [];
32
+ slots = new Map();
33
+ pool = [];
34
+ traced = [];
35
+ /** Instances without fields: an empty object in the pool. */
36
+ emptyObjects;
37
+ inputs = [];
38
+ goInits = [];
39
+ /** Slots of the conditions' guard variables (XNode.mem), which start at 0 like every member of KIELER's struct. */
40
+ guardSlots = [];
41
+ /** The padding bytes of KIELER's struct (memory.ts), zero at the start. */
42
+ padding;
43
+ varCount;
44
+ rootEntry;
45
+ /** Names of every variable in the pool (inputs or not). */
46
+ knownNames = new Set();
47
+ signalValues = new Map();
48
+ presence = new Map();
49
+ plain = new Map();
50
+ constructor(compiled, iface) {
51
+ this.compiled = compiled;
52
+ this.iface = iface;
53
+ // Variables: everything declared anywhere in the core chart.
54
+ let slot = 0;
55
+ for (const scope of allScopes(compiled.core)) {
56
+ for (const v of scope.decls) {
57
+ if (this.slots.has(v) || v.const)
58
+ continue;
59
+ this.slots.set(v, { slot: slot++, type: ctypeOf(v.type), dims: v.dims.map(d => (d.k === 'lit' && typeof d.v === 'number' ? d.v : 0)) });
60
+ }
61
+ }
62
+ const ensure = (v) => {
63
+ let info = this.slots.get(v);
64
+ if (!info) {
65
+ info = { slot: slot++, type: ctypeOf(v.type), dims: v.dims.map(d => (d.k === 'lit' && typeof d.v === 'number' ? d.v : 0)) };
66
+ this.slots.set(v, info);
67
+ }
68
+ return info;
69
+ };
70
+ // KIELER's struct of the chart's variables, for indices outside an array (memory.ts); its padding in a slot.
71
+ const rootVars = new Map();
72
+ for (const v of compiled.core.decls)
73
+ if (v.decl && !v.generated && !v.role && !rootVars.has(v.decl))
74
+ rootVars.set(v.decl, v);
75
+ const padding = slot++;
76
+ const memory = new Memory(compiled.chart, id => {
77
+ const v = rootVars.get(id);
78
+ const info = v ? this.slots.get(v) : undefined;
79
+ return v && info ? { v, slot: info.slot, dims: info.dims } : undefined;
80
+ }, padding, compiled.lowered.takenOrder.length);
81
+ this.padding = { slot: padding, size: memory.size };
82
+ const ec = new ExprCompiler({ info: ensure, label: v => v.display ?? v.name, memory });
83
+ // The source triggers, for the values a check read (reasons.ts).
84
+ const sources = sourceElements(compiled.chart, compiled.shared.index);
85
+ const probe = (core, trigger) => {
86
+ const list = triggerProbes(core, trigger, r => ec.compile(r).fn, r => {
87
+ const type = ctypeOf(lowermost(r).v.type);
88
+ return v => toValue(v, type, false);
89
+ });
90
+ return list.length ? list : undefined;
91
+ };
92
+ // KIELER's data pool: the root's declarations, without constants and generated helpers.
93
+ for (const v of compiled.core.decls) {
94
+ if (v.member && !v.const && !v.declKind) {
95
+ if (!v.tags.has('#const-member'))
96
+ this.pool.push({ name: v.member.name, v, type: ctypeOf(v.type), of: v.member.of.name });
97
+ continue;
98
+ }
99
+ if (v.const || v.declKind || v.name.startsWith('_'))
100
+ continue;
101
+ this.pool.push({ name: v.name, v, type: ctypeOf(v.type) });
102
+ this.knownNames.add(v.name);
103
+ if (v.input && !v.generated)
104
+ this.inputs.push({ v, name: v.name, type: ctypeOf(v.type) });
105
+ if (v.role === 'value' && v.of)
106
+ this.signalValues.set(v.of.name, v);
107
+ else if (v.role === 'presence')
108
+ this.presence.set(v.name, v);
109
+ else if (!v.role)
110
+ this.plain.set(v.name, v);
111
+ }
112
+ this.emptyObjects = compiled.core.ext.emptyInstances ?? [];
113
+ // What a reader may trace beyond the pool: members of the root's instances, locals of inner scopes.
114
+ const rootDecls = new Set(compiled.core.decls);
115
+ const traceKeys = new Set();
116
+ const trace = (key, v) => {
117
+ if (traceKeys.has(key) && v.role !== 'value')
118
+ return;
119
+ const i = this.traced.findIndex(t => t.key === key);
120
+ if (i >= 0)
121
+ this.traced.splice(i, 1);
122
+ traceKeys.add(key);
123
+ this.traced.push({ key, v, type: ctypeOf(v.type) });
124
+ };
125
+ for (const [v] of this.slots) {
126
+ if (v.const || v.declKind || !v.decl || v.decl.includes('/'))
127
+ continue;
128
+ if (v.member && rootDecls.has(v)) {
129
+ if (!v.tags.has('#const-member'))
130
+ trace(`${v.member.of.name}.${v.member.name}`, v);
131
+ continue;
132
+ }
133
+ if (rootDecls.has(v) || v.member)
134
+ continue;
135
+ // Source variables only (a region's declaration keeps its id when KIELER moves it to the parent state); a
136
+ // local signal is its presence and, when valued, its value (which replaces it).
137
+ if (!v.decl.includes('$') || (v.role && v.role !== 'value' && v.role !== 'presence'))
138
+ continue;
139
+ // A local of a for-region copy's state: one key per copy (traceableVariables).
140
+ trace(v.forCopy ? `${v.decl}|${v.forCopy.region}=${v.forCopy.value}` : v.decl, v);
141
+ }
142
+ // Inputs the chart writes (KIELER's copy propagation keeps the guard variable of a condition that reads one).
143
+ const writtenInputs = new Set();
144
+ for (const n of compiled.scg.nodes) {
145
+ const f = n.effect;
146
+ if (f?.k === 'assign' && lowermost(f.ref).v.input)
147
+ writtenInputs.add(lowermost(f.ref).v);
148
+ }
149
+ // Nodes in schedule order.
150
+ const order = compiled.analysis.order;
151
+ const index = new Map();
152
+ order.forEach((n, i) => index.set(n, i));
153
+ const at = (n) => (n && index.has(n) ? index.get(n) : -1);
154
+ const rootExit = compiled.scg.root.exit;
155
+ for (const n of order) {
156
+ const x = { kind: kindOf(n), src: n, next: at(n.next), then: at(n.then), else: at(n.else), pair: -1 };
157
+ switch (n.kind) {
158
+ case 'fork':
159
+ x.entries = n.threads.map(t => at(t.entry));
160
+ break;
161
+ case 'surface':
162
+ x.pair = at(n.depth);
163
+ x.log = surfaceLog(n);
164
+ break;
165
+ case 'depth':
166
+ x.pair = at(n.surface);
167
+ break;
168
+ case 'exit':
169
+ if (n === rootExit)
170
+ x.rootExit = true;
171
+ break;
172
+ case 'cond': {
173
+ // KIELER's C code drops some indices of a condition (guardIndices.ts): the array's address instead.
174
+ const dropped = droppedIndexRefs(n.expr);
175
+ const condition = dropped.size ? withAddresses(n.expr, dropped, v => addressOf(v, ensure(v).slot)) : n.expr;
176
+ // KIELER's guard `_c<g> = condition` is a char that keeps its value between ticks: a conditional
177
+ // without an else part (`c ? a` in a trigger) gives that value when `c` is false (ExprCompiler.selves).
178
+ if (hasConditionalWithoutElse(condition)) {
179
+ const mem = slot++;
180
+ x.mem = mem;
181
+ this.guardSlots.push(mem);
182
+ x.test = ec.withSelf({ fn: rt => rt.vals[mem], type: 'int' }, () => ec.compile(condition)).fn;
183
+ }
184
+ else {
185
+ x.test = ec.compile(condition).fn;
186
+ }
187
+ // KIELER's copy propagation drops the guard variable of a plain read of an input the chart never
188
+ // writes (`_g3 = _g2 && n`); every other condition goes through the char (`if n` with n = 256 holds,
189
+ // but `if (c) ? n` with c true and n = 256 does not).
190
+ const e = n.expr;
191
+ x.char = !(e.k === 'ref' && !e.sub && lowermost(e).v.input && !writtenInputs.has(lowermost(e).v));
192
+ const t = n.transition;
193
+ const check = t?.origin ?? t?.checks;
194
+ // An `if` of a method body KIELER copied into the graph (n.method) tests the body, not the trigger.
195
+ if (check && !n.method) {
196
+ x.log = { check, checkKey: takeMark(t)?.key ?? check };
197
+ x.probes = probe(n.expr, lookupSource(sources.transitions, check)?.trigger);
198
+ }
199
+ else if (t?.about && isActionId(t.about))
200
+ x.log = { actionCheck: t.about };
201
+ break;
202
+ }
203
+ case 'assign': {
204
+ const f = n.effect;
205
+ x.run = compileEffect(f, ec);
206
+ if (f.k === 'mark') {
207
+ if (f.m.kind === 'take')
208
+ x.log = { take: f.m.transition, takeKey: f.m.key, takeOptions: takeOptions(f.m), triggered: !!lookupSource(sources.transitions, f.m.transition)?.trigger };
209
+ else if (f.m.kind === 'action')
210
+ x.log = { action: f.m.action };
211
+ else if (isHook(f.m))
212
+ x.log = { hook: f.m };
213
+ }
214
+ else if (f.k === 'assign') {
215
+ const target = f.ref.v;
216
+ const visible = !f.o.hidden && !target.generated;
217
+ if (visible || f.o.emits)
218
+ x.log = { write: { v: target, by: f.o.by, how: f.o.init ? 'init' : 'update', emits: f.o.emits } };
219
+ else if (target.role === 'enabled' && f.o.by && /!suspend\d+$/.test(f.o.by)) {
220
+ x.log = { suspendFlag: target };
221
+ x.probes = probe(f.expr, lookupSource(sources.actions, f.o.by)?.trigger);
222
+ }
223
+ if (compiled.goBlock.moved.has(n) && lowermost(f.ref).v.input)
224
+ x.goInit = true;
225
+ }
226
+ else if (f.k === 'print') {
227
+ x.log = { print: f.o.by };
228
+ }
229
+ break;
230
+ }
231
+ case 'join': {
232
+ const info = compiled.analysis.joins.get(n);
233
+ if (info && !info.dead) {
234
+ const any = info.sync === 'any';
235
+ x.join = {
236
+ sync: info.sync,
237
+ first: info.first ? at(info.first.exit) : -1,
238
+ threads: info.counted.map(t => ({
239
+ exit: at(t.exit), watch: any ? [] : watchNodes(compiled, t, info.sync).map(at).filter(i => i >= 0),
240
+ region: t.region?.origin ?? t.region?.about,
241
+ })),
242
+ };
243
+ if (any) {
244
+ const fork = n.fork;
245
+ x.join.kill = fork.threads.flatMap(t => threadNodes(compiled.scg, t)).filter(m => m.kind === 'surface').map(at).filter(i => i >= 0);
246
+ x.join.state = fork.state?.origin ?? fork.state?.about;
247
+ }
248
+ }
249
+ break;
250
+ }
251
+ }
252
+ const preempt = compiled.analysis.preemption?.get(n);
253
+ if (preempt)
254
+ x.preempt = preempt.map(at).filter(i => i >= 0);
255
+ this.nodes.push(x);
256
+ }
257
+ // KIELER's reset(): the GO block's assignments without input reads, in order (only their effect on inputs is kept).
258
+ for (const n of compiled.goBlock.nodes) {
259
+ if (!compiled.goBlock.moved.has(n) || !index.has(n))
260
+ continue;
261
+ this.goInits.push(index.get(n));
262
+ }
263
+ this.rootEntry = at(compiled.scg.root.entry);
264
+ this.varCount = slot;
265
+ }
266
+ initialState(tracker) {
267
+ const vals = new Array(this.varCount);
268
+ for (const info of this.slots.values())
269
+ vals[info.slot] = makeArray(info.dims, () => defaultValue(info.type));
270
+ for (const g of this.guardSlots)
271
+ vals[g] = 0;
272
+ vals[this.padding.slot] = new Array(this.padding.size).fill(0);
273
+ tracker.reset();
274
+ return {
275
+ vals, rand: newRandState(), paused: new Uint8Array(this.nodes.length), started: false, dead: false,
276
+ terminated: false, tracker: tracker.snapshot(),
277
+ };
278
+ }
279
+ // ----- reporting -----
280
+ report(vals, extra = {}) {
281
+ const trace = {};
282
+ for (const t of this.traced)
283
+ trace[t.key] = toValue(vals[this.slots.get(t.v).slot], t.type, false);
284
+ const pool = { ...extra };
285
+ for (const name of this.emptyObjects)
286
+ pool[name] = {};
287
+ for (const p of this.pool) {
288
+ const value = toValue(vals[this.slots.get(p.v).slot], p.type, true);
289
+ if (value === null)
290
+ continue;
291
+ if (p.of)
292
+ (pool[p.of] ??= {})[p.name] = value;
293
+ else
294
+ pool[p.name] = value;
295
+ }
296
+ const values = {};
297
+ const present = {};
298
+ for (const info of this.iface) {
299
+ if (info.const)
300
+ continue;
301
+ if (info.signal) {
302
+ const pres = this.presence.get(info.name);
303
+ const p = pres ? vals[this.slots.get(pres).slot] : 0;
304
+ present[info.name] = typeof p === 'number' ? p !== 0 : false;
305
+ if (info.valued) {
306
+ const vv = this.signalValues.get(info.name);
307
+ values[info.name] = vv ? toValue(vals[this.slots.get(vv).slot], ctypeOf(vv.type), false) : null;
308
+ }
309
+ else {
310
+ values[info.name] = present[info.name];
311
+ }
312
+ continue;
313
+ }
314
+ const v = this.plain.get(info.name);
315
+ if (v)
316
+ values[info.name] = toValue(vals[this.slots.get(v).slot], ctypeOf(v.type), false);
317
+ }
318
+ return { values, present, pool, trace };
319
+ }
320
+ /**
321
+ * Every input's value in `vals`, by KIELER's names: a valued input signal V as `V` (its presence) and `V_val` (its
322
+ * value); an unset string is null. Read right after applyInputs: the values a tick runs with (TickResult.ranWith).
323
+ */
324
+ inputValues(vals) {
325
+ const out = {};
326
+ for (const input of this.inputs) {
327
+ const key = input.v.role === 'value' && input.v.of ? input.v.of.name + '_val' : input.name;
328
+ out[key] = toValue(vals[this.slots.get(input.v).slot], input.type, false);
329
+ }
330
+ return out;
331
+ }
332
+ /**
333
+ * Applies the environment's inputs (B-9): missing keep their value, arrays are overwritten element-wise. Keys
334
+ * that are not inputs of the chart stay in KIELER's data pool (`extra`), as KIELER's server keeps them.
335
+ */
336
+ applyInputs(vals, given, extra) {
337
+ const consumed = new Set();
338
+ for (const input of this.inputs) {
339
+ consumed.add(input.name);
340
+ if (input.v.of)
341
+ consumed.add(input.v.of.name);
342
+ const slot = this.slots.get(input.v).slot;
343
+ let name = input.name;
344
+ let value = given[name];
345
+ // A valued input signal V is set by its value (`V_val`, or the signal's name with a non-boolean).
346
+ if (input.v.role === 'value' && input.v.of) {
347
+ value = given[name] ?? (given[input.v.of.name] !== undefined && typeof given[input.v.of.name] !== 'boolean' ? given[input.v.of.name] : undefined);
348
+ name = input.v.of.name;
349
+ }
350
+ if (input.v.role === 'presence') {
351
+ const g = given[name];
352
+ value = typeof g === 'boolean' ? g : g === undefined || g === null ? undefined : true;
353
+ }
354
+ if (value !== undefined)
355
+ vals[slot] = fromInput(value, input.type, vals[slot]);
356
+ else if (input.type === 'string')
357
+ vals[slot] = rematerialise(vals[slot]);
358
+ }
359
+ for (const [k, v] of Object.entries(given))
360
+ if (!consumed.has(k) && !this.knownNames.has(k))
361
+ extra[k] = v;
362
+ }
363
+ }
364
+ function rematerialise(v) {
365
+ if (isCString(v))
366
+ return freshString(v.s);
367
+ if (Array.isArray(v))
368
+ return v.map(rematerialise);
369
+ return v;
370
+ }
371
+ function kindOf(n) {
372
+ switch (n.kind) {
373
+ case 'entry': return K.Entry;
374
+ case 'exit': return K.Exit;
375
+ case 'assign': return K.Assign;
376
+ case 'cond': return K.Cond;
377
+ case 'fork': return K.Fork;
378
+ case 'join': return K.Join;
379
+ case 'surface': return K.Surface;
380
+ case 'depth': return K.Depth;
381
+ }
382
+ }
383
+ function isActionId(id) {
384
+ return /![a-z]+\d+$/.test(id);
385
+ }
386
+ function surfaceLog(n) {
387
+ const s = n.state;
388
+ const state = s?.origin ?? s?.about;
389
+ return state ? { pause: { state } } : undefined;
390
+ }
391
+ function watchNodes(compiled, t, sync) {
392
+ const kind = sync === 'surface' ? 'surface' : 'depth';
393
+ const inside = (x) => {
394
+ for (let y = x; y; y = y.parent)
395
+ if (y === t)
396
+ return true;
397
+ return false;
398
+ };
399
+ return compiled.scg.nodes.filter(n => n.kind === kind && inside(n.thread));
400
+ }
401
+ /** Converts a run-time value for reporting (bools as booleans; strings as text; `pool`: KIELER's JSON). */
402
+ function toValue(v, type, pool) {
403
+ if (Array.isArray(v))
404
+ return v.map(x => (pool && type === 'string' && x === null ? '' : toValue(x, type, pool)));
405
+ if (v === null)
406
+ return null;
407
+ if (isCString(v))
408
+ return v.s;
409
+ if (type === 'bool')
410
+ return v !== 0;
411
+ return v;
412
+ }
413
+ /** cJSON's valueint: a saturating conversion of the number to int. */
414
+ function jsonInt(n) {
415
+ if (n >= INT_MAX)
416
+ return INT_MAX;
417
+ if (n <= INT_MIN)
418
+ return INT_MIN;
419
+ return doubleToInt(n);
420
+ }
421
+ function fromInput(value, type, current) {
422
+ if (Array.isArray(value)) {
423
+ const target = Array.isArray(current) ? current.map(cloneValue) : [];
424
+ value.forEach((x, i) => { if (i < target.length)
425
+ target[i] = fromInput(x, type, target[i]); });
426
+ return target;
427
+ }
428
+ switch (type) {
429
+ case 'string': return typeof value === 'string' ? freshString(value) : null;
430
+ case 'float': return typeof value === 'number' ? value : value === true ? 1 : 0;
431
+ case 'bool': return typeof value === 'boolean' ? (value ? 1 : 0) : typeof value === 'number' ? toChar(jsonInt(value)) : 0;
432
+ default: return typeof value === 'boolean' ? (value ? 1 : 0) : typeof value === 'number' ? jsonInt(value) : 0;
433
+ }
434
+ }
435
+ // ---------------------------------------------------------------------------------------------------
436
+ // The simulation
437
+ // ---------------------------------------------------------------------------------------------------
438
+ export class SimRunner {
439
+ exe;
440
+ chart;
441
+ state;
442
+ /** Environment values for names that are not inputs (KIELER's server keeps them in its pool). */
443
+ extra = {};
444
+ tracker;
445
+ takenIds;
446
+ names;
447
+ regionNames = new Map();
448
+ abortRegions = new Set();
449
+ constructor(exe, chart) {
450
+ this.exe = exe;
451
+ this.chart = chart;
452
+ // References and for-regions: the tracker follows the chart with its instances and copies (structure/track.ts).
453
+ const view = trackView(exe.compiled, chart);
454
+ this.tracker = new Tracker(view.root, view.report);
455
+ for (const id of exe.compiled.scg.silentHops ?? [])
456
+ this.tracker.autoTake.add(id);
457
+ this.names = new StateNames(chart);
458
+ const visit = (st) => {
459
+ for (const r of st.regions) {
460
+ if (r.name)
461
+ this.regionNames.set(r.id, r.name);
462
+ if (r.abort)
463
+ this.abortRegions.add(r.id);
464
+ r.states.forEach(visit);
465
+ }
466
+ };
467
+ visit(chart);
468
+ this.state = exe.initialState(this.tracker);
469
+ this.takenIds = new Set(exe.compiled.lowered.takenOrder);
470
+ }
471
+ reset() {
472
+ this.state = this.exe.initialState(this.tracker);
473
+ this.extra = {};
474
+ }
475
+ snapshot() {
476
+ const s = this.state;
477
+ return {
478
+ extra: { ...this.extra },
479
+ vals: s.vals.map(cloneValue), rand: cloneRandState(s.rand), paused: s.paused.slice(), started: s.started,
480
+ dead: s.dead, terminated: s.terminated, halted: s.halted, tracker: this.tracker.snapshot(),
481
+ };
482
+ }
483
+ restore(s) {
484
+ this.extra = { ...(s.extra ?? {}) };
485
+ this.state = { ...s, vals: s.vals.map(cloneValue), rand: cloneRandState(s.rand), paused: s.paused.slice() };
486
+ this.tracker.restore(s.tracker);
487
+ }
488
+ step(tick, given) {
489
+ const exe = this.exe;
490
+ const s = this.state;
491
+ const tracker = this.tracker;
492
+ tracker.restore(s.tracker);
493
+ tracker.beginTick();
494
+ const log = [];
495
+ const printed = [];
496
+ const taken = [];
497
+ const actions = [];
498
+ let terminatedNow = false;
499
+ let error;
500
+ const before = s.vals.map(cloneValue);
501
+ const rt = { vals: s.vals, rand: s.rand, printed };
502
+ if (s.halted) {
503
+ return this.result(tick, given, log, printed, taken, actions, false, s.halted, before, exe.inputValues(s.vals));
504
+ }
505
+ const nodes = exe.nodes;
506
+ const act = new Uint8Array(nodes.length);
507
+ const condValue = new Uint8Array(nodes.length);
508
+ let ranWith;
509
+ try {
510
+ if (!s.started && exe.goInits.length) {
511
+ // KIELER's reset() runs the GO block's input-free assignments before the first inputs are read
512
+ // (B-7). Only what they do to inputs matters here: the rest runs in tick 1, in written order.
513
+ const scratch = { vals: s.vals.map(cloneValue), rand: cloneRandState(s.rand) };
514
+ for (const i of exe.goInits)
515
+ nodes[i].run(scratch, []);
516
+ for (const input of exe.inputs) {
517
+ const slot = exe.slots.get(input.v).slot;
518
+ s.vals[slot] = scratch.vals[slot];
519
+ }
520
+ }
521
+ exe.applyInputs(s.vals, given, this.extra);
522
+ ranWith = exe.inputValues(s.vals);
523
+ if (!s.dead) {
524
+ if (!s.started) {
525
+ if (exe.rootEntry >= 0)
526
+ act[exe.rootEntry] = 1;
527
+ for (const id of tracker.start())
528
+ log.push({ kind: 'enter', state: id });
529
+ }
530
+ for (let i = 0; i < nodes.length; i++)
531
+ if (nodes[i].kind === K.Depth && s.paused[nodes[i].pair])
532
+ act[i] = 1;
533
+ const paused = new Uint8Array(nodes.length);
534
+ const checked = new Set();
535
+ // Per fired transition (take key): what its trigger read when it was last checked true in this tick.
536
+ const checkedTrue = new Map();
537
+ // Per suspend flag: what its suspend triggers read.
538
+ const suspendSeen = new Map();
539
+ // KIELER's history records, for history entries in the source-level configuration (passes/history.ts).
540
+ const records = historyRecordReader(exe.compiled.core.ext.historyRecords, v => {
541
+ const info = exe.slots.get(v);
542
+ const value = info ? s.vals[info.slot] : 0;
543
+ return typeof value === 'number' ? value : 0;
544
+ });
545
+ const parOr = [];
546
+ for (let i = 0; i < nodes.length; i++) {
547
+ const x = nodes[i];
548
+ if (x.kind === K.Join) {
549
+ if (x.join && joinFires(x.join, act)) {
550
+ if (x.next >= 0)
551
+ act[x.next] = 1;
552
+ if (x.join.kill)
553
+ parOr.push(x.join);
554
+ }
555
+ continue;
556
+ }
557
+ // KIELER's netlist computes every condition's guard `_c<g> = condition` in every tick, at its place in
558
+ // the schedule, whether control reaches the condition or not: a random() or a C function in the
559
+ // trigger of a state that is not active runs anyway, and a division by zero there stops the
560
+ // simulation (probes kieler/rare/probe-trigger-*).
561
+ if (x.kind === K.Cond) {
562
+ let raw;
563
+ try {
564
+ raw = x.test(rt);
565
+ }
566
+ catch (e) {
567
+ // What C only gets wrong without crashing (a read outside an array the guide cannot lay out,
568
+ // a C function that returns nothing) does no harm where control does not go.
569
+ if (act[i] || !(e instanceof SimError) || (e.code !== 'index-out-of-range' && e.code !== 'missing-return'))
570
+ throw e;
571
+ continue;
572
+ }
573
+ const value = x.char && typeof raw === 'number' ? toChar(raw) : raw;
574
+ if (x.mem !== undefined)
575
+ rt.vals[x.mem] = value;
576
+ condValue[i] = typeof value === 'number' ? (value !== 0 ? 1 : 0) : value !== null ? 1 : 0;
577
+ }
578
+ if (!act[i])
579
+ continue;
580
+ switch (x.kind) {
581
+ case K.Entry:
582
+ case K.Depth:
583
+ // Abort regions: an earlier thread of a preemptive fork finished in this tick.
584
+ if (x.preempt && x.preempt.some(e => act[e])) {
585
+ act[i] = 0;
586
+ break;
587
+ }
588
+ if (x.next >= 0)
589
+ act[x.next] = 1;
590
+ break;
591
+ case K.Exit:
592
+ if (x.rootExit)
593
+ terminatedNow = true;
594
+ break;
595
+ case K.Fork:
596
+ for (const e of x.entries)
597
+ if (e >= 0)
598
+ act[e] = 1;
599
+ break;
600
+ case K.Surface:
601
+ paused[i] = 1;
602
+ break;
603
+ case K.Cond: {
604
+ const yes = condValue[i] === 1;
605
+ const target = yes ? x.then : x.else;
606
+ if (target >= 0)
607
+ act[target] = 1;
608
+ const lg = x.log;
609
+ if (lg?.check) {
610
+ const seen = x.probes ? readProbes(x.probes, rt) : undefined;
611
+ const reason = seen?.length ? seenText(seen) : undefined;
612
+ // Once per transition, result and values read (a generated condition that only tests a
613
+ // trigger flag adds nothing to a check already logged); each for-region copy's own.
614
+ const any = `${lg.checkKey ?? lg.check}:${yes}`;
615
+ const key = reason ? `${any}:${reason}` : any;
616
+ if (!checked.has(key) && (reason || !checked.has(`${any}:*`))) {
617
+ checked.add(key);
618
+ checked.add(`${any}:*`);
619
+ log.push(reason ? { kind: 'check', transition: lg.check, result: yes, reason, seen } : { kind: 'check', transition: lg.check, result: yes });
620
+ }
621
+ if (yes) {
622
+ // A later check without values (a generated condition) keeps what the trigger read.
623
+ if (seen?.length || !checkedTrue.has(lg.checkKey))
624
+ checkedTrue.set(lg.checkKey, seen ?? []);
625
+ }
626
+ }
627
+ else if (lg?.actionCheck && !yes) {
628
+ log.push({ kind: 'action', action: lg.actionCheck, fired: false });
629
+ }
630
+ break;
631
+ }
632
+ case K.Assign: {
633
+ if (x.goInit && !s.started) {
634
+ // Ran in KIELER's reset(), before the environment's tick-1 inputs (B-7).
635
+ const f = x.src.effect;
636
+ // (Not for deltaT's generated start value: the environment always gives deltaT.)
637
+ if (f?.k === 'assign' && !f.o.hidden && !lowermost(f.ref).v.tags.has('#deltaT')) {
638
+ const name = lowermost(f.ref).v.display ?? lowermost(f.ref).v.name;
639
+ const say = (c) => `${c(name)} is an input: KIELER sets it before reading the first inputs, so the value the environment gives ${c(name)} in tick 1 wins.`;
640
+ log.push({ kind: 'note', text: say(n => n), markdown: say(n => '`' + n + '`'), related: f.o.by ? [f.o.by] : undefined });
641
+ }
642
+ if (x.next >= 0)
643
+ act[x.next] = 1;
644
+ break;
645
+ }
646
+ const seenBefore = x.probes && x.log?.suspendFlag ? readProbes(x.probes, rt) : undefined;
647
+ const w = x.run(rt, printed);
648
+ if (rt.notes?.length) {
649
+ for (const n of rt.notes)
650
+ log.push({ kind: 'note', text: n.text, markdown: n.markdown, related: x.src.effect?.o.by ? [x.src.effect.o.by] : undefined });
651
+ rt.notes = [];
652
+ }
653
+ const lg = x.log;
654
+ if (lg) {
655
+ if (lg.take) {
656
+ taken.push(lg.take);
657
+ const key = lg.takeKey ?? lg.take;
658
+ const seen = checkedTrue.get(key);
659
+ checkedTrue.delete(key);
660
+ log.push(seen?.length ? { kind: 'take', transition: lg.take, reason: seenText(seen), seen }
661
+ : !seen && lg.triggered ? { kind: 'take', transition: lg.take, unchecked: true } : { kind: 'take', transition: lg.take });
662
+ const moved = tracker.take(lg.takeKey ?? lg.take, lg.takeOptions && { ...lg.takeOptions, record: records });
663
+ if (lg.takeKey)
664
+ log.push(...copyNotes(lg.take, lg.takeKey, exe.compiled));
665
+ for (const id of moved.exited)
666
+ log.push({ kind: 'exit', state: id });
667
+ for (const id of moved.entered)
668
+ log.push({ kind: 'enter', state: id });
669
+ if (lg.takeOptions)
670
+ log.push(...takeNotes(lg.take, lg.takeOptions, moved.entered, this.names, tracker));
671
+ }
672
+ else if (lg.hook) {
673
+ log.push(...hookEvents(lg.hook, tracker, this.names, records));
674
+ }
675
+ else if (lg.action) {
676
+ actions.push(lg.action);
677
+ log.push({ kind: 'action', action: lg.action, fired: true });
678
+ }
679
+ else if (lg.write && w) {
680
+ const value = toValue(w.value, ctypeOf(w.v.type), false);
681
+ const name = lg.write.emits ? (lg.write.emits.display ?? lg.write.emits.name) : (w.v.display ?? w.v.name);
682
+ if (lg.write.emits) {
683
+ if (w.v.role === 'curval')
684
+ log.push({ kind: 'emit', signal: name, value, by: lg.write.by ?? '' });
685
+ else if (!hasValueEmission(log, name))
686
+ log.push({ kind: 'emit', signal: name, by: lg.write.by ?? '' });
687
+ }
688
+ else {
689
+ log.push({ kind: 'write', variable: w.index ? `${name}[${w.index.join('][')}]` : name, value, by: lg.write.by ?? '', how: lg.write.how });
690
+ }
691
+ }
692
+ else if (lg.print !== undefined && printed.length) {
693
+ log.push({ kind: 'print', text: printed[printed.length - 1], by: lg.print });
694
+ }
695
+ else if (lg.suspendFlag && seenBefore?.length) {
696
+ const list = suspendSeen.get(lg.suspendFlag) ?? [];
697
+ for (const x of seenBefore)
698
+ if (!list.some(y => y.name === x.name))
699
+ list.push(x);
700
+ suspendSeen.set(lg.suspendFlag, list);
701
+ }
702
+ }
703
+ if (x.next >= 0)
704
+ act[x.next] = 1;
705
+ break;
706
+ }
707
+ }
708
+ }
709
+ // A par-or join fired: its state's regions stop. At the end of the tick, since the regions after the
710
+ // one that finished still react in this tick (a weak abort).
711
+ for (const j of parOr)
712
+ log.push(...this.parOrEvents(j, act));
713
+ for (let i = 0; i < nodes.length; i++) {
714
+ if (paused[i] && nodes[i].log?.pause) {
715
+ const state = nodes[i].log.pause.state;
716
+ const region = tracker.regionOf(state);
717
+ if (region && tracker.activeIn(region) === state)
718
+ log.push({ kind: 'pause', state, region });
719
+ }
720
+ }
721
+ const suspended = suspendEvents(exe.compiled.core.ext.suspends, new Set(tracker.activeStates()), v => {
722
+ const info = exe.slots.get(v);
723
+ const value = info ? s.vals[info.slot] : 0;
724
+ return typeof value === 'number' ? value !== 0 : false;
725
+ }, this.names, flag => suspendSeen.get(flag));
726
+ if (suspended.length) {
727
+ // At the start of the tick (after tick 1's entries): what the reader looks for first.
728
+ let at = 0;
729
+ while (at < log.length && log[at].kind === 'enter')
730
+ at++;
731
+ log.splice(at, 0, ...suspended);
732
+ }
733
+ // After a par-or join fired, nothing inside its threads resumes in the next tick (`!pre(join)`).
734
+ for (const j of parOr)
735
+ for (const i of j.kill)
736
+ paused[i] = 0;
737
+ s.paused = paused;
738
+ s.started = true;
739
+ if (terminatedNow) {
740
+ s.dead = true;
741
+ s.terminated = true;
742
+ log.push({ kind: 'terminate', region: this.chart.id });
743
+ }
744
+ }
745
+ }
746
+ catch (e) {
747
+ if (!(e instanceof SimError))
748
+ throw e;
749
+ error = { severity: 'error', code: e.code, message: e.message, span: e.span, hint: e.hint, tick };
750
+ // The tick did not happen: KIELER's process dies and the previous values stay (B-20).
751
+ s.vals = before;
752
+ s.halted = error;
753
+ tracker.restore(s.tracker);
754
+ tracker.beginTick();
755
+ return this.result(tick, given, log, printed, [], [], false, error, before, ranWith);
756
+ }
757
+ s.tracker = tracker.snapshot();
758
+ return this.result(tick, given, log, printed, taken, actions, terminatedNow, error, undefined, ranWith);
759
+ }
760
+ result(tick, given, log, printed, taken, actions, terminatedNow, error, vals, ranWith) {
761
+ const s = this.state;
762
+ const report = this.exe.report(vals ?? s.vals, this.extra);
763
+ const inputs = {};
764
+ for (const input of this.exe.inputs) {
765
+ const key = input.v.role === 'value' && input.v.of ? input.v.of.name + '_val' : input.name;
766
+ const v = report.pool[key];
767
+ inputs[input.v.role === 'value' && input.v.of ? input.v.of.name : input.name] = v === undefined ? null : v;
768
+ }
769
+ for (const [k, v] of Object.entries(given))
770
+ if (!(k in inputs))
771
+ inputs[k] = v;
772
+ const r = {
773
+ tick,
774
+ inputs,
775
+ ranWith: ranWith ?? this.exe.inputValues(vals ?? s.vals),
776
+ values: report.values,
777
+ present: report.present,
778
+ active: this.tracker.activeStates(),
779
+ entered: [...this.tracker.entered],
780
+ exited: [...this.tracker.exited],
781
+ taken,
782
+ actions,
783
+ terminated: s.terminated,
784
+ terminatedNow,
785
+ log,
786
+ printed,
787
+ pool: report.pool,
788
+ trace: report.trace,
789
+ };
790
+ const copies = copyStates(this.exe.compiled, this.tracker.activeInternal(), this.tracker.enteredInternal);
791
+ if (copies)
792
+ r.copies = copies;
793
+ if (error)
794
+ r.error = error;
795
+ return r;
796
+ }
797
+ /** A par-or join fired: the state's regions stop (abort regions, preemption.md P-62), in source terms. */
798
+ parOrEvents(j, act) {
799
+ if (!j.state)
800
+ return [];
801
+ const out = [];
802
+ const done = j.threads.find(t => t.exit >= 0 && act[t.exit] === 1);
803
+ const name = this.names.name(j.state);
804
+ const region = done?.region ? this.regionNames.get(done.region) : undefined;
805
+ const abort = done?.region ? this.abortRegions.has(done.region) : false;
806
+ const exited = this.tracker.stopRegions(j.state);
807
+ const say = (c) => !done?.region
808
+ ? `The regions of ${c(name)} that are not abort regions all finished. ${c(name)} has abort regions, so it is done: they stop.`
809
+ : abort
810
+ ? `The abort region ${region ? `${c(region)} ` : ''}of ${c(name)} finished, so ${c(name)} is done: its other regions stop.`
811
+ : `${region ? `Region ${c(region)}` : 'A region'} of ${c(name)} finished. ${c(name)} has abort regions, so it is done as soon as any of its regions finishes: the others stop.`;
812
+ out.push({ kind: 'note', related: [j.state, ...(done?.region ? [done.region] : [])], text: say(x => x), markdown: say(x => '`' + x + '`') });
813
+ for (const id of exited)
814
+ out.push({ kind: 'exit', state: id });
815
+ return out;
816
+ }
817
+ /** KIELER's taken-transition counts for a tick (index order of Taken Transition Signaling). */
818
+ takenCounts(result) {
819
+ const order = this.exe.compiled.lowered.takenOrder;
820
+ const counts = order.map(() => 0);
821
+ for (const id of result.taken) {
822
+ const i = order.indexOf(id);
823
+ if (i >= 0)
824
+ counts[i]++;
825
+ }
826
+ return counts;
827
+ }
828
+ get knownTransitions() {
829
+ return this.takenIds;
830
+ }
831
+ }
832
+ /** The Taken Transition Signaling mark of a transition (its first effect, lower.ts). */
833
+ function takeMark(t) {
834
+ const f = t?.effects.find(e => e.k === 'mark' && e.m.kind === 'take');
835
+ return f?.k === 'mark' && f.m.kind === 'take' ? f.m : undefined;
836
+ }
837
+ function lowermost(r) {
838
+ let x = r;
839
+ while (x.sub)
840
+ x = x.sub;
841
+ return x;
842
+ }
843
+ /** A conditional without an else part (`c ? a`) anywhere in the expression. */
844
+ function hasConditionalWithoutElse(e) {
845
+ let found = false;
846
+ walkExpr(e, x => { if (x.k === 'op' && x.op === '?:' && x.args.length === 2)
847
+ found = true; });
848
+ return found;
849
+ }
850
+ function hasValueEmission(log, signal) {
851
+ const last = log[log.length - 1];
852
+ return last?.kind === 'emit' && last.signal === signal;
853
+ }
854
+ function joinFires(j, act) {
855
+ if (j.sync === 'instantaneous')
856
+ return j.first >= 0 && act[j.first] === 1;
857
+ // ParOrSynchronizer: any live thread exit.
858
+ if (j.sync === 'any')
859
+ return j.threads.some(t => t.exit >= 0 && act[t.exit] === 1);
860
+ let anyExit = false;
861
+ for (const t of j.threads) {
862
+ if (t.exit >= 0 && act[t.exit]) {
863
+ anyExit = true;
864
+ continue;
865
+ }
866
+ // Not exiting now: the thread must be empty (no pause reached now / no pause resumed now).
867
+ for (const w of t.watch)
868
+ if (act[w])
869
+ return false;
870
+ }
871
+ return anyExit;
872
+ }
873
+ export { convert };
874
+ //# sourceMappingURL=exec.js.map