embedded-react 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +1 -0
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +16 -46
  5. package/aot/compiler/animations.mjs +299 -57
  6. package/aot/compiler/boot.mjs +27 -2
  7. package/aot/compiler/check.mjs +61 -9
  8. package/aot/compiler/collect.mjs +516 -136
  9. package/aot/compiler/contexts.mjs +391 -0
  10. package/aot/compiler/control-flow.mjs +276 -117
  11. package/aot/compiler/custom-hooks.mjs +686 -0
  12. package/aot/compiler/elements/button.mjs +182 -0
  13. package/aot/compiler/elements/image-background.mjs +76 -0
  14. package/aot/compiler/elements/image.mjs +2 -1
  15. package/aot/compiler/elements/props.mjs +38 -3
  16. package/aot/compiler/elements/rewrite.mjs +118 -0
  17. package/aot/compiler/elements/section-list.mjs +370 -0
  18. package/aot/compiler/expressions.mjs +1351 -97
  19. package/aot/compiler/handlers.mjs +1761 -365
  20. package/aot/compiler/helper-values.mjs +312 -0
  21. package/aot/compiler/ir/nodes.mjs +40 -1
  22. package/aot/compiler/ir/reads.mjs +206 -5
  23. package/aot/compiler/ir/text.mjs +5 -1
  24. package/aot/compiler/ir/types.mjs +12 -0
  25. package/aot/compiler/kept-states.mjs +177 -0
  26. package/aot/compiler/list-items.mjs +226 -0
  27. package/aot/compiler/list-order.mjs +586 -0
  28. package/aot/compiler/list-split.mjs +259 -0
  29. package/aot/compiler/loops.mjs +582 -0
  30. package/aot/compiler/lower.mjs +191 -53
  31. package/aot/compiler/native-files.mjs +439 -0
  32. package/aot/compiler/native-header.mjs +335 -0
  33. package/aot/compiler/native-modules.mjs +1173 -0
  34. package/aot/compiler/nodes.mjs +28 -22
  35. package/aot/compiler/options.mjs +3 -2
  36. package/aot/compiler/out.mjs +14 -1
  37. package/aot/compiler/package/animations.mjs +133 -23
  38. package/aot/compiler/package/assemble.mjs +2 -4
  39. package/aot/compiler/package/bytecode.mjs +37 -8
  40. package/aot/compiler/package/checks.mjs +4 -0
  41. package/aot/compiler/package/codegen.mjs +870 -31
  42. package/aot/compiler/package/enums.mjs +10 -0
  43. package/aot/compiler/package/format.mjs +12 -1
  44. package/aot/compiler/package/lower.mjs +658 -161
  45. package/aot/compiler/package/string-caps.mjs +515 -0
  46. package/aot/compiler/package/tables.mjs +24 -0
  47. package/aot/compiler/package/writer.mjs +22 -0
  48. package/aot/compiler/parse.mjs +3 -1
  49. package/aot/compiler/record-shapes.mjs +246 -0
  50. package/aot/compiler/records.mjs +654 -0
  51. package/aot/compiler/reducers.mjs +272 -0
  52. package/aot/compiler/static-eval.mjs +315 -7
  53. package/aot/compiler/style-text.mjs +18 -3
  54. package/aot/compiler/svg.mjs +7 -4
  55. package/aot/compiler/switch-cases.mjs +198 -0
  56. package/aot/compiler/tagged-records.mjs +450 -0
  57. package/aot/compiler/typing.mjs +307 -0
  58. package/aot/compiler/updaters.mjs +320 -0
  59. package/aot/compiler/window-dimensions.mjs +94 -0
  60. package/aot/compiler/worked-values.mjs +319 -0
  61. package/aot/demo-file.mjs +30 -0
  62. package/aot/style-map.mjs +50 -2
  63. package/build.mjs +9 -1
  64. package/cli.mjs +44 -1
  65. package/hotreload/pack-split.mjs +29 -40
  66. package/pack-container.mjs +9 -1
  67. package/package.json +1 -1
  68. package/sim/embedded-react.wasm +0 -0
  69. package/sim-server.mjs +22 -22
  70. package/src/embedded-react/Dimensions.js +37 -0
  71. package/src/embedded-react/SectionList.js +1 -3
  72. package/src/embedded-react/index.d.ts +83 -3
  73. package/src/embedded-react/index.js +2 -0
  74. package/src/embedded-react/nativeModule.js +462 -0
@@ -0,0 +1,335 @@
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
+ * A C header for each native module a file declares, so the firmware's C is written against what apps compile
18
+ * against: a struct per record with helpers that pack and unpack its cells, where each argument starts in a call's
19
+ * or post's cells, and an entry per method and event with its name, version and signature. The modules are read as
20
+ * the compiler reads them (see native-modules.mts).
21
+ */
22
+ /*----------------------------------------------------------------------------------------------------------------------
23
+ - Imports
24
+ ---------------------------------------------------------------------------------------------------------------------*/
25
+ import { codeOf, declaredModules, signatureOf } from './native-modules.mjs';
26
+ /*----------------------------------------------------------------------------------------------------------------------
27
+ - Constants
28
+ ---------------------------------------------------------------------------------------------------------------------*/
29
+ /** The cells each type takes. */
30
+ const CELLS = {
31
+ int: 1,
32
+ float: 1,
33
+ bool: 1,
34
+ int64: 2,
35
+ string: 1,
36
+ };
37
+ const C_TYPES = {
38
+ int: 'int32_t',
39
+ float: 'float',
40
+ bool: 'bool',
41
+ int64: 'int64_t',
42
+ string: 'const char*',
43
+ };
44
+ /** Each type as the interface writes it, for the comments. */
45
+ const TYPESCRIPT_TYPES = {
46
+ int: 'Int',
47
+ float: 'number',
48
+ bool: 'boolean',
49
+ int64: 'Int64',
50
+ string: 'string',
51
+ void: 'void',
52
+ };
53
+ /** The keywords of C and C++, and the names their headers define as keywords, which a struct's field can't have. */
54
+ const KEYWORDS = new Set(('alignas alignof and and_eq asm auto bitand bitor bool break case catch char char8_t char16_t char32_t class ' +
55
+ 'compl concept const consteval constexpr constinit const_cast continue co_await co_return co_yield decltype ' +
56
+ 'default delete do double dynamic_cast else enum explicit export extern false float for friend goto if inline ' +
57
+ 'int long mutable namespace new noexcept not not_eq nullptr operator or or_eq private protected public ' +
58
+ 'register reinterpret_cast requires restrict return short signed sizeof static static_assert static_cast ' +
59
+ 'struct switch template this thread_local throw true try typedef typeid typename typeof typeof_unqual union ' +
60
+ 'unsigned using virtual void volatile wchar_t while xor xor_eq').split(' '));
61
+ /** A name C or C++ keeps for itself: `_Atomic`, `__packed`, or one with `__` in it. */
62
+ const KEPT_NAME = /^_[A-Z]|__/;
63
+ const INDENT = ' ';
64
+ /*----------------------------------------------------------------------------------------------------------------------
65
+ - Implementation
66
+ ---------------------------------------------------------------------------------------------------------------------*/
67
+ /**
68
+ * An error with how to fix it.
69
+ *
70
+ * @param message What is wrong.
71
+ * @param hint How to fix it.
72
+ *
73
+ * @returns The error, for the caller to throw.
74
+ */
75
+ function headerError(message, hint) {
76
+ const error = new Error(message);
77
+ error.aotHint = hint;
78
+ return error;
79
+ }
80
+ /**
81
+ * A name's words: freeMemory and free_memory are both free, memory.
82
+ *
83
+ * @param name The name.
84
+ *
85
+ * @returns Its words.
86
+ */
87
+ const wordsOf = (name) => name
88
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
89
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
90
+ .split('_')
91
+ .filter(Boolean);
92
+ const macroOf = (words) => words.join('_').toUpperCase();
93
+ const functionOf = (words) => words.join('_').toLowerCase();
94
+ const typeOf = (words) => words.map(word => word[0].toUpperCase() + word.slice(1)).join('');
95
+ /**
96
+ * How many cells a value takes.
97
+ *
98
+ * @param value The value.
99
+ *
100
+ * @returns The count.
101
+ */
102
+ const cellsOf = (value) => typeof value === 'string'
103
+ ? CELLS[value]
104
+ : value.fields.reduce((cells, field) => cells + cellsOf(field.type), 0);
105
+ /**
106
+ * One module's header.
107
+ *
108
+ * @param module The module.
109
+ *
110
+ * @returns The header.
111
+ */
112
+ function headerOf(module) {
113
+ /** A name's words, which every C name it is part of needs at least one of. */
114
+ const namedWords = (name, what) => {
115
+ const words = wordsOf(name);
116
+ if (!words.length) {
117
+ throw headerError(`${module.interfaceName}: ${what} is named ${name}, which leaves nothing to name it by in the header`, 'give it a name with a letter in it.');
118
+ }
119
+ return words;
120
+ };
121
+ // Every name in the header starts with the module's, so it must start as a C name does.
122
+ const moduleWords = namedWords(module.name, 'the module');
123
+ if (/^[0-9]/.test(moduleWords[0])) {
124
+ throw headerError(`${module.interfaceName}: the module is named ${module.name}, so its names in the header would start with a digit`, 'start its name with a letter.');
125
+ }
126
+ const structs = [];
127
+ const taken = new Map();
128
+ /** Keeps a name the header defines, and refuses one defined twice. */
129
+ const define = (name, what) => {
130
+ const first = taken.get(name);
131
+ if (first) {
132
+ throw headerError(`${module.interfaceName}: ${first} and ${what} would both be ${name} in the header`, 'rename one of them.');
133
+ }
134
+ taken.set(name, what);
135
+ return name;
136
+ };
137
+ /** A record's struct, its records first. A record with no name is named after where it is. */
138
+ const structOf = (record, place) => {
139
+ const words = [
140
+ ...moduleWords,
141
+ ...(record.name ? namedWords(record.name, 'a record') : place),
142
+ ];
143
+ const type = typeOf(words);
144
+ const known = structs.find(struct => struct.type === type);
145
+ if (known && codeOf(known.record) === codeOf(record))
146
+ return known;
147
+ const what = record.name ? `the record ${record.name}` : 'a record';
148
+ const fields = record.fields.map(field => {
149
+ if (KEYWORDS.has(field.name) || KEPT_NAME.test(field.name)) {
150
+ throw headerError(`${module.interfaceName}: ${what} has a field named ${field.name}, which C keeps for itself`, 'rename the field.');
151
+ }
152
+ return typeof field.type === 'string'
153
+ ? null
154
+ : structOf(field.type, [
155
+ ...words.slice(moduleWords.length),
156
+ ...namedWords(field.name, `${what}'s field`),
157
+ ]);
158
+ });
159
+ define(type, what);
160
+ define(`${macroOf(words)}_CELLS`, what);
161
+ define(`${functionOf(words)}_pack`, what);
162
+ define(`${functionOf(words)}_unpack`, what);
163
+ const struct = { type, words, record, fields };
164
+ structs.push(struct);
165
+ return struct;
166
+ };
167
+ /** A value's type in the comments, and its struct when it is a record. */
168
+ const shownType = (value, place) => typeof value === 'string'
169
+ ? TYPESCRIPT_TYPES[value]
170
+ : structOf(value, place).type;
171
+ /** A method's or event's macros. */
172
+ const memberLines = (name, member) => {
173
+ if (member.kind === 'refused') {
174
+ throw headerError(`${module.interfaceName}.${name} ${member.reason}`, member.hint);
175
+ }
176
+ const what = `${name}()`;
177
+ const memberWords = namedWords(name, 'a method or event');
178
+ const words = [...moduleWords, ...memberWords];
179
+ const argumentWords = member.names.map(argument => namedWords(argument, `${what}'s argument`));
180
+ const parameters = member.params.map((param, index) => `${member.names[index]}: ${shownType(param, [...memberWords, ...argumentWords[index]])}`);
181
+ const lines = [
182
+ `/* ${name}(${parameters.join(', ')}): ${shownType(member.result, [...memberWords, 'result'])} */`,
183
+ `#define ${define(`${macroOf(words)}_ENTRY`, what)} ` +
184
+ `"${module.name}.${name}", ${module.version}, "${signatureOf(member)}"`,
185
+ ];
186
+ let offset = 0;
187
+ member.params.forEach((param, index) => {
188
+ const macro = macroOf([...words, 'ARG', ...argumentWords[index]]);
189
+ lines.push(`#define ${define(macro, `${what}'s ${member.names[index]}`)} ${offset}`);
190
+ offset += cellsOf(param);
191
+ });
192
+ if (member.params.length) {
193
+ lines.push(`#define ${define(`${macroOf(words)}_ARG_CELLS`, `${what}'s cell count`)} ${offset}`);
194
+ }
195
+ return lines;
196
+ };
197
+ const methods = [...module.members].map(([name, member]) => memberLines(name, member));
198
+ const events = [...module.events].map(([name, member]) => memberLines(name, member));
199
+ if (!methods.length && !events.length) {
200
+ throw headerError(`${module.interfaceName} has no methods or events`, 'declare what the firmware provides in its interface.');
201
+ }
202
+ const guard = `${macroOf(moduleWords)}_MODULE_H`;
203
+ const [first] = module.members.size ? module.members.keys() : [''];
204
+ const [firstEvent] = module.events.size ? module.events.keys() : [''];
205
+ const example = [
206
+ first &&
207
+ `{${macroOf([...moduleWords, ...wordsOf(first)])}_ENTRY, ${functionOf([...moduleWords, ...wordsOf(first)])}}`,
208
+ firstEvent &&
209
+ `{${macroOf([...moduleWords, ...wordsOf(firstEvent)])}_ENTRY, NULL} for an event`,
210
+ ]
211
+ .filter(Boolean)
212
+ .join(', or ');
213
+ const lines = [
214
+ '/*',
215
+ ` * The ${module.name} native module, version ${module.version}, generated by \`embedded-react native-header\`. Don't edit it:`,
216
+ " * change the module's interface and generate it again.",
217
+ ' *',
218
+ " * Each method and event has an entry for the firmware's ErbNative table:",
219
+ ` * ${example}.`,
220
+ " * An _ARG_ macro is where that argument starts in a call's or post's cells, and a record's pack and unpack write",
221
+ ' * and read its cells.',
222
+ ' */',
223
+ '',
224
+ `#ifndef ${guard}`,
225
+ `#define ${guard}`,
226
+ '',
227
+ '#include "erb_native.h"',
228
+ '',
229
+ '#include <stdbool.h>',
230
+ '#include <stdint.h>',
231
+ ];
232
+ const section = (title, blocks) => {
233
+ if (!blocks.length)
234
+ return;
235
+ lines.push('', `/* ${title} */`);
236
+ for (const block of blocks) {
237
+ lines.push('', ...block);
238
+ }
239
+ };
240
+ section('Records', structs.map(structLines));
241
+ section('Methods', methods);
242
+ section('Events', events);
243
+ lines.push('', '#endif', '');
244
+ return {
245
+ module: module.name,
246
+ file: `${functionOf(moduleWords)}_module.h`,
247
+ text: lines.join('\n'),
248
+ };
249
+ }
250
+ /**
251
+ * A record's struct, cell count, and pack and unpack helpers.
252
+ *
253
+ * @param struct The struct.
254
+ *
255
+ * @returns The lines.
256
+ */
257
+ function structLines(struct) {
258
+ const pack = [];
259
+ const unpack = [];
260
+ const fields = [];
261
+ let offset = 0;
262
+ struct.record.fields.forEach(({ name, type }, index) => {
263
+ const cell = `cells[${offset}]`;
264
+ const inner = struct.fields[index];
265
+ if (typeof type !== 'string') {
266
+ const helper = functionOf(inner.words);
267
+ pack.push(`${helper}_pack(&${cell}, &value->${name});`);
268
+ unpack.push(`value.${name} = ${helper}_unpack(&${cell});`);
269
+ }
270
+ else if (type === 'int') {
271
+ pack.push(`${cell} = value->${name};`);
272
+ unpack.push(`value.${name} = ${cell};`);
273
+ }
274
+ else if (type === 'bool') {
275
+ pack.push(`${cell} = value->${name} ? 1 : 0;`);
276
+ unpack.push(`value.${name} = ${cell} != 0;`);
277
+ }
278
+ else if (type === 'float') {
279
+ pack.push(`erb_native_set_float(&${cell}, value->${name});`);
280
+ unpack.push(`value.${name} = erb_native_float(${cell});`);
281
+ }
282
+ else if (type === 'int64') {
283
+ pack.push(`erb_native_set_int64(&${cell}, value->${name});`);
284
+ unpack.push(`value.${name} = erb_native_int64(&${cell});`);
285
+ }
286
+ else {
287
+ pack.push(`${cell} = erb_native_text(value->${name});`);
288
+ unpack.push(`value.${name} = erb_native_string(${cell});`);
289
+ }
290
+ fields.push(`${typeof type === 'string' ? C_TYPES[type] : inner.type} ${name};`);
291
+ offset += cellsOf(type);
292
+ });
293
+ const indent = (lines) => lines.map(line => INDENT + line);
294
+ const helper = functionOf(struct.words);
295
+ return [
296
+ 'typedef struct',
297
+ '{',
298
+ ...indent(fields),
299
+ `} ${struct.type};`,
300
+ '',
301
+ `#define ${macroOf(struct.words)}_CELLS ${offset}`,
302
+ '',
303
+ `static inline void ${helper}_pack(int32_t* cells, const ${struct.type}* value)`,
304
+ '{',
305
+ ...indent(pack),
306
+ '}',
307
+ '',
308
+ `static inline ${struct.type} ${helper}_unpack(const int32_t* cells)`,
309
+ '{',
310
+ ...indent([`${struct.type} value;`, ...unpack, 'return value;']),
311
+ '}',
312
+ ];
313
+ }
314
+ /**
315
+ * A C header for each native module a file declares.
316
+ *
317
+ * @param source The file's source.
318
+ * @param files The local files it imports a module's interface from (see readModuleFile).
319
+ *
320
+ * @returns Each module's header, in the order the file declares them.
321
+ */
322
+ export function nativeHeaders(source, files = {}) {
323
+ const modules = declaredModules(source, files);
324
+ if (!modules.length) {
325
+ throw headerError('The file declares no native modules', "pass the file that declares them: export const Can = nativeModule<Can>('can', 1);");
326
+ }
327
+ const headers = modules.map(headerOf);
328
+ for (const header of headers) {
329
+ const twice = headers.find(other => other !== header && other.file === header.file);
330
+ if (twice) {
331
+ throw headerError(`The modules "${header.module}" and "${twice.module}" would both be written to ${header.file}`, 'rename one of them.');
332
+ }
333
+ }
334
+ return headers;
335
+ }