embedded-react 0.19.0 → 0.21.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 (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
@@ -0,0 +1,118 @@
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
+ * Constant props as package records.
18
+ */
19
+ /*----------------------------------------------------------------------------------------------------------------------
20
+ - Imports
21
+ ---------------------------------------------------------------------------------------------------------------------*/
22
+ import { aotError } from '../diagnostics.mjs';
23
+ import { ABI_PROPS, ENGINE_VALUES, PropKind } from './format.mjs';
24
+ /*----------------------------------------------------------------------------------------------------------------------
25
+ - Constants
26
+ ---------------------------------------------------------------------------------------------------------------------*/
27
+ // The values each whole-number kind holds, as the runtime checks them at load. A float holds any, and an
28
+ // enum's largest value is its prop's own.
29
+ const RANGES = {
30
+ i16: [-32768, 32767],
31
+ u8: [0, 255],
32
+ opacity: [0, 255],
33
+ u16: [0, 65535],
34
+ bool: [0, 1],
35
+ color: [0, 0xffffffff],
36
+ };
37
+ /*----------------------------------------------------------------------------------------------------------------------
38
+ - Implementation
39
+ ---------------------------------------------------------------------------------------------------------------------*/
40
+ /**
41
+ * The ABI prop an ERProps field is.
42
+ *
43
+ * @param field The field, as lowering names it (`flex_grow`, `gradient_stops[0].color`).
44
+ *
45
+ * @returns The prop.
46
+ */
47
+ export function abiProp(field) {
48
+ const prop = ABI_PROPS.get(field);
49
+ if (!prop) {
50
+ throw aotError(`AOT: a package has no engine prop for \`${field}\` yet`);
51
+ }
52
+ return prop;
53
+ }
54
+ /**
55
+ * A float's 32 bits.
56
+ *
57
+ * @param value The number.
58
+ *
59
+ * @returns The bits.
60
+ */
61
+ export function floatBits(value) {
62
+ const view = new DataView(new ArrayBuffer(4));
63
+ view.setFloat32(0, value, true);
64
+ return view.getUint32(0, true);
65
+ }
66
+ /**
67
+ * A constant's number.
68
+ *
69
+ * @param constant A number, or an er_scene.h name.
70
+ *
71
+ * @returns The number, or null for a name the format doesn't have.
72
+ */
73
+ export function constantNumber(constant) {
74
+ return typeof constant === 'number'
75
+ ? constant
76
+ : (ENGINE_VALUES.get(constant) ?? null);
77
+ }
78
+ /**
79
+ * A constant prop as a prop set entry.
80
+ *
81
+ * @param field The ERProps field.
82
+ * @param constant Its value.
83
+ *
84
+ * @returns The entry.
85
+ */
86
+ export function constantPropEntry(field, constant) {
87
+ const prop = abiProp(field);
88
+ const value = constantNumber(constant);
89
+ if (value === null || !Number.isFinite(value)) {
90
+ throw aotError(`AOT: a package can't hold the constant \`${constant}\` for \`${field}\` yet`);
91
+ }
92
+ if (prop.kind === 'float') {
93
+ return { prop: prop.id, kind: PropKind.float, value: floatBits(value) };
94
+ }
95
+ // The runtime refuses a package with a value its field can't hold.
96
+ const whole = Math.trunc(value);
97
+ const [min, max] = prop.kind === 'enum' ? [0, prop.max] : RANGES[prop.kind];
98
+ if (whole < min || whole > max) {
99
+ throw aotError(`AOT: \`${field}\` is ${whole}, but the engine holds ${min} to ${max} there`, 'use a value in that range.');
100
+ }
101
+ return {
102
+ prop: prop.id,
103
+ kind: PropKind[prop.kind],
104
+ value: prop.kind === 'color' ? whole >>> 0 : whole | 0,
105
+ };
106
+ }
107
+ /**
108
+ * A string or image prop as a prop set entry.
109
+ *
110
+ * @param field `text`, `placeholder` or `image_name`.
111
+ * @param stringIndex The string's index in the strings table.
112
+ *
113
+ * @returns The entry.
114
+ */
115
+ export function stringPropEntry(field, stringIndex) {
116
+ const prop = abiProp(field);
117
+ return { prop: prop.id, kind: PropKind[prop.kind], value: stringIndex };
118
+ }
@@ -0,0 +1,515 @@
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
+ * String caps: each string buffer is sized from the values that can reach it. A string state's or a list
18
+ * field's cap is the most bytes its initial value or any write can hold, and a local's is its value's. A write
19
+ * is built in the format buffer, so it holds at most ER_TEXT_MAX bytes.
20
+ *
21
+ * A string built from itself, where a write reads it back and adds to it (`setLog(log + '.')`), has no bound
22
+ * of its own, so it takes the default cap (listStrCap). A `slice` with a fixed length bounds what it cuts, which
23
+ * is how an app sets a cap of its own: `setLog(log.slice(-39) + '.')`.
24
+ */
25
+ /*----------------------------------------------------------------------------------------------------------------------
26
+ - Imports
27
+ ---------------------------------------------------------------------------------------------------------------------*/
28
+ import { aotError, constantText, ENGINE_STRING_MAX } from '../diagnostics.mjs';
29
+ import { nodesOf } from '../ir/nodes.mjs';
30
+ import { itemReadOf, itemValueAt } from '../list-items.mjs';
31
+ import { TEXT_END } from '../ir/text.mjs';
32
+ /*----------------------------------------------------------------------------------------------------------------------
33
+ - Constants
34
+ ---------------------------------------------------------------------------------------------------------------------*/
35
+ // What an IR walk skips: where a value came from (which repeats its reads, untyped) and source positions.
36
+ const SKIPPED_KEYS = new Set(['source', 'location']);
37
+ // The most bytes JS prints for a number: "-2147483648", "-9223372036854775808", and a float below 1e21 in full.
38
+ const INT_TEXT_MAX = 11;
39
+ const INT64_TEXT_MAX = 20;
40
+ const FLOAT_TEXT_MAX = 22;
41
+ // The most bytes the VM prints for a float's toFixed.
42
+ const FIXED_TEXT_MAX = 63;
43
+ const BOOLEAN_TEXT_MAX = 5;
44
+ // The most UTF-8 bytes in one JS character (a 4-byte character counts as two).
45
+ const BYTES_PER_UNIT = 3;
46
+ /** The most bytes a string buffer holds. */
47
+ export const STRING_CAP_MAX = 32767;
48
+ const WRITE_MAX = ENGINE_STRING_MAX.ER_TEXT_MAX;
49
+ /*----------------------------------------------------------------------------------------------------------------------
50
+ - Implementation
51
+ ---------------------------------------------------------------------------------------------------------------------*/
52
+ const byteLength = (text) => Buffer.byteLength(text, 'utf8');
53
+ const literalBound = (text) => ({
54
+ bytes: byteLength(text),
55
+ ascii: /^[\x00-\x7f]*$/.test(text),
56
+ });
57
+ /** What a string the compiler can't follow can be: anything a write holds. */
58
+ const UNKNOWN = { bytes: WRITE_MAX, ascii: false };
59
+ const widest = (bounds) => bounds.reduce((widened, bound) => ({
60
+ bytes: Math.max(widened.bytes, bound.bytes),
61
+ ascii: widened.ascii && bound.ascii,
62
+ }), { bytes: 0, ascii: true });
63
+ /**
64
+ * The string literals in an expression, as one bound: what a boot value's string can be, since nothing else
65
+ * reaches it at boot.
66
+ *
67
+ * @param expression The value.
68
+ *
69
+ * @returns The bound.
70
+ */
71
+ function literalsBound(expression) {
72
+ const bounds = [];
73
+ const walk = (value) => {
74
+ if (!value || typeof value !== 'object') {
75
+ return;
76
+ }
77
+ const node = value;
78
+ if (node.kind === 'string' && typeof node.value === 'string') {
79
+ bounds.push(literalBound(node.value));
80
+ return;
81
+ }
82
+ Object.values(node).forEach(walk);
83
+ };
84
+ walk(expression);
85
+ return widest(bounds);
86
+ }
87
+ /**
88
+ * The most bytes a boot value's string can be: its longest literal.
89
+ *
90
+ * @param expression The value.
91
+ *
92
+ * @returns The bytes, at least 1.
93
+ */
94
+ export const longestLiteral = (expression) => Math.max(literalsBound(expression).bytes, 1);
95
+ /**
96
+ * The most JS characters a slice keeps, whatever it cuts: null when that depends on how long the string is.
97
+ *
98
+ * @param edit The slice.
99
+ *
100
+ * @returns The characters, or null.
101
+ */
102
+ function sliceLength(edit) {
103
+ const start = edit.start.kind === 'number' ? edit.start.value : null;
104
+ const end = edit.end.kind === 'number' && edit.end.value !== TEXT_END
105
+ ? edit.end.value
106
+ : null;
107
+ const lengths = [];
108
+ if (start !== null && start < 0) {
109
+ lengths.push(-start);
110
+ }
111
+ if (end !== null && end >= 0) {
112
+ lengths.push(Math.max(0, end - Math.max(start ?? 0, 0)));
113
+ }
114
+ if (start !== null && end !== null && start < 0 && end < 0) {
115
+ lengths.push(Math.max(0, end - start));
116
+ }
117
+ return lengths.length ? Math.min(...lengths) : null;
118
+ }
119
+ /** Whether a piece's edits cut it to a fixed length, so what it prints no longer depends on its value's. */
120
+ const isCutShort = (part) => part.kind !== 'literal' &&
121
+ (part.edits ?? []).some(edit => edit.kind === 'slice' && sliceLength(edit) !== null);
122
+ /**
123
+ * A bound after a string helper.
124
+ *
125
+ * @param bound The piece's bound.
126
+ * @param edit The helper.
127
+ *
128
+ * @returns The bound.
129
+ */
130
+ function editedBound(bound, edit) {
131
+ if (edit.kind === 'pad') {
132
+ // A character can take several bytes, so padding non-ASCII text adds up to the whole width.
133
+ return {
134
+ bytes: bound.ascii
135
+ ? Math.max(bound.bytes, edit.width)
136
+ : bound.bytes + edit.width,
137
+ ascii: bound.ascii,
138
+ };
139
+ }
140
+ if (edit.kind === 'slice') {
141
+ const length = sliceLength(edit);
142
+ if (length !== null) {
143
+ return {
144
+ bytes: Math.min(bound.bytes, bound.ascii ? length : length * BYTES_PER_UNIT),
145
+ ascii: bound.ascii,
146
+ };
147
+ }
148
+ }
149
+ return bound;
150
+ }
151
+ /**
152
+ * Calls `visit` on every statement in the app, wherever it is.
153
+ *
154
+ * @param app The app.
155
+ * @param visit Called on each statement.
156
+ */
157
+ function eachStatement(app, visit) {
158
+ const seen = new Set();
159
+ const walk = (value) => {
160
+ if (!value || typeof value !== 'object' || seen.has(value)) {
161
+ return;
162
+ }
163
+ seen.add(value);
164
+ if (Array.isArray(value)) {
165
+ value.forEach(walk);
166
+ return;
167
+ }
168
+ const node = value;
169
+ if (node.kind === 'setStateText' ||
170
+ node.kind === 'appendItem' ||
171
+ node.kind === 'setRow' ||
172
+ node.kind === 'splitItems' ||
173
+ node.kind === 'declareLocal' ||
174
+ node.kind === 'assignLocal') {
175
+ visit(node);
176
+ }
177
+ for (const [key, child] of Object.entries(node)) {
178
+ if (!SKIPPED_KEYS.has(key)) {
179
+ walk(child);
180
+ }
181
+ }
182
+ };
183
+ const { output } = app;
184
+ walk([
185
+ nodesOf(app.root),
186
+ output.handlers,
187
+ output.timerFunctions,
188
+ output.nativeEventHandlers,
189
+ output.effectFunctions,
190
+ output.mountEffects,
191
+ output.dependencyEffects,
192
+ output.animationCallbacks,
193
+ output.panResponders,
194
+ output.vectors,
195
+ app.boot,
196
+ app.state.map(state => state.kind === 'list' ? state.derived : state.worked),
197
+ ]);
198
+ }
199
+ /**
200
+ * Pins an error to a source position, unless it has one.
201
+ *
202
+ * @param error The error.
203
+ * @param location The position.
204
+ *
205
+ * @returns The error.
206
+ */
207
+ function located(error, location) {
208
+ if (location && !error.aotLoc) {
209
+ error.aotLoc = location;
210
+ }
211
+ return error;
212
+ }
213
+ /**
214
+ * Works out every string buffer's cap from the values that reach it, and refuses a constant too long for a
215
+ * string built from itself.
216
+ *
217
+ * @param app The app.
218
+ * @param interned The interned string states, each with its values.
219
+ * @param defaultCap The cap of a string built from itself.
220
+ *
221
+ * @returns The caps.
222
+ */
223
+ export function stringCaps(app, interned, defaultCap) {
224
+ const newBuffer = (what, initial, initialAt) => ({
225
+ what,
226
+ initial,
227
+ initialAt,
228
+ writes: [],
229
+ bound: widest(initial.map(literalBound)),
230
+ isSelfBuilt: false,
231
+ });
232
+ const states = new Map();
233
+ const fields = new Map();
234
+ const locals = new Map();
235
+ for (const state of app.state) {
236
+ if (state.kind === 'list') {
237
+ fields.set(state, new Map(state.struct.fields
238
+ .filter(field => field.kind === 'string')
239
+ .map(field => [
240
+ field.key,
241
+ newBuffer(`field "${field.key}" of list state "${state.name}"`, state.items.map(item => {
242
+ const { present, value } = itemValueAt(item, field);
243
+ return present ? String(value) : '';
244
+ }), state.initialAt),
245
+ ])));
246
+ }
247
+ else if (state.slotKind === 'string' && !interned.has(state)) {
248
+ states.set(state, newBuffer(`state "${state.name}"`, [String(state.initial)], state.initialAt));
249
+ }
250
+ }
251
+ eachStatement(app, statement => {
252
+ const { location } = statement;
253
+ if (statement.kind === 'setStateText') {
254
+ states
255
+ .get(statement.state)
256
+ ?.writes.push({ text: statement.text, location });
257
+ }
258
+ else if (statement.kind === 'appendItem' || statement.kind === 'setRow') {
259
+ for (const itemValue of statement.values) {
260
+ const buffer = fields.get(statement.list)?.get(itemValue.field.key);
261
+ buffer?.writes.push({
262
+ text: 'text' in itemValue
263
+ ? itemValue.text
264
+ : { parts: [{ kind: 'value', value: itemValue.value }] },
265
+ location,
266
+ });
267
+ }
268
+ }
269
+ else if (statement.kind === 'splitItems') {
270
+ // A piece is at most the whole string.
271
+ const [field] = statement.list.struct.fields;
272
+ fields
273
+ .get(statement.list)
274
+ ?.get(field.key)
275
+ ?.writes.push({
276
+ text: { parts: [{ kind: 'value', value: statement.text }] },
277
+ location,
278
+ });
279
+ }
280
+ else if ((statement.kind === 'declareLocal' &&
281
+ statement.initializer.type.kind === 'string') ||
282
+ (statement.kind === 'assignLocal' &&
283
+ statement.value.type.kind === 'string')) {
284
+ if (!locals.has(statement.name)) {
285
+ locals.set(statement.name, newBuffer(`local "${statement.name}"`, [], undefined));
286
+ }
287
+ const value = statement.kind === 'declareLocal'
288
+ ? statement.initializer
289
+ : statement.value;
290
+ locals.get(statement.name).writes.push({
291
+ text: statement.text ?? { parts: [{ kind: 'value', value }] },
292
+ location,
293
+ });
294
+ }
295
+ });
296
+ const bufferOf = (expression) => {
297
+ switch (expression.kind) {
298
+ case 'state':
299
+ return states.get(expression.state);
300
+ case 'local':
301
+ return expression.local.name !== undefined
302
+ ? locals.get(expression.local.name)
303
+ : undefined;
304
+ case 'itemField':
305
+ return expression.item.list
306
+ ? fields.get(expression.item.list)?.get(expression.field.key)
307
+ : undefined;
308
+ default:
309
+ return undefined;
310
+ }
311
+ };
312
+ const valueBound = (expression) => {
313
+ if (expression.kind === 'string') {
314
+ return literalBound(expression.value);
315
+ }
316
+ if (expression.kind === 'state' && interned.has(expression.state)) {
317
+ return widest(interned.get(expression.state).map(literalBound));
318
+ }
319
+ if (expression.kind === 'local' && expression.local.expression) {
320
+ return valueBound(expression.local.expression);
321
+ }
322
+ if (expression.kind === 'boot') {
323
+ return expression.slot.initializer.kind === 'expr'
324
+ ? literalsBound(expression.slot.initializer.expression)
325
+ : UNKNOWN;
326
+ }
327
+ if (expression.kind === 'conditional') {
328
+ return widest([
329
+ valueBound(expression.consequent),
330
+ valueBound(expression.alternate),
331
+ ]);
332
+ }
333
+ // A <TextInput>'s text, or a value the compiler can't follow.
334
+ return bufferOf(expression)?.bound ?? UNKNOWN;
335
+ };
336
+ const partBound = (part) => {
337
+ if (part.kind === 'literal') {
338
+ return literalBound(part.text);
339
+ }
340
+ let bound;
341
+ if (part.kind === 'booleanWord') {
342
+ bound = { bytes: BOOLEAN_TEXT_MAX, ascii: true };
343
+ }
344
+ else {
345
+ // A whole number's toFixed prints its decimals after it.
346
+ const decimals = part.digits ? part.digits + 1 : 0;
347
+ const type = part.value.type.kind;
348
+ bound =
349
+ type === 'string'
350
+ ? valueBound(part.value)
351
+ : {
352
+ bytes: type === 'float'
353
+ ? Math.min(FIXED_TEXT_MAX, FLOAT_TEXT_MAX + decimals)
354
+ : (type === 'int64' ? INT64_TEXT_MAX : INT_TEXT_MAX) +
355
+ decimals,
356
+ ascii: true,
357
+ };
358
+ }
359
+ bound = (part.edits ?? []).reduce(editedBound, bound);
360
+ const read = itemReadOf(part.value);
361
+ return part.missing && (read?.field.optional || read?.item.guarded)
362
+ ? widest([bound, literalBound(part.missing)])
363
+ : bound;
364
+ };
365
+ const writtenBound = (text) => {
366
+ const bounds = text.parts.map(partBound);
367
+ return {
368
+ bytes: Math.min(WRITE_MAX, bounds.reduce((total, bound) => total + bound.bytes, 0)),
369
+ ascii: bounds.every(bound => bound.ascii),
370
+ };
371
+ };
372
+ // The strings a value reads, through choices and the values locals stand for.
373
+ const readsOf = (expression, found) => {
374
+ if (expression.kind === 'conditional') {
375
+ readsOf(expression.consequent, found);
376
+ readsOf(expression.alternate, found);
377
+ }
378
+ else if (expression.kind === 'local' && expression.local.expression) {
379
+ readsOf(expression.local.expression, found);
380
+ }
381
+ else {
382
+ const buffer = bufferOf(expression);
383
+ if (buffer) {
384
+ found.push(buffer);
385
+ }
386
+ }
387
+ };
388
+ // The strings each buffer's writes read, unless a slice cuts them to a fixed length.
389
+ const buffers = [
390
+ ...states.values(),
391
+ ...[...fields.values()].flatMap(byKey => [...byKey.values()]),
392
+ ...locals.values(),
393
+ ];
394
+ const reads = new Map();
395
+ for (const buffer of buffers) {
396
+ const found = [];
397
+ for (const { text } of buffer.writes) {
398
+ text.parts.forEach((part, index) => {
399
+ if (part.kind !== 'value' ||
400
+ part.value.type.kind !== 'string' ||
401
+ isCutShort(part)) {
402
+ return;
403
+ }
404
+ // A pad's width already bounds it, so only another part adds.
405
+ const adds = text.parts.some((other, otherIndex) => otherIndex !== index &&
406
+ !(other.kind === 'literal' && other.text === ''));
407
+ const read = [];
408
+ readsOf(part.value, read);
409
+ found.push(...read.map(readBuffer => ({ buffer: readBuffer, adds })));
410
+ });
411
+ }
412
+ reads.set(buffer, found);
413
+ }
414
+ // A buffer is built from itself when it is in a cycle of reads that adds to it (Tarjan's strongly connected
415
+ // components).
416
+ const order = new Map();
417
+ const lowest = new Map();
418
+ const stack = [];
419
+ const onStack = new Set();
420
+ const visit = (buffer) => {
421
+ order.set(buffer, order.size);
422
+ lowest.set(buffer, order.get(buffer));
423
+ stack.push(buffer);
424
+ onStack.add(buffer);
425
+ for (const read of reads.get(buffer)) {
426
+ if (!order.has(read.buffer)) {
427
+ visit(read.buffer);
428
+ lowest.set(buffer, Math.min(lowest.get(buffer), lowest.get(read.buffer)));
429
+ }
430
+ else if (onStack.has(read.buffer)) {
431
+ lowest.set(buffer, Math.min(lowest.get(buffer), order.get(read.buffer)));
432
+ }
433
+ }
434
+ if (lowest.get(buffer) !== order.get(buffer)) {
435
+ return;
436
+ }
437
+ const component = new Set();
438
+ let member;
439
+ do {
440
+ member = stack.pop();
441
+ onStack.delete(member);
442
+ component.add(member);
443
+ } while (member !== buffer);
444
+ const adds = [...component].some(inCycle => reads.get(inCycle).some(read => read.adds && component.has(read.buffer)));
445
+ if (adds) {
446
+ for (const inCycle of component) {
447
+ inCycle.isSelfBuilt = true;
448
+ inCycle.bound = { bytes: defaultCap, ascii: false };
449
+ }
450
+ }
451
+ };
452
+ for (const buffer of buffers) {
453
+ if (!order.has(buffer)) {
454
+ visit(buffer);
455
+ }
456
+ }
457
+ // Each bound only grows, and a write holds at most WRITE_MAX bytes, so this settles.
458
+ let hasChanged = true;
459
+ while (hasChanged) {
460
+ hasChanged = false;
461
+ for (const buffer of buffers) {
462
+ if (buffer.isSelfBuilt) {
463
+ continue;
464
+ }
465
+ const next = widest([
466
+ buffer.bound,
467
+ ...buffer.writes.map(write => writtenBound(write.text)),
468
+ ]);
469
+ if (next.bytes !== buffer.bound.bytes ||
470
+ next.ascii !== buffer.bound.ascii) {
471
+ buffer.bound = next;
472
+ hasChanged = true;
473
+ }
474
+ }
475
+ }
476
+ checkFits(buffers, defaultCap);
477
+ // The package verifier refuses a string cap of 0.
478
+ const capOf = (buffer) => Math.max(1, buffer ? buffer.bound.bytes : WRITE_MAX);
479
+ return {
480
+ state: state => capOf(states.get(state)),
481
+ field: (list, key) => capOf(fields.get(list)?.get(key)),
482
+ local: name => capOf(locals.get(name)),
483
+ value: expression => Math.max(1, Math.min(STRING_CAP_MAX, valueBound(expression).bytes)),
484
+ };
485
+ }
486
+ /**
487
+ * Refuses a constant too long for a string built from itself, and a string too long for any buffer.
488
+ *
489
+ * @param buffers The string buffers, their bounds settled.
490
+ * @param defaultCap The cap of a string built from itself.
491
+ */
492
+ function checkFits(buffers, defaultCap) {
493
+ const hint = 'raise ER_AOT_LIST_STR_CAP (the listStrCap option), shorten the string, or keep it to a fixed length ' +
494
+ "with slice, e.g. setLog(log.slice(-39) + '.').";
495
+ for (const buffer of buffers) {
496
+ if (!buffer.isSelfBuilt) {
497
+ if (buffer.bound.bytes > STRING_CAP_MAX) {
498
+ throw located(aotError(`AOT: ${buffer.what} starts ${buffer.bound.bytes} bytes long, but a string holds ${STRING_CAP_MAX} bytes`, 'shorten the string.'), buffer.initialAt);
499
+ }
500
+ continue;
501
+ }
502
+ const initial = buffer.initial.find(text => byteLength(text) > defaultCap);
503
+ if (initial !== undefined) {
504
+ throw located(aotError(`AOT: ${buffer.what} starts ${byteLength(initial)} bytes long, but a string built from itself holds ` +
505
+ `${defaultCap} bytes`, hint), buffer.initialAt);
506
+ }
507
+ for (const write of buffer.writes) {
508
+ const constant = constantText(write.text);
509
+ if (constant !== null && byteLength(constant) > defaultCap) {
510
+ throw located(aotError(`AOT: ${buffer.what} is set to a ${byteLength(constant)}-byte string, but a string built from itself ` +
511
+ `holds ${defaultCap} bytes`, hint), write.location);
512
+ }
513
+ }
514
+ }
515
+ }