@tinyactors/wasm 0.0.0-stage → 0.4.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.
@@ -0,0 +1,390 @@
1
+ // The compiler, as the addon defines it (src/compile.c): compileCharts is
2
+ // ta_compile_charts, compileSystem is ta_compile_system (a <system>
3
+ // manifest), a compile result is the object both return, and a resolver,
4
+ // any callable (base, source) => string, is ta_compile_options.resolve:
5
+ // the only place a resolver is given, so it lives at compile time only.
6
+ //
7
+ // Who holds what:
8
+ // - a compile result holds the ta_compile_result in linear memory:
9
+ // close() frees it (ta_compile_free), a FinalizationRegistry frees it
10
+ // when close() was not called;
11
+ // - `image` is a Uint8Array copied from the result on its first read,
12
+ // kept on the object, the application's from then on;
13
+ // - the call's sources are views in the environment's arena (a mark per
14
+ // call); a resolver's texts and messages are copied into the
15
+ // compilation's scratch arena (request->scratch, ta_web_resolve_room),
16
+ // which lives until the compile call returns.
17
+ //
18
+ // After a compilation that succeeded, every expression and script of an
19
+ // "ecmascript" chart is parsed by the engine in the native datamodel's
20
+ // shapes, nothing run (the addon's check): each syntax error a warning at
21
+ // its line, an error with warningsAsErrors, and so is a script's top-level
22
+ // declaration the native datamodel refuses (let, const, class) or makes a
23
+ // variable of the session (var), asked of the application's kit (realm.js,
24
+ // `advice`). The parser is node:vm's Script
25
+ // in node and bun (the addon's), the realm's Function in a browser, where
26
+ // a page finds the error's line and column by a <script> element that
27
+ // does not parse (it runs nothing: the source is inside a function
28
+ // expression); a Worker reports the expression's own position. Under a
29
+ // policy that refuses string evaluation (realms.mjs, policyRefusal) the
30
+ // check is skipped: the native datamodel cannot run there either.
31
+ import { CompileError, ResolveError, TinyactorsError, refusal } from './errors.mjs';
32
+ import { application, policyRefusal } from './realms.mjs';
33
+ import { instance } from './state.mjs';
34
+
35
+ const SEVERITIES = ['note', 'warning', 'error'];
36
+ const ERROR = 2;
37
+ const WERROR = 2; // TA_COMPILE_WERROR
38
+ const TA_OK = 0, TA_ERROR_INVALID = -3, TA_ERROR_NO_MEMORY = -4;
39
+ const encoder = new TextEncoder();
40
+
41
+ // The results not closed: freed by the collector as a fallback. The token
42
+ // is the module and the result's pointer, never the object.
43
+ const unclosed = new FinalizationRegistry(({ module, result }) => {
44
+ try {
45
+ if (!module.poisoned) module.call('ta_web_compile_free', result);
46
+ } catch {
47
+ // a poisoned module frees nothing more
48
+ }
49
+ });
50
+
51
+ // The token the constructor checks: only the compile calls make a result.
52
+ const MAKING = Symbol('making');
53
+
54
+ export class Compiled {
55
+ #module;
56
+ #result; // 0 once closed
57
+ #image;
58
+
59
+ constructor(making, module, result, diagnostics) {
60
+ if (making !== MAKING) throw new TypeError('a compile result is made by compileCharts and compileSystem');
61
+ this.#module = module;
62
+ this.#result = result;
63
+ Object.defineProperty(this, 'diagnostics', { value: diagnostics, enumerable: true });
64
+ unclosed.register(this, { module, result }, this);
65
+ }
66
+
67
+ static #of(self) {
68
+ if (self === null || typeof self !== 'object' || !(#result in self)) throw new TypeError('not a compile result');
69
+ return self;
70
+ }
71
+
72
+ // The image, copied on the first read and the same after; a first read
73
+ // after close() throws TA_ERROR_STALE.
74
+ get image() {
75
+ const self = Compiled.#of(this);
76
+ if (self.#image !== undefined) return self.#image;
77
+ if (self.#result === 0) throw refusal('TA_ERROR_STALE', 'the compile result was closed before its image was read');
78
+ const module = self.#module;
79
+ const at = module.call('ta_web_compile_image', module.env, self.#result) >>> 0;
80
+ self.#image = module.copyOut(at, module.word(0));
81
+ return self.#image;
82
+ }
83
+
84
+ // Frees the result; again, nothing.
85
+ close() {
86
+ const self = Compiled.#of(this);
87
+ if (self.#result === 0) return;
88
+ const result = self.#result;
89
+ self.#result = 0;
90
+ unclosed.unregister(self);
91
+ self.#module.call('ta_web_compile_free', result);
92
+ }
93
+
94
+ [Symbol.dispose]() {
95
+ this.close();
96
+ }
97
+ }
98
+
99
+ // One diagnostic as a frozen object; its record's words (compile.c).
100
+ function diagnosticAt(module, result, i) {
101
+ module.call('ta_web_compile_diagnostic', module.env, result, i);
102
+ const w = module.words().slice(module.record, module.record + 8);
103
+ const severity = w[0];
104
+ return Object.freeze({
105
+ severity: SEVERITIES[severity < 3 ? severity : 2],
106
+ code: w[1],
107
+ file: module.string(w[4], w[5]),
108
+ line: w[2],
109
+ column: w[3],
110
+ message: module.string(w[6], w[7]),
111
+ });
112
+ }
113
+
114
+ // A compile call's resolver: the import's owner while the call runs.
115
+ class Resolving {
116
+ constructor(module, resolver) {
117
+ this.module = module;
118
+ this.resolver = resolver;
119
+ this.error = undefined; // the first exception that is not a refusal, thrown after the call
120
+ this.thrown = false;
121
+ }
122
+
123
+ // Text into the compilation's scratch arena: [pointer, length].
124
+ room(text) {
125
+ const module = this.module;
126
+ if (!text.isWellFormed()) throw refusal('TA_ERROR_INVALID', 'a string with a lone surrogate is not text');
127
+ const bytes = encoder.encode(text);
128
+ const at = module.call('ta_web_resolve_room', module.env, bytes.length) >>> 0;
129
+ if (at === 0) throw refusal('TA_ERROR_NO_MEMORY', 'no memory for a string');
130
+ module.bytes().set(bytes, at);
131
+ return [at, bytes.length];
132
+ }
133
+
134
+ // ta_web.resolve: base and source in the record's words 0-3; the answer
135
+ // in it (compile.c).
136
+ resolve() {
137
+ const module = this.module;
138
+ const w = module.words().slice(module.record, module.record + 4);
139
+ const base = module.string(w[0], w[1]), source = module.string(w[2], w[3]);
140
+ let text;
141
+ try {
142
+ text = this.resolver(base, source);
143
+ if (typeof text !== 'string') throw new TypeError('a resolver (base, source) => string returns a string');
144
+ const [at, length] = this.room(text);
145
+ module.words().set([TA_OK, w[2], w[3], at, length], module.record);
146
+ return TA_OK;
147
+ } catch (error) {
148
+ let message = '', line = 0, column = 0;
149
+ const position = (value) => (typeof value === 'number' && value >= 1 && value <= 4294967295 ? Math.trunc(value) : 0);
150
+ if (error instanceof ResolveError) {
151
+ message = this.text(error.message);
152
+ line = position(error.line);
153
+ column = position(error.column);
154
+ } else {
155
+ message = this.text(error);
156
+ this.raised(error);
157
+ }
158
+ module.words().set([TA_ERROR_INVALID, w[2], w[3], 0, 0, line, column, message[0], message[1]], module.record);
159
+ return TA_OK;
160
+ }
161
+ }
162
+
163
+ // `value` as text in the scratch arena; empty when it cannot be had (the
164
+ // compiler then gives its generic message).
165
+ text(value) {
166
+ try {
167
+ return this.room(String(value));
168
+ } catch {
169
+ return [0, 0];
170
+ }
171
+ }
172
+
173
+ // The first exception that is not a refusal (and the import guard's,
174
+ // for one of resolve() itself): kept, thrown after the call.
175
+ raised(error) {
176
+ if (this.thrown) return;
177
+ this.thrown = true;
178
+ this.error = error;
179
+ }
180
+ }
181
+
182
+ // ---- the syntax check -------------------------------------------------------------------------
183
+
184
+ const KIND = { CONDITION: 1, VALUE: 2, LOCATION: 3, SCRIPT: 4, STRING: 5, CONTENT: 6, ITEM: 7, GLOBAL_SCRIPT: 8 };
185
+ const VALUE_SHAPE = ["(function(){'use strict';return (\n", '\n);})', 'expr'];
186
+
187
+ // The shape an expression is checked in (the datamodel's own), or null
188
+ // for <content> (JSON, XML or text, not ECMAScript).
189
+ function shapeOf(kind) {
190
+ switch (kind) {
191
+ case KIND.CONDITION: return [VALUE_SHAPE[0], VALUE_SHAPE[1], 'cond'];
192
+ case KIND.VALUE:
193
+ case KIND.STRING: return VALUE_SHAPE;
194
+ case KIND.LOCATION: return ["(function(__v){'use strict';(\n", '\n) = __v;})', 'location'];
195
+ case KIND.ITEM: return ["(function(__v){'use strict';(\n", '\n) = __v;})', 'item'];
196
+ case KIND.GLOBAL_SCRIPT:
197
+ case KIND.SCRIPT: return ["(function(){'use strict';\n", '\n})', '<script>'];
198
+ default: return null;
199
+ }
200
+ }
201
+
202
+ // The engine's parser over one source: null when it parses, else
203
+ // [message, line, column] of its SyntaxError in the source given.
204
+ function makeChecker() {
205
+ const vm = globalThis.process?.getBuiltinModule?.('node:vm');
206
+ if (vm) {
207
+ return (source) => {
208
+ try {
209
+ new vm.Script(source, { filename: 'chart' }); // eslint-disable-line no-new
210
+ return null;
211
+ } catch (error) {
212
+ if (!(error instanceof SyntaxError)) return null;
213
+ const lines = String(error.stack).split('\n');
214
+ const at = /:(\d+)$/.exec(lines[0]);
215
+ const caret = lines.length > 2 ? lines[2].indexOf('^') : -1;
216
+ return [error.message, at ? Number(at[1]) : 2, caret >= 0 ? caret + 1 : 1];
217
+ }
218
+ };
219
+ }
220
+ const document = globalThis.document;
221
+ return (source) => {
222
+ try {
223
+ new Function(source); // eslint-disable-line no-new
224
+ return null;
225
+ } catch (error) {
226
+ if (!(error instanceof SyntaxError)) return null;
227
+ let line = 2, column = 1;
228
+ if (typeof document?.createElement === 'function') { // a page: where, from a <script> that does not parse
229
+ const listener = (event) => {
230
+ line = event.lineno - 1;
231
+ column = event.colno;
232
+ event.preventDefault();
233
+ };
234
+ globalThis.addEventListener('error', listener);
235
+ try {
236
+ const script = document.createElement('script');
237
+ script.text = `(function(){\n${source}\n})`;
238
+ (document.head ?? document.documentElement).appendChild(script);
239
+ script.remove();
240
+ } finally {
241
+ globalThis.removeEventListener('error', listener);
242
+ }
243
+ }
244
+ return [error.message, line, column];
245
+ }
246
+ };
247
+ }
248
+
249
+ let checker = null;
250
+
251
+ // The SyntaxErrors of the result's "ecmascript" charts as diagnostics.
252
+ function checkImage(module, result, errors) {
253
+ if (policyRefusal() !== null) return [];
254
+ checker ??= makeChecker();
255
+ const found = [];
256
+ const image = module.call('ta_web_image_open', module.env, result) >>> 0;
257
+ if (image === 0) return found; // core's to refuse
258
+ const charts = module.word(0);
259
+ for (let c = 0; c < charts; c++) {
260
+ const count = module.call('ta_web_image_chart', module.env, image, c);
261
+ const w = module.words().slice(module.record, module.record + 4);
262
+ if (module.string(w[0], w[1]) !== 'ecmascript') continue;
263
+ const file = module.string(w[2], w[3]);
264
+ for (let e = 0; e < count; e++) {
265
+ module.setWord(0, c);
266
+ if (module.call('ta_web_image_expression', module.env, image, e) !== 0) continue;
267
+ const x = module.words().slice(module.record, module.record + 6);
268
+ const info = { kind: x[1], line: x[2], column: x[3], source: module.string(x[4], x[5]) };
269
+ const shape = shapeOf(info.kind);
270
+ if (shape === null) continue;
271
+ const script = info.kind === KIND.SCRIPT || info.kind === KIND.GLOBAL_SCRIPT;
272
+ const source = script ? info.source : info.source.replace(/[; \t\n\r]+$/, '');
273
+ let failure = checker(shape[0] + source + shape[1]), label = 'SyntaxError: ';
274
+ if (failure === null && script) { // it parses: a top-level declaration the native datamodel refuses or keeps
275
+ const advice = application().advice(info.source);
276
+ if (advice !== null) [failure, label] = [[advice, 2, 1], ''];
277
+ }
278
+ if (failure === null) continue;
279
+ const [message, inShape] = failure;
280
+ let column = failure[2];
281
+ const lines = info.source.split('\n').length;
282
+ let sourceLine = inShape >= 2 ? inShape - 1 : 1;
283
+ if (sourceLine > lines) { // past the source: at its end
284
+ sourceLine = lines;
285
+ column = info.source.length - info.source.lastIndexOf('\n');
286
+ }
287
+ found.push(Object.freeze({
288
+ severity: errors ? 'error' : 'warning',
289
+ code: 0,
290
+ file,
291
+ line: info.line + sourceLine - 1,
292
+ column: sourceLine === 1 ? info.column : column,
293
+ message: `${shape[2]}: ${label}${message}`,
294
+ }));
295
+ }
296
+ }
297
+ return found;
298
+ }
299
+
300
+ function compileWith(manifest, [given, options], usage) {
301
+ let flags = 0, resolver;
302
+ if (options !== undefined) {
303
+ if (options === null || typeof options !== 'object') throw new TypeError('a compile call\'s options are an object: {resolver, warningsAsErrors}');
304
+ for (const key of Object.keys(options)) {
305
+ if (key !== 'resolver' && key !== 'warningsAsErrors') throw new TypeError('a compile call\'s options are {resolver, warningsAsErrors}');
306
+ }
307
+ resolver = options.resolver;
308
+ const werror = options.warningsAsErrors;
309
+ if (werror !== undefined && typeof werror !== 'boolean') throw new TypeError('warningsAsErrors is a boolean');
310
+ if (werror) flags |= WERROR;
311
+ }
312
+ if (resolver !== undefined && resolver !== null && typeof resolver !== 'function') {
313
+ throw new TypeError('a resolver is a function (base, source) => string');
314
+ }
315
+ const module = instance();
316
+ const scratch = module.scratch;
317
+ const sources = manifest ? [given] : given;
318
+ if (!manifest && !Array.isArray(given)) throw new TypeError(usage);
319
+ const resolving = typeof resolver === 'function' ? new Resolving(module, resolver) : null;
320
+ const id = resolving ? module.register(resolving) : 0;
321
+ try {
322
+ return module.scoped(scratch, () => {
323
+ const count = sources.length;
324
+ const pairs = module.room(scratch, 16 * (count || 1)) >>> 2;
325
+ for (let i = 0; i < count; i++) {
326
+ const source = sources[i];
327
+ if (source === null || typeof source !== 'object') throw new TypeError(usage);
328
+ if (typeof source.name !== 'string') throw new TypeError(usage);
329
+ const [n, nl] = module.text(scratch, source.name);
330
+ if (typeof source.text !== 'string') throw new TypeError(usage);
331
+ const [t, tl] = module.text(scratch, source.text);
332
+ module.words().set([n, nl, t, tl], pairs + 4 * i);
333
+ }
334
+ module.words().set([pairs << 2, count, flags, resolving ? 1 : 0, id], module.record);
335
+ const result = module.call('ta_web_compile', module.env, manifest ? 1 : 0) >>> 0;
336
+ const status = module.word(0) | 0;
337
+ let diagnostics, first;
338
+ try {
339
+ const list = [];
340
+ const n = result ? module.call('ta_web_compile_diagnostic_count', result) : 0;
341
+ for (let i = 0; i < n; i++) {
342
+ const diagnostic = diagnosticAt(module, result, i);
343
+ list.push(diagnostic);
344
+ if (first === undefined && diagnostic.severity === 'error') {
345
+ first = `${diagnostic.file}:${diagnostic.line}:${diagnostic.column}: error: ${diagnostic.message}`;
346
+ }
347
+ }
348
+ diagnostics = Object.freeze(list);
349
+ } catch (error) {
350
+ if (result) module.call('ta_web_compile_free', result);
351
+ throw error;
352
+ }
353
+ if (resolving?.thrown || status !== TA_OK || first !== undefined) {
354
+ if (result) module.call('ta_web_compile_free', result); // freed before it throws
355
+ if (resolving?.thrown) throw resolving.error;
356
+ if (status === TA_ERROR_NO_MEMORY) throw refusal('TA_ERROR_NO_MEMORY', 'the compiler\'s allocator refused memory');
357
+ const name = module.statusName(status === TA_OK ? TA_ERROR_INVALID : status);
358
+ throw new CompileError(first ?? name, { diagnostics, status: name });
359
+ }
360
+ // the charts' ECMAScript, parsed: warnings, or errors with warningsAsErrors
361
+ let found;
362
+ try {
363
+ found = checkImage(module, result, (flags & WERROR) !== 0);
364
+ } catch (error) {
365
+ module.call('ta_web_compile_free', result);
366
+ throw error;
367
+ }
368
+ if (found.length > 0) diagnostics = Object.freeze([...diagnostics, ...found]);
369
+ if (found.length > 0 && (flags & WERROR) !== 0) {
370
+ module.call('ta_web_compile_free', result); // freed before it throws
371
+ const d = found[0];
372
+ throw new CompileError(`${d.file}:${d.line}:${d.column}: error: ${d.message}`, { diagnostics, status: module.statusName(TA_ERROR_INVALID) });
373
+ }
374
+ return new Compiled(MAKING, module, result, diagnostics);
375
+ });
376
+ } finally {
377
+ if (id) module.unregister(id);
378
+ }
379
+ }
380
+
381
+ // each takes (sources or manifest, options?): their lengths are 2
382
+ export function compileCharts(sources, options) { // eslint-disable-line no-unused-vars
383
+ return compileWith(false, [...arguments], 'compileCharts(sources, options?): sources an array of {name, text} of strings');
384
+ }
385
+
386
+ export function compileSystem(manifest, options) { // eslint-disable-line no-unused-vars
387
+ return compileWith(true, [...arguments], 'compileSystem(manifest, options?): the manifest a {name, text} of strings');
388
+ }
389
+
390
+ export { TinyactorsError };