@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
package/dist/format.js ADDED
@@ -0,0 +1,872 @@
1
+ // Pretty-printing of expressions, effects, triggers, declarations, actions and transition labels, exactly as
2
+ // KIELER shows them in its diagrams.
3
+ //
4
+ // This mirrors KIELER's "human readable" serialisers:
5
+ // kexpressions/.../KExpressionsSerializeExtensions.xtend (plain `serialize`)
6
+ // kexpressions/.../KExpressionsSerializeHRExtensions.xtend (`serializeHR`: only necessary parentheses)
7
+ // kexpressions/.../keffects/.../KEffectsSerialize(HR)Extensions.xtend
8
+ // sccharts/.../extensions/SCChartsSerializeHRExtensions.xtend (declarations, actions, regions, states)
9
+ // sccharts.ui/.../synthesis/labels/TransitionLabelSerializer.xtend (transition labels)
10
+ // sccharts.ui/.../synthesis/styles/StateStyles.xtend#addKeywordLabel (how highlighted parts are merged)
11
+ // including their quirks, so that a diagram here reads the same as in KIELER. The quirks are noted where
12
+ // they occur (for example a valued emission prints its value with the plain serialiser: `V((x + 1))`).
13
+ /** Builds a context for all charts of a program: declaration lookup and the pragma symbol table. */
14
+ export function createFormatContext(program) {
15
+ const map = new Map();
16
+ const addDecls = (decls) => {
17
+ for (const declaration of decls)
18
+ for (const valuedObject of declaration.valuedObjects)
19
+ map.set(valuedObject.id, { declaration, valuedObject });
20
+ };
21
+ const visitState = (state) => {
22
+ addDecls(state.declarations);
23
+ for (const region of state.regions) {
24
+ addDecls(region.declarations);
25
+ for (const child of region.states)
26
+ visitState(child);
27
+ }
28
+ };
29
+ for (const chart of program.charts)
30
+ visitState(chart);
31
+ return { lookup: id => map.get(id), symbols: symbolTableFromPragmas(program.pragmas ?? []) };
32
+ }
33
+ const GREEK_UPPER = ['Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta', 'Iota', 'Kappa', 'Lambda', 'Mu', 'Nu',
34
+ 'Xi', 'Omicron', 'Pi', 'Rho', '', 'Sigma', 'Tau', 'Upsilon', 'Phi', 'Chi', 'Psi', 'Omega'];
35
+ const SUBSCRIPTS = {
36
+ 0: '₀', 1: '₁', 2: '₂', 3: '₃', 4: '₄', 5: '₅', 6: '₆', 7: '₇', 8: '₈', 9: '₉', a: 'ₐ', e: 'ₑ', h: 'ₕ', i: 'ᵢ', j: 'ⱼ',
37
+ k: 'ₖ', l: 'ₗ', m: 'ₘ', n: 'ₙ', o: 'ₒ', p: 'ₚ', r: 'ᵣ', s: 'ₛ', t: 'ₜ', u: 'ᵤ', v: 'ᵥ', x: 'ₓ',
38
+ };
39
+ function symbolTableFromPragmas(pragmas) {
40
+ const table = { prefixes: new Map(), suffixes: new Map() };
41
+ for (const pragma of pragmas) {
42
+ const [kind, arg] = pragma.values;
43
+ if (pragma.name === 'symbols') {
44
+ const prefix = arg ?? '';
45
+ if (kind === 'greek') {
46
+ table.prefixes.set(prefix + 'Heta', 'Ͱ');
47
+ table.prefixes.set(prefix + 'heta', 'ͱ');
48
+ table.prefixes.set(prefix + 'Yot', 'Ϳ');
49
+ GREEK_UPPER.forEach((name, i) => {
50
+ if (!name)
51
+ return;
52
+ table.prefixes.set(prefix + name, String.fromCodePoint(0x391 + i));
53
+ table.prefixes.set(prefix + name.toLowerCase(), String.fromCodePoint(0x3b1 + i));
54
+ });
55
+ table.prefixes.set(prefix + 'finalsigma', 'ς');
56
+ }
57
+ else if (kind === 'subscript') {
58
+ table.suffixes.set(prefix, s => [...s].map(c => SUBSCRIPTS[c] ?? c).join(''));
59
+ }
60
+ // "math script", "math fraktur" and "math doublestruck" are not supported here.
61
+ }
62
+ else if (pragma.name === 'symbol' && pragma.values.length >= 2) {
63
+ table.prefixes.set(pragma.values[0], pragma.values[1]);
64
+ }
65
+ }
66
+ return table.prefixes.size || table.suffixes.size ? table : undefined;
67
+ }
68
+ /** KIELER's `applySymbolTable`: strips Xtext's `^` keyword escape and applies pragma symbols. */
69
+ export function displayName(name, ctx) {
70
+ let n = name.startsWith('^') ? name.slice(1) : name;
71
+ const table = ctx?.symbols;
72
+ if (!table)
73
+ return n;
74
+ for (const [prefix, symbol] of table.prefixes)
75
+ if (n.startsWith(prefix))
76
+ return symbol + n.slice(prefix.length);
77
+ for (const [sep, process] of table.suffixes) {
78
+ const pos = n.indexOf(sep);
79
+ if (pos >= 0)
80
+ return n.slice(0, pos) + process(n.slice(pos + 1));
81
+ }
82
+ return n;
83
+ }
84
+ // ---------------------------------------------------------------------------------------------------
85
+ // Literals
86
+ // ---------------------------------------------------------------------------------------------------
87
+ /** Java's `Double.toString` (KIELER stores float literals as doubles): `1.0`, `0.5`, `1.0E7`, `1.0E-4`. */
88
+ export function formatFloat(value) {
89
+ if (Number.isNaN(value))
90
+ return 'NaN';
91
+ if (!Number.isFinite(value))
92
+ return value > 0 ? 'Infinity' : '-Infinity';
93
+ if (value === 0)
94
+ return Object.is(value, -0) ? '-0.0' : '0.0';
95
+ const abs = Math.abs(value);
96
+ const sign = value < 0 ? '-' : '';
97
+ // Shortest round-tripping digits, as Java (JDK 19+) also produces.
98
+ const [mantissa, expPart] = abs.toExponential().split('e');
99
+ const digits = mantissa.replace('.', '');
100
+ const exp = Number(expPart);
101
+ if (abs >= 1e-3 && abs < 1e7) {
102
+ let s;
103
+ if (exp >= 0) {
104
+ const intLen = exp + 1;
105
+ const intPart = digits.slice(0, intLen).padEnd(intLen, '0');
106
+ const frac = digits.slice(intLen);
107
+ s = `${intPart}.${frac || '0'}`;
108
+ }
109
+ else {
110
+ s = `0.${'0'.repeat(-exp - 1)}${digits}`;
111
+ }
112
+ return sign + s;
113
+ }
114
+ const frac = digits.slice(1);
115
+ return `${sign}${digits[0]}.${frac || '0'}E${exp}`;
116
+ }
117
+ /** KIELER's operator identity: unary minus is SUB with one operand. */
118
+ function kOp(e) {
119
+ return e.op === 'neg' ? '-' : e.op;
120
+ }
121
+ /** KExpressionsSerializeHRExtensions.precedence */
122
+ function precedence(op) {
123
+ switch (op) {
124
+ case '!':
125
+ case '~': return 2;
126
+ case '*':
127
+ case '/':
128
+ case '%': return 3;
129
+ case '+':
130
+ case '-':
131
+ case 'neg': return 4;
132
+ case '<<':
133
+ case '>>':
134
+ case '>>>': return 5;
135
+ case '<':
136
+ case '<=':
137
+ case '>':
138
+ case '>=': return 6;
139
+ case '==':
140
+ case '!=': return 7;
141
+ case '&': return 8;
142
+ case '^': return 9;
143
+ case '|': return 10;
144
+ case '&&': return 11;
145
+ case '||': return 12;
146
+ case '?:': return 13;
147
+ default: return 99; // pre, val, ->, fby, sfby
148
+ }
149
+ }
150
+ const ALWAYS_OMIT_PARENTHESIS = new Set(['||', '&&', '!', '+', '-', '*', '&', '|', '^', '~']);
151
+ /** KExpressionsSerializeHRExtensions.requiresParenthesis */
152
+ function requiresParenthesis(e, parent, position) {
153
+ const mine = precedence(kOp(e));
154
+ const theirs = precedence(kOp(parent));
155
+ if (mine > theirs)
156
+ return true;
157
+ if (mine === theirs) {
158
+ if (position === 0 && !(parent.args.length === 1 && kOp(parent) === '-'))
159
+ return false;
160
+ if (kOp(e) === kOp(parent) && ALWAYS_OMIT_PARENTHESIS.has(kOp(e)))
161
+ return false;
162
+ return true;
163
+ }
164
+ return false;
165
+ }
166
+ const BINARY_SEPARATORS = {
167
+ '==': ' == ', '<': ' < ', '<=': ' <= ', '>': ' > ', '>=': ' >= ', '!=': ' != ', '&&': ' && ', '||': ' || ',
168
+ '&': ' & ', '|': ' | ', '^': ' ^ ', '<<': ' << ', '>>': ' >> ', '>>>': ' >>> ', '+': ' + ', '-': ' - ',
169
+ '*': ' * ', '/': ' / ', '%': ' % ', '->': ' -> ', 'fby': ' fby ', 'sfby': ' sfby ',
170
+ };
171
+ function formatReference(ref, ctx, hr) {
172
+ // SCChartsSerializeHRExtensions.serializeVOR (HR) / KExpressionsSerializeExtensions (plain)
173
+ let s = hr ? displayName(ref.name, ctx) : ref.name;
174
+ for (const index of ref.indices)
175
+ s += `[${hr ? formatExpression(index, ctx) : formatExpressionPlain(index, ctx)}]`;
176
+ const label = ref.decl ? ctx?.lookup?.(ref.decl)?.valuedObject.label : undefined;
177
+ if (label != null)
178
+ s = label;
179
+ if (ref.sub)
180
+ s += '.' + formatReference(ref.sub, ctx, hr);
181
+ return s;
182
+ }
183
+ /** `serializeHRParameters`: `(a, &b, !&c)`. */
184
+ function formatArgs(args, ctx, hr, access) {
185
+ return '(' + args.map((a, i) => (access?.[i] ?? '') + (hr ? formatExpression(a, ctx) : formatExpressionPlain(a, ctx))).join(', ') + ')';
186
+ }
187
+ /** A reference call `f(x)` / `obj.f(x)` / `super.f(x)`, or a function call `extern f(x)`. */
188
+ function formatCall(c, ctx, hr) {
189
+ if (c.extern)
190
+ return 'extern ' + c.name + formatArgs(c.args, ctx, hr, c.paramAccess);
191
+ const callee = c.target ? formatReference(c.target, ctx, hr) : hr ? displayName(c.name, ctx) : c.name;
192
+ return (c.super ? 'super.' : '') + callee + formatArgs(c.args, ctx, hr, c.paramAccess);
193
+ }
194
+ function formatAtom(e, ctx, hr) {
195
+ switch (e.kind) {
196
+ case 'bool': return e.value ? 'true' : 'false';
197
+ case 'int': return Number.isInteger(e.value) ? String(e.value) : formatFloat(e.value);
198
+ case 'float': return formatFloat(e.value);
199
+ case 'string': return `"${e.value}"`;
200
+ case 'ref': return formatReference(e, ctx, hr);
201
+ case 'call': return formatCall(e, ctx, hr);
202
+ case 'random': return 'random';
203
+ case 'randomize': return 'randomize';
204
+ // SCCharts' serializeHR(TextExpression) shows host code without the backticks.
205
+ case 'hostcode': return hr ? e.text : '`' + e.text + '`';
206
+ case 'vector': {
207
+ const item = (v) => (hr ? formatExpression(v, ctx) : formatExpressionPlain(v, ctx));
208
+ if (e.range)
209
+ return `{${e.values[0] ? item(e.values[0]) : ''} to ${e.values.length ? item(e.values[e.values.length - 1]) : ''}}`;
210
+ return e.values.length ? '{' + e.values.map(item).join(', ') + '}' : '{}';
211
+ }
212
+ case 'ignore': return '_';
213
+ case 'null': return 'null';
214
+ case 'this': return 'this';
215
+ case 'special': {
216
+ if (e.target === undefined)
217
+ return e.text;
218
+ const sub = e.sub ? '.' + formatReference(e.sub, ctx, hr) : '';
219
+ // SCCharts prints a static access (`scchart(Target).member`) as `Target.member`, the others as
220
+ // `access(Container.Target).member`.
221
+ if (e.access === 'static' || e.access === 'scchart')
222
+ return e.target + sub;
223
+ return `${e.access}(${e.container ? e.container + '.' : ''}${e.target})${sub}`;
224
+ }
225
+ }
226
+ }
227
+ /** The operator expression without its own parentheses (`serializeHROperatorExpression`). */
228
+ function formatOpInner(e, ctx, hr) {
229
+ const sub = (child, index) => (hr ? formatHR(child, ctx, e, index) : formatExpressionPlain(child, ctx));
230
+ const op = kOp(e);
231
+ switch (op) {
232
+ case '!': return '!' + sub(e.args[0], 0);
233
+ case '~': return '~' + sub(e.args[0], 0);
234
+ case 'pre': return `pre(${sub(e.args[0], 0)})`;
235
+ case 'val': return `val(${sub(e.args[0], 0)})`;
236
+ case '-':
237
+ if (e.args.length === 1)
238
+ return '-' + sub(e.args[0], 0);
239
+ break;
240
+ case '?:':
241
+ return sub(e.args[0], 0) + ' ? ' + sub(e.args[1], 1) + (e.args.length > 2 ? ' : ' + sub(e.args[2], 2) : '');
242
+ case '<<':
243
+ case '>>':
244
+ case '>>>':
245
+ // KIELER's HR serialiser combines shift operands with the plain serialiser.
246
+ return e.args.map(a => formatExpressionPlain(a, ctx)).join(BINARY_SEPARATORS[op]);
247
+ case 'fby':
248
+ case 'sfby':
249
+ // The plain serialiser does not know these operators and prints nothing.
250
+ if (!hr)
251
+ return '';
252
+ break;
253
+ }
254
+ return e.args.map((a, i) => sub(a, i)).join(BINARY_SEPARATORS[op] ?? ` ${op} `);
255
+ }
256
+ function formatHR(e, ctx, parent, position = 0) {
257
+ if (e.kind !== 'op')
258
+ return formatAtom(e, ctx, true);
259
+ const result = formatOpInner(e, ctx, true);
260
+ const op = kOp(e);
261
+ if (op === '!' || op === 'val' || op === 'pre')
262
+ return result;
263
+ if (parent && requiresParenthesis(e, parent, position))
264
+ return `(${result})`;
265
+ return result;
266
+ }
267
+ /** An expression as KIELER's diagrams show it (`serializeHR`): parentheses only where precedence needs them. */
268
+ export function formatExpression(e, ctx) {
269
+ return formatHR(e, ctx);
270
+ }
271
+ /** KIELER's plain `serialize`: every operator expression except `!`, `~`, `pre` and `val` in parentheses.
272
+ * The diagram uses it for the value of a valued emission. */
273
+ export function formatExpressionPlain(e, ctx) {
274
+ if (e.kind !== 'op')
275
+ return formatAtom(e, ctx, false);
276
+ const result = formatOpInner(e, ctx, false);
277
+ const op = kOp(e);
278
+ if (op === '!' || op === '~' || op === 'val' || op === 'pre')
279
+ return result;
280
+ return `(${result})`;
281
+ }
282
+ /**
283
+ * The expression with every operation that is an operand of another one in parentheses, so the grouping KIELER's
284
+ * parser chose is visible: `a + b * c` is `a + (b * c)`, `!a && b` is `(!a) && b`, `a > 0 ? 1 : 2` is
285
+ * `a > (0 ? 1 : 2)`. The whole expression, array indices, arguments and vector members get no extra parentheses,
286
+ * `pre(x)` and `val(S)` none either (they look like calls already). Names print as written (no labels, no
287
+ * symbol tables): pass the result of `parseExpression`.
288
+ */
289
+ export function formatExpressionParenthesised(e, options = {}) {
290
+ return parenthesised(e, options, true);
291
+ }
292
+ /** An effect with its expressions printed by `formatExpressionParenthesised`: `x = a + (b * c)`, `S(a + (b * c))`. */
293
+ export function formatEffectParenthesised(effect, options = {}) {
294
+ const top = (x) => parenthesised(x, options, true);
295
+ const target = (r) => parenthesisedReference(r, options);
296
+ switch (effect.kind) {
297
+ case 'assign': return `${target(effect.target)} ${effect.operator} ${top(effect.expression)}`;
298
+ case 'postfix': return target(effect.target) + effect.operator;
299
+ case 'emit': return effect.value ? `${target(effect.target)}(${top(effect.value)})` : target(effect.target);
300
+ case 'call': return parenthesisedCall(effect, options);
301
+ case 'print': return `print(${effect.args.map(top).join(', ')})`;
302
+ default: return formatEffect(effect);
303
+ }
304
+ }
305
+ function parenthesisedReference(ref, options) {
306
+ let s = ref.name;
307
+ for (const index of ref.indices)
308
+ s += `[${parenthesised(index, options, true)}]`;
309
+ if (ref.sub)
310
+ s += '.' + parenthesisedReference(ref.sub, options);
311
+ return s;
312
+ }
313
+ function parenthesisedCall(c, options) {
314
+ const args = '(' + c.args.map((a, i) => (c.paramAccess?.[i] ?? '') + parenthesised(a, options, true)).join(', ') + ')';
315
+ if (c.extern)
316
+ return 'extern ' + c.name + args;
317
+ return (c.super ? 'super.' : '') + (c.target ? parenthesisedReference(c.target, options) : c.name) + args;
318
+ }
319
+ function parenthesised(e, options, top) {
320
+ const sub = (x) => parenthesised(x, options, false);
321
+ switch (e.kind) {
322
+ case 'ref': return parenthesisedReference(e, options);
323
+ case 'call': return parenthesisedCall(e, options);
324
+ case 'vector':
325
+ if (e.range)
326
+ return formatAtom(e, undefined, true);
327
+ return '{' + e.values.map(v => parenthesised(v, options, true)).join(', ') + '}';
328
+ case 'op': break;
329
+ default: return formatAtom(e, undefined, true);
330
+ }
331
+ const op = kOp(e);
332
+ let inner;
333
+ switch (op) {
334
+ case 'pre':
335
+ case 'val': return `${op}(${e.args.map(a => parenthesised(a, options, true)).join(', ')})`;
336
+ case '!':
337
+ case '~':
338
+ inner = op + sub(e.args[0]);
339
+ break;
340
+ case '-':
341
+ if (e.args.length === 1) {
342
+ inner = '-' + sub(e.args[0]);
343
+ break;
344
+ }
345
+ inner = binary();
346
+ break;
347
+ case '?:':
348
+ inner = sub(e.args[0]) + ' ? ' + sub(e.args[1]) + (e.args.length > 2 ? ' : ' + sub(e.args[2]) : '');
349
+ break;
350
+ default:
351
+ inner = binary();
352
+ }
353
+ return top ? inner : `(${inner})`;
354
+ function binary() {
355
+ const separator = BINARY_SEPARATORS[op] ?? ` ${op} `;
356
+ if (options.nary !== 'left' || e.kind !== 'op')
357
+ return e.args.map(sub).join(separator);
358
+ const [first, ...rest] = e.args;
359
+ return rest.reduce((acc, arg, i) => (i === 0 ? acc : `(${acc})`) + separator + sub(arg), sub(first));
360
+ }
361
+ }
362
+ // ---------------------------------------------------------------------------------------------------
363
+ // Effects
364
+ // ---------------------------------------------------------------------------------------------------
365
+ /** An effect as KIELER's diagrams show it: `x = a + 1`, `x++`, `S`, `V((x + 1))`, `print(x)`. */
366
+ export function formatEffect(effect, ctx) {
367
+ switch (effect.kind) {
368
+ case 'assign':
369
+ return `${formatReference(effect.target, ctx, true)} ${effect.operator} ${formatExpression(effect.expression, ctx)}`;
370
+ case 'postfix':
371
+ return formatReference(effect.target, ctx, true) + effect.operator;
372
+ case 'emit': {
373
+ const name = formatReference(effect.target, ctx, true);
374
+ if (!effect.value)
375
+ return name;
376
+ // KIELER prints the value only for a valued signal, and with the plain serialiser.
377
+ const decl = effect.target.decl ? ctx?.lookup?.(effect.target.decl)?.declaration : undefined;
378
+ if (decl && (decl.type === undefined || decl.type === 'pure'))
379
+ return name;
380
+ return `${name}(${formatExpressionPlain(effect.value, ctx)})`;
381
+ }
382
+ case 'call':
383
+ return formatCall(effect, ctx, true);
384
+ case 'print':
385
+ return `print(${effect.args.map(a => formatExpression(a, ctx)).join(', ')})`;
386
+ case 'randomize':
387
+ return 'randomize';
388
+ case 'hostcode':
389
+ return effect.text;
390
+ case 'code':
391
+ return effect.statements ? formatScl(effect.declarations ?? [], effect.statements, ctx) : effect.text;
392
+ }
393
+ }
394
+ /**
395
+ * An SCL code block (`do { ... }`) as KIELER prints it (SCLSerializeExtensions): `{` declarations joined by
396
+ * `; `, then the statements joined by spaces, `}`, each statement ending in `;`. Loops print as their body
397
+ * (`for` and `while` become `{...}`), conditionals as `if (c) {...} else {...}`.
398
+ */
399
+ export function formatScl(declarations, statements, ctx) {
400
+ return '{' + declarations.map(d => sclDeclaration(d, ctx)).join('; ') + statements.map(s => sclStatement(s, ctx)).join(' ') + '}';
401
+ }
402
+ function sclDeclaration(d, ctx) {
403
+ const parts = [];
404
+ if (d.access)
405
+ parts.push(d.access);
406
+ if (d.extern)
407
+ parts.push('extern');
408
+ if (d.global)
409
+ parts.push('global');
410
+ if (d.static)
411
+ parts.push('static');
412
+ if (d.const)
413
+ parts.push('const');
414
+ if (d.input)
415
+ parts.push('input');
416
+ if (d.output)
417
+ parts.push('output');
418
+ if (d.signal)
419
+ parts.push('signal');
420
+ if (d.type === 'host')
421
+ parts.push(d.hostType ?? 'host');
422
+ else if (d.type && d.type !== 'pure')
423
+ parts.push(d.type === 'clock-time' ? 'time' : d.type);
424
+ d.valuedObjects.forEach((vo, i) => {
425
+ parts.push(vo.label ?? vo.name + vo.cardinalities.map(c => `[${formatExpressionPlain(c, ctx)}]`).join(''));
426
+ if (vo.initialValue)
427
+ parts.push('=', formatExpressionPlain(vo.initialValue, ctx));
428
+ if (i < d.valuedObjects.length - 1)
429
+ parts.push(',');
430
+ });
431
+ return parts.join(' ');
432
+ }
433
+ function sclStatement(st, ctx) {
434
+ switch (st.kind) {
435
+ case 'assign': return `${formatReference(st.target, ctx, true)} ${st.operator} ${formatExpression(st.expression, ctx)};`;
436
+ case 'postfix': return `${formatReference(st.target, ctx, true)}${st.operator};`;
437
+ case 'label': return `${st.name}:`;
438
+ case 'goto': return `goto ${st.target};`;
439
+ case 'return': return `return ${formatExpression(st.expression, ctx)};`;
440
+ case 'block':
441
+ case 'while':
442
+ case 'for': return formatScl(st.declarations, st.statements, ctx);
443
+ case 'if': return `if (${formatExpression(st.condition, ctx)}) {` + st.declarations.map(d => sclDeclaration(d, ctx)).join('; ')
444
+ + st.statements.map(s => sclStatement(s, ctx)).join(' ') + '}' + (st.else ? ' else ' + formatScl(st.else.declarations, st.else.statements, ctx) : '');
445
+ case 'print': return `print ${st.args.map(a => formatExpressionPlain(a, ctx)).join(', ')};`;
446
+ case 'call': return `${formatCall(st, ctx, true)};`;
447
+ case 'randomize': return 'randomize;';
448
+ case 'hostcode': return '`' + st.text + '`;';
449
+ case 'expression': return `${formatExpression(st.expression, ctx)};`;
450
+ }
451
+ }
452
+ /** Effects joined with `; `. */
453
+ export function formatEffects(effects, ctx) {
454
+ return effects.map(e => formatEffect(e, ctx)).join('; ');
455
+ }
456
+ // ---------------------------------------------------------------------------------------------------
457
+ // Transitions
458
+ // ---------------------------------------------------------------------------------------------------
459
+ /** The trigger with its count delay: `3 A`. Empty when there is no trigger. */
460
+ export function formatTrigger(t, ctx) {
461
+ if (!t.trigger)
462
+ return '';
463
+ return (t.triggerDelay !== undefined && t.triggerDelay > 1 ? `${t.triggerDelay} ` : '') + formatExpression(t.trigger, ctx);
464
+ }
465
+ /** `serializeHR(Transition)`: trigger and effects, without priority (`3 A / x = 1; S`). */
466
+ export function formatTransition(t, ctx) {
467
+ let s = formatTrigger(t, ctx);
468
+ if (t.effects.length)
469
+ s += ' / ' + formatEffects(t.effects, ctx);
470
+ return s;
471
+ }
472
+ /**
473
+ * The lines of a transition label, as KIELER's TransitionLabelSerializer.serializeMultilineLabel builds them:
474
+ * `["1: A && B", "/ O = true;", " x++"]`. The priority is shown only when the source state has more than one
475
+ * outgoing transition; the trigger goes on the first line and each effect on its own line, indented under the
476
+ * first. `outgoing` is the number of outgoing transitions of the source state.
477
+ */
478
+ export function transitionLabelLines(t, outgoing, options = {}) {
479
+ const userLabels = options.userLabels ?? true;
480
+ if (userLabels && t.label)
481
+ return [t.label];
482
+ const parts = [];
483
+ let part = '';
484
+ let effectPrefix = '';
485
+ if (outgoing > 1)
486
+ part += `${t.priority}: `;
487
+ if (t.probability !== undefined && t.probability > 0)
488
+ part += `Pr=${formatFloat(t.probability)}: `;
489
+ if (t.trigger) {
490
+ if (t.triggerDelay !== undefined && t.triggerDelay > 1)
491
+ part += `${t.triggerDelay} `;
492
+ part += formatExpression(t.trigger, options);
493
+ parts.push(part);
494
+ }
495
+ else {
496
+ effectPrefix = part;
497
+ }
498
+ if (parts.length === 0 && t.effects.length === 0) {
499
+ parts.push(effectPrefix);
500
+ }
501
+ else {
502
+ effectPrefix += '/ ';
503
+ t.effects.forEach((effect, i) => {
504
+ parts.push(effectPrefix + formatEffect(effect, options) + (i < t.effects.length - 1 ? ';' : ''));
505
+ effectPrefix = ' '.repeat(effectPrefix.length);
506
+ });
507
+ }
508
+ return parts;
509
+ }
510
+ /** The transition label on one line (`TransitionLabelSerializer.serializeLabel`): `1: A && B / O = true; x++`.
511
+ * Empty when KIELER shows no label. */
512
+ export function transitionLabel(t, outgoing, options = {}) {
513
+ return transitionLabelLines(t, outgoing, options).map(s => s.trim()).join(' ');
514
+ }
515
+ /** KIELER draws a transition dashed when it is immediate, leaves a connector, or is a termination without
516
+ * trigger that is not explicitly delayed (`SCChartsTransitionExtensions.isImplicitlyImmediate`). */
517
+ export function isImplicitlyImmediate(t, source) {
518
+ return t.delay === 'immediate' || source.connector || (t.preemption === 'termination' && !t.trigger && t.delay !== 'delayed');
519
+ }
520
+ /**
521
+ * Merges label components into runs the way KIELER's `addKeywordLabel` does: consecutive components of the
522
+ * same format are joined with a space (no space before a comma); a run that is followed by a run of another
523
+ * format keeps a trailing space. Empty runs are dropped.
524
+ */
525
+ export function mergeComponents(components) {
526
+ const out = [];
527
+ let builder = '';
528
+ let format = 'keyword';
529
+ for (const c of components) {
530
+ if (builder.length > 0 && format !== c.format) {
531
+ out.push({ text: builder + ' ', format });
532
+ builder = '';
533
+ }
534
+ if (builder.length > 0)
535
+ builder += c.text === ',' ? '' : ' ';
536
+ builder += c.text;
537
+ format = c.format;
538
+ }
539
+ if (builder.length > 0)
540
+ out.push({ text: builder, format });
541
+ return out;
542
+ }
543
+ /** The text of merged segments on one line. */
544
+ export function segmentsText(segments) {
545
+ return segments.map(s => s.text).join('').trimEnd();
546
+ }
547
+ const kw = (text) => ({ text, format: 'keyword' });
548
+ const tx = (text) => ({ text, format: 'text' });
549
+ const hl = (text) => ({ text, format: 'highlight' });
550
+ function combineName(op) {
551
+ switch (op) {
552
+ case '|': return 'or';
553
+ case '&': return 'and';
554
+ default: return op;
555
+ }
556
+ }
557
+ /** A valued object as declared: `arr[3]`, or its display label. */
558
+ export function formatValuedObject(vo, ctx) {
559
+ // KExpressionsSerializeHRExtensions.serializeHR(ValuedObject): the name as written (a `^` escape stays),
560
+ // without the symbol table that references get.
561
+ if (vo.label != null)
562
+ return vo.label;
563
+ return vo.name + vo.cardinalities.map(c => `[${formatExpression(c, ctx)}]`).join('');
564
+ }
565
+ function valuedObjectComponents(d, ctx, c) {
566
+ d.valuedObjects.forEach((vo, i) => {
567
+ // With bindings: `ref Chart c(x, y)` prints the valued object's parameters.
568
+ let text = formatValuedObject(vo, ctx);
569
+ if (vo.genericParameters?.length)
570
+ text += `<${vo.genericParameters.join(', ')}>`;
571
+ if (vo.parameters?.length)
572
+ text += formatScopeParameters(vo.parameters, ctx);
573
+ c.push(tx(text));
574
+ if (vo.initialValue) {
575
+ c.push(tx('='));
576
+ c.push(tx(formatExpression(vo.initialValue, ctx)));
577
+ }
578
+ if (vo.combine && vo.combine !== 'none') {
579
+ c.push(kw('combine'));
580
+ c.push(tx(combineName(vo.combine)));
581
+ }
582
+ if (i < d.valuedObjects.length - 1)
583
+ c.push(tx(','));
584
+ });
585
+ }
586
+ function formatScopeParameters(params, ctx) {
587
+ return formatArgs(params.map(p => p.expression), ctx, true, params.map(p => (p.pureOutput ? '!&' : p.byReference ? '&' : null)));
588
+ }
589
+ /** A method signature (`serializeMethodHighlighted` without body): `int f(int x, bool b)`. */
590
+ /** A method signature (`serializeMethodHighlighted`): `[abstract] [override|access] int f(int x)`, and
591
+ * with `body` (class members, as KIELER lists them) ` { <statements> }`. */
592
+ function methodComponents(d, ctx, c, options = {}) {
593
+ // A method without implementation is abstract, unless it belongs to a host class.
594
+ if (!d.body && !options.hostClass)
595
+ c.push(kw('abstract'));
596
+ if (d.override)
597
+ c.push(kw('override'));
598
+ else if (d.access)
599
+ c.push(kw(d.access));
600
+ const ret = d.returnType ?? 'void';
601
+ c.push(kw(ret === 'host' ? (d.returnHostType ?? 'host') : ret === 'pure' ? 'void' : ret));
602
+ c.push(tx(displayName(d.valuedObjects[0]?.name ?? '', ctx) + '('));
603
+ (d.parameters ?? []).forEach((p, i, all) => {
604
+ c.push(...declarationComponents(p, ctx));
605
+ if (i < all.length - 1)
606
+ c.push(tx(','));
607
+ });
608
+ c.push(tx(')'));
609
+ if (options.body && d.body?.statements.length) {
610
+ // The SCL serialisation without its outer braces and last semicolon.
611
+ const text = formatScl(d.body.declarations, d.body.statements, ctx);
612
+ c.push(tx('{'), tx(text.endsWith(';}') ? text.slice(1, -2) : text.slice(1, -1)), tx('}'));
613
+ }
614
+ }
615
+ /** The label components of a declaration (`serializeHighlighted(declaration, hr = true)`), before merging.
616
+ * For a class, struct or enum this is only its first line; see `declarationLines`. */
617
+ export function declarationComponents(d, ctx) {
618
+ return declarationLines(d, ctx)[0]?.components ?? [];
619
+ }
620
+ /**
621
+ * The lines of a declaration label. Most declarations are one line; a class or struct shows its members
622
+ * indented between `class Name {` and `} instances`, as KIELER's StateSynthesis.addStructDeclarations does.
623
+ */
624
+ export function declarationLines(d, ctx, indent = 0, member) {
625
+ const c = [];
626
+ if (d.declKind === 'method') {
627
+ methodComponents(d, ctx, c, member ? { body: true, hostClass: member.hostClass } : {});
628
+ return [{ indent, components: c }];
629
+ }
630
+ if (d.access)
631
+ c.push(kw(d.access));
632
+ if (d.declKind === 'variable' || d.declKind === 'class' || d.declKind === 'struct' || d.declKind === 'enum') {
633
+ if (d.extern)
634
+ c.push(kw('extern'));
635
+ if (d.global)
636
+ c.push(kw('global'));
637
+ if (d.static)
638
+ c.push(kw('static'));
639
+ if (d.input)
640
+ c.push(kw('input'));
641
+ if (d.output)
642
+ c.push(kw('output'));
643
+ if (d.const)
644
+ c.push(kw('const'));
645
+ if (d.signal)
646
+ c.push(kw('signal'));
647
+ const type = d.type;
648
+ if (d.declKind !== 'variable') {
649
+ if (d.host)
650
+ c.push(kw('host'));
651
+ c.push(kw(d.declKind));
652
+ }
653
+ else if (type === undefined || type === 'pure') {
654
+ // indicated by the signal keyword
655
+ }
656
+ else if (type === 'host') {
657
+ c.push(kw(d.hostType ?? 'host'));
658
+ }
659
+ else if (type === 'clock') {
660
+ if (d.annotations.some(a => a.name.toLowerCase() === 'passive'))
661
+ c.push(kw('passive'));
662
+ else if (d.annotations.some(a => a.name.toLowerCase() === 'logical'))
663
+ c.push(kw('logical'));
664
+ c.push(kw('clock'));
665
+ }
666
+ else if (type === 'clock-time') {
667
+ c.push(kw('time'));
668
+ }
669
+ else {
670
+ c.push(kw(type));
671
+ }
672
+ }
673
+ else if (d.declKind === 'reference' || d.declKind === 'primitive') {
674
+ if (d.extern || d.externs?.length) {
675
+ c.push(kw('extern'));
676
+ c.push(hl(d.externs?.[0]?.code ?? d.hostType ?? ''));
677
+ }
678
+ else {
679
+ if (d.input)
680
+ c.push(kw('input'));
681
+ if (d.output)
682
+ c.push(kw('output'));
683
+ if (d.const)
684
+ c.push(kw('const'));
685
+ // A declaration of a generic primitive type (`input primitive T v`) is a "simple" reference: no `ref`.
686
+ if (d.declKind === 'reference')
687
+ c.push(kw('ref'));
688
+ c.push(hl((d.referenceContainer ? d.referenceContainer + '.' : '') + (d.referenceTarget ?? '<BROKEN-REFERENCE>')));
689
+ if (d.genericParameters?.length)
690
+ c.push(tx(`<${d.genericParameters.join(', ')}>`));
691
+ }
692
+ }
693
+ else if (d.declKind === 'schedule') {
694
+ c.push(kw('schedule'));
695
+ if (d.priorities?.length) {
696
+ c.push(tx('{'));
697
+ d.priorities.forEach((prio, i, all) => {
698
+ if (prio === 'conflicting' || prio === 'commuting')
699
+ c.push(kw(prio));
700
+ if (i < all.length - 1)
701
+ c.push(tx(', '));
702
+ });
703
+ c.push(tx('}'));
704
+ }
705
+ const name = d.valuedObjects[0]?.name;
706
+ if (name)
707
+ c.push(hl(name));
708
+ return [{ indent, components: c }];
709
+ }
710
+ else if (d.text) {
711
+ c.push(tx(d.text.split('\n')[0].trim()));
712
+ return [{ indent, components: c }];
713
+ }
714
+ if (d.declKind === 'class' || d.declKind === 'struct' || d.declKind === 'enum') {
715
+ const lines = [];
716
+ if (d.className)
717
+ c.push(tx(d.className));
718
+ else if (d.declKind === 'enum' && d.valuedObjects[0])
719
+ c.push(tx(d.valuedObjects[0].name));
720
+ c.push(tx('{'));
721
+ lines.push({ indent, components: c });
722
+ for (const member of d.members ?? [])
723
+ lines.push(...declarationLines(member, ctx, indent + 1, { hostClass: !!d.host }));
724
+ const tail = [tx('}')];
725
+ if (d.declKind !== 'enum')
726
+ valuedObjectComponents(d, ctx, tail);
727
+ lines.push({ indent, components: tail });
728
+ return lines;
729
+ }
730
+ valuedObjectComponents(d, ctx, c);
731
+ return [{ indent, components: c }];
732
+ }
733
+ /** A declaration line as KIELER's diagram shows it, e.g. `[input bool ][A, B]` (first line only). */
734
+ export function declarationSegments(d, ctx) {
735
+ return mergeComponents(declarationComponents(d, ctx));
736
+ }
737
+ /** A declaration on one line: `output int F = 0`. */
738
+ export function formatDeclaration(d, ctx) {
739
+ return segmentsText(declarationSegments(d, ctx));
740
+ }
741
+ function actionKeyword(a) {
742
+ switch (a.kind) {
743
+ case 'entry': return a.preemption === 'weak' ? 'weak entry' : 'entry';
744
+ case 'during': return 'during';
745
+ case 'exit': return a.preemption === 'weak' ? 'weak exit' : 'exit';
746
+ case 'suspend': return a.weak ? 'weak suspend' : 'suspend';
747
+ case 'period': return 'period';
748
+ case 'ode': return 'ode';
749
+ }
750
+ }
751
+ /** The label components of a local action (`serializeHighlighted(action, hr = true, userLabels)`). Note that
752
+ * KIELER does not show an action's count delay. */
753
+ export function actionComponents(a, options = {}) {
754
+ const c = [];
755
+ if (a.delay === 'immediate')
756
+ c.push(kw('immediate'));
757
+ c.push(kw(actionKeyword(a)));
758
+ if ((options.userLabels ?? true) && a.label) {
759
+ c.push(tx(a.label));
760
+ }
761
+ else {
762
+ if (a.trigger) {
763
+ c.push(tx(formatExpression(a.trigger, options)));
764
+ // KIELER adds an (empty) schedule part after every trigger; it only matters for merging.
765
+ c.push({ text: '', format: 'schedule' });
766
+ }
767
+ if (a.effects.length) {
768
+ c.push(tx('/'));
769
+ c.push(tx(formatEffects(a.effects, options)));
770
+ }
771
+ }
772
+ return c;
773
+ }
774
+ /** An action line: `[during ][A ][/ c--]`. */
775
+ export function actionSegments(a, options = {}) {
776
+ return mergeComponents(actionComponents(a, options));
777
+ }
778
+ /** An action on one line: `immediate during A / c++`. */
779
+ export function formatAction(a, options = {}) {
780
+ return segmentsText(actionSegments(a, options));
781
+ }
782
+ /** The name a state shows: its label, or its name (`serializeHR(State)`). */
783
+ export function stateDisplayName(s, ctx) {
784
+ return displayName(s.label ?? s.name ?? '', ctx);
785
+ }
786
+ /** The title of a superstate or root state: the name, and for a reference state `@ Other (a, b)`. */
787
+ export function stateTitleSegments(s, ctx) {
788
+ const c = [tx(stateDisplayName(s, ctx))];
789
+ if (s.reference) {
790
+ c.push(kw('@'));
791
+ c.push(tx(s.reference.target));
792
+ // KIELER always prints the parameter list, `()` when empty.
793
+ c.push(tx(formatScopeParameters(s.reference.parameters, ctx)));
794
+ }
795
+ if (s.genericParameters?.length) {
796
+ // serializeGenericParametersHighlighted: `< T is int, U is ref Other >`.
797
+ c.push(tx('<'));
798
+ s.genericParameters.forEach((param, i, all) => {
799
+ const m = /^(\S+)\s+is\s+(ref\s+)?(.+)$/.exec(param.trim());
800
+ if (!m)
801
+ c.push(tx(param.trim()));
802
+ else {
803
+ c.push(tx(m[1]), kw('is'));
804
+ if (m[2])
805
+ c.push(kw('ref'), tx(m[3]));
806
+ else if (/^(bool|int|float|string|pure|host|clock|primitive)$/.test(m[3]))
807
+ c.push(kw(m[3]));
808
+ else
809
+ c.push(tx(m[3]));
810
+ }
811
+ if (i < all.length - 1)
812
+ c.push(tx(','));
813
+ });
814
+ c.push(tx('>'));
815
+ }
816
+ if (s.baseStates?.length) {
817
+ c.push(kw('extends'));
818
+ s.baseStates.forEach((b, i) => {
819
+ c.push(tx(b.target + (b.parameters.length ? formatScopeParameters(b.parameters, ctx) : '')));
820
+ if (i < s.baseStates.length - 1)
821
+ c.push(tx(','));
822
+ });
823
+ }
824
+ return mergeComponents(c);
825
+ }
826
+ /** The label of a region (`serializeHighlighted(region)`): `override`, its label or name, and for a `for`
827
+ * region `| i[0,3]`. Empty for an anonymous region. */
828
+ export function regionLabelSegments(r, ctx) {
829
+ const c = [];
830
+ if (r.override)
831
+ c.push(kw('override'));
832
+ const label = r.label ?? r.name;
833
+ if (label)
834
+ c.push(tx(displayName(label, ctx)));
835
+ if (r.forLoop) {
836
+ const [from, to] = forRegionRange(r.forLoop, ctx);
837
+ c.push(kw('|'));
838
+ c.push(tx(r.forLoop.variable));
839
+ c.push(tx('['));
840
+ c.push(tx(String(from)));
841
+ c.push(tx(','));
842
+ c.push(tx(String(to)));
843
+ c.push(tx(']'));
844
+ }
845
+ return mergeComponents(c);
846
+ }
847
+ /**
848
+ * The index range of a `for` region as KIELER computes it (For.getForRegionRange): `for i : 0 to 3` gives
849
+ * [0, 3]; `for i : arr` iterates the indices of the array, [0, size - 1] (the size a literal or a constant's
850
+ * initial value), and [0, -1] when the size is unknown.
851
+ */
852
+ export function forRegionRange(loop, ctx) {
853
+ if (loop.from.kind === 'int')
854
+ return [loop.from.value, loop.to?.kind === 'int' ? loop.to.value : NaN];
855
+ if (loop.from.kind === 'ref') {
856
+ const card = loop.from.decl ? ctx?.lookup?.(loop.from.decl)?.valuedObject.cardinalities[0] : undefined;
857
+ if (card?.kind === 'int')
858
+ return [0, card.value - 1];
859
+ if (card?.kind === 'ref' && card.decl) {
860
+ const init = ctx?.lookup?.(card.decl)?.valuedObject.initialValue;
861
+ if (init?.kind === 'int')
862
+ return [0, init.value - 1];
863
+ }
864
+ return [0, -1];
865
+ }
866
+ return [NaN, NaN];
867
+ }
868
+ /** A dataflow equation on one line: `O = A && !pre(A)`. */
869
+ export function formatEquation(eq, ctx) {
870
+ return `${formatReference(eq.target, ctx, true)} ${eq.operator} ${formatExpression(eq.expression, ctx)}`;
871
+ }
872
+ //# sourceMappingURL=format.js.map