@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,550 @@
1
+ // Methods and code effects (structure.md S-43, S-44).
2
+ //
3
+ // KIELER compiles a method into an SCG of its own, and its SCG Methods processor (scg/processors/MethodProcessor
4
+ // .xtend) inlines every call of a *simple* method (fewer than 30 nodes, no loop, no call inside) into the caller's
5
+ // SCG: the body's nodes come before the calling node, parameters are replaced by the arguments, and a body with
6
+ // exactly one `return` gives the call its expression (otherwise a return variable). The inlined reads and writes are
7
+ // then the caller's for the dependency analysis. Other methods stay C functions: their bodies are invisible to the
8
+ // analysis (only the arguments are read), and the simulator interprets them when they are called. Code effects
9
+ // `do { ... }` are methods too (lower.ts makes them `_effect<n>`), so they are inlined like any short method.
10
+ import { compileEffect, SimError } from "../eval.js";
11
+ import { CVar, copyEffect, copyExpr, } from "../model.js";
12
+ import { convert, ctypeOf, defaultValue } from "../values.js";
13
+ import { rewriteEffect, rewriteExpr } from "./rewrite.js";
14
+ /** KIELER's limit for inlining (MethodProcessor.isSimpleMethod: fewer than 30 SCG nodes). */
15
+ const SIMPLE_NODES = 30;
16
+ /** A loop in a method running longer than this is reported (KIELER's C code would hang). */
17
+ const LOOP_LIMIT = 1_000_000;
18
+ const compiling = new WeakMap();
19
+ const methodType = (m) => (m.returnType === 'void' ? 'int' : ctypeOf(m.returnType));
20
+ /** A call of a method: evaluates the arguments, binds the parameters, runs the body, gives the return value. */
21
+ export function compileMethodCall(ec, call, m) {
22
+ const args = call.args.map(a => ec.compile(a));
23
+ const params = m.params.map(p => ({ slot: ec.ctx.info(p).slot, type: ec.ctx.info(p).type }));
24
+ const type = methodType(m);
25
+ let cell = compiling.get(m);
26
+ if (!cell)
27
+ compiling.set(m, (cell = {}));
28
+ const holder = cell;
29
+ const span = call.span;
30
+ const name = call.name;
31
+ return {
32
+ fn: rt => {
33
+ // Compiled on first use, so recursive methods compile.
34
+ if (!holder.body)
35
+ holder.body = compileBlock(ec, m.body, name);
36
+ const values = args.map(a => a.fn(rt));
37
+ params.forEach((p, i) => { rt.vals[p.slot] = convert(values[i] ?? defaultValue(p.type), args[i]?.type === 'f32' ? 'float' : (args[i]?.type ?? p.type), p.type); });
38
+ const flow = holder.body(rt);
39
+ if (m.returnType === 'void')
40
+ return 0;
41
+ if (!flow || !('ret' in flow))
42
+ throw new SimError(`The method ${name} ended without returning a value`, span, 'missing-return', 'In C the result would be undefined. Make every path of the method end with `return`.');
43
+ return flow.ret;
44
+ },
45
+ type,
46
+ };
47
+ }
48
+ /**
49
+ * A statement list of a method KIELER compiles to a C function. KIELER generates that function from the method's
50
+ * graph with structured code, which has no jumps: a `goto` to a label before it leads to code already written out, so
51
+ * the jump is dropped and the rest of the method only runs when it is not taken (the method ends there); a `goto` to a
52
+ * label that ends a nested block goes to the method's end, where KIELER puts such labels (probes
53
+ * kieler/rare/probe-goto-*). A jump forward skips to its label.
54
+ */
55
+ function compileBlock(ec, list, method) {
56
+ const steps = list.map(s => compileStatement(ec, s, method));
57
+ const labels = new Map();
58
+ list.forEach((s, i) => { if (s.k === 'label')
59
+ labels.set(s.name, i); });
60
+ // A label followed only by labels: nothing of this list comes after it.
61
+ const trailing = new Set([...labels].filter(([, i]) => list.slice(i + 1).every(s => s.k === 'label')).map(([l]) => l));
62
+ const END = { end: true };
63
+ return rt => {
64
+ for (let pc = 0; pc < steps.length; pc++) {
65
+ const flow = steps[pc](rt);
66
+ if (!flow)
67
+ continue;
68
+ if ('goto' in flow && labels.has(flow.goto)) {
69
+ const to = labels.get(flow.goto);
70
+ if (to <= pc || trailing.has(flow.goto))
71
+ return END;
72
+ pc = to;
73
+ continue;
74
+ }
75
+ return flow;
76
+ }
77
+ return undefined;
78
+ };
79
+ }
80
+ const truthy = (v) => (typeof v === 'number' ? v !== 0 : v !== null);
81
+ function compileStatement(ec, s, method) {
82
+ switch (s.k) {
83
+ case 'do': {
84
+ const run = compileEffect(s.f, ec);
85
+ return rt => { run(rt, rt.printed ?? []); return undefined; };
86
+ }
87
+ case 'expr': {
88
+ const c = ec.compile(s.e);
89
+ return rt => { c.fn(rt); return undefined; };
90
+ }
91
+ case 'return': {
92
+ const c = s.expr ? ec.compile(s.expr) : undefined;
93
+ return rt => ({ ret: c ? c.fn(rt) : 0 });
94
+ }
95
+ case 'if': {
96
+ const cond = ec.compile(s.cond);
97
+ const then = compileBlock(ec, s.then, method);
98
+ const other = s.else ? compileBlock(ec, s.else, method) : undefined;
99
+ return rt => (truthy(cond.fn(rt)) ? then(rt) : other?.(rt));
100
+ }
101
+ case 'while':
102
+ case 'for': {
103
+ const init = s.k === 'for' ? compileBlock(ec, s.init, method) : undefined;
104
+ const cond = s.cond ? ec.compile(s.cond) : undefined;
105
+ const body = compileBlock(ec, s.body, method);
106
+ const update = s.k === 'for' ? compileBlock(ec, s.update, method) : undefined;
107
+ const span = s.span;
108
+ return rt => {
109
+ init?.(rt);
110
+ for (let n = 0; !cond || truthy(cond.fn(rt)); n++) {
111
+ if (n >= LOOP_LIMIT) {
112
+ throw new SimError(`The loop in ${method} ran more than ${LOOP_LIMIT.toLocaleString('en-NZ')} times in one tick`, span, 'runaway-loop', 'KIELER\'s C code would hang here. Check that the loop condition becomes false.');
113
+ }
114
+ const flow = body(rt);
115
+ if (flow)
116
+ return flow;
117
+ update?.(rt);
118
+ }
119
+ return undefined;
120
+ };
121
+ }
122
+ case 'label': return () => undefined;
123
+ case 'goto': {
124
+ const flow = { goto: s.target, span: s.span };
125
+ return () => flow;
126
+ }
127
+ case 'unsupported': {
128
+ const span = s.span;
129
+ return () => { throw new SimError(`The simulator cannot run ${s.what} in methods`, span, 'unsupported'); };
130
+ }
131
+ }
132
+ }
133
+ // ---------------------------------------------------------------------------------------------------
134
+ // Inlining (KIELER's SCG Methods processor)
135
+ // ---------------------------------------------------------------------------------------------------
136
+ /** A loop anywhere in the statements. */
137
+ function hasLoop(list) {
138
+ return list.some(s => s.k === 'while' || s.k === 'for' || (s.k === 'if' && (hasLoop(s.then) || (!!s.else && hasLoop(s.else)))));
139
+ }
140
+ /** KIELER inlines a method's calls: a simple one, or one marked `@inline` (one with a loop cannot be, see inlineMethods). */
141
+ export function isInlined(m) {
142
+ // inline() copies effects, conditionals, returns, labels and gotos; anything else stays a C call here.
143
+ const basic = (list) => list.every(s => s.k === 'do' || s.k === 'return' || s.k === 'label' || s.k === 'goto' || (s.k === 'if' && basic(s.then) && (!s.else || basic(s.else))));
144
+ return isSimple(m) || (!!m.inline && basic(m.body));
145
+ }
146
+ /**
147
+ * The statements KIELER keeps (SCLExtensions.removeUnreachableCode, applied before the body becomes a graph): after a
148
+ * `goto` or a `return` (KIELER adds `goto _end` after it), everything up to the next label is dropped.
149
+ */
150
+ function reachableStatements(list) {
151
+ const out = [];
152
+ let dead = false;
153
+ for (const s of list) {
154
+ if (s.k === 'label')
155
+ dead = false;
156
+ if (dead)
157
+ continue;
158
+ out.push(s);
159
+ if (s.k === 'goto' || s.k === 'return')
160
+ dead = true;
161
+ }
162
+ return out;
163
+ }
164
+ /**
165
+ * KIELER's isSimpleMethod: the method's SCG has fewer than 30 nodes, no loop and no call. Its nodes are the entry,
166
+ * the exit and one per assignment, `if` and `return`; labels and gotos are control flow only (a backward `goto` is
167
+ * no loop to KIELER: it gets no loop annotation, so the method is inlined and the jump becomes a cycle in the tick,
168
+ * probes kieler/rare/probe-goto-*).
169
+ */
170
+ export function isSimple(m) {
171
+ let nodes = 2;
172
+ let ok = true;
173
+ const expr = (e) => {
174
+ if (!e)
175
+ return;
176
+ const visit = (x) => {
177
+ if (x.k === 'call' || x.k === 'host')
178
+ ok = false;
179
+ else if (x.k === 'op')
180
+ x.args.forEach(visit);
181
+ else if (x.k === 'ref')
182
+ x.idx.forEach(visit);
183
+ else if (x.k === 'vector')
184
+ x.values.forEach(visit);
185
+ };
186
+ visit(e);
187
+ };
188
+ const visit = (list) => {
189
+ for (const s of reachableStatements(list)) {
190
+ switch (s.k) {
191
+ case 'do':
192
+ nodes++;
193
+ if (s.f.k === 'call' || s.f.k === 'host' || s.f.k === 'unsupported')
194
+ ok = false;
195
+ if (s.f.k === 'assign') {
196
+ expr(s.f.expr);
197
+ s.f.ref.idx.forEach(expr);
198
+ }
199
+ if (s.f.k === 'print')
200
+ s.f.args.forEach(expr);
201
+ break;
202
+ case 'if':
203
+ nodes++;
204
+ expr(s.cond);
205
+ visit(s.then);
206
+ if (s.else)
207
+ visit(s.else);
208
+ break;
209
+ case 'return':
210
+ nodes++;
211
+ expr(s.expr);
212
+ break;
213
+ case 'label':
214
+ case 'goto': break;
215
+ case 'expr':
216
+ ok = false;
217
+ break;
218
+ default: ok = false;
219
+ }
220
+ }
221
+ };
222
+ visit(m.body);
223
+ return ok && nodes < SIMPLE_NODES;
224
+ }
225
+ /** The calls of simple methods in a node, innermost last (KIELER handles them in reverse containment order). */
226
+ function callsIn(n) {
227
+ const out = [];
228
+ const visit = (e) => {
229
+ if (!e)
230
+ return;
231
+ if (e.k === 'call') {
232
+ if (!e.extern && e.target?.v.method)
233
+ out.push(e);
234
+ e.args.forEach(visit);
235
+ }
236
+ else if (e.k === 'op')
237
+ e.args.forEach(visit);
238
+ else if (e.k === 'ref')
239
+ e.idx.forEach(visit);
240
+ else if (e.k === 'vector')
241
+ e.values.forEach(visit);
242
+ };
243
+ if (n.kind === 'cond')
244
+ visit(n.expr);
245
+ else if (n.kind === 'assign' && n.effect) {
246
+ const f = n.effect;
247
+ if (f.k === 'call')
248
+ visit(f.call);
249
+ else if (f.k === 'assign') {
250
+ f.ref.idx.forEach(visit);
251
+ visit(f.expr);
252
+ }
253
+ else if (f.k === 'emit')
254
+ visit(f.value);
255
+ else if (f.k === 'print')
256
+ f.args.forEach(visit);
257
+ }
258
+ return out;
259
+ }
260
+ /** Inlines the calls of simple methods into the SCG (after the superfluous fork removal, as KIELER does). */
261
+ export function inlineMethods(scg) {
262
+ const diagnostics = [];
263
+ let counter = 0;
264
+ const work = scg.nodes.filter(n => n.kind === 'assign' || n.kind === 'cond');
265
+ for (const node of work) {
266
+ const calls = callsIn(node).reverse();
267
+ // KIELER keeps one call per method and node (a HashBasedTable cell): it inlines that one, drops the method
268
+ // as inlined, and the other calls of it in the node call a C function that no longer exists.
269
+ const twice = calls.find((c, i) => isInlined(c.target.v.method) && calls.some((d, j) => j !== i && d.target.v === c.target.v));
270
+ if (twice) {
271
+ diagnostics.push({
272
+ severity: 'error', code: 'method-twice', span: twice.span,
273
+ message: `KIELER cannot compile two calls of \`${twice.name}\` in one effect or trigger`,
274
+ kieler: `implicit declaration of function \u2018${twice.name}\u2019 [-Wimplicit-function-declaration]\nCompiler did not return success (exit value != 0)`,
275
+ hint: `KIELER copies a short method into the place it is called, but only once per effect or trigger; the second call is left calling a C function it never generates. Store one result in a variable first (\`t = ${twice.name}(...)\`) and use \`t\` in the second effect.`,
276
+ });
277
+ continue;
278
+ }
279
+ for (const call of calls) {
280
+ const m = call.target.v.method;
281
+ // `@inline` on a method with a loop: KIELER copies the loop into the tick's graph, a cycle it cannot
282
+ // schedule (conformance structure/155).
283
+ if (m.inline && hasLoop(m.body)) {
284
+ diagnostics.push({
285
+ severity: 'error', code: 'inline-loop', span: call.span,
286
+ message: `\`@inline\` makes KIELER copy \`${call.name}\`, loop and all, into the tick, and it cannot schedule a loop there`,
287
+ kieler: 'The SCG is NOT asc-schedulable!',
288
+ hint: `Remove \`@inline\`: without it KIELER runs a method with a loop as a C function, which may loop as long as it likes within the tick.`,
289
+ });
290
+ continue;
291
+ }
292
+ if (!isInlined(m))
293
+ continue;
294
+ const problem = inline(scg, node, call, m, counter++);
295
+ if (problem)
296
+ diagnostics.push(problem);
297
+ }
298
+ }
299
+ scg.nodes.forEach((n, i) => { n.id = i; });
300
+ return diagnostics;
301
+ }
302
+ /** All flows into a node, as setters (KIELER's allPrevious). */
303
+ function incoming(scg, target) {
304
+ const out = [];
305
+ for (const n of scg.nodes) {
306
+ if (n.next === target)
307
+ out.push(to => { n.next = to; });
308
+ if (n.then === target)
309
+ out.push(to => { n.then = to; });
310
+ if (n.else === target)
311
+ out.push(to => { n.else = to; });
312
+ }
313
+ return out;
314
+ }
315
+ function inline(scg, node, call, m, index) {
316
+ const origin = node.effect?.o ?? { by: node.transition?.origin ?? node.transition?.about };
317
+ // Fresh frame variables for this copy (KIELER copies the method's SCG and prefixes its names `_fn<n>_`).
318
+ const frame = new Map();
319
+ m.params.forEach((p, i) => {
320
+ const arg = call.args[i];
321
+ if (arg)
322
+ frame.set(p, arg);
323
+ });
324
+ // A parameter assigned in the body is replaced by its argument (KIELER inlines by substitution): with an argument
325
+ // that is not a variable, KIELER's compiler fails (conformance structure/151).
326
+ const assigned = assignedVars(m.body);
327
+ const literal = m.params.findIndex((p, i) => assigned.has(p) && call.args[i] && call.args[i].k !== 'ref');
328
+ if (literal >= 0) {
329
+ const p = m.params[literal];
330
+ return {
331
+ severity: 'error', code: 'kieler-crash', span: call.args[literal].span ?? call.span,
332
+ message: `KIELER's compiler crashes on this call: \`${call.name}\` assigns its parameter \`${p.name}\`, and the argument is not a variable`,
333
+ kieler: 'The compiler failed during compilation setup.',
334
+ hint: `KIELER copies a short method into the place it is called and replaces \`${p.name}\` by the argument, which cannot be assigned. Give \`${call.name}\` a local variable (\`int v = ${p.name}\`) and change that, or pass a variable.`,
335
+ };
336
+ }
337
+ const locals = new Map();
338
+ for (const v of m.locals) {
339
+ const c = new CVar(`_fn${index}_${call.name}_${v.name}`, v.type);
340
+ c.generated = true;
341
+ c.dims = v.dims.map(d => copyExpr(d));
342
+ c.display = v.name;
343
+ locals.set(v, c);
344
+ }
345
+ const rw = {
346
+ read: r => {
347
+ const local = locals.get(r.v);
348
+ if (local)
349
+ return { ...r, v: local };
350
+ const arg = frame.get(r.v);
351
+ if (!arg)
352
+ return undefined;
353
+ if (arg.k === 'ref')
354
+ return { ...arg, idx: [...arg.idx.map(i => copyExpr(i)), ...r.idx] };
355
+ return copyExpr(arg);
356
+ },
357
+ target: r => {
358
+ const local = locals.get(r.v);
359
+ if (local)
360
+ return { ...r, v: local };
361
+ const arg = frame.get(r.v);
362
+ if (arg?.k === 'ref')
363
+ return { ...arg, idx: [...arg.idx.map(i => copyExpr(i)), ...r.idx] };
364
+ return undefined;
365
+ },
366
+ };
367
+ const returns = countReturns(m.body);
368
+ const returnVar = m.returnType !== 'void' && returns > 1 ? new CVar(`_fn${index}_${call.name}_return`, m.returnType) : undefined;
369
+ if (returnVar)
370
+ returnVar.generated = true;
371
+ let returnExpr;
372
+ const reads = node.kind === 'cond' || !(node.effect?.k === 'call' && node.effect.call === call);
373
+ // KIELER takes the value from the body's return assignments; a method without any (void, or typed but never
374
+ // returning) has none (MethodProcessor: "The method does not return any value!").
375
+ if (reads && (m.returnType === 'void' || returns === 0)) {
376
+ return m.returnType === 'void'
377
+ ? { severity: 'error', code: 'method-without-value', span: call.span, message: `\`${call.name}()\` returns no value, so it cannot be used in an expression`, kieler: 'The method does not return any value!', hint: `Give \`${call.name}\` a return type and a \`return\` statement, or call it as an effect on its own.` }
378
+ : { severity: 'error', code: 'method-without-return', span: call.span, message: `\`${call.name}()\` is declared to return a value but has no return statement`, kieler: 'The method does not return any value!', hint: `End the body of \`${call.name}\` with \`return\` and the value it should give.` };
379
+ }
380
+ const made = [];
381
+ const info = { name: call.name };
382
+ const mk = (kind, extra) => {
383
+ const n = { id: scg.nodes.length + made.length, kind, thread: node.thread, state: node.state, transition: node.transition, method: info, ...extra };
384
+ n.gen = (scg.nodes.length + made.length) * 1000;
385
+ made.push(n);
386
+ return n;
387
+ };
388
+ const effect = (f, span) => ({ ...rewriteEffect(copyEffect(f), rw), o: { ...origin, span: span ?? f.o.span, hidden: origin.hidden } });
389
+ const labelNode = new Map();
390
+ const gotos = [];
391
+ const returned = [];
392
+ const toExit = [];
393
+ const build = (list, incoming) => {
394
+ let cf = incoming;
395
+ let labels = [];
396
+ const place = (n) => {
397
+ for (const e of cf)
398
+ e(n);
399
+ for (const l of labels)
400
+ labelNode.set(l, n);
401
+ labels = [];
402
+ };
403
+ for (const s of reachableStatements(list)) {
404
+ if (s.k === 'label') {
405
+ labels.push(s.name);
406
+ continue;
407
+ }
408
+ if (s.k === 'do') {
409
+ const n = mk('assign', { effect: effect(s.f) });
410
+ place(n);
411
+ cf = [to => { n.next = to; }];
412
+ }
413
+ else if (s.k === 'if') {
414
+ const n = mk('cond', { expr: rewriteExpr(copyExpr(s.cond), rw) });
415
+ place(n);
416
+ cf = [...build(s.then, [to => { n.then = to; }]), ...build(s.else ?? [], [to => { n.else = to; }])];
417
+ }
418
+ else if (s.k === 'goto') {
419
+ gotos.push({ label: s.target, ends: cf, span: s.span, at: made.length });
420
+ cf = [];
421
+ }
422
+ else if (s.k === 'return') {
423
+ const value = s.expr ? rewriteExpr(copyExpr(s.expr), rw) : undefined;
424
+ if (returnVar && value) {
425
+ const n = mk('assign', { effect: { k: 'assign', ref: { k: 'ref', v: returnVar, idx: [] }, op: '=', expr: value, o: { ...origin, hidden: true, span: s.span } } });
426
+ place(n);
427
+ returned.push(to => { n.next = to; });
428
+ }
429
+ else {
430
+ returnExpr = value;
431
+ returned.push(...cf);
432
+ toExit.push(...labels);
433
+ labels = [];
434
+ }
435
+ cf = [];
436
+ }
437
+ }
438
+ // Labels at the end of a list: the next node of this list does not exist (KIELER's unmappedLabels).
439
+ if (labels.length)
440
+ toExit.push(...labels);
441
+ return cf;
442
+ };
443
+ const preds = incoming(scg, node);
444
+ let first;
445
+ let entered = false;
446
+ const entry = to => { entered = true; first = to; for (const p of preds)
447
+ p(to); };
448
+ const ends = build(m.body, [entry]);
449
+ // Where the body goes on: back to the calling node (or past it when the call is the whole effect).
450
+ const after = reads ? node : node.next;
451
+ for (const e of [...ends, ...returned])
452
+ e(after);
453
+ for (const g of gotos) {
454
+ const target = toExit.includes(g.label) ? undefined : labelNode.get(g.label);
455
+ // A label before the goto: control goes round within the tick.
456
+ if (target && made.indexOf(target) < g.at) {
457
+ const from = made[g.at - 1];
458
+ for (const n of made)
459
+ if (n === from || n === target)
460
+ n.method = { name: call.name, jumpsBack: { label: g.label, span: g.span } };
461
+ }
462
+ for (const e of g.ends)
463
+ e(target ?? after);
464
+ }
465
+ if (!entered)
466
+ first = after;
467
+ if (reads) {
468
+ const replacement = returnVar ? { k: 'ref', v: returnVar, idx: [], span: call.span } : returnExpr ? { ...returnExpr, span: call.span } : { k: 'lit', t: 'int', v: 0 };
469
+ replaceCall(node, call, replacement);
470
+ }
471
+ else {
472
+ // The call node goes.
473
+ const i = scg.nodes.indexOf(node);
474
+ if (i >= 0)
475
+ scg.nodes.splice(i, 1);
476
+ const instead = first ?? after;
477
+ for (const [st, n] of scg.stateNodes)
478
+ if (n === node && instead)
479
+ scg.stateNodes.set(st, instead);
480
+ }
481
+ for (const n of made)
482
+ n.seq = { next: scg.seq++, then: n.kind === 'cond' ? scg.seq++ : undefined, else: n.kind === 'cond' ? scg.seq++ : undefined };
483
+ scg.nodes.push(...made);
484
+ return undefined;
485
+ }
486
+ function countReturns(list) {
487
+ let n = 0;
488
+ for (const s of list) {
489
+ if (s.k === 'return')
490
+ n++;
491
+ else if (s.k === 'if')
492
+ n += countReturns(s.then) + countReturns(s.else ?? []);
493
+ else if (s.k === 'while' || s.k === 'for')
494
+ n += countReturns(s.body);
495
+ }
496
+ return n;
497
+ }
498
+ /** Replaces the call expression (by identity) in the node's condition or effect. */
499
+ function replaceCall(node, call, replacement) {
500
+ if (node.kind === 'cond' && node.expr)
501
+ node.expr = rewriteExprIdentity(node.expr, call, replacement);
502
+ else if (node.effect)
503
+ node.effect = rewriteEffectIdentity(node.effect, call, replacement);
504
+ }
505
+ function rewriteExprIdentity(e, target, replacement) {
506
+ if (e === target)
507
+ return replacement;
508
+ switch (e.k) {
509
+ case 'op': return { ...e, args: e.args.map(a => rewriteExprIdentity(a, target, replacement)) };
510
+ case 'ref': return { ...e, idx: e.idx.map(a => rewriteExprIdentity(a, target, replacement)) };
511
+ case 'vector': return { ...e, values: e.values.map(a => rewriteExprIdentity(a, target, replacement)) };
512
+ case 'call': return { ...e, args: e.args.map(a => rewriteExprIdentity(a, target, replacement)) };
513
+ default: return e;
514
+ }
515
+ }
516
+ function rewriteEffectIdentity(f, target, replacement) {
517
+ const m = (e) => rewriteExprIdentity(e, target, replacement);
518
+ switch (f.k) {
519
+ case 'assign': return { ...f, ref: { ...f.ref, idx: f.ref.idx.map(m) }, expr: f.expr ? m(f.expr) : undefined };
520
+ case 'emit': return { ...f, value: f.value ? m(f.value) : undefined };
521
+ case 'print': return { ...f, args: f.args.map(m) };
522
+ case 'call': return { ...f, call: m(f.call) };
523
+ default: return f;
524
+ }
525
+ }
526
+ /** The variables a statement list assigns (at any depth). */
527
+ function assignedVars(list) {
528
+ const out = new Set();
529
+ const visit = (stmts) => {
530
+ for (const st of stmts) {
531
+ if (st.k === 'do' && st.f.k === 'assign')
532
+ out.add(st.f.ref.v);
533
+ else if (st.k === 'if') {
534
+ visit(st.then);
535
+ if (st.else)
536
+ visit(st.else);
537
+ }
538
+ else if (st.k === 'while')
539
+ visit(st.body);
540
+ else if (st.k === 'for') {
541
+ visit(st.init);
542
+ visit(st.update);
543
+ visit(st.body);
544
+ }
545
+ }
546
+ };
547
+ visit(list);
548
+ return out;
549
+ }
550
+ //# sourceMappingURL=methods.js.map