embedded-react 0.16.0 → 0.18.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 (41) hide show
  1. package/aot/compiler/animations.mjs +102 -34
  2. package/aot/compiler/assemble.mjs +169 -31
  3. package/aot/compiler/boot.mjs +441 -0
  4. package/aot/compiler/branch-merge.mjs +315 -0
  5. package/aot/compiler/c/animations.mjs +90 -16
  6. package/aot/compiler/c/boot.mjs +127 -0
  7. package/aot/compiler/c/expressions.mjs +63 -8
  8. package/aot/compiler/c/nodes.mjs +34 -13
  9. package/aot/compiler/c/statements.mjs +92 -15
  10. package/aot/compiler/check.mjs +32 -3
  11. package/aot/compiler/collect.mjs +95 -9
  12. package/aot/compiler/control-flow.mjs +43 -18
  13. package/aot/compiler/diagnostics.mjs +33 -0
  14. package/aot/compiler/elements/dial.mjs +8 -7
  15. package/aot/compiler/elements/props.mjs +19 -9
  16. package/aot/compiler/elements/text-input.mjs +7 -2
  17. package/aot/compiler/expressions.mjs +132 -10
  18. package/aot/compiler/handlers.mjs +62 -24
  19. package/aot/compiler/ir/boot.mjs +16 -0
  20. package/aot/compiler/ir/nodes.mjs +28 -4
  21. package/aot/compiler/ir/reads.mjs +351 -0
  22. package/aot/compiler/keyboard.mjs +35 -21
  23. package/aot/compiler/lower.mjs +40 -11
  24. package/aot/compiler/nodes.mjs +22 -9
  25. package/aot/compiler/options.mjs +63 -12
  26. package/aot/compiler/static-eval.mjs +314 -56
  27. package/aot/compiler/style-text.mjs +201 -19
  28. package/aot/compiler/svg.mjs +7 -3
  29. package/aot/style-map.mjs +9 -11
  30. package/assets/bake-svg.mjs +3 -2
  31. package/package.json +1 -1
  32. package/sim/embedded-react.wasm +0 -0
  33. package/src/embedded-react/Animated.js +41 -0
  34. package/src/embedded-react/Button.js +3 -4
  35. package/src/embedded-react/Pressable.js +59 -0
  36. package/src/embedded-react/TouchableOpacity.js +6 -9
  37. package/src/embedded-react/index.d.ts +118 -30
  38. package/src/embedded-react/index.js +1 -1
  39. package/src/embedded-react/named-colors.js +37 -0
  40. package/src/embedded-react/svg-ops.js +13 -16
  41. package/src/host-config.js +50 -8
@@ -19,7 +19,8 @@
19
19
  import { attemptLowering, checkNumber } from './check.mjs';
20
20
  import { traverse } from '@babel/core';
21
21
  import { aotError, locateError, withLoc } from './diagnostics.mjs';
22
- import { evalStatic, foldScope } from './static-eval.mjs';
22
+ import { bootSlotOf, containsBoot, foldBoot, isBoot, wholeBootValue, } from './boot.mjs';
23
+ import { evalStatic, foldScope, hasBinding } from './static-eval.mjs';
23
24
  import { lowerGestureField } from './pan-responder.mjs';
24
25
  import { toCExpr } from './c/expressions.mjs';
25
26
  import { printText } from './c/text.mjs';
@@ -45,6 +46,14 @@ const CHECKED_HELPER = {
45
46
  '-': 'sub',
46
47
  '*': 'mul',
47
48
  };
49
+ /** Expressions an app may write over values worked out at boot, which then read as one boot slot. */
50
+ const WHOLE_BOOT_TYPES = new Set([
51
+ 'BinaryExpression',
52
+ 'UnaryExpression',
53
+ 'LogicalExpression',
54
+ 'ConditionalExpression',
55
+ 'CallExpression',
56
+ ]);
48
57
  /** The range of a C int. */
49
58
  const INT_MIN = -(2 ** 31);
50
59
  export const INT_MAX = 2 ** 31 - 1;
@@ -143,7 +152,7 @@ export function findShadowedClockCalls(ast) {
143
152
  */
144
153
  export function staticInt(node, env) {
145
154
  try {
146
- const value = evalStatic(node, foldScope(env, env.consts ?? {}));
155
+ const value = evalStatic(node, foldScope(env, env.consts ?? {}), 'strict');
147
156
  return Number.isInteger(value) ? value : null;
148
157
  }
149
158
  catch {
@@ -182,6 +191,87 @@ function numberSource(value, loc) {
182
191
  }
183
192
  return { kind: 'number', value, loc };
184
193
  }
194
+ /**
195
+ * A read of a value worked out at boot. One boot cannot work out is taken at the build's panel instead, which
196
+ * the panel at boot must then give too.
197
+ *
198
+ * @param value The value.
199
+ * @param loc Where it is read.
200
+ *
201
+ * @returns Its source.
202
+ */
203
+ function bootSource(value, loc) {
204
+ const slot = bootSlotOf(value);
205
+ if (slot) {
206
+ return { kind: 'fixed', expr: { kind: 'boot', slot, type: slot.type }, loc };
207
+ }
208
+ const buildValue = foldBoot(value);
209
+ if (typeof buildValue === 'number')
210
+ return numberSource(buildValue, loc);
211
+ if (typeof buildValue === 'string') {
212
+ return { kind: 'string', value: buildValue, loc };
213
+ }
214
+ if (typeof buildValue === 'boolean') {
215
+ return { kind: 'boolean', value: buildValue, loc };
216
+ }
217
+ throw new Error('AOT: a value derived from the panel size cannot be used in a dynamic expression');
218
+ }
219
+ /**
220
+ * Whether an expression names a binding that is, or holds, a value worked out at boot.
221
+ *
222
+ * @param node The expression.
223
+ * @param scope The constants it reads.
224
+ *
225
+ * @returns True when it does.
226
+ */
227
+ function readsBootName(node, scope) {
228
+ if (typeof node !== 'object' || node === null)
229
+ return false;
230
+ if (Array.isArray(node))
231
+ return node.some(item => readsBootName(item, scope));
232
+ const typed = node;
233
+ if (typed.type === 'Identifier') {
234
+ return hasBinding(scope, typed.name) && containsBoot(scope[typed.name]);
235
+ }
236
+ // A member's name and an object key are not reads.
237
+ if (typed.type === 'MemberExpression') {
238
+ return (readsBootName(typed.object, scope) ||
239
+ (typed.computed && readsBootName(typed.property, scope)));
240
+ }
241
+ if (typed.type === 'ObjectProperty' && !typed.computed) {
242
+ return readsBootName(typed.value, scope);
243
+ }
244
+ return Object.entries(typed).some(([key, value]) => key !== 'loc' && readsBootName(value, scope));
245
+ }
246
+ /**
247
+ * An expression that depends only on the panel, read as a whole from its boot slot, so it is worked out once and
248
+ * in double precision. Null for one that also reads state, or that boot cannot work out.
249
+ *
250
+ * @param node The expression.
251
+ * @param env The expression environment.
252
+ * @param loc Where it is.
253
+ *
254
+ * @returns Its source, or null.
255
+ */
256
+ function wholeBootSource(node, env, loc) {
257
+ const scope = foldScope(env, env.consts ?? {});
258
+ if (!readsBootName(node, scope))
259
+ return null;
260
+ let value;
261
+ try {
262
+ value = evalStatic(node, scope, 'boot');
263
+ }
264
+ catch {
265
+ return null;
266
+ }
267
+ if (!isBoot(value) || !value.lowerable)
268
+ return null;
269
+ const whole = wholeBootValue(node, scope, value);
270
+ const slot = whole && bootSlotOf(whole);
271
+ return slot
272
+ ? { kind: 'fixed', expr: { kind: 'boot', slot, type: slot.type }, loc }
273
+ : null;
274
+ }
185
275
  /**
186
276
  * A compile-time string.
187
277
  *
@@ -1013,6 +1103,25 @@ const binarySource = (node, left, right, env) => ({
1013
1103
  rightIsNumber: isWrittenAsNumber(node.right, env),
1014
1104
  loc: node.loc?.start,
1015
1105
  });
1106
+ /**
1107
+ * Whether `node` is the handler's event, or its `nativeEvent` as React Native code reads it.
1108
+ *
1109
+ * @param node The expression.
1110
+ * @param event The event parameter's name, if the handler has one.
1111
+ *
1112
+ * @returns True for `<event>` or `<event>.nativeEvent`.
1113
+ */
1114
+ function isEventRoot(node, event) {
1115
+ if (!event)
1116
+ return false;
1117
+ if (node.type === 'Identifier')
1118
+ return node.name === event;
1119
+ return (node.type === 'MemberExpression' &&
1120
+ !node.computed &&
1121
+ node.object.type === 'Identifier' &&
1122
+ node.object.name === event &&
1123
+ node.property.name === 'nativeEvent');
1124
+ }
1016
1125
  /**
1017
1126
  * Lowers one JS expression to its source: names resolved, constants folded, and each operand lowered and typed
1018
1127
  * in turn, so an error in it is reported before anything after it.
@@ -1024,6 +1133,12 @@ const binarySource = (node, left, right, env) => ({
1024
1133
  */
1025
1134
  function sourceOf(node, env) {
1026
1135
  const loc = node.loc?.start;
1136
+ // An expression that depends only on the panel is read from a slot worked out at boot, in doubles as JS.
1137
+ const whole = WHOLE_BOOT_TYPES.has(node.type)
1138
+ ? wholeBootSource(node, env, loc)
1139
+ : null;
1140
+ if (whole)
1141
+ return whole;
1027
1142
  const operand = (operandNode) => lowerSource(operandNode, env).source;
1028
1143
  switch (node.type) {
1029
1144
  case 'NumericLiteral':
@@ -1044,8 +1159,10 @@ function sourceOf(node, env) {
1044
1159
  }
1045
1160
  return { kind: 'state', state: stateRecord, loc };
1046
1161
  }
1047
- if (node.name in env.consts) {
1162
+ if (hasBinding(env.consts, node.name)) {
1048
1163
  const constValue = env.consts[node.name];
1164
+ if (isBoot(constValue))
1165
+ return bootSource(constValue, loc);
1049
1166
  if (typeof constValue === 'number')
1050
1167
  return numberSource(constValue, loc);
1051
1168
  if (typeof constValue === 'string') {
@@ -1110,7 +1227,9 @@ function sourceOf(node, env) {
1110
1227
  case 'MemberExpression': {
1111
1228
  // Static fold: member access that resolves to a compile-time constant (e.g., a .map item's `.key`).
1112
1229
  try {
1113
- const constValue = evalStatic(node, foldScope(env, env.consts ?? {}));
1230
+ const constValue = evalStatic(node, foldScope(env, env.consts ?? {}), 'boot');
1231
+ if (isBoot(constValue))
1232
+ return bootSource(constValue, loc);
1114
1233
  // A number with no float form falls through too, so its check runs now, not in the check pass.
1115
1234
  if (typeof constValue === 'number') {
1116
1235
  return attemptLowering(() => numberSource(constValue, loc));
@@ -1179,12 +1298,15 @@ function sourceOf(node, env) {
1179
1298
  if (object.type === 'Identifier' && env.gesture === object.name && prop) {
1180
1299
  return fixed(lowerGestureField(prop, env.pan));
1181
1300
  }
1182
- // `<event>.layout.x / .y / .width / .height` — the onLayout rect.
1301
+ // `<event>.layout.x / .y / .width / .height` — the onLayout rect, also read as
1302
+ // `<event>.nativeEvent.layout.…` as in React Native.
1183
1303
  if (object.type === 'MemberExpression' &&
1184
1304
  !object.computed &&
1185
- object.object.type === 'Identifier' &&
1186
- env.event === object.object.name &&
1187
- object.property.name === 'layout') {
1305
+ object.property.name === 'layout' &&
1306
+ isEventRoot(object.object, env.event)) {
1307
+ if (!env.layout) {
1308
+ throw aotError('AOT: only an onLayout event carries a layout rect', 'read e.layout (or e.nativeEvent.layout) inside an onLayout handler.');
1309
+ }
1188
1310
  if (!LAYOUT_FIELDS.has(prop)) {
1189
1311
  throw new Error(`AOT: unknown onLayout rect field "${prop}" (use x / y / width / height)`);
1190
1312
  }
@@ -1387,9 +1509,9 @@ function lowerTextParts(node, env, scope, isOperand = false) {
1387
1509
  parts: [{ kind: 'literal', text: isOperand ? 'undefined' : '' }],
1388
1510
  };
1389
1511
  }
1390
- // A compile-time constant becomes literal text.
1512
+ // A compile-time constant becomes literal text; a value worked out at boot is a runtime value.
1391
1513
  try {
1392
- const constValue = evalStatic(node, scope);
1514
+ const constValue = evalStatic(node, scope, 'strict');
1393
1515
  return {
1394
1516
  isString: typeof constValue === 'string',
1395
1517
  parts: [
@@ -17,7 +17,7 @@
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
19
  import { parseColor, parsePath } from '../../src/embedded-react/svg-ops.js';
20
- import { aotError, withLoc } from './diagnostics.mjs';
20
+ import { aotError, constantText, withLoc } from './diagnostics.mjs';
21
21
  import { evalStatic } from './static-eval.mjs';
22
22
  import { mix64Error, staticInt, isTime64, constDivisor, emitSourcedWide, lowerSource, lowerExpr, lowerExprWide, lowerText, } from './expressions.mjs';
23
23
  import { isFn } from './collect.mjs';
@@ -25,7 +25,7 @@ import { isAnimatedCall, resolveAnim, animValues, lowerAnimateStart, stopWaitOwn
25
25
  import { svgNum, CAP_MAP, JOIN_MAP, arcTape, circleTape, rectTape, lineTape, checkedTapeNumber, checkVectorPaints, vectorPaintOf, } from './svg.mjs';
26
26
  import { armedFlag } from './c/functions.mjs';
27
27
  import { toCExpr } from './c/expressions.mjs';
28
- import { INT, isConvertible64, isIntSlot, isTime, refType, slotOf, } from './ir/types.mjs';
28
+ import { FLOAT, INT, isConvertible64, isIntSlot, isTime, refType, slotOf, } from './ir/types.mjs';
29
29
  /*----------------------------------------------------------------------------------------------------------------------
30
30
  - Constants
31
31
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -62,9 +62,13 @@ function lowerListOp(listState, nextList, env) {
62
62
  firstElement.argument.name !== listState.name) {
63
63
  throw new Error(`AOT: a list literal must spread the current list first: [...${listState.name}, item]`);
64
64
  }
65
- // Each appended object literal fills the fields of the next free slot; a full list drops it.
65
+ // Each appended object literal fills every field of the next free slot; a full list drops it. A field it
66
+ // leaves out is reset to 0 or "", as an initial item's is, so the slot keeps nothing from a cleared item.
66
67
  const statements = [];
67
68
  for (const item of appendedItems) {
69
+ if (!item) {
70
+ throw aotError('AOT: a list literal has an empty slot');
71
+ }
68
72
  if (item.type !== 'ObjectExpression') {
69
73
  throw new Error('AOT: appended list items must be object literals');
70
74
  }
@@ -76,10 +80,22 @@ function lowerListOp(listState, nextList, env) {
76
80
  const values = [];
77
81
  for (const field of struct.fields) {
78
82
  const valueNode = props.get(field.key);
79
- if (!valueNode)
80
- continue;
81
- if (field.kind === 'string') {
82
- values.push({ field, text: lowerText(valueNode, env) });
83
+ if (!valueNode) {
84
+ values.push(field.kind === 'string'
85
+ ? { field, text: { parts: [] } }
86
+ : {
87
+ field,
88
+ value: {
89
+ kind: 'number',
90
+ value: 0,
91
+ type: field.kind === 'float' ? FLOAT : INT,
92
+ },
93
+ });
94
+ }
95
+ else if (field.kind === 'string') {
96
+ const text = lowerText(valueNode, env);
97
+ checkConstantFits(text, `field "${field.key}" of list state "${listState.name}"`, env);
98
+ values.push({ field, text });
83
99
  }
84
100
  else {
85
101
  values.push({
@@ -207,6 +223,24 @@ const refRead = (ref) => ({
207
223
  ref,
208
224
  type: refType(ref),
209
225
  });
226
+ /**
227
+ * Refuses a constant string too long for the buffer it is written into, which C would cut short. A string
228
+ * built at run time is checked when it is written instead.
229
+ *
230
+ * @param text The text written.
231
+ * @param what What it is written into, for the error.
232
+ * @param env The expression environment.
233
+ */
234
+ function checkConstantFits(text, what, env) {
235
+ const constant = constantText(text);
236
+ if (constant === null) {
237
+ return;
238
+ }
239
+ const bytes = Buffer.byteLength(constant, 'utf8');
240
+ if (bytes >= env.caps.listStrCap) {
241
+ throw aotError(`AOT: ${what} is set to a ${bytes}-byte string, but a string holds ${env.caps.listStrCap - 1} bytes`, 'raise ER_AOT_LIST_STR_CAP (the listStrCap option), or shorten the string.');
242
+ }
243
+ }
210
244
  /**
211
245
  * Lowers a write of an expression into a scalar state slot: text for a string buffer (so a `+` chain keeps its
212
246
  * parts), a plain value otherwise.
@@ -229,10 +263,12 @@ function lowerScalarSet(scalarState, valueNode, env) {
229
263
  value: storeValue(value, scalarState.cType),
230
264
  };
231
265
  }
266
+ const text = lowerText(valueNode, env);
267
+ checkConstantFits(text, `state "${scalarState.name}"`, env);
232
268
  return {
233
269
  kind: 'setStateText',
234
270
  state: scalarState,
235
- text: lowerText(valueNode, env),
271
+ text,
236
272
  };
237
273
  }
238
274
  /**
@@ -290,15 +326,12 @@ function imperativeShape(shapeNode, env, tag) {
290
326
  throw aotError(`AOT: updateVector "${key}" needs ${required} numbers (got ${elements.length})`, shapeHint);
291
327
  }
292
328
  // A hole (`[1, , 3]`) has no value to lower; an optional rect radius left out is just a shorter array.
293
- const values = elements.slice(0, count);
294
- const hole = values.findIndex(valueNode => valueNode == null);
295
- if (hole >= 0) {
296
- throw aotError(`AOT: updateVector "${key}" has an empty slot at position ${hole}`, shapeHint);
297
- }
298
- return values.map(valueNode => ({
299
- kind: 'float',
300
- value: lowerExpr(valueNode, env),
301
- }));
329
+ return elements.slice(0, count).map((valueNode, position) => {
330
+ if (!valueNode) {
331
+ throw aotError(`AOT: updateVector "${key}" has an empty slot at position ${position}`, shapeHint);
332
+ }
333
+ return { kind: 'float', value: lowerExpr(valueNode, env) };
334
+ });
302
335
  };
303
336
  let geometry;
304
337
  if (props.arc) {
@@ -397,9 +430,12 @@ function lowerUpdateVector(expr, env, ctx) {
397
430
  if (dirtyArg.type !== 'ArrayExpression' || dirtyArg.elements.length < 4) {
398
431
  throw new Error('AOT: updateVector dirtyRect must be a [x, y, w, h] array literal');
399
432
  }
400
- update.dirty = dirtyArg.elements
401
- .slice(0, 4)
402
- .map(edgeNode => lowerExpr(edgeNode, env));
433
+ update.dirty = dirtyArg.elements.slice(0, 4).map((edgeNode, edge) => {
434
+ if (!edgeNode) {
435
+ throw aotError(`AOT: updateVector dirtyRect has an empty slot at position ${edge}`);
436
+ }
437
+ return lowerExpr(edgeNode, env);
438
+ });
403
439
  }
404
440
  return update;
405
441
  }
@@ -793,6 +829,9 @@ export function lowerStmts(statements, env, state, ctx) {
793
829
  // Any other initializer must lower to a number, a boolean or a string.
794
830
  const { source: initSource, expr: initExpr } = lowerSource(decl.init, env);
795
831
  if (initExpr.type.kind === 'string') {
832
+ if (initExpr.kind === 'string') {
833
+ checkConstantFits({ parts: [{ kind: 'literal', text: initExpr.value }] }, `local "${decl.id.name}"`, env);
834
+ }
796
835
  // Copy into a buffer of its own; aliasing a state slot would hide a self-read like `setLabel(t + '!')`.
797
836
  if (isHoisted) {
798
837
  ctx.hoist.decls.push({
@@ -904,10 +943,9 @@ export function lowerEffect(effect, env, state, out) {
904
943
  const statements = body.type === 'BlockStatement'
905
944
  ? body.body
906
945
  : [{ type: 'ExpressionStatement', expression: body }];
907
- // A mount-once effect (no dependency list, or `[]`) runs once, from er_app_build.
908
- const isMount = !effect.deps ||
909
- (effect.deps.type === 'ArrayExpression' &&
910
- effect.deps.elements.length === 0);
946
+ // A mount-once effect (`[]`) runs once, from er_app_build.
947
+ const isMount = effect.deps.type === 'ArrayExpression' &&
948
+ effect.deps.elements.length === 0;
911
949
  if (isMount) {
912
950
  const ctx = {
913
951
  stateChanged: false,
@@ -0,0 +1,16 @@
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
+ export {};
@@ -13,20 +13,44 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Imports
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ import { isBootOnlyNode, isBootOnlyVector } from './reads.mjs';
16
20
  /*----------------------------------------------------------------------------------------------------------------------
17
21
  - Implementation
18
22
  ---------------------------------------------------------------------------------------------------------------------*/
19
23
  /**
20
- * Whether state drives any of a node's props, text or image, so it keeps a handle and app_update() sets its
21
- * props again.
24
+ * Whether any of a node's props, text, or image is a runtime value rather than a constant.
22
25
  *
23
26
  * @param node The node.
24
27
  *
25
- * @returns True when state drives it.
28
+ * @returns True when one is.
26
29
  */
27
- export const isStateDriven = (node) => (node.text?.parts.some(part => part.kind !== 'literal') ?? false) ||
30
+ export const hasRuntimeProps = (node) => (node.text?.parts.some(part => part.kind !== 'literal') ?? false) ||
28
31
  node.stateProps.length > 0 ||
29
32
  node.image?.kind === 'value';
33
+ /**
34
+ * Whether state drives any of a node's props, text or image, so it keeps a handle and app_update() sets its
35
+ * props again. Props that read-only values worked out at boot are set once, by er_app_build().
36
+ *
37
+ * @param node The node.
38
+ *
39
+ * @returns True when state drives it.
40
+ */
41
+ export const isStateDriven = (node) => hasRuntimeProps(node) && !isBootOnlyNode(node);
42
+ /**
43
+ * The drawing state drives on a node if it has one: a drawing that reads only values worked out at boot is
44
+ * built once, by er_app_build().
45
+ *
46
+ * @param node The node.
47
+ *
48
+ * @returns The drawing, or null.
49
+ */
50
+ export function updatedVectorOf(node) {
51
+ const vector = stateDrivenVectorOf(node);
52
+ return vector && !isBootOnlyVector(vector) ? vector : null;
53
+ }
30
54
  /**
31
55
  * The drawing state drives on a node, if it has one.
32
56
  *