embedded-react 0.20.0 → 0.22.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.
- package/NOTICE +5 -0
- package/README.md +3 -2
- package/aot/app-file-loader.mjs +116 -0
- package/aot/compile.mjs +17 -47
- package/aot/compiler/alerts.mjs +604 -0
- package/aot/compiler/animations.mjs +299 -57
- package/aot/compiler/boot.mjs +27 -2
- package/aot/compiler/check.mjs +62 -10
- package/aot/compiler/collect.mjs +517 -137
- package/aot/compiler/contexts.mjs +391 -0
- package/aot/compiler/control-flow.mjs +276 -117
- package/aot/compiler/custom-hooks.mjs +686 -0
- package/aot/compiler/elements/button.mjs +182 -0
- package/aot/compiler/elements/image-background.mjs +76 -0
- package/aot/compiler/elements/image.mjs +2 -1
- package/aot/compiler/elements/props.mjs +47 -8
- package/aot/compiler/elements/rewrite.mjs +118 -0
- package/aot/compiler/elements/section-list.mjs +370 -0
- package/aot/compiler/expressions.mjs +1378 -97
- package/aot/compiler/handlers.mjs +1807 -354
- package/aot/compiler/helper-values.mjs +312 -0
- package/aot/compiler/ir/nodes.mjs +40 -1
- package/aot/compiler/ir/reads.mjs +206 -5
- package/aot/compiler/ir/text.mjs +5 -1
- package/aot/compiler/ir/types.mjs +12 -0
- package/aot/compiler/kept-states.mjs +177 -0
- package/aot/compiler/keyboard-dismiss.mjs +99 -0
- package/aot/compiler/keyboard.mjs +1 -1
- package/aot/compiler/list-items.mjs +226 -0
- package/aot/compiler/list-order.mjs +586 -0
- package/aot/compiler/list-split.mjs +259 -0
- package/aot/compiler/loops.mjs +582 -0
- package/aot/compiler/lower.mjs +203 -53
- package/aot/compiler/native-files.mjs +439 -0
- package/aot/compiler/native-header.mjs +335 -0
- package/aot/compiler/native-modules.mjs +1173 -0
- package/aot/compiler/nodes.mjs +45 -31
- package/aot/compiler/options.mjs +3 -2
- package/aot/compiler/out.mjs +18 -1
- package/aot/compiler/package/animations.mjs +133 -23
- package/aot/compiler/package/assemble.mjs +2 -4
- package/aot/compiler/package/bytecode.mjs +37 -8
- package/aot/compiler/package/checks.mjs +4 -0
- package/aot/compiler/package/codegen.mjs +906 -33
- package/aot/compiler/package/enums.mjs +10 -0
- package/aot/compiler/package/format.mjs +16 -3
- package/aot/compiler/package/lower.mjs +707 -176
- package/aot/compiler/package/string-caps.mjs +515 -0
- package/aot/compiler/package/tables.mjs +24 -0
- package/aot/compiler/package/writer.mjs +22 -0
- package/aot/compiler/parse.mjs +3 -1
- package/aot/compiler/record-shapes.mjs +246 -0
- package/aot/compiler/records.mjs +654 -0
- package/aot/compiler/reducers.mjs +272 -0
- package/aot/compiler/scroll-to.mjs +112 -0
- package/aot/compiler/static-eval.mjs +315 -7
- package/aot/compiler/style-text.mjs +20 -5
- package/aot/compiler/svg.mjs +13 -7
- package/aot/compiler/switch-cases.mjs +198 -0
- package/aot/compiler/tagged-records.mjs +450 -0
- package/aot/compiler/typing.mjs +307 -0
- package/aot/compiler/updaters.mjs +321 -0
- package/aot/compiler/window-dimensions.mjs +94 -0
- package/aot/compiler/worked-values.mjs +319 -0
- package/aot/demo-file.mjs +30 -0
- package/aot/style-map.mjs +94 -3
- package/assets/bake-font.mjs +187 -244
- package/assets/bake-image.mjs +47 -71
- package/assets/bake-svg.mjs +465 -533
- package/assets/build-builtin-font.mjs +14 -27
- package/assets/emit-c.mjs +124 -204
- package/assets/emit-container.mjs +129 -197
- package/assets/emit-pack.mjs +92 -136
- package/assets/font-config.mjs +19 -27
- package/assets/font-sizes.mjs +432 -507
- package/assets/glyph-coverage.mjs +170 -214
- package/assets/index.mjs +52 -97
- package/assets/rasterize.mjs +173 -194
- package/assets/svg-loader.mjs +42 -48
- package/build.mjs +85 -94
- package/cli.mjs +490 -586
- package/compile-bin.mjs +24 -36
- package/flash.mjs +297 -401
- package/hotreload/dev-device.mjs +229 -270
- package/hotreload/pack-app.mjs +118 -159
- package/hotreload/pack-split.mjs +146 -213
- package/hotreload/package-transfer.mjs +128 -131
- package/hotreload/protocol.mjs +118 -118
- package/hotreload/uploader.mjs +132 -159
- package/hotreload/watch-tree.mjs +56 -65
- package/pack-container.mjs +94 -116
- package/package.json +19 -16
- package/persist-transform.mjs +89 -105
- package/qjsc-wasm.mjs +47 -72
- package/sim/embedded-react.wasm +0 -0
- package/sim/index.html +1 -1
- package/sim-server.mjs +260 -354
- package/src/embedded-react/Alert.mjs +112 -0
- package/src/embedded-react/Animated.mjs +412 -0
- package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
- package/src/embedded-react/{Button.js → Button.mjs} +29 -53
- package/src/embedded-react/Dimensions.mjs +32 -0
- package/src/embedded-react/Easing.mjs +34 -0
- package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
- package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
- package/src/embedded-react/Keyboard.mjs +82 -0
- package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
- package/src/embedded-react/PanResponder.mjs +256 -0
- package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
- package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
- package/src/embedded-react/SectionList.mjs +103 -0
- package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
- package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
- package/src/embedded-react/background-image.mjs +321 -0
- package/src/embedded-react/{components.js → components.mjs} +1 -3
- package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
- package/src/embedded-react/index.d.ts +238 -5
- package/src/embedded-react/index.js +26 -17
- package/src/embedded-react/layout-anim-config.mjs +85 -0
- package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
- package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
- package/src/embedded-react/nativeModule.mjs +371 -0
- package/src/embedded-react/split-style.mjs +57 -0
- package/src/embedded-react/svg-ops.mjs +1075 -0
- package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
- package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
- package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
- package/src/host-config.mjs +512 -0
- package/src/{native-ui.js → native-ui.mjs} +1 -8
- package/src/props.mjs +341 -0
- package/src/{renderer.js → renderer.mjs} +30 -44
- package/src/embedded-react/Animated.js +0 -440
- package/src/embedded-react/Easing.js +0 -39
- package/src/embedded-react/PanResponder.js +0 -330
- package/src/embedded-react/SectionList.js +0 -148
- package/src/embedded-react/layout-anim-config.js +0 -101
- package/src/embedded-react/split-style.js +0 -58
- package/src/embedded-react/svg-ops.js +0 -1295
- package/src/host-config.js +0 -548
- package/src/props.js +0 -306
|
@@ -16,20 +16,60 @@
|
|
|
16
16
|
/*----------------------------------------------------------------------------------------------------------------------
|
|
17
17
|
- Imports
|
|
18
18
|
---------------------------------------------------------------------------------------------------------------------*/
|
|
19
|
-
import { parseColor, parsePath } from '../../src/embedded-react/svg-ops.
|
|
20
|
-
import { aotError, constantText, withLoc } from './diagnostics.mjs';
|
|
21
|
-
import { evalStatic } from './static-eval.mjs';
|
|
22
|
-
import {
|
|
19
|
+
import { parseColor, parsePath } from '../../src/embedded-react/svg-ops.mjs';
|
|
20
|
+
import { aotError, constantText, ENGINE_STRING_MAX, withLoc, } from './diagnostics.mjs';
|
|
21
|
+
import { evalStatic, foldScope, RuntimeLeaf } from './static-eval.mjs';
|
|
22
|
+
import { ALERT_CALL, raiseAlert, withAlertBase } from './alerts.mjs';
|
|
23
|
+
import { KEYBOARD_DISMISS_CALL } from './keyboard-dismiss.mjs';
|
|
24
|
+
import { fieldsUnder } from './list-items.mjs';
|
|
25
|
+
import { lowerNativeCall, nativeCalleeOf, nativeEventOf, nativeRecordCallOf, recordTreeOf, valueCount, } from './native-modules.mjs';
|
|
26
|
+
import { itemCallback, listChainOf, orderStatements } from './list-order.mjs';
|
|
27
|
+
import { handlerSplitList, lowerSplitInto } from './list-split.mjs';
|
|
28
|
+
import { boundObjectOf, expandObjectDeclarator, lowerRecordSet, objectTreeOf, } from './records.mjs';
|
|
29
|
+
import { narrowOn, narrowed } from './tagged-records.mjs';
|
|
30
|
+
import { exits, helperEnvironment, statementsOf } from './helper-values.mjs';
|
|
31
|
+
import { lowerFor, lowerForOf } from './loops.mjs';
|
|
32
|
+
import { switchAsIf } from './switch-cases.mjs';
|
|
33
|
+
import { isReturnSet, updaterStatements } from './updaters.mjs';
|
|
34
|
+
import { actionChoice, actionEnvironment, prunedStatements, } from './reducers.mjs';
|
|
35
|
+
import { whenTyped } from './check.mjs';
|
|
36
|
+
import { copyLocal, holdLater, localShape, setLater, shapeOf, typedLater, } from './typing.mjs';
|
|
37
|
+
import { bareLocalOf, binarySource, stateRead, is64BitLocal, is64BitSlot, mix64Error, staticInt, isTime64, constDivisor, lowerSource, typeSource, slotValueOf, lowerExpr, lowerExprWide, lowerText, lowerLogText, buildsText, } from './expressions.mjs';
|
|
23
38
|
import { isFn } from './collect.mjs';
|
|
39
|
+
import { keepingStates, readingLatest } from './kept-states.mjs';
|
|
24
40
|
import { isAnimatedCall, resolveAnim, animValues, lowerAnimateStart, stopWaitOwner, } from './animations.mjs';
|
|
25
41
|
import { svgNum, CAP_MAP, JOIN_MAP, arcTape, circleTape, rectTape, lineTape, checkedTapeNumber, checkVectorPaints, vectorPaintOf, DEFAULT_MITER_LIMIT, } from './svg.mjs';
|
|
42
|
+
import { isScrollToCall, lowerScrollTo, SCROLL_POSITION_FIELDS, } from './scroll-to.mjs';
|
|
26
43
|
import { armedFlag } from './ir/functions.mjs';
|
|
27
|
-
import {
|
|
44
|
+
import { INT, isConvertible64, isIntSlot, isTime, refType, STRING, } from './ir/types.mjs';
|
|
28
45
|
/*----------------------------------------------------------------------------------------------------------------------
|
|
29
46
|
- Constants
|
|
30
47
|
---------------------------------------------------------------------------------------------------------------------*/
|
|
48
|
+
/** The slot a native event's value of each type is read as: an Int64 converts like any number. */
|
|
49
|
+
const VALUE_SLOTS = {
|
|
50
|
+
int: { slotKind: 'int' },
|
|
51
|
+
float: { slotKind: 'float' },
|
|
52
|
+
bool: { slotKind: 'int', isBoolean: true },
|
|
53
|
+
int64: { slotKind: 'i64', isLiteral: true },
|
|
54
|
+
string: { slotKind: 'string' },
|
|
55
|
+
};
|
|
31
56
|
/** The constant 0, which a remainder by 0 or ±1 stores. */
|
|
32
57
|
const ZERO = { kind: 'number', value: 0, type: INT };
|
|
58
|
+
/** Keys an AST node keeps besides what it says: where it is, and its comments. */
|
|
59
|
+
const POSITION_KEYS = new Set([
|
|
60
|
+
'loc',
|
|
61
|
+
'start',
|
|
62
|
+
'end',
|
|
63
|
+
'range',
|
|
64
|
+
'extra',
|
|
65
|
+
'leadingComments',
|
|
66
|
+
'trailingComments',
|
|
67
|
+
'innerComments',
|
|
68
|
+
]);
|
|
69
|
+
/** Update locals made so far, which numbers the next one's name. */
|
|
70
|
+
let updateRows = 0;
|
|
71
|
+
/** Counts the native calls whose record is kept, to name its locals as no JS binding can be named. */
|
|
72
|
+
let keptRecords = 0;
|
|
33
73
|
/** Each updateVector shape key and the numbers its array takes, for errors. */
|
|
34
74
|
const UPDATE_VECTOR_ARGUMENTS = {
|
|
35
75
|
arc: '[cx, cy, r, startAngle, endAngle]',
|
|
@@ -40,82 +80,670 @@ const UPDATE_VECTOR_ARGUMENTS = {
|
|
|
40
80
|
/*----------------------------------------------------------------------------------------------------------------------
|
|
41
81
|
- Implementation
|
|
42
82
|
---------------------------------------------------------------------------------------------------------------------*/
|
|
83
|
+
/**
|
|
84
|
+
* Whether a value is left out of an item: null or undefined.
|
|
85
|
+
*
|
|
86
|
+
* @param node The value.
|
|
87
|
+
*
|
|
88
|
+
* @returns Whether it is.
|
|
89
|
+
*/
|
|
90
|
+
const leavesOut = (node) => node.type === 'NullLiteral' ||
|
|
91
|
+
(node.type === 'Identifier' && node.name === 'undefined');
|
|
92
|
+
/**
|
|
93
|
+
* Whether two expressions are written the same, wherever they are.
|
|
94
|
+
*
|
|
95
|
+
* @param first One.
|
|
96
|
+
* @param second The other.
|
|
97
|
+
*
|
|
98
|
+
* @returns Whether they are.
|
|
99
|
+
*/
|
|
100
|
+
function sameNode(first, second) {
|
|
101
|
+
if (first === second)
|
|
102
|
+
return true;
|
|
103
|
+
if (!first ||
|
|
104
|
+
!second ||
|
|
105
|
+
typeof first !== 'object' ||
|
|
106
|
+
typeof second !== 'object' ||
|
|
107
|
+
Array.isArray(first) !== Array.isArray(second)) {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
const keysOf = (value) => Object.keys(value).filter(key => !POSITION_KEYS.has(key));
|
|
111
|
+
const firstKeys = keysOf(first);
|
|
112
|
+
return (firstKeys.length === keysOf(second).length &&
|
|
113
|
+
firstKeys.every(key => sameNode(first[key], second[key])));
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Whether an expression reads any of some names.
|
|
117
|
+
*
|
|
118
|
+
* @param node The expression.
|
|
119
|
+
* @param names The names.
|
|
120
|
+
*
|
|
121
|
+
* @returns Whether it does.
|
|
122
|
+
*/
|
|
123
|
+
function mentions(node, names) {
|
|
124
|
+
if (!node || typeof node !== 'object')
|
|
125
|
+
return false;
|
|
126
|
+
if (Array.isArray(node))
|
|
127
|
+
return node.some(child => mentions(child, names));
|
|
128
|
+
const astNode = node;
|
|
129
|
+
if (astNode.type === 'Identifier')
|
|
130
|
+
return names.has(astNode.name);
|
|
131
|
+
return Object.entries(astNode).some(([key, child]) => !POSITION_KEYS.has(key) &&
|
|
132
|
+
!(key === 'property' &&
|
|
133
|
+
(astNode.type === 'MemberExpression' ||
|
|
134
|
+
astNode.type === 'OptionalMemberExpression') &&
|
|
135
|
+
!astNode.computed) &&
|
|
136
|
+
!(key === 'key' &&
|
|
137
|
+
astNode.type === 'ObjectProperty' &&
|
|
138
|
+
!astNode.computed) &&
|
|
139
|
+
mentions(child, names));
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* The value an item's field is set to, checked against the field.
|
|
143
|
+
*
|
|
144
|
+
* @param field The field.
|
|
145
|
+
* @param valueNode Its value.
|
|
146
|
+
* @param listState The list.
|
|
147
|
+
* @param environment The expression environment.
|
|
148
|
+
*
|
|
149
|
+
* @returns The value.
|
|
150
|
+
*/
|
|
151
|
+
function itemValue(field, valueNode, listState, environment) {
|
|
152
|
+
if (field.kind === 'string') {
|
|
153
|
+
const text = lowerText(valueNode, environment);
|
|
154
|
+
checkConstantFits(text, `field "${field.key}" of list state "${listState.name}"`);
|
|
155
|
+
return { field, text };
|
|
156
|
+
}
|
|
157
|
+
const value = lowerExpr(valueNode, environment);
|
|
158
|
+
if ((field.kind === 'bool') !== (shapeOf(value) === 'bool')) {
|
|
159
|
+
throw aotError(`AOT: field "${field.key || 'value'}" of list state "${listState.name}" holds ${field.kind === 'bool' ? 'a boolean' : 'a number'}`, 'give it a value of the same kind as the initial ones.');
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
field,
|
|
163
|
+
value: field.kind === 'bool'
|
|
164
|
+
? value
|
|
165
|
+
: storeValue(value, () => field.kind),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* The fields an appended item sets, by key: an object literal's, nested ones flattened into dotted keys, or a plain
|
|
170
|
+
* value's one field. A field set to null or undefined is left out.
|
|
171
|
+
*
|
|
172
|
+
* @param item The appended item.
|
|
173
|
+
* @param struct The list's fields.
|
|
174
|
+
* @param listName The list, for errors.
|
|
175
|
+
*
|
|
176
|
+
* @returns Each field's value.
|
|
177
|
+
*/
|
|
178
|
+
function appendedFields(item, struct, listName) {
|
|
179
|
+
const given = new Map();
|
|
180
|
+
if (struct.plain) {
|
|
181
|
+
if (item.type === 'ObjectExpression') {
|
|
182
|
+
throw aotError(`AOT: list state "${listName}" holds plain values, not objects`, 'append a value of the same kind as the initial ones.');
|
|
183
|
+
}
|
|
184
|
+
if (!leavesOut(item)) {
|
|
185
|
+
given.set('', item);
|
|
186
|
+
}
|
|
187
|
+
return given;
|
|
188
|
+
}
|
|
189
|
+
const visit = (object, path) => {
|
|
190
|
+
for (const property of object.properties) {
|
|
191
|
+
if (property.type !== 'ObjectProperty' || property.computed) {
|
|
192
|
+
throw aotError('AOT: an appended item must be an object literal of plain fields', 'write each field out: {title: t, n: 1}. Spreads, methods and computed keys are not lowered.');
|
|
193
|
+
}
|
|
194
|
+
const fieldPath = [...path, propertyKey(property)];
|
|
195
|
+
if (property.value.type === 'ObjectExpression') {
|
|
196
|
+
visit(property.value, fieldPath);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
// A field set to null or undefined, or an object of fields set to one, is left out.
|
|
200
|
+
const name = fieldPath.join('.');
|
|
201
|
+
const isField = struct.fields.some(field => field.key === name);
|
|
202
|
+
if (!isField &&
|
|
203
|
+
!(leavesOut(property.value) && fieldsUnder(struct, fieldPath).length)) {
|
|
204
|
+
throw noField(listName, name);
|
|
205
|
+
}
|
|
206
|
+
if (!leavesOut(property.value)) {
|
|
207
|
+
given.set(name, property.value);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
if (item.type !== 'ObjectExpression') {
|
|
212
|
+
throw new Error('AOT: appended list items must be object literals');
|
|
213
|
+
}
|
|
214
|
+
visit(item, []);
|
|
215
|
+
return given;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* An object property's key.
|
|
219
|
+
*
|
|
220
|
+
* @param property The property.
|
|
221
|
+
*
|
|
222
|
+
* @returns The key.
|
|
223
|
+
*/
|
|
224
|
+
const propertyKey = (property) => property.key.name ??
|
|
225
|
+
String(property.key.value);
|
|
226
|
+
/**
|
|
227
|
+
* The error for a field a list's items don't have.
|
|
228
|
+
*
|
|
229
|
+
* @param listName The list.
|
|
230
|
+
* @param name The field.
|
|
231
|
+
*
|
|
232
|
+
* @returns The error.
|
|
233
|
+
*/
|
|
234
|
+
const noField = (listName, name) => aotError(`AOT: list state "${listName}" has no field "${name}"`, "a list's fields are those of its initial items. Give one of them the field, and leave it out of the " +
|
|
235
|
+
'others to make it optional.');
|
|
236
|
+
/**
|
|
237
|
+
* A list row index: a whole number.
|
|
238
|
+
*
|
|
239
|
+
* @param node The index.
|
|
240
|
+
* @param listName The list, for errors.
|
|
241
|
+
* @param environment The expression environment.
|
|
242
|
+
*
|
|
243
|
+
* @returns The index.
|
|
244
|
+
*/
|
|
245
|
+
function rowIndexOf(node, listName, environment) {
|
|
246
|
+
const index = lowerExpr(node, environment);
|
|
247
|
+
whenTyped(() => {
|
|
248
|
+
if (index.type.kind !== 'int') {
|
|
249
|
+
throw aotError(`AOT: an index into "${listName}" must be a whole number`, 'an index is an int: Math.floor(x) or a whole-number state.');
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
return index;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* The index `items.filter((_, i) => i !== n)` removes: n.
|
|
256
|
+
*
|
|
257
|
+
* @param callback The filter's function.
|
|
258
|
+
*
|
|
259
|
+
* @returns n, or null when the filter is no such test.
|
|
260
|
+
*/
|
|
261
|
+
function filteredIndex(callback) {
|
|
262
|
+
const { itemName, indexName, body } = callback;
|
|
263
|
+
const isIndex = (node) => node.type === 'Identifier' && node.name === indexName;
|
|
264
|
+
const other = indexName &&
|
|
265
|
+
body.type === 'BinaryExpression' &&
|
|
266
|
+
(body.operator === '!==' || body.operator === '!=')
|
|
267
|
+
? isIndex(body.left)
|
|
268
|
+
? body.right
|
|
269
|
+
: isIndex(body.right)
|
|
270
|
+
? body.left
|
|
271
|
+
: null
|
|
272
|
+
: null;
|
|
273
|
+
const names = new Set([itemName, indexName].filter(Boolean));
|
|
274
|
+
return other && !mentions(other, names) ? other : null;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Whether an expression is the object at a path in an item: `base.pos.x` for ['pos', 'x'].
|
|
278
|
+
*
|
|
279
|
+
* @param node The expression.
|
|
280
|
+
* @param path The path.
|
|
281
|
+
* @param isItem Whether an expression is the item.
|
|
282
|
+
*
|
|
283
|
+
* @returns Whether it is.
|
|
284
|
+
*/
|
|
285
|
+
function isPathOf(node, path, isItem) {
|
|
286
|
+
let current = node;
|
|
287
|
+
for (let index = path.length - 1; index >= 0; index--) {
|
|
288
|
+
if (current.type !== 'MemberExpression' ||
|
|
289
|
+
current.computed ||
|
|
290
|
+
current.property.name !== path[index]) {
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
293
|
+
current = current.object;
|
|
294
|
+
}
|
|
295
|
+
return isItem(current);
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* The statements an update runs on a row: `if`s for a ternary's tests, and a `setRow` for each item it builds.
|
|
299
|
+
* A branch that gives back the item itself changes nothing.
|
|
300
|
+
*
|
|
301
|
+
* @param node What the update gives the row.
|
|
302
|
+
* @param update The update.
|
|
303
|
+
*
|
|
304
|
+
* @returns The statements.
|
|
305
|
+
*/
|
|
306
|
+
function updateBody(node, update) {
|
|
307
|
+
if (update.isRow(node, [])) {
|
|
308
|
+
return [];
|
|
309
|
+
}
|
|
310
|
+
if (node.type === 'ConditionalExpression') {
|
|
311
|
+
const consequent = updateBody(node.consequent, update);
|
|
312
|
+
const alternate = updateBody(node.alternate, update);
|
|
313
|
+
if (!consequent.length && !alternate.length) {
|
|
314
|
+
return [];
|
|
315
|
+
}
|
|
316
|
+
return [
|
|
317
|
+
{
|
|
318
|
+
kind: 'if',
|
|
319
|
+
test: lowerExprWide(node.test, update.environment),
|
|
320
|
+
consequent,
|
|
321
|
+
alternate: alternate.length ? alternate : null,
|
|
322
|
+
},
|
|
323
|
+
];
|
|
324
|
+
}
|
|
325
|
+
return [setRow(node, update)];
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Sets a row to an item: a spread of the row's own item keeps the fields it doesn't set; without one, every field
|
|
329
|
+
* it leaves out is undefined from then on.
|
|
330
|
+
*
|
|
331
|
+
* @param node The item.
|
|
332
|
+
* @param update The update.
|
|
333
|
+
*
|
|
334
|
+
* @returns The statement.
|
|
335
|
+
*/
|
|
336
|
+
function setRow(node, update) {
|
|
337
|
+
const { list, listName, environment } = update;
|
|
338
|
+
const { struct } = list;
|
|
339
|
+
const given = new Map();
|
|
340
|
+
const cleared = new Set();
|
|
341
|
+
// A key written twice takes its last value, as in JS.
|
|
342
|
+
const give = (field, value) => {
|
|
343
|
+
cleared.delete(field);
|
|
344
|
+
given.set(field, value);
|
|
345
|
+
};
|
|
346
|
+
const clear = (field) => {
|
|
347
|
+
given.delete(field);
|
|
348
|
+
cleared.add(field);
|
|
349
|
+
};
|
|
350
|
+
if (struct.plain) {
|
|
351
|
+
if (node.type === 'ObjectExpression') {
|
|
352
|
+
throw aotError(`AOT: list state "${listName}" holds plain values, not objects`, 'give a value of the same kind as the initial ones.');
|
|
353
|
+
}
|
|
354
|
+
if (leavesOut(node)) {
|
|
355
|
+
clear(struct.fields[0]);
|
|
356
|
+
}
|
|
357
|
+
else {
|
|
358
|
+
give(struct.fields[0], node);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
if (node.type !== 'ObjectExpression') {
|
|
363
|
+
throw aotError(`AOT: an item of "${listName}" must be replaced with an object literal`, 'spread the item and set the fields that change: {...item, done: true}.');
|
|
364
|
+
}
|
|
365
|
+
const visit = (object, path) => {
|
|
366
|
+
const seen = new Set();
|
|
367
|
+
let keeps = false;
|
|
368
|
+
object.properties.forEach((property, position) => {
|
|
369
|
+
if (property.type === 'SpreadElement') {
|
|
370
|
+
if (position !== 0 || !update.isRow(property.argument, path)) {
|
|
371
|
+
throw aotError('AOT: an updated item can spread only the item it replaces, first', path.length
|
|
372
|
+
? `spread the same object: {...item, ${path[0]}: {...item.${path.join('.')}, x: 1}}.`
|
|
373
|
+
: 'spread the item, then set the fields that change: {...item, done: true}.');
|
|
374
|
+
}
|
|
375
|
+
keeps = true;
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (property.type !== 'ObjectProperty' || property.computed) {
|
|
379
|
+
throw aotError('AOT: an updated item must be an object literal of plain fields', 'write each field out: {...item, title: t, n: 1}. Methods and computed keys are not lowered.');
|
|
380
|
+
}
|
|
381
|
+
const fieldPath = [...path, propertyKey(property)];
|
|
382
|
+
const fields = fieldsUnder(struct, fieldPath);
|
|
383
|
+
if (!fields.length) {
|
|
384
|
+
throw noField(listName, fieldPath.join('.'));
|
|
385
|
+
}
|
|
386
|
+
// A key written again replaces all an earlier value set under it.
|
|
387
|
+
fields.forEach(field => {
|
|
388
|
+
seen.add(field);
|
|
389
|
+
given.delete(field);
|
|
390
|
+
cleared.delete(field);
|
|
391
|
+
});
|
|
392
|
+
const { value } = property;
|
|
393
|
+
if (value.type === 'ObjectExpression') {
|
|
394
|
+
visit(value, fieldPath);
|
|
395
|
+
}
|
|
396
|
+
else if (leavesOut(value)) {
|
|
397
|
+
fields.forEach(field => clear(field));
|
|
398
|
+
}
|
|
399
|
+
else if (fields.length === 1 &&
|
|
400
|
+
fields[0].key === fieldPath.join('.')) {
|
|
401
|
+
give(fields[0], value);
|
|
402
|
+
}
|
|
403
|
+
else if (!update.isRow(value, fieldPath)) {
|
|
404
|
+
throw aotError(`AOT: field "${fieldPath.join('.')}" of list state "${listName}" holds an object`, `set its fields with an object literal: {...item, ${fieldPath[0]}: {...item.${fieldPath.join('.')}, x: 1}}.`);
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
if (!keeps) {
|
|
408
|
+
for (const field of fieldsUnder(struct, path)) {
|
|
409
|
+
if (!seen.has(field)) {
|
|
410
|
+
clear(field);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
visit(node, []);
|
|
416
|
+
}
|
|
417
|
+
const values = [];
|
|
418
|
+
for (const field of struct.fields) {
|
|
419
|
+
const valueNode = given.get(field);
|
|
420
|
+
if (cleared.has(field)) {
|
|
421
|
+
field.optional = true;
|
|
422
|
+
}
|
|
423
|
+
else if (valueNode) {
|
|
424
|
+
values.push(itemValue(field, valueNode, list, environment));
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return { kind: 'setRow', list, values, cleared: [...cleared] };
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* The local an update's row index is read through. Each has a name of its own, which no JS name can clash with.
|
|
431
|
+
*
|
|
432
|
+
* @returns The local.
|
|
433
|
+
*/
|
|
434
|
+
function updateRowLocal() {
|
|
435
|
+
return { slotKind: 'int', name: `#row${updateRows++}` };
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Whether an expression reads a row of a list by index: `items[k]`, under the list's name or the name a setter's
|
|
439
|
+
* updater gives it.
|
|
440
|
+
*
|
|
441
|
+
* @param node The expression.
|
|
442
|
+
* @param listState The list.
|
|
443
|
+
* @param listName What the setter's argument calls it.
|
|
444
|
+
* @param environment The expression environment.
|
|
445
|
+
*
|
|
446
|
+
* @returns Whether it does.
|
|
447
|
+
*/
|
|
448
|
+
function readsRowsOf(node, listState, listName, environment) {
|
|
449
|
+
if (!node || typeof node !== 'object')
|
|
450
|
+
return false;
|
|
451
|
+
if (Array.isArray(node)) {
|
|
452
|
+
return node.some(child => readsRowsOf(child, listState, listName, environment));
|
|
453
|
+
}
|
|
454
|
+
const astNode = node;
|
|
455
|
+
if ((astNode.type === 'MemberExpression' ||
|
|
456
|
+
astNode.type === 'OptionalMemberExpression') &&
|
|
457
|
+
astNode.computed &&
|
|
458
|
+
astNode.object.type === 'Identifier' &&
|
|
459
|
+
(astNode.object.name === listName ||
|
|
460
|
+
environment.state.get(astNode.object.name) === listState)) {
|
|
461
|
+
return true;
|
|
462
|
+
}
|
|
463
|
+
return Object.entries(astNode).some(([key, child]) => !POSITION_KEYS.has(key) &&
|
|
464
|
+
readsRowsOf(child, listState, listName, environment));
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Lowers `items.map(…)` as a list's next value: each row is visited, and set to what the function gives it.
|
|
468
|
+
*
|
|
469
|
+
* @param listState The list.
|
|
470
|
+
* @param listName What the setter's argument calls it.
|
|
471
|
+
* @param argument The map's function.
|
|
472
|
+
* @param environment The expression environment.
|
|
473
|
+
*
|
|
474
|
+
* @returns The statements.
|
|
475
|
+
*/
|
|
476
|
+
function lowerItemsMap(listState, listName, argument, environment) {
|
|
477
|
+
const { itemName, indexName, body } = itemCallback(argument, `${listName}.map`);
|
|
478
|
+
// The rows are set in place, one after another, so a read of another row could see its new value.
|
|
479
|
+
if (readsRowsOf(body, listState, listName, environment)) {
|
|
480
|
+
throw aotError(`AOT: ${listName}.map's function can't read other items of ${listName}`, 'its items are set in place, so a read of another one could see its new value. Read it into a const ' +
|
|
481
|
+
`before the setter: const first = ${listName}[0].n.`);
|
|
482
|
+
}
|
|
483
|
+
const row = updateRowLocal();
|
|
484
|
+
const locals = new Map(environment.locals);
|
|
485
|
+
if (itemName) {
|
|
486
|
+
locals.set(itemName, {
|
|
487
|
+
name: itemName,
|
|
488
|
+
struct: listState.struct,
|
|
489
|
+
list: listState,
|
|
490
|
+
index: { kind: 'local', local: row, type: INT },
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
if (indexName) {
|
|
494
|
+
locals.set(indexName, row);
|
|
495
|
+
}
|
|
496
|
+
const statements = updateBody(body, {
|
|
497
|
+
list: listState,
|
|
498
|
+
listName,
|
|
499
|
+
environment: { ...environment, locals },
|
|
500
|
+
isRow: (node, path) => isPathOf(node, path, item => item.type === 'Identifier' && item.name === itemName),
|
|
501
|
+
});
|
|
502
|
+
return statements.length
|
|
503
|
+
? [
|
|
504
|
+
{
|
|
505
|
+
kind: 'updateItems',
|
|
506
|
+
list: listState,
|
|
507
|
+
row,
|
|
508
|
+
index: null,
|
|
509
|
+
body: statements,
|
|
510
|
+
},
|
|
511
|
+
]
|
|
512
|
+
: [];
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Lowers `items.with(n, item)` as a list's next value: row n is set to the item. A negative n counts back from the
|
|
516
|
+
* end, and a row past either end stops the app, as JS throws there.
|
|
517
|
+
*
|
|
518
|
+
* @param listState The list.
|
|
519
|
+
* @param listName What the setter's argument calls it.
|
|
520
|
+
* @param argumentNodes The call's arguments.
|
|
521
|
+
* @param environment The expression environment.
|
|
522
|
+
*
|
|
523
|
+
* @returns The statements.
|
|
524
|
+
*/
|
|
525
|
+
function lowerItemsWith(listState, listName, argumentNodes, environment) {
|
|
526
|
+
const [indexNode, itemNode] = argumentNodes;
|
|
527
|
+
if (argumentNodes.length !== 2 ||
|
|
528
|
+
indexNode.type === 'SpreadElement' ||
|
|
529
|
+
itemNode.type === 'SpreadElement') {
|
|
530
|
+
throw aotError(`AOT: ${listName}.with takes an index and an item`, `e.g. ${listName}.with(n, {...${listName}[n], done: true}).`);
|
|
531
|
+
}
|
|
532
|
+
const index = rowIndexOf(indexNode, listName, environment);
|
|
533
|
+
const constantIndex = staticInt(indexNode, environment);
|
|
534
|
+
// The replaced item: items[n], or a row's own item when n is that row's index. For a negative n, with() counts
|
|
535
|
+
// back but items[n] is undefined, so what the update keeps from it isn't the row's.
|
|
536
|
+
let keepsIndexed = false;
|
|
537
|
+
const isItem = (node) => {
|
|
538
|
+
if (node.type === 'MemberExpression' &&
|
|
539
|
+
node.computed &&
|
|
540
|
+
node.object.type === 'Identifier' &&
|
|
541
|
+
node.object.name === listName) {
|
|
542
|
+
const same = sameNode(node.property, indexNode);
|
|
543
|
+
keepsIndexed ||= same;
|
|
544
|
+
return same;
|
|
545
|
+
}
|
|
546
|
+
const local = node.type === 'Identifier'
|
|
547
|
+
? environment.locals.get(node.name)
|
|
548
|
+
: undefined;
|
|
549
|
+
return (local?.list === listState &&
|
|
550
|
+
local.row !== undefined &&
|
|
551
|
+
local.row === constantIndex);
|
|
552
|
+
};
|
|
553
|
+
const row = updateRowLocal();
|
|
554
|
+
const statements = updateBody(itemNode, {
|
|
555
|
+
list: listState,
|
|
556
|
+
listName,
|
|
557
|
+
environment,
|
|
558
|
+
isRow: (node, path) => isPathOf(node, path, isItem),
|
|
559
|
+
});
|
|
560
|
+
if (keepsIndexed && constantIndex !== null && constantIndex < 0) {
|
|
561
|
+
throw aotError(`AOT: ${listName}.with(${constantIndex}, …) keeps fields of ${listName}[${constantIndex}], which is undefined`, `with() counts a negative index back from the end, but ${listName}[${constantIndex}] doesn't. ` +
|
|
562
|
+
`Use the index it counts back to, e.g. ${listName}.length - 1.`);
|
|
563
|
+
}
|
|
564
|
+
// Even an update that changes nothing reads the row, so an index past the end faults.
|
|
565
|
+
return [
|
|
566
|
+
{
|
|
567
|
+
kind: 'updateItems',
|
|
568
|
+
list: listState,
|
|
569
|
+
row,
|
|
570
|
+
index,
|
|
571
|
+
body: statements,
|
|
572
|
+
negativeKeeps: keepsIndexed && constantIndex === null,
|
|
573
|
+
},
|
|
574
|
+
];
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* The arguments of a call to a method of the list: `items.slice(…)`, or null when it is no such call.
|
|
578
|
+
*
|
|
579
|
+
* @param node The expression.
|
|
580
|
+
* @param listName The list's name.
|
|
581
|
+
* @param method The method.
|
|
582
|
+
*
|
|
583
|
+
* @returns The arguments.
|
|
584
|
+
*/
|
|
585
|
+
function listCall(node, listName, method) {
|
|
586
|
+
return node?.type === 'CallExpression' &&
|
|
587
|
+
node.callee.type === 'MemberExpression' &&
|
|
588
|
+
!node.callee.computed &&
|
|
589
|
+
node.callee.object.type === 'Identifier' &&
|
|
590
|
+
node.callee.object.name === listName &&
|
|
591
|
+
node.callee.property.name === method
|
|
592
|
+
? node.arguments
|
|
593
|
+
: null;
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* The index `[...items.slice(0, n), ...items.slice(n + 1)]` removes, or null when the list literal is not that.
|
|
597
|
+
*
|
|
598
|
+
* @param nextList The list literal.
|
|
599
|
+
* @param listName The list's name.
|
|
600
|
+
* @param environment The expression environment.
|
|
601
|
+
*
|
|
602
|
+
* @returns n.
|
|
603
|
+
*/
|
|
604
|
+
function slicedOutIndex(nextList, listName, environment) {
|
|
605
|
+
const [first, second] = nextList.elements;
|
|
606
|
+
if (nextList.elements.length !== 2 ||
|
|
607
|
+
first?.type !== 'SpreadElement' ||
|
|
608
|
+
second?.type !== 'SpreadElement') {
|
|
609
|
+
return null;
|
|
610
|
+
}
|
|
611
|
+
const before = listCall(first.argument, listName, 'slice');
|
|
612
|
+
const after = listCall(second.argument, listName, 'slice');
|
|
613
|
+
if (before?.length !== 2 || after?.length !== 1) {
|
|
614
|
+
return null;
|
|
615
|
+
}
|
|
616
|
+
const [start, end] = before;
|
|
617
|
+
const [next] = after;
|
|
618
|
+
const constantEnd = staticInt(end, environment);
|
|
619
|
+
const constantNext = staticInt(next, environment);
|
|
620
|
+
const followsOn = (next.type === 'BinaryExpression' &&
|
|
621
|
+
next.operator === '+' &&
|
|
622
|
+
sameNode(next.left, end) &&
|
|
623
|
+
staticInt(next.right, environment) === 1) ||
|
|
624
|
+
(constantEnd !== null && constantNext === constantEnd + 1);
|
|
625
|
+
if (staticInt(start, environment) !== 0 ||
|
|
626
|
+
!followsOn ||
|
|
627
|
+
(constantEnd !== null && constantEnd < 0)) {
|
|
628
|
+
throw aotError(`AOT: only [...${listName}.slice(0, n), ...${listName}.slice(n + 1)] is supported to splice a list`, 'it removes item n, which must not be negative.');
|
|
629
|
+
}
|
|
630
|
+
return end;
|
|
631
|
+
}
|
|
43
632
|
/**
|
|
44
633
|
* Lowers a list-state setter call (`setItems(...)`) to bounded list operations.
|
|
45
634
|
*
|
|
46
635
|
* @param listState The list state.
|
|
47
636
|
* @param nextList The setter's argument: the list's next value.
|
|
48
637
|
* @param environment The expression environment.
|
|
638
|
+
* @param listName What the argument calls the list: its name, or an updater's parameter.
|
|
49
639
|
*
|
|
50
640
|
* @returns The statements.
|
|
51
641
|
*/
|
|
52
|
-
function lowerListOp(listState, nextList, environment) {
|
|
642
|
+
function lowerListOp(listState, nextList, environment, listName = listState.name) {
|
|
53
643
|
const { capacity: capacity, struct } = listState;
|
|
54
|
-
//
|
|
644
|
+
// setWords(text.split(',')) — the pieces replace the rows.
|
|
645
|
+
const split = lowerSplitInto(listState, nextList, environment, listName);
|
|
646
|
+
if (split)
|
|
647
|
+
return split;
|
|
648
|
+
// setItems([...items, a, b]) — append; setItems([]) — clear; [...items.slice(0, n), ...items.slice(n + 1)] — remove.
|
|
55
649
|
if (nextList.type === 'ArrayExpression') {
|
|
56
650
|
if (nextList.elements.length === 0) {
|
|
57
651
|
return [{ kind: 'clearList', list: listState }];
|
|
58
652
|
}
|
|
653
|
+
const slicedOut = slicedOutIndex(nextList, listName, environment);
|
|
654
|
+
if (slicedOut) {
|
|
655
|
+
return [
|
|
656
|
+
{
|
|
657
|
+
kind: 'removeItem',
|
|
658
|
+
list: listState,
|
|
659
|
+
index: rowIndexOf(slicedOut, listName, environment),
|
|
660
|
+
negative: 'sliced',
|
|
661
|
+
},
|
|
662
|
+
];
|
|
663
|
+
}
|
|
59
664
|
const [firstElement, ...appendedItems] = nextList.elements;
|
|
60
665
|
if (firstElement?.type !== 'SpreadElement' ||
|
|
61
|
-
firstElement.argument.name !==
|
|
62
|
-
throw new Error(`AOT: a list literal must spread the current list first: [...${
|
|
666
|
+
firstElement.argument.name !== listName) {
|
|
667
|
+
throw new Error(`AOT: a list literal must spread the current list first: [...${listName}, item]`);
|
|
63
668
|
}
|
|
64
|
-
// Each appended
|
|
65
|
-
//
|
|
669
|
+
// Each appended item fills the next free row; a full list drops it. A field it leaves out is 0 or "", and
|
|
670
|
+
// optional from then on, so a read of it sees undefined.
|
|
66
671
|
const statements = [];
|
|
67
672
|
for (const item of appendedItems) {
|
|
68
673
|
if (!item) {
|
|
69
674
|
throw aotError('AOT: a list literal has an empty slot');
|
|
70
675
|
}
|
|
71
|
-
if (item.type
|
|
72
|
-
throw
|
|
676
|
+
if (item.type === 'SpreadElement') {
|
|
677
|
+
throw aotError(`AOT: a list literal can spread only the current list, first: [...${listName}, item]`);
|
|
73
678
|
}
|
|
74
|
-
const
|
|
75
|
-
prop.key.name ??
|
|
76
|
-
prop.key.value,
|
|
77
|
-
prop.value,
|
|
78
|
-
]));
|
|
679
|
+
const given = appendedFields(item, struct, listName);
|
|
79
680
|
const values = [];
|
|
80
681
|
for (const field of struct.fields) {
|
|
81
|
-
const valueNode =
|
|
82
|
-
if (
|
|
83
|
-
values.push(field
|
|
84
|
-
? { field, text: { parts: [] } }
|
|
85
|
-
: {
|
|
86
|
-
field,
|
|
87
|
-
value: {
|
|
88
|
-
kind: 'number',
|
|
89
|
-
value: 0,
|
|
90
|
-
type: field.kind === 'float' ? FLOAT : INT,
|
|
91
|
-
},
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
else if (field.kind === 'string') {
|
|
95
|
-
const text = lowerText(valueNode, environment);
|
|
96
|
-
checkConstantFits(text, `field "${field.key}" of list state "${listState.name}"`, environment);
|
|
97
|
-
values.push({ field, text });
|
|
682
|
+
const valueNode = given.get(field.key);
|
|
683
|
+
if (valueNode) {
|
|
684
|
+
values.push(itemValue(field, valueNode, listState, environment));
|
|
98
685
|
}
|
|
99
686
|
else {
|
|
100
|
-
|
|
101
|
-
field,
|
|
102
|
-
value: storeValue(lowerExpr(valueNode, environment), field.kind),
|
|
103
|
-
});
|
|
687
|
+
field.optional = true;
|
|
104
688
|
}
|
|
105
689
|
}
|
|
106
690
|
statements.push({ kind: 'appendItem', list: listState, values });
|
|
107
691
|
}
|
|
108
692
|
return statements;
|
|
109
693
|
}
|
|
694
|
+
// filter((_, i) => i !== n) removes item n; other filters and sorts change the rows in place.
|
|
695
|
+
const chain = listChainOf(nextList);
|
|
696
|
+
if (chain?.base.type === 'Identifier' && chain.base.name === listName) {
|
|
697
|
+
const [step] = chain.steps;
|
|
698
|
+
const index = chain.steps.length === 1 && step.kind === 'filter'
|
|
699
|
+
? filteredIndex(itemCallback(step.callback, step.what))
|
|
700
|
+
: null;
|
|
701
|
+
if (index) {
|
|
702
|
+
return [
|
|
703
|
+
{
|
|
704
|
+
kind: 'removeItem',
|
|
705
|
+
list: listState,
|
|
706
|
+
index: rowIndexOf(index, listName, environment),
|
|
707
|
+
negative: 'none',
|
|
708
|
+
},
|
|
709
|
+
];
|
|
710
|
+
}
|
|
711
|
+
return lowerListOrder(listState, listName, chain, environment);
|
|
712
|
+
}
|
|
713
|
+
// toSpliced(n, 1) removes item n, counting a negative n back from the end.
|
|
714
|
+
const splicedArguments = listCall(nextList, listName, 'toSpliced');
|
|
715
|
+
if (splicedArguments) {
|
|
716
|
+
const [start, count] = splicedArguments;
|
|
717
|
+
if (splicedArguments.length !== 2 ||
|
|
718
|
+
start.type === 'SpreadElement' ||
|
|
719
|
+
staticInt(count, environment) !== 1) {
|
|
720
|
+
throw aotError(`AOT: only ${listName}.toSpliced(n, 1) is supported on a list`, 'it removes item n.');
|
|
721
|
+
}
|
|
722
|
+
return [
|
|
723
|
+
{
|
|
724
|
+
kind: 'removeItem',
|
|
725
|
+
list: listState,
|
|
726
|
+
index: rowIndexOf(start, listName, environment),
|
|
727
|
+
negative: 'spliced',
|
|
728
|
+
},
|
|
729
|
+
];
|
|
730
|
+
}
|
|
731
|
+
// map(item => …) and with(n, item) set items in place.
|
|
732
|
+
const mapArguments = listCall(nextList, listName, 'map');
|
|
733
|
+
if (mapArguments) {
|
|
734
|
+
return lowerItemsMap(listState, listName, mapArguments[0], environment);
|
|
735
|
+
}
|
|
736
|
+
const withArguments = listCall(nextList, listName, 'with');
|
|
737
|
+
if (withArguments) {
|
|
738
|
+
return lowerItemsWith(listState, listName, withArguments, environment);
|
|
739
|
+
}
|
|
110
740
|
// slice(0, end) keeps the first items by JS rules: a negative end counts back, a large or missing one keeps all.
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
nextList.callee.property.name === 'slice') {
|
|
115
|
-
const [start, end] = nextList.arguments;
|
|
741
|
+
const sliceArguments = listCall(nextList, listName, 'slice');
|
|
742
|
+
if (sliceArguments) {
|
|
743
|
+
const [start, end] = sliceArguments;
|
|
116
744
|
if (start && staticInt(start, environment) !== 0) {
|
|
117
|
-
throw aotError(`AOT: only ${
|
|
118
|
-
`e.g. ${
|
|
745
|
+
throw aotError(`AOT: only ${listName}.slice(0, end) is supported on a list`, `a list is a fixed pool and a count, so a slice can only drop items from the end — ` +
|
|
746
|
+
`e.g. ${listName}.slice(0, -1) drops the last one.`);
|
|
119
747
|
}
|
|
120
748
|
if (!end)
|
|
121
749
|
return [];
|
|
@@ -146,43 +774,67 @@ function lowerListOp(listState, nextList, environment) {
|
|
|
146
774
|
},
|
|
147
775
|
];
|
|
148
776
|
}
|
|
149
|
-
throw
|
|
150
|
-
|
|
777
|
+
throw aotError(`AOT: unsupported list operation on "${listName}"`, `use [...${listName}, item], ${listName}.slice(0, n), [], ${listName}.filter(item => …), ` +
|
|
778
|
+
`${listName}.toSorted((a, b) => …), ${listName}.toSpliced(n, 1), ${listName}.map(item => …) or ` +
|
|
779
|
+
`${listName}.with(n, item).`);
|
|
151
780
|
}
|
|
152
781
|
/**
|
|
153
|
-
*
|
|
782
|
+
* Lowers filters and sorts as a list's next value: each changes the rows in place, a filter dropping the rows it
|
|
783
|
+
* doesn't keep and a sort moving them, equal ones kept in order.
|
|
154
784
|
*
|
|
155
|
-
* @param
|
|
785
|
+
* @param listState The list.
|
|
786
|
+
* @param listName What the setter's argument calls it.
|
|
787
|
+
* @param chain The filters and sorts.
|
|
788
|
+
* @param environment The expression environment.
|
|
156
789
|
*
|
|
157
|
-
* @returns
|
|
790
|
+
* @returns The statements.
|
|
158
791
|
*/
|
|
159
|
-
function
|
|
160
|
-
|
|
792
|
+
function lowerListOrder(listState, listName, chain, environment) {
|
|
793
|
+
// The rows move as the steps run, so a read of another row could see a different one.
|
|
794
|
+
for (const step of chain.steps) {
|
|
795
|
+
if (readsRowsOf(step.callback, listState, listName, environment)) {
|
|
796
|
+
throw aotError(`AOT: ${step.what}'s function can't read other items of ${listName}`, 'its items move as it runs, so a read of another one could see a different item. Read it into a ' +
|
|
797
|
+
`const before the setter: const first = ${listName}[0].n.`);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
return orderStatements(listState, chain.steps.map(step => ({ ...step, environment })), {
|
|
801
|
+
itemAt: position => ({
|
|
802
|
+
name: `${listName}[]`,
|
|
803
|
+
struct: listState.struct,
|
|
804
|
+
list: listState,
|
|
805
|
+
index: { kind: 'local', local: position, type: INT },
|
|
806
|
+
}),
|
|
807
|
+
listName,
|
|
808
|
+
source: listState,
|
|
809
|
+
});
|
|
161
810
|
}
|
|
162
811
|
/**
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
* @param lowered The value: its source, and its type.
|
|
170
|
-
* @param slotType The slot's kind.
|
|
171
|
-
* @param isBoolean The slot holds a boolean.
|
|
172
|
-
* @param widened What the slot holds, if it was widened to 64 bits.
|
|
173
|
-
* @param slotName The slot's name, for environment.stores.
|
|
174
|
-
* @param slotDescription The slot, for the message.
|
|
812
|
+
* Records a value written to a whole-number state, ref or `let` slot, whose kind came from its initial value:
|
|
813
|
+
* from every such value the typing pass infers the slots that hold 64 bits.
|
|
814
|
+
*
|
|
815
|
+
* @param value The value's source.
|
|
816
|
+
* @param slotName The slot's name.
|
|
817
|
+
* @param target The state or ref, or the `let` local.
|
|
175
818
|
* @param environment The expression environment.
|
|
176
819
|
*/
|
|
177
|
-
function
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
820
|
+
function recordStore(value, slotName, target, environment) {
|
|
821
|
+
environment.stores.push({
|
|
822
|
+
slot: slotName,
|
|
823
|
+
value,
|
|
824
|
+
math64: environment.math64,
|
|
825
|
+
...('kind' in target ? { target } : { local: target }),
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Checks a value written to a numeric slot, once both are typed. A timestamp cannot go into a float or boolean
|
|
830
|
+
* slot (a 64-bit constant can go into a float one), and a 64-bit slot takes no floats.
|
|
831
|
+
*
|
|
832
|
+
* @param value The typed value.
|
|
833
|
+
* @param slot The slot.
|
|
834
|
+
* @param slotDescription The slot, for the message.
|
|
835
|
+
*/
|
|
836
|
+
function checkStored(value, slot, slotDescription) {
|
|
837
|
+
const { slotType, isBoolean } = slot;
|
|
186
838
|
if (value.type.kind === 'int64' && slotType !== 'i64') {
|
|
187
839
|
if (slotType === 'int' && !isBoolean)
|
|
188
840
|
return;
|
|
@@ -195,25 +847,46 @@ function storeCheck(lowered, slotType, isBoolean, widened, slotName, slotDescrip
|
|
|
195
847
|
}
|
|
196
848
|
}
|
|
197
849
|
/**
|
|
198
|
-
*
|
|
199
|
-
*
|
|
850
|
+
* The environment a value stored in a slot is lowered in: a 64-bit slot takes int `+ - *` worked out in 64
|
|
851
|
+
* bits.
|
|
200
852
|
*
|
|
201
|
-
* @param
|
|
853
|
+
* @param environment The expression environment.
|
|
854
|
+
* @param is64Bit Whether the slot holds 64 bits, asked once its width is known.
|
|
855
|
+
*
|
|
856
|
+
* @returns The value's environment.
|
|
857
|
+
*/
|
|
858
|
+
function storeEnvironment(environment, is64Bit) {
|
|
859
|
+
const outer = environment.math64;
|
|
860
|
+
return { ...environment, math64: () => is64Bit() || Boolean(outer?.()) };
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* A typed value for an int destination. A float goes through a checked conversion: a plain one is undefined
|
|
864
|
+
* for NaN or a value past the int range.
|
|
865
|
+
*
|
|
866
|
+
* @param value The typed value.
|
|
202
867
|
*
|
|
203
868
|
* @returns The value as an int.
|
|
204
869
|
*/
|
|
205
|
-
const
|
|
870
|
+
const typedAsInt = (value) => value.type.kind === 'float'
|
|
206
871
|
? { kind: 'toInt', operand: value, type: INT }
|
|
207
872
|
: value;
|
|
208
873
|
/**
|
|
209
|
-
* `value` for
|
|
874
|
+
* `value` for an int destination (see typedAsInt).
|
|
210
875
|
*
|
|
211
876
|
* @param value The lowered value.
|
|
212
|
-
*
|
|
877
|
+
*
|
|
878
|
+
* @returns The value as an int.
|
|
879
|
+
*/
|
|
880
|
+
const asInt = (value) => typedLater('number', () => typedAsInt(value), [value]);
|
|
881
|
+
/**
|
|
882
|
+
* `value` for a slot: an int slot takes a float the way asInt does.
|
|
883
|
+
*
|
|
884
|
+
* @param value The lowered value.
|
|
885
|
+
* @param slotType The slot's kind, asked once it is known.
|
|
213
886
|
*
|
|
214
887
|
* @returns The value the slot stores.
|
|
215
888
|
*/
|
|
216
|
-
const storeValue = (value, slotType) => slotType === 'int' ?
|
|
889
|
+
const storeValue = (value, slotType) => typedLater(shapeOf(value), () => (slotType() === 'int' ? typedAsInt(value) : value), [value]);
|
|
217
890
|
/**
|
|
218
891
|
* A read of a ref's current value.
|
|
219
892
|
*
|
|
@@ -227,21 +900,20 @@ const refRead = (ref) => ({
|
|
|
227
900
|
type: refType(ref),
|
|
228
901
|
});
|
|
229
902
|
/**
|
|
230
|
-
* Refuses a constant string too long for the buffer
|
|
903
|
+
* Refuses a constant string too long for the buffer a write is built in, which would cut it short. A string
|
|
231
904
|
* built at run time is checked when it is written instead.
|
|
232
905
|
*
|
|
233
906
|
* @param text The text written.
|
|
234
907
|
* @param what What it is written into, for the error.
|
|
235
|
-
* @param environment The expression environment.
|
|
236
908
|
*/
|
|
237
|
-
function checkConstantFits(text, what
|
|
909
|
+
function checkConstantFits(text, what) {
|
|
238
910
|
const constant = constantText(text);
|
|
239
911
|
if (constant === null) {
|
|
240
912
|
return;
|
|
241
913
|
}
|
|
242
914
|
const bytes = Buffer.byteLength(constant, 'utf8');
|
|
243
|
-
if (bytes
|
|
244
|
-
throw aotError(`AOT: ${what} is set to a ${bytes}-byte string, but a
|
|
915
|
+
if (bytes > ENGINE_STRING_MAX.ER_TEXT_MAX) {
|
|
916
|
+
throw aotError(`AOT: ${what} is set to a ${bytes}-byte string, but a write holds ${ENGINE_STRING_MAX.ER_TEXT_MAX} bytes (ER_TEXT_MAX)`, 'shorten the string: a write is built in a buffer that ER_TEXT_MAX in er_scene.h sizes.');
|
|
245
917
|
}
|
|
246
918
|
}
|
|
247
919
|
/**
|
|
@@ -256,26 +928,126 @@ function checkConstantFits(text, what, environment) {
|
|
|
256
928
|
*/
|
|
257
929
|
function lowerScalarSet(scalarState, valueNode, environment) {
|
|
258
930
|
if (scalarState.slotKind !== 'string') {
|
|
259
|
-
|
|
260
|
-
const lowered = lowerSource(valueNode, scalarState.slotKind === 'i64'
|
|
261
|
-
? { ...environment, math64: true }
|
|
262
|
-
: environment);
|
|
931
|
+
const lowered = lowerSource(valueNode, storeEnvironment(environment, () => is64BitSlot(scalarState)));
|
|
263
932
|
const value = lowered.expression;
|
|
264
|
-
|
|
933
|
+
if ((scalarState.slotKind === 'int' && !scalarState.isBoolean) ||
|
|
934
|
+
scalarState.widened === 'number') {
|
|
935
|
+
recordStore(lowered.source, scalarState.slotName, scalarState, environment);
|
|
936
|
+
}
|
|
937
|
+
whenTyped(() => checkStored(value, { slotType: scalarState.slotKind, isBoolean: scalarState.isBoolean }, `state "${scalarState.name}"`));
|
|
265
938
|
return {
|
|
266
939
|
kind: 'setState',
|
|
267
940
|
state: scalarState,
|
|
268
|
-
value: storeValue(value, scalarState.slotKind),
|
|
941
|
+
value: storeValue(value, () => scalarState.slotKind),
|
|
269
942
|
};
|
|
270
943
|
}
|
|
271
944
|
const text = lowerText(valueNode, environment);
|
|
272
|
-
checkConstantFits(text, `state "${scalarState.name}"
|
|
945
|
+
checkConstantFits(text, `state "${scalarState.name}"`);
|
|
273
946
|
return {
|
|
274
947
|
kind: 'setStateText',
|
|
275
948
|
state: scalarState,
|
|
276
949
|
text,
|
|
277
950
|
};
|
|
278
951
|
}
|
|
952
|
+
/** How an object setter's writes are lowered. */
|
|
953
|
+
const RECORD_LOWERING = {
|
|
954
|
+
field: lowerScalarSet,
|
|
955
|
+
test: (node, environment) => lowerExprWide(node, environment),
|
|
956
|
+
};
|
|
957
|
+
/**
|
|
958
|
+
* Works out a write to a value ref, `ref.current = …` or a compound assignment, once the ref and the value are
|
|
959
|
+
* typed. It does not trigger a re-render.
|
|
960
|
+
*
|
|
961
|
+
* @param expression The assignment.
|
|
962
|
+
* @param ref The ref.
|
|
963
|
+
* @param loweredValue The right side: its source, and the typed value.
|
|
964
|
+
* @param environment The expression environment.
|
|
965
|
+
*
|
|
966
|
+
* @returns The write's operator and value.
|
|
967
|
+
*/
|
|
968
|
+
function typedRefWrite(expression, ref, loweredValue, environment) {
|
|
969
|
+
const valueExpression = loweredValue.expression;
|
|
970
|
+
const refHoldsTime = isTime(refType(ref));
|
|
971
|
+
if (expression.operator === '/=' &&
|
|
972
|
+
(refHoldsTime || isTime64(valueExpression))) {
|
|
973
|
+
throw aotError('AOT: `/=` on a 64-bit time value is not supported', 'JS division gives a fraction; write ref.current = Math.floor(ref.current / n) for whole units.');
|
|
974
|
+
}
|
|
975
|
+
// A 64-bit `%=` keeps its constant divisor.
|
|
976
|
+
const wideModuloDivisor = expression.operator === '%=' && (refHoldsTime || isTime64(valueExpression))
|
|
977
|
+
? constDivisor(expression.right, environment)
|
|
978
|
+
: null;
|
|
979
|
+
checkStored(valueExpression, { slotType: ref.slotKind, isBoolean: false }, `ref "${expression.left.object.name}"`);
|
|
980
|
+
const stored = (value) => ref.slotKind === 'int' ? typedAsInt(value) : value;
|
|
981
|
+
// Whole-ref `+= -= *=`, float `/=` and float `%=` are the binary op, to share its checked and float math.
|
|
982
|
+
const isWholeRef = ref.slotKind === 'int' || ref.slotKind === 'i64';
|
|
983
|
+
const binaryOperation = { '+=': '+', '-=': '-', '*=': '*' }[expression.operator];
|
|
984
|
+
const isFloatModulo = expression.operator === '%=' &&
|
|
985
|
+
(ref.slotKind === 'float' || valueExpression.type.kind === 'float');
|
|
986
|
+
if ((isWholeRef &&
|
|
987
|
+
(binaryOperation ||
|
|
988
|
+
(expression.operator === '/=' &&
|
|
989
|
+
valueExpression.type.kind === 'float'))) ||
|
|
990
|
+
isFloatModulo) {
|
|
991
|
+
const resultExpression = typeSource(binarySource({
|
|
992
|
+
type: 'BinaryExpression',
|
|
993
|
+
operator: binaryOperation ?? expression.operator.slice(0, -1),
|
|
994
|
+
left: expression.left,
|
|
995
|
+
right: expression.right,
|
|
996
|
+
loc: expression.loc,
|
|
997
|
+
}, { kind: 'ref', ref, location: expression.left.loc?.start }, loweredValue.source, environment), ref.slotKind === 'i64' || Boolean(environment.math64?.()));
|
|
998
|
+
return { operator: '=', value: stored(resultExpression) };
|
|
999
|
+
}
|
|
1000
|
+
// Whole-number `/=` and `%=` use the checked helpers for JS's answer, in 64 bits on a 64-bit ref that holds no
|
|
1001
|
+
// time; a constant divisor other than 0 or -1 needs no check.
|
|
1002
|
+
const isWholeValue = isIntSlot(valueExpression.type) ||
|
|
1003
|
+
(valueExpression.type.kind === 'int64' && !isTime64(valueExpression));
|
|
1004
|
+
const refBits = ref.slotKind === 'i64' ? 64 : 32;
|
|
1005
|
+
if (((ref.slotKind === 'int' && isIntSlot(valueExpression.type)) ||
|
|
1006
|
+
(ref.slotKind === 'i64' && !refHoldsTime && isWholeValue)) &&
|
|
1007
|
+
(expression.operator === '/=' || expression.operator === '%=')) {
|
|
1008
|
+
const staticDivisor = staticInt(expression.right, environment);
|
|
1009
|
+
if (expression.operator === '/=' &&
|
|
1010
|
+
(staticDivisor === null || staticDivisor === 0 || staticDivisor === -1)) {
|
|
1011
|
+
return {
|
|
1012
|
+
operator: '=',
|
|
1013
|
+
value: {
|
|
1014
|
+
kind: 'helper',
|
|
1015
|
+
helper: 'div',
|
|
1016
|
+
bits: refBits,
|
|
1017
|
+
callArguments: [refRead(ref), valueExpression],
|
|
1018
|
+
type: refType(ref),
|
|
1019
|
+
},
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
if (expression.operator === '%=' &&
|
|
1023
|
+
(staticDivisor === 0 || staticDivisor === -1)) {
|
|
1024
|
+
return { operator: '=', value: ZERO };
|
|
1025
|
+
}
|
|
1026
|
+
if (expression.operator === '%=' && staticDivisor === null) {
|
|
1027
|
+
return {
|
|
1028
|
+
operator: '=',
|
|
1029
|
+
value: {
|
|
1030
|
+
kind: 'helper',
|
|
1031
|
+
helper: 'mod',
|
|
1032
|
+
bits: refBits,
|
|
1033
|
+
callArguments: [refRead(ref), valueExpression],
|
|
1034
|
+
type: refType(ref),
|
|
1035
|
+
},
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
// A 64-bit `%=` by 0 or ±1 stores 0: no remainder, JS's NaN as 0, and no overflow on INT64_MIN % -1.
|
|
1040
|
+
if (wideModuloDivisor === 0 ||
|
|
1041
|
+
wideModuloDivisor === 1 ||
|
|
1042
|
+
wideModuloDivisor === -1) {
|
|
1043
|
+
return { operator: '=', value: ZERO };
|
|
1044
|
+
}
|
|
1045
|
+
// Everything else is a plain assignment or compound assignment.
|
|
1046
|
+
return {
|
|
1047
|
+
operator: expression.operator,
|
|
1048
|
+
value: expression.operator === '=' ? stored(valueExpression) : valueExpression,
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
279
1051
|
/**
|
|
280
1052
|
* Resolves `node` to its ref when it is `<ref>.current` member access on a known value ref.
|
|
281
1053
|
*
|
|
@@ -444,38 +1216,295 @@ function lowerUpdateVector(expression, environment, context) {
|
|
|
444
1216
|
return lowerExpr(edgeNode, environment);
|
|
445
1217
|
});
|
|
446
1218
|
}
|
|
447
|
-
return update;
|
|
1219
|
+
return update;
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* Lowers setInterval/setTimeout(cb, ms) to a timer, and registers cb as a timer function of its own.
|
|
1223
|
+
*
|
|
1224
|
+
* @param expression The setInterval / setTimeout call.
|
|
1225
|
+
* @param environment The expression environment.
|
|
1226
|
+
* @param state The component's state table.
|
|
1227
|
+
* @param context The statement compiler's context.
|
|
1228
|
+
*
|
|
1229
|
+
* @returns The timer.
|
|
1230
|
+
*/
|
|
1231
|
+
function lowerTimer(expression, environment, state, context) {
|
|
1232
|
+
const callback = expression.arguments[0];
|
|
1233
|
+
if (!isFn(callback)) {
|
|
1234
|
+
throw aotError('AOT: a setInterval/setTimeout callback must be an inline function', 'pass an inline arrow, e.g. setInterval(() => setTick((t) => t + 1), 1000).');
|
|
1235
|
+
}
|
|
1236
|
+
// Any delay is accepted here; the printer converts a timestamp or float one the way Flow A's setTimeout does.
|
|
1237
|
+
const delay = expression.arguments[1]
|
|
1238
|
+
? lowerExprWide(expression.arguments[1], environment)
|
|
1239
|
+
: null;
|
|
1240
|
+
const isRepeating = expression.callee.name === 'setInterval';
|
|
1241
|
+
// Reserve the timer's slot before compiling its body, which may add timers of its own.
|
|
1242
|
+
const slot = context.output.timerFunctions.length;
|
|
1243
|
+
const timerFunctionName = `timer_${slot}`;
|
|
1244
|
+
context.output.timerFunctions.push({ name: timerFunctionName, callback: null });
|
|
1245
|
+
context.output.timerFunctions[slot].callback = lowerHandler(callback, environment, state, context.output);
|
|
1246
|
+
return { delay, isRepeating, functionName: timerFunctionName };
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Checks a setter called inside a loop. One for a list the loop visits is refused, as the loop would see the rows
|
|
1250
|
+
* it changes, where React's loops over the list as it was. So is a setter given a value that reads its own state:
|
|
1251
|
+
* React's reads the value from before the loop each time, so only the last call counts, where Flow B's would see
|
|
1252
|
+
* each call's.
|
|
1253
|
+
*
|
|
1254
|
+
* @param setter The setter's name.
|
|
1255
|
+
* @param target What it sets.
|
|
1256
|
+
* @param argument What it is given.
|
|
1257
|
+
* @param environment The expression environment.
|
|
1258
|
+
* @param loops The lists each loop around it visits or is bounded by.
|
|
1259
|
+
*/
|
|
1260
|
+
function checkLoopSetter(setter, target, argument, environment, loops) {
|
|
1261
|
+
if (target.kind === 'list' && loops.some(lists => lists.includes(target))) {
|
|
1262
|
+
throw aotError(`AOT: ${setter} can't change ${target.name} inside a loop over it`, 'the loop would see the rows it changes, where React loops over the list as it was. Work out what to ' +
|
|
1263
|
+
'change in the loop, into a let, and set the list after it.');
|
|
1264
|
+
}
|
|
1265
|
+
if (!argument || isFn(argument))
|
|
1266
|
+
return;
|
|
1267
|
+
const names = new Set([target.name]);
|
|
1268
|
+
for (const [name, record] of environment.state) {
|
|
1269
|
+
if (record === target)
|
|
1270
|
+
names.add(name);
|
|
1271
|
+
}
|
|
1272
|
+
if (mentions(argument, names)) {
|
|
1273
|
+
throw aotError(`AOT: ${setter}(…) inside a loop must take an updater to read ${target.name}`, `React reads ${target.name} from before the loop each time, so only the last call would count. Write ` +
|
|
1274
|
+
`${setter}(previous => …), or work the value out in a let and set it after the loop.`);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
/**
|
|
1278
|
+
* Lowers `x = …`, `x += …` or `x++` on a `let` local. A whole-number `let` given a fraction or a timestamp is
|
|
1279
|
+
* widened to hold it, once every store is lowered; a boolean or a string one holds only those.
|
|
1280
|
+
*
|
|
1281
|
+
* @param expression The assignment or update.
|
|
1282
|
+
* @param target The local's name.
|
|
1283
|
+
* @param local The local.
|
|
1284
|
+
* @param environment The expression environment.
|
|
1285
|
+
*
|
|
1286
|
+
* @returns The statement.
|
|
1287
|
+
*/
|
|
1288
|
+
function lowerLocalAssign(expression, target, local, environment) {
|
|
1289
|
+
const { name } = target;
|
|
1290
|
+
if (!local.assignable) {
|
|
1291
|
+
if (local.list) {
|
|
1292
|
+
throw aotError(`AOT: "${name}" is a list's item, which can't be set`, `copy what you need into a let: let value = ${name}.value;`);
|
|
1293
|
+
}
|
|
1294
|
+
throw aotError(local.counter
|
|
1295
|
+
? `AOT: "${name}" is a loop's counter, which only the loop sets`
|
|
1296
|
+
: `AOT: "${name}" can't be assigned: only a \`let\` can`, local.counter
|
|
1297
|
+
? `copy it into a let of its own first: let at = ${name};`
|
|
1298
|
+
: `declare it with let to change it: let ${name} = …;`);
|
|
1299
|
+
}
|
|
1300
|
+
// What it is set to, as one expression: `x += e` is `x + e`, and `x++` is `x + 1`.
|
|
1301
|
+
const { loc } = expression;
|
|
1302
|
+
let valueNode;
|
|
1303
|
+
if (expression.type === 'UpdateExpression') {
|
|
1304
|
+
valueNode = {
|
|
1305
|
+
type: 'BinaryExpression',
|
|
1306
|
+
operator: expression.operator === '++' ? '+' : '-',
|
|
1307
|
+
left: target,
|
|
1308
|
+
right: { type: 'NumericLiteral', value: 1 },
|
|
1309
|
+
loc,
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
else if (expression.operator === '=') {
|
|
1313
|
+
valueNode = expression.right;
|
|
1314
|
+
}
|
|
1315
|
+
else {
|
|
1316
|
+
const operator = expression.operator.slice(0, -1);
|
|
1317
|
+
valueNode =
|
|
1318
|
+
operator === '&&' || operator === '||' || operator === '??'
|
|
1319
|
+
? {
|
|
1320
|
+
type: 'LogicalExpression',
|
|
1321
|
+
operator,
|
|
1322
|
+
left: target,
|
|
1323
|
+
right: expression.right,
|
|
1324
|
+
loc,
|
|
1325
|
+
}
|
|
1326
|
+
: {
|
|
1327
|
+
type: 'BinaryExpression',
|
|
1328
|
+
operator: operator,
|
|
1329
|
+
left: target,
|
|
1330
|
+
right: expression.right,
|
|
1331
|
+
loc,
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
const holds = (what) => aotError(`AOT: "${name}" holds ${what}, so it can only be set to ${what === 'a string' ? 'strings' : what === 'a boolean' ? 'booleans' : 'numbers'}`, `a let keeps the kind of value it starts with; declare another let for a value of another kind.`);
|
|
1335
|
+
const localName = local.name;
|
|
1336
|
+
// A string is built in the local's buffer, which may be read to build it.
|
|
1337
|
+
if (localShape(local) === 'string') {
|
|
1338
|
+
if (buildsText(valueNode, environment)) {
|
|
1339
|
+
return {
|
|
1340
|
+
kind: 'assignLocal',
|
|
1341
|
+
name: localName,
|
|
1342
|
+
value: { kind: 'string', value: '', type: STRING },
|
|
1343
|
+
text: lowerText(valueNode, environment),
|
|
1344
|
+
};
|
|
1345
|
+
}
|
|
1346
|
+
const value = lowerExpr(valueNode, environment);
|
|
1347
|
+
if (shapeOf(value) !== 'string')
|
|
1348
|
+
throw holds('a string');
|
|
1349
|
+
whenTyped(() => {
|
|
1350
|
+
if (value.kind === 'string') {
|
|
1351
|
+
checkConstantFits({ parts: [{ kind: 'literal', text: value.value }] }, `local "${name}"`);
|
|
1352
|
+
}
|
|
1353
|
+
});
|
|
1354
|
+
return { kind: 'assignLocal', name: localName, value };
|
|
1355
|
+
}
|
|
1356
|
+
const holdsBoolean = localShape(local) === 'bool';
|
|
1357
|
+
const lowered = lowerSource(valueNode, storeEnvironment(environment, () => is64BitLocal(local)));
|
|
1358
|
+
const shape = shapeOf(lowered.expression);
|
|
1359
|
+
if (holdsBoolean ? shape !== 'bool' : shape === 'bool') {
|
|
1360
|
+
throw holds(holdsBoolean ? 'a boolean' : 'a number');
|
|
1361
|
+
}
|
|
1362
|
+
if (shape === 'string')
|
|
1363
|
+
throw holds('a number');
|
|
1364
|
+
if (!holdsBoolean) {
|
|
1365
|
+
recordStore(lowered.source, local.assignable, local, environment);
|
|
1366
|
+
}
|
|
1367
|
+
whenTyped(() => checkStored(lowered.expression, { slotType: local.slotKind, isBoolean: holdsBoolean }, `local "${name}"`));
|
|
1368
|
+
return {
|
|
1369
|
+
kind: 'assignLocal',
|
|
1370
|
+
name: localName,
|
|
1371
|
+
value: storeValue(lowered.expression, () => local.slotKind),
|
|
1372
|
+
};
|
|
1373
|
+
}
|
|
1374
|
+
/**
|
|
1375
|
+
* The environment an updater's body reads: its parameter names the state's current value. A list's is the list,
|
|
1376
|
+
* an object's its fields, and a scalar's a read of its slot.
|
|
1377
|
+
*
|
|
1378
|
+
* @param target The state set.
|
|
1379
|
+
* @param updater The updater.
|
|
1380
|
+
* @param environment The handler's environment.
|
|
1381
|
+
*
|
|
1382
|
+
* @returns The body's environment.
|
|
1383
|
+
*/
|
|
1384
|
+
function updaterEnvironment(target, updater, environment) {
|
|
1385
|
+
const previousName = updater.params[0]?.name;
|
|
1386
|
+
if (!previousName)
|
|
1387
|
+
return environment;
|
|
1388
|
+
// The parameter hides any local or state of its name.
|
|
1389
|
+
const locals = new Map(environment.locals);
|
|
1390
|
+
locals.delete(previousName);
|
|
1391
|
+
const state = new Map(environment.state);
|
|
1392
|
+
state.delete(previousName);
|
|
1393
|
+
if (target.kind === 'list') {
|
|
1394
|
+
return {
|
|
1395
|
+
...environment,
|
|
1396
|
+
locals,
|
|
1397
|
+
state: state.set(previousName, target),
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
if (target.kind === 'record') {
|
|
1401
|
+
return {
|
|
1402
|
+
...environment,
|
|
1403
|
+
locals,
|
|
1404
|
+
state,
|
|
1405
|
+
constants: { ...environment.constants, [previousName]: target.value },
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
const previous = stateRead(target, true);
|
|
1409
|
+
locals.set(previousName, holdLater({
|
|
1410
|
+
source: {
|
|
1411
|
+
kind: 'state',
|
|
1412
|
+
state: target,
|
|
1413
|
+
latest: true,
|
|
1414
|
+
location: undefined,
|
|
1415
|
+
},
|
|
1416
|
+
expression: previous,
|
|
1417
|
+
}, shapeOf(previous), () => ({
|
|
1418
|
+
slotKind: target.slotKind,
|
|
1419
|
+
isBoolean: target.isBoolean,
|
|
1420
|
+
...(target.widened === 'number' ? { isLiteral: true } : {}),
|
|
1421
|
+
})));
|
|
1422
|
+
return { ...environment, locals, state };
|
|
1423
|
+
}
|
|
1424
|
+
/**
|
|
1425
|
+
* Lowers a setter given an updater with a block body: the body runs in place, and each `return next` sets the
|
|
1426
|
+
* state through an updater of its own, then leaves the body.
|
|
1427
|
+
*
|
|
1428
|
+
* @param setter The setter's name.
|
|
1429
|
+
* @param target The state set.
|
|
1430
|
+
* @param updater The updater.
|
|
1431
|
+
* @param environment The handler's environment.
|
|
1432
|
+
* @param state The component's state table.
|
|
1433
|
+
* @param context The statement compiler's context.
|
|
1434
|
+
* @param what What the updater is, for errors.
|
|
1435
|
+
*
|
|
1436
|
+
* @returns The statements.
|
|
1437
|
+
*/
|
|
1438
|
+
function inlineUpdater(setter, target, updater, environment, state, context, what) {
|
|
1439
|
+
const statements = updaterStatements(setter, updater, target.kind === 'list', what);
|
|
1440
|
+
const { helperList, usedReturn } = context;
|
|
1441
|
+
context.helperList = statements;
|
|
1442
|
+
context.usedReturn = false;
|
|
1443
|
+
try {
|
|
1444
|
+
const lowered = lowerStmts(statements, updaterEnvironment(target, updater, environment), state, context);
|
|
1445
|
+
return context.usedReturn ? [{ kind: 'block', body: lowered }] : lowered;
|
|
1446
|
+
}
|
|
1447
|
+
finally {
|
|
1448
|
+
context.helperList = helperList;
|
|
1449
|
+
context.usedReturn = usedReturn;
|
|
1450
|
+
}
|
|
448
1451
|
}
|
|
449
1452
|
/**
|
|
450
|
-
* Lowers
|
|
1453
|
+
* Lowers a dispatch: the reducer runs in place as an updater, its state parameter reading the state and its action
|
|
1454
|
+
* parameter bound to what is dispatched. Branches the action's constant fields rule out are dropped first.
|
|
451
1455
|
*
|
|
452
|
-
* @param
|
|
453
|
-
* @param
|
|
1456
|
+
* @param dispatch The dispatch's name.
|
|
1457
|
+
* @param target The state it sets.
|
|
1458
|
+
* @param reducer The state's reducer.
|
|
1459
|
+
* @param action What is dispatched.
|
|
1460
|
+
* @param environment The handler's environment.
|
|
454
1461
|
* @param state The component's state table.
|
|
455
1462
|
* @param context The statement compiler's context.
|
|
456
1463
|
*
|
|
457
|
-
* @returns The
|
|
1464
|
+
* @returns The statements.
|
|
458
1465
|
*/
|
|
459
|
-
function
|
|
460
|
-
const
|
|
461
|
-
if (!
|
|
462
|
-
throw aotError(
|
|
1466
|
+
function inlineReducer(dispatch, target, { name, functionNode }, action, environment, state, context) {
|
|
1467
|
+
const [stateParameter, actionParameter] = functionNode.params;
|
|
1468
|
+
if (!action || action.type === 'SpreadElement') {
|
|
1469
|
+
throw aotError(`AOT: ${dispatch} must be given an action`, `pass the action itself: ${dispatch}({type: 'increment'}).`);
|
|
463
1470
|
}
|
|
464
|
-
//
|
|
465
|
-
const
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
1471
|
+
// An action that picks between two at run time dispatches each in a branch of its own.
|
|
1472
|
+
const choice = actionChoice(action, foldScope(environment, environment.constants ?? {}));
|
|
1473
|
+
if (choice) {
|
|
1474
|
+
const dispatchOf = (picked) => inlineReducer(dispatch, target, { name, functionNode }, picked, environment, state, context);
|
|
1475
|
+
return [
|
|
1476
|
+
{
|
|
1477
|
+
kind: 'if',
|
|
1478
|
+
test: lowerExprWide(choice.test, environment),
|
|
1479
|
+
consequent: dispatchOf(choice.whenTrue),
|
|
1480
|
+
alternate: dispatchOf(choice.whenFalse),
|
|
1481
|
+
},
|
|
1482
|
+
];
|
|
1483
|
+
}
|
|
1484
|
+
const bodyEnvironment = actionEnvironment(actionParameter?.name, action, environment);
|
|
1485
|
+
const statements = functionNode.body.type === 'BlockStatement'
|
|
1486
|
+
? functionNode.body.body
|
|
1487
|
+
: [{ type: 'ReturnStatement', argument: functionNode.body }];
|
|
1488
|
+
const unpruned = {
|
|
1489
|
+
type: 'ArrowFunctionExpression',
|
|
1490
|
+
params: stateParameter ? [stateParameter] : [],
|
|
1491
|
+
body: { type: 'BlockStatement', body: statements, directives: [] },
|
|
1492
|
+
loc: functionNode.loc,
|
|
1493
|
+
};
|
|
1494
|
+
const readEnvironment = updaterEnvironment(target, unpruned, bodyEnvironment);
|
|
1495
|
+
const updater = {
|
|
1496
|
+
...unpruned,
|
|
1497
|
+
body: {
|
|
1498
|
+
...unpruned.body,
|
|
1499
|
+
body: prunedStatements(statements, foldScope(readEnvironment, readEnvironment.constants ?? {})),
|
|
1500
|
+
},
|
|
1501
|
+
};
|
|
1502
|
+
return inlineUpdater(dispatch, target, updater, bodyEnvironment, state, context, `reducer "${name}"`);
|
|
475
1503
|
}
|
|
476
1504
|
/**
|
|
477
|
-
* Inlines a handler-statement call to a helper / useCallback: binds the call's args to the helper's params
|
|
478
|
-
*
|
|
1505
|
+
* Inlines a handler-statement call to a helper / useCallback: binds the call's args to the helper's params, then
|
|
1506
|
+
* lowers the helper body here in the current env/state/ctx. A `return` in it leaves the helper, which becomes a
|
|
1507
|
+
* block.
|
|
479
1508
|
*
|
|
480
1509
|
* @param helperName The helper's name.
|
|
481
1510
|
* @param helper The helper.
|
|
@@ -487,48 +1516,50 @@ function lowerTimer(expression, environment, state, context) {
|
|
|
487
1516
|
* @returns The helper's body as statements.
|
|
488
1517
|
*/
|
|
489
1518
|
function inlineHelperCall(helperName, helper, callArguments, environment, state, context) {
|
|
490
|
-
// A helper already being inlined further up this call chain is recursive.
|
|
491
|
-
context.inlining = context.inlining ?? new Set();
|
|
492
|
-
if (context.inlining.has(helperName)) {
|
|
493
|
-
throw aotError(`AOT: helper "${helperName}" is recursive — can't be inlined into a handler`, 'handlers are flattened to straight-line code, so a helper that calls itself (directly ' +
|
|
494
|
-
'or via another helper) has no base case to unroll. Move recursive logic out of the ' +
|
|
495
|
-
'handler, or precompute the value.');
|
|
496
|
-
}
|
|
497
|
-
// Bind each passed argument to its parameter as a local holding the argument's expression.
|
|
498
|
-
const locals = new Map(environment.locals);
|
|
499
|
-
helper.params.forEach((parameter, parameterIndex) => {
|
|
500
|
-
if (parameter.type !== 'Identifier') {
|
|
501
|
-
throw aotError(`AOT: helper "${helperName}" must take simple (identifier) params to be inlined`, 'a helper called from a handler must use plain positional params (e.g. `(a, b) => …`) ' +
|
|
502
|
-
'— destructuring or default params in the signature are not supported.');
|
|
503
|
-
}
|
|
504
|
-
if (callArguments[parameterIndex]) {
|
|
505
|
-
const argumentExpression = lowerSourcedWide(callArguments[parameterIndex], environment);
|
|
506
|
-
locals.set(parameter.name, {
|
|
507
|
-
slotKind: argumentExpression.slotKind,
|
|
508
|
-
isBoolean: argumentExpression.isBoolean,
|
|
509
|
-
isLiteral: argumentExpression.isLiteral,
|
|
510
|
-
wide: argumentExpression.wide,
|
|
511
|
-
source: argumentExpression.source,
|
|
512
|
-
expression: argumentExpression.expression,
|
|
513
|
-
});
|
|
514
|
-
}
|
|
515
|
-
});
|
|
516
1519
|
// An expression body is a single statement.
|
|
517
1520
|
const body = helper.body;
|
|
518
1521
|
const statements = body.type === 'BlockStatement'
|
|
519
1522
|
? body.body
|
|
520
1523
|
: [{ type: 'ExpressionStatement', expression: body }];
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
context.
|
|
524
|
-
context.allowReturn = false;
|
|
1524
|
+
const { helperList, usedReturn } = context;
|
|
1525
|
+
context.helperList = statements;
|
|
1526
|
+
context.usedReturn = false;
|
|
525
1527
|
try {
|
|
526
|
-
|
|
1528
|
+
const lowered = lowerStmts(statements, helperEnvironment(helperName, helper, callArguments, environment), state, context);
|
|
1529
|
+
return context.usedReturn ? [{ kind: 'block', body: lowered }] : lowered;
|
|
527
1530
|
}
|
|
528
1531
|
finally {
|
|
529
|
-
context.
|
|
530
|
-
context.
|
|
1532
|
+
context.helperList = helperList;
|
|
1533
|
+
context.usedReturn = usedReturn;
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
/** The console methods a package can call, as Flow A has them. */
|
|
1537
|
+
const CONSOLE_METHODS = new Set(['log', 'warn', 'error']);
|
|
1538
|
+
/**
|
|
1539
|
+
* Whether a call is `console.log`, `console.warn` or `console.error`, on the global console: not a local, a state
|
|
1540
|
+
* or a constant of that name.
|
|
1541
|
+
*
|
|
1542
|
+
* @param call The call.
|
|
1543
|
+
* @param environment The expression environment.
|
|
1544
|
+
*
|
|
1545
|
+
* @returns True when it is.
|
|
1546
|
+
*/
|
|
1547
|
+
function isConsoleCall(call, environment) {
|
|
1548
|
+
const { callee } = call;
|
|
1549
|
+
if (callee.type !== 'MemberExpression' ||
|
|
1550
|
+
callee.computed ||
|
|
1551
|
+
callee.object.type !== 'Identifier' ||
|
|
1552
|
+
callee.object.name !== 'console' ||
|
|
1553
|
+
callee.property.type !== 'Identifier' ||
|
|
1554
|
+
environment.locals.has('console') ||
|
|
1555
|
+
environment.state.has('console') ||
|
|
1556
|
+
'console' in (environment.constants ?? {})) {
|
|
1557
|
+
return false;
|
|
1558
|
+
}
|
|
1559
|
+
if (!CONSOLE_METHODS.has(callee.property.name)) {
|
|
1560
|
+
throw aotError(`AOT: console.${callee.property.name} is not supported`, 'a package has console.log, console.warn and console.error, each one line in the host log.');
|
|
531
1561
|
}
|
|
1562
|
+
return true;
|
|
532
1563
|
}
|
|
533
1564
|
/**
|
|
534
1565
|
* Lowers one handler ExpressionStatement: a state setter, ref mutation, timer, updateVector, helper call, or
|
|
@@ -541,13 +1572,51 @@ function inlineHelperCall(helperName, helper, callArguments, environment, state,
|
|
|
541
1572
|
*
|
|
542
1573
|
* @returns The statements.
|
|
543
1574
|
*/
|
|
544
|
-
function lowerHandlerExprImpl(expression,
|
|
1575
|
+
function lowerHandlerExprImpl(expression, handlerEnvironment, state, context) {
|
|
1576
|
+
const environment = handlerEnvironment.outsideRender
|
|
1577
|
+
? handlerEnvironment
|
|
1578
|
+
: { ...handlerEnvironment, outsideRender: true };
|
|
1579
|
+
// `Sensors.setLed(on)`: a native method called for what it does.
|
|
1580
|
+
if (expression.type === 'CallExpression') {
|
|
1581
|
+
const nativeCallee = nativeCalleeOf(expression, environment);
|
|
1582
|
+
if (nativeCallee) {
|
|
1583
|
+
return [
|
|
1584
|
+
{
|
|
1585
|
+
kind: 'callNative',
|
|
1586
|
+
call: lowerNativeCall(expression, nativeCallee, environment),
|
|
1587
|
+
},
|
|
1588
|
+
];
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
// console.log / warn / error(…) → one line for the host's log.
|
|
1592
|
+
if (expression.type === 'CallExpression' &&
|
|
1593
|
+
isConsoleCall(expression, environment)) {
|
|
1594
|
+
const text = lowerLogText(expression.arguments, environment);
|
|
1595
|
+
return context.output.release ? [] : [{ kind: 'log', text }];
|
|
1596
|
+
}
|
|
1597
|
+
// Alert.alert(…) → its dialog is built under the root, and the call sets the state that shows it.
|
|
1598
|
+
if (expression.type === 'CallExpression' &&
|
|
1599
|
+
expression.callee.type === 'Identifier' &&
|
|
1600
|
+
expression.callee.name === ALERT_CALL) {
|
|
1601
|
+
const raised = raiseAlert(expression, environment, state, context.output);
|
|
1602
|
+
return lowerHandlerExprImpl(raised.setter, raised.environment, raised.state, context);
|
|
1603
|
+
}
|
|
545
1604
|
// updateVector(ref, shapes, dirtyRect?) — imperative vector redraw (no update).
|
|
546
1605
|
if (expression.type === 'CallExpression' &&
|
|
547
1606
|
expression.callee.type === 'Identifier' &&
|
|
548
1607
|
expression.callee.name === 'updateVector') {
|
|
549
1608
|
return [lowerUpdateVector(expression, environment, context)];
|
|
550
1609
|
}
|
|
1610
|
+
// scrollTo(ref.current, {x, y}) — scrolls a ScrollView, its position dropped.
|
|
1611
|
+
if (isScrollToCall(expression)) {
|
|
1612
|
+
return [lowerScrollTo(expression, environment)];
|
|
1613
|
+
}
|
|
1614
|
+
// Keyboard.dismiss() — blurs the focused TextInput.
|
|
1615
|
+
if (expression.type === 'CallExpression' &&
|
|
1616
|
+
expression.callee.type === 'Identifier' &&
|
|
1617
|
+
expression.callee.name === KEYBOARD_DISMISS_CALL) {
|
|
1618
|
+
return [{ kind: 'dismissKeyboard' }];
|
|
1619
|
+
}
|
|
551
1620
|
// setInterval / setTimeout(cb, ms) → register a host-tick timer (the returned id is discarded here).
|
|
552
1621
|
if (expression.type === 'CallExpression' &&
|
|
553
1622
|
expression.callee.type === 'Identifier' &&
|
|
@@ -573,139 +1642,58 @@ function lowerHandlerExprImpl(expression, environment, state, context) {
|
|
|
573
1642
|
},
|
|
574
1643
|
];
|
|
575
1644
|
}
|
|
576
|
-
// `
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
}
|
|
582
|
-
// Lower the right side in the ref's width and check it fits; a 64-bit `%=` keeps its constant divisor.
|
|
583
|
-
const refEnvironment = ref.slotKind === 'i64' ? { ...environment, math64: true } : environment;
|
|
584
|
-
const loweredValue = lowerSource(expression.right, refEnvironment);
|
|
585
|
-
const valueExpression = loweredValue.expression;
|
|
586
|
-
const refHoldsTime = isTime(refType(ref));
|
|
587
|
-
if (expression.operator === '/=' &&
|
|
588
|
-
(refHoldsTime || isTime64(valueExpression))) {
|
|
589
|
-
throw aotError('AOT: `/=` on a 64-bit time value is not supported', 'JS division gives a fraction; write ref.current = Math.floor(ref.current / n) for whole units.');
|
|
590
|
-
}
|
|
591
|
-
const wideModuloDivisor = expression.operator === '%=' &&
|
|
592
|
-
(refHoldsTime || isTime64(valueExpression))
|
|
593
|
-
? constDivisor(expression.right, environment)
|
|
1645
|
+
// `x = …`, `x += …` and `x++` on a local, which must be a `let`.
|
|
1646
|
+
const assigned = expression.type === 'AssignmentExpression'
|
|
1647
|
+
? expression.left
|
|
1648
|
+
: expression.type === 'UpdateExpression'
|
|
1649
|
+
? expression.argument
|
|
594
1650
|
: null;
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
const binaryOperation = { '+=': '+', '-=': '-', '*=': '*' }[expression.operator];
|
|
599
|
-
const isFloatModulo = expression.operator === '%=' &&
|
|
600
|
-
(ref.slotKind === 'float' || valueExpression.type.kind === 'float');
|
|
601
|
-
if ((isWholeRef &&
|
|
602
|
-
(binaryOperation ||
|
|
603
|
-
(expression.operator === '/=' &&
|
|
604
|
-
valueExpression.type.kind === 'float'))) ||
|
|
605
|
-
isFloatModulo) {
|
|
606
|
-
const resultExpression = lowerExprWide({
|
|
607
|
-
type: 'BinaryExpression',
|
|
608
|
-
operator: binaryOperation ?? expression.operator.slice(0, -1),
|
|
609
|
-
left: expression.left,
|
|
610
|
-
right: expression.right,
|
|
611
|
-
loc: expression.loc,
|
|
612
|
-
}, refEnvironment);
|
|
1651
|
+
if (assigned?.type === 'Identifier') {
|
|
1652
|
+
const local = environment.locals.get(assigned.name);
|
|
1653
|
+
if (local) {
|
|
613
1654
|
return [
|
|
614
|
-
|
|
615
|
-
kind: 'writeRef',
|
|
616
|
-
ref,
|
|
617
|
-
operator: '=',
|
|
618
|
-
value: storeValue(resultExpression, ref.slotKind),
|
|
619
|
-
},
|
|
1655
|
+
lowerLocalAssign(expression, assigned, local, environment),
|
|
620
1656
|
];
|
|
621
1657
|
}
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
(ref.slotKind === 'i64' && !refHoldsTime && isWholeValue)) &&
|
|
629
|
-
(expression.operator === '/=' || expression.operator === '%=')) {
|
|
630
|
-
const staticDivisor = staticInt(expression.right, environment);
|
|
631
|
-
if (expression.operator === '/=' &&
|
|
632
|
-
(staticDivisor === null || staticDivisor === 0 || staticDivisor === -1)) {
|
|
633
|
-
return [
|
|
634
|
-
{
|
|
635
|
-
kind: 'writeRef',
|
|
636
|
-
ref,
|
|
637
|
-
operator: '=',
|
|
638
|
-
value: {
|
|
639
|
-
kind: 'helper',
|
|
640
|
-
helper: 'div',
|
|
641
|
-
bits: refBits,
|
|
642
|
-
callArguments: [refRead(ref), valueExpression],
|
|
643
|
-
type: refType(ref),
|
|
644
|
-
},
|
|
645
|
-
},
|
|
646
|
-
];
|
|
647
|
-
}
|
|
648
|
-
if (expression.operator === '%=' &&
|
|
649
|
-
(staticDivisor === 0 || staticDivisor === -1)) {
|
|
650
|
-
return [{ kind: 'writeRef', ref, operator: '=', value: ZERO }];
|
|
651
|
-
}
|
|
652
|
-
if (expression.operator === '%=' && staticDivisor === null) {
|
|
653
|
-
return [
|
|
654
|
-
{
|
|
655
|
-
kind: 'writeRef',
|
|
656
|
-
ref,
|
|
657
|
-
operator: '=',
|
|
658
|
-
value: {
|
|
659
|
-
kind: 'helper',
|
|
660
|
-
helper: 'mod',
|
|
661
|
-
bits: refBits,
|
|
662
|
-
callArguments: [refRead(ref), valueExpression],
|
|
663
|
-
type: refType(ref),
|
|
664
|
-
},
|
|
665
|
-
},
|
|
666
|
-
];
|
|
667
|
-
}
|
|
1658
|
+
}
|
|
1659
|
+
// `ref.current = expr` / `ref.current += expr` — a value ref write; does NOT trigger a re-render.
|
|
1660
|
+
if (expression.type === 'AssignmentExpression') {
|
|
1661
|
+
const ref = refTarget(expression.left, environment);
|
|
1662
|
+
if (!ref) {
|
|
1663
|
+
throw new Error('AOT: a handler can only assign a `let` local or `ref.current`');
|
|
668
1664
|
}
|
|
669
|
-
//
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
return [{ kind: 'writeRef', ref, operator: '=', value: ZERO }];
|
|
1665
|
+
// Lower the right side; the typing pass works out the write, once it knows the ref's width.
|
|
1666
|
+
const value = lowerSource(expression.right, storeEnvironment(environment, () => is64BitSlot(ref)));
|
|
1667
|
+
if (ref.kind === 'value' && ref.slotKind !== 'float') {
|
|
1668
|
+
recordStore(value.source, ref.slotName, ref, environment);
|
|
674
1669
|
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
kind: 'writeRef',
|
|
679
|
-
ref,
|
|
680
|
-
operator: expression.operator,
|
|
681
|
-
value: expression.operator === '='
|
|
682
|
-
? storeValue(valueExpression, ref.slotKind)
|
|
683
|
-
: valueExpression,
|
|
684
|
-
},
|
|
685
|
-
];
|
|
1670
|
+
const statement = { kind: 'writeRef', ref };
|
|
1671
|
+
setLater(statement, ['operator', 'value'], () => typedRefWrite(expression, ref, value, environment));
|
|
1672
|
+
return [statement];
|
|
686
1673
|
}
|
|
687
1674
|
// `ref.current++` / `ref.current--`; a whole-number ref steps through the checked `+ 1` / `- 1`.
|
|
688
1675
|
if (expression.type === 'UpdateExpression') {
|
|
689
1676
|
const ref = refTarget(expression.argument, environment);
|
|
690
1677
|
if (!ref) {
|
|
691
|
-
throw new Error('AOT:
|
|
1678
|
+
throw new Error('AOT: a handler can only use ++/-- on a `let` local or `ref.current`');
|
|
692
1679
|
}
|
|
693
1680
|
if (ref.slotKind === 'int' || ref.slotKind === 'i64') {
|
|
1681
|
+
const { operator } = expression;
|
|
694
1682
|
return [
|
|
695
1683
|
{
|
|
696
1684
|
kind: 'writeRef',
|
|
697
1685
|
ref,
|
|
698
1686
|
operator: '=',
|
|
699
|
-
value: {
|
|
1687
|
+
value: typedLater('number', () => ({
|
|
700
1688
|
kind: 'helper',
|
|
701
|
-
helper:
|
|
1689
|
+
helper: operator === '++' ? 'add' : 'sub',
|
|
702
1690
|
bits: ref.slotKind === 'i64' ? 64 : 32,
|
|
703
1691
|
callArguments: [
|
|
704
1692
|
refRead(ref),
|
|
705
1693
|
{ kind: 'number', value: 1, type: INT },
|
|
706
1694
|
],
|
|
707
1695
|
type: refType(ref),
|
|
708
|
-
},
|
|
1696
|
+
})),
|
|
709
1697
|
},
|
|
710
1698
|
];
|
|
711
1699
|
}
|
|
@@ -748,41 +1736,74 @@ function lowerHandlerExprImpl(expression, environment, state, context) {
|
|
|
748
1736
|
if (!targetState) {
|
|
749
1737
|
throw aotError(`AOT: "${expression.callee.name}" is not a known state setter`, `a handler can only call a setter from this component's own useState (e.g. setCount), ` +
|
|
750
1738
|
`a ref write, updateVector(…), or Animated…start(). "${expression.callee.name}" isn't one ` +
|
|
751
|
-
`of those — arbitrary functions (fetch,
|
|
1739
|
+
`of those — arbitrary functions (fetch, helpers) can't be lowered.`);
|
|
752
1740
|
}
|
|
753
1741
|
context.stateChanged = true;
|
|
754
1742
|
const setterArgument = expression.arguments[0];
|
|
1743
|
+
const setterCall = expression;
|
|
1744
|
+
// An object's updater and reducer read its fields as they are now. A scalar's parameter is marked itself.
|
|
1745
|
+
if (targetState.kind === 'record' &&
|
|
1746
|
+
(targetState.reducer || isFn(setterArgument))) {
|
|
1747
|
+
const slots = [...targetState.fields.values(), targetState.tag?.state];
|
|
1748
|
+
return readingLatest(lowerSetter(setterCall, targetState, environment, state, context), new Set(slots.filter(slot => slot !== undefined)));
|
|
1749
|
+
}
|
|
1750
|
+
return lowerSetter(setterCall, targetState, environment, state, context);
|
|
1751
|
+
}
|
|
1752
|
+
/**
|
|
1753
|
+
* Lowers a state setter's call: a dispatch, an updater, or the new value itself.
|
|
1754
|
+
*
|
|
1755
|
+
* @param expression The call.
|
|
1756
|
+
* @param targetState The state it sets.
|
|
1757
|
+
* @param environment The expression environment.
|
|
1758
|
+
* @param state The component's state table.
|
|
1759
|
+
* @param context The statement compiler's context.
|
|
1760
|
+
*
|
|
1761
|
+
* @returns The statements.
|
|
1762
|
+
*/
|
|
1763
|
+
function lowerSetter(expression, targetState, environment, state, context) {
|
|
1764
|
+
const setterArgument = expression.arguments[0];
|
|
1765
|
+
// A dispatch runs the reducer. Its reads of the state are an updater's, so inside a loop only the list rule holds.
|
|
1766
|
+
if (targetState.reducer && !isReturnSet(expression)) {
|
|
1767
|
+
if (context.loops?.length) {
|
|
1768
|
+
checkLoopSetter(expression.callee.name, targetState, undefined, environment, context.loops);
|
|
1769
|
+
}
|
|
1770
|
+
return inlineReducer(expression.callee.name, targetState, targetState.reducer, setterArgument, environment, state, context);
|
|
1771
|
+
}
|
|
1772
|
+
if (context.loops?.length && !isReturnSet(expression)) {
|
|
1773
|
+
checkLoopSetter(expression.callee.name, targetState, setterArgument, environment, context.loops);
|
|
1774
|
+
}
|
|
1775
|
+
// An updater with a block body runs here, each `return next` setting the state.
|
|
1776
|
+
if (isFn(setterArgument) && setterArgument.body.type === 'BlockStatement') {
|
|
1777
|
+
return inlineUpdater(expression.callee.name, targetState, setterArgument, environment, state, context);
|
|
1778
|
+
}
|
|
755
1779
|
if (targetState.kind === 'list') {
|
|
1780
|
+
// setItems(prev => …): the parameter names the list.
|
|
1781
|
+
if (isFn(setterArgument)) {
|
|
1782
|
+
const { itemName: previousName, body } = itemCallback(setterArgument, `${expression.callee.name}'s updater`);
|
|
1783
|
+
if (!previousName) {
|
|
1784
|
+
return lowerListOp(targetState, body, environment);
|
|
1785
|
+
}
|
|
1786
|
+
return lowerListOp(targetState, body, {
|
|
1787
|
+
...environment,
|
|
1788
|
+
state: new Map(environment.state).set(previousName, targetState),
|
|
1789
|
+
}, previousName);
|
|
1790
|
+
}
|
|
756
1791
|
return lowerListOp(targetState, setterArgument, environment);
|
|
757
1792
|
}
|
|
1793
|
+
// An object setter writes each field; setP(prev => …) binds the parameter to the object.
|
|
1794
|
+
if (targetState.kind === 'record') {
|
|
1795
|
+
if (isFn(setterArgument)) {
|
|
1796
|
+
return lowerRecordSet(targetState, setterArgument.body, updaterEnvironment(targetState, setterArgument, environment), RECORD_LOWERING);
|
|
1797
|
+
}
|
|
1798
|
+
return lowerRecordSet(targetState, setterArgument, environment, RECORD_LOWERING);
|
|
1799
|
+
}
|
|
758
1800
|
// A scalar setter takes either an updater function or the new value itself.
|
|
759
1801
|
if (setterArgument &&
|
|
760
1802
|
(setterArgument.type === 'ArrowFunctionExpression' ||
|
|
761
1803
|
setterArgument.type === 'FunctionExpression')) {
|
|
762
|
-
// setState(prev => expr):
|
|
763
|
-
const previousParameter = setterArgument.params[0]?.name;
|
|
764
|
-
const locals = new Map(environment.locals);
|
|
765
|
-
if (previousParameter) {
|
|
766
|
-
locals.set(previousParameter, {
|
|
767
|
-
slotKind: targetState.slotKind,
|
|
768
|
-
isBoolean: targetState.isBoolean,
|
|
769
|
-
...(targetState.widened === 'number' ? { isLiteral: true } : {}),
|
|
770
|
-
source: { kind: 'state', state: targetState, location: undefined },
|
|
771
|
-
expression: {
|
|
772
|
-
kind: 'state',
|
|
773
|
-
state: targetState,
|
|
774
|
-
type: stateType(targetState),
|
|
775
|
-
},
|
|
776
|
-
});
|
|
777
|
-
}
|
|
778
|
-
if (setterArgument.body.type === 'BlockStatement') {
|
|
779
|
-
throw new Error('AOT: updater function must be a single expression (for now)');
|
|
780
|
-
}
|
|
1804
|
+
// setState(prev => expr): the param reads the current value, and the result is assigned.
|
|
781
1805
|
return [
|
|
782
|
-
lowerScalarSet(targetState, setterArgument.body,
|
|
783
|
-
...environment,
|
|
784
|
-
locals,
|
|
785
|
-
}),
|
|
1806
|
+
lowerScalarSet(targetState, setterArgument.body, updaterEnvironment(targetState, setterArgument, environment)),
|
|
786
1807
|
];
|
|
787
1808
|
}
|
|
788
1809
|
return [lowerScalarSet(targetState, setterArgument, environment)];
|
|
@@ -793,10 +1814,10 @@ const lowerHandlerExpression = withLoc(lowerHandlerExprImpl);
|
|
|
793
1814
|
* Lowers a list of handler statements to the IR. This one-statement lowering runs event handlers, effect bodies
|
|
794
1815
|
* (useEffect), timer callbacks, and inlined helper calls. Supports: `const x = expr` (a local, visible to later
|
|
795
1816
|
* statements), `if (cond) {...} else {...}`, state setters (list setters included), ref writes, timers,
|
|
796
|
-
* updateVector() and Animated.*(...).start()
|
|
797
|
-
* and `usedReturn` (an early `return` was lowered, so the body
|
|
798
|
-
* function of its own). `context.
|
|
799
|
-
*
|
|
1817
|
+
* updateVector() and Animated.*(...).start(), `switch` (as an if/else chain) and `return`. `context` accumulates
|
|
1818
|
+
* `stateChanged` (→ a trailing update) and `usedReturn` (an early `return` was lowered, so the body or helper is a
|
|
1819
|
+
* block it leaves, or an effect's function of its own). `context.bodyList` and `context.helperList` mark the
|
|
1820
|
+
* statements whose tail `return` needs no jump.
|
|
800
1821
|
*
|
|
801
1822
|
* @param statements The statements.
|
|
802
1823
|
* @param environment The expression environment.
|
|
@@ -805,19 +1826,89 @@ const lowerHandlerExpression = withLoc(lowerHandlerExprImpl);
|
|
|
805
1826
|
*
|
|
806
1827
|
* @returns The lowered statements.
|
|
807
1828
|
*/
|
|
808
|
-
export function lowerStmts(statements,
|
|
1829
|
+
export function lowerStmts(statements, bodyEnvironment, state, context) {
|
|
1830
|
+
let environment = bodyEnvironment.outsideRender
|
|
1831
|
+
? bodyEnvironment
|
|
1832
|
+
: { ...bodyEnvironment, outsideRender: true };
|
|
809
1833
|
const lowered = [];
|
|
810
|
-
// What each statement lowers to is marked with where it is, once the next one starts
|
|
1834
|
+
// What each statement lowers to is marked with where it is, once the next one starts, after the values a helper
|
|
1835
|
+
// loops for that it reads.
|
|
811
1836
|
let from = 0;
|
|
812
1837
|
let location;
|
|
813
|
-
|
|
1838
|
+
let before;
|
|
1839
|
+
const settle = () => {
|
|
1840
|
+
if (before?.statements.length)
|
|
1841
|
+
lowered.splice(from, 0, ...before.statements);
|
|
814
1842
|
markLoc(lowered, from, location);
|
|
1843
|
+
};
|
|
1844
|
+
for (let statementIndex = 0; statementIndex < statements.length; statementIndex++) {
|
|
1845
|
+
settle();
|
|
815
1846
|
const statement = statements[statementIndex];
|
|
816
1847
|
from = lowered.length;
|
|
817
1848
|
location = startOf(statement);
|
|
1849
|
+
before = { statements: [], state, output: context.output };
|
|
1850
|
+
environment = { ...environment, before };
|
|
818
1851
|
// `const x = …` declares a local that the statements after it can read.
|
|
819
1852
|
if (statement.type === 'VariableDeclaration') {
|
|
820
|
-
|
|
1853
|
+
// An object's declaration expands into a local per field, put back in the queue.
|
|
1854
|
+
const queue = [
|
|
1855
|
+
...statement.declarations,
|
|
1856
|
+
];
|
|
1857
|
+
// Each initializer's looping values go just before it, as a later one may read an earlier local.
|
|
1858
|
+
const sink = before;
|
|
1859
|
+
let declaratorFrom = lowered.length;
|
|
1860
|
+
const nextDeclarator = () => {
|
|
1861
|
+
lowered.splice(declaratorFrom, 0, ...sink.statements);
|
|
1862
|
+
sink.statements = [];
|
|
1863
|
+
declaratorFrom = lowered.length;
|
|
1864
|
+
};
|
|
1865
|
+
while (queue.length) {
|
|
1866
|
+
nextDeclarator();
|
|
1867
|
+
const entry = queue.shift();
|
|
1868
|
+
if (!('type' in entry)) {
|
|
1869
|
+
const locals = new Map(environment.locals);
|
|
1870
|
+
locals.delete(entry.name);
|
|
1871
|
+
environment = {
|
|
1872
|
+
...environment,
|
|
1873
|
+
locals,
|
|
1874
|
+
constants: {
|
|
1875
|
+
...environment.constants,
|
|
1876
|
+
[entry.name]: boundObjectOf(entry, environment.locals),
|
|
1877
|
+
},
|
|
1878
|
+
};
|
|
1879
|
+
continue;
|
|
1880
|
+
}
|
|
1881
|
+
const declarator = entry;
|
|
1882
|
+
// A native method's record, or scrollTo's: its values kept in locals, then declared as an object of them,
|
|
1883
|
+
// or a field.
|
|
1884
|
+
const recordRoot = recordRootOf(declarator.init, environment);
|
|
1885
|
+
if (recordRoot) {
|
|
1886
|
+
const kept = recordRoot.keep(environment);
|
|
1887
|
+
lowered.push(kept.statement);
|
|
1888
|
+
environment = kept.environment;
|
|
1889
|
+
queue.unshift({
|
|
1890
|
+
...declarator,
|
|
1891
|
+
init: recordRoot.replaced({
|
|
1892
|
+
type: 'Identifier',
|
|
1893
|
+
name: kept.name,
|
|
1894
|
+
}),
|
|
1895
|
+
});
|
|
1896
|
+
continue;
|
|
1897
|
+
}
|
|
1898
|
+
const expanded = expandObjectDeclarator(declarator, environment);
|
|
1899
|
+
if (expanded) {
|
|
1900
|
+
if (statement.kind !== 'const') {
|
|
1901
|
+
throw aotError('AOT: an object in a handler must be a `const`', 'build a new object instead of changing this one, and declare it with const.');
|
|
1902
|
+
}
|
|
1903
|
+
queue.unshift(...expanded.entries);
|
|
1904
|
+
if (expanded.locals.size) {
|
|
1905
|
+
environment = {
|
|
1906
|
+
...environment,
|
|
1907
|
+
locals: new Map([...environment.locals, ...expanded.locals]),
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
continue;
|
|
1911
|
+
}
|
|
821
1912
|
if (declarator.id.type !== 'Identifier') {
|
|
822
1913
|
throw new Error('AOT: destructuring a handler local is not supported');
|
|
823
1914
|
}
|
|
@@ -835,11 +1926,28 @@ export function lowerStmts(statements, environment, state, context) {
|
|
|
835
1926
|
};
|
|
836
1927
|
continue;
|
|
837
1928
|
}
|
|
838
|
-
//
|
|
1929
|
+
// `const parts = text.split(',')` fills a list of the handler's own, read as `parts[i]` and `parts.length`.
|
|
1930
|
+
const split = handlerSplitList(declarator.id.name, declarator.init, statement.kind, environment);
|
|
1931
|
+
if (split) {
|
|
1932
|
+
lowered.push(...split.statements);
|
|
1933
|
+
const locals = new Map(environment.locals);
|
|
1934
|
+
locals.delete(declarator.id.name);
|
|
1935
|
+
environment = {
|
|
1936
|
+
...environment,
|
|
1937
|
+
locals,
|
|
1938
|
+
state: new Map(environment.state).set(declarator.id.name, split.list),
|
|
1939
|
+
};
|
|
1940
|
+
continue;
|
|
1941
|
+
}
|
|
1942
|
+
// A dep-driven effect's cleanup outlives the call, so the body's locals become slots. A `let`, and a local
|
|
1943
|
+
// that hides an outer one, has a name of its own, so the two keep apart, string buffers too.
|
|
839
1944
|
const isHoisted = Boolean(context.hoist && statements === context.bodyList);
|
|
1945
|
+
const isLet = statement.kind !== 'const';
|
|
840
1946
|
const localName = isHoisted
|
|
841
1947
|
? `${context.hoist.prefix}${declarator.id.name}`
|
|
842
|
-
:
|
|
1948
|
+
: isLet || environment.locals.has(declarator.id.name)
|
|
1949
|
+
? `local_${declarator.id.name}@${declarator.start ?? 0}`
|
|
1950
|
+
: `local_${declarator.id.name}`;
|
|
843
1951
|
// `const id = setInterval/setTimeout(…)` is an int timer-id local, so a later clearInterval(id) resolves.
|
|
844
1952
|
if (declarator.init.type === 'CallExpression' &&
|
|
845
1953
|
declarator.init.callee.type === 'Identifier' &&
|
|
@@ -867,12 +1975,25 @@ export function lowerStmts(statements, environment, state, context) {
|
|
|
867
1975
|
};
|
|
868
1976
|
continue;
|
|
869
1977
|
}
|
|
870
|
-
// Any other initializer must lower to a number, a boolean or a string.
|
|
871
|
-
const
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
1978
|
+
// Any other initializer must lower to a number, a boolean or a string. A built string is text.
|
|
1979
|
+
const text = buildsText(declarator.init, environment)
|
|
1980
|
+
? lowerText(declarator.init, environment)
|
|
1981
|
+
: undefined;
|
|
1982
|
+
const initial = text
|
|
1983
|
+
? {
|
|
1984
|
+
source: undefined,
|
|
1985
|
+
expression: { kind: 'string', value: '', type: STRING },
|
|
875
1986
|
}
|
|
1987
|
+
: lowerSource(declarator.init, environment);
|
|
1988
|
+
const { source: initialSource, expression: initialExpression } = initial;
|
|
1989
|
+
const localId = declarator.id.name;
|
|
1990
|
+
const shape = shapeOf(initialExpression);
|
|
1991
|
+
if (shape === 'string') {
|
|
1992
|
+
whenTyped(() => {
|
|
1993
|
+
if (initialExpression.kind === 'string') {
|
|
1994
|
+
checkConstantFits({ parts: [{ kind: 'literal', text: initialExpression.value }] }, `local "${localId}"`);
|
|
1995
|
+
}
|
|
1996
|
+
});
|
|
876
1997
|
// Copy into a buffer of its own; aliasing a state slot would hide a self-read like `setLabel(t + '!')`.
|
|
877
1998
|
if (isHoisted) {
|
|
878
1999
|
context.hoist.declarations.push({
|
|
@@ -882,50 +2003,130 @@ export function lowerStmts(statements, environment, state, context) {
|
|
|
882
2003
|
});
|
|
883
2004
|
}
|
|
884
2005
|
}
|
|
885
|
-
else {
|
|
886
|
-
const
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
2006
|
+
else if (shape !== 'number' && shape !== 'bool') {
|
|
2007
|
+
throw aotError('AOT: a handler local must hold a number, a boolean or a string', 'bind the value itself — e.g. `const id = item.id` — rather than a list item or a node ref.');
|
|
2008
|
+
}
|
|
2009
|
+
// A whole-number `let` set to a fraction or a timestamp later holds one from the start. Later statements
|
|
2010
|
+
// read the name as the local; a `let` is read from where it is kept, whatever set it last.
|
|
2011
|
+
const letKey = `let@${declarator.id.name}@${declarator.start ?? 0}`;
|
|
2012
|
+
const widthOf = () => isLet && initialExpression.type.kind === 'int'
|
|
2013
|
+
? environment.wide.get(letKey)
|
|
2014
|
+
: undefined;
|
|
2015
|
+
const bare = !isLet && initialSource
|
|
2016
|
+
? bareLocalOf({
|
|
2017
|
+
source: initialSource,
|
|
2018
|
+
expression: initialExpression,
|
|
2019
|
+
})
|
|
2020
|
+
: null;
|
|
2021
|
+
const local = bare
|
|
2022
|
+
? copyLocal(bare, { name: localName, source: initialSource })
|
|
2023
|
+
: holdLater(isLet
|
|
2024
|
+
? {
|
|
893
2025
|
name: localName,
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
2026
|
+
assignable: letKey,
|
|
2027
|
+
declared: initialSource,
|
|
2028
|
+
}
|
|
2029
|
+
: { name: localName, source: initialSource }, shape, () => {
|
|
2030
|
+
const width = widthOf();
|
|
2031
|
+
const held = width
|
|
2032
|
+
? width === 'float'
|
|
2033
|
+
? { slotKind: 'float' }
|
|
2034
|
+
: {
|
|
2035
|
+
slotKind: 'i64',
|
|
2036
|
+
...(width === 'number' ? { isLiteral: true } : {}),
|
|
2037
|
+
}
|
|
2038
|
+
: slotValueOf(initialExpression);
|
|
2039
|
+
return isLet
|
|
2040
|
+
? {
|
|
2041
|
+
slotKind: held.slotKind,
|
|
2042
|
+
...(held.isBoolean ? { isBoolean: true } : {}),
|
|
2043
|
+
...(held.isLiteral ? { isLiteral: true } : {}),
|
|
2044
|
+
...(held.wide ? { wide: true } : {}),
|
|
2045
|
+
}
|
|
2046
|
+
: held;
|
|
2047
|
+
});
|
|
2048
|
+
if (isHoisted && shape !== 'string') {
|
|
2049
|
+
const declaration = { kind: 'local', name: localName };
|
|
2050
|
+
context.hoist.declarations.push(declaration);
|
|
2051
|
+
setLater(declaration, ['slotKind'], () => ({
|
|
2052
|
+
slotKind: local.slotKind,
|
|
2053
|
+
}));
|
|
897
2054
|
}
|
|
898
|
-
|
|
2055
|
+
const declare = {
|
|
899
2056
|
kind: 'declareLocal',
|
|
900
2057
|
name: localName,
|
|
901
2058
|
initializer: initialExpression,
|
|
2059
|
+
...(text ? { text } : {}),
|
|
902
2060
|
isHoisted,
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
2061
|
+
};
|
|
2062
|
+
if (isLet && shape === 'number') {
|
|
2063
|
+
setLater(declare, ['widenedTo'], () => {
|
|
2064
|
+
const width = widthOf();
|
|
2065
|
+
const widenedTo = !width
|
|
2066
|
+
? undefined
|
|
2067
|
+
: width === 'float'
|
|
2068
|
+
? 'float'
|
|
2069
|
+
: 'int64';
|
|
2070
|
+
return { widenedTo };
|
|
2071
|
+
});
|
|
2072
|
+
}
|
|
2073
|
+
lowered.push(declare);
|
|
906
2074
|
environment = {
|
|
907
2075
|
...environment,
|
|
908
|
-
locals: new Map(environment.locals).set(declarator.id.name,
|
|
909
|
-
...slotValueOf(initialExpression),
|
|
910
|
-
name: localName,
|
|
911
|
-
source: initialSource,
|
|
912
|
-
}),
|
|
2076
|
+
locals: new Map(environment.locals).set(declarator.id.name, local),
|
|
913
2077
|
};
|
|
914
2078
|
}
|
|
2079
|
+
nextDeclarator();
|
|
915
2080
|
continue;
|
|
916
2081
|
}
|
|
917
|
-
//
|
|
918
|
-
if (statement.type === '
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
2082
|
+
// `switch` runs as an if/else chain; a bare block lowers in place, its locals its own.
|
|
2083
|
+
if (statement.type === 'SwitchStatement') {
|
|
2084
|
+
lowered.push(...lowerStmts([switchAsIf(statement)], environment, state, context));
|
|
2085
|
+
continue;
|
|
2086
|
+
}
|
|
2087
|
+
if (statement.type === 'BlockStatement') {
|
|
2088
|
+
lowered.push(...lowerStmts(statement.body, environment, state, context));
|
|
2089
|
+
continue;
|
|
2090
|
+
}
|
|
2091
|
+
// `for` counts to a bound the compiler works out, and `for…of` visits a list's rows.
|
|
2092
|
+
if (statement.type === 'ForStatement') {
|
|
2093
|
+
lowered.push(...lowerFor(statement, environment, state, context, lowerStmts));
|
|
2094
|
+
continue;
|
|
2095
|
+
}
|
|
2096
|
+
if (statement.type === 'ForOfStatement') {
|
|
2097
|
+
lowered.push(...lowerForOf(statement, environment, state, context, lowerStmts));
|
|
2098
|
+
continue;
|
|
2099
|
+
}
|
|
2100
|
+
if (statement.type === 'BreakStatement' ||
|
|
2101
|
+
statement.type === 'ContinueStatement') {
|
|
2102
|
+
const word = statement.type === 'BreakStatement' ? 'break' : 'continue';
|
|
2103
|
+
if (statement.label) {
|
|
2104
|
+
throw located(aotError(`AOT: a labeled \`${word}\` is not supported`, 'leave the inner loop with a plain break and test a let after it, or move the loops into a helper ' +
|
|
2105
|
+
'and return from it.'), statement);
|
|
925
2106
|
}
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
2107
|
+
if (!context.loops?.length) {
|
|
2108
|
+
throw located(aotError(`AOT: a \`${word}\` must be inside a loop`), statement);
|
|
2109
|
+
}
|
|
2110
|
+
lowered.push({ kind: word });
|
|
2111
|
+
continue;
|
|
2112
|
+
}
|
|
2113
|
+
if (statement.type === 'LabeledStatement') {
|
|
2114
|
+
throw located(aotError('AOT: a labeled statement is not supported', 'leave the inner loop with a plain break and test a let after it, or move the loops into a helper ' +
|
|
2115
|
+
'and return from it.'), statement);
|
|
2116
|
+
}
|
|
2117
|
+
if (statement.type === 'WhileStatement' ||
|
|
2118
|
+
statement.type === 'DoWhileStatement' ||
|
|
2119
|
+
statement.type === 'ForInStatement') {
|
|
2120
|
+
throw located(aotError(`AOT: a ${statement.type === 'ForInStatement' ? 'for…in' : 'while'} loop is not supported`, "a loop needs a bound the compiler can count. Write a for loop from a constant or a list's length to " +
|
|
2121
|
+
'another, or for (const item of items), and break out of it early.'), statement);
|
|
2122
|
+
}
|
|
2123
|
+
// An effect body's tail `return` is the cleanup, dropped on mount and armed if dep-driven; any other `return`
|
|
2124
|
+
// leaves the body or helper, the value it gives unused.
|
|
2125
|
+
if (statement.type === 'ReturnStatement') {
|
|
2126
|
+
const argument = statement.argument;
|
|
2127
|
+
const isLast = statementIndex === statements.length - 1;
|
|
2128
|
+
const isBodyTail = isLast && statements === context.bodyList;
|
|
2129
|
+
if (context.dependencyDriven && isFn(argument) && !isBodyTail) {
|
|
929
2130
|
const error = aotError('AOT: a useEffect cleanup must be the last statement of the effect body', 'a cleanup returned from inside an `if` would be dropped. Return `undefined` from the ' +
|
|
930
2131
|
'guard and put the single `return () => …` at the end of the body.');
|
|
931
2132
|
if (statement.loc) {
|
|
@@ -933,11 +2134,22 @@ export function lowerStmts(statements, environment, state, context) {
|
|
|
933
2134
|
}
|
|
934
2135
|
throw error;
|
|
935
2136
|
}
|
|
936
|
-
if (
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
2137
|
+
if (isBodyTail && context.cleanup && isFn(argument)) {
|
|
2138
|
+
context.cleanup.emit(argument, environment);
|
|
2139
|
+
lowered.push({ kind: 'armCleanup', flag: context.cleanup.armed });
|
|
2140
|
+
continue;
|
|
2141
|
+
}
|
|
2142
|
+
// A body that works out a value keeps what it returns; elsewhere `return setX(…)` still sets it.
|
|
2143
|
+
if (context.returnsValue && argument) {
|
|
2144
|
+
lowered.push(...context.returnsValue(argument, environment));
|
|
2145
|
+
}
|
|
2146
|
+
else if (argument?.type === 'CallExpression' ||
|
|
2147
|
+
argument?.type === 'AssignmentExpression' ||
|
|
2148
|
+
argument?.type === 'UpdateExpression') {
|
|
2149
|
+
lowered.push(...lowerHandlerExpression(argument, environment, state, context));
|
|
2150
|
+
}
|
|
2151
|
+
if (isLast &&
|
|
2152
|
+
(statements === context.bodyList || statements === context.helperList)) {
|
|
941
2153
|
continue;
|
|
942
2154
|
}
|
|
943
2155
|
context.usedReturn = true;
|
|
@@ -947,25 +2159,94 @@ export function lowerStmts(statements, environment, state, context) {
|
|
|
947
2159
|
// `if (…) { … } else { … }` lowers each branch in order: the test, then the consequent, then the alternate.
|
|
948
2160
|
if (statement.type === 'IfStatement') {
|
|
949
2161
|
const test = lowerExprWide(statement.test, environment);
|
|
950
|
-
|
|
2162
|
+
// A test on a tagged object's tag narrows the fields each branch can read.
|
|
2163
|
+
const narrowing = narrowOn(statement.test, environment);
|
|
2164
|
+
const consequentStatements = statementsOf(statement.consequent);
|
|
2165
|
+
const alternateStatements = statement.alternate
|
|
2166
|
+
? statementsOf(statement.alternate)
|
|
2167
|
+
: [];
|
|
2168
|
+
const consequent = lowerStmts(consequentStatements, narrowed(environment, narrowing.whenTrue), state, context);
|
|
951
2169
|
const alternate = statement.alternate
|
|
952
|
-
? lowerStmts(
|
|
2170
|
+
? lowerStmts(alternateStatements, narrowed(environment, narrowing.whenFalse), state, context)
|
|
953
2171
|
: null;
|
|
954
2172
|
lowered.push({ kind: 'if', test, consequent, alternate });
|
|
2173
|
+
// The statements after a branch that returns, breaks or continues read what the other branch's test leaves.
|
|
2174
|
+
const inLoop = Boolean(context.loops?.length);
|
|
2175
|
+
if (exits(consequentStatements, inLoop)) {
|
|
2176
|
+
environment = narrowed(environment, narrowing.whenFalse);
|
|
2177
|
+
}
|
|
2178
|
+
else if (exits(alternateStatements, inLoop)) {
|
|
2179
|
+
environment = narrowed(environment, narrowing.whenTrue);
|
|
2180
|
+
}
|
|
955
2181
|
continue;
|
|
956
2182
|
}
|
|
957
2183
|
// Anything else must be an expression statement: a setter call, a ref write, a timer, and so on.
|
|
958
2184
|
if (statement.type !== 'ExpressionStatement') {
|
|
959
|
-
throw aotError(`AOT: unsupported statement "${statement.type}" in event handler`, 'a handler supports only `const
|
|
960
|
-
'expression statements (setters / ref writes / updateVector / Animated…start).
|
|
961
|
-
'
|
|
962
|
-
|
|
2185
|
+
throw aotError(`AOT: unsupported statement "${statement.type}" in event handler`, 'a handler supports only `const` and `let` locals, `if`, `switch`, `for`, `for…of`, `return`, and ' +
|
|
2186
|
+
'expression statements (setters / ref and local writes / updateVector / Animated…start). ' +
|
|
2187
|
+
'try/catch is not lowered.');
|
|
2188
|
+
}
|
|
2189
|
+
// A native method's record given straight to a call that takes one, setFix(Gps.fix()), or a field of it,
|
|
2190
|
+
// setLat(Gps.fix().lat): kept first, then passed by its name.
|
|
2191
|
+
let expression = statement.expression;
|
|
2192
|
+
const keptRoot = (argument, index) => {
|
|
2193
|
+
const recordRoot = recordRootOf(argument, environment);
|
|
2194
|
+
return recordRoot &&
|
|
2195
|
+
(recordRoot.call !== argument ||
|
|
2196
|
+
takesRecord(expression, index, environment, state))
|
|
2197
|
+
? recordRoot
|
|
2198
|
+
: null;
|
|
2199
|
+
};
|
|
2200
|
+
if (expression.type === 'CallExpression' &&
|
|
2201
|
+
expression.arguments.some(keptRoot)) {
|
|
2202
|
+
const callArguments = expression.arguments.map((argument, index) => {
|
|
2203
|
+
const recordRoot = keptRoot(argument, index);
|
|
2204
|
+
if (!recordRoot)
|
|
2205
|
+
return argument;
|
|
2206
|
+
const kept = recordRoot.keep(environment);
|
|
2207
|
+
lowered.push(kept.statement);
|
|
2208
|
+
environment = kept.environment;
|
|
2209
|
+
return recordRoot.replaced({
|
|
2210
|
+
type: 'Identifier',
|
|
2211
|
+
name: kept.name,
|
|
2212
|
+
});
|
|
2213
|
+
});
|
|
2214
|
+
expression = { ...expression, arguments: callArguments };
|
|
963
2215
|
}
|
|
964
|
-
lowered.push(...lowerHandlerExpression(
|
|
2216
|
+
lowered.push(...lowerHandlerExpression(expression, environment, state, context));
|
|
965
2217
|
}
|
|
966
|
-
|
|
2218
|
+
settle();
|
|
967
2219
|
return lowered;
|
|
968
2220
|
}
|
|
2221
|
+
/**
|
|
2222
|
+
* An error located at a statement.
|
|
2223
|
+
*
|
|
2224
|
+
* @param error The error.
|
|
2225
|
+
* @param statement The statement.
|
|
2226
|
+
*
|
|
2227
|
+
* @returns The error.
|
|
2228
|
+
*/
|
|
2229
|
+
function located(error, statement) {
|
|
2230
|
+
if (statement.loc)
|
|
2231
|
+
error.aotLoc = statement.loc.start;
|
|
2232
|
+
return error;
|
|
2233
|
+
}
|
|
2234
|
+
/**
|
|
2235
|
+
* Lowers a body of its own: a handler's, a timer's, an animation completion's or an effect cleanup's. A `return` in
|
|
2236
|
+
* it leaves the block it becomes.
|
|
2237
|
+
*
|
|
2238
|
+
* @param statements The body's statements.
|
|
2239
|
+
* @param environment The expression environment.
|
|
2240
|
+
* @param state The component's state table.
|
|
2241
|
+
* @param context The statement compiler's context, new for this body.
|
|
2242
|
+
*
|
|
2243
|
+
* @returns The lowered statements.
|
|
2244
|
+
*/
|
|
2245
|
+
export function lowerBody(statements, environment, state, context) {
|
|
2246
|
+
context.bodyList = statements;
|
|
2247
|
+
const lowered = lowerStmts(statements, environment, state, context);
|
|
2248
|
+
return keepingStates(context.usedReturn ? [{ kind: 'block', body: lowered }] : lowered, context.output);
|
|
2249
|
+
}
|
|
969
2250
|
/**
|
|
970
2251
|
* Where a statement starts. An expression body made into a statement has no location of its own.
|
|
971
2252
|
*
|
|
@@ -996,9 +2277,9 @@ function markLoc(lowered, from, location) {
|
|
|
996
2277
|
* Lowers a useEffect (App or child). Two shapes:
|
|
997
2278
|
* - `useEffect(fn, [])` — MOUNT-ONCE: body runs after the initial the update (in the build).
|
|
998
2279
|
* - `useEffect(fn, [dep…])` — DEP-DRIVEN: body becomes a function of its own; runs once at mount,
|
|
999
|
-
* then again
|
|
1000
|
-
*
|
|
1001
|
-
*
|
|
2280
|
+
* then again after an update whenever a SCALAR dep changes (compared against a stored prev). It runs after
|
|
2281
|
+
* the update pass, and one that set state asks for another pass, which shows it; an effect that keeps changing
|
|
2282
|
+
* its deps stops the app at the runtime's pass limit, where React reports an update loop.
|
|
1002
2283
|
* A dep-driven `return () => …` becomes `effect_N_cleanup()`, run at the top of the next re-run.
|
|
1003
2284
|
*
|
|
1004
2285
|
* @param effect The effect.
|
|
@@ -1006,7 +2287,8 @@ function markLoc(lowered, from, location) {
|
|
|
1006
2287
|
* @param state The component's state table.
|
|
1007
2288
|
* @param output Everything emitted so far; the effect is added to it.
|
|
1008
2289
|
*/
|
|
1009
|
-
export function lowerEffect(effect,
|
|
2290
|
+
export function lowerEffect(effect, componentEnvironment, state, output) {
|
|
2291
|
+
const environment = withAlertBase(componentEnvironment);
|
|
1010
2292
|
// An expression body is a single statement.
|
|
1011
2293
|
const body = effect.functionNode.body;
|
|
1012
2294
|
const statements = body.type === 'BlockStatement'
|
|
@@ -1019,10 +2301,9 @@ export function lowerEffect(effect, environment, state, output) {
|
|
|
1019
2301
|
const context = {
|
|
1020
2302
|
stateChanged: false,
|
|
1021
2303
|
output,
|
|
1022
|
-
allowReturn: true,
|
|
1023
2304
|
bodyList: statements,
|
|
1024
2305
|
};
|
|
1025
|
-
const lowered = lowerStmts(statements, environment, state, context);
|
|
2306
|
+
const lowered = keepingStates(lowerStmts(statements, environment, state, context), output);
|
|
1026
2307
|
if (!context.usedReturn) {
|
|
1027
2308
|
output.mountEffects.push({
|
|
1028
2309
|
kind: 'inline',
|
|
@@ -1049,8 +2330,12 @@ export function lowerEffect(effect, environment, state, output) {
|
|
|
1049
2330
|
if (!dependencyNode) {
|
|
1050
2331
|
throw aotError('AOT: a useEffect dependency must be an expression');
|
|
1051
2332
|
}
|
|
2333
|
+
if (objectTreeOf(dependencyNode, environment)) {
|
|
2334
|
+
throw aotError('AOT: a useEffect dependency on a whole object', 'depend on the fields the effect reads: [p.x, p.y].');
|
|
2335
|
+
}
|
|
1052
2336
|
const dependencyExpression = lowerExprWide(dependencyNode, environment);
|
|
1053
|
-
|
|
2337
|
+
const dependencyShape = shapeOf(dependencyExpression);
|
|
2338
|
+
if (dependencyShape === 'struct' || dependencyShape === 'node') {
|
|
1054
2339
|
throw aotError('AOT: useEffect dependencies must be scalar (number / bool / string)', 'depend on scalar state values; object/array dependencies are not yet supported.');
|
|
1055
2340
|
}
|
|
1056
2341
|
return dependencyExpression;
|
|
@@ -1068,7 +2353,6 @@ export function lowerEffect(effect, environment, state, output) {
|
|
|
1068
2353
|
const context = {
|
|
1069
2354
|
stateChanged: false,
|
|
1070
2355
|
output,
|
|
1071
|
-
allowReturn: true,
|
|
1072
2356
|
bodyList: statements,
|
|
1073
2357
|
dependencyDriven: true,
|
|
1074
2358
|
};
|
|
@@ -1089,7 +2373,7 @@ export function lowerEffect(effect, environment, state, output) {
|
|
|
1089
2373
|
stateChanged: false,
|
|
1090
2374
|
output,
|
|
1091
2375
|
};
|
|
1092
|
-
dependencyEffect.cleanup =
|
|
2376
|
+
dependencyEffect.cleanup = lowerBody(cleanupStatements, cleanupEnvironment, state, cleanupContext);
|
|
1093
2377
|
output.effectFunctions.push({
|
|
1094
2378
|
kind: 'cleanup',
|
|
1095
2379
|
effect: dependencyEffect,
|
|
@@ -1099,13 +2383,181 @@ export function lowerEffect(effect, environment, state, output) {
|
|
|
1099
2383
|
output.effectDeclarations.push({ kind: 'armed', effect: dependencyEffect });
|
|
1100
2384
|
}
|
|
1101
2385
|
// The effect function runs the last run's cleanup first, if that run armed it, then the body.
|
|
1102
|
-
dependencyEffect.body = lowerStmts(statements, environment, state, context);
|
|
2386
|
+
dependencyEffect.body = keepingStates(lowerStmts(statements, environment, state, context), output);
|
|
1103
2387
|
output.effectFunctions.push({ kind: 'effect', effect: dependencyEffect });
|
|
1104
2388
|
// A copy of each dep, taken at mount; the update re-runs the effect when one no longer matches its copy.
|
|
1105
2389
|
output.effectDeclarations.push({ kind: 'deps', effect: dependencyEffect });
|
|
1106
2390
|
output.mountEffects.push({ kind: 'depEffect', effect: dependencyEffect });
|
|
1107
2391
|
output.dependencyEffects.push(dependencyEffect);
|
|
1108
2392
|
}
|
|
2393
|
+
/**
|
|
2394
|
+
* The call that returns a record at the root of an expression, a native method's or scrollTo's: the call itself,
|
|
2395
|
+
* or the record a field read starts from, `Gps.fix().place.lat`.
|
|
2396
|
+
*
|
|
2397
|
+
* @param node The expression.
|
|
2398
|
+
* @param environment The expression environment.
|
|
2399
|
+
*
|
|
2400
|
+
* @returns The call, or null.
|
|
2401
|
+
*/
|
|
2402
|
+
function recordRootOf(node, environment) {
|
|
2403
|
+
if (node?.type === 'MemberExpression') {
|
|
2404
|
+
const root = recordRootOf(node.object, environment);
|
|
2405
|
+
return (root && {
|
|
2406
|
+
...root,
|
|
2407
|
+
replaced: by => ({ ...node, object: root.replaced(by) }),
|
|
2408
|
+
});
|
|
2409
|
+
}
|
|
2410
|
+
if (isScrollToCall(node)) {
|
|
2411
|
+
const call = node;
|
|
2412
|
+
return {
|
|
2413
|
+
call,
|
|
2414
|
+
keep: inEnvironment => keepScrollPosition(call, inEnvironment),
|
|
2415
|
+
replaced: by => by,
|
|
2416
|
+
};
|
|
2417
|
+
}
|
|
2418
|
+
const callee = nativeRecordCallOf(node, environment);
|
|
2419
|
+
return (callee && {
|
|
2420
|
+
call: node,
|
|
2421
|
+
keep: inEnvironment => keepNativeRecord(node, callee, inEnvironment),
|
|
2422
|
+
replaced: by => by,
|
|
2423
|
+
});
|
|
2424
|
+
}
|
|
2425
|
+
/**
|
|
2426
|
+
* Whether a call takes a record as one of its arguments: an object state's setter, or a native method's record
|
|
2427
|
+
* parameter.
|
|
2428
|
+
*
|
|
2429
|
+
* @param call The call.
|
|
2430
|
+
* @param index The argument's position.
|
|
2431
|
+
* @param environment The expression environment.
|
|
2432
|
+
* @param state The component's state table.
|
|
2433
|
+
*
|
|
2434
|
+
* @returns True when it does.
|
|
2435
|
+
*/
|
|
2436
|
+
function takesRecord(call, index, environment, state) {
|
|
2437
|
+
if (call.callee.type === 'Identifier' &&
|
|
2438
|
+
state.bySetter.get(call.callee.name)?.kind === 'record') {
|
|
2439
|
+
return true;
|
|
2440
|
+
}
|
|
2441
|
+
const callee = nativeCalleeOf(call, environment);
|
|
2442
|
+
const member = callee?.module.members.get(callee.method);
|
|
2443
|
+
return member?.kind === 'method' && typeof member.params[index] === 'object';
|
|
2444
|
+
}
|
|
2445
|
+
/**
|
|
2446
|
+
* Calls a native method that returns a record, keeping its values in locals, and binds the record to a name no JS
|
|
2447
|
+
* binding has, as an object of them.
|
|
2448
|
+
*
|
|
2449
|
+
* @param node The call.
|
|
2450
|
+
* @param callee Its module, method and record (see nativeRecordCallOf).
|
|
2451
|
+
* @param environment The expression environment.
|
|
2452
|
+
*
|
|
2453
|
+
* @returns The call, the name, and the environment that binds it.
|
|
2454
|
+
*/
|
|
2455
|
+
function keepNativeRecord(node, callee, environment) {
|
|
2456
|
+
const call = lowerNativeCall(node, callee, environment);
|
|
2457
|
+
const name = `#record${keptRecords++}`;
|
|
2458
|
+
const results = call.import.results.map((_, index) => `${name}_${index}`);
|
|
2459
|
+
const tree = recordTreeOf(callee.record, (index, type) => new RuntimeLeaf({ name: results[index], ...VALUE_SLOTS[type] }));
|
|
2460
|
+
return {
|
|
2461
|
+
statement: { kind: 'callNative', call, results },
|
|
2462
|
+
name,
|
|
2463
|
+
environment: {
|
|
2464
|
+
...environment,
|
|
2465
|
+
constants: { ...environment.constants, [name]: tree },
|
|
2466
|
+
},
|
|
2467
|
+
};
|
|
2468
|
+
}
|
|
2469
|
+
/**
|
|
2470
|
+
* Scrolls with scrollTo, keeping the position it returns in locals, and binds the position to a name no JS binding
|
|
2471
|
+
* has, as an object of them.
|
|
2472
|
+
*
|
|
2473
|
+
* @param node The call.
|
|
2474
|
+
* @param environment The expression environment.
|
|
2475
|
+
*
|
|
2476
|
+
* @returns The call, the name, and the environment that binds it.
|
|
2477
|
+
*/
|
|
2478
|
+
function keepScrollPosition(node, environment) {
|
|
2479
|
+
const name = `#record${keptRecords++}`;
|
|
2480
|
+
const results = SCROLL_POSITION_FIELDS.map(field => `${name}_${field}`);
|
|
2481
|
+
const position = Object.fromEntries(SCROLL_POSITION_FIELDS.map((field, index) => [
|
|
2482
|
+
field,
|
|
2483
|
+
new RuntimeLeaf({ name: results[index], slotKind: 'float' }),
|
|
2484
|
+
]));
|
|
2485
|
+
return {
|
|
2486
|
+
statement: lowerScrollTo(node, environment, results),
|
|
2487
|
+
name,
|
|
2488
|
+
environment: {
|
|
2489
|
+
...environment,
|
|
2490
|
+
constants: { ...environment.constants, [name]: position },
|
|
2491
|
+
},
|
|
2492
|
+
};
|
|
2493
|
+
}
|
|
2494
|
+
/**
|
|
2495
|
+
* Lowers a `useNativeEvent(Module, 'event', handler)` to a handler the runtime runs with the event's values. The
|
|
2496
|
+
* handler does nothing while its component isn't mounted: the conditions it is built under, read as it runs.
|
|
2497
|
+
*
|
|
2498
|
+
* @param call The call.
|
|
2499
|
+
* @param environment The component's expression environment.
|
|
2500
|
+
* @param state The component's state table.
|
|
2501
|
+
* @param output Everything emitted so far; the handler is added to it.
|
|
2502
|
+
*/
|
|
2503
|
+
export function lowerNativeEvent(call, componentEnvironment, state, output) {
|
|
2504
|
+
const environment = withAlertBase(componentEnvironment);
|
|
2505
|
+
const { event, values: declared, handler } = nativeEventOf(call, environment);
|
|
2506
|
+
const index = output.nativeEventHandlers.length;
|
|
2507
|
+
// Each value is a register the handler is entered with, read by a name no JS binding can have. A record's fields
|
|
2508
|
+
// are values of their own, and the record is bound as an object of them; destructuring one declares its fields.
|
|
2509
|
+
const values = event.params.map((_, position) => `#native${index}_${position}`);
|
|
2510
|
+
const locals = new Map(environment.locals);
|
|
2511
|
+
const constants = { ...environment.constants };
|
|
2512
|
+
const destructured = [];
|
|
2513
|
+
let first = 0;
|
|
2514
|
+
handler.params.forEach((parameter, position) => {
|
|
2515
|
+
const type = declared[position];
|
|
2516
|
+
const from = first;
|
|
2517
|
+
first += valueCount(type);
|
|
2518
|
+
if (typeof type === 'string') {
|
|
2519
|
+
locals.set(parameter.name, {
|
|
2520
|
+
name: values[from],
|
|
2521
|
+
...VALUE_SLOTS[type],
|
|
2522
|
+
});
|
|
2523
|
+
return;
|
|
2524
|
+
}
|
|
2525
|
+
const name = parameter.type === 'Identifier'
|
|
2526
|
+
? parameter.name
|
|
2527
|
+
: `#value${index}_${position}`;
|
|
2528
|
+
locals.delete(name);
|
|
2529
|
+
constants[name] = recordTreeOf(type, (leaf, leafType) => new RuntimeLeaf({ name: values[leaf], ...VALUE_SLOTS[leafType] }), from);
|
|
2530
|
+
if (parameter.type === 'ObjectPattern') {
|
|
2531
|
+
destructured.push({
|
|
2532
|
+
type: 'VariableDeclaration',
|
|
2533
|
+
kind: 'const',
|
|
2534
|
+
declarations: [
|
|
2535
|
+
{
|
|
2536
|
+
type: 'VariableDeclarator',
|
|
2537
|
+
id: parameter,
|
|
2538
|
+
init: { type: 'Identifier', name },
|
|
2539
|
+
},
|
|
2540
|
+
],
|
|
2541
|
+
});
|
|
2542
|
+
}
|
|
2543
|
+
});
|
|
2544
|
+
const body = handler.body;
|
|
2545
|
+
const statements = [
|
|
2546
|
+
...destructured,
|
|
2547
|
+
...(body.type === 'BlockStatement'
|
|
2548
|
+
? body.body
|
|
2549
|
+
: [{ type: 'ExpressionStatement', expression: body }]),
|
|
2550
|
+
];
|
|
2551
|
+
const context = { stateChanged: false, output };
|
|
2552
|
+
const lowered = lowerBody(statements, { ...environment, locals, constants }, state, context);
|
|
2553
|
+
output.nativeEventHandlers.push({
|
|
2554
|
+
name: `native_event_${index}`,
|
|
2555
|
+
event,
|
|
2556
|
+
values,
|
|
2557
|
+
mounted: environment.mounted ?? null,
|
|
2558
|
+
callback: { body: lowered, updatesState: context.stateChanged },
|
|
2559
|
+
});
|
|
2560
|
+
}
|
|
1109
2561
|
/**
|
|
1110
2562
|
* Lowers an event handler to a callback. Its first parameter is the event, whose touch fields read
|
|
1111
2563
|
* EREventData; a PanResponder callback's second is RN's gestureState (see lowerGestureField).
|
|
@@ -1131,7 +2583,7 @@ export function lowerHandler(functionNode, environment, state, output, pan = nul
|
|
|
1131
2583
|
const gestureParameter = pan && functionNode.params[1]?.type === 'Identifier'
|
|
1132
2584
|
? functionNode.params[1].name
|
|
1133
2585
|
: null;
|
|
1134
|
-
let handlerEnvironment = environment;
|
|
2586
|
+
let handlerEnvironment = withAlertBase(environment);
|
|
1135
2587
|
if (eventParameter) {
|
|
1136
2588
|
handlerEnvironment = { ...handlerEnvironment, event: eventParameter };
|
|
1137
2589
|
}
|
|
@@ -1145,7 +2597,7 @@ export function lowerHandler(functionNode, environment, state, output, pan = nul
|
|
|
1145
2597
|
// The body re-applies state-dependent props once at its end if it set state.
|
|
1146
2598
|
const context = { stateChanged: false, output };
|
|
1147
2599
|
return {
|
|
1148
|
-
body:
|
|
2600
|
+
body: lowerBody(statements, handlerEnvironment, state, context),
|
|
1149
2601
|
updatesState: context.stateChanged,
|
|
1150
2602
|
};
|
|
1151
2603
|
}
|
|
@@ -1163,7 +2615,8 @@ export function lowerHandler(functionNode, environment, state, output, pan = nul
|
|
|
1163
2615
|
*
|
|
1164
2616
|
* @returns The callback.
|
|
1165
2617
|
*/
|
|
1166
|
-
export function lowerValueHandler(functionNode,
|
|
2618
|
+
export function lowerValueHandler(functionNode, componentEnvironment, state, output, slotKind, isBoolean, valueExpression, secondValueExpression) {
|
|
2619
|
+
const environment = withAlertBase(componentEnvironment);
|
|
1167
2620
|
// A <Switch> hands its callback a boolean; carry that so `'on=' + v` prints true/false, not 1/0.
|
|
1168
2621
|
const valueParameter = functionNode.params[0]?.type === 'Identifier'
|
|
1169
2622
|
? functionNode.params[0].name
|
|
@@ -1190,7 +2643,7 @@ export function lowerValueHandler(functionNode, environment, state, output, slot
|
|
|
1190
2643
|
? body.body
|
|
1191
2644
|
: [{ type: 'ExpressionStatement', expression: body }];
|
|
1192
2645
|
return {
|
|
1193
|
-
body:
|
|
2646
|
+
body: lowerBody(statements, { ...environment, locals }, state, context),
|
|
1194
2647
|
updatesState: context.stateChanged,
|
|
1195
2648
|
};
|
|
1196
2649
|
}
|