embedded-react 0.17.0 → 0.19.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 (47) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +1 -1
  3. package/aot/compile.mjs +2 -2
  4. package/aot/compiler/animations.mjs +102 -34
  5. package/aot/compiler/assemble.mjs +27 -5
  6. package/aot/compiler/branch-merge.mjs +5 -9
  7. package/aot/compiler/c/animations.mjs +90 -16
  8. package/aot/compiler/c/nodes.mjs +20 -11
  9. package/aot/compiler/c/statements.mjs +59 -11
  10. package/aot/compiler/check.mjs +32 -3
  11. package/aot/compiler/collect.mjs +46 -2
  12. package/aot/compiler/control-flow.mjs +26 -14
  13. package/aot/compiler/diagnostics.mjs +33 -0
  14. package/aot/compiler/elements/dial.mjs +1 -3
  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 +29 -7
  18. package/aot/compiler/handlers.mjs +62 -24
  19. package/aot/compiler/keyboard.mjs +35 -21
  20. package/aot/compiler/lower.mjs +3 -3
  21. package/aot/compiler/nodes.mjs +16 -8
  22. package/aot/compiler/options.mjs +63 -12
  23. package/aot/compiler/static-eval.mjs +36 -4
  24. package/aot/compiler/style-text.mjs +35 -12
  25. package/aot/compiler/svg.mjs +7 -3
  26. package/aot/screenshot-smoke.mjs +3 -3
  27. package/aot/style-map.mjs +9 -11
  28. package/assets/bake-svg.mjs +3 -2
  29. package/assets/build-builtin-font.mjs +3 -3
  30. package/assets/emit-c.mjs +6 -4
  31. package/assets/emit-container.mjs +1 -1
  32. package/build.mjs +2 -2
  33. package/compile-bin.mjs +2 -2
  34. package/hotreload/protocol.mjs +1 -1
  35. package/pack-container.mjs +3 -3
  36. package/package.json +7 -7
  37. package/sim/embedded-react.wasm +0 -0
  38. package/src/embedded-react/Animated.js +41 -0
  39. package/src/embedded-react/Button.js +3 -4
  40. package/src/embedded-react/FlatList.js +1 -1
  41. package/src/embedded-react/Pressable.js +59 -0
  42. package/src/embedded-react/TouchableOpacity.js +6 -9
  43. package/src/embedded-react/index.d.ts +118 -30
  44. package/src/embedded-react/index.js +1 -1
  45. package/src/embedded-react/named-colors.js +37 -0
  46. package/src/embedded-react/svg-ops.js +13 -16
  47. package/src/host-config.js +50 -8
@@ -17,7 +17,7 @@
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
19
  import { colorLiteral } from '../../style-map.mjs';
20
- import { aotError } from '../diagnostics.mjs';
20
+ import { aotError, checkEngineString, constantText } from '../diagnostics.mjs';
21
21
  import { evalStatic } from '../static-eval.mjs';
22
22
  import { lowerExpr, lowerText } from '../expressions.mjs';
23
23
  import { isFn } from '../collect.mjs';
@@ -83,6 +83,7 @@ export function emitTextInput(element, scope, out, env, state) {
83
83
  }
84
84
  else if (name === 'placeholder') {
85
85
  placeholder = String(evalStatic(node, scope));
86
+ checkEngineString(placeholder, 'ER_PLACEHOLDER_MAX', 'a <TextInput> placeholder');
86
87
  }
87
88
  else if (name === 'placeholderTextColor') {
88
89
  staticAssigns.push({
@@ -124,6 +125,10 @@ export function emitTextInput(element, scope, out, env, state) {
124
125
  throw aotError(`AOT: <TextInput> prop "${name}" is not supported`);
125
126
  }
126
127
  }
128
+ const text = valueNode ? lowerText(valueNode, env, scope) : null;
129
+ if (text) {
130
+ checkEngineString(constantText(text), 'ER_TEXT_MAX', 'a <TextInput> value');
131
+ }
127
132
  // value → the input's text buffer (er_node_set_props → er_text_input_set_text): static literal, or a
128
133
  // state-driven value re-synced each app_update.
129
134
  const node = {
@@ -132,7 +137,7 @@ export function emitTextInput(element, scope, out, env, state) {
132
137
  constantProps: staticAssigns,
133
138
  stateProps: dynAssigns,
134
139
  placeholder,
135
- text: valueNode ? lowerText(valueNode, env, scope) : null,
140
+ text,
136
141
  image: null,
137
142
  spans: null,
138
143
  children: [],
@@ -20,7 +20,7 @@ import { attemptLowering, checkNumber } from './check.mjs';
20
20
  import { traverse } from '@babel/core';
21
21
  import { aotError, locateError, withLoc } from './diagnostics.mjs';
22
22
  import { bootSlotOf, containsBoot, foldBoot, isBoot, wholeBootValue, } from './boot.mjs';
23
- import { evalStatic, foldScope } from './static-eval.mjs';
23
+ import { evalStatic, foldScope, hasBinding } from './static-eval.mjs';
24
24
  import { lowerGestureField } from './pan-responder.mjs';
25
25
  import { toCExpr } from './c/expressions.mjs';
26
26
  import { printText } from './c/text.mjs';
@@ -231,7 +231,7 @@ function readsBootName(node, scope) {
231
231
  return node.some(item => readsBootName(item, scope));
232
232
  const typed = node;
233
233
  if (typed.type === 'Identifier') {
234
- return typed.name in scope && containsBoot(scope[typed.name]);
234
+ return hasBinding(scope, typed.name) && containsBoot(scope[typed.name]);
235
235
  }
236
236
  // A member's name and an object key are not reads.
237
237
  if (typed.type === 'MemberExpression') {
@@ -1103,6 +1103,25 @@ const binarySource = (node, left, right, env) => ({
1103
1103
  rightIsNumber: isWrittenAsNumber(node.right, env),
1104
1104
  loc: node.loc?.start,
1105
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
+ }
1106
1125
  /**
1107
1126
  * Lowers one JS expression to its source: names resolved, constants folded, and each operand lowered and typed
1108
1127
  * in turn, so an error in it is reported before anything after it.
@@ -1140,7 +1159,7 @@ function sourceOf(node, env) {
1140
1159
  }
1141
1160
  return { kind: 'state', state: stateRecord, loc };
1142
1161
  }
1143
- if (node.name in env.consts) {
1162
+ if (hasBinding(env.consts, node.name)) {
1144
1163
  const constValue = env.consts[node.name];
1145
1164
  if (isBoot(constValue))
1146
1165
  return bootSource(constValue, loc);
@@ -1279,12 +1298,15 @@ function sourceOf(node, env) {
1279
1298
  if (object.type === 'Identifier' && env.gesture === object.name && prop) {
1280
1299
  return fixed(lowerGestureField(prop, env.pan));
1281
1300
  }
1282
- // `<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.
1283
1303
  if (object.type === 'MemberExpression' &&
1284
1304
  !object.computed &&
1285
- object.object.type === 'Identifier' &&
1286
- env.event === object.object.name &&
1287
- 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
+ }
1288
1310
  if (!LAYOUT_FIELDS.has(prop)) {
1289
1311
  throw new Error(`AOT: unknown onLayout rect field "${prop}" (use x / y / width / height)`);
1290
1312
  }
@@ -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,
@@ -17,7 +17,7 @@
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
19
  import { parseColor } from '../../src/embedded-react/svg-ops.js';
20
- import { aotError } from './diagnostics.mjs';
20
+ import { aotError, withLoc } from './diagnostics.mjs';
21
21
  import { evalStatic } from './static-eval.mjs';
22
22
  /*----------------------------------------------------------------------------------------------------------------------
23
23
  - Implementation
@@ -89,28 +89,13 @@ function lowerKey(key, layerIndex) {
89
89
  };
90
90
  }
91
91
  /**
92
- * Lowers a module-level `setKeyboardConfig({...})`, which customizes the on-screen keyboard (colors/sizes, and
93
- * optionally a full layout) from the app with no engine edit. The config must be statically foldable; omit
94
- * `layers` to keep the built-in QWERTY.
92
+ * Lowers the argument of a `setKeyboardConfig(...)` call, its AOT errors located at it.
95
93
  *
96
- * @param program The parsed module.
94
+ * @param configArg The call's config argument.
97
95
  *
98
- * @returns The config, or null when the module has none.
96
+ * @returns The config.
99
97
  */
100
- export function lowerKeyboardConfig(program) {
101
- // Find the first top-level setKeyboardConfig(...) call; without one, the built-in keyboard stays as is.
102
- let configArg = null;
103
- for (const statement of program.body) {
104
- if (statement.type === 'ExpressionStatement' &&
105
- statement.expression.type === 'CallExpression' &&
106
- statement.expression.callee.type === 'Identifier' &&
107
- statement.expression.callee.name === 'setKeyboardConfig') {
108
- configArg = statement.expression.arguments[0];
109
- break;
110
- }
111
- }
112
- if (!configArg)
113
- return null;
98
+ const lowerConfig = withLoc((configArg) => {
114
99
  // Fold the config object at compile time.
115
100
  let config;
116
101
  try {
@@ -122,13 +107,19 @@ export function lowerKeyboardConfig(program) {
122
107
  if (config == null || typeof config !== 'object') {
123
108
  throw aotError('AOT: setKeyboardConfig(...) needs a config object');
124
109
  }
125
- // Lower the layout when the app gives one, layer by layer and row by row.
110
+ // Lower the layout when the app gives one, layer by layer and row by row; C has no empty table.
126
111
  let layers = null;
127
112
  if (Array.isArray(config.layers)) {
113
+ if (!config.layers.length) {
114
+ throw aotError('AOT: setKeyboardConfig `layers` needs at least one layer', 'omit `layers` to keep the built-in QWERTY.');
115
+ }
128
116
  layers = config.layers.map((layer, layerIndex) => {
129
117
  if (!Array.isArray(layer)) {
130
118
  throw aotError('AOT: setKeyboardConfig `layers[i]` must be an array of rows');
131
119
  }
120
+ if (!layer.length) {
121
+ throw aotError(`AOT: setKeyboardConfig \`layers[${layerIndex}]\` needs at least one row`);
122
+ }
132
123
  return layer.map(row => {
133
124
  if (!Array.isArray(row) || !row.length) {
134
125
  throw aotError('AOT: each keyboard row must be a non-empty array of keys');
@@ -149,4 +140,27 @@ export function lowerKeyboardConfig(program) {
149
140
  keyActiveColor: kbdColor(config.keyActiveColor),
150
141
  labelColor: kbdColor(config.labelColor),
151
142
  };
143
+ });
144
+ /**
145
+ * Lowers a module-level `setKeyboardConfig({...})`, which customizes the on-screen keyboard (colors/sizes, and
146
+ * optionally a full layout) from the app with no engine edit. The config must be statically foldable; omit
147
+ * `layers` to keep the built-in QWERTY.
148
+ *
149
+ * @param program The parsed module.
150
+ *
151
+ * @returns The config, or null when the module has none.
152
+ */
153
+ export function lowerKeyboardConfig(program) {
154
+ // Find the first top-level setKeyboardConfig(...) call; without one, the built-in keyboard stays as is.
155
+ let configArg = null;
156
+ for (const statement of program.body) {
157
+ if (statement.type === 'ExpressionStatement' &&
158
+ statement.expression.type === 'CallExpression' &&
159
+ statement.expression.callee.type === 'Identifier' &&
160
+ statement.expression.callee.name === 'setKeyboardConfig') {
161
+ configArg = statement.expression.arguments[0];
162
+ break;
163
+ }
164
+ }
165
+ return configArg ? lowerConfig(configArg) : null;
152
166
  }
@@ -18,7 +18,7 @@
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
19
  import { checkNumber, lowerWithChecks, runChecks } from './check.mjs';
20
20
  import { aotError } from './diagnostics.mjs';
21
- import { evalStatic, withUndefined } from './static-eval.mjs';
21
+ import { evalStatic, setBinding, withUndefined } from './static-eval.mjs';
22
22
  import { abandonBoot, beginBoot, endBoot, setBootLowering } from './boot.mjs';
23
23
  import { findShadowedClockCalls, emitSourcedWide, lowerExpr, } from './expressions.mjs';
24
24
  import { findComponent, declaredNames, moduleScope, collectState, findReturnJSX, collectComponents, collectHelpers, collectImageImports, collectSvgImports, collectCallbacks, collectMemos, collectEffects, bindConst, } from './collect.mjs';
@@ -205,7 +205,7 @@ function lowerProgram(src, opts, wide, stores) {
205
205
  if (decl.id.type !== 'Identifier' || !decl.init)
206
206
  continue;
207
207
  try {
208
- scope[decl.id.name] = bindConst(decl.id.name, evalStatic(decl.init, withUndefined(scope), 'boot'));
208
+ setBinding(scope, decl.id.name, bindConst(decl.id.name, evalStatic(decl.init, withUndefined(scope), 'boot')));
209
209
  }
210
210
  catch {
211
211
  // A dynamic const must hide a same-named module const, or the JSX quietly renders the module value.
@@ -258,7 +258,7 @@ function lowerProgram(src, opts, wide, stores) {
258
258
  // Before emit, fold each memo or inline its C expression at each use (no cache needed: dep tracking re-applies).
259
259
  for (const [name, expr] of memos) {
260
260
  try {
261
- scope[name] = bindConst(name, evalStatic(expr, scope, 'boot'));
261
+ setBinding(scope, name, bindConst(name, evalStatic(expr, scope, 'boot')));
262
262
  }
263
263
  catch {
264
264
  const cExpr = emitSourcedWide(expr, env);
@@ -18,7 +18,7 @@
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
19
  import { checkNumber } from './check.mjs';
20
20
  import { NODE_TYPES } from '../style-map.mjs';
21
- import { aotError, withLoc } from './diagnostics.mjs';
21
+ import { aotError, checkEngineString, constantText, withLoc, } from './diagnostics.mjs';
22
22
  import { buildValueOf, foldBoot } from './boot.mjs';
23
23
  import { evalStaticOrThrow, evalStatic, foldScope } from './static-eval.mjs';
24
24
  import { lowerExpr } from './expressions.mjs';
@@ -318,17 +318,21 @@ function applyShow(node, show) {
318
318
  */
319
319
  export function lowerEventHandler(attr, out, env, state) {
320
320
  const fn = attrExpr(attr);
321
+ const layout = attr.name.name === 'onLayout';
321
322
  if (fn.type === 'Identifier' && env.callbacks?.has(fn.name)) {
322
323
  // A useCallback compiles to one shared handler, namespaced by cbPrefix so each child instance gets its own.
324
+ // Its onLayout use gets a handler of its own, since only that event carries the layout rect. The key's
325
+ // `layout:` and the name's `er_cbl_` can't come from an identifier, so they never meet another callback.
323
326
  const callbackKey = `${env.cbPrefix ?? ''}${fn.name}`;
324
- let handlerName = out.cbEmitted.get(callbackKey);
327
+ const emittedKey = layout ? `layout:${callbackKey}` : callbackKey;
328
+ let handlerName = out.cbEmitted.get(emittedKey);
325
329
  if (!handlerName) {
326
- handlerName = `er_cb_${callbackKey}`;
327
- out.cbEmitted.set(callbackKey, handlerName);
330
+ handlerName = `${layout ? 'er_cbl_' : 'er_cb_'}${callbackKey}`;
331
+ out.cbEmitted.set(emittedKey, handlerName);
328
332
  out.handlers.push({
329
333
  kind: 'callback',
330
334
  name: handlerName,
331
- callback: lowerHandler(env.callbacks.get(fn.name), env, state, out),
335
+ callback: lowerHandler(env.callbacks.get(fn.name), { ...env, layout }, state, out),
332
336
  });
333
337
  }
334
338
  return handlerName;
@@ -340,14 +344,14 @@ export function lowerEventHandler(attr, out, env, state) {
340
344
  out.handlers.push({
341
345
  kind: 'callback',
342
346
  name: handlerName,
343
- callback: lowerHandler(callbackProp.node, callbackProp.env, callbackProp.state, out),
347
+ callback: lowerHandler(callbackProp.node, { ...callbackProp.env, layout }, callbackProp.state, out),
344
348
  });
345
349
  }
346
350
  else if (isFn(fn)) {
347
351
  out.handlers.push({
348
352
  kind: 'callback',
349
353
  name: handlerName,
350
- callback: lowerHandler(fn, env, state, out),
354
+ callback: lowerHandler(fn, { ...env, layout }, state, out),
351
355
  });
352
356
  }
353
357
  else {
@@ -468,8 +472,12 @@ function emitNodeImpl(element, scope, out, env, state, opts = {}) {
468
472
  const text = tag === 'Text' && !spans
469
473
  ? lowerNodeText(element.children, scope, env)
470
474
  : null;
475
+ if (text) {
476
+ checkEngineString(constantText(text), 'ER_TEXT_MAX', 'a <Text>');
477
+ }
471
478
  // An <Image>'s resize/tint are static, so fold them into staticAssigns for both the static and dynamic paths.
472
479
  const image = tag === 'Image' ? resolveImageAttrs(element, env, out) : null;
480
+ checkEngineString(image?.imageName ?? null, 'ER_IMAGE_NAME_MAX', `image name "${image?.imageName}"`);
473
481
  if (image?.resizeMode) {
474
482
  staticAssigns.push({ field: 'resize_mode', expr: image.resizeMode });
475
483
  }
@@ -555,7 +563,7 @@ function emitNodeImpl(element, scope, out, env, state, opts = {}) {
555
563
  image: image?.imageNameDyn != null
556
564
  ? { kind: 'value', value: image.imageNameDyn }
557
565
  : image?.imageName != null
558
- ? { kind: 'static', name: image.imageName, resetOnUpdate: false }
566
+ ? { kind: 'static', name: image.imageName }
559
567
  : null,
560
568
  spans,
561
569
  wiring,
@@ -13,9 +13,41 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Constants
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ /**
20
+ * The largest value each size or cap takes; the smallest is 1. Screen dimensions end up in int16_t props, a
21
+ * list's row count and a string buffer's size in a C `int`, and a nested <Text>'s segment count in the
22
+ * engine's uint8_t `span_count`.
23
+ */
24
+ const MAX_SCREEN = 32767;
25
+ const MAX_LIST_CAP = 32767;
26
+ const MAX_LIST_STR_CAP = 32767;
27
+ const MAX_TEXT_SPANS = 255;
16
28
  /*----------------------------------------------------------------------------------------------------------------------
17
29
  - Implementation
18
30
  ---------------------------------------------------------------------------------------------------------------------*/
31
+ /**
32
+ * Checks that a size or cap is a whole number from 1 to `max`, since it is written into the generated C as a
33
+ * `#define` or an array size.
34
+ *
35
+ * @param value The value, as the option or the parsed variable gave it.
36
+ * @param name The option or variable, as the error names it.
37
+ * @param max The largest value allowed.
38
+ * @param shown The value as the error shows it. Defaults to `value`.
39
+ *
40
+ * @returns The value, when it is in range.
41
+ */
42
+ function wholeInRange(value, name, max, shown = String(value)) {
43
+ if (typeof value !== 'number' ||
44
+ !Number.isInteger(value) ||
45
+ value < 1 ||
46
+ value > max) {
47
+ throw new Error(`AOT: ${name} must be a whole number from 1 to ${max}, got ${shown}`);
48
+ }
49
+ return value;
50
+ }
19
51
  /**
20
52
  * compileSource's options with the target screen and the fixed-buffer caps filled in. Each one the caller
21
53
  * leaves out falls back to its environment variable, then to a default. The environment is read on every
@@ -29,27 +61,46 @@
29
61
  * maxTextSpans ER_AOT_MAX_TEXT_SPANS 4 Inline segments in a nested <Text>. Must match the
30
62
  * engine's ER_TEXT_MAX_SPANS.
31
63
  *
64
+ * Each value must be a whole number from 1 up: to 32767 for the screen and the list caps, to 255 for
65
+ * maxTextSpans. One that isn't, from the options or a variable, is an `AOT:` error that names it.
66
+ *
32
67
  * @param opts The options the caller passed.
33
68
  *
34
69
  * @returns The same options with every value filled in.
35
70
  */
36
71
  export function resolveOptions(opts) {
37
- // A blank or unparsable variable falls back to the default for that value alone.
38
- const fromEnv = (name, fallback) => Number(process.env[name]) || fallback;
39
- const screenFromEnv = Number(process.env.ER_AOT_SCREEN_W) > 0 &&
40
- Number(process.env.ER_AOT_SCREEN_H) > 0;
72
+ // An unset or blank variable falls back to the default; any other value must parse to one in range.
73
+ const isSet = (name) => (process.env[name] ?? '').trim() !== '';
74
+ const fromEnv = (name, fallback, max) => {
75
+ if (!isSet(name))
76
+ return fallback;
77
+ const raw = process.env[name];
78
+ return wholeInRange(Number(raw), name, max, JSON.stringify(raw));
79
+ };
80
+ const fromOption = (value, name, envName, fallback, max) => value != null
81
+ ? wholeInRange(value, name, max)
82
+ : fromEnv(envName, fallback, max);
41
83
  return {
42
84
  ...opts,
43
- screen: opts.screen ?? {
44
- width: fromEnv('ER_AOT_SCREEN_W', 800),
45
- height: fromEnv('ER_AOT_SCREEN_H', 480),
46
- },
85
+ screen: opts.screen
86
+ ? {
87
+ width: wholeInRange(opts.screen.width, 'screen.width', MAX_SCREEN),
88
+ height: wholeInRange(opts.screen.height, 'screen.height', MAX_SCREEN),
89
+ }
90
+ : {
91
+ width: fromEnv('ER_AOT_SCREEN_W', 800, MAX_SCREEN),
92
+ height: fromEnv('ER_AOT_SCREEN_H', 480, MAX_SCREEN),
93
+ },
47
94
  // Where the size came from, for the error footer: 'option', 'env' (both dimensions) or 'default'.
48
- screenFrom: opts.screen ? 'option' : screenFromEnv ? 'env' : 'default',
95
+ screenFrom: opts.screen
96
+ ? 'option'
97
+ : isSet('ER_AOT_SCREEN_W') && isSet('ER_AOT_SCREEN_H')
98
+ ? 'env'
99
+ : 'default',
49
100
  caps: {
50
- listCap: opts.listCap ?? fromEnv('ER_AOT_LIST_CAP', 16),
51
- listStrCap: opts.listStrCap ?? fromEnv('ER_AOT_LIST_STR_CAP', 48),
52
- maxTextSpans: opts.maxTextSpans ?? fromEnv('ER_AOT_MAX_TEXT_SPANS', 4),
101
+ listCap: fromOption(opts.listCap, 'listCap', 'ER_AOT_LIST_CAP', 16, MAX_LIST_CAP),
102
+ listStrCap: fromOption(opts.listStrCap, 'listStrCap', 'ER_AOT_LIST_STR_CAP', 48, MAX_LIST_STR_CAP),
103
+ maxTextSpans: fromOption(opts.maxTextSpans, 'maxTextSpans', 'ER_AOT_MAX_TEXT_SPANS', 4, MAX_TEXT_SPANS),
53
104
  },
54
105
  };
55
106
  }
@@ -98,7 +98,7 @@ function snapshotOf(fold) {
98
98
  if (!fold.snapshot) {
99
99
  const copy = {};
100
100
  for (const name in fold.scope) {
101
- copy[name] = fold.scope[name];
101
+ setBinding(copy, name, fold.scope[name]);
102
102
  }
103
103
  fold.snapshot = copy;
104
104
  }
@@ -276,7 +276,7 @@ function evaluate(node, scope, fold) {
276
276
  : evaluate(node.alternate, scope, fold);
277
277
  }
278
278
  case 'Identifier':
279
- if (node.name in scope)
279
+ if (hasBinding(scope, node.name))
280
280
  return scope[node.name];
281
281
  throw new Error(`AOT: cannot statically resolve identifier "${node.name}"`);
282
282
  case 'MemberExpression': {
@@ -332,7 +332,7 @@ function evaluate(node, scope, fold) {
332
332
  !callee.computed &&
333
333
  callee.object.type === 'Identifier' &&
334
334
  callee.object.name === 'Math' &&
335
- !('Math' in scope)
335
+ !hasBinding(scope, 'Math')
336
336
  ? callee.property.name
337
337
  : null;
338
338
  if (mathFn && Object.hasOwn(STATIC_MATH, mathFn)) {
@@ -380,9 +380,11 @@ function binary(operator, left, right) {
380
380
  case '>=':
381
381
  return left >= right;
382
382
  case '==':
383
+ return left == right;
383
384
  case '===':
384
385
  return left === right;
385
386
  case '!=':
387
+ return left != right;
386
388
  case '!==':
387
389
  return left !== right;
388
390
  }
@@ -416,7 +418,7 @@ export function foldScope(env, scope) {
416
418
  // Copy the scope only when a runtime name actually shadows one of its constants.
417
419
  let hasShadowedName = false;
418
420
  for (const name of runtimeNames) {
419
- if (name in scope) {
421
+ if (hasBinding(scope, name)) {
420
422
  hasShadowedName = true;
421
423
  break;
422
424
  }
@@ -425,6 +427,36 @@ export function foldScope(env, scope) {
425
427
  return scope;
426
428
  return Object.fromEntries(Object.entries(scope).filter(([name]) => !runtimeNames.has(name)));
427
429
  }
430
+ /**
431
+ * Whether `scope` binds `name`, through the scopes it reads through to but not Object.prototype.
432
+ *
433
+ * @param scope Compile-time constants in reach.
434
+ * @param name The identifier.
435
+ *
436
+ * @returns True when a scope in the chain has it as its own.
437
+ */
438
+ export function hasBinding(scope, name) {
439
+ for (let layer = scope; layer && layer !== Object.prototype; layer = Object.getPrototypeOf(layer)) {
440
+ if (Object.hasOwn(layer, name))
441
+ return true;
442
+ }
443
+ return false;
444
+ }
445
+ /**
446
+ * Binds `name` in `scope` as its own property, so `__proto__` is a name rather than Object.prototype's setter.
447
+ *
448
+ * @param scope The scope to bind in.
449
+ * @param name The identifier.
450
+ * @param value Its value.
451
+ */
452
+ export function setBinding(scope, name, value) {
453
+ Object.defineProperty(scope, name, {
454
+ value,
455
+ writable: true,
456
+ enumerable: true,
457
+ configurable: true,
458
+ });
459
+ }
428
460
  /**
429
461
  * `scope` with the global `undefined` bound, so a fold can resolve the name.
430
462
  *