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.
Files changed (140) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +3 -2
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +17 -47
  5. package/aot/compiler/alerts.mjs +604 -0
  6. package/aot/compiler/animations.mjs +299 -57
  7. package/aot/compiler/boot.mjs +27 -2
  8. package/aot/compiler/check.mjs +62 -10
  9. package/aot/compiler/collect.mjs +517 -137
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +276 -117
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/elements/button.mjs +182 -0
  14. package/aot/compiler/elements/image-background.mjs +76 -0
  15. package/aot/compiler/elements/image.mjs +2 -1
  16. package/aot/compiler/elements/props.mjs +47 -8
  17. package/aot/compiler/elements/rewrite.mjs +118 -0
  18. package/aot/compiler/elements/section-list.mjs +370 -0
  19. package/aot/compiler/expressions.mjs +1378 -97
  20. package/aot/compiler/handlers.mjs +1807 -354
  21. package/aot/compiler/helper-values.mjs +312 -0
  22. package/aot/compiler/ir/nodes.mjs +40 -1
  23. package/aot/compiler/ir/reads.mjs +206 -5
  24. package/aot/compiler/ir/text.mjs +5 -1
  25. package/aot/compiler/ir/types.mjs +12 -0
  26. package/aot/compiler/kept-states.mjs +177 -0
  27. package/aot/compiler/keyboard-dismiss.mjs +99 -0
  28. package/aot/compiler/keyboard.mjs +1 -1
  29. package/aot/compiler/list-items.mjs +226 -0
  30. package/aot/compiler/list-order.mjs +586 -0
  31. package/aot/compiler/list-split.mjs +259 -0
  32. package/aot/compiler/loops.mjs +582 -0
  33. package/aot/compiler/lower.mjs +203 -53
  34. package/aot/compiler/native-files.mjs +439 -0
  35. package/aot/compiler/native-header.mjs +335 -0
  36. package/aot/compiler/native-modules.mjs +1173 -0
  37. package/aot/compiler/nodes.mjs +45 -31
  38. package/aot/compiler/options.mjs +3 -2
  39. package/aot/compiler/out.mjs +18 -1
  40. package/aot/compiler/package/animations.mjs +133 -23
  41. package/aot/compiler/package/assemble.mjs +2 -4
  42. package/aot/compiler/package/bytecode.mjs +37 -8
  43. package/aot/compiler/package/checks.mjs +4 -0
  44. package/aot/compiler/package/codegen.mjs +906 -33
  45. package/aot/compiler/package/enums.mjs +10 -0
  46. package/aot/compiler/package/format.mjs +16 -3
  47. package/aot/compiler/package/lower.mjs +707 -176
  48. package/aot/compiler/package/string-caps.mjs +515 -0
  49. package/aot/compiler/package/tables.mjs +24 -0
  50. package/aot/compiler/package/writer.mjs +22 -0
  51. package/aot/compiler/parse.mjs +3 -1
  52. package/aot/compiler/record-shapes.mjs +246 -0
  53. package/aot/compiler/records.mjs +654 -0
  54. package/aot/compiler/reducers.mjs +272 -0
  55. package/aot/compiler/scroll-to.mjs +112 -0
  56. package/aot/compiler/static-eval.mjs +315 -7
  57. package/aot/compiler/style-text.mjs +20 -5
  58. package/aot/compiler/svg.mjs +13 -7
  59. package/aot/compiler/switch-cases.mjs +198 -0
  60. package/aot/compiler/tagged-records.mjs +450 -0
  61. package/aot/compiler/typing.mjs +307 -0
  62. package/aot/compiler/updaters.mjs +321 -0
  63. package/aot/compiler/window-dimensions.mjs +94 -0
  64. package/aot/compiler/worked-values.mjs +319 -0
  65. package/aot/demo-file.mjs +30 -0
  66. package/aot/style-map.mjs +94 -3
  67. package/assets/bake-font.mjs +187 -244
  68. package/assets/bake-image.mjs +47 -71
  69. package/assets/bake-svg.mjs +465 -533
  70. package/assets/build-builtin-font.mjs +14 -27
  71. package/assets/emit-c.mjs +124 -204
  72. package/assets/emit-container.mjs +129 -197
  73. package/assets/emit-pack.mjs +92 -136
  74. package/assets/font-config.mjs +19 -27
  75. package/assets/font-sizes.mjs +432 -507
  76. package/assets/glyph-coverage.mjs +170 -214
  77. package/assets/index.mjs +52 -97
  78. package/assets/rasterize.mjs +173 -194
  79. package/assets/svg-loader.mjs +42 -48
  80. package/build.mjs +85 -94
  81. package/cli.mjs +490 -586
  82. package/compile-bin.mjs +24 -36
  83. package/flash.mjs +297 -401
  84. package/hotreload/dev-device.mjs +229 -270
  85. package/hotreload/pack-app.mjs +118 -159
  86. package/hotreload/pack-split.mjs +146 -213
  87. package/hotreload/package-transfer.mjs +128 -131
  88. package/hotreload/protocol.mjs +118 -118
  89. package/hotreload/uploader.mjs +132 -159
  90. package/hotreload/watch-tree.mjs +56 -65
  91. package/pack-container.mjs +94 -116
  92. package/package.json +19 -16
  93. package/persist-transform.mjs +89 -105
  94. package/qjsc-wasm.mjs +47 -72
  95. package/sim/embedded-react.wasm +0 -0
  96. package/sim/index.html +1 -1
  97. package/sim-server.mjs +260 -354
  98. package/src/embedded-react/Alert.mjs +112 -0
  99. package/src/embedded-react/Animated.mjs +412 -0
  100. package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
  101. package/src/embedded-react/{Button.js → Button.mjs} +29 -53
  102. package/src/embedded-react/Dimensions.mjs +32 -0
  103. package/src/embedded-react/Easing.mjs +34 -0
  104. package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
  105. package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
  106. package/src/embedded-react/Keyboard.mjs +82 -0
  107. package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
  108. package/src/embedded-react/PanResponder.mjs +256 -0
  109. package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
  110. package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
  111. package/src/embedded-react/SectionList.mjs +103 -0
  112. package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
  113. package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
  114. package/src/embedded-react/background-image.mjs +321 -0
  115. package/src/embedded-react/{components.js → components.mjs} +1 -3
  116. package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
  117. package/src/embedded-react/index.d.ts +238 -5
  118. package/src/embedded-react/index.js +26 -17
  119. package/src/embedded-react/layout-anim-config.mjs +85 -0
  120. package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
  121. package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
  122. package/src/embedded-react/nativeModule.mjs +371 -0
  123. package/src/embedded-react/split-style.mjs +57 -0
  124. package/src/embedded-react/svg-ops.mjs +1075 -0
  125. package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
  126. package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
  127. package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
  128. package/src/host-config.mjs +512 -0
  129. package/src/{native-ui.js → native-ui.mjs} +1 -8
  130. package/src/props.mjs +341 -0
  131. package/src/{renderer.js → renderer.mjs} +30 -44
  132. package/src/embedded-react/Animated.js +0 -440
  133. package/src/embedded-react/Easing.js +0 -39
  134. package/src/embedded-react/PanResponder.js +0 -330
  135. package/src/embedded-react/SectionList.js +0 -148
  136. package/src/embedded-react/layout-anim-config.js +0 -101
  137. package/src/embedded-react/split-style.js +0 -58
  138. package/src/embedded-react/svg-ops.js +0 -1295
  139. package/src/host-config.js +0 -548
  140. package/src/props.js +0 -306
@@ -0,0 +1,1173 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*
17
+ * Native modules: `const Sensors = nativeModule<Sensors>('sensors', 1)` at module level, typed by an interface in
18
+ * the app's file or in a local .ts file the CLI reads. An app may import a module declared in another file or a
19
+ * package instead, `import {Can} from 'my-device'`, which the CLI reads too (see native-files.mts). Each method called becomes an import named
20
+ * `module.method`, and each call a CALLN. The interface's `events: {reading(celsius: number): void}` are what the
21
+ * firmware posts; each useNativeEvent becomes a handler the runtime runs with the event's values. In Flow A the
22
+ * bundler passes nativeModule() each method's and event's signature instead, and in the simulators the module's mock
23
+ * too.
24
+ *
25
+ * `nativeModule.optional<Wifi>('wifi', 1)` is a module only some boards have. `Wifi.available` says whether the
26
+ * firmware has every method and event of it; the package lists them all, so both flows agree.
27
+ *
28
+ * A record, an interface or object type of fields declared beside the module's interface, passes as its fields one by
29
+ * one, in order; its signature names them, so a renamed or reordered field doesn't load.
30
+ */
31
+ /*----------------------------------------------------------------------------------------------------------------------
32
+ - Imports
33
+ ---------------------------------------------------------------------------------------------------------------------*/
34
+ import { parse } from '@babel/parser';
35
+ import { whenTyped } from './check.mjs';
36
+ import { aotError } from './diagnostics.mjs';
37
+ import { buildsText, lowerExpr, lowerExprWide } from './expressions.mjs';
38
+ import { flattenTree, leafNode, objectTreeOf } from './records.mjs';
39
+ import { nativeAvailableSlot } from './boot.mjs';
40
+ import { BOOL } from './ir/types.mjs';
41
+ /*----------------------------------------------------------------------------------------------------------------------
42
+ - Constants
43
+ ---------------------------------------------------------------------------------------------------------------------*/
44
+ /** Native methods a package may import: the runtime's ERB_MAX_IMPORTS. */
45
+ export const MAX_IMPORTS = 32;
46
+ const MAX_VERSION = 0xffff;
47
+ /** Values a native method may take, and return, a record's fields counted one by one: ERB_NATIVE_MAX_PARAMETERS. */
48
+ const MAX_PARAMETERS = 16;
49
+ /** What a record's field may be named, as a signature names it. */
50
+ const FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
51
+ const SIGNATURE_CODES = {
52
+ int: 'i',
53
+ float: 'f',
54
+ bool: 'b',
55
+ int64: 'l',
56
+ string: 's',
57
+ void: 'v',
58
+ };
59
+ /** The types a native method takes and returns, as embedded-react exports them. */
60
+ const WHOLE_TYPES = { Int: 'int', Int64: 'int64' };
61
+ /** The types of value each parameter takes: a whole number may be passed as a number or an Int64. */
62
+ const ARGUMENT_TYPES = {
63
+ int: ['int'],
64
+ float: ['int', 'float'],
65
+ bool: ['bool'],
66
+ int64: ['int', 'int64'],
67
+ string: ['string'],
68
+ };
69
+ /** What each parameter takes, and how to pass one, for errors. */
70
+ const ARGUMENT_HINTS = {
71
+ int: {
72
+ what: 'an Int',
73
+ hint: 'pass a whole number, e.g. Math.round(value), Math.floor(value) or Math.trunc(value).',
74
+ },
75
+ float: { what: 'a number', hint: 'pass a number.' },
76
+ bool: { what: 'a boolean', hint: 'pass a boolean, e.g. value > 0.' },
77
+ int64: {
78
+ what: 'an Int64',
79
+ hint: 'pass a whole number, e.g. Date.now() or Math.trunc(value).',
80
+ },
81
+ string: {
82
+ what: 'a string',
83
+ hint: 'build text in a const first, and pass that: const label = `${count} items`;',
84
+ },
85
+ };
86
+ const DECLARATION_HINT = "declare it at module level: const Sensors = nativeModule<Sensors>('sensors', 1)";
87
+ /** Optional modules a package may have: the runtime's ERB_MAX_OPTIONAL_MODULES. */
88
+ const MAX_OPTIONAL_MODULES = 32;
89
+ const EVENTS_HINT = 'declare the events as an object of methods that return void: events: {reading(celsius: number): void};';
90
+ /** useNativeEvents a package may have, counting each list row; so no more events than the runtime's ERB_MAX_NATIVE_EVENTS. */
91
+ export const MAX_NATIVE_EVENTS = 32;
92
+ /*----------------------------------------------------------------------------------------------------------------------
93
+ - Implementation
94
+ ---------------------------------------------------------------------------------------------------------------------*/
95
+ /**
96
+ * An error pinned to a node of the app's source.
97
+ *
98
+ * @param node The node.
99
+ * @param message What is wrong.
100
+ * @param hint How to fix it.
101
+ *
102
+ * @returns The error, for the caller to throw.
103
+ */
104
+ function errorAt(node, message, hint) {
105
+ const error = aotError(message, hint);
106
+ if (node.loc) {
107
+ error.aotLoc = node.loc.start;
108
+ }
109
+ return error;
110
+ }
111
+ /**
112
+ * The nativeModule() calls declared at module level, by the const each one is bound to.
113
+ *
114
+ * @param program The app's program, types and all.
115
+ *
116
+ * @returns Each declarator.
117
+ */
118
+ export function declarationsOf(program) {
119
+ const declarators = [];
120
+ for (const statement of program.body) {
121
+ const declaration = statement.type === 'ExportNamedDeclaration'
122
+ ? statement.declaration
123
+ : statement;
124
+ if (declaration?.type !== 'VariableDeclaration')
125
+ continue;
126
+ for (const declarator of declaration.declarations) {
127
+ if (!isNativeModuleCall(declarator.init))
128
+ continue;
129
+ if (declaration.kind !== 'const' || declarator.id.type !== 'Identifier') {
130
+ throw errorAt(declarator, 'AOT: a native module must be bound to a const', DECLARATION_HINT + '.');
131
+ }
132
+ declarators.push(declarator);
133
+ }
134
+ }
135
+ return declarators;
136
+ }
137
+ /**
138
+ * Whether a node is a nativeModule() call.
139
+ *
140
+ * @param node The node.
141
+ *
142
+ * @returns True when it is.
143
+ */
144
+ const isNativeModuleCall = (node) => node?.type === 'CallExpression' &&
145
+ ((node.callee.type === 'Identifier' && node.callee.name === 'nativeModule') ||
146
+ isOptionalCallee(node.callee));
147
+ /**
148
+ * Whether a callee is `nativeModule.optional`.
149
+ *
150
+ * @param callee The callee.
151
+ *
152
+ * @returns True when it is.
153
+ */
154
+ const isOptionalCallee = (callee) => callee.type === 'MemberExpression' &&
155
+ !callee.computed &&
156
+ callee.object.type === 'Identifier' &&
157
+ callee.object.name === 'nativeModule' &&
158
+ callee.property.type === 'Identifier' &&
159
+ callee.property.name === 'optional';
160
+ /**
161
+ * Refuses a nativeModule() call anywhere but a module-level declaration.
162
+ *
163
+ * @param node The node to search, at any depth.
164
+ * @param declared The calls the module level declares.
165
+ */
166
+ function refuseInnerDeclarations(node, declared) {
167
+ if (!node || typeof node !== 'object')
168
+ return;
169
+ if (Array.isArray(node)) {
170
+ node.forEach(child => refuseInnerDeclarations(child, declared));
171
+ return;
172
+ }
173
+ const record = node;
174
+ if (typeof record.type !== 'string')
175
+ return;
176
+ if (isNativeModuleCall(record) && !declared.has(record)) {
177
+ throw errorAt(record, 'AOT: nativeModule() is called outside module level', DECLARATION_HINT + '.');
178
+ }
179
+ for (const key of Object.keys(record)) {
180
+ if (key !== 'loc' && !key.endsWith('Comments')) {
181
+ refuseInnerDeclarations(record[key], declared);
182
+ }
183
+ }
184
+ }
185
+ /**
186
+ * The interface a nativeModule() call names in its type argument.
187
+ *
188
+ * @param call The call.
189
+ *
190
+ * @returns The interface's name.
191
+ */
192
+ function interfaceNameOf(call) {
193
+ const typeArguments = call.typeParameters?.params ?? [];
194
+ const [typeArgument] = typeArguments;
195
+ if (typeArguments.length !== 1 ||
196
+ typeArgument.type !== 'TSTypeReference' ||
197
+ typeArgument.typeName.type !== 'Identifier' ||
198
+ typeArgument.typeParameters) {
199
+ throw errorAt(call, 'AOT: nativeModule() needs the interface that declares the module, as its type argument', DECLARATION_HINT +
200
+ ', in a .tsx app, with `interface Sensors` in the same file or a local .ts file.');
201
+ }
202
+ return typeArgument.typeName.name;
203
+ }
204
+ /**
205
+ * The module's name and version, from the call's arguments.
206
+ *
207
+ * @param call The nativeModule() call.
208
+ *
209
+ * @returns The name and version.
210
+ */
211
+ function nameAndVersionOf(call) {
212
+ const [name, version] = call.arguments;
213
+ if (call.arguments.length !== 2 ||
214
+ name.type !== 'StringLiteral' ||
215
+ version.type !== 'NumericLiteral') {
216
+ throw errorAt(call, 'AOT: nativeModule() takes the module name and version as literals', DECLARATION_HINT + '.');
217
+ }
218
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name.value)) {
219
+ throw errorAt(name, `AOT: "${name.value}" isn't a native module name`, 'name it with letters, digits and underscores, as the firmware registers it: "sensors".');
220
+ }
221
+ if (!Number.isInteger(version.value) ||
222
+ version.value < 0 ||
223
+ version.value > MAX_VERSION) {
224
+ throw errorAt(version, `AOT: a native module's version is a whole number from 0 to ${MAX_VERSION}`, 'give the version the firmware registers the module with.');
225
+ }
226
+ return { name: name.value, version: version.value };
227
+ }
228
+ /**
229
+ * The members of an interface, or of a type alias of an object type, declared in a file.
230
+ *
231
+ * @param program The file.
232
+ * @param name The interface's name.
233
+ *
234
+ * @returns Its members, null when the file doesn't declare it, or a reason it can't be read.
235
+ */
236
+ export function declaredMembers(program, name) {
237
+ for (const statement of program.body) {
238
+ const declaration = statement.type === 'ExportNamedDeclaration' ||
239
+ statement.type === 'ExportDefaultDeclaration'
240
+ ? statement.declaration
241
+ : statement;
242
+ if (declaration?.type === 'TSInterfaceDeclaration' &&
243
+ declaration.id.name === name) {
244
+ if (declaration.extends?.length || declaration.typeParameters) {
245
+ return `the interface ${name} extends another or takes type parameters`;
246
+ }
247
+ return declaration.body.body;
248
+ }
249
+ if (declaration?.type === 'TSTypeAliasDeclaration' &&
250
+ declaration.id.name === name) {
251
+ return declaration.typeAnnotation.type === 'TSTypeLiteral' &&
252
+ !declaration.typeParameters
253
+ ? declaration.typeAnnotation.members
254
+ : `the type ${name} isn't an object type`;
255
+ }
256
+ }
257
+ return null;
258
+ }
259
+ /**
260
+ * Where the app imports a name from, when it imports it from a local file.
261
+ *
262
+ * @param program The app's program.
263
+ * @param name The name the app reads.
264
+ *
265
+ * @returns The import path as the app writes it, and the name the file exports; or null.
266
+ */
267
+ export function localImportOf(program, name) {
268
+ for (const statement of program.body) {
269
+ if (statement.type !== 'ImportDeclaration' ||
270
+ !statement.source.value.startsWith('.')) {
271
+ continue;
272
+ }
273
+ for (const specifier of statement.specifiers) {
274
+ if (specifier.type === 'ImportSpecifier' &&
275
+ specifier.local.name === name) {
276
+ const imported = specifier.imported;
277
+ return {
278
+ path: statement.source.value,
279
+ exported: imported.type === 'Identifier' ? imported.name : imported.value,
280
+ };
281
+ }
282
+ }
283
+ }
284
+ return null;
285
+ }
286
+ /**
287
+ * Parses an interface file.
288
+ *
289
+ * @param source Its source.
290
+ *
291
+ * @returns Its program.
292
+ */
293
+ const parseInterfaceFile = (source) => parse(source, { sourceType: 'module', plugins: ['typescript', 'jsx'] }).program;
294
+ /**
295
+ * The type a parameter, result or field is passed as, or what it is that can't be.
296
+ *
297
+ * @param type The TypeScript type.
298
+ * @param isResult It is the result, which may be void.
299
+ * @param scope The record types the interface's file declares.
300
+ * @param seen The records it is part of, which it can't hold.
301
+ *
302
+ * @returns The native type, or what it is, as in "takes …".
303
+ */
304
+ function nativeValueOf(type, isResult, scope, seen = new Set()) {
305
+ switch (type.type) {
306
+ case 'TSNumberKeyword':
307
+ return 'float';
308
+ case 'TSBooleanKeyword':
309
+ return 'bool';
310
+ case 'TSStringKeyword':
311
+ return 'string';
312
+ case 'TSVoidKeyword':
313
+ return isResult ? 'void' : { what: 'void' };
314
+ case 'TSTypeLiteral':
315
+ return recordOf(type.members, scope, seen);
316
+ case 'TSTypeReference': {
317
+ if (type.typeName.type !== 'Identifier' || type.typeParameters)
318
+ break;
319
+ const { name } = type.typeName;
320
+ if (Object.hasOwn(WHOLE_TYPES, name)) {
321
+ return WHOLE_TYPES[name];
322
+ }
323
+ const members = scope(name);
324
+ if (typeof members === 'string') {
325
+ return { what: `${name}, which isn't a plain interface or object type` };
326
+ }
327
+ if (!members)
328
+ break;
329
+ if (seen.has(name)) {
330
+ return { what: `the record ${name}, which holds itself` };
331
+ }
332
+ const record = recordOf(members, scope, new Set(seen).add(name));
333
+ return 'kind' in record ? { ...record, name } : record;
334
+ }
335
+ }
336
+ return { what: "a type native modules don't pass" };
337
+ }
338
+ /**
339
+ * A record: an interface or object type whose fields are each a value native modules pass, required, and named as a
340
+ * signature names them.
341
+ *
342
+ * @param members Its members.
343
+ * @param scope The record types the interface's file declares.
344
+ * @param seen The records it is part of.
345
+ *
346
+ * @returns The record, or what it is that can't be.
347
+ */
348
+ function recordOf(members, scope, seen) {
349
+ const record = { kind: 'record', fields: [] };
350
+ for (const member of members) {
351
+ if (member.type !== 'TSPropertySignature' ||
352
+ member.computed ||
353
+ (member.key.type !== 'Identifier' && member.key.type !== 'StringLiteral')) {
354
+ return { what: 'a record with a member that is not a plain field' };
355
+ }
356
+ const name = member.key.type === 'Identifier' ? member.key.name : member.key.value;
357
+ if (!FIELD_NAME.test(name) || name === '__proto__') {
358
+ return {
359
+ what: `a record with a field named ${name}, which a native signature can't name`,
360
+ };
361
+ }
362
+ if (record.fields.some(field => field.name === name)) {
363
+ return { what: `a record that declares ${name} twice` };
364
+ }
365
+ if (member.optional) {
366
+ return { what: `a record whose field ${name} is optional` };
367
+ }
368
+ const fieldType = member.typeAnnotation?.typeAnnotation;
369
+ if (!fieldType) {
370
+ return { what: `a record whose field ${name} has no type` };
371
+ }
372
+ const type = nativeValueOf(fieldType, false, scope, seen);
373
+ if (typeof type === 'object' && !('kind' in type)) {
374
+ return { what: `a record whose field ${name} is ${type.what}` };
375
+ }
376
+ record.fields.push({ name, type: type });
377
+ }
378
+ return record.fields.length ? record : { what: 'an empty record' };
379
+ }
380
+ /**
381
+ * A value's values one by one, a record's fields in order, each by its path.
382
+ *
383
+ * @param value The value.
384
+ * @param path Its path, '' at the top.
385
+ *
386
+ * @returns Its values.
387
+ */
388
+ const leavesOf = (value, path = '') => typeof value === 'string'
389
+ ? [{ path, type: value }]
390
+ : value.fields.flatMap(field => leavesOf(field.type, path ? `${path}.${field.name}` : field.name));
391
+ /**
392
+ * One member of a module's interface: a method whose parameters and result are Int, Int64, number, boolean, string,
393
+ * or records of them.
394
+ *
395
+ * @param member The interface member.
396
+ * @param scope The record types the interface's file declares.
397
+ *
398
+ * @returns Its name and what it is, or null for a member without a plain name.
399
+ */
400
+ function memberOf(member, scope) {
401
+ if ((member.type !== 'TSMethodSignature' &&
402
+ member.type !== 'TSPropertySignature') ||
403
+ member.computed ||
404
+ member.key.type !== 'Identifier') {
405
+ return null;
406
+ }
407
+ const { name } = member.key;
408
+ const refuse = (reason, hint) => ({
409
+ name,
410
+ member: { kind: 'refused', reason, hint },
411
+ });
412
+ const typeHint = 'a native method takes and returns Int and Int64 (from embedded-react), number, boolean, string and records of ' +
413
+ 'them, and may return void. A record is an interface or object type of required fields, declared beside the ' +
414
+ "module's: interface Fix { lat: number; lon: number; }";
415
+ // A method, or a property whose type is a function.
416
+ const functionType = member.type === 'TSMethodSignature'
417
+ ? member
418
+ : member.typeAnnotation?.typeAnnotation.type === 'TSFunctionType'
419
+ ? member.typeAnnotation.typeAnnotation
420
+ : null;
421
+ if (!functionType) {
422
+ return refuse("isn't a method", 'declare it as a method: read(channel: Int): number;');
423
+ }
424
+ if (member.optional) {
425
+ return refuse('is optional', 'declare every method the firmware provides.');
426
+ }
427
+ if (functionType.typeParameters) {
428
+ return refuse('takes type parameters', typeHint);
429
+ }
430
+ const params = [];
431
+ const names = [];
432
+ for (const parameter of functionType.parameters) {
433
+ if (parameter.type !== 'Identifier' || parameter.optional) {
434
+ return refuse('has an optional, rest or destructured parameter', 'give each parameter a name and a type: read(channel: Int): number;');
435
+ }
436
+ if (parameter.typeAnnotation?.type !== 'TSTypeAnnotation') {
437
+ return refuse('has no parameter type', typeHint);
438
+ }
439
+ const type = nativeValueOf(parameter.typeAnnotation.typeAnnotation, false, scope);
440
+ if (typeof type === 'object' && !('kind' in type)) {
441
+ return refuse(`takes ${type.what}`, typeHint);
442
+ }
443
+ params.push(type);
444
+ names.push(parameter.name);
445
+ }
446
+ const resultType = functionType.typeAnnotation?.typeAnnotation;
447
+ if (!resultType) {
448
+ return refuse('has no result type', typeHint);
449
+ }
450
+ const result = nativeValueOf(resultType, true, scope);
451
+ if (typeof result === 'object' && !('kind' in result)) {
452
+ return refuse(`returns ${result.what}`, typeHint);
453
+ }
454
+ if (params.flatMap(param => leavesOf(param)).length > MAX_PARAMETERS) {
455
+ return refuse(`takes more than ${MAX_PARAMETERS} values, counting each field of a record`, 'split it into methods that take fewer.');
456
+ }
457
+ if (result !== 'void' &&
458
+ leavesOf(result).length > MAX_PARAMETERS) {
459
+ return refuse(`returns more than ${MAX_PARAMETERS} values, counting each field of its record`, 'split it into methods that return fewer.');
460
+ }
461
+ return {
462
+ name,
463
+ member: {
464
+ kind: 'method',
465
+ params,
466
+ names,
467
+ result: result,
468
+ },
469
+ };
470
+ }
471
+ /**
472
+ * Whether an interface member is its `events`.
473
+ *
474
+ * @param member The member.
475
+ *
476
+ * @returns True when it is named `events`.
477
+ */
478
+ const isEventsMember = (member) => (member.type === 'TSPropertySignature' ||
479
+ member.type === 'TSMethodSignature') &&
480
+ !member.computed &&
481
+ member.key.type === 'Identifier' &&
482
+ member.key.name === 'events';
483
+ /**
484
+ * A module's events, from its interface's `events: {…}`. Each is a method that returns void.
485
+ *
486
+ * @param member The `events` member.
487
+ * @param call The nativeModule() call, for errors.
488
+ * @param interfaceName The interface's name, for errors.
489
+ * @param scope The record types the interface's file declares.
490
+ *
491
+ * @returns Each event, or why it can't be used.
492
+ */
493
+ function eventsOf(member, call, interfaceName, scope) {
494
+ const type = member.type === 'TSPropertySignature'
495
+ ? member.typeAnnotation?.typeAnnotation
496
+ : undefined;
497
+ if (type?.type !== 'TSTypeLiteral' ||
498
+ member.optional) {
499
+ throw errorAt(call, `AOT: ${interfaceName}'s events aren't an object type of events`, EVENTS_HINT);
500
+ }
501
+ const events = new Map();
502
+ for (const element of type.members) {
503
+ const event = memberOf(element, scope);
504
+ if (!event)
505
+ continue;
506
+ if (event.name === '__proto__') {
507
+ throw errorAt(call, `AOT: ${interfaceName} has an event named __proto__, which a native module can't have`, "rename it; JavaScript keeps __proto__ for an object's prototype.");
508
+ }
509
+ const refused = (reason, hint) => ({
510
+ kind: 'refused',
511
+ reason,
512
+ hint,
513
+ });
514
+ events.set(event.name, events.has(event.name)
515
+ ? refused('is overloaded, but a native event has one signature', 'declare each event once, and give another signature a name of its own.')
516
+ : event.member.kind === 'method' && event.member.result !== 'void'
517
+ ? refused('returns a value, but an event returns nothing', EVENTS_HINT)
518
+ : event.member);
519
+ }
520
+ return events;
521
+ }
522
+ /**
523
+ * The native modules a file declares, by the const each is bound to, before they are numbered (see
524
+ * collectNativeModules): an optional module's index is 0.
525
+ *
526
+ * @param program The file's program, types and all.
527
+ * @param files The local files it imports a module's interface from, by import path (see readNativeFiles).
528
+ *
529
+ * @returns Each module, and the call that declares it.
530
+ */
531
+ function declaredIn(program, files) {
532
+ const modules = new Map();
533
+ const declarators = declarationsOf(program);
534
+ refuseInnerDeclarations(program.body, new Set(declarators.map(declarator => declarator.init)));
535
+ for (const declarator of declarators) {
536
+ const call = declarator.init;
537
+ const interfaceName = interfaceNameOf(call);
538
+ const { name, version } = nameAndVersionOf(call);
539
+ // The interface, in this file or in the local file the app imports it from, and the records that file declares.
540
+ let members = declaredMembers(program, interfaceName);
541
+ let scope = name => declaredMembers(program, name);
542
+ if (members === null) {
543
+ const local = localImportOf(program, interfaceName);
544
+ const source = local ? files[local.path]?.source : undefined;
545
+ if (!local || source == null) {
546
+ throw errorAt(call, `AOT: can't find the interface ${interfaceName}`, 'declare it in this file, or in a local .ts file the app imports it from: ' +
547
+ "import type {Sensors} from './sensors';");
548
+ }
549
+ const interfaceFile = parseInterfaceFile(source);
550
+ members = declaredMembers(interfaceFile, local.exported);
551
+ scope = name => declaredMembers(interfaceFile, name);
552
+ if (members === null) {
553
+ throw errorAt(call, `AOT: ${local.path} doesn't declare the interface ${local.exported}`, 'declare the interface in that file itself; a native module interface is not followed through re-exports.');
554
+ }
555
+ }
556
+ if (typeof members === 'string') {
557
+ throw errorAt(call, `AOT: ${members}, which a native module can't be declared by`, 'declare the module as an interface of its methods: interface Sensors { read(channel: Int): number; }');
558
+ }
559
+ const optional = isOptionalCallee(call.callee);
560
+ const module = {
561
+ name,
562
+ version,
563
+ interfaceName,
564
+ members: new Map(),
565
+ events: new Map(),
566
+ optional: optional ? 0 : null,
567
+ };
568
+ for (const element of members) {
569
+ if (isEventsMember(element)) {
570
+ module.events = eventsOf(element, call, interfaceName, scope);
571
+ continue;
572
+ }
573
+ const member = memberOf(element, scope);
574
+ if (!member)
575
+ continue;
576
+ if (optional && member.name === 'available') {
577
+ throw errorAt(call, `AOT: ${interfaceName} has a method named available, which an optional native module can't have`, 'rename it; Wifi.available says whether the firmware has the module.');
578
+ }
579
+ // Flow A keeps the methods in objects, where __proto__ is the prototype.
580
+ if (member.name === '__proto__') {
581
+ throw errorAt(call, `AOT: ${interfaceName} has a method named __proto__, which a native module can't have`, "rename it; JavaScript keeps __proto__ for an object's prototype.");
582
+ }
583
+ // An import has one signature, so an overloaded method can't be called.
584
+ module.members.set(member.name, module.members.has(member.name)
585
+ ? {
586
+ kind: 'refused',
587
+ reason: 'is overloaded, but a native method has one signature',
588
+ hint: 'declare each method once, and give another signature a name of its own.',
589
+ }
590
+ : member.member);
591
+ }
592
+ const usable = [...module.members.values(), ...module.events.values()];
593
+ if (optional && !usable.some(member => member.kind === 'method')) {
594
+ throw errorAt(call, `AOT: the optional native module "${name}" has no methods or events to look for`, 'declare what the firmware provides in its interface; whether the firmware has them all is what ' +
595
+ 'available says.');
596
+ }
597
+ modules.set(declarator.id.name, { module, call });
598
+ }
599
+ return modules;
600
+ }
601
+ /**
602
+ * The native modules a file declares, in order, for the C header.
603
+ *
604
+ * @param source The file's source.
605
+ * @param files The local files it imports a module's interface from (see readNativeFiles).
606
+ *
607
+ * @returns The modules.
608
+ */
609
+ export const declaredModules = (source, files = {}) => [...declaredIn(parseInterfaceFile(source), files).values()].map(({ module }) => module);
610
+ /**
611
+ * The const a file exports under a name: `export const Can = …`, or `export {can as Can}`.
612
+ *
613
+ * @param program The file.
614
+ * @param exported The name it is imported by.
615
+ *
616
+ * @returns The const's name, 'reexport' when the file may pass it on from another file, or null.
617
+ */
618
+ function exportedConstOf(program, exported) {
619
+ let reexports = false;
620
+ for (const statement of program.body) {
621
+ if (statement.type === 'ExportAllDeclaration' &&
622
+ statement.exportKind !== 'type') {
623
+ reexports = true;
624
+ }
625
+ if (statement.type !== 'ExportNamedDeclaration' ||
626
+ statement.exportKind === 'type') {
627
+ continue;
628
+ }
629
+ const declaration = statement.declaration;
630
+ if (declaration?.type === 'VariableDeclaration') {
631
+ const declares = declaration.declarations.some(declarator => declarator.id.type === 'Identifier' &&
632
+ declarator.id.name === exported);
633
+ if (declares)
634
+ return exported;
635
+ }
636
+ for (const specifier of statement.specifiers) {
637
+ if (specifier.type !== 'ExportSpecifier' ||
638
+ specifier.exportKind === 'type') {
639
+ continue;
640
+ }
641
+ const name = specifier.exported.type === 'Identifier'
642
+ ? specifier.exported.name
643
+ : specifier.exported.value;
644
+ if (name !== exported)
645
+ continue;
646
+ return statement.source ? 'reexport' : specifier.local.name;
647
+ }
648
+ }
649
+ return reexports ? 'reexport' : null;
650
+ }
651
+ /**
652
+ * Pins an error from another file's module to the app's import of it, and says where in that file it is.
653
+ *
654
+ * @param error The thrown value.
655
+ * @param file The file, as the app imports it.
656
+ * @param at The app's import.
657
+ *
658
+ * @returns The error, for the caller to throw.
659
+ */
660
+ function importedError(error, file, at) {
661
+ const aotError = error;
662
+ if (!aotError?.message?.startsWith('AOT:'))
663
+ return error;
664
+ const where = aotError.aotLoc
665
+ ? `${file.path}:${aotError.aotLoc.line}:${aotError.aotLoc.column + 1}`
666
+ : file.path;
667
+ aotError.message += ` (in ${where})`;
668
+ aotError.aotLoc = at.loc?.start;
669
+ return aotError;
670
+ }
671
+ /**
672
+ * The modules an app imports from other files, by the name it imports each as: the file, or the package's, declares
673
+ * the module.
674
+ *
675
+ * @param program The app's program.
676
+ * @param files The files it imports from (see readNativeFiles).
677
+ *
678
+ * @returns Each module, where the app imports it, and where it is declared.
679
+ */
680
+ function importedIn(program, files) {
681
+ const found = [];
682
+ for (const statement of program.body) {
683
+ if (statement.type !== 'ImportDeclaration' ||
684
+ statement.importKind === 'type' ||
685
+ !Object.hasOwn(files, statement.source.value)) {
686
+ continue;
687
+ }
688
+ const importPath = statement.source.value;
689
+ const file = files[importPath];
690
+ const specifiers = statement.specifiers.filter(specifier => specifier.type === 'ImportSpecifier' && specifier.importKind !== 'type');
691
+ if (!specifiers.length)
692
+ continue;
693
+ if (file.source === null) {
694
+ throw errorAt(statement.source, `AOT: ${importPath} is JavaScript or a .d.ts, which a native module isn't read from (${file.path})`, 'ship the package\'s .ts source, and point its exports at it: "exports": "./index.ts".');
695
+ }
696
+ let fileProgram;
697
+ let declared;
698
+ try {
699
+ fileProgram = parseInterfaceFile(file.source);
700
+ declared = declaredIn(fileProgram, file.imports);
701
+ }
702
+ catch (error) {
703
+ throw importedError(error, file, statement.source);
704
+ }
705
+ for (const specifier of specifiers) {
706
+ const imported = specifier.imported.type === 'Identifier'
707
+ ? specifier.imported.name
708
+ : specifier.imported.value;
709
+ const local = exportedConstOf(fileProgram, imported);
710
+ if (local === 'reexport') {
711
+ throw errorAt(specifier, `AOT: ${importPath} passes ${imported} on from another file, and a native module isn't followed further`, 'declare the module in the file the app imports, or import it from the file that declares it.');
712
+ }
713
+ const entry = local === null ? undefined : declared.get(local);
714
+ if (!entry)
715
+ continue;
716
+ found.push({
717
+ binding: specifier.local.name,
718
+ module: entry.module,
719
+ at: specifier,
720
+ origin: `${file.path}:${entry.call.start}`,
721
+ });
722
+ }
723
+ }
724
+ return found;
725
+ }
726
+ /**
727
+ * The native modules an app declares or imports, by the const each is bound to. Run on the app before its types are
728
+ * stripped. Optional modules are numbered in order, the app's own first.
729
+ *
730
+ * @param program The app's program, types and all.
731
+ * @param files The files the app imports a module or its interface from, by import path (see readNativeFiles).
732
+ *
733
+ * @returns The modules.
734
+ */
735
+ export function collectNativeModules(program, files = {}) {
736
+ const found = [
737
+ ...[...declaredIn(program, files)].map(([binding, { module, call }]) => ({
738
+ binding,
739
+ module,
740
+ at: call,
741
+ origin: `:${call.start}`,
742
+ })),
743
+ ...importedIn(program, files),
744
+ ];
745
+ const modules = new Map();
746
+ const byName = new Map();
747
+ let optionalCount = 0;
748
+ for (const { binding, module, at, origin } of found) {
749
+ // The same declaration imported twice is one module.
750
+ const first = byName.get(module.name);
751
+ if (first) {
752
+ if (first.origin !== origin) {
753
+ throw errorAt(at, `AOT: the native module "${module.name}" is declared twice`, 'declare each module once, and call its methods through that const.');
754
+ }
755
+ modules.set(binding, first.module);
756
+ continue;
757
+ }
758
+ if (module.optional !== null) {
759
+ if (optionalCount === MAX_OPTIONAL_MODULES) {
760
+ throw errorAt(at, `AOT: an app may declare at most ${MAX_OPTIONAL_MODULES} optional native modules`, 'declare fewer optional modules, or merge ones that boards always have together.');
761
+ }
762
+ module.optional = optionalCount++;
763
+ }
764
+ byName.set(module.name, { module, origin });
765
+ modules.set(binding, module);
766
+ }
767
+ return modules;
768
+ }
769
+ /**
770
+ * A value's code in a signature: a record names its fields in order, {x:i,y:i}.
771
+ *
772
+ * @param value The value.
773
+ *
774
+ * @returns The code.
775
+ */
776
+ export const codeOf = (value) => typeof value === 'string'
777
+ ? SIGNATURE_CODES[value]
778
+ : `{${value.fields.map(field => `${field.name}:${codeOf(field.type)}`).join(',')}}`;
779
+ /**
780
+ * A method's signature: its result, ':', then its parameters.
781
+ *
782
+ * @param member The method.
783
+ *
784
+ * @returns The signature, such as "i:if".
785
+ */
786
+ export const signatureOf = (member) => codeOf(member.result) + ':' + member.params.map(codeOf).join('');
787
+ /**
788
+ * The optional modules, in order, each with every method and event of its interface that can be used: the package
789
+ * lists them all, called or not, so that whether the module is there means what it does in Flow A.
790
+ *
791
+ * @param modules The app's modules (see collectNativeModules).
792
+ *
793
+ * @returns The optional modules, by index.
794
+ */
795
+ export function optionalModulesOf(modules) {
796
+ const optional = [...modules.values()]
797
+ .filter(module => module.optional !== null)
798
+ .sort((first, second) => first.optional - second.optional);
799
+ return optional.map(module => ({
800
+ name: module.name,
801
+ methods: [...module.members]
802
+ .filter(([, member]) => member.kind === 'method')
803
+ .map(([method]) => nativeImportOf(module, method)),
804
+ events: [...module.events]
805
+ .filter(([, event]) => event.kind === 'method')
806
+ .map(([event]) => nativeEventFor(module, event)),
807
+ }));
808
+ }
809
+ /**
810
+ * A method's import, as the firmware registers it.
811
+ *
812
+ * @param module Its module.
813
+ * @param method A method the interface declares, that can be called.
814
+ *
815
+ * @returns The import.
816
+ */
817
+ function nativeImportOf(module, method) {
818
+ const member = module.members.get(method);
819
+ const { result } = member;
820
+ return {
821
+ name: `${module.name}.${method}`,
822
+ version: module.version,
823
+ signature: signatureOf(member),
824
+ params: member.params.flatMap(param => leavesOf(param).map(leaf => leaf.type)),
825
+ result: typeof result === 'string' ? result : 'record',
826
+ results: result === 'void' ? [] : leavesOf(result).map(leaf => leaf.type),
827
+ module: module.optional,
828
+ };
829
+ }
830
+ /**
831
+ * An event, as the firmware registers it.
832
+ *
833
+ * @param module Its module.
834
+ * @param event An event the interface declares, that can be used.
835
+ *
836
+ * @returns The event.
837
+ */
838
+ function nativeEventFor(module, event) {
839
+ const member = module.events.get(event);
840
+ return {
841
+ name: `${module.name}.${event}`,
842
+ version: module.version,
843
+ signature: signatureOf(member),
844
+ params: member.params.flatMap(param => leavesOf(param).map(leaf => leaf.type)),
845
+ module: module.optional,
846
+ };
847
+ }
848
+ /**
849
+ * Flow A's side: since the bundle has no types, each nativeModule() call is given its methods' and events' signatures
850
+ * as a third argument, `{methods, events}`, read from its interface as the compiler reads it. One that can't be used
851
+ * gets the reason instead.
852
+ * With mocks, for the simulators, each call is also given its module's mock, or null when it has none.
853
+ *
854
+ * @param source An app file's source.
855
+ * @param files The files it imports a module or its interface from (see readNativeFiles).
856
+ * @param mocks Each module's mock as the file imports it, or null when it has none, by module name.
857
+ *
858
+ * @returns The source with the signatures added.
859
+ */
860
+ export function addNativeSignatures(source, files, mocks) {
861
+ const program = parse(source, {
862
+ sourceType: 'module',
863
+ plugins: ['jsx', 'typescript'],
864
+ }).program;
865
+ const modules = collectNativeModules(program, files);
866
+ const mockImports = [];
867
+ const mockNames = new Set();
868
+ let signed = source;
869
+ for (const declarator of declarationsOf(program).reverse()) {
870
+ const module = modules.get(declarator.id.name);
871
+ const signatures = (members) => Object.fromEntries([...members].map(([name, member]) => [
872
+ name,
873
+ member.kind === 'method'
874
+ ? signatureOf(member)
875
+ : { reason: member.reason },
876
+ ]));
877
+ let added = `, ${JSON.stringify({
878
+ methods: signatures(module.members),
879
+ events: signatures(module.events),
880
+ })}`;
881
+ if (mocks) {
882
+ const mockPath = mocks.get(module.name);
883
+ if (mockPath) {
884
+ // A name the file doesn't use, nor another mock.
885
+ let mockName = `__erNativeMock_${module.name}`;
886
+ while (source.includes(mockName) || mockNames.has(mockName)) {
887
+ mockName += '_';
888
+ }
889
+ mockNames.add(mockName);
890
+ mockImports.push(`import ${mockName} from ${JSON.stringify(mockPath)};`);
891
+ added += `, ${mockName}`;
892
+ }
893
+ else {
894
+ added += ', null';
895
+ }
896
+ }
897
+ const versionEnd = declarator.init.arguments[1].end;
898
+ signed = signed.slice(0, versionEnd) + added + signed.slice(versionEnd);
899
+ }
900
+ // At the end, so the app's lines keep their numbers.
901
+ return mockImports.length
902
+ ? `${signed}\n${mockImports.reverse().join('\n')}\n`
903
+ : signed;
904
+ }
905
+ /**
906
+ * The native module a call's callee reads a method of, when it is one: `Sensors.read(…)`.
907
+ *
908
+ * @param node The call.
909
+ * @param environment The expression environment.
910
+ *
911
+ * @returns The module and the method's name, or null.
912
+ */
913
+ export function nativeCalleeOf(node, environment) {
914
+ const { callee } = node;
915
+ if (callee.type !== 'MemberExpression' ||
916
+ callee.computed ||
917
+ callee.object.type !== 'Identifier' ||
918
+ callee.property.type !== 'Identifier') {
919
+ return null;
920
+ }
921
+ const binding = callee.object.name;
922
+ const module = environment.nativeModules?.get(binding);
923
+ if (!module ||
924
+ environment.locals.has(binding) ||
925
+ environment.state.has(binding) ||
926
+ binding in environment.constants) {
927
+ return null;
928
+ }
929
+ return { module, method: callee.property.name };
930
+ }
931
+ /**
932
+ * Whether an identifier reads a native module itself, rather than calling one of its methods.
933
+ *
934
+ * @param name The identifier.
935
+ * @param environment The expression environment.
936
+ *
937
+ * @returns True when it does.
938
+ */
939
+ export const readsNativeModule = (name, environment) => !!environment.nativeModules?.has(name) &&
940
+ !environment.locals.has(name) &&
941
+ !environment.state.has(name) &&
942
+ !(name in environment.constants);
943
+ /**
944
+ * Lowers a call to a native method. Only a handler, an effect or a timer calls one: Flow A would call it on every
945
+ * render, and Flow B only works out what changed, so the two would show different values.
946
+ *
947
+ * @param node The call.
948
+ * @param callee Its module and method (see nativeCalleeOf).
949
+ * @param environment The expression environment.
950
+ *
951
+ * @returns The call.
952
+ */
953
+ export function lowerNativeCall(node, callee, environment) {
954
+ const { module, method } = callee;
955
+ const binding = node.callee.object
956
+ .name;
957
+ const what = `${binding}.${method}`;
958
+ if (!environment.outsideRender || environment.workedInRender) {
959
+ throw errorAt(node, `AOT: ${what}() is called in render`, 'call a native method in a handler, an effect or a timer, and keep what it returns in state: ' +
960
+ 'Flow A would call it on every render, and Flow B only when what it reads changes.');
961
+ }
962
+ const member = module.members.get(method);
963
+ if (!member) {
964
+ throw errorAt(node, `AOT: ${module.interfaceName} has no method ${method}`, `declare it in the interface: ${method}(…): number;`);
965
+ }
966
+ if (member.kind === 'refused') {
967
+ throw errorAt(node, `AOT: ${module.interfaceName}.${method} ${member.reason}`, member.hint);
968
+ }
969
+ if (node.arguments.length !== member.params.length) {
970
+ throw errorAt(node, `AOT: ${what}() takes ${member.params.length} argument${member.params.length === 1 ? '' : 's'}, ` +
971
+ `not ${node.arguments.length}`, `pass one for each parameter ${module.interfaceName}.${method} declares.`);
972
+ }
973
+ // Each argument must already be of its parameter's type, except a whole number passed as a number. A record's
974
+ // fields are passed one by one, each read from the object given by its name.
975
+ const callArguments = node.arguments.flatMap((argument, index) => {
976
+ if (argument.type === 'SpreadElement' ||
977
+ argument.type === 'ArgumentPlaceholder') {
978
+ throw errorAt(argument, `AOT: ${what}() takes plain arguments`, 'pass each argument by itself.');
979
+ }
980
+ const param = member.params[index];
981
+ if (typeof param === 'string') {
982
+ return [lowerArgument(argument, param, environment, what, null)];
983
+ }
984
+ const tree = objectTreeOf(argument, environment);
985
+ const leaves = leavesOf(param);
986
+ if (!tree) {
987
+ throw errorAt(argument, `AOT: ${what}() takes a record here`, `pass an object of its fields: {${leaves.map(leaf => leaf.path).join(', ')}}.`);
988
+ }
989
+ const fields = flattenTree(tree);
990
+ return leaves.map(leaf => {
991
+ if (!fields.has(leaf.path)) {
992
+ throw errorAt(argument, `AOT: the record ${what}() takes has a field ${leaf.path}, which this object doesn't`, 'give the object every field the interface declares.');
993
+ }
994
+ const field = leafNode(fields.get(leaf.path), environment);
995
+ return lowerArgument(field.node, leaf.type, field.environment, what, leaf.path, argument);
996
+ });
997
+ });
998
+ return { import: nativeImportOf(module, method), callArguments };
999
+ }
1000
+ /**
1001
+ * Lowers one value a native method is given, checked against its type.
1002
+ *
1003
+ * @param argument The value.
1004
+ * @param param Its type.
1005
+ * @param environment The expression environment.
1006
+ * @param what The method, for errors: `Sensors.read`.
1007
+ * @param field The record's field it is, or null for an argument.
1008
+ * @param at Where an error points, when not at the value: the record a field is part of.
1009
+ *
1010
+ * @returns The value.
1011
+ */
1012
+ function lowerArgument(argument, param, environment, what, field, at = argument) {
1013
+ // Built text needs a buffer to be built in, which a const has.
1014
+ if (param === 'string' && buildsText(argument, environment)) {
1015
+ throw errorAt(at, `AOT: ${what}() takes a string${field === null ? '' : ` as ${field}`}, not text built in the call`, ARGUMENT_HINTS.string.hint);
1016
+ }
1017
+ // Only an Int64 parameter holds a 64-bit value whole.
1018
+ const lowered = param === 'int64'
1019
+ ? lowerExprWide(argument, environment)
1020
+ : lowerExpr(argument, environment);
1021
+ whenTyped(() => {
1022
+ if (!ARGUMENT_TYPES[param].includes(lowered.type.kind)) {
1023
+ throw errorAt(at, `AOT: ${what}() takes ${ARGUMENT_HINTS[param].what} ${field === null ? 'here' : `as ${field}`}`, ARGUMENT_HINTS[param].hint);
1024
+ }
1025
+ });
1026
+ return lowered;
1027
+ }
1028
+ /**
1029
+ * The native method a call calls, when it returns a record: a const or an object state keeps it, as JS would.
1030
+ *
1031
+ * @param node The expression.
1032
+ * @param environment The expression environment.
1033
+ *
1034
+ * @returns The call's module, method and record, or null.
1035
+ */
1036
+ export function nativeRecordCallOf(node, environment) {
1037
+ if (node?.type !== 'CallExpression')
1038
+ return null;
1039
+ const callee = nativeCalleeOf(node, environment);
1040
+ const member = callee?.module.members.get(callee.method);
1041
+ return member?.kind === 'method' && typeof member.result === 'object'
1042
+ ? { ...callee, record: member.result }
1043
+ : null;
1044
+ }
1045
+ /**
1046
+ * Refuses a record a native method returns where it can't be kept: anywhere but a const, an object state's setter, a
1047
+ * native method's record parameter, or a field read of one of those.
1048
+ *
1049
+ * @param node The call.
1050
+ * @param environment The expression environment.
1051
+ *
1052
+ * @returns The error, or null when the call returns no record.
1053
+ */
1054
+ export function unkeptRecordError(node, environment) {
1055
+ const callee = nativeRecordCallOf(node, environment);
1056
+ if (!callee)
1057
+ return null;
1058
+ const binding = node.callee
1059
+ .object;
1060
+ const what = `${binding.name}.${callee.method}`;
1061
+ return errorAt(node, `AOT: ${what}() returns a record, which only a const or an object state keeps`, `keep it first, then read its fields: const fix = ${what}(…); or setFix(${what}(…));`);
1062
+ }
1063
+ /**
1064
+ * How many values a value is, a record's fields counted one by one.
1065
+ *
1066
+ * @param value The value.
1067
+ *
1068
+ * @returns The count.
1069
+ */
1070
+ export const valueCount = (value) => leavesOf(value).length;
1071
+ /**
1072
+ * Where each of a record's values is, by its path: a tree of `read(index, type)`, in field order.
1073
+ *
1074
+ * @param record The record.
1075
+ * @param read Each value, by its index among the record's values.
1076
+ * @param from The index of the record's first value.
1077
+ *
1078
+ * @returns The tree.
1079
+ */
1080
+ export function recordTreeOf(record, read, from = 0) {
1081
+ const tree = {};
1082
+ let index = from;
1083
+ for (const field of record.fields) {
1084
+ if (typeof field.type === 'string') {
1085
+ tree[field.name] = read(index++, field.type);
1086
+ }
1087
+ else {
1088
+ tree[field.name] = recordTreeOf(field.type, read, index);
1089
+ index += valueCount(field.type);
1090
+ }
1091
+ }
1092
+ return tree;
1093
+ }
1094
+ /**
1095
+ * `Wifi.available`: whether the firmware has every method and event of an optional module. Boot reads it, and it
1096
+ * never changes after.
1097
+ *
1098
+ * @param node A member read.
1099
+ * @param environment The expression environment.
1100
+ *
1101
+ * @returns The read, or null when the node isn't a native module's `available`.
1102
+ */
1103
+ export function nativeAvailableOf(node, environment) {
1104
+ if (node.computed ||
1105
+ node.object.type !== 'Identifier' ||
1106
+ node.property.type !== 'Identifier' ||
1107
+ node.property.name !== 'available' ||
1108
+ !readsNativeModule(node.object.name, environment)) {
1109
+ return null;
1110
+ }
1111
+ const module = environment.nativeModules.get(node.object.name);
1112
+ if (module.optional === null) {
1113
+ throw errorAt(node, `AOT: ${node.object.name} is always available, since the firmware must have it`, `declare it with nativeModule.optional<${module.interfaceName}>('${module.name}', ${module.version}) ` +
1114
+ "if some boards don't have it.");
1115
+ }
1116
+ return {
1117
+ kind: 'boot',
1118
+ slot: nativeAvailableSlot(module.optional, module.name),
1119
+ type: BOOL,
1120
+ };
1121
+ }
1122
+ /**
1123
+ * The event a `useNativeEvent(Module, 'event', handler)` call subscribes to, checked against its module's interface.
1124
+ *
1125
+ * @param call The call.
1126
+ * @param environment The expression environment.
1127
+ *
1128
+ * @returns The event and its values, and the handler with no more parameters than the event's values.
1129
+ */
1130
+ export function nativeEventOf(call, environment) {
1131
+ const [moduleArgument, eventArgument, handler] = call.arguments;
1132
+ const usage = "subscribe as useNativeEvent(Sensors, 'reading', celsius => setTemperature(celsius)).";
1133
+ if (call.arguments.length !== 3 ||
1134
+ moduleArgument.type !== 'Identifier' ||
1135
+ !readsNativeModule(moduleArgument.name, environment)) {
1136
+ throw errorAt(call, 'AOT: useNativeEvent() takes a native module, an event name and a handler', usage);
1137
+ }
1138
+ const module = environment.nativeModules.get(moduleArgument.name);
1139
+ if (eventArgument.type !== 'StringLiteral') {
1140
+ throw errorAt(eventArgument, "AOT: useNativeEvent()'s event is named by a string literal", usage);
1141
+ }
1142
+ const event = module.events.get(eventArgument.value);
1143
+ if (!event) {
1144
+ throw errorAt(eventArgument, `AOT: ${module.interfaceName} has no event ${eventArgument.value}`, `declare it in the interface: events: {${eventArgument.value}(…): void};`);
1145
+ }
1146
+ if (event.kind === 'refused') {
1147
+ throw errorAt(eventArgument, `AOT: ${module.interfaceName}'s event ${eventArgument.value} ${event.reason}`, event.hint);
1148
+ }
1149
+ if (handler.type !== 'ArrowFunctionExpression' &&
1150
+ handler.type !== 'FunctionExpression') {
1151
+ throw errorAt(handler, "AOT: useNativeEvent()'s handler must be an inline function", usage);
1152
+ }
1153
+ if (handler.async || handler.generator) {
1154
+ throw errorAt(handler, "AOT: useNativeEvent()'s handler can't be async or a generator", 'write a plain function; the firmware posts the event when its work is done.');
1155
+ }
1156
+ if (handler.params.length > event.params.length) {
1157
+ throw errorAt(handler, `AOT: ${module.interfaceName}'s event ${eventArgument.value} has ${event.params.length} value` +
1158
+ `${event.params.length === 1 ? '' : 's'}, but the handler takes ${handler.params.length}`, 'take one parameter for each value the interface declares, or fewer.');
1159
+ }
1160
+ handler.params.forEach((parameter, position) => {
1161
+ // A record may be destructured, as JS would.
1162
+ if (parameter.type !== 'Identifier' &&
1163
+ (parameter.type !== 'ObjectPattern' ||
1164
+ typeof event.params[position] === 'string')) {
1165
+ throw errorAt(parameter, "AOT: useNativeEvent()'s handler takes plain parameters", 'name each value: (celsius, ok) => …, or destructure a record: ({lat, lon}) => …');
1166
+ }
1167
+ });
1168
+ return {
1169
+ event: nativeEventFor(module, eventArgument.value),
1170
+ values: event.params,
1171
+ handler,
1172
+ };
1173
+ }