embedded-react 0.15.0 → 0.17.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 (62) hide show
  1. package/aot/compile.mjs +173 -8272
  2. package/aot/compiler/animations.mjs +1001 -0
  3. package/aot/compiler/assemble.mjs +922 -0
  4. package/aot/compiler/boot.mjs +441 -0
  5. package/aot/compiler/branch-merge.mjs +319 -0
  6. package/aot/compiler/c/animations.mjs +362 -0
  7. package/aot/compiler/c/boot.mjs +127 -0
  8. package/aot/compiler/c/expressions.mjs +270 -0
  9. package/aot/compiler/c/functions.mjs +268 -0
  10. package/aot/compiler/c/keyboard.mjs +96 -0
  11. package/aot/compiler/c/nodes.mjs +294 -0
  12. package/aot/compiler/c/pan-responder.mjs +136 -0
  13. package/aot/compiler/c/statements.mjs +271 -0
  14. package/aot/compiler/c/text.mjs +83 -0
  15. package/aot/compiler/c/vectors.mjs +381 -0
  16. package/aot/compiler/c-syntax.mjs +127 -0
  17. package/aot/compiler/check.mjs +165 -0
  18. package/aot/compiler/collect.mjs +785 -0
  19. package/aot/compiler/control-flow.mjs +696 -0
  20. package/aot/compiler/diagnostics.mjs +137 -0
  21. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  22. package/aot/compiler/elements/dial.mjs +346 -0
  23. package/aot/compiler/elements/flat-list.mjs +139 -0
  24. package/aot/compiler/elements/image.mjs +151 -0
  25. package/aot/compiler/elements/modal.mjs +158 -0
  26. package/aot/compiler/elements/props.mjs +474 -0
  27. package/aot/compiler/elements/switch.mjs +183 -0
  28. package/aot/compiler/elements/text-input.mjs +171 -0
  29. package/aot/compiler/expressions.mjs +1579 -0
  30. package/aot/compiler/handlers.mjs +1072 -0
  31. package/aot/compiler/ir/animations.mjs +16 -0
  32. package/aot/compiler/ir/app.mjs +16 -0
  33. package/aot/compiler/ir/boot.mjs +16 -0
  34. package/aot/compiler/ir/expressions.mjs +16 -0
  35. package/aot/compiler/ir/functions.mjs +16 -0
  36. package/aot/compiler/ir/keyboard.mjs +16 -0
  37. package/aot/compiler/ir/nodes.mjs +107 -0
  38. package/aot/compiler/ir/pan-responder.mjs +16 -0
  39. package/aot/compiler/ir/reads.mjs +351 -0
  40. package/aot/compiler/ir/source.mjs +16 -0
  41. package/aot/compiler/ir/statements.mjs +16 -0
  42. package/aot/compiler/ir/text.mjs +16 -0
  43. package/aot/compiler/ir/types.mjs +185 -0
  44. package/aot/compiler/ir/vectors.mjs +16 -0
  45. package/aot/compiler/keyboard.mjs +152 -0
  46. package/aot/compiler/lower.mjs +311 -0
  47. package/aot/compiler/nodes.mjs +688 -0
  48. package/aot/compiler/options.mjs +55 -0
  49. package/aot/compiler/out.mjs +94 -0
  50. package/aot/compiler/pan-responder.mjs +354 -0
  51. package/aot/compiler/parse.mjs +300 -0
  52. package/aot/compiler/static-eval.mjs +454 -0
  53. package/aot/compiler/style-text.mjs +807 -0
  54. package/aot/compiler/svg.mjs +1167 -0
  55. package/aot/compiler/types.mjs +16 -0
  56. package/aot/screenshot-smoke.mjs +95 -55
  57. package/aot/style-map.mjs +366 -304
  58. package/cli.mjs +5 -8
  59. package/package.json +14 -6
  60. package/sim/embedded-react.wasm +0 -0
  61. package/src/embedded-react/FlatList.js +4 -4
  62. package/src/props.js +1 -1
@@ -0,0 +1,319 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Constants
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ /** Node fields that say where a node is or how it was written, not what it is. */
20
+ const POSITION_KEYS = new Set([
21
+ 'loc',
22
+ 'start',
23
+ 'end',
24
+ 'range',
25
+ 'extra',
26
+ 'leadingComments',
27
+ 'trailingComments',
28
+ 'innerComments',
29
+ ]);
30
+ /** Node types a merged value may not contain: their meaning is not a value boot can pick. */
31
+ const UNMERGEABLE_TYPES = new Set([
32
+ 'JSXElement',
33
+ 'JSXFragment',
34
+ 'ArrowFunctionExpression',
35
+ 'FunctionExpression',
36
+ 'CallExpression',
37
+ 'NewExpression',
38
+ 'AssignmentExpression',
39
+ 'UpdateExpression',
40
+ ]);
41
+ /** The Math functions the compiler lowers, and how many arguments each takes. */
42
+ const MATH_ARITY = {
43
+ sin: 1,
44
+ cos: 1,
45
+ tan: 1,
46
+ sqrt: 1,
47
+ abs: 1,
48
+ round: 1,
49
+ floor: 1,
50
+ ceil: 1,
51
+ trunc: 1,
52
+ min: 2,
53
+ max: 2,
54
+ atan2: 2,
55
+ pow: 2,
56
+ };
57
+ /*----------------------------------------------------------------------------------------------------------------------
58
+ - Implementation
59
+ ---------------------------------------------------------------------------------------------------------------------*/
60
+ /**
61
+ * Whether two nodes are the same code, wherever each was written.
62
+ *
63
+ * @param first One node.
64
+ * @param second The other.
65
+ *
66
+ * @returns True when they are.
67
+ */
68
+ export function sameCode(first, second) {
69
+ if (first === second)
70
+ return true;
71
+ if (typeof first !== 'object' ||
72
+ typeof second !== 'object' ||
73
+ first === null ||
74
+ second === null) {
75
+ return false;
76
+ }
77
+ if (Array.isArray(first) !== Array.isArray(second))
78
+ return false;
79
+ const keysOf = (node) => Object.keys(node).filter(key => !POSITION_KEYS.has(key) &&
80
+ node[key] !== undefined);
81
+ const firstKeys = keysOf(first);
82
+ const secondKeys = keysOf(second);
83
+ return (firstKeys.length === secondKeys.length &&
84
+ firstKeys.every(key => sameCode(first[key], second[key])));
85
+ }
86
+ /**
87
+ * Whether a node holds code a merged value cannot pick between: an element, a function, or a call (other than
88
+ * Math's, which boot works out).
89
+ *
90
+ * @param node The node.
91
+ *
92
+ * @returns True when it does.
93
+ */
94
+ function holdsUnmergeable(node) {
95
+ if (typeof node !== 'object' || node === null)
96
+ return false;
97
+ if (Array.isArray(node))
98
+ return node.some(holdsUnmergeable);
99
+ const typed = node;
100
+ if (typed.type === 'CallExpression' && isLowerableMath(typed)) {
101
+ return typed.arguments.some(holdsUnmergeable);
102
+ }
103
+ if (typed.type && UNMERGEABLE_TYPES.has(typed.type))
104
+ return true;
105
+ return Object.keys(typed).some(key => !POSITION_KEYS.has(key) && holdsUnmergeable(typed[key]));
106
+ }
107
+ /**
108
+ * Whether a node is a `Math.<fn>(…)` call the compiler lowers, with the number of arguments it takes.
109
+ *
110
+ * @param node The node.
111
+ *
112
+ * @returns True when it is.
113
+ */
114
+ function isLowerableMath(node) {
115
+ if (node.type !== 'CallExpression' ||
116
+ node.callee.type !== 'MemberExpression' ||
117
+ node.callee.computed ||
118
+ node.callee.object.type !== 'Identifier' ||
119
+ node.callee.object.name !== 'Math' ||
120
+ node.callee.property.type !== 'Identifier' ||
121
+ node.arguments.some(arg => arg.type === 'SpreadElement')) {
122
+ return false;
123
+ }
124
+ const fn = node.callee.property.name;
125
+ return (Object.hasOwn(MATH_ARITY, fn) && MATH_ARITY[fn] === node.arguments.length);
126
+ }
127
+ /**
128
+ * `test ? whenTrue : whenFalse`, entry by entry where both are object or array literals of the same shape, so
129
+ * an entry that reads state stays an expression of its own.
130
+ *
131
+ * @param test The test.
132
+ * @param whenTrue The value when it holds.
133
+ * @param whenFalse The value when it does not.
134
+ *
135
+ * @returns The merged value.
136
+ */
137
+ function mergeValues(test, whenTrue, whenFalse) {
138
+ if (sameCode(whenTrue, whenFalse))
139
+ return whenTrue;
140
+ // Two objects with the same keys in the same order merge entry by entry.
141
+ if (whenTrue.type === 'ObjectExpression' &&
142
+ whenFalse.type === 'ObjectExpression' &&
143
+ whenTrue.properties.length === whenFalse.properties.length &&
144
+ whenTrue.properties.every((property, index) => {
145
+ const other = whenFalse.properties[index];
146
+ return (property.type === 'ObjectProperty' &&
147
+ other.type === 'ObjectProperty' &&
148
+ !property.computed &&
149
+ !other.computed &&
150
+ sameCode(property.key, other.key));
151
+ })) {
152
+ return {
153
+ ...whenTrue,
154
+ properties: whenTrue.properties.map((property, index) => ({
155
+ ...property,
156
+ value: mergeValues(test, property.value, whenFalse.properties[index]
157
+ .value),
158
+ })),
159
+ };
160
+ }
161
+ // Two arrays of the same length merge element by element.
162
+ if (whenTrue.type === 'ArrayExpression' &&
163
+ whenFalse.type === 'ArrayExpression' &&
164
+ whenTrue.elements.length === whenFalse.elements.length &&
165
+ [...whenTrue.elements, ...whenFalse.elements].every(element => element && element.type !== 'SpreadElement')) {
166
+ return {
167
+ ...whenTrue,
168
+ elements: whenTrue.elements.map((element, index) => mergeValues(test, element, whenFalse.elements[index])),
169
+ };
170
+ }
171
+ return {
172
+ type: 'ConditionalExpression',
173
+ test,
174
+ consequent: whenTrue,
175
+ alternate: whenFalse,
176
+ loc: whenTrue.loc,
177
+ };
178
+ }
179
+ /**
180
+ * An attribute's value as an expression, or null for a bare attribute (`<Switch disabled />`).
181
+ *
182
+ * @param attribute The attribute.
183
+ *
184
+ * @returns The value.
185
+ */
186
+ function attributeValue(attribute) {
187
+ const { value } = attribute;
188
+ if (!value)
189
+ return null;
190
+ if (value.type === 'JSXExpressionContainer') {
191
+ return value.expression.type === 'JSXEmptyExpression'
192
+ ? null
193
+ : value.expression;
194
+ }
195
+ return value;
196
+ }
197
+ /**
198
+ * Two attributes merged, or null when they differ in a way boot cannot pick: their names, or a value that is a
199
+ * handler, a ref, a key, an element or a call.
200
+ *
201
+ * @param test The test.
202
+ * @param whenTrue The attribute when it holds.
203
+ * @param whenFalse The attribute when it does not.
204
+ *
205
+ * @returns The merged attribute, or null.
206
+ */
207
+ function mergeAttributes(test, whenTrue, whenFalse) {
208
+ if (sameCode(whenTrue, whenFalse))
209
+ return whenTrue;
210
+ if (whenTrue.type !== 'JSXAttribute' ||
211
+ whenFalse.type !== 'JSXAttribute' ||
212
+ !sameCode(whenTrue.name, whenFalse.name)) {
213
+ return null;
214
+ }
215
+ const name = whenTrue.name.type === 'JSXIdentifier' ? whenTrue.name.name : '';
216
+ const trueValue = attributeValue(whenTrue);
217
+ const falseValue = attributeValue(whenFalse);
218
+ if (name === 'key' ||
219
+ name === 'ref' ||
220
+ /^on[A-Z]/.test(name) ||
221
+ !trueValue ||
222
+ !falseValue ||
223
+ holdsUnmergeable(trueValue) ||
224
+ holdsUnmergeable(falseValue)) {
225
+ return null;
226
+ }
227
+ return {
228
+ ...whenTrue,
229
+ value: {
230
+ type: 'JSXExpressionContainer',
231
+ expression: mergeValues(test, trueValue, falseValue),
232
+ loc: whenTrue.value?.loc,
233
+ },
234
+ };
235
+ }
236
+ /**
237
+ * An element's children, less the empty `{}` a JSX comment leaves.
238
+ *
239
+ * @param element The element.
240
+ *
241
+ * @returns The children.
242
+ */
243
+ const childrenOf = (element) => element.children.filter(child => !(child.type === 'JSXExpressionContainer' &&
244
+ child.expression.type === 'JSXEmptyExpression'));
245
+ /**
246
+ * JSX text as it renders: text spanning lines collapses its whitespace, as Babel does.
247
+ *
248
+ * @param text The text.
249
+ *
250
+ * @returns The rendered text.
251
+ */
252
+ const renderedText = (text) => /\n/.test(text.value) ? text.value.replace(/\s+/g, ' ').trim() : text.value;
253
+ /**
254
+ * Two branches of a test that depends on the panel, as one element whose differing values each pick at boot,
255
+ * or null when the branches differ in shape: their elements, attributes, children, handlers or text. A branch
256
+ * that changes only values then needs no per-panel variant.
257
+ *
258
+ * @param test The test.
259
+ * @param whenTrue The element when it holds.
260
+ * @param whenFalse The element when it does not.
261
+ *
262
+ * @returns The merged element, or null.
263
+ */
264
+ export function mergeBranchElements(test, whenTrue, whenFalse) {
265
+ if (sameCode(whenTrue, whenFalse))
266
+ return whenTrue;
267
+ const trueOpening = whenTrue.openingElement;
268
+ const falseOpening = whenFalse.openingElement;
269
+ if (!sameCode(trueOpening.name, falseOpening.name) ||
270
+ trueOpening.attributes.length !== falseOpening.attributes.length) {
271
+ return null;
272
+ }
273
+ // Attributes pair up in order, since a later style or spread wins over an earlier one.
274
+ const attributes = [];
275
+ for (const [index, attribute] of trueOpening.attributes.entries()) {
276
+ const merged = mergeAttributes(test, attribute, falseOpening.attributes[index]);
277
+ if (!merged)
278
+ return null;
279
+ attributes.push(merged);
280
+ }
281
+ // Children pair up too: elements merge in turn, and a differing {value} picks at boot.
282
+ const trueChildren = childrenOf(whenTrue);
283
+ const falseChildren = childrenOf(whenFalse);
284
+ if (trueChildren.length !== falseChildren.length)
285
+ return null;
286
+ const children = [];
287
+ for (const [index, child] of trueChildren.entries()) {
288
+ const other = falseChildren[index];
289
+ if (sameCode(child, other) ||
290
+ (child.type === 'JSXText' &&
291
+ other.type === 'JSXText' &&
292
+ renderedText(child) === renderedText(other))) {
293
+ children.push(child);
294
+ }
295
+ else if (child.type === 'JSXElement' && other.type === 'JSXElement') {
296
+ const merged = mergeBranchElements(test, child, other);
297
+ if (!merged)
298
+ return null;
299
+ children.push(merged);
300
+ }
301
+ else if (child.type === 'JSXExpressionContainer' &&
302
+ other.type === 'JSXExpressionContainer' &&
303
+ !holdsUnmergeable(child.expression) &&
304
+ !holdsUnmergeable(other.expression)) {
305
+ children.push({
306
+ ...child,
307
+ expression: mergeValues(test, child.expression, other.expression),
308
+ });
309
+ }
310
+ else {
311
+ return null;
312
+ }
313
+ }
314
+ return {
315
+ ...whenTrue,
316
+ openingElement: { ...trueOpening, attributes },
317
+ children,
318
+ };
319
+ }
@@ -0,0 +1,362 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Imports
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ import { floatLit } from '../c-syntax.mjs';
20
+ import { printExpr } from './expressions.mjs';
21
+ /*----------------------------------------------------------------------------------------------------------------------
22
+ - Implementation
23
+ ---------------------------------------------------------------------------------------------------------------------*/
24
+ /**
25
+ * One animation as a scoped ERAnimConfig and the er_anim_value_animate call that starts it. Animation lines
26
+ * carry their own indent, whatever block they sit in.
27
+ *
28
+ * @param animation The animation.
29
+ * @param configName The config's name, unique within the function.
30
+ * @param onComplete The C function to run when it completes, or null.
31
+ *
32
+ * @returns The C block.
33
+ */
34
+ export function printAnimation(animation, configName, onComplete) {
35
+ const set = (field, value) => ` ${configName}.${field} = ${value};`;
36
+ const lines = [
37
+ ' {',
38
+ ` ERAnimConfig ${configName};`,
39
+ ` memset(&${configName}, 0, sizeof(${configName}));`,
40
+ ];
41
+ // The curve's own fields.
42
+ const curve = animation.curve;
43
+ if (curve.kind === 'spring') {
44
+ lines.push(set('type', 'ER_ANIM_SPRING'), set('stiffness', floatLit(curve.stiffness)), set('damping', floatLit(curve.damping)), set('mass', floatLit(curve.mass)));
45
+ }
46
+ else if (curve.kind === 'decay') {
47
+ lines.push(set('type', 'ER_ANIM_DECAY'), set('deceleration', floatLit(curve.deceleration)), set('velocity', floatLit(curve.velocity)));
48
+ }
49
+ else {
50
+ lines.push(set('type', 'ER_ANIM_TIMING'), set('duration_ms', String(curve.durationMs)), set('easing', curve.easing));
51
+ if (curve.bezier) {
52
+ const [x1, y1, x2, y2] = curve.bezier.map(point => floatLit(point));
53
+ lines.push(` ${configName}.bezier_x1 = ${x1}; ${configName}.bezier_y1 = ${y1};`, ` ${configName}.bezier_x2 = ${x2}; ${configName}.bezier_y2 = ${y2};`);
54
+ }
55
+ }
56
+ // The fields every curve shares.
57
+ if (animation.delayMs > 0) {
58
+ lines.push(set('delay_ms', String(animation.delayMs)));
59
+ }
60
+ if (animation.isLooping) {
61
+ lines.push(set('loop', 'true'));
62
+ }
63
+ if (onComplete) {
64
+ lines.push(set('on_complete', onComplete));
65
+ }
66
+ // Decay with no target is given the value it holds now.
67
+ const to = animation.to
68
+ ? printExpr(animation.to)
69
+ : `er_anim_value_get(${animation.handle})`;
70
+ lines.push(` er_anim_value_animate(${animation.handle}, (float)(${to}), &${configName});`, ' }');
71
+ return lines;
72
+ }
73
+ /**
74
+ * Runs a completion as finished, outside the engine's own on_complete.
75
+ *
76
+ * @param completion The completion.
77
+ *
78
+ * @returns The C line.
79
+ */
80
+ export const printCompletionCall = (completion) => ` ${completion.name}(true, NULL);`;
81
+ /**
82
+ * Starts a completion wait for one run of a composition.
83
+ *
84
+ * @param owner The composition.
85
+ * @param delayMs The wait.
86
+ * @param completion The completion it runs.
87
+ *
88
+ * @returns The C line.
89
+ */
90
+ const printWaitStart = (owner, delayMs, completion) => ` app_wait_start(${owner}, ${delayMs}, ${completion.name});`;
91
+ /**
92
+ * The completion-wait table and the helpers that drive it, each helper only when the generated code calls it
93
+ * (an unused static function would warn). Every run of a composition has a wait of its own, so starting one never
94
+ * ends another; a stop ends every run of its composition.
95
+ *
96
+ * @param callers The generated code, to look for calls in.
97
+ *
98
+ * @returns The C block.
99
+ */
100
+ export function printWaitDeclarations(callers) {
101
+ const blocks = [
102
+ `#ifndef ER_AOT_MAX_WAITS
103
+ #define ER_AOT_MAX_WAITS 8
104
+ #endif
105
+
106
+ /* The wait between a run's last animation and its completion: the composition it belongs to (which a stop
107
+ names), the time left and the completion it runs. */
108
+ typedef struct
109
+ {
110
+ int remaining_ms;
111
+ int owner;
112
+ ERAnimCompleteFn done;
113
+ uint8_t state;
114
+ } ErAnimWait;
115
+ enum
116
+ {
117
+ APP_WAIT_FREE,
118
+ APP_WAIT_PENDING,
119
+ APP_WAIT_DUE,
120
+ APP_WAIT_STOPPING
121
+ };
122
+ static ErAnimWait s_waits[ER_AOT_MAX_WAITS];
123
+
124
+ /* Starts a wait for one run; runs never share one. */
125
+ static void app_wait_start(int owner, int ms, ERAnimCompleteFn done)
126
+ {
127
+ for (int i = 0; i < ER_AOT_MAX_WAITS; i++)
128
+ {
129
+ if (s_waits[i].state == APP_WAIT_FREE)
130
+ {
131
+ s_waits[i].remaining_ms = ms;
132
+ s_waits[i].owner = owner;
133
+ s_waits[i].done = done;
134
+ s_waits[i].state = APP_WAIT_PENDING;
135
+ return;
136
+ }
137
+ }
138
+
139
+ /* The table is full (raise ER_AOT_MAX_WAITS): the run cannot wait, so it ends now, as not finished. A run
140
+ that completion starts while the table is still full is dropped instead of recursing. */
141
+ static bool s_reporting_full;
142
+ if (!s_reporting_full)
143
+ {
144
+ s_reporting_full = true;
145
+ done(false, NULL);
146
+ s_reporting_full = false;
147
+ }
148
+ }
149
+
150
+ /* Counts down every wait, then completes the ones that ran out. A wait a completion starts here waits its
151
+ full time. */
152
+ static void app_wait_tick(int dt_ms)
153
+ {
154
+ for (int i = 0; i < ER_AOT_MAX_WAITS; i++)
155
+ {
156
+ if (s_waits[i].state == APP_WAIT_PENDING)
157
+ {
158
+ s_waits[i].remaining_ms -= dt_ms;
159
+ if (s_waits[i].remaining_ms <= 0)
160
+ {
161
+ s_waits[i].state = APP_WAIT_DUE;
162
+ }
163
+ }
164
+ }
165
+ for (int i = 0; i < ER_AOT_MAX_WAITS; i++)
166
+ {
167
+ if (s_waits[i].state == APP_WAIT_DUE)
168
+ {
169
+ s_waits[i].state = APP_WAIT_FREE;
170
+ s_waits[i].done(true, NULL);
171
+ }
172
+ }
173
+ }`,
174
+ ];
175
+ if (callers.includes('app_wait_detach(')) {
176
+ blocks.push(`/* A stop's two halves: detach the composition's waits, then report them as not finished. Anything a
177
+ completion in between starts is a new run, which the stop leaves alone. */
178
+ static void app_wait_detach(int owner)
179
+ {
180
+ for (int i = 0; i < ER_AOT_MAX_WAITS; i++)
181
+ {
182
+ if (s_waits[i].owner == owner &&
183
+ (s_waits[i].state == APP_WAIT_PENDING || s_waits[i].state == APP_WAIT_DUE))
184
+ {
185
+ s_waits[i].state = APP_WAIT_STOPPING;
186
+ }
187
+ }
188
+ }
189
+
190
+ static void app_wait_report(int owner)
191
+ {
192
+ for (int i = 0; i < ER_AOT_MAX_WAITS; i++)
193
+ {
194
+ if (s_waits[i].owner == owner && s_waits[i].state == APP_WAIT_STOPPING)
195
+ {
196
+ s_waits[i].state = APP_WAIT_FREE;
197
+ s_waits[i].done(false, NULL);
198
+ }
199
+ }
200
+ }`);
201
+ }
202
+ return blocks.join('\n\n');
203
+ }
204
+ /**
205
+ * The name of a chain's callback that starts step `index` (step 0's starts a repeat).
206
+ *
207
+ * @param chain The chain.
208
+ * @param index The step.
209
+ *
210
+ * @returns The C function's name.
211
+ */
212
+ const chainCallback = (chain, index) => `er_seqcb_${chain.id}_${index}`;
213
+ /** The slot that counts a counted loop's passes. */
214
+ const passCounter = (chain) => `s_loop${chain.id}_n`;
215
+ /** The slot that keeps where a looped value started. */
216
+ const startValue = (chain) => `s_loop${chain.id}_from`;
217
+ /**
218
+ * The callback the step after `index` is started from, or what runs after the last step: the repeat for a
219
+ * loop, else the completion.
220
+ *
221
+ * @param chain The chain.
222
+ * @param index The step.
223
+ *
224
+ * @returns The C function's name, or null for nothing.
225
+ */
226
+ function afterStep(chain, index) {
227
+ if (index < chain.steps.length - 1) {
228
+ return chainCallback(chain, index + 1);
229
+ }
230
+ if (chain.loop) {
231
+ return chainCallback(chain, 0);
232
+ }
233
+ return chain.completionWait?.callback ?? chain.completion?.name ?? null;
234
+ }
235
+ /**
236
+ * Calls the completion with `finished`, from inside a chain callback.
237
+ *
238
+ * @param completion The completion, or null.
239
+ * @param finished The C value passed as `finished`.
240
+ *
241
+ * @returns The C line, or none.
242
+ */
243
+ const callCompletion = (completion, finished) => completion ? [` ${completion.name}(${finished}, NULL);`] : [];
244
+ /**
245
+ * Ends a chain or composition when the animation before was interrupted, calling the completion as not finished.
246
+ *
247
+ * @param completion The completion, or null.
248
+ *
249
+ * @returns The C lines.
250
+ */
251
+ const endIfInterrupted = (completion) => [
252
+ ' if (!finished)',
253
+ ' {',
254
+ ...callCompletion(completion, 'false'),
255
+ ' return;',
256
+ ' }',
257
+ ];
258
+ /**
259
+ * The on_complete callback that starts a completion's wait once the last animation has finished.
260
+ *
261
+ * @param completion The completion.
262
+ * @param wait The wait.
263
+ *
264
+ * @returns The C function.
265
+ */
266
+ export const printCompletionWait = (completion, wait) => ({
267
+ name: wait.callback,
268
+ body: [
269
+ ...endIfInterrupted(completion),
270
+ printWaitStart(wait.owner, wait.delayMs, completion),
271
+ ],
272
+ });
273
+ /**
274
+ * A chain's file-scope callbacks and loop slots. Each callback first ends the chain if the step before it was
275
+ * interrupted, as JS does.
276
+ *
277
+ * @param chain The chain.
278
+ *
279
+ * @returns The callbacks and declarations.
280
+ */
281
+ export function printChainFunctions(chain) {
282
+ const interrupted = endIfInterrupted(chain.completion);
283
+ // The wait after the last step comes first, then steps n..1, each started from the callback of the step before.
284
+ const callbacks = [];
285
+ if (chain.completion && chain.completionWait) {
286
+ callbacks.push(printCompletionWait(chain.completion, chain.completionWait));
287
+ }
288
+ for (let index = chain.steps.length - 1; index >= 1; index--) {
289
+ callbacks.push({
290
+ name: chainCallback(chain, index),
291
+ body: [
292
+ ...interrupted,
293
+ ...printAnimation(chain.steps[index], `cfg${chain.id}_${index}`, afterStep(chain, index)),
294
+ ],
295
+ });
296
+ }
297
+ const decls = [];
298
+ const loop = chain.loop;
299
+ if (!loop) {
300
+ return { callbacks, decls };
301
+ }
302
+ // The repeat runs when the last step finishes: it counts the pass, resets the value, and starts step 0 again.
303
+ const repeat = [...interrupted];
304
+ if (loop.iterations >= 0) {
305
+ const counter = passCounter(chain);
306
+ decls.push(`static int ${counter};`);
307
+ const finish = loop.finalWait && chain.completion
308
+ ? [
309
+ ' ' +
310
+ printWaitStart(loop.finalWait.owner, loop.finalWait.delayMs, chain.completion),
311
+ ]
312
+ : callCompletion(chain.completion, 'true');
313
+ repeat.push(` if (${counter} >= ${loop.iterations})`, ' {', ...finish, ' return;', ' }', ` ${counter}++;`);
314
+ }
315
+ if (loop.resetHandle) {
316
+ decls.push(`static float ${startValue(chain)};`);
317
+ repeat.push(` er_anim_value_set(${loop.resetHandle}, ${startValue(chain)});`);
318
+ }
319
+ repeat.push(...printAnimation(loop.restart, `cfg${chain.id}_0`, afterStep(chain, 0)));
320
+ callbacks.push({ name: chainCallback(chain, 0), body: repeat });
321
+ return { callbacks, decls };
322
+ }
323
+ /**
324
+ * The C that starts an animation where `.start()` was called. A chain's callbacks and slots are file-scope
325
+ * (see printChainFunctions).
326
+ *
327
+ * @param start The start.
328
+ *
329
+ * @returns The C lines, which carry their own indent.
330
+ */
331
+ export function printAnimationStart(start) {
332
+ switch (start.kind) {
333
+ case 'startAnimations': {
334
+ // A completion nothing can run (an endless loop of delays) is still referenced, so -Werror builds pass.
335
+ if (!start.animations.length) {
336
+ return start.completion ? [` (void)${start.completion.name};`] : [];
337
+ }
338
+ // The completion (or its wait) goes on the last animation, the only one when there is a completion.
339
+ const last = start.animations.length - 1;
340
+ const onComplete = start.completionWait?.callback ?? start.completion?.name ?? null;
341
+ return start.animations.flatMap((animation, index) => printAnimation(animation, `cfg${start.firstConfig + index}`, index === last ? onComplete : null));
342
+ }
343
+ case 'completeAfter':
344
+ return start.owner !== null
345
+ ? [printWaitStart(start.owner, start.delayMs, start.completion)]
346
+ : [printCompletionCall(start.completion)];
347
+ case 'startChain': {
348
+ // A loop first records the pass and where the value starts, then step 0 starts inline.
349
+ const lines = [];
350
+ if (start.loop && start.loop.iterations >= 0) {
351
+ lines.push(` ${passCounter(start)} = 1;`);
352
+ }
353
+ if (start.loop?.resetHandle) {
354
+ lines.push(` ${startValue(start)} = er_anim_value_get(${start.loop.resetHandle});`);
355
+ }
356
+ return [
357
+ ...lines,
358
+ ...printAnimation(start.steps[0], `cfg${start.id}_0`, afterStep(start, 0)),
359
+ ];
360
+ }
361
+ }
362
+ }