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,198 @@
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 { aotError } from './diagnostics.mjs';
20
+ /*----------------------------------------------------------------------------------------------------------------------
21
+ - Implementation
22
+ ---------------------------------------------------------------------------------------------------------------------*/
23
+ /**
24
+ * A case's statements without the `break` that ends them, and whether they end there (a `break` or a `return`)
25
+ * rather than falling through to the next case.
26
+ *
27
+ * @param statements The case's statements.
28
+ *
29
+ * @returns The statements, and whether they end.
30
+ */
31
+ function endOfCase(statements) {
32
+ const last = statements.at(-1);
33
+ if (last?.type === 'BreakStatement' && !last.label) {
34
+ return { statements: statements.slice(0, -1), ends: true };
35
+ }
36
+ if (last?.type === 'ReturnStatement')
37
+ return { statements, ends: true };
38
+ // `case 1: { …; break; }`
39
+ if (last?.type === 'BlockStatement') {
40
+ const inner = endOfCase(last.body);
41
+ return {
42
+ statements: [
43
+ ...statements.slice(0, -1),
44
+ { ...last, body: inner.statements },
45
+ ],
46
+ ends: inner.ends,
47
+ };
48
+ }
49
+ return { statements, ends: false };
50
+ }
51
+ /**
52
+ * Refuses a `break` left in a case's statements, one that does not end the case.
53
+ *
54
+ * @param node The statements, or a node in them.
55
+ */
56
+ function refuseInnerBreak(node) {
57
+ if (!node || typeof node !== 'object')
58
+ return;
59
+ if (Array.isArray(node)) {
60
+ node.forEach(refuseInnerBreak);
61
+ return;
62
+ }
63
+ const statement = node;
64
+ if (statement.type === 'BreakStatement') {
65
+ const error = aotError('AOT: a `break` must be the last statement of its case', 'end the case with break, and write a break that depends on a test as if/else inside the case.');
66
+ if (statement.loc)
67
+ error.aotLoc = statement.loc.start;
68
+ throw error;
69
+ }
70
+ // A nested switch has breaks of its own, and a function's body is not this case's.
71
+ if (statement.type === 'SwitchStatement' ||
72
+ statement.type === 'ArrowFunctionExpression' ||
73
+ statement.type === 'FunctionExpression' ||
74
+ statement.type === 'FunctionDeclaration') {
75
+ return;
76
+ }
77
+ if (statement.type === 'IfStatement') {
78
+ refuseInnerBreak(statement.consequent);
79
+ refuseInnerBreak(statement.alternate);
80
+ }
81
+ else if (statement.type === 'BlockStatement') {
82
+ refuseInnerBreak(statement.body);
83
+ }
84
+ }
85
+ /**
86
+ * Whether an expression reads the same each time it is worked out: a name, a field of one, or a literal.
87
+ *
88
+ * @param node The expression.
89
+ *
90
+ * @returns Whether it does.
91
+ */
92
+ const readsSame = (node) => node.type === 'Identifier' ||
93
+ node.type === 'NumericLiteral' ||
94
+ node.type === 'StringLiteral' ||
95
+ node.type === 'BooleanLiteral' ||
96
+ (node.type === 'MemberExpression' &&
97
+ !node.computed &&
98
+ readsSame(node.object));
99
+ /**
100
+ * A `switch` as the `if … else if …` chain it runs as. Each case tests `discriminant === test`, and runs its own
101
+ * statements then the next cases' until one ends. Empty cases share the next one's statements, and the
102
+ * default is the last `else`. A discriminant that is not a plain read is worked out once, into a `const`.
103
+ *
104
+ * @param statement The switch.
105
+ *
106
+ * @returns The chain.
107
+ */
108
+ export function switchAsIf(statement) {
109
+ if (!readsSame(statement.discriminant)) {
110
+ const name = {
111
+ type: 'Identifier',
112
+ // `@` keeps it from naming anything the app declares.
113
+ name: `switch@${statement.start ?? 0}`,
114
+ };
115
+ return {
116
+ type: 'BlockStatement',
117
+ body: [
118
+ {
119
+ type: 'VariableDeclaration',
120
+ kind: 'const',
121
+ declarations: [
122
+ {
123
+ type: 'VariableDeclarator',
124
+ id: name,
125
+ init: statement.discriminant,
126
+ loc: statement.discriminant.loc,
127
+ },
128
+ ],
129
+ loc: statement.discriminant.loc,
130
+ },
131
+ switchAsIf({ ...statement, discriminant: name }),
132
+ ],
133
+ directives: [],
134
+ };
135
+ }
136
+ const { cases, discriminant } = statement;
137
+ // What each case runs: its own statements, then the next cases' until one ends.
138
+ const runs = cases.map((_, index) => {
139
+ const run = [];
140
+ for (let at = index; at < cases.length; at++) {
141
+ const { statements, ends } = endOfCase(cases[at].consequent);
142
+ run.push(...statements);
143
+ if (ends)
144
+ break;
145
+ }
146
+ refuseInnerBreak(run);
147
+ return run;
148
+ });
149
+ // Empty cases join the next case with a body.
150
+ const groups = [];
151
+ let pending = { tests: [], hasDefault: false, statements: [] };
152
+ cases.forEach((switchCase, index) => {
153
+ if (switchCase.test)
154
+ pending.tests.push(switchCase.test);
155
+ else
156
+ pending.hasDefault = true;
157
+ if (switchCase.consequent.length || index === cases.length - 1) {
158
+ pending.statements = runs[index];
159
+ groups.push(pending);
160
+ pending = { tests: [], hasDefault: false, statements: [] };
161
+ }
162
+ });
163
+ // The default's group runs for every value the other cases miss, its own tests included.
164
+ const fallback = groups.find(group => group.hasDefault);
165
+ const block = (statements) => ({
166
+ type: 'BlockStatement',
167
+ body: statements,
168
+ directives: [],
169
+ });
170
+ let chain = fallback ? block(fallback.statements) : null;
171
+ for (const group of groups.reverse()) {
172
+ if (group.hasDefault || (!fallback && !group.statements.length))
173
+ continue;
174
+ const test = group.tests
175
+ .map((caseTest) => ({
176
+ type: 'BinaryExpression',
177
+ operator: '===',
178
+ left: discriminant,
179
+ right: caseTest,
180
+ loc: caseTest.loc,
181
+ }))
182
+ .reduce((left, right) => ({
183
+ type: 'LogicalExpression',
184
+ operator: '||',
185
+ left,
186
+ right,
187
+ loc: left.loc,
188
+ }));
189
+ chain = {
190
+ type: 'IfStatement',
191
+ test,
192
+ consequent: block(group.statements),
193
+ alternate: chain,
194
+ loc: test.loc,
195
+ };
196
+ }
197
+ return chain ?? block([]);
198
+ }
@@ -0,0 +1,450 @@
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
+ // tagged-records.mts — an object state of several shapes: a hidden tag, the union of the fields, and the tests on
17
+ // the tag that narrow which fields can be read.
18
+ /*----------------------------------------------------------------------------------------------------------------------
19
+ - Imports
20
+ ---------------------------------------------------------------------------------------------------------------------*/
21
+ import { aotError } from './diagnostics.mjs';
22
+ import { stateRead, stateShape } from './expressions.mjs';
23
+ import { holdLater } from './typing.mjs';
24
+ import { HiddenField, RuntimeLeaf, evalStatic, foldScope, hasBinding, rethrowFoldLimit, setBinding, } from './static-eval.mjs';
25
+ import { BOOL, FLOAT, INT, STRING, stateType } from './ir/types.mjs';
26
+ /*----------------------------------------------------------------------------------------------------------------------
27
+ - Implementation
28
+ ---------------------------------------------------------------------------------------------------------------------*/
29
+ /** Each tagged object code can read, and what it is. */
30
+ const views = new WeakMap();
31
+ /** Each read of a tag worked out at run time, and the record whose tag it is. */
32
+ const tagLeaves = new WeakMap();
33
+ /**
34
+ * A read of a scalar state, as a local that stands for it.
35
+ *
36
+ * @param state The state.
37
+ *
38
+ * @returns The local.
39
+ */
40
+ export const stateLocal = (state) => holdLater({
41
+ source: { kind: 'state', state, location: undefined },
42
+ expression: stateRead(state),
43
+ }, stateShape(state), () => ({
44
+ slotKind: state.slotKind,
45
+ isBoolean: state.isBoolean,
46
+ ...(state.widened === 'number' ? { isLiteral: true } : {}),
47
+ }));
48
+ /**
49
+ * A tag value as code writes it.
50
+ *
51
+ * @param value The value.
52
+ *
53
+ * @returns `'busy'`, `2` or `true`.
54
+ */
55
+ export const tagText = (value) => typeof value === 'string' ? `'${value}'` : String(value);
56
+ /**
57
+ * The shapes' tag values, as a list for a message.
58
+ *
59
+ * @param values The values.
60
+ *
61
+ * @returns `'idle' or 'busy'`.
62
+ */
63
+ const tagList = (values) => values.map(tagText).join(' or ');
64
+ /**
65
+ * Whether a shape's tag equals a value, as `===` or `==` compares them.
66
+ *
67
+ * @param record The record.
68
+ * @param value The value it is compared with.
69
+ * @param strict The test is `===` or `!==`.
70
+ * @param shape The shape.
71
+ *
72
+ * @returns Whether the tag equals the value.
73
+ */
74
+ const tagEquals = (record, value, strict, shape) => strict
75
+ ? record.tag.values[shape] === value
76
+ : record.tag.values[shape] == value;
77
+ /**
78
+ * A comparison of the hidden tag with a shape's index.
79
+ *
80
+ * @param record The record.
81
+ * @param shape The shape.
82
+ * @param operator `==` or `!=`.
83
+ *
84
+ * @returns The comparison.
85
+ */
86
+ function tagIs(record, shape, operator = '==') {
87
+ const { state } = record.tag;
88
+ return {
89
+ kind: 'compare',
90
+ operator,
91
+ left: { kind: 'state', state, type: stateType(state) },
92
+ right: { kind: 'number', value: shape, type: INT },
93
+ type: BOOL,
94
+ };
95
+ }
96
+ /**
97
+ * A read of the tag where the shape isn't known: the tag value of the shape the hidden tag names.
98
+ *
99
+ * @param record The record.
100
+ * @param shapes The shapes it can have there.
101
+ *
102
+ * @returns The read.
103
+ */
104
+ function tagLeaf(record, shapes) {
105
+ const values = shapes.map(shape => record.tag.values[shape]);
106
+ const isString = typeof values[0] === 'string';
107
+ const isBoolean = typeof values[0] === 'boolean';
108
+ const isFloat = values.some(value => typeof value === 'number' && !Number.isInteger(value));
109
+ const type = isString ? STRING : isBoolean ? BOOL : isFloat ? FLOAT : INT;
110
+ const constant = (value) => typeof value === 'string'
111
+ ? { kind: 'string', value, type }
112
+ : typeof value === 'boolean'
113
+ ? { kind: 'boolean', value, type }
114
+ : { kind: 'number', value, type };
115
+ let expression = constant(values.at(-1));
116
+ for (let position = shapes.length - 2; position >= 0; position--) {
117
+ expression = {
118
+ kind: 'conditional',
119
+ test: tagIs(record, shapes[position]),
120
+ consequent: constant(values[position]),
121
+ alternate: expression,
122
+ type,
123
+ };
124
+ }
125
+ const leaf = new RuntimeLeaf({
126
+ slotKind: isString ? 'string' : isFloat ? 'float' : 'int',
127
+ isBoolean,
128
+ source: { kind: 'fixed', expression, location: undefined },
129
+ expression,
130
+ });
131
+ tagLeaves.set(leaf, record);
132
+ return leaf;
133
+ }
134
+ /**
135
+ * A field only some of the shapes have, where the shape isn't known.
136
+ *
137
+ * @param record The record.
138
+ * @param key The field's path, joined with dots.
139
+ * @param field Its slot.
140
+ *
141
+ * @returns The field.
142
+ */
143
+ function hiddenField(record, key, field) {
144
+ const { tag, name } = record;
145
+ const owners = tag.values.filter((_, shape) => tag.shapes[shape].has(key));
146
+ const first = tagText(owners[0]);
147
+ return new HiddenField(field, `AOT: "${name}.${key}" is only there when ${name}.${tag.key} is ${tagList(owners)}`, `test the tag first: ${name}.${tag.key} === ${first} && …, or if (${name}.${tag.key} === ${first}) { … }.`);
148
+ }
149
+ /**
150
+ * A tagged object as code reads it where it can have only some shapes: the tag a constant when there is one shape,
151
+ * the fields every shape has, and the others hidden.
152
+ *
153
+ * @param record The record.
154
+ * @param shapes The shapes.
155
+ *
156
+ * @returns The object.
157
+ */
158
+ export function taggedTreeOf(record, shapes) {
159
+ const tree = {};
160
+ const place = (key, value) => {
161
+ const path = key.split('.');
162
+ let branch = tree;
163
+ for (const part of path.slice(0, -1)) {
164
+ branch = (branch[part] ??= {});
165
+ }
166
+ branch[path.at(-1)] = value;
167
+ };
168
+ const { tag } = record;
169
+ place(tag.key, shapes.length === 1 ? tag.values[shapes[0]] : tagLeaf(record, shapes));
170
+ for (const [key, field] of record.fields) {
171
+ const visible = shapes.every(shape => tag.shapes[shape].has(key));
172
+ place(key, visible
173
+ ? new RuntimeLeaf(stateLocal(field))
174
+ : hiddenField(record, key, field));
175
+ }
176
+ views.set(tree, { record, shapes });
177
+ return tree;
178
+ }
179
+ /**
180
+ * The shapes a tagged object can have where it is read.
181
+ *
182
+ * @param value The object.
183
+ *
184
+ * @returns The shapes, or null when it isn't a tagged object.
185
+ */
186
+ export const shapesOf = (value) => (typeof value === 'object' && value !== null && views.get(value)?.shapes) ||
187
+ null;
188
+ /**
189
+ * Whether a value is a read of a record's own tag where its shape isn't known.
190
+ *
191
+ * @param value The value.
192
+ * @param record The record.
193
+ *
194
+ * @returns Whether it is.
195
+ */
196
+ export const isTagOf = (value, record) => value instanceof RuntimeLeaf && tagLeaves.get(value) === record;
197
+ /**
198
+ * The tagged object a name reads, if it reads one.
199
+ *
200
+ * @param node The expression.
201
+ * @param environment The expression environment.
202
+ *
203
+ * @returns The name and the object, or null.
204
+ */
205
+ function viewOf(node, environment) {
206
+ if (node.type !== 'Identifier' ||
207
+ environment.locals.has(node.name) ||
208
+ !hasBinding(environment.constants, node.name)) {
209
+ return null;
210
+ }
211
+ const value = environment.constants[node.name];
212
+ const view = typeof value === 'object' && value !== null ? views.get(value) : undefined;
213
+ return view ? { name: node.name, view } : null;
214
+ }
215
+ /**
216
+ * The tagged object whose tag an expression reads: `s.kind`.
217
+ *
218
+ * @param node The expression.
219
+ * @param environment The expression environment.
220
+ *
221
+ * @returns The name and the object, or null.
222
+ */
223
+ function tagReadOf(node, environment) {
224
+ if (node.type !== 'MemberExpression')
225
+ return null;
226
+ const key = !node.computed
227
+ ? node.property.name
228
+ : node.property.type === 'StringLiteral'
229
+ ? node.property.value
230
+ : null;
231
+ const found = viewOf(node.object, environment);
232
+ return found && key === found.view.record.tag.key ? found : null;
233
+ }
234
+ /**
235
+ * Reads a test of a tagged object's tag against a constant: `s.kind === 'busy'`, `'idle' !== s.kind`.
236
+ *
237
+ * @param node The test.
238
+ * @param environment The expression environment.
239
+ *
240
+ * @returns The test, or null when it is none.
241
+ */
242
+ export function tagTestOf(node, environment) {
243
+ if (node.type !== 'BinaryExpression' ||
244
+ !['===', '==', '!==', '!='].includes(node.operator)) {
245
+ return null;
246
+ }
247
+ for (const [member, other] of [
248
+ [node.left, node.right],
249
+ [node.right, node.left],
250
+ ]) {
251
+ const found = tagReadOf(member, environment);
252
+ if (!found)
253
+ continue;
254
+ const key = found.view.record.tag.key;
255
+ let value;
256
+ try {
257
+ value = evalStatic(other, foldScope(environment, environment.constants ?? {}));
258
+ }
259
+ catch (error) {
260
+ rethrowFoldLimit(error);
261
+ continue;
262
+ }
263
+ const { name, view } = found;
264
+ const { record } = view;
265
+ const strict = node.operator.length === 3;
266
+ const all = record.tag.values.map((_, shape) => shape);
267
+ if (!all.some(shape => tagEquals(record, value, strict, shape))) {
268
+ throw aotError(`AOT: ${name}.${key} is never ${tagText(value)}`, `its shapes have ${key} ${tagList(record.tag.values)}.`);
269
+ }
270
+ const matching = view.shapes.filter(shape => tagEquals(record, value, strict, shape));
271
+ const rest = view.shapes.filter(shape => !matching.includes(shape));
272
+ const negated = node.operator.startsWith('!');
273
+ return {
274
+ name,
275
+ view,
276
+ whenTrue: negated ? rest : matching,
277
+ whenFalse: negated ? matching : rest,
278
+ };
279
+ }
280
+ return null;
281
+ }
282
+ /**
283
+ * Lowers a test of a tagged object's tag: a comparison of the hidden tag, or a constant when the shapes it can
284
+ * have there decide it.
285
+ *
286
+ * @param test The test.
287
+ *
288
+ * @returns The test's value.
289
+ */
290
+ export function lowerTagTest(test) {
291
+ if (!test.whenTrue.length || !test.whenFalse.length) {
292
+ return { kind: 'boolean', value: !test.whenFalse.length, type: BOOL };
293
+ }
294
+ const { record } = test.view;
295
+ if (test.whenTrue.length === 1)
296
+ return tagIs(record, test.whenTrue[0]);
297
+ if (test.whenFalse.length === 1) {
298
+ return tagIs(record, test.whenFalse[0], '!=');
299
+ }
300
+ return test.whenTrue
301
+ .map(shape => tagIs(record, shape))
302
+ .reduce((left, right) => ({
303
+ kind: 'logical',
304
+ operator: '||',
305
+ left,
306
+ right,
307
+ type: BOOL,
308
+ }));
309
+ }
310
+ /**
311
+ * The tagged objects narrowed to the shapes an outcome leaves them; one that keeps every shape it had, or none, is
312
+ * left as it is.
313
+ *
314
+ * @param sets The shapes, by name.
315
+ * @param environment The expression environment.
316
+ *
317
+ * @returns The objects, by name.
318
+ */
319
+ function treesOf(sets, environment) {
320
+ const trees = new Map();
321
+ for (const [name, { record, shapes }] of sets) {
322
+ const here = viewOf({ type: 'Identifier', name }, environment);
323
+ if (shapes.length && shapes.length !== here?.view.shapes.length) {
324
+ trees.set(name, taggedTreeOf(record, shapes));
325
+ }
326
+ }
327
+ return trees;
328
+ }
329
+ /**
330
+ * The shapes either of two outcomes leaves, as when `a || b` is true. A name one outcome doesn't narrow keeps the
331
+ * shapes it has where that outcome is tested.
332
+ *
333
+ * @param first The first outcome's shapes.
334
+ * @param firstAt Where the first outcome is tested.
335
+ * @param second The second outcome's shapes.
336
+ * @param secondAt Where the second outcome is tested.
337
+ *
338
+ * @returns The shapes, by name.
339
+ */
340
+ function joinShapes(first, firstAt, second, secondAt) {
341
+ const sets = new Map();
342
+ for (const name of new Set([...first.keys(), ...second.keys()])) {
343
+ const identifier = { type: 'Identifier', name };
344
+ const one = first.get(name) ?? viewOf(identifier, firstAt)?.view;
345
+ const other = second.get(name) ?? viewOf(identifier, secondAt)?.view;
346
+ if (!one || !other)
347
+ continue;
348
+ const shapes = [...new Set([...one.shapes, ...other.shapes])].sort((left, right) => left - right);
349
+ sets.set(name, { record: one.record, shapes });
350
+ }
351
+ return sets;
352
+ }
353
+ /**
354
+ * The shapes a test leaves tagged objects on each outcome: a test on a tag, `!`, `&&` and `||` of them.
355
+ *
356
+ * @param test The test.
357
+ * @param environment The expression environment.
358
+ *
359
+ * @returns The shapes each outcome leaves.
360
+ */
361
+ function shapesOn(test, environment) {
362
+ if (test.type === 'UnaryExpression' && test.operator === '!') {
363
+ const inner = shapesOn(test.argument, environment);
364
+ return { whenTrue: inner.whenFalse, whenFalse: inner.whenTrue };
365
+ }
366
+ if (test.type === 'LogicalExpression' &&
367
+ (test.operator === '&&' || test.operator === '||')) {
368
+ // The right side is tested where the left side's outcome lets it run.
369
+ const isAnd = test.operator === '&&';
370
+ const left = shapesOn(test.left, environment);
371
+ const leftRuns = isAnd ? left.whenTrue : left.whenFalse;
372
+ const rightAt = narrowed(environment, treesOf(leftRuns, environment));
373
+ const right = shapesOn(test.right, rightAt);
374
+ // Both sides decide one outcome; either side decides the other.
375
+ const both = new Map([
376
+ ...leftRuns,
377
+ ...(isAnd ? right.whenTrue : right.whenFalse),
378
+ ]);
379
+ const either = isAnd
380
+ ? joinShapes(left.whenFalse, environment, right.whenFalse, rightAt)
381
+ : joinShapes(left.whenTrue, environment, right.whenTrue, rightAt);
382
+ return isAnd
383
+ ? { whenTrue: both, whenFalse: either }
384
+ : { whenTrue: either, whenFalse: both };
385
+ }
386
+ // `r.ok` as a test: the shapes whose tag is truthy.
387
+ const read = tagReadOf(test, environment);
388
+ const truthy = read?.view.shapes.filter(shape => read.view.record.tag.values[shape]);
389
+ const tagTest = read
390
+ ? {
391
+ ...read,
392
+ whenTrue: truthy,
393
+ whenFalse: read.view.shapes.filter(shape => !truthy.includes(shape)),
394
+ }
395
+ : tagTestOf(test, environment);
396
+ const side = (shapes) => tagTest
397
+ ? new Map([[tagTest.name, { record: tagTest.view.record, shapes }]])
398
+ : new Map();
399
+ return {
400
+ whenTrue: side(tagTest?.whenTrue ?? []),
401
+ whenFalse: side(tagTest?.whenFalse ?? []),
402
+ };
403
+ }
404
+ /**
405
+ * The tagged objects a test narrows: a test on a tag, `!`, `&&` and `||` of them.
406
+ *
407
+ * @param test The test.
408
+ * @param environment The expression environment.
409
+ *
410
+ * @returns What each outcome narrows.
411
+ */
412
+ export function narrowOn(test, environment) {
413
+ const { whenTrue, whenFalse } = shapesOn(test, environment);
414
+ return {
415
+ whenTrue: treesOf(whenTrue, environment),
416
+ whenFalse: treesOf(whenFalse, environment),
417
+ };
418
+ }
419
+ /**
420
+ * Constants with names bound to narrowed objects.
421
+ *
422
+ * @param scope The constants.
423
+ * @param bindings The objects, by name.
424
+ *
425
+ * @returns The constants.
426
+ */
427
+ export function narrowedScope(scope, bindings) {
428
+ if (!bindings.size)
429
+ return scope;
430
+ const constants = { ...scope };
431
+ for (const [name, tree] of bindings)
432
+ setBinding(constants, name, tree);
433
+ return constants;
434
+ }
435
+ /**
436
+ * An environment with names bound to narrowed objects.
437
+ *
438
+ * @param environment The expression environment.
439
+ * @param bindings The objects, by name.
440
+ *
441
+ * @returns The environment.
442
+ */
443
+ export function narrowed(environment, bindings) {
444
+ if (!bindings.size)
445
+ return environment;
446
+ return {
447
+ ...environment,
448
+ constants: narrowedScope(environment.constants, bindings),
449
+ };
450
+ }