embedded-react 0.14.1 → 0.16.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 (61) hide show
  1. package/README.md +51 -486
  2. package/aot/compile.mjs +173 -8272
  3. package/aot/compiler/animations.mjs +1001 -0
  4. package/aot/compiler/assemble.mjs +806 -0
  5. package/aot/compiler/c/animations.mjs +362 -0
  6. package/aot/compiler/c/expressions.mjs +215 -0
  7. package/aot/compiler/c/functions.mjs +268 -0
  8. package/aot/compiler/c/keyboard.mjs +96 -0
  9. package/aot/compiler/c/nodes.mjs +282 -0
  10. package/aot/compiler/c/pan-responder.mjs +136 -0
  11. package/aot/compiler/c/statements.mjs +242 -0
  12. package/aot/compiler/c/text.mjs +83 -0
  13. package/aot/compiler/c/vectors.mjs +381 -0
  14. package/aot/compiler/c-syntax.mjs +127 -0
  15. package/aot/compiler/check.mjs +165 -0
  16. package/aot/compiler/collect.mjs +743 -0
  17. package/aot/compiler/control-flow.mjs +683 -0
  18. package/aot/compiler/diagnostics.mjs +137 -0
  19. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  20. package/aot/compiler/elements/dial.mjs +343 -0
  21. package/aot/compiler/elements/flat-list.mjs +139 -0
  22. package/aot/compiler/elements/image.mjs +151 -0
  23. package/aot/compiler/elements/modal.mjs +158 -0
  24. package/aot/compiler/elements/props.mjs +474 -0
  25. package/aot/compiler/elements/switch.mjs +183 -0
  26. package/aot/compiler/elements/text-input.mjs +171 -0
  27. package/aot/compiler/expressions.mjs +1479 -0
  28. package/aot/compiler/handlers.mjs +1072 -0
  29. package/aot/compiler/ir/animations.mjs +16 -0
  30. package/aot/compiler/ir/app.mjs +16 -0
  31. package/aot/compiler/ir/expressions.mjs +16 -0
  32. package/aot/compiler/ir/functions.mjs +16 -0
  33. package/aot/compiler/ir/keyboard.mjs +16 -0
  34. package/aot/compiler/ir/nodes.mjs +83 -0
  35. package/aot/compiler/ir/pan-responder.mjs +16 -0
  36. package/aot/compiler/ir/source.mjs +16 -0
  37. package/aot/compiler/ir/statements.mjs +16 -0
  38. package/aot/compiler/ir/text.mjs +16 -0
  39. package/aot/compiler/ir/types.mjs +185 -0
  40. package/aot/compiler/ir/vectors.mjs +16 -0
  41. package/aot/compiler/keyboard.mjs +152 -0
  42. package/aot/compiler/lower.mjs +282 -0
  43. package/aot/compiler/nodes.mjs +683 -0
  44. package/aot/compiler/options.mjs +55 -0
  45. package/aot/compiler/out.mjs +94 -0
  46. package/aot/compiler/pan-responder.mjs +354 -0
  47. package/aot/compiler/parse.mjs +300 -0
  48. package/aot/compiler/static-eval.mjs +228 -0
  49. package/aot/compiler/style-text.mjs +648 -0
  50. package/aot/compiler/svg.mjs +1167 -0
  51. package/aot/compiler/types.mjs +16 -0
  52. package/aot/screenshot-smoke.mjs +95 -55
  53. package/aot/style-map.mjs +366 -304
  54. package/cli.mjs +5 -8
  55. package/package.json +14 -6
  56. package/sim/embedded-react.cjs +1 -1
  57. package/sim/embedded-react.js +1 -1
  58. package/sim/embedded-react.wasm +0 -0
  59. package/src/embedded-react/FlatList.js +4 -4
  60. package/src/embedded-react/index.d.ts +2 -1
  61. package/src/props.js +1 -1
@@ -0,0 +1,381 @@
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 { printCondition, printExpr } from './expressions.mjs';
21
+ import { printPropValue } from './nodes.mjs';
22
+ /*----------------------------------------------------------------------------------------------------------------------
23
+ - Constants
24
+ ---------------------------------------------------------------------------------------------------------------------*/
25
+ /** The most color stops the engine's ERVectorGradient holds; more are dropped. */
26
+ export const MAX_GRADIENT_STOPS = 8;
27
+ /*----------------------------------------------------------------------------------------------------------------------
28
+ - Implementation
29
+ ---------------------------------------------------------------------------------------------------------------------*/
30
+ /**
31
+ * One paint as an ERVectorPaint initializer.
32
+ *
33
+ * @param paint The paint.
34
+ *
35
+ * @returns The C.
36
+ */
37
+ export const printVectorPaint = (paint) => `{ .fill = ${paint.fill}u, .stroke = ${paint.stroke}u, .stroke_w = ` +
38
+ `${floatLit(paint.strokeWidth)}, .miter = ${floatLit(paint.miter)}, .cap = ${paint.cap}, .join ` +
39
+ `= ${paint.join}, .fill_rule = ${paint.fillRule}, .fill_grad = ` +
40
+ `${paint.fillGradient}, .stroke_grad = ${paint.strokeGradient} }`;
41
+ /**
42
+ * One gradient as an ERVectorGradient initializer. Stops fill the C ERGradientStop[] positionally; geometry
43
+ * means, per type: linear axis (ax, ay)->(bx, by); radial center (ax, ay) and radius r; conic center (ax, ay)
44
+ * and start angle r.
45
+ *
46
+ * @param gradient The gradient.
47
+ *
48
+ * @returns The C.
49
+ */
50
+ export function printVectorGradient(gradient) {
51
+ const allStops = gradient.stops || [];
52
+ const keptStops = allStops.length > MAX_GRADIENT_STOPS
53
+ ? allStops.slice(0, MAX_GRADIENT_STOPS)
54
+ : allStops;
55
+ const stopInits = keptStops
56
+ .map(stop => `{ ${stop.color >>> 0}u, ${floatLit(stop.offset)} }`)
57
+ .join(', ');
58
+ return (`{ .type = ${gradient.type | 0}, .stop_count = ${keptStops.length}, .stops = { ${stopInits} }, ` +
59
+ `.ax = ${floatLit(gradient.ax || 0)}, .ay = ${floatLit(gradient.ay || 0)}, .bx = ${floatLit(gradient.bx || 0)}, ` +
60
+ `.by = ${floatLit(gradient.by || 0)}, .r = ${floatLit(gradient.r || 0)} }`);
61
+ }
62
+ /**
63
+ * A baked drawing's const tables: its op-tape, its paints, and its gradients when it has any. An empty tape
64
+ * has none.
65
+ *
66
+ * @param tables The drawing.
67
+ *
68
+ * @returns The C declarations.
69
+ */
70
+ export function printVectorTables(tables) {
71
+ if (!tables.ops.length) {
72
+ return [];
73
+ }
74
+ const { id } = tables;
75
+ const declarations = [
76
+ `static const float s_svg${id}_ops[] = {\n ${tables.ops.map(op => floatLit(op)).join(', ')}\n};`,
77
+ `static const ERVectorPaint s_svg${id}_paints[] = {\n` +
78
+ `${tables.paints.map(paint => ' ' + printVectorPaint(paint)).join(',\n')}\n};`,
79
+ ];
80
+ if (tables.gradients.length) {
81
+ declarations.push(`static const ERVectorGradient s_svg${id}_grads[] = ` +
82
+ `{\n${tables.gradients.map(gradient => ' ' + printVectorGradient(gradient)).join(',\n')}\n};`);
83
+ }
84
+ return declarations;
85
+ }
86
+ /**
87
+ * Points a vector node at its baked tables; an empty tape leaves the node blank.
88
+ *
89
+ * @param nodeId The node's variable.
90
+ * @param tables The drawing.
91
+ *
92
+ * @returns The C lines.
93
+ */
94
+ export function printVectorOps(nodeId, tables) {
95
+ if (!tables.ops.length) {
96
+ return [];
97
+ }
98
+ const { id, gradients } = tables;
99
+ const gradsRef = gradients.length ? `s_svg${id}_grads` : 'NULL';
100
+ return [
101
+ ` er_node_set_vector_ops(${nodeId}, s_svg${id}_ops, ${tables.ops.length}, ` +
102
+ `s_svg${id}_paints, ${tables.paints.length}, ${gradsRef}, ${gradients.length});`,
103
+ ];
104
+ }
105
+ /**
106
+ * One op-tape slot as the C float it is.
107
+ *
108
+ * @param value The slot.
109
+ *
110
+ * @returns The C.
111
+ */
112
+ export function printTapeValue(value) {
113
+ switch (value.kind) {
114
+ case 'op':
115
+ return value.op;
116
+ case 'number':
117
+ return floatLit(value.value);
118
+ case 'float':
119
+ return `(float)(${printExpr(value.value)})`;
120
+ case 'local':
121
+ return value.name;
122
+ case 'chain':
123
+ return `(${[
124
+ printTapeValue(value.first),
125
+ ...value.rest.map(term => `${term.op} ${printTapeValue(term.value)}`),
126
+ ].join(' ')})`;
127
+ case 'radians':
128
+ return `((${printTapeValue(value.degrees)} - 90.0f) * (float)M_PI / 180.0f)`;
129
+ case 'fullTurn':
130
+ return '(2.0f * (float)M_PI)';
131
+ case 'clampRadius':
132
+ return `fminf(fmaxf(${printTapeValue(value.radius)}, 0.0f), (${printTapeValue(value.side)}) * 0.5f)`;
133
+ }
134
+ }
135
+ /**
136
+ * A paint color as C: a constant ARGB, or the color state chooses.
137
+ *
138
+ * @param color The color.
139
+ *
140
+ * @returns The C.
141
+ */
142
+ const printPaintColor = (color) => color.kind === 'static' ? `${color.argb}u` : printPropValue(color.value);
143
+ /**
144
+ * A paint's gradient index as C: 0 for none, the index, or the index while its condition holds.
145
+ *
146
+ * @param ref The gradient.
147
+ *
148
+ * @returns The C.
149
+ */
150
+ function printGradientRef(ref) {
151
+ if (!ref.index || !ref.when) {
152
+ return String(ref.index);
153
+ }
154
+ const test = printCondition(ref.when.test);
155
+ return `((${ref.when.negate ? `!(${test})` : test}) ? ${ref.index} : 0)`;
156
+ }
157
+ /**
158
+ * Whether a gradient follows state: a stop color or a geometry field does.
159
+ *
160
+ * @param gradient The gradient.
161
+ *
162
+ * @returns Whether it does.
163
+ */
164
+ const isGradientStateDriven = (gradient) => gradient.stops.some(stop => stop.color.kind === 'state' || stop.offset.kind !== 'number') ||
165
+ [gradient.ax, gradient.ay, gradient.bx, gradient.by, gradient.r].some(field => field.kind !== 'number');
166
+ /**
167
+ * Whether a paint follows state: a color, the stroke width, or a gradient it uses (or its condition) does.
168
+ *
169
+ * @param paint The paint.
170
+ * @param gradients The drawing's gradients.
171
+ *
172
+ * @returns Whether it does.
173
+ */
174
+ function isPaintStateDriven(paint, gradients) {
175
+ const followsState = (ref) => ref.index > 0 &&
176
+ (ref.when !== null || isGradientStateDriven(gradients[ref.index - 1]));
177
+ return (paint.fill.kind === 'state' ||
178
+ paint.stroke.kind === 'state' ||
179
+ paint.strokeWidth.kind !== 'number' ||
180
+ followsState(paint.fillGradient) ||
181
+ followsState(paint.strokeGradient));
182
+ }
183
+ /**
184
+ * A paint's ERVectorPaint fields, in struct order.
185
+ *
186
+ * @param paint The paint.
187
+ *
188
+ * @returns Each field's name and C value.
189
+ */
190
+ const paintFields = (paint) => [
191
+ ['fill', printPaintColor(paint.fill)],
192
+ ['stroke', printPaintColor(paint.stroke)],
193
+ ['stroke_w', printTapeValue(paint.strokeWidth)],
194
+ ['miter', floatLit(paint.miter)],
195
+ ['cap', String(paint.cap)],
196
+ ['join', String(paint.join)],
197
+ ['fill_rule', String(paint.fillRule)],
198
+ ['fill_grad', printGradientRef(paint.fillGradient)],
199
+ ['stroke_grad', printGradientRef(paint.strokeGradient)],
200
+ ];
201
+ /**
202
+ * A gradient's ERVectorGradient fields after its stops, in struct order.
203
+ *
204
+ * @param gradient The gradient.
205
+ *
206
+ * @returns Each field's name and C value.
207
+ */
208
+ const gradientGeometry = (gradient) => ['ax', 'ay', 'bx', 'by', 'r'].map(field => [
209
+ field,
210
+ printTapeValue(gradient[field]),
211
+ ]);
212
+ /**
213
+ * A state-driven drawing's tables and its build_svg<id>() function. The op-tape is always mutable; the
214
+ * gradients and paints are const tables unless state drives something in them, in which case the builder
215
+ * rewrites them too.
216
+ *
217
+ * @param vector The drawing.
218
+ *
219
+ * @returns The table declarations, and the builder function.
220
+ */
221
+ export function printStateDrivenVector(vector) {
222
+ const { id, gradients, paints } = vector;
223
+ const hasStatePaint = paints.some(paint => isPaintStateDriven(paint, gradients));
224
+ const hasStateGradient = gradients.some(isGradientStateDriven);
225
+ const data = [`static float s_svg${id}_ops[${vector.tape.length}];`];
226
+ if (gradients.length) {
227
+ if (hasStateGradient) {
228
+ data.push(`static ERVectorGradient s_svg${id}_grads[${gradients.length}];`);
229
+ }
230
+ else {
231
+ const inits = gradients.map(gradient => {
232
+ const stops = gradient.stops
233
+ .map(stop => `{ ${printPaintColor(stop.color)}, ${printTapeValue(stop.offset)} }`)
234
+ .join(', ');
235
+ const geometry = gradientGeometry(gradient)
236
+ .map(([field, value]) => `.${field} = ${value}`)
237
+ .join(', ');
238
+ return (` { .type = ${gradient.type}, .stop_count = ${gradient.stops.length}, ` +
239
+ `.stops = { ${stops} }, ${geometry} }`);
240
+ });
241
+ data.push(`static const ERVectorGradient s_svg${id}_grads[] = {\n${inits.join(',\n')}\n};`);
242
+ }
243
+ }
244
+ if (hasStatePaint) {
245
+ data.push(`static ERVectorPaint s_svg${id}_paints[${paints.length}];`);
246
+ }
247
+ else {
248
+ const inits = paints.map(paint => ` { ${paintFields(paint)
249
+ .map(([field, value]) => `.${field} = ${value}`)
250
+ .join(', ')} }`);
251
+ data.push(`static const ERVectorPaint s_svg${id}_paints[] = {\n${inits.join(',\n')}\n};`);
252
+ }
253
+ // The builder: the locals, every tape slot, then the paints and gradients state drives.
254
+ const lines = [
255
+ ...vector.locals.map(local => ` const float ${local.name} = ${printTapeValue(local.value)};`),
256
+ ...vector.tape.map((value, slot) => ` s_svg${id}_ops[${slot}] = ${printTapeValue(value)};`),
257
+ ];
258
+ if (hasStatePaint) {
259
+ paints.forEach((paint, paintIndex) => {
260
+ for (const [field, value] of paintFields(paint)) {
261
+ lines.push(` s_svg${id}_paints[${paintIndex}].${field} = ${value};`);
262
+ }
263
+ });
264
+ }
265
+ if (hasStateGradient) {
266
+ gradients.forEach((gradient, entry) => {
267
+ const prefix = ` s_svg${id}_grads[${entry}]`;
268
+ lines.push(`${prefix}.type = ${gradient.type};`, `${prefix}.stop_count = ${gradient.stops.length};`);
269
+ gradient.stops.forEach((stop, stopIndex) => {
270
+ lines.push(`${prefix}.stops[${stopIndex}].color = ${printPaintColor(stop.color)};`, `${prefix}.stops[${stopIndex}].position = ${printTapeValue(stop.offset)};`);
271
+ });
272
+ for (const [field, value] of gradientGeometry(gradient)) {
273
+ lines.push(`${prefix}.${field} = ${value};`);
274
+ }
275
+ });
276
+ }
277
+ return {
278
+ data,
279
+ builder: `static void build_svg${id}(void)\n{\n${lines.join('\n')}\n}`,
280
+ };
281
+ }
282
+ /**
283
+ * Builds a state-driven drawing once, points its node at the tables, and keeps the node's handle for app_update.
284
+ *
285
+ * @param nodeId The node's variable.
286
+ * @param vector The drawing.
287
+ *
288
+ * @returns The C lines.
289
+ */
290
+ export function printStateDrivenVectorWiring(nodeId, vector) {
291
+ const { id, gradients } = vector;
292
+ return [
293
+ ` build_svg${id}();`,
294
+ ` er_node_set_vector_ops(${nodeId}, s_svg${id}_ops, ${vector.tape.length}, ` +
295
+ `s_svg${id}_paints, ${vector.paints.length}, ` +
296
+ `${gradients.length ? `s_svg${id}_grads` : 'NULL'}, ${gradients.length});`,
297
+ ` s_${nodeId} = ${nodeId};`,
298
+ ];
299
+ }
300
+ /**
301
+ * An updateVector call's file-scope tables: its mutable op-tape and its const paints.
302
+ *
303
+ * @param update The call.
304
+ *
305
+ * @returns The C declarations.
306
+ */
307
+ export const printUpdateVectorData = (update) => [
308
+ `static float s_uv${update.id}_ops[${update.tape.length}];`,
309
+ `static const ERVectorPaint s_uv${update.id}_paints[] = ` +
310
+ `{\n${update.paints.map(paint => ' ' + printVectorPaint(paint)).join(',\n')}\n};`,
311
+ ];
312
+ /**
313
+ * An updateVector call as statements: its locals, every tape slot, the hand-over to the node, and the dirty
314
+ * hint. A float edge may be NaN, so it goes through app_vector_dirty, which drops such a hint (a zero-width
315
+ * hint would paint nothing).
316
+ *
317
+ * @param update The call.
318
+ *
319
+ * @returns The C lines, without their indent.
320
+ */
321
+ export function printUpdateVector(update) {
322
+ const { id, node, tape } = update;
323
+ const lines = [
324
+ ...update.locals.map(local => `const float ${local.name} = ${printTapeValue(local.value)};`),
325
+ ...tape.map((value, slot) => `s_uv${id}_ops[${slot}] = ${printTapeValue(value)};`),
326
+ `er_node_set_vector_ops(${node}, s_uv${id}_ops, ${tape.length}, ` +
327
+ `s_uv${id}_paints, ${update.paints.length}, NULL, 0);`,
328
+ ];
329
+ if (update.dirty) {
330
+ const dirtyFn = update.dirty.some(edge => edge.type.kind === 'float')
331
+ ? 'app_vector_dirty'
332
+ : 'er_node_set_vector_dirty_rect';
333
+ lines.push(`${dirtyFn}(${node}, ${update.dirty.map(printExpr).join(', ')});`);
334
+ }
335
+ return lines;
336
+ }
337
+ /**
338
+ * Every drawing's file-scope C, in the order the app declares them: the table declarations, and apart from
339
+ * them the builders of the state-driven drawings (app_update() calls those, so they go ahead of it).
340
+ *
341
+ * @param vectors The drawings.
342
+ *
343
+ * @returns The declarations and the builders, each a block of C.
344
+ */
345
+ export function printVectorBlocks(vectors) {
346
+ const data = [];
347
+ const builders = [];
348
+ for (const vector of vectors) {
349
+ if (vector.kind === 'tables') {
350
+ data.push(...printVectorTables(vector.tables));
351
+ }
352
+ else if (vector.kind === 'drawing') {
353
+ const printed = printStateDrivenVector(vector.vector);
354
+ data.push(...printed.data);
355
+ builders.push(printed.builder);
356
+ }
357
+ else {
358
+ data.push(...printUpdateVectorData(vector.update));
359
+ }
360
+ }
361
+ return { data: data.join('\n\n'), builders: builders.join('\n\n') };
362
+ }
363
+ /**
364
+ * A state-driven drawing's app_update() entry: its tape rebuilt from state, then handed to its node again.
365
+ *
366
+ * @param nodeId The node's variable; its handle is `s_<nodeId>`.
367
+ * @param vector The drawing.
368
+ *
369
+ * @returns The C lines.
370
+ */
371
+ export function printVectorRebuild(nodeId, vector) {
372
+ const { id } = vector;
373
+ const gradientCount = vector.gradients.length;
374
+ return [
375
+ ` build_svg${id}();`,
376
+ ` er_node_set_vector_ops(s_${nodeId}, s_svg${id}_ops, ` +
377
+ `${vector.tape.length}, s_svg${id}_paints, ${vector.paints.length}, ` +
378
+ `${gradientCount ? `s_svg${id}_grads` : 'NULL'}, ` +
379
+ `${gradientCount});`,
380
+ ];
381
+ }
@@ -0,0 +1,127 @@
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 { numberProblem } from './check.mjs';
20
+ /*----------------------------------------------------------------------------------------------------------------------
21
+ - Implementation
22
+ ---------------------------------------------------------------------------------------------------------------------*/
23
+ /**
24
+ * A whole number in the int64 range as a C literal. `String(value)` is JS's shortest spelling that reads back
25
+ * as the same double, which past 2^53 is not the number itself: 4611686018427387904 prints as
26
+ * 4611686018427388000.
27
+ *
28
+ * @param value A whole number in the int64 range.
29
+ *
30
+ * @returns Its C literal.
31
+ */
32
+ export function i64Lit(value) {
33
+ // `-9223372036854775808` is `-` applied to 9223372036854775808, which fits no signed type.
34
+ return value === -(2 ** 63)
35
+ ? '(-9223372036854775807 - 1)'
36
+ : BigInt(value).toString();
37
+ }
38
+ /**
39
+ * A constant as a slot of `cType` holds it: a string literal, a float, a 64-bit or an int literal.
40
+ *
41
+ * @param value The constant.
42
+ * @param cType The slot's kind.
43
+ *
44
+ * @returns The C literal.
45
+ */
46
+ export function cConstant(value, cType) {
47
+ if (cType === 'string')
48
+ return cstr(String(value));
49
+ if (cType === 'float')
50
+ return floatLit(value);
51
+ if (cType === 'i64')
52
+ return i64Lit(Number(value));
53
+ return String(Number(value));
54
+ }
55
+ /**
56
+ * The C type a numeric state, ref, or local slot of `cType` is declared with.
57
+ *
58
+ * @param cType The slot's kind; a string slot has no scalar type.
59
+ *
60
+ * @returns The C type name.
61
+ */
62
+ export function cScalarType(cType) {
63
+ if (cType === 'int')
64
+ return 'int';
65
+ if (cType === 'float')
66
+ return 'float';
67
+ if (cType === 'i64')
68
+ return 'int64_t';
69
+ throw new Error(`AOT internal: no C scalar type for "${cType}"`);
70
+ }
71
+ /**
72
+ * C source with its string and char literals and its comments blanked, so a scan for a call sees only code.
73
+ *
74
+ * @param cSource C source.
75
+ *
76
+ * @returns The source with every literal and comment replaced by a space.
77
+ */
78
+ export const stripCLiterals = (cSource) => cSource.replace(/"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, ' ');
79
+ /**
80
+ * The kind of slot a constant is stored in: string, float (a fractional number), or int (anything else).
81
+ *
82
+ * @param value A compile-time value.
83
+ *
84
+ * @returns Its slot kind.
85
+ */
86
+ export const cTypeOfValue = (value) => typeof value === 'string'
87
+ ? 'string'
88
+ : typeof value === 'number' && !Number.isInteger(value)
89
+ ? 'float'
90
+ : 'int';
91
+ /**
92
+ * Formats a number as a valid C float literal (`1` → `1.0f`, not `1f` which doesn't compile).
93
+ *
94
+ * @param rawValue The value; anything `Number()` converts to a finite float.
95
+ *
96
+ * @returns Its C float literal.
97
+ */
98
+ export function floatLit(rawValue) {
99
+ // The check pass refuses what a float cannot hold; a value that reaches here unchecked fails the same way.
100
+ const problem = numberProblem(rawValue);
101
+ if (problem) {
102
+ throw problem;
103
+ }
104
+ // Write float underflow as 0, since C compilers warn about it.
105
+ const value = Number(rawValue);
106
+ if (Math.fround(value) === 0 && value !== 0)
107
+ return value < 0 ? '-0.0f' : '0.0f';
108
+ // An exponent (`1e+21`) already makes a float literal; `.0` after one would not be C.
109
+ const spelling = String(value);
110
+ return /[.e]/.test(spelling) ? `${spelling}f` : `${spelling}.0f`;
111
+ }
112
+ /**
113
+ * A JS string as a C string literal, with backslashes, quotes, newlines, and tabs escaped.
114
+ *
115
+ * @param text The string.
116
+ *
117
+ * @returns Its C literal, quotes included.
118
+ */
119
+ export const cstr = (text) => {
120
+ // Backslashes first, so the ones added for the other escapes are not doubled.
121
+ const escaped = text
122
+ .replace(/\\/g, '\\\\')
123
+ .replace(/"/g, '\\"')
124
+ .replace(/\n/g, '\\n')
125
+ .replace(/\t/g, '\\t');
126
+ return `"${escaped}"`;
127
+ };
@@ -0,0 +1,165 @@
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 { GRAD_MAX_STOPS } from '../../src/embedded-react/svg-ops.js';
20
+ import { aotError, currentLoc } from './diagnostics.mjs';
21
+ /*----------------------------------------------------------------------------------------------------------------------
22
+ - Constants
23
+ ---------------------------------------------------------------------------------------------------------------------*/
24
+ /** The most breakpoints an interpolation holds (the engine's ER_INTERPOLATE_MAX_POINTS). */
25
+ const MAX_INTERPOLATION_POINTS = 8;
26
+ /** The most stops a <Dial indicatorGradient> holds (the engine's ER_GRADIENT_MAX_STOPS). */
27
+ export const DIAL_MAX_GRADIENT_STOPS = 4;
28
+ /** Where lowering records its checks while a compile runs, or null outside one, when a check runs at once. */
29
+ let recording = null;
30
+ /** How many fallback attempts are running: a check inside one runs at once, so its failure picks the fallback. */
31
+ let attempts = 0;
32
+ /*----------------------------------------------------------------------------------------------------------------------
33
+ - Implementation
34
+ ---------------------------------------------------------------------------------------------------------------------*/
35
+ /**
36
+ * What is wrong with a number the app stores as a float, if anything: every backend refuses NaN, Infinity and
37
+ * a value past the float range.
38
+ *
39
+ * @param rawValue The value; anything `Number()` converts.
40
+ *
41
+ * @returns The error to report, or null for a value a float holds.
42
+ */
43
+ export function numberProblem(rawValue) {
44
+ const value = Number(rawValue);
45
+ if (!Number.isFinite(value)) {
46
+ return aotError(`AOT: a numeric constant folded to ` +
47
+ `${rawValue === undefined ? 'undefined' : String(rawValue)}, which has no C form`, 'the value must be a finite number.');
48
+ }
49
+ if (!Number.isFinite(Math.fround(value))) {
50
+ return aotError(`AOT: the numeric constant ${value} is past the float range`, 'a float holds up to about 3.4e38.');
51
+ }
52
+ return null;
53
+ }
54
+ /**
55
+ * What is wrong with a recorded subject, if anything.
56
+ *
57
+ * @param subject The subject.
58
+ *
59
+ * @returns The error to report, or null when it passes.
60
+ */
61
+ export function checkProblem(subject) {
62
+ switch (subject.kind) {
63
+ case 'number':
64
+ return numberProblem(subject.value);
65
+ case 'interpolationPoints':
66
+ return subject.count > MAX_INTERPOLATION_POINTS
67
+ ? aotError(`AOT: .interpolate() supports up to ${MAX_INTERPOLATION_POINTS} breakpoints ` +
68
+ '(ER_INTERPOLATE_MAX_POINTS)')
69
+ : null;
70
+ case 'textSpans':
71
+ return subject.count > subject.max
72
+ ? aotError(`AOT: a <Text> has ${subject.count} inline segments but the engine renders at most ${subject.max}`, `combine adjacent plain-text segments, or end the sentence right after a styled ` +
73
+ `<Text> (e.g. "A <b>B</b> C <b>D</b>" is 4). If your engine build raised ` +
74
+ `ER_TEXT_MAX_SPANS, set ER_AOT_MAX_TEXT_SPANS to match when running the AOT.`)
75
+ : null;
76
+ case 'gradientStops':
77
+ return subject.count < 2 || subject.count > GRAD_MAX_STOPS
78
+ ? aotError(`AOT: "${subject.attribute}.stops" needs 2..${GRAD_MAX_STOPS} entries (got ${subject.count})`)
79
+ : null;
80
+ case 'dialGradientStops':
81
+ if (subject.count < 2) {
82
+ return aotError('AOT: <Dial indicatorGradient> needs at least two stops (max 4)');
83
+ }
84
+ return subject.count > DIAL_MAX_GRADIENT_STOPS
85
+ ? aotError(`AOT: <Dial indicatorGradient> takes at most ${DIAL_MAX_GRADIENT_STOPS} stops (got ${subject.count})`, "the engine's arc holds 4 (ER_GRADIENT_MAX_STOPS); merge stops that sit close together.")
86
+ : null;
87
+ }
88
+ }
89
+ /**
90
+ * Checks a subject. During a compile it is recorded for the check pass, with where its error would be
91
+ * reported; otherwise, or inside a fallback attempt, it is checked at once.
92
+ *
93
+ * @param subject The subject.
94
+ */
95
+ export function check(subject) {
96
+ if (recording && !attempts) {
97
+ recording.push({ ...subject, loc: currentLoc() });
98
+ return;
99
+ }
100
+ const problem = checkProblem(subject);
101
+ if (problem) {
102
+ throw problem;
103
+ }
104
+ }
105
+ /**
106
+ * Checks a number the app stores as a float (see check).
107
+ *
108
+ * @param value The value.
109
+ */
110
+ export const checkNumber = (value) => check({ kind: 'number', value });
111
+ /**
112
+ * Runs a lowering attempt whose failure picks a fallback, so the checks inside it run at once.
113
+ *
114
+ * @param attempt The attempt.
115
+ *
116
+ * @returns What the attempt returns.
117
+ */
118
+ export function attemptLowering(attempt) {
119
+ attempts++;
120
+ try {
121
+ return attempt();
122
+ }
123
+ finally {
124
+ attempts--;
125
+ }
126
+ }
127
+ /**
128
+ * The check pass: reports the first recorded check that fails, at its location.
129
+ *
130
+ * @param checks The checks, in the order lowering recorded them.
131
+ */
132
+ export function runChecks(checks) {
133
+ for (const recorded of checks) {
134
+ const problem = checkProblem(recorded);
135
+ if (problem) {
136
+ if (recorded.loc) {
137
+ problem.aotLoc = recorded.loc;
138
+ }
139
+ throw problem;
140
+ }
141
+ }
142
+ }
143
+ /**
144
+ * Lowers with its checks recorded rather than run. When lowering fails, the checks recorded before the
145
+ * failure run first, so the first problem in the app is the one reported, as when every check ran at once.
146
+ *
147
+ * @param lower The lowering.
148
+ *
149
+ * @returns What lowering returns, and its checks, in order.
150
+ */
151
+ export function lowerWithChecks(lower) {
152
+ const checks = [];
153
+ const outer = recording;
154
+ recording = checks;
155
+ try {
156
+ return { result: lower(), checks };
157
+ }
158
+ catch (error) {
159
+ runChecks(checks);
160
+ throw error;
161
+ }
162
+ finally {
163
+ recording = outer;
164
+ }
165
+ }