paseo-plugin-genui 0.1.0 → 0.1.2

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.
@@ -13,6 +13,7 @@ import {
13
13
  stateMismatch,
14
14
  type Kind,
15
15
  } from "./validate";
16
+ import { defineClass } from "./define-class";
16
17
 
17
18
  /** Longest string any operation may produce; repeated doubling would otherwise exhaust memory. */
18
19
  const MAX_STRING_LENGTH = 100_000;
@@ -21,34 +22,57 @@ const MAX_EVAL_DEPTH = 1_000;
21
22
  /** Data for callers that load no files: every `Load` reports it is still loading, every `Snippet` shows its loading state. */
22
23
  const NO_DATA: ReadonlyMap<string, LoadedData> = new Map();
23
24
 
24
- abstract class EvalFailure extends Error {
25
- constructor(
26
- readonly pos: Pos,
27
- message: string,
28
- ) {
29
- super(message);
30
- }
25
+ interface EvalFailureFields extends Error {
26
+ pos: Pos;
31
27
  }
32
28
 
29
+ const EvalFailure = defineClass(
30
+ function (this: EvalFailureFields, pos: Pos, message: string): void {
31
+ this.pos = pos;
32
+ this.message = message;
33
+ },
34
+ undefined,
35
+ Error,
36
+ );
37
+ type EvalFailure = InstanceType<typeof EvalFailure>;
38
+
33
39
  /** A problem local to one component: it becomes an Error node, siblings still render. */
34
- class RuntimeError extends EvalFailure {}
40
+ const RuntimeError = defineClass(
41
+ function (this: EvalFailureFields, pos: Pos, message: string): void {
42
+ this.pos = pos;
43
+ this.message = message;
44
+ },
45
+ undefined,
46
+ EvalFailure,
47
+ );
48
+ type RuntimeError = InstanceType<typeof RuntimeError>;
35
49
 
36
50
  /** A resource limit: evaluation stops. */
37
- class LimitError extends EvalFailure {}
51
+ const LimitError = defineClass(
52
+ function (this: EvalFailureFields, pos: Pos, message: string): void {
53
+ this.pos = pos;
54
+ this.message = message;
55
+ },
56
+ undefined,
57
+ EvalFailure,
58
+ );
59
+ type LimitError = InstanceType<typeof LimitError>;
38
60
 
39
61
  /**
40
62
  * A `Load` whose file is still being read. It travels like a RuntimeError, so
41
63
  * whatever used the value waits too, but the component becomes a Loading
42
64
  * placeholder instead of an Error, and it is no diagnostic.
43
65
  */
44
- class LoadPending extends RuntimeError {
45
- constructor(
46
- pos: Pos,
47
- readonly path: string,
48
- ) {
49
- super(pos, `Loading ${path}…`);
50
- }
51
- }
66
+ const LoadPending = defineClass(
67
+ function (this: EvalFailureFields & { path: string }, pos: Pos, path: string): void {
68
+ this.pos = pos;
69
+ this.message = `Loading ${path}…`;
70
+ this.path = path;
71
+ },
72
+ undefined,
73
+ RuntimeError,
74
+ );
75
+ type LoadPending = InstanceType<typeof LoadPending>;
52
76
 
53
77
  function kindOf(value: Value): Kind {
54
78
  if (value === null) return "null";
@@ -159,542 +183,554 @@ interface Scope {
159
183
  readonly parent: Scope | null;
160
184
  }
161
185
 
162
- class Interpreter {
163
- readonly diagnostics = new DiagnosticList();
164
- private steps = 0;
165
- private nodes = 0;
166
- private depth = 0;
167
- /** `#index` per enclosing map iteration, appended to node keys. */
168
- private suffix = "";
169
- private readonly cache = new Map<string, { readonly value: Value } | { readonly error: RuntimeError }>();
170
-
171
- constructor(
172
- private readonly program: Program,
173
- private readonly state: UiState,
174
- private readonly data: ReadonlyMap<string, LoadedData>,
175
- ) {}
176
-
177
- /** Reports a failure (a load still in flight is none) and restores the evaluation context saved before it; rethrows anything else. */
178
- recover(error: unknown, depth: number, suffix: string): EvalFailure {
179
- if (!(error instanceof EvalFailure)) throw error;
180
- this.depth = depth;
181
- this.suffix = suffix;
182
- if (!(error instanceof LoadPending)) this.diagnostics.report(error.pos, error.message);
183
- return error;
184
- }
186
+ interface InterpreterFields {
187
+ diagnostics: DiagnosticList;
188
+ steps: number;
189
+ nodes: number;
190
+ depth: number;
191
+ suffix: string;
192
+ cache: Map<string, { readonly value: Value } | { readonly error: RuntimeError }>;
193
+ program: Program;
194
+ state: UiState;
195
+ data: ReadonlyMap<string, LoadedData>;
196
+ }
185
197
 
186
- expr(expr: Expr, scope: Scope | null): Value {
187
- if (++this.steps > LIMITS.steps) {
188
- throw new LimitError(expr.pos, `the UI needs more than ${LIMITS.steps} evaluation steps; simplify it`);
189
- }
190
- if (++this.depth > MAX_EVAL_DEPTH) throw new LimitError(expr.pos, "expressions are nested too deeply");
191
- const value = this.compute(expr, scope);
192
- this.depth--;
193
- return value;
194
- }
198
+ const Interpreter = defineClass(
199
+ function (this: InterpreterFields, program: Program, state: UiState, data: ReadonlyMap<string, LoadedData>): void {
200
+ this.program = program;
201
+ this.state = state;
202
+ this.data = data;
203
+ this.diagnostics = new DiagnosticList();
204
+ this.steps = 0;
205
+ this.nodes = 0;
206
+ this.depth = 0;
207
+ this.suffix = "";
208
+ this.cache = new Map<string, { readonly value: Value } | { readonly error: RuntimeError }>();
209
+ },
210
+ {
211
+ /** Reports a failure (a load still in flight is none) and restores the evaluation context saved before it; rethrows anything else. */
212
+ recover(error: unknown, depth: number, suffix: string): EvalFailure {
213
+ if (!(error instanceof EvalFailure)) throw error;
214
+ this.depth = depth;
215
+ this.suffix = suffix;
216
+ if (!(error instanceof LoadPending)) this.diagnostics.report(error.pos, error.message);
217
+ return error;
218
+ },
195
219
 
196
- private compute(expr: Expr, scope: Scope | null): Value {
197
- switch (expr.type) {
198
- case "literal":
199
- return expr.value;
200
- case "template": {
201
- let text = expr.quasis[0];
202
- expr.parts.forEach((part, index) => {
203
- text += toText(this.expr(part, scope), part.pos) + expr.quasis[index + 1];
204
- });
205
- return checkString(text, expr.pos);
220
+ expr(expr: Expr, scope: Scope | null): Value {
221
+ if (++this.steps > LIMITS.steps) {
222
+ throw new LimitError(expr.pos, `the UI needs more than ${LIMITS.steps} evaluation steps; simplify it`);
206
223
  }
207
- case "state":
208
- return Object.hasOwn(this.state, expr.name) ? this.state[expr.name] : null;
209
- case "ident":
210
- for (let current = scope; current !== null; current = current.parent) {
211
- if (current.name === expr.name) return current.value;
224
+ if (++this.depth > MAX_EVAL_DEPTH) throw new LimitError(expr.pos, "expressions are nested too deeply");
225
+ const value = this.compute(expr, scope);
226
+ this.depth--;
227
+ return value;
228
+ },
229
+
230
+ compute(expr: Expr, scope: Scope | null): Value {
231
+ switch (expr.type) {
232
+ case "literal":
233
+ return expr.value;
234
+ case "template": {
235
+ let text = expr.quasis[0];
236
+ expr.parts.forEach((part, index) => {
237
+ text += toText(this.expr(part, scope), part.pos) + expr.quasis[index + 1];
238
+ });
239
+ return checkString(text, expr.pos);
212
240
  }
213
- return this.named(expr.name, expr.pos);
214
- case "list":
215
- return checkLength(
216
- expr.items.map((item) => this.expr(item, scope)),
217
- expr.pos,
218
- );
219
- case "object": {
220
- const object: Record<string, Value> = {};
221
- for (const entry of expr.entries) {
222
- const value = this.expr(entry.value, scope);
223
- if (entry.key === "kind" && (value === "node" || value === "action" || value === "binding")) {
224
- throw new RuntimeError(entry.pos, `\`kind: "${value}"\` is reserved; use another key or value`);
241
+ case "state":
242
+ return Object.hasOwn(this.state, expr.name) ? this.state[expr.name] : null;
243
+ case "ident":
244
+ for (let current = scope; current !== null; current = current.parent) {
245
+ if (current.name === expr.name) return current.value;
225
246
  }
226
- object[entry.key] = value;
247
+ return this.named(expr.name, expr.pos);
248
+ case "list":
249
+ return checkLength(
250
+ expr.items.map((item) => this.expr(item, scope)),
251
+ expr.pos,
252
+ );
253
+ case "object": {
254
+ const object: Record<string, Value> = {};
255
+ for (const entry of expr.entries) {
256
+ const value = this.expr(entry.value, scope);
257
+ if (entry.key === "kind" && (value === "node" || value === "action" || value === "binding")) {
258
+ throw new RuntimeError(entry.pos, `\`kind: "${value}"\` is reserved; use another key or value`);
259
+ }
260
+ object[entry.key] = value;
261
+ }
262
+ return object;
263
+ }
264
+ case "unary": {
265
+ const operand = this.expr(expr.operand, scope);
266
+ return expr.op === "!" ? !truthy(operand) : finite(-this.number(operand, expr.pos, "`-`"));
227
267
  }
228
- return object;
268
+ case "binary":
269
+ return this.binary(expr, scope);
270
+ case "conditional":
271
+ return truthy(this.expr(expr.test, scope)) ? this.expr(expr.then, scope) : this.expr(expr.else, scope);
272
+ case "member":
273
+ return this.member(this.expr(expr.object, scope), expr.name, expr.pos);
274
+ case "index":
275
+ return this.index(this.expr(expr.object, scope), this.expr(expr.index, scope), expr.pos);
276
+ case "call": {
277
+ const component = COMPONENT_SPECS.get(expr.name);
278
+ if (component !== undefined) return this.component(expr, component, scope);
279
+ const action = ACTION_SPECS.get(expr.name);
280
+ if (action !== undefined) return this.action(expr, action, scope);
281
+ const own = this.program.named.get(expr.name)?.value;
282
+ if (own?.type === "arrow") return this.callOwn(expr, own, scope);
283
+ return this.callFunction(expr, scope);
284
+ }
285
+ case "method":
286
+ return this.method(expr, scope);
287
+ case "arrow":
288
+ throw new RuntimeError(
289
+ expr.pos,
290
+ "arrow functions can only be declared as a named function (`share = p => ...`) or passed to map, filter, find, some or every",
291
+ );
229
292
  }
230
- case "unary": {
231
- const operand = this.expr(expr.operand, scope);
232
- return expr.op === "!" ? !truthy(operand) : finite(-this.number(operand, expr.pos, "`-`"));
293
+ },
294
+
295
+ named(name: string, pos: Pos): Value {
296
+ const cached = this.cache.get(name);
297
+ if (cached !== undefined) {
298
+ if ("error" in cached) throw cached.error;
299
+ return cached.value;
233
300
  }
234
- case "binary":
235
- return this.binary(expr, scope);
236
- case "conditional":
237
- return truthy(this.expr(expr.test, scope)) ? this.expr(expr.then, scope) : this.expr(expr.else, scope);
238
- case "member":
239
- return this.member(this.expr(expr.object, scope), expr.name, expr.pos);
240
- case "index":
241
- return this.index(this.expr(expr.object, scope), this.expr(expr.index, scope), expr.pos);
242
- case "call": {
243
- const component = COMPONENT_SPECS.get(expr.name);
244
- if (component !== undefined) return this.component(expr, component, scope);
245
- const action = ACTION_SPECS.get(expr.name);
246
- if (action !== undefined) return this.action(expr, action, scope);
247
- const own = this.program.named.get(expr.name)?.value;
248
- if (own?.type === "arrow") return this.callOwn(expr, own, scope);
249
- return this.callFunction(expr, scope);
301
+ const decl = this.program.named.get(name);
302
+ if (decl === undefined) throw new RuntimeError(pos, `\`${name}\` is not defined`);
303
+ if (decl.value.type === "arrow") throw new RuntimeError(pos, `\`${name}\` is a function; call it, as in \`${name}(...)\``);
304
+ // Named values are top-level: their nodes never take the keys of the map that reads them.
305
+ const suffix = this.suffix;
306
+ this.suffix = "";
307
+ try {
308
+ const value = this.expr(decl.value, null);
309
+ this.cache.set(name, { value });
310
+ this.suffix = suffix;
311
+ return value;
312
+ } catch (error) {
313
+ if (error instanceof RuntimeError) this.cache.set(name, { error });
314
+ throw error;
250
315
  }
251
- case "method":
252
- return this.method(expr, scope);
253
- case "arrow":
254
- throw new RuntimeError(
255
- expr.pos,
256
- "arrow functions can only be declared as a named function (`share = p => ...`) or passed to map, filter, find, some or every",
257
- );
258
- }
259
- }
316
+ },
260
317
 
261
- private named(name: string, pos: Pos): Value {
262
- const cached = this.cache.get(name);
263
- if (cached !== undefined) {
264
- if ("error" in cached) throw cached.error;
265
- return cached.value;
266
- }
267
- const decl = this.program.named.get(name);
268
- if (decl === undefined) throw new RuntimeError(pos, `\`${name}\` is not defined`);
269
- if (decl.value.type === "arrow") throw new RuntimeError(pos, `\`${name}\` is a function; call it, as in \`${name}(...)\``);
270
- // Named values are top-level: their nodes never take the keys of the map that reads them.
271
- const suffix = this.suffix;
272
- this.suffix = "";
273
- try {
274
- const value = this.expr(decl.value, null);
275
- this.cache.set(name, { value });
276
- this.suffix = suffix;
318
+ number(value: Value, pos: Pos, label: string): number {
319
+ if (typeof value !== "number") throw new RuntimeError(pos, `${label} needs a number, got ${describe(value)}`);
277
320
  return value;
278
- } catch (error) {
279
- if (error instanceof RuntimeError) this.cache.set(name, { error });
280
- throw error;
281
- }
282
- }
321
+ },
283
322
 
284
- private number(value: Value, pos: Pos, label: string): number {
285
- if (typeof value !== "number") throw new RuntimeError(pos, `${label} needs a number, got ${describe(value)}`);
286
- return value;
287
- }
288
-
289
- private text(value: Value, pos: Pos, label: string): string {
290
- if (typeof value !== "string") throw new RuntimeError(pos, `${label} needs text, got ${describe(value)}`);
291
- return value;
292
- }
293
-
294
- private digits(value: Value, pos: Pos, label: string): number {
295
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 20) {
296
- throw new RuntimeError(pos, `${label} digits must be a whole number from 0 to 20`);
297
- }
298
- return value;
299
- }
300
-
301
- private binary(expr: Extract<Expr, { type: "binary" }>, scope: Scope | null): Value {
302
- const op = expr.op;
303
- const left = this.expr(expr.left, scope);
304
- if (op === "&&") return truthy(left) ? this.expr(expr.right, scope) : left;
305
- if (op === "||") return truthy(left) ? left : this.expr(expr.right, scope);
306
- if (op === "??") return left === null ? this.expr(expr.right, scope) : left;
307
- const right = this.expr(expr.right, scope);
308
- switch (op) {
309
- case "==":
310
- case "===":
311
- return left === right;
312
- case "!=":
313
- case "!==":
314
- return left !== right;
315
- case "+":
316
- if (typeof left === "string" || typeof right === "string") {
317
- return checkString(toText(left, expr.left.pos) + toText(right, expr.right.pos), expr.pos);
318
- }
319
- if (typeof left === "number" && typeof right === "number") return finite(left + right);
320
- throw new RuntimeError(expr.pos, `\`+\` needs numbers or text, got ${describe(left)} and ${describe(right)}`);
321
- case "<":
322
- case "<=":
323
- case ">":
324
- case ">=":
325
- if (typeof left === "number" && typeof right === "number") return compare(op, left, right);
326
- if (typeof left === "string" && typeof right === "string") return compare(op, left, right);
327
- throw new RuntimeError(expr.pos, `\`${op}\` compares two numbers or two texts, got ${describe(left)} and ${describe(right)}`);
328
- }
329
- const a = this.number(left, expr.left.pos, `\`${op}\``);
330
- const b = this.number(right, expr.right.pos, `\`${op}\``);
331
- switch (op) {
332
- case "-":
333
- return finite(a - b);
334
- case "*":
335
- return finite(a * b);
336
- case "/":
337
- return finite(a / b);
338
- case "%":
339
- return finite(a % b);
340
- case "**":
341
- return finite(a ** b);
342
- }
343
- }
344
-
345
- private member(object: Value, name: string, pos: Pos): Value {
346
- if (object === null) return null;
347
- if (isPlainObject(object)) {
348
- // Narrowing keeps structurally compatible Action shapes; widen to read by key.
349
- const record: PlainObject = object;
350
- return Object.hasOwn(record, name) ? record[name] : null;
351
- }
352
- if (isList(object) || typeof object === "string") {
353
- if (name === "length") return object.length;
354
- throw new RuntimeError(pos, `${describe(object)} only has \`.length\`; \`.${name}\` does not exist`);
355
- }
356
- throw new RuntimeError(pos, `cannot read \`.${name}\` of ${describe(object)}`);
357
- }
323
+ text(value: Value, pos: Pos, label: string): string {
324
+ if (typeof value !== "string") throw new RuntimeError(pos, `${label} needs text, got ${describe(value)}`);
325
+ return value;
326
+ },
358
327
 
359
- private index(object: Value, index: Value, pos: Pos): Value {
360
- if (object === null) return null;
361
- if (isList(object) || typeof object === "string") {
362
- const at = this.number(index, pos, "an index");
363
- return Number.isInteger(at) && at >= 0 && at < object.length ? object[at] : null;
364
- }
365
- if (isPlainObject(object)) {
366
- const record: PlainObject = object;
367
- const key = this.text(index, pos, "an object key");
368
- if ((FORBIDDEN_PROPERTIES as readonly string[]).includes(key)) {
369
- throw new RuntimeError(pos, `\`${key}\` is not accessible`);
328
+ digits(value: Value, pos: Pos, label: string): number {
329
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 20) {
330
+ throw new RuntimeError(pos, `${label} digits must be a whole number from 0 to 20`);
370
331
  }
371
- return Object.hasOwn(record, key) ? record[key] : null;
372
- }
373
- throw new RuntimeError(pos, `cannot index ${describe(object)}`);
374
- }
375
-
376
- private node(type: UiNode["type"], key: string, props: Record<string, Value>, pos: Pos): UiNode {
377
- if (++this.nodes > LIMITS.nodes) throw new LimitError(pos, `the UI has more than ${LIMITS.nodes} components`);
378
- return { kind: "node", type, key, props };
379
- }
380
-
381
- private component(call: CallExpr, spec: ComponentSpec, scope: Scope | null): UiNode {
382
- const key = `${call.pos.line}:${call.pos.column}${this.suffix}`;
383
- // COMPONENT_SPECS only holds catalog names.
384
- const type = call.name as ComponentName;
385
- const depth = this.depth;
386
- const suffix = this.suffix;
387
- try {
388
- const props: Record<string, Value> = {};
389
- spec.params.forEach((param, index) => {
390
- const arg = argument(call, spec.params, index);
391
- if (arg === undefined) return;
392
- const value = this.param(param, arg, scope, `${call.name} ${param.name}`, key);
393
- if (value !== undefined) props[param.name] = value;
394
- });
395
- return this.node(type, key, type === "Snippet" ? this.snippet(props) : props, call.pos);
396
- } catch (error) {
397
- if (!(error instanceof RuntimeError)) throw error;
398
- const failure = this.recover(error, depth, suffix);
399
- return failure instanceof LoadPending
400
- ? this.node("Loading", key, { path: failure.path, component: type }, call.pos)
401
- : this.node("Error", key, { message: failure.message }, call.pos);
402
- }
403
- }
404
-
405
- /**
406
- * Snippet props: the requested range plus its lines from the raw file. A file
407
- * still loading is `code: null` (the renderer shows a placeholder), and a
408
- * file or range problem is `error`, never an Error node.
409
- */
410
- private snippet(props: Readonly<Record<string, Value>>): Record<string, Value> {
411
- // `path` is a required string param and the others optional numbers, so these are the evaluated values.
412
- const path = typeof props.path === "string" ? props.path : "";
413
- const from = typeof props.from === "number" ? props.from : null;
414
- const to = typeof props.to === "number" ? props.to : null;
415
- const loaded = this.data.get(dataKey({ path, raw: true }));
416
- const rangeError = snippetRangeError(from, to);
417
- let shown: { code: string | null; error: string | null };
418
- if (rangeError !== null) shown = { code: null, error: rangeError };
419
- else if (loaded === undefined) shown = { code: null, error: null };
420
- else if (!loaded.ok) shown = { code: null, error: loaded.error };
421
- else if (typeof loaded.value !== "string") shown = { code: null, error: "not a text file" };
422
- else shown = snippetLines(loaded.value, from, to);
423
- return { path, from, to, code: shown.code, error: shown.error, language: languageOf(path) };
424
- }
425
-
426
- /** Evaluates and normalizes one argument; `undefined` means an optional param passed as null. */
427
- private param(param: ParamSpec, arg: Expr, scope: Scope | null, label: string, key: string): Value | undefined {
428
- if (param.kind === "binding") {
429
- if (arg.type !== "state") throw new RuntimeError(arg.pos, `${label} must be a state variable written as \`$name\``);
430
- const value = Object.hasOwn(this.state, arg.name) ? this.state[arg.name] : null;
431
- // Set() or a computed initial value can still give the state the wrong
432
- // type; a lossless reading keeps the input working, anything else fails.
433
- const mismatch = stateMismatch(label, param, arg.name, kindOf(value), "holds");
434
- const coerced = mismatch === null ? value : coerceState(param.holds, value);
435
- if (coerced === undefined) throw new RuntimeError(arg.pos, mismatch!);
436
- const binding: Binding = { kind: "binding", name: arg.name, value: coerced };
437
- return binding;
438
- }
439
- const value = this.expr(arg, scope);
440
- if (param.kind === "nodes") return this.children(value, arg.pos, label, key);
441
- if (param.kind === "actions") return this.actions(value, arg.pos, label);
442
- if (value === null) {
443
- if (param.optional) return undefined;
444
- if (param.nullable || param.kind === "any") return null;
445
- }
446
- switch (param.kind) {
447
- case "string":
448
- case "text":
449
- if (value !== null && typeof value !== "object") return String(value);
450
- break;
451
- case "number":
452
- if (typeof value === "number") return value;
453
- break;
454
- case "boolean":
455
- if (typeof value === "boolean") return value;
456
- break;
457
- case "enum": {
458
- const values = param.values ?? [];
459
- if (typeof value === "string" && values.includes(value)) return value;
460
- const got = typeof value === "string" ? JSON.stringify(value) : describe(value);
461
- throw new RuntimeError(arg.pos, `${label} must be one of ${values.join(", ")}; got ${got}`);
332
+ return value;
333
+ },
334
+
335
+ binary(expr: Extract<Expr, { type: "binary" }>, scope: Scope | null): Value {
336
+ const op = expr.op;
337
+ const left = this.expr(expr.left, scope);
338
+ if (op === "&&") return truthy(left) ? this.expr(expr.right, scope) : left;
339
+ if (op === "||") return truthy(left) ? left : this.expr(expr.right, scope);
340
+ if (op === "??") return left === null ? this.expr(expr.right, scope) : left;
341
+ const right = this.expr(expr.right, scope);
342
+ switch (op) {
343
+ case "==":
344
+ case "===":
345
+ return left === right;
346
+ case "!=":
347
+ case "!==":
348
+ return left !== right;
349
+ case "+":
350
+ if (typeof left === "string" || typeof right === "string") {
351
+ return checkString(toText(left, expr.left.pos) + toText(right, expr.right.pos), expr.pos);
352
+ }
353
+ if (typeof left === "number" && typeof right === "number") return finite(left + right);
354
+ throw new RuntimeError(expr.pos, `\`+\` needs numbers or text, got ${describe(left)} and ${describe(right)}`);
355
+ case "<":
356
+ case "<=":
357
+ case ">":
358
+ case ">=":
359
+ if (typeof left === "number" && typeof right === "number") return compare(op, left, right);
360
+ if (typeof left === "string" && typeof right === "string") return compare(op, left, right);
361
+ throw new RuntimeError(expr.pos, `\`${op}\` compares two numbers or two texts, got ${describe(left)} and ${describe(right)}`);
462
362
  }
463
- case "list":
464
- if (isList(value)) return value;
465
- break;
466
- case "series": {
467
- const isNumbers = (item: Value) => isList(item) && item.every((n) => typeof n === "number" || n === null);
468
- if (isNumbers(value) || (isPlainObject(value) && Object.values(value).every(isNumbers))) return value;
469
- break;
363
+ const a = this.number(left, expr.left.pos, `\`${op}\``);
364
+ const b = this.number(right, expr.right.pos, `\`${op}\``);
365
+ switch (op) {
366
+ case "-":
367
+ return finite(a - b);
368
+ case "*":
369
+ return finite(a * b);
370
+ case "/":
371
+ return finite(a / b);
372
+ case "%":
373
+ return finite(a % b);
374
+ case "**":
375
+ return finite(a ** b);
470
376
  }
471
- case "any":
472
- return value;
473
- }
474
- throw new RuntimeError(arg.pos, `${label} needs ${EXPECTED[param.kind]}, got ${describe(value)}`);
475
- }
476
-
477
- /** Flattens children: strings/numbers become Text nodes, null/false are dropped. */
478
- children(value: Value, pos: Pos, label: string, key: string): UiNode[] {
479
- const out: UiNode[] = [];
480
- const visit = (item: Value): void => {
481
- if (item === null || item === false) return;
482
- if (typeof item === "string" || typeof item === "number") {
483
- out.push(this.node("Text", `${key}.${out.length}`, { text: String(item) }, pos));
484
- } else if (isList(item)) {
485
- for (const child of item) visit(child);
486
- } else if (isNode(item)) {
487
- out.push(item);
488
- } else {
489
- throw new RuntimeError(pos, `${label} must be components or text, got ${describe(item)}`);
377
+ },
378
+
379
+ member(object: Value, name: string, pos: Pos): Value {
380
+ if (object === null) return null;
381
+ if (isPlainObject(object)) {
382
+ // Narrowing keeps structurally compatible Action shapes; widen to read by key.
383
+ const record: PlainObject = object;
384
+ return Object.hasOwn(record, name) ? record[name] : null;
490
385
  }
491
- };
492
- visit(value);
493
- return out;
494
- }
495
-
496
- private actions(value: Value, pos: Pos, label: string): Action[] {
497
- const out: Action[] = [];
498
- const visit = (item: Value): void => {
499
- if (item === null || item === false) return;
500
- if (isList(item)) {
501
- for (const child of item) visit(child);
502
- } else if (isAction(item)) {
503
- out.push(item);
504
- } else {
505
- throw new RuntimeError(pos, `${label} takes actions such as Send("..."), got ${describe(item)}`);
386
+ if (isList(object) || typeof object === "string") {
387
+ if (name === "length") return object.length;
388
+ throw new RuntimeError(pos, `${describe(object)} only has \`.length\`; \`.${name}\` does not exist`);
506
389
  }
507
- };
508
- visit(value);
509
- return out;
510
- }
511
-
512
- private action(call: CallExpr, spec: ComponentSpec, scope: Scope | null): Action {
513
- // Every action has a required first param; the validator guarantees it is present.
514
- const first = argument(call, spec.params, 0)!;
515
- if (call.name === "Set") {
516
- if (first.type !== "state") throw new RuntimeError(first.pos, "Set needs a state variable written as `$name`");
517
- const second = argument(call, spec.params, 1)!;
518
- return { kind: "action", type: "set", name: first.name, value: this.expr(second, scope) };
519
- }
520
- const value = this.expr(first, scope);
521
- if (value === null || typeof value === "object") {
522
- throw new RuntimeError(first.pos, `${call.name} needs text, got ${describe(value)}`);
523
- }
524
- const text = String(value);
525
- switch (call.name) {
526
- case "Send":
527
- return { kind: "action", type: "send", text };
528
- case "Copy":
529
- return { kind: "action", type: "copy", text };
530
- case "OpenUrl":
531
- if (!/^https?:\/\//i.test(text)) throw new RuntimeError(first.pos, "OpenUrl needs an http:// or https:// URL");
532
- return { kind: "action", type: "openUrl", url: text };
533
- }
534
- throw new RuntimeError(call.pos, `unknown action \`${call.name}\``);
535
- }
536
-
537
- /** Numbers in a list; nulls are skipped. */
538
- private numbers(value: Value, pos: Pos, label: string): number[] {
539
- if (!isList(value)) throw new RuntimeError(pos, `${label} needs a list of numbers, got ${describe(value)}`);
540
- const out: number[] = [];
541
- for (const item of value) if (item !== null) out.push(this.number(item, pos, label));
542
- return out;
543
- }
544
-
545
- private callFunction(call: CallExpr, scope: Scope | null): Value {
546
- const args = call.args.map((arg) => this.expr(arg, scope));
547
- const name = call.name;
548
- const numberAt = (index: number) => this.number(args[index], call.args[index].pos, `${name}()`);
549
- const digitsAt = (index: number) =>
550
- index < args.length ? this.digits(args[index], call.args[index].pos, `${name}()`) : undefined;
551
- switch (name) {
552
- case "round":
553
- return finite(roundTo(numberAt(0), digitsAt(1) ?? 0));
554
- case "fmt":
555
- return fmt(numberAt(0), digitsAt(1));
556
- case "abs":
557
- return Math.abs(numberAt(0));
558
- case "floor":
559
- return Math.floor(numberAt(0));
560
- case "ceil":
561
- return Math.ceil(numberAt(0));
562
- case "sqrt":
563
- return finite(Math.sqrt(numberAt(0)));
564
- case "pow":
565
- return finite(numberAt(0) ** numberAt(1));
566
- case "sum":
567
- return finite(this.numbers(args[0], call.args[0].pos, "sum()").reduce((total, n) => total + n, 0));
568
- case "min":
569
- case "max": {
570
- const values =
571
- args.length === 1 && isList(args[0])
572
- ? this.numbers(args[0], call.args[0].pos, `${name}()`)
573
- : args.map((_, index) => numberAt(index));
574
- if (values.length === 0) return null;
575
- return name === "min" ? Math.min(...values) : Math.max(...values);
390
+ throw new RuntimeError(pos, `cannot read \`.${name}\` of ${describe(object)}`);
391
+ },
392
+
393
+ index(object: Value, index: Value, pos: Pos): Value {
394
+ if (object === null) return null;
395
+ if (isList(object) || typeof object === "string") {
396
+ const at = this.number(index, pos, "an index");
397
+ return Number.isInteger(at) && at >= 0 && at < object.length ? object[at] : null;
576
398
  }
577
- case "keys":
578
- case "values":
579
- case "entries": {
580
- const object = args[0];
581
- if (!isPlainObject(object)) throw new RuntimeError(call.args[0].pos, `${name}() needs an object, got ${describe(object)}`);
582
- const pairs = Object.entries(object);
583
- return checkLength(
584
- name === "keys" ? pairs.map(([key]) => key) : name === "values" ? pairs.map(([, value]) => value) : pairs,
585
- call.pos,
586
- );
399
+ if (isPlainObject(object)) {
400
+ const record: PlainObject = object;
401
+ const key = this.text(index, pos, "an object key");
402
+ if ((FORBIDDEN_PROPERTIES as readonly string[]).includes(key)) {
403
+ throw new RuntimeError(pos, `\`${key}\` is not accessible`);
404
+ }
405
+ return Object.hasOwn(record, key) ? record[key] : null;
587
406
  }
588
- case "Load": {
589
- const path = this.text(args[0], call.args[0].pos, "Load()");
590
- const loaded = this.data.get(dataKey({ path, raw: false }));
591
- if (loaded === undefined) throw new LoadPending(call.pos, path);
592
- if (!loaded.ok) throw new RuntimeError(call.pos, `Couldn't load ${path}: ${loaded.error}`);
593
- return loaded.value;
407
+ throw new RuntimeError(pos, `cannot index ${describe(object)}`);
408
+ },
409
+
410
+ node(type: UiNode["type"], key: string, props: Record<string, Value>, pos: Pos): UiNode {
411
+ if (++this.nodes > LIMITS.nodes) throw new LimitError(pos, `the UI has more than ${LIMITS.nodes} components`);
412
+ return { kind: "node", type, key, props };
413
+ },
414
+
415
+ component(call: CallExpr, spec: ComponentSpec, scope: Scope | null): UiNode {
416
+ const key = `${call.pos.line}:${call.pos.column}${this.suffix}`;
417
+ // COMPONENT_SPECS only holds catalog names.
418
+ const type = call.name as ComponentName;
419
+ const depth = this.depth;
420
+ const suffix = this.suffix;
421
+ try {
422
+ const props: Record<string, Value> = {};
423
+ spec.params.forEach((param, index) => {
424
+ const arg = argument(call, spec.params, index);
425
+ if (arg === undefined) return;
426
+ const value = this.param(param, arg, scope, `${call.name} ${param.name}`, key);
427
+ if (value !== undefined) props[param.name] = value;
428
+ });
429
+ return this.node(type, key, type === "Snippet" ? this.snippet(props) : props, call.pos);
430
+ } catch (error) {
431
+ if (!(error instanceof RuntimeError)) throw error;
432
+ const failure = this.recover(error, depth, suffix);
433
+ return failure instanceof LoadPending
434
+ ? this.node("Loading", key, { path: failure.path, component: type }, call.pos)
435
+ : this.node("Error", key, { message: failure.message }, call.pos);
594
436
  }
595
- }
596
- throw new RuntimeError(call.pos, `\`${name}\` is not a function`);
597
- }
598
-
599
- /**
600
- * A named function (`share = p => ...`). Its body sees its parameters and
601
- * top-level names only; missing arguments are null. Nodes it makes are keyed
602
- * by the call site too, so two calls never share component state.
603
- */
604
- private callOwn(call: CallExpr, fn: ArrowExpr, scope: Scope | null): Value {
605
- const args = call.args.map((arg) => this.expr(arg, scope));
606
- let inner: Scope | null = null;
607
- for (const [index, name] of fn.params.entries()) {
608
- inner = { name, value: index < args.length ? args[index] : null, parent: inner };
609
- }
610
- const base = this.suffix;
611
- this.suffix = `${base}@${call.pos.line}:${call.pos.column}`;
612
- try {
613
- return this.expr(fn.body, inner);
614
- } finally {
615
- this.suffix = base;
616
- }
617
- }
618
-
619
- private method(call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
620
- const receiver = this.expr(call.object, scope);
621
- if (isList(receiver) && LAMBDA_METHODS.has(call.name)) return this.lambdaMethod(receiver, call, scope);
622
- const args = call.args.map((arg) => this.expr(arg, scope));
623
- const label = `.${call.name}()`;
624
- const textAt = (index: number) => this.text(args[index], call.args[index].pos, label);
625
- const bounds = () => args.map((arg, index) => this.number(arg, call.args[index].pos, label));
626
- if (isList(receiver)) {
437
+ },
438
+
439
+ /**
440
+ * Snippet props: the requested range plus its lines from the raw file. A file
441
+ * still loading is `code: null` (the renderer shows a placeholder), and a
442
+ * file or range problem is `error`, never an Error node.
443
+ */
444
+ snippet(props: Readonly<Record<string, Value>>): Record<string, Value> {
445
+ // `path` is a required string param and the others optional numbers, so these are the evaluated values.
446
+ const path = typeof props.path === "string" ? props.path : "";
447
+ const from = typeof props.from === "number" ? props.from : null;
448
+ const to = typeof props.to === "number" ? props.to : null;
449
+ const loaded = this.data.get(dataKey({ path, raw: true }));
450
+ const rangeError = snippetRangeError(from, to);
451
+ let shown: { code: string | null; error: string | null };
452
+ if (rangeError !== null) shown = { code: null, error: rangeError };
453
+ else if (loaded === undefined) shown = { code: null, error: null };
454
+ else if (!loaded.ok) shown = { code: null, error: loaded.error };
455
+ else if (typeof loaded.value !== "string") shown = { code: null, error: "not a text file" };
456
+ else shown = snippetLines(loaded.value, from, to);
457
+ return { path, from, to, code: shown.code, error: shown.error, language: languageOf(path) };
458
+ },
459
+
460
+ /** Evaluates and normalizes one argument; `undefined` means an optional param passed as null. */
461
+ param(param: ParamSpec, arg: Expr, scope: Scope | null, label: string, key: string): Value | undefined {
462
+ if (param.kind === "binding") {
463
+ if (arg.type !== "state") throw new RuntimeError(arg.pos, `${label} must be a state variable written as \`$name\``);
464
+ const value = Object.hasOwn(this.state, arg.name) ? this.state[arg.name] : null;
465
+ // Set() or a computed initial value can still give the state the wrong
466
+ // type; a lossless reading keeps the input working, anything else fails.
467
+ const mismatch = stateMismatch(label, param, arg.name, kindOf(value), "holds");
468
+ const coerced = mismatch === null ? value : coerceState(param.holds, value);
469
+ if (coerced === undefined) throw new RuntimeError(arg.pos, mismatch!);
470
+ const binding: Binding = { kind: "binding", name: arg.name, value: coerced };
471
+ return binding;
472
+ }
473
+ const value = this.expr(arg, scope);
474
+ if (param.kind === "nodes") return this.children(value, arg.pos, label, key);
475
+ if (param.kind === "actions") return this.actions(value, arg.pos, label);
476
+ if (value === null) {
477
+ if (param.optional) return undefined;
478
+ if (param.nullable || param.kind === "any") return null;
479
+ }
480
+ switch (param.kind) {
481
+ case "string":
482
+ case "text":
483
+ if (value !== null && typeof value !== "object") return String(value);
484
+ break;
485
+ case "number":
486
+ if (typeof value === "number") return value;
487
+ break;
488
+ case "boolean":
489
+ if (typeof value === "boolean") return value;
490
+ break;
491
+ case "enum": {
492
+ const values = param.values ?? [];
493
+ if (typeof value === "string" && values.includes(value)) return value;
494
+ const got = typeof value === "string" ? JSON.stringify(value) : describe(value);
495
+ throw new RuntimeError(arg.pos, `${label} must be one of ${values.join(", ")}; got ${got}`);
496
+ }
497
+ case "list":
498
+ if (isList(value)) return value;
499
+ break;
500
+ case "series": {
501
+ const isNumbers = (item: Value) => isList(item) && item.every((n) => typeof n === "number" || n === null);
502
+ if (isNumbers(value) || (isPlainObject(value) && Object.values(value).every(isNumbers))) return value;
503
+ break;
504
+ }
505
+ case "any":
506
+ return value;
507
+ }
508
+ throw new RuntimeError(arg.pos, `${label} needs ${EXPECTED[param.kind]}, got ${describe(value)}`);
509
+ },
510
+
511
+ /** Flattens children: strings/numbers become Text nodes, null/false are dropped. */
512
+ children(value: Value, pos: Pos, label: string, key: string): UiNode[] {
513
+ const out: UiNode[] = [];
514
+ const visit = (item: Value): void => {
515
+ if (item === null || item === false) return;
516
+ if (typeof item === "string" || typeof item === "number") {
517
+ out.push(this.node("Text", `${key}.${out.length}`, { text: String(item) }, pos));
518
+ } else if (isList(item)) {
519
+ for (const child of item) visit(child);
520
+ } else if (isNode(item)) {
521
+ out.push(item);
522
+ } else {
523
+ throw new RuntimeError(pos, `${label} must be components or text, got ${describe(item)}`);
524
+ }
525
+ };
526
+ visit(value);
527
+ return out;
528
+ },
529
+
530
+ actions(value: Value, pos: Pos, label: string): Action[] {
531
+ const out: Action[] = [];
532
+ const visit = (item: Value): void => {
533
+ if (item === null || item === false) return;
534
+ if (isList(item)) {
535
+ for (const child of item) visit(child);
536
+ } else if (isAction(item)) {
537
+ out.push(item);
538
+ } else {
539
+ throw new RuntimeError(pos, `${label} takes actions such as Send("..."), got ${describe(item)}`);
540
+ }
541
+ };
542
+ visit(value);
543
+ return out;
544
+ },
545
+
546
+ action(call: CallExpr, spec: ComponentSpec, scope: Scope | null): Action {
547
+ // Every action has a required first param; the validator guarantees it is present.
548
+ const first = argument(call, spec.params, 0)!;
549
+ if (call.name === "Set") {
550
+ if (first.type !== "state") throw new RuntimeError(first.pos, "Set needs a state variable written as `$name`");
551
+ const second = argument(call, spec.params, 1)!;
552
+ return { kind: "action", type: "set", name: first.name, value: this.expr(second, scope) };
553
+ }
554
+ const value = this.expr(first, scope);
555
+ if (value === null || typeof value === "object") {
556
+ throw new RuntimeError(first.pos, `${call.name} needs text, got ${describe(value)}`);
557
+ }
558
+ const text = String(value);
627
559
  switch (call.name) {
628
- case "join":
629
- return checkString(
630
- receiver.map((item) => toText(item, call.pos)).join(args.length > 0 ? textAt(0) : ","),
560
+ case "Send":
561
+ return { kind: "action", type: "send", text };
562
+ case "Copy":
563
+ return { kind: "action", type: "copy", text };
564
+ case "OpenUrl":
565
+ if (!/^https?:\/\//i.test(text)) throw new RuntimeError(first.pos, "OpenUrl needs an http:// or https:// URL");
566
+ return { kind: "action", type: "openUrl", url: text };
567
+ }
568
+ throw new RuntimeError(call.pos, `unknown action \`${call.name}\``);
569
+ },
570
+
571
+ /** Numbers in a list; nulls are skipped. */
572
+ numbers(value: Value, pos: Pos, label: string): number[] {
573
+ if (!isList(value)) throw new RuntimeError(pos, `${label} needs a list of numbers, got ${describe(value)}`);
574
+ const out: number[] = [];
575
+ for (const item of value) if (item !== null) out.push(this.number(item, pos, label));
576
+ return out;
577
+ },
578
+
579
+ callFunction(call: CallExpr, scope: Scope | null): Value {
580
+ const args = call.args.map((arg) => this.expr(arg, scope));
581
+ const name = call.name;
582
+ const numberAt = (index: number) => this.number(args[index], call.args[index].pos, `${name}()`);
583
+ const digitsAt = (index: number) =>
584
+ index < args.length ? this.digits(args[index], call.args[index].pos, `${name}()`) : undefined;
585
+ switch (name) {
586
+ case "round":
587
+ return finite(roundTo(numberAt(0), digitsAt(1) ?? 0));
588
+ case "fmt":
589
+ return fmt(numberAt(0), digitsAt(1));
590
+ case "abs":
591
+ return Math.abs(numberAt(0));
592
+ case "floor":
593
+ return Math.floor(numberAt(0));
594
+ case "ceil":
595
+ return Math.ceil(numberAt(0));
596
+ case "sqrt":
597
+ return finite(Math.sqrt(numberAt(0)));
598
+ case "pow":
599
+ return finite(numberAt(0) ** numberAt(1));
600
+ case "sum":
601
+ return finite(this.numbers(args[0], call.args[0].pos, "sum()").reduce((total, n) => total + n, 0));
602
+ case "min":
603
+ case "max": {
604
+ const values =
605
+ args.length === 1 && isList(args[0])
606
+ ? this.numbers(args[0], call.args[0].pos, `${name}()`)
607
+ : args.map((_, index) => numberAt(index));
608
+ if (values.length === 0) return null;
609
+ return name === "min" ? Math.min(...values) : Math.max(...values);
610
+ }
611
+ case "keys":
612
+ case "values":
613
+ case "entries": {
614
+ const object = args[0];
615
+ if (!isPlainObject(object)) throw new RuntimeError(call.args[0].pos, `${name}() needs an object, got ${describe(object)}`);
616
+ const pairs = Object.entries(object);
617
+ return checkLength(
618
+ name === "keys" ? pairs.map(([key]) => key) : name === "values" ? pairs.map(([, value]) => value) : pairs,
631
619
  call.pos,
632
620
  );
633
- case "slice":
634
- return receiver.slice(...bounds());
635
- case "includes":
636
- return receiver.includes(args[0]);
637
- case "indexOf":
638
- return receiver.indexOf(args[0]);
621
+ }
622
+ case "Load": {
623
+ const path = this.text(args[0], call.args[0].pos, "Load()");
624
+ const loaded = this.data.get(dataKey({ path, raw: false }));
625
+ if (loaded === undefined) throw new LoadPending(call.pos, path);
626
+ if (!loaded.ok) throw new RuntimeError(call.pos, `Couldn't load ${path}: ${loaded.error}`);
627
+ return loaded.value;
628
+ }
639
629
  }
640
- } else if (typeof receiver === "string") {
641
- switch (call.name) {
642
- case "includes":
643
- return receiver.includes(textAt(0));
644
- case "startsWith":
645
- return receiver.startsWith(textAt(0));
646
- case "endsWith":
647
- return receiver.endsWith(textAt(0));
648
- case "slice":
649
- return receiver.slice(...bounds());
650
- case "split":
651
- return checkLength(receiver.split(textAt(0)), call.pos);
652
- case "trim":
653
- return receiver.trim();
654
- case "toUpperCase":
655
- return receiver.toUpperCase();
656
- case "toLowerCase":
657
- return receiver.toLowerCase();
630
+ throw new RuntimeError(call.pos, `\`${name}\` is not a function`);
631
+ },
632
+
633
+ /**
634
+ * A named function (`share = p => ...`). Its body sees its parameters and
635
+ * top-level names only; missing arguments are null. Nodes it makes are keyed
636
+ * by the call site too, so two calls never share component state.
637
+ */
638
+ callOwn(call: CallExpr, fn: ArrowExpr, scope: Scope | null): Value {
639
+ const args = call.args.map((arg) => this.expr(arg, scope));
640
+ let inner: Scope | null = null;
641
+ for (const [index, name] of fn.params.entries()) {
642
+ inner = { name, value: index < args.length ? args[index] : null, parent: inner };
658
643
  }
659
- } else if (typeof receiver === "number" && call.name === "toFixed") {
660
- const digits = args.length > 0 ? this.digits(args[0], call.args[0].pos, label) : 0;
661
- return roundTo(receiver, digits).toFixed(digits);
662
- }
663
- throw new RuntimeError(call.pos, `\`${label}\` is not available on ${describe(receiver)}`);
664
- }
665
-
666
- private lambdaMethod(list: readonly Value[], call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
667
- checkLength(list, call.pos);
668
- const fn = call.args[0];
669
- if (fn?.type !== "arrow") throw new RuntimeError(call.pos, `\`.${call.name}()\` takes a function, as in \`x => x.price\``);
670
- const [itemName, indexName] = fn.params;
671
- const apply = (item: Value, index: number): Value => {
672
- let inner = scope;
673
- if (itemName !== undefined) inner = { name: itemName, value: item, parent: inner };
674
- if (indexName !== undefined) inner = { name: indexName, value: index, parent: inner };
675
- return this.expr(fn.body, inner);
676
- };
677
- switch (call.name) {
678
- case "map": {
679
- const base = this.suffix;
680
- const out = list.map((item, index) => {
681
- this.suffix = `${base}#${index}`;
682
- return apply(item, index);
683
- });
644
+ const base = this.suffix;
645
+ this.suffix = `${base}@${call.pos.line}:${call.pos.column}`;
646
+ try {
647
+ return this.expr(fn.body, inner);
648
+ } finally {
684
649
  this.suffix = base;
685
- return out;
686
650
  }
687
- case "filter":
688
- return list.filter((item, index) => truthy(apply(item, index)));
689
- case "find":
690
- return list.find((item, index) => truthy(apply(item, index))) ?? null;
691
- case "some":
692
- return list.some((item, index) => truthy(apply(item, index)));
693
- default:
694
- return list.every((item, index) => truthy(apply(item, index)));
695
- }
696
- }
697
- }
651
+ },
652
+
653
+ method(call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
654
+ const receiver = this.expr(call.object, scope);
655
+ if (isList(receiver) && LAMBDA_METHODS.has(call.name)) return this.lambdaMethod(receiver, call, scope);
656
+ const args = call.args.map((arg) => this.expr(arg, scope));
657
+ const label = `.${call.name}()`;
658
+ const textAt = (index: number) => this.text(args[index], call.args[index].pos, label);
659
+ const bounds = () => args.map((arg, index) => this.number(arg, call.args[index].pos, label));
660
+ if (isList(receiver)) {
661
+ switch (call.name) {
662
+ case "join":
663
+ return checkString(
664
+ receiver.map((item) => toText(item, call.pos)).join(args.length > 0 ? textAt(0) : ","),
665
+ call.pos,
666
+ );
667
+ case "slice":
668
+ return receiver.slice(...bounds());
669
+ case "includes":
670
+ return receiver.includes(args[0]);
671
+ case "indexOf":
672
+ return receiver.indexOf(args[0]);
673
+ }
674
+ } else if (typeof receiver === "string") {
675
+ switch (call.name) {
676
+ case "includes":
677
+ return receiver.includes(textAt(0));
678
+ case "startsWith":
679
+ return receiver.startsWith(textAt(0));
680
+ case "endsWith":
681
+ return receiver.endsWith(textAt(0));
682
+ case "slice":
683
+ return receiver.slice(...bounds());
684
+ case "split":
685
+ return checkLength(receiver.split(textAt(0)), call.pos);
686
+ case "trim":
687
+ return receiver.trim();
688
+ case "toUpperCase":
689
+ return receiver.toUpperCase();
690
+ case "toLowerCase":
691
+ return receiver.toLowerCase();
692
+ }
693
+ } else if (typeof receiver === "number" && call.name === "toFixed") {
694
+ const digits = args.length > 0 ? this.digits(args[0], call.args[0].pos, label) : 0;
695
+ return roundTo(receiver, digits).toFixed(digits);
696
+ }
697
+ throw new RuntimeError(call.pos, `\`${label}\` is not available on ${describe(receiver)}`);
698
+ },
699
+
700
+ lambdaMethod(list: readonly Value[], call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
701
+ checkLength(list, call.pos);
702
+ const fn = call.args[0];
703
+ if (fn?.type !== "arrow") throw new RuntimeError(call.pos, `\`.${call.name}()\` takes a function, as in \`x => x.price\``);
704
+ const [itemName, indexName] = fn.params;
705
+ const apply = (item: Value, index: number): Value => {
706
+ let inner = scope;
707
+ if (itemName !== undefined) inner = { name: itemName, value: item, parent: inner };
708
+ if (indexName !== undefined) inner = { name: indexName, value: index, parent: inner };
709
+ return this.expr(fn.body, inner);
710
+ };
711
+ switch (call.name) {
712
+ case "map": {
713
+ const base = this.suffix;
714
+ const out = list.map((item, index) => {
715
+ this.suffix = `${base}#${index}`;
716
+ return apply(item, index);
717
+ });
718
+ this.suffix = base;
719
+ return out;
720
+ }
721
+ case "filter":
722
+ return list.filter((item, index) => truthy(apply(item, index)));
723
+ case "find":
724
+ return list.find((item, index) => truthy(apply(item, index))) ?? null;
725
+ case "some":
726
+ return list.some((item, index) => truthy(apply(item, index)));
727
+ default:
728
+ return list.every((item, index) => truthy(apply(item, index)));
729
+ }
730
+ },
731
+ },
732
+ );
733
+ type Interpreter = InstanceType<typeof Interpreter>;
698
734
 
699
735
  /** `$state` initial values in declaration order; an initializer that fails yields null. */
700
736
  export function initialState(program: Program, data = NO_DATA): Record<string, Value> {