paseo-plugin-genui 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paseo-plugin-genui",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Paseo plugin: agents answer with charts, diagrams, maps, plans and forms rendered inline in the chat.",
5
5
  "keywords": [
6
6
  "paseo",
@@ -5,7 +5,8 @@ export type BinaryOperator =
5
5
  | "??" | "||" | "&&"
6
6
  | "==" | "!=" | "===" | "!=="
7
7
  | "<" | "<=" | ">" | ">="
8
- | "+" | "-" | "*" | "/" | "%" | "**";
8
+ | "+" | "-" | "*" | "/" | "%" | "**"
9
+ | "in";
9
10
 
10
11
  export interface NamedArg {
11
12
  readonly name: string;
@@ -24,10 +25,13 @@ export type Expr =
24
25
  | { readonly type: "list"; readonly items: readonly Expr[]; readonly pos: Pos }
25
26
  | {
26
27
  readonly type: "object";
27
- readonly entries: readonly { readonly key: string; readonly value: Expr; readonly pos: Pos }[];
28
+ /** An expression key is computed, as in `{[k]: 1}`; a null key spreads `value`, as in `{...o}`. */
29
+ readonly entries: readonly { readonly key: string | Expr | null; readonly value: Expr; readonly pos: Pos }[];
28
30
  readonly pos: Pos;
29
31
  }
30
- | { readonly type: "unary"; readonly op: "!" | "-"; readonly operand: Expr; readonly pos: Pos }
32
+ /** `...value`; the parser makes it only as a list item or an argument. */
33
+ | { readonly type: "spread"; readonly value: Expr; readonly pos: Pos }
34
+ | { readonly type: "unary"; readonly op: "!" | "-" | "typeof"; readonly operand: Expr; readonly pos: Pos }
31
35
  | { readonly type: "binary"; readonly op: BinaryOperator; readonly left: Expr; readonly right: Expr; readonly pos: Pos }
32
36
  | { readonly type: "conditional"; readonly test: Expr; readonly then: Expr; readonly else: Expr; readonly pos: Pos }
33
37
  /** `object.name`; `pos` is the property name. */
@@ -41,16 +45,19 @@ export type Expr =
41
45
  readonly named: readonly NamedArg[];
42
46
  readonly pos: Pos;
43
47
  }
44
- /** `object.name(...)`; `pos` is the method name. */
48
+ /** `object.name(...)`; `pos` is the method name. `optional`: after a `?.`, so a null object gives null. */
45
49
  | {
46
50
  readonly type: "method";
47
51
  readonly object: Expr;
48
52
  readonly name: string;
49
53
  readonly args: readonly Expr[];
50
54
  readonly named: readonly NamedArg[];
55
+ readonly optional: boolean;
51
56
  readonly pos: Pos;
52
57
  }
53
- | { readonly type: "arrow"; readonly params: readonly string[]; readonly body: Expr; readonly pos: Pos };
58
+ | { readonly type: "arrow"; readonly params: readonly string[]; readonly body: Expr; readonly pos: Pos }
59
+ /** `name` holds `value` while `body` runs; block bodies and destructuring parse into these. */
60
+ | { readonly type: "let"; readonly name: string; readonly value: Expr; readonly body: Expr; readonly pos: Pos };
54
61
 
55
62
  export type CallExpr = Extract<Expr, { type: "call" }>;
56
63
  export type ArrowExpr = Extract<Expr, { type: "arrow" }>;
@@ -674,6 +674,12 @@ export const FUNCTIONS = {
674
674
  keys: "keys(object) → list of keys",
675
675
  values: "values(object) → list of values",
676
676
  entries: "entries(object) → list of [key, value]",
677
+ Number: "Number(x) → a number, or null for text that is not one",
678
+ String: "String(x) → text",
679
+ parseInt: "parseInt(text, radix?) → a whole number, or null",
680
+ parseFloat: "parseFloat(text) → a number, or null",
681
+ "JSON.stringify": "JSON.stringify(value, null?, indent?) → JSON text",
682
+ "Date.now": "Date.now() → milliseconds since 1970",
677
683
  Load: "Load(path): JSON/CSV/TSV/JSONL/text file, workspace-relative or in thread storage",
678
684
  } as const;
679
685
 
@@ -693,6 +699,13 @@ export const METHODS = {
693
699
  "indexOf",
694
700
  "concat",
695
701
  "sort",
702
+ "reduce",
703
+ "flatMap",
704
+ "flat",
705
+ "at",
706
+ "findIndex",
707
+ "lastIndexOf",
708
+ "reverse",
696
709
  ],
697
710
  string: [
698
711
  "includes",
@@ -705,8 +718,19 @@ export const METHODS = {
705
718
  "endsWith",
706
719
  "replace",
707
720
  "replaceAll",
721
+ "indexOf",
722
+ "lastIndexOf",
723
+ "at",
724
+ "charAt",
725
+ "substring",
726
+ "padStart",
727
+ "padEnd",
728
+ "repeat",
729
+ "trimStart",
730
+ "trimEnd",
731
+ "toString",
708
732
  ],
709
- number: ["toFixed"],
733
+ number: ["toFixed", "toLocaleString", "toString"],
710
734
  } as const;
711
735
 
712
736
  /** Read-only properties allowed on lists and strings (plain objects allow any own key). */
@@ -47,7 +47,17 @@ export function collectLoads(program: Program): DataRequest[] {
47
47
  expr.items.forEach(visit);
48
48
  return;
49
49
  case "object":
50
- for (const entry of expr.entries) visit(entry.value);
50
+ for (const entry of expr.entries) {
51
+ if (entry.key !== null && typeof entry.key !== "string") visit(entry.key);
52
+ visit(entry.value);
53
+ }
54
+ return;
55
+ case "spread":
56
+ visit(expr.value);
57
+ return;
58
+ case "let":
59
+ visit(expr.value);
60
+ visit(expr.body);
51
61
  return;
52
62
  case "unary":
53
63
  visit(expr.operand);
@@ -9,6 +9,7 @@ import {
9
9
  coerceState,
10
10
  DESCRIPTIONS,
11
11
  EXPECTED,
12
+ functionArg,
12
13
  LAMBDA_METHODS,
13
14
  stateMismatch,
14
15
  type Kind,
@@ -163,15 +164,26 @@ function roundTo(value: number, digits: number): number {
163
164
  return value < 0 ? -rounded : rounded;
164
165
  }
165
166
 
166
- /** `1234.5` → "1,234.5"; fixed `digits`, or up to 2 with trailing zeros trimmed. */
167
- function fmt(value: number, digits: number | undefined): string {
168
- let fixed = roundTo(value, digits ?? 2).toFixed(digits ?? 2);
167
+ /** `1234.5` → "1,234.5"; fixed `digits`, or up to `most` with trailing zeros trimmed. */
168
+ function fmt(value: number, digits: number | undefined, most = 2): string {
169
+ let fixed = roundTo(value, digits ?? most).toFixed(digits ?? most);
169
170
  if (digits === undefined) fixed = fixed.replace(/\.0+$|(\.\d*?)0+$/, "$1");
170
171
  const [whole, fraction] = fixed.split(".");
171
172
  const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
172
173
  return fraction === undefined ? grouped : `${grouped}.${fraction}`;
173
174
  }
174
175
 
176
+ /** `list[index]`, counting from the end for a negative index, as `.at()` does. */
177
+ function at(list: readonly Value[] | string, index: number): Value {
178
+ const from = Math.trunc(index) < 0 ? list.length + Math.trunc(index) : Math.trunc(index);
179
+ return from >= 0 && from < list.length ? list[from] : null;
180
+ }
181
+
182
+ function typeOf(value: Value): string {
183
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") return typeof value;
184
+ return "object";
185
+ }
186
+
175
187
  /** The expression passed for `params[index]`, positionally or by name. */
176
188
  function argument(call: CallExpr, params: readonly ParamSpec[], index: number): Expr | undefined {
177
189
  return index < call.args.length ? call.args[index] : call.named.find((arg) => arg.name === params[index].name)?.value;
@@ -246,23 +258,36 @@ const Interpreter = defineClass(
246
258
  }
247
259
  return this.named(expr.name, expr.pos);
248
260
  case "list":
249
- return checkLength(
250
- expr.items.map((item) => this.expr(item, scope)),
251
- expr.pos,
252
- );
261
+ return checkLength(this.spread(expr.items, scope).values, expr.pos);
253
262
  case "object": {
254
263
  const object: Record<string, Value> = {};
255
264
  for (const entry of expr.entries) {
256
265
  const value = this.expr(entry.value, scope);
257
- if (entry.key === "kind" && (value === "node" || value === "action" || value === "binding")) {
266
+ if (entry.key === null) {
267
+ if (value === null) continue;
268
+ if (!isPlainObject(value)) throw new RuntimeError(entry.pos, `\`...\` in an object needs an object, got ${describe(value)}`);
269
+ // Copy own keys one by one: Object.assign would run the `__proto__` setter for loaded JSON's own `__proto__` key.
270
+ for (const [key, item] of Object.entries(value)) {
271
+ if (!(FORBIDDEN_PROPERTIES as readonly string[]).includes(key)) object[key] = item;
272
+ }
273
+ continue;
274
+ }
275
+ const key = typeof entry.key === "string" ? entry.key : toText(this.expr(entry.key, scope), entry.key.pos);
276
+ if ((FORBIDDEN_PROPERTIES as readonly string[]).includes(key)) throw new RuntimeError(entry.pos, `\`${key}\` is not accessible`);
277
+ if (key === "kind" && (value === "node" || value === "action" || value === "binding")) {
258
278
  throw new RuntimeError(entry.pos, `\`kind: "${value}"\` is reserved; use another key or value`);
259
279
  }
260
- object[entry.key] = value;
280
+ object[key] = value;
261
281
  }
262
282
  return object;
263
283
  }
284
+ case "spread":
285
+ throw new RuntimeError(expr.pos, "`...` works only inside [ ], { } and function arguments");
286
+ case "let":
287
+ return this.expr(expr.body, { name: expr.name, value: this.expr(expr.value, scope), parent: scope });
264
288
  case "unary": {
265
289
  const operand = this.expr(expr.operand, scope);
290
+ if (expr.op === "typeof") return typeOf(operand);
266
291
  return expr.op === "!" ? !truthy(operand) : finite(-this.number(operand, expr.pos, "`-`"));
267
292
  }
268
293
  case "binary":
@@ -352,6 +377,10 @@ const Interpreter = defineClass(
352
377
  }
353
378
  if (typeof left === "number" && typeof right === "number") return finite(left + right);
354
379
  throw new RuntimeError(expr.pos, `\`+\` needs numbers or text, got ${describe(left)} and ${describe(right)}`);
380
+ case "in":
381
+ if (isList(right)) return typeof left === "number" && Number.isInteger(left) && left >= 0 && left < right.length;
382
+ if (isPlainObject(right)) return Object.hasOwn(right, this.text(left, expr.left.pos, "`in`"));
383
+ throw new RuntimeError(expr.pos, `\`in\` needs an object or a list on its right, got ${describe(right)}`);
355
384
  case "<":
356
385
  case "<=":
357
386
  case ">":
@@ -572,6 +601,27 @@ const Interpreter = defineClass(
572
601
  throw new RuntimeError(call.pos, `unknown action \`${call.name}\``);
573
602
  },
574
603
 
604
+ /** Evaluated items or arguments with `...list` spread in place, and the position each came from. */
605
+ spread(exprs: readonly Expr[], scope: Scope | null): { values: Value[]; positions: Pos[] } {
606
+ const values: Value[] = [];
607
+ const positions: Pos[] = [];
608
+ for (const expr of exprs) {
609
+ if (expr.type !== "spread") {
610
+ values.push(this.expr(expr, scope));
611
+ positions.push(expr.pos);
612
+ continue;
613
+ }
614
+ const list = this.expr(expr.value, scope);
615
+ if (!isList(list)) throw new RuntimeError(expr.pos, `\`...\` needs a list here, got ${describe(list)}`);
616
+ checkLength(list, expr.pos);
617
+ for (const item of list) {
618
+ values.push(item);
619
+ positions.push(expr.pos);
620
+ }
621
+ }
622
+ return { values, positions };
623
+ },
624
+
575
625
  /** Numbers in a list; nulls are skipped. */
576
626
  numbers(value: Value, pos: Pos, label: string): number[] {
577
627
  if (!isList(value)) throw new RuntimeError(pos, `${label} needs a list of numbers, got ${describe(value)}`);
@@ -581,11 +631,12 @@ const Interpreter = defineClass(
581
631
  },
582
632
 
583
633
  callFunction(call: CallExpr, scope: Scope | null): Value {
584
- const args = call.args.map((arg) => this.expr(arg, scope));
634
+ const { values: args, positions } = this.spread(call.args, scope);
635
+ const posAt = (index: number) => positions[index] ?? call.pos;
585
636
  const name = call.name;
586
- const numberAt = (index: number) => this.number(args[index], call.args[index].pos, `${name}()`);
637
+ const numberAt = (index: number) => this.number(args[index] ?? null, posAt(index), `${name}()`);
587
638
  const digitsAt = (index: number) =>
588
- index < args.length ? this.digits(args[index], call.args[index].pos, `${name}()`) : undefined;
639
+ index < args.length ? this.digits(args[index], posAt(index), `${name}()`) : undefined;
589
640
  switch (name) {
590
641
  case "round":
591
642
  return finite(roundTo(numberAt(0), digitsAt(1) ?? 0));
@@ -602,12 +653,12 @@ const Interpreter = defineClass(
602
653
  case "pow":
603
654
  return finite(numberAt(0) ** numberAt(1));
604
655
  case "sum":
605
- return finite(this.numbers(args[0], call.args[0].pos, "sum()").reduce((total, n) => total + n, 0));
656
+ return finite(this.numbers(args[0] ?? null, posAt(0), "sum()").reduce((total, n) => total + n, 0));
606
657
  case "min":
607
658
  case "max": {
608
659
  const values =
609
660
  args.length === 1 && isList(args[0])
610
- ? this.numbers(args[0], call.args[0].pos, `${name}()`)
661
+ ? this.numbers(args[0], posAt(0), `${name}()`)
611
662
  : args.map((_, index) => numberAt(index));
612
663
  if (values.length === 0) return null;
613
664
  return name === "min" ? Math.min(...values) : Math.max(...values);
@@ -615,8 +666,8 @@ const Interpreter = defineClass(
615
666
  case "keys":
616
667
  case "values":
617
668
  case "entries": {
618
- const object = args[0];
619
- if (!isPlainObject(object)) throw new RuntimeError(call.args[0].pos, `${name}() needs an object, got ${describe(object)}`);
669
+ const object = args[0] ?? null;
670
+ if (!isPlainObject(object)) throw new RuntimeError(posAt(0), `${name}() needs an object, got ${describe(object)}`);
620
671
  const pairs = Object.entries(object);
621
672
  return checkLength(
622
673
  name === "keys" ? pairs.map(([key]) => key) : name === "values" ? pairs.map(([, value]) => value) : pairs,
@@ -624,12 +675,35 @@ const Interpreter = defineClass(
624
675
  );
625
676
  }
626
677
  case "Load": {
627
- const path = this.text(args[0], call.args[0].pos, "Load()");
678
+ const path = this.text(args[0], posAt(0), "Load()");
628
679
  const loaded = this.data.get(dataKey({ path, raw: false }));
629
680
  if (loaded === undefined) throw new LoadPending(call.pos, path);
630
681
  if (!loaded.ok) throw new RuntimeError(call.pos, `Couldn't load ${path}: ${loaded.error}`);
631
682
  return loaded.value;
632
683
  }
684
+ case "Number": {
685
+ const value = args[0] ?? null;
686
+ if (value === null) return 0;
687
+ if (typeof value === "boolean") return value ? 1 : 0;
688
+ if (typeof value === "number") return value;
689
+ if (typeof value === "string") return finite(Number(value.trim().replaceAll(",", "")));
690
+ throw new RuntimeError(posAt(0), `Number() needs text or a number, got ${describe(value)}`);
691
+ }
692
+ case "String":
693
+ return toText(args[0] ?? null, posAt(0));
694
+ case "parseInt":
695
+ return finite(parseInt(toText(args[0] ?? null, posAt(0)), args.length > 1 ? numberAt(1) : 10));
696
+ case "parseFloat":
697
+ return finite(parseFloat(toText(args[0] ?? null, posAt(0))));
698
+ case "JSON.stringify": {
699
+ const indent = args[2] ?? null;
700
+ if (indent !== null && typeof indent !== "number" && typeof indent !== "string") {
701
+ throw new RuntimeError(posAt(2), `JSON.stringify() indent must be a number or text, got ${describe(indent)}`);
702
+ }
703
+ return checkString(JSON.stringify(args[0] ?? null, null, indent ?? undefined), call.pos);
704
+ }
705
+ case "Date.now":
706
+ return Date.now();
633
707
  }
634
708
  throw new RuntimeError(call.pos, `\`${name}\` is not a function`);
635
709
  },
@@ -640,7 +714,7 @@ const Interpreter = defineClass(
640
714
  * by the call site too, so two calls never share component state.
641
715
  */
642
716
  callOwn(call: CallExpr, fn: ArrowExpr, scope: Scope | null): Value {
643
- const args = call.args.map((arg) => this.expr(arg, scope));
717
+ const args = this.spread(call.args, scope).values;
644
718
  let inner: Scope | null = null;
645
719
  for (const [index, name] of fn.params.entries()) {
646
720
  inner = { name, value: index < args.length ? args[index] : null, parent: inner };
@@ -656,12 +730,23 @@ const Interpreter = defineClass(
656
730
 
657
731
  method(call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
658
732
  const receiver = this.expr(call.object, scope);
733
+ if (receiver === null && call.optional) return null;
659
734
  if (isList(receiver) && LAMBDA_METHODS.has(call.name)) return this.lambdaMethod(receiver, call, scope);
660
735
  if (isList(receiver) && call.name === "sort") return this.sort(receiver, call, scope);
661
- const args = call.args.map((arg) => this.expr(arg, scope));
736
+ if (isList(receiver) && call.name === "reduce") return this.reduce(receiver, call, scope);
737
+ const { values: args, positions } = this.spread(call.args, scope);
738
+ const posAt = (index: number) => positions[index] ?? call.pos;
662
739
  const label = `.${call.name}()`;
663
- const textAt = (index: number) => this.text(args[index], call.args[index].pos, label);
664
- const bounds = () => args.map((arg, index) => this.number(arg, call.args[index].pos, label));
740
+ const textAt = (index: number) => this.text(args[index] ?? null, posAt(index), label);
741
+ const numberAt = (index: number) => this.number(args[index] ?? null, posAt(index), label);
742
+ const bounds = () => args.map((arg, index) => this.number(arg, posAt(index), label));
743
+ /** A whole count that keeps the result within the text limit. */
744
+ const sizeAt = (index: number, per: number) => {
745
+ const count = numberAt(index);
746
+ if (!Number.isInteger(count) || count < 0) throw new RuntimeError(posAt(index), `${label} needs a whole number of 0 or more`);
747
+ if (count * per > MAX_STRING_LENGTH) throw new RuntimeError(call.pos, `text longer than ${MAX_STRING_LENGTH} characters`);
748
+ return count;
749
+ };
665
750
  if (isList(receiver)) {
666
751
  switch (call.name) {
667
752
  case "join":
@@ -677,6 +762,18 @@ const Interpreter = defineClass(
677
762
  return receiver.indexOf(args[0]);
678
763
  case "concat":
679
764
  return checkLength(receiver.concat(...args), call.pos);
765
+ case "at":
766
+ return at(receiver, numberAt(0));
767
+ case "lastIndexOf":
768
+ return receiver.lastIndexOf(args[0] ?? null);
769
+ case "reverse":
770
+ return [...receiver].reverse();
771
+ case "flat": {
772
+ const depth = args.length > 0 ? numberAt(0) : 1;
773
+ const flatten = (list: readonly Value[], level: number): Value[] =>
774
+ checkLength(list.flatMap((item) => (isList(item) && level > 0 ? flatten(item, level - 1) : [item])), call.pos);
775
+ return flatten(receiver, depth);
776
+ }
680
777
  }
681
778
  } else if (typeof receiver === "string") {
682
779
  switch (call.name) {
@@ -701,10 +798,40 @@ const Interpreter = defineClass(
701
798
  return checkString(receiver.replace(textAt(0), () => textAt(1)), call.pos);
702
799
  case "replaceAll":
703
800
  return checkString(receiver.replaceAll(textAt(0), () => textAt(1)), call.pos);
801
+ case "indexOf":
802
+ return receiver.indexOf(textAt(0));
803
+ case "lastIndexOf":
804
+ return receiver.lastIndexOf(textAt(0));
805
+ case "at":
806
+ return at(receiver, numberAt(0));
807
+ case "charAt":
808
+ return receiver.charAt(numberAt(0));
809
+ case "substring":
810
+ return receiver.substring(...(bounds() as [number, number?]));
811
+ case "padStart":
812
+ case "padEnd": {
813
+ const width = sizeAt(0, 1);
814
+ const fill = args.length > 1 ? textAt(1) : " ";
815
+ return call.name === "padStart" ? receiver.padStart(width, fill) : receiver.padEnd(width, fill);
816
+ }
817
+ case "repeat":
818
+ return receiver.repeat(sizeAt(0, receiver.length));
819
+ case "trimStart":
820
+ return receiver.trimStart();
821
+ case "trimEnd":
822
+ return receiver.trimEnd();
704
823
  }
705
824
  } else if (typeof receiver === "number" && call.name === "toFixed") {
706
- const digits = args.length > 0 ? this.digits(args[0], call.args[0].pos, label) : 0;
825
+ const digits = args.length > 0 ? this.digits(args[0], posAt(0), label) : 0;
707
826
  return roundTo(receiver, digits).toFixed(digits);
827
+ } else if (typeof receiver === "number" && call.name === "toLocaleString") {
828
+ return fmt(receiver, undefined, 3);
829
+ }
830
+ if (call.name === "toString" && (typeof receiver === "number" || typeof receiver === "string" || typeof receiver === "boolean")) {
831
+ if (args.length === 0 || typeof receiver !== "number") return String(receiver);
832
+ const radix = numberAt(0);
833
+ if (!Number.isInteger(radix) || radix < 2 || radix > 36) throw new RuntimeError(posAt(0), `${label} radix must be a whole number from 2 to 36`);
834
+ return receiver.toString(radix);
708
835
  }
709
836
  throw new RuntimeError(call.pos, `\`${label}\` is not available on ${describe(receiver)}`);
710
837
  },
@@ -712,7 +839,7 @@ const Interpreter = defineClass(
712
839
  /** A sorted copy; without a comparator, numbers sort numerically and anything else as text. */
713
840
  sort(list: readonly Value[], call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
714
841
  checkLength(list, call.pos);
715
- const fn = call.args[0];
842
+ const fn = call.args[0] && functionArg(call.args[0], this.program.named, "sort");
716
843
  if (fn === undefined) {
717
844
  return [...list].sort((a, b) =>
718
845
  typeof a === "number" && typeof b === "number" ? a - b : toText(a, call.pos).localeCompare(toText(b, call.pos)),
@@ -728,9 +855,29 @@ const Interpreter = defineClass(
728
855
  });
729
856
  },
730
857
 
858
+ /** `.reduce(fn, start?)`; without `start` the first item starts the total. */
859
+ reduce(list: readonly Value[], call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
860
+ checkLength(list, call.pos);
861
+ const fn = call.args[0] && functionArg(call.args[0], this.program.named, "reduce");
862
+ if (fn?.type !== "arrow") throw new RuntimeError(call.pos, "`.reduce()` takes a function, as in `(total, x) => total + x.price, 0`");
863
+ if (call.args.length < 2 && list.length === 0) {
864
+ throw new RuntimeError(call.pos, "`.reduce()` on an empty list needs a starting value, as in `.reduce(f, 0)`");
865
+ }
866
+ const [totalName, itemName, indexName] = fn.params;
867
+ let total = call.args.length > 1 ? this.expr(call.args[1], scope) : list[0];
868
+ for (let index = call.args.length > 1 ? 0 : 1; index < list.length; index++) {
869
+ let inner = scope;
870
+ if (totalName !== undefined) inner = { name: totalName, value: total, parent: inner };
871
+ if (itemName !== undefined) inner = { name: itemName, value: list[index], parent: inner };
872
+ if (indexName !== undefined) inner = { name: indexName, value: index, parent: inner };
873
+ total = this.expr(fn.body, inner);
874
+ }
875
+ return total;
876
+ },
877
+
731
878
  lambdaMethod(list: readonly Value[], call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
732
879
  checkLength(list, call.pos);
733
- const fn = call.args[0];
880
+ const fn = call.args[0] && functionArg(call.args[0], this.program.named, call.name);
734
881
  if (fn?.type !== "arrow") throw new RuntimeError(call.pos, `\`.${call.name}()\` takes a function, as in \`x => x.price\``);
735
882
  const [itemName, indexName] = fn.params;
736
883
  const apply = (item: Value, index: number): Value => {
@@ -740,15 +887,18 @@ const Interpreter = defineClass(
740
887
  return this.expr(fn.body, inner);
741
888
  };
742
889
  switch (call.name) {
743
- case "map": {
890
+ case "map":
891
+ case "flatMap": {
744
892
  const base = this.suffix;
745
893
  const out = list.map((item, index) => {
746
894
  this.suffix = `${base}#${index}`;
747
895
  return apply(item, index);
748
896
  });
749
897
  this.suffix = base;
750
- return out;
898
+ return call.name === "map" ? out : checkLength(out.flatMap((item) => (isList(item) ? item : [item])), call.pos);
751
899
  }
900
+ case "findIndex":
901
+ return list.findIndex((item, index) => truthy(apply(item, index)));
752
902
  case "filter":
753
903
  return list.filter((item, index) => truthy(apply(item, index)));
754
904
  case "find":
@@ -17,8 +17,8 @@ export type Token =
17
17
  | (Pos & { readonly t: "eof" });
18
18
 
19
19
  const PUNCTUATION = [
20
- "===", "!==",
21
- "==", "!=", "<=", ">=", "&&", "||", "??", "=>", "**",
20
+ "===", "!==", "...",
21
+ "?.", "==", "!=", "<=", ">=", "&&", "||", "??", "=>", "**",
22
22
  "(", ")", "[", "]", "{", "}", ",", ":", ".", "?", "<", ">", "+", "-", "*", "/", "%", "!", "=",
23
23
  ];
24
24
 
@@ -28,7 +28,7 @@ const CONTINUES_AFTER: Record<string, true> = {
28
28
  "==": true, "!=": true, "===": true, "!==": true,
29
29
  "<": true, "<=": true, ">": true, ">=": true,
30
30
  "&&": true, "||": true, "??": true, "?": true, ":": true,
31
- ".": true, "=": true, "=>": true,
31
+ ".": true, "?.": true, "=": true, "=>": true,
32
32
  };
33
33
 
34
34
  /** A line starting with one of these continues the previous line (none can start an expression). */
@@ -37,7 +37,7 @@ const CONTINUES_BEFORE: Record<string, true> = {
37
37
  "==": true, "!=": true, "===": true, "!==": true,
38
38
  "<": true, "<=": true, ">": true, ">=": true,
39
39
  "&&": true, "||": true, "??": true, "?": true, ":": true,
40
- ".": true, "=>": true,
40
+ ".": true, "?.": true, "=>": true,
41
41
  };
42
42
 
43
43
  const NUMBER = /\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d+)?/y;
@@ -8,13 +8,36 @@ const PRECEDENCE: Record<string, number> = {
8
8
  "||": 2,
9
9
  "&&": 3,
10
10
  "==": 4, "!=": 4, "===": 4, "!==": 4,
11
- "<": 5, "<=": 5, ">": 5, ">=": 5,
11
+ "<": 5, "<=": 5, ">": 5, ">=": 5, in: 5,
12
12
  "+": 6, "-": 6,
13
13
  "*": 7, "/": 7, "%": 7,
14
14
  };
15
15
 
16
16
  const KEYWORDS: Record<string, true | false | null> = { true: true, false: false, null: null };
17
17
 
18
+ /**
19
+ * `Math.round(x)` and `Object.entries(o)` are how models write the built-ins;
20
+ * they parse as the plain calls `round(x)` and `entries(o)`. `JSON.stringify`
21
+ * and `Date.now` keep their dotted names, which no written name can shadow.
22
+ */
23
+ const NAMESPACES: Record<string, string> = { Math: "", Object: "", JSON: "JSON.", Date: "Date." };
24
+
25
+ const BLOCK_WORDS: Record<string, true> = { return: true, const: true, let: true, var: true };
26
+
27
+ /** A parameter or `const` target: a name, or `{a, b: c}` / `[a, b]` destructuring with optional `= fallback`s. */
28
+ type Pattern =
29
+ | { readonly kind: "name"; readonly name: string; readonly pos: Pos }
30
+ | {
31
+ readonly kind: "object";
32
+ readonly props: readonly { readonly key: string; readonly target: Pattern; readonly fallback: Expr | null }[];
33
+ readonly pos: Pos;
34
+ }
35
+ | {
36
+ readonly kind: "array";
37
+ readonly items: readonly ({ readonly target: Pattern; readonly fallback: Expr | null } | null)[];
38
+ readonly pos: Pos;
39
+ };
40
+
18
41
  /** AST depth beyond this is rejected so later tree walks cannot overflow the stack. */
19
42
  const MAX_NESTING = 100;
20
43
 
@@ -76,6 +99,8 @@ interface ParserFields {
76
99
  i: number;
77
100
  tokens: readonly Token[];
78
101
  depth: number;
102
+ /** Counter for the names destructuring binds its intermediate values to. */
103
+ hidden: number;
79
104
  }
80
105
 
81
106
  const Parser = defineClass(
@@ -83,6 +108,7 @@ const Parser = defineClass(
83
108
  this.tokens = tokens;
84
109
  this.depth = depth;
85
110
  this.i = 0;
111
+ this.hidden = 0;
86
112
  },
87
113
  {
88
114
  peek(offset = 0): Token {
@@ -154,32 +180,142 @@ const Parser = defineClass(
154
180
  return expr;
155
181
  },
156
182
 
183
+ /** `x =>`, or a bracketed group followed by `=>`. */
157
184
  isArrowStart(): boolean {
158
185
  if (this.peek().t === "ident") return this.isPunct("=>", 1);
159
186
  if (!this.isPunct("(")) return false;
160
- let offset = 1;
161
- if (this.peek(offset).t === "ident") {
162
- offset++;
163
- while (this.isPunct(",", offset) && this.peek(offset + 1).t === "ident") offset += 2;
187
+ let depth = 0;
188
+ for (let offset = 0; ; offset++) {
189
+ const token = this.peek(offset);
190
+ if (token.t === "eof" || token.t === "sep") return false;
191
+ if (token.t !== "punct") continue;
192
+ if (token.value === "(" || token.value === "[" || token.value === "{") depth++;
193
+ if ((token.value === ")" || token.value === "]" || token.value === "}") && --depth === 0) {
194
+ return this.isPunct("=>", offset + 1);
195
+ }
164
196
  }
165
- return this.isPunct(")", offset) && this.isPunct("=>", offset + 1);
166
197
  },
167
198
 
168
199
  arrow(): Expr {
169
200
  const start = this.peek();
170
- const params: string[] = [];
201
+ const patterns: Pattern[] = [];
171
202
  if (this.eat("(")) {
172
203
  while (!this.eat(")")) {
173
- params.push(this.ident("a parameter name").value);
174
- this.eat(",");
204
+ patterns.push(this.pattern());
205
+ if (!this.eat(",")) {
206
+ this.close(")", start, "`,` or ");
207
+ break;
208
+ }
175
209
  }
176
210
  } else {
177
- params.push(this.ident("a parameter name").value);
211
+ patterns.push(this.pattern());
178
212
  }
179
- const keyword = params.find((name) => Object.hasOwn(KEYWORDS, name));
180
- if (keyword !== undefined) throw new ParseError(start, `\`${keyword}\` cannot be a parameter name`);
181
213
  this.i++; // `=>`, guaranteed by isArrowStart
182
- return { type: "arrow", params, body: this.expr(), pos: start };
214
+ let body = this.isBlockStart() ? this.block() : this.expr();
215
+ const params = patterns.map((pattern, index) => (pattern.kind === "name" ? pattern.name : `#p${index}`));
216
+ for (let index = patterns.length - 1; index >= 0; index--) {
217
+ if (patterns[index].kind !== "name") body = this.bind(patterns[index], { type: "ident", name: params[index], pos: start }, body);
218
+ }
219
+ return { type: "arrow", params, body, pos: start };
220
+ },
221
+
222
+ pattern(): Pattern {
223
+ const open = this.peek();
224
+ if (this.eat("{")) {
225
+ const props: { key: string; target: Pattern; fallback: Expr | null }[] = [];
226
+ while (!this.eat("}")) {
227
+ const key = this.peek();
228
+ if (key.t !== "ident" && key.t !== "str") {
229
+ throw new ParseError(key, `expected a property name to destructure, found ${describe(key)}`);
230
+ }
231
+ this.i++;
232
+ const target: Pattern = this.eat(":") ? this.pattern() : this.patternName(key);
233
+ props.push({ key: key.value, target, fallback: this.eat("=") ? this.expr() : null });
234
+ if (!this.eat(",")) {
235
+ this.close("}", open, "`,` or ");
236
+ break;
237
+ }
238
+ }
239
+ return { kind: "object", props, pos: open };
240
+ }
241
+ if (this.eat("[")) {
242
+ const items: ({ target: Pattern; fallback: Expr | null } | null)[] = [];
243
+ while (!this.eat("]")) {
244
+ if (this.eat(",")) {
245
+ items.push(null);
246
+ continue;
247
+ }
248
+ const target = this.pattern();
249
+ items.push({ target, fallback: this.eat("=") ? this.expr() : null });
250
+ if (!this.eat(",")) {
251
+ this.close("]", open, "`,` or ");
252
+ break;
253
+ }
254
+ }
255
+ return { kind: "array", items, pos: open };
256
+ }
257
+ return this.patternName(this.ident("a parameter name"));
258
+ },
259
+
260
+ patternName(token: Pos & { readonly value: string }): Pattern {
261
+ if (Object.hasOwn(KEYWORDS, token.value) || Object.hasOwn(BLOCK_WORDS, token.value)) {
262
+ throw new ParseError(token, `\`${token.value}\` cannot be a parameter name`);
263
+ }
264
+ return { kind: "name", name: token.value, pos: token };
265
+ },
266
+
267
+ /** `body` with `pattern`'s names bound from `source`; a missing value is null, or its fallback. */
268
+ bind(pattern: Pattern, source: Expr, body: Expr): Expr {
269
+ if (pattern.kind === "name") return { type: "let", name: pattern.name, value: source, body, pos: pattern.pos };
270
+ const holder = `#d${this.hidden++}`;
271
+ const from: Expr = { type: "ident", name: holder, pos: pattern.pos };
272
+ const parts =
273
+ pattern.kind === "object"
274
+ ? pattern.props.map((prop) => ({ ...prop, key: prop.key as string | number }))
275
+ : pattern.items.flatMap((item, index) => (item === null ? [] : [{ ...item, key: index as string | number }]));
276
+ let inner = body;
277
+ for (let index = parts.length - 1; index >= 0; index--) {
278
+ const { key, target, fallback } = parts[index];
279
+ let value: Expr = { type: "index", object: from, index: { type: "literal", value: key, pos: pattern.pos }, pos: pattern.pos };
280
+ if (fallback !== null) value = { type: "binary", op: "??", left: value, right: fallback, pos: pattern.pos };
281
+ inner = this.bind(target, value, inner);
282
+ }
283
+ return { type: "let", name: holder, value: source, body: inner, pos: pattern.pos };
284
+ },
285
+
286
+ isBlockStart(): boolean {
287
+ const next = this.peek(1);
288
+ // `if` is no block word, but a body starting with it is meant as one; block() explains what is allowed.
289
+ return this.isPunct("{") && next.t === "ident" && (Object.hasOwn(BLOCK_WORDS, next.value) || next.value === "if");
290
+ },
291
+
292
+ /** `{ const a = ...; return ... }`: declarations, then one return. */
293
+ block(): Expr {
294
+ const open = this.tokens[this.i++];
295
+ const decls: { pattern: Pattern; value: Expr }[] = [];
296
+ for (;;) {
297
+ while (this.peek().t === "sep") this.i++;
298
+ const word = this.peek();
299
+ if (word.t === "ident" && (word.value === "const" || word.value === "let" || word.value === "var")) {
300
+ this.i++;
301
+ const pattern = this.pattern();
302
+ if (!this.eat("=")) throw new ParseError(this.peek(), `expected \`=\` after the \`${word.value}\` name, found ${describe(this.peek())}`);
303
+ decls.push({ pattern, value: this.expr() });
304
+ continue;
305
+ }
306
+ if (word.t === "ident" && word.value === "return") {
307
+ this.i++;
308
+ let body = this.expr();
309
+ while (this.peek().t === "sep") this.i++;
310
+ this.close("}", open);
311
+ for (let index = decls.length - 1; index >= 0; index--) body = this.bind(decls[index].pattern, decls[index].value, body);
312
+ return body;
313
+ }
314
+ throw new ParseError(
315
+ word,
316
+ `a \`{ }\` function body holds \`const name = ...\` lines and one \`return ...\`; found ${describe(word)}. Use \`?:\` for conditions`,
317
+ );
318
+ }
183
319
  },
184
320
 
185
321
  conditional(): Expr {
@@ -198,13 +334,14 @@ const Parser = defineClass(
198
334
  let left = this.unary();
199
335
  for (;;) {
200
336
  const token = this.peek();
201
- if (token.t !== "punct") break;
202
- const precedence = PRECEDENCE[token.value];
203
- if (precedence === undefined || precedence < minPrecedence) break;
337
+ const op = token.t === "punct" || (token.t === "ident" && token.value === "in") ? token.value : null;
338
+ if (op === null || !Object.hasOwn(PRECEDENCE, op)) break;
339
+ const precedence = PRECEDENCE[op];
340
+ if (precedence < minPrecedence) break;
204
341
  this.nest(token);
205
342
  this.i++;
206
343
  const right = this.binary(precedence + 1);
207
- left = { type: "binary", op: token.value as BinaryOperator, left, right, pos: token };
344
+ left = { type: "binary", op: op as BinaryOperator, left, right, pos: token };
208
345
  }
209
346
  this.depth = saved;
210
347
  return left;
@@ -213,7 +350,7 @@ const Parser = defineClass(
213
350
  unary(): Expr {
214
351
  const saved = this.depth;
215
352
  const operators: Token[] = [];
216
- while (this.isPunct("!") || this.isPunct("-")) {
353
+ while (this.isPunct("!") || this.isPunct("-") || this.isTypeof()) {
217
354
  this.nest(this.peek());
218
355
  operators.push(this.tokens[this.i++]);
219
356
  }
@@ -228,29 +365,39 @@ const Parser = defineClass(
228
365
  }
229
366
  for (let k = operators.length - 1; k >= 0; k--) {
230
367
  const token = operators[k];
231
- expr = { type: "unary", op: token.t === "punct" && token.value === "!" ? "!" : "-", operand: expr, pos: token };
368
+ const op = token.t === "ident" ? "typeof" : token.t === "punct" && token.value === "!" ? "!" : "-";
369
+ expr = { type: "unary", op, operand: expr, pos: token };
232
370
  }
233
371
  this.depth = saved;
234
372
  return expr;
235
373
  },
236
374
 
375
+ /** `typeof` followed by something that starts an expression. */
376
+ isTypeof(): boolean {
377
+ const token = this.peek();
378
+ if (token.t !== "ident" || token.value !== "typeof") return false;
379
+ const next = this.peek(1);
380
+ if (next.t === "punct") return ["(", "[", "{", "!", "-"].includes(next.value);
381
+ return next.t !== "sep" && next.t !== "eof";
382
+ },
383
+
237
384
  postfix(): Expr {
238
385
  let expr = this.primary();
386
+ // Reading a property of null gives null already; after a `?.`, so does calling a method on it.
387
+ let optional = false;
239
388
  for (;;) {
240
- if (this.isPunct(".") || this.isPunct("[") || this.isPunct("(")) this.nest(this.peek());
241
- if (this.eat(".")) {
242
- const name = this.ident("a property or method name after `.`");
243
- if (this.isPunct("(")) {
244
- // `Math.round(x)` and `Object.entries(o)` are how models write the
245
- // built-ins; they parse as the plain calls `round(x)` and `entries(o)`.
246
- expr =
247
- expr.type === "ident" && (expr.name === "Math" || expr.name === "Object")
248
- ? { type: "call", name: name.value, ...this.args(), pos: name }
249
- : { type: "method", object: expr, name: name.value, ...this.args(), pos: name };
250
- } else {
251
- expr = { type: "member", object: expr, name: name.value, pos: name };
389
+ if (this.isPunct(".") || this.isPunct("?.") || this.isPunct("[") || this.isPunct("(")) this.nest(this.peek());
390
+ if (this.eat("?.")) {
391
+ optional = true;
392
+ if (!this.isPunct("[")) {
393
+ expr = this.property(expr, optional);
394
+ continue;
252
395
  }
253
- } else if (this.isPunct("[")) {
396
+ } else if (this.eat(".")) {
397
+ expr = this.property(expr, optional);
398
+ continue;
399
+ }
400
+ if (this.isPunct("[")) {
254
401
  const open = this.tokens[this.i++];
255
402
  const index = this.expr();
256
403
  this.close("]", open);
@@ -266,6 +413,23 @@ const Parser = defineClass(
266
413
  }
267
414
  },
268
415
 
416
+ /** `.name` or `.name(...)` after `object`. */
417
+ property(object: Expr, optional: boolean): Expr {
418
+ const name = this.ident("a property or method name after `.`");
419
+ if (!this.isPunct("(")) return { type: "member", object, name: name.value, pos: name };
420
+ if (object.type === "ident" && Object.hasOwn(NAMESPACES, object.name)) {
421
+ return { type: "call", name: NAMESPACES[object.name] + name.value, ...this.args(), pos: name };
422
+ }
423
+ return { type: "method", object, name: name.value, ...this.args(), optional, pos: name };
424
+ },
425
+
426
+ /** An expression, or `...expr` where a list item or argument may spread. */
427
+ item(): Expr {
428
+ const token = this.peek();
429
+ if (!this.eat("...")) return this.expr();
430
+ return { type: "spread", value: this.expr(), pos: token };
431
+ },
432
+
269
433
  args(): { args: Expr[]; named: NamedArg[] } {
270
434
  const open = this.tokens[this.i++];
271
435
  const args: Expr[] = [];
@@ -279,7 +443,7 @@ const Parser = defineClass(
279
443
  if (named.length > 0) {
280
444
  throw new ParseError(token, "positional arguments must come before named ones");
281
445
  }
282
- args.push(this.expr());
446
+ args.push(this.item());
283
447
  }
284
448
  if (!this.eat(",")) {
285
449
  this.close(")", open, "`,` or ");
@@ -327,7 +491,7 @@ const Parser = defineClass(
327
491
  this.i++;
328
492
  const items: Expr[] = [];
329
493
  while (!this.eat("]")) {
330
- items.push(this.expr());
494
+ items.push(this.item());
331
495
  if (!this.eat(",")) {
332
496
  this.close("]", token, "`,` or ");
333
497
  break;
@@ -343,13 +507,41 @@ const Parser = defineClass(
343
507
 
344
508
  object(open: Token): Expr {
345
509
  this.i++;
346
- const entries: { key: string; value: Expr; pos: Pos }[] = [];
510
+ const entries: { key: string | Expr | null; value: Expr; pos: Pos }[] = [];
347
511
  while (!this.eat("}")) {
348
512
  const key = this.peek();
513
+ if (this.eat("...")) {
514
+ entries.push({ key: null, value: this.expr(), pos: key });
515
+ if (!this.eat(",")) {
516
+ this.close("}", open, "`,` or ");
517
+ break;
518
+ }
519
+ continue;
520
+ }
521
+ if (this.eat("[")) {
522
+ const computed = this.expr();
523
+ this.close("]", key);
524
+ if (!this.eat(":")) throw new ParseError(this.peek(), `expected \`:\` after the object key, found ${describe(this.peek())}`);
525
+ entries.push({ key: computed, value: this.expr(), pos: key });
526
+ if (!this.eat(",")) {
527
+ this.close("}", open, "`,` or ");
528
+ break;
529
+ }
530
+ continue;
531
+ }
349
532
  if (key.t !== "ident" && key.t !== "str") {
350
- throw new ParseError(key, `expected an object key (a name or a string), found ${describe(key)}`);
533
+ throw new ParseError(key, `expected an object key (a name, a string or [expression]), found ${describe(key)}`);
351
534
  }
352
535
  this.i++;
536
+ // `{name}` is `{name: name}`.
537
+ if (key.t === "ident" && (this.isPunct(",") || this.isPunct("}"))) {
538
+ entries.push({ key: key.value, value: { type: "ident", name: key.value, pos: key }, pos: key });
539
+ if (!this.eat(",")) {
540
+ this.close("}", open, "`,` or ");
541
+ break;
542
+ }
543
+ continue;
544
+ }
353
545
  // `{Good for: …}`: models write labels as bare words; nothing else may follow a key, so read them as one.
354
546
  let name = key.value;
355
547
  if (key.t === "ident") {
@@ -1,4 +1,4 @@
1
- import type { CallExpr, Decl, Expr, Program, Statement } from "./ast";
1
+ import type { ArrowExpr, CallExpr, Decl, Expr, Program, Statement } from "./ast";
2
2
  import {
3
3
  ACTIONS,
4
4
  COMPONENTS,
@@ -24,7 +24,25 @@ export const ACTION_SPECS: ReadonlyMap<string, ComponentSpec> = new Map(Object.e
24
24
  type MethodName = (typeof METHODS)[keyof typeof METHODS][number];
25
25
 
26
26
  /** Methods whose single argument is an arrow `(item, index?) => ...`. */
27
- export const LAMBDA_METHODS: ReadonlySet<string> = new Set(["map", "filter", "find", "some", "every"]);
27
+ export const LAMBDA_METHODS: ReadonlySet<string> = new Set(["map", "filter", "find", "some", "every", "findIndex", "flatMap"]);
28
+
29
+ /** What a method's function receives, for those that take one. */
30
+ export const FUNCTION_PARAMS: ReadonlyMap<string, readonly string[]> = new Map([
31
+ ...[...LAMBDA_METHODS].map((name): [string, readonly string[]] => [name, ["item", "index"]]),
32
+ ["sort", ["a", "b"]],
33
+ ["reduce", ["total", "item", "index"]],
34
+ ]);
35
+
36
+ /** A method's function argument; a declared function's name, as in `rows.map(row)`, becomes `(a, b) => row(a, b)`. */
37
+ export function functionArg(arg: Expr, named: ReadonlyMap<string, Decl>, method: string, params: readonly string[] = []): Expr {
38
+ if (arg.type !== "ident" || params.includes(arg.name)) return arg;
39
+ const own = named.get(arg.name)?.value;
40
+ if (own?.type !== "arrow") return arg;
41
+ // `#` cannot appear in a written name, so these never shadow anything.
42
+ const names = own.params.slice(0, FUNCTION_PARAMS.get(method)?.length ?? 2).map((_, index) => `#${index}`);
43
+ const args = names.map((name): Expr => ({ type: "ident", name, pos: arg.pos }));
44
+ return { type: "arrow", params: names, body: { type: "call", name: arg.name, args, named: [], pos: arg.pos }, pos: arg.pos } satisfies ArrowExpr;
45
+ }
28
46
 
29
47
  type Arity = readonly [min: number, max: number];
30
48
 
@@ -32,8 +50,11 @@ const METHOD_ARITY: ReadonlyMap<string, Arity> = new Map(
32
50
  Object.entries({
33
51
  map: [1, 1], filter: [1, 1], find: [1, 1], some: [1, 1], every: [1, 1],
34
52
  join: [0, 1], slice: [0, 2], includes: [1, 1], indexOf: [1, 1], concat: [1, Infinity], sort: [0, 1],
53
+ reduce: [1, 2], flatMap: [1, 1], flat: [0, 1], at: [1, 1], findIndex: [1, 1], lastIndexOf: [1, 1], reverse: [0, 0],
35
54
  split: [1, 1], trim: [0, 0], toUpperCase: [0, 0], toLowerCase: [0, 0],
36
- startsWith: [1, 1], endsWith: [1, 1], replace: [2, 2], replaceAll: [2, 2], toFixed: [0, 1],
55
+ startsWith: [1, 1], endsWith: [1, 1], replace: [2, 2], replaceAll: [2, 2],
56
+ charAt: [1, 1], substring: [1, 2], padStart: [1, 2], padEnd: [1, 2], repeat: [1, 1], trimStart: [0, 0], trimEnd: [0, 0],
57
+ toFixed: [0, 1], toLocaleString: [0, 0], toString: [0, 1],
37
58
  } satisfies Record<MethodName, Arity>),
38
59
  );
39
60
 
@@ -41,12 +62,13 @@ const FUNCTION_ARITY: ReadonlyMap<string, Arity> = new Map(
41
62
  Object.entries({
42
63
  round: [1, 2], fmt: [1, 2], sum: [1, 1], min: [1, Infinity], max: [1, Infinity], abs: [1, 1], Load: [1, 1],
43
64
  keys: [1, 1], values: [1, 1], entries: [1, 1], floor: [1, 1], ceil: [1, 1], sqrt: [1, 1], pow: [2, 2],
65
+ Number: [1, 1], String: [1, 1], parseInt: [1, 2], parseFloat: [1, 1], "JSON.stringify": [1, 3], "Date.now": [0, 0],
44
66
  } satisfies Record<FunctionName, Arity>),
45
67
  );
46
68
 
47
69
  const ACTION_LIST = [...ACTION_SPECS].map(([name, spec]) => signature(name, spec)).join(", ");
48
70
  const ARROW_ONLY =
49
- "arrow functions can only be declared as a named function (`share = p => ...`) or passed to map, filter, find, some, every or sort";
71
+ "arrow functions can only be declared as a named function (`share = p => ...`) or passed to a list method such as map, filter, reduce or sort";
50
72
 
51
73
  /** The type of a value, as named in diagnostics. */
52
74
  export type Kind = "null" | "boolean" | "number" | "string" | "list" | "object" | "node" | "action" | "binding";
@@ -136,6 +158,10 @@ function signature(name: string, spec: ComponentSpec): string {
136
158
  return `${name}(${params.join(", ")})`;
137
159
  }
138
160
 
161
+ function isSpread(arg: Expr): boolean {
162
+ return arg.type === "spread";
163
+ }
164
+
139
165
  function arityText([min, max]: Arity): string {
140
166
  if (max === Infinity) return `at least ${min} argument${min === 1 ? "" : "s"}`;
141
167
  if (min === max) return `${min} argument${min === 1 ? "" : "s"}`;
@@ -366,10 +392,18 @@ const Validator = defineClass(
366
392
  return;
367
393
  case "object":
368
394
  for (const entry of expr.entries) {
369
- this.forbidden(entry.key, entry.pos);
395
+ if (typeof entry.key === "string") this.forbidden(entry.key, entry.pos);
396
+ else if (entry.key !== null) this.check(entry.key, params, refs);
370
397
  this.check(entry.value, params, refs);
371
398
  }
372
399
  return;
400
+ case "spread":
401
+ this.check(expr.value, params, refs);
402
+ return;
403
+ case "let":
404
+ this.check(expr.value, params, refs);
405
+ this.check(expr.body, [...params, expr.name], refs);
406
+ return;
373
407
  case "unary":
374
408
  this.check(expr.operand, params, refs);
375
409
  return;
@@ -428,20 +462,24 @@ const Validator = defineClass(
428
462
  expr.pos,
429
463
  `\`.${expr.name}()\` is not an allowed method.${hint} Lists: ${METHODS.list.join(", ")}. Text: ${METHODS.string.join(", ")}. Numbers: ${METHODS.number.join(", ")}.`,
430
464
  );
431
- } else if (expr.args.length < arity[0] || expr.args.length > arity[1]) {
465
+ } else if (!expr.args.some(isSpread) && (expr.args.length < arity[0] || expr.args.length > arity[1])) {
432
466
  this.diagnostics.report(expr.pos, `\`.${expr.name}()\` takes ${arityText(arity)}`);
433
467
  }
434
- const [first, ...rest] = expr.args;
435
- const sort = expr.name === "sort";
436
- if ((LAMBDA_METHODS.has(expr.name) || sort) && first !== undefined) {
468
+ const [written, ...rest] = expr.args;
469
+ const passes = FUNCTION_PARAMS.get(expr.name);
470
+ const first = written !== undefined && passes !== undefined ? functionArg(written, this.named, expr.name, params) : written;
471
+ if (passes !== undefined && first !== undefined) {
437
472
  if (first.type !== "arrow") {
438
- const example = sort ? "(a, b) => a.price - b.price" : "x => x.price";
473
+ const example =
474
+ expr.name === "sort" ? "(a, b) => a.price - b.price" : expr.name === "reduce" ? "(total, x) => total + x.price, 0" : "x => x.price";
439
475
  this.diagnostics.report(first.pos, `\`.${expr.name}()\` takes a function, as in \`${example}\``);
440
476
  this.check(first, params, refs);
441
477
  } else {
442
- if (first.params.length > 2) {
443
- const passes = sort ? "(a, b)" : "(item, index)";
444
- this.diagnostics.report(first.pos, `\`.${expr.name}()\` passes ${passes}; use at most 2 parameters`);
478
+ if (first.params.length > passes.length) {
479
+ this.diagnostics.report(
480
+ first.pos,
481
+ `\`.${expr.name}()\` passes (${passes.join(", ")}); use at most ${passes.length} parameters`,
482
+ );
445
483
  }
446
484
  this.check(first.body, [...params, ...first.params], refs);
447
485
  }
@@ -460,7 +498,7 @@ const Validator = defineClass(
460
498
  if (expr.named.length > 0) {
461
499
  this.diagnostics.report(expr.named[0].pos, `\`${expr.name}\` takes positional arguments only`);
462
500
  }
463
- if (expr.args.length > own.params.length) {
501
+ if (!expr.args.some(isSpread) && expr.args.length > own.params.length) {
464
502
  const count = own.params.length;
465
503
  this.diagnostics.report(expr.pos, `\`${expr.name}\` takes ${count} argument${count === 1 ? "" : "s"}`);
466
504
  }
@@ -473,7 +511,7 @@ const Validator = defineClass(
473
511
  if (expr.named.length > 0) {
474
512
  this.diagnostics.report(expr.named[0].pos, `\`${expr.name}\` takes positional arguments only`);
475
513
  }
476
- if (expr.args.length < arity[0] || expr.args.length > arity[1]) {
514
+ if (!expr.args.some(isSpread) && (expr.args.length < arity[0] || expr.args.length > arity[1])) {
477
515
  this.diagnostics.report(expr.pos, `\`${expr.name}\` takes ${arityText(arity)}: ${FUNCTIONS[expr.name as FunctionName]}`);
478
516
  } else if (expr.name === "Load") {
479
517
  this.literalPath(expr.args[0], "Load");
@@ -516,6 +554,9 @@ const Validator = defineClass(
516
554
  /** Maps arguments onto catalog params and checks what is knowable before evaluation. */
517
555
  catalogCall(expr: CallExpr, spec: ComponentSpec): void {
518
556
  const sig = signature(expr.name, spec);
557
+ for (const arg of expr.args.filter(isSpread)) {
558
+ this.diagnostics.report(arg.pos, `\`...\` cannot spread into ${expr.name}; pass the list or object itself`);
559
+ }
519
560
  const slots: (Expr | undefined)[] = spec.params.map((_, index) => expr.args[index]);
520
561
  if (expr.args.length > spec.params.length) {
521
562
  this.diagnostics.report(expr.args[spec.params.length].pos, `too many arguments: ${sig}`);
@@ -81,6 +81,25 @@ describe("paseo-plugin-genui core, instructions, and gallery", () => {
81
81
  expect(roots.map((root) => root.props.text)).toEqual(["a b b", "a$&!b"]);
82
82
  });
83
83
 
84
+ it("accepts a declared function's name as a list method's function", () => {
85
+ const compiled = compile(
86
+ [
87
+ "items = [{n: \"x\", v: 3}, {n: \"y\", v: 1}, {n: \"z\", v: 2}]",
88
+ "label = (p, i) => `${i}:${p.n}`",
89
+ "big = p => p.v > 1",
90
+ "byV = (a, b) => a.v - b.v",
91
+ "Text(items.filter(big).map(label).join(\",\"))",
92
+ "Text(items.sort(byV).map(p => p.n).join(\",\"))",
93
+ "row = p => [p.n, p.v]",
94
+ "Table([\"n\", \"v\"], items.map(row))",
95
+ ].join("\n"),
96
+ );
97
+ expect(compiled.diagnostics).toEqual([]);
98
+ const { roots } = evaluate(compiled.program!, initialState(compiled.program!));
99
+ expect(roots.slice(0, 2).map((root) => root.props.text)).toEqual(["0:x,1:z", "y,z,x"]);
100
+ expect(roots[2].props.rows).toEqual([["x", 3], ["y", 1], ["z", 2]]);
101
+ });
102
+
84
103
  it("covers all 86 catalog components in the gallery and compiles + evaluates every gallery spec", async () => {
85
104
  const files = await listGallery();
86
105
  expect(files.length).toBeGreaterThanOrEqual(170);
@@ -24,7 +24,7 @@ export const REFERENCE_MORE_GROUPS: readonly ComponentGroup[] = ["Inputs", "Widg
24
24
 
25
25
  export const UI_REFERENCE = `# Inline UI reference
26
26
  The \`\`\`ui language used by the Inline UI section below.
27
- Syntax: one statement per line. \`$x = 8\` is state inputs bind to; \`name = expr\` names a value and \`f = (a, b) => expr\` a function; each bare expression renders. JS expressions incl. ** ?: ?? \`\${x}\` [lists] {objects} x.y map/filter/find/sort/concat/join/replace/length, plus round(x, d), fmt(x, d), sum, min, max, abs, entries, Load(path). Named args go last: Slider($n, 0, 10, label: "N").
27
+ Syntax: one statement per line. \`$x = 8\` is state inputs bind to; \`name = expr\` names a value and \`f = (a, b) => expr\` a function; each bare expression renders. JS expressions incl. ** ?: ?? ?. ...spread, destructuring, \`x => { const y = ...; return y }\`, \`\${x}\`, the common list and text methods, Math.*, Object.keys/entries, Number(), String(), JSON.stringify; plus round(x, d), fmt(x, d), sum, Load(path). No if, for or reassignment. Named args go last: Slider($n, 0, 10, label: "N").
28
28
  Components (? optional; tone: neutral|good|warn|bad|info if meaningful; more in the next section):
29
29
  ${componentLines(REFERENCE_GROUPS)}
30
30
  Actions: ${actionList}; a list runs in order; Send posts as the user.
@@ -0,0 +1,114 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { compile, dataKey, evaluate, initialState } from "./core";
3
+
4
+ // JavaScript that agents write without thinking; each must compile and give the value JavaScript gives.
5
+ const PRELUDE = [
6
+ 'xs = [{n: "a", v: 3, tags: ["t", "u"]}, {n: "b", v: 1, tags: []}]',
7
+ "o = {a: 1, b: 2}",
8
+ 's = "Hello world"',
9
+ ].join("\n");
10
+
11
+ const CASES: Record<string, [source: string, expected: string]> = {
12
+ // list methods
13
+ reduce: ["xs.reduce((t, x) => t + x.v, 0)", "4"],
14
+ "reduce without a start": ["[1, 2, 3].reduce((a, b) => a + b)", "6"],
15
+ flatMap: ['xs.flatMap(x => x.tags).join("|")', "t|u"],
16
+ flat: ['[[1], [2, [3]]].flat().length', "3"],
17
+ at: ["xs.at(-1).n", "b"],
18
+ findIndex: ["xs.findIndex(x => x.v == 1)", "1"],
19
+ lastIndexOf: ["[1, 2, 1].lastIndexOf(1)", "2"],
20
+ reverse: ['[1, 2].reverse().join("")', "21"],
21
+ "reverse copies": ['[1, 2].reverse().concat(xs.map(x => x.n)).join("")', "21ab"],
22
+ // text and number methods
23
+ padStart: ['"5".padStart(2, "0")', "05"],
24
+ padEnd: ['"ab".padEnd(4, ".")', "ab.."],
25
+ substring: ["s.substring(0, 5)", "Hello"],
26
+ charAt: ["s.charAt(1)", "e"],
27
+ repeat: ['"=".repeat(3)', "==="],
28
+ trimStart: ['" a ".trimStart() + "|"', "a |"],
29
+ trimEnd: ['"|" + " a ".trimEnd()', "| a"],
30
+ "indexOf on text": ['s.indexOf("w")', "6"],
31
+ "lastIndexOf on text": ['s.lastIndexOf("o")', "7"],
32
+ "at on text": ["s.at(-1)", "d"],
33
+ toLocaleString: ["(1234567.891).toLocaleString()", "1,234,567.891"],
34
+ toFixed: ["(1/3).toFixed(2)", "0.33"],
35
+ // conversion and globals
36
+ Number: ['Number("3") + 1', "4"],
37
+ "Number of grouped text": ['Number("1,234")', "1234"],
38
+ "Number of junk": ['Number("x") ?? "none"', "none"],
39
+ String: ["String(3) + String(4)", "34"],
40
+ toString: ['(12).toString() + (255).toString(16) + true.toString() + "x".toString()', "12fftruex"],
41
+ parseInt: ['parseInt("42px") + parseInt("ff", 16)', "297"],
42
+ "parseInt of junk": ['parseInt("x") ?? "none"', "none"],
43
+ parseFloat: ['parseFloat("3.5 kg") * 2', "7"],
44
+ "computed object key": ['["a", "b"].reduce((acc, k) => ({...acc, [k]: 1}), {}).b', "1"],
45
+ "JSON.stringify": ["JSON.stringify(o)", '{"a":1,"b":2}'],
46
+ "Date.now": ["Date.now() > 0", "true"],
47
+ "Math and Object": ['Math.max(...[1, 5, 2]) + Object.keys(o).length', "7"],
48
+ // syntax
49
+ "optional chaining": ["xs[0]?.n", "a"],
50
+ "optional method on null": ['o.z?.toUpperCase() ?? "none"', "none"],
51
+ "optional index": ['o.z?.[0] ?? "none"', "none"],
52
+ "list spread": ["[...xs, {n: 'c'}].length", "3"],
53
+ "object spread": ["{...o, c: 3}.c + {...o, a: 9}.a", "12"],
54
+ "argument spread": ["max(...xs.map(x => x.v))", "3"],
55
+ "shorthand property": ['f = n => ({n})\nf("k").n', "k"],
56
+ "block arrow": ['xs.map(x => { return x.n }).join("")', "ab"],
57
+ "block arrow with const": ['xs.map(x => { const d = x.v * 2; return `${x.n}${d}` }).join(",")', "a6,b2"],
58
+ "object destructuring": ['xs.map(({n}) => n).join("")', "ab"],
59
+ "destructuring with rename and default": ['xs.map(({n: name, w = 0}) => name + w).join("")', "a0b0"],
60
+ "array destructuring of entries": ['entries(o).map(([k, v]) => k + v).join(",")', "a1,b2"],
61
+ "nested destructuring": ['[{p: {q: 1}}].map(({p: {q}}) => q).join("")', "1"],
62
+ "destructuring in const": ['f = x => { const {n, v} = x; return n + v }\nf(xs[0])', "a3"],
63
+ typeof: ['typeof 3 + typeof "x" + typeof null', "numberstringobject"],
64
+ in: ['("a" in o) + "," + ("z" in o) + "," + (1 in xs)', "true,false,true"],
65
+ // already supported; kept so they stay that way
66
+ "named function in map": ['f = (x, i) => i\nxs.map(f).join("")', "01"],
67
+ "strict equality": ["1 === 1 && 1 !== 2", "true"],
68
+ "includes on a list": ['xs.map(x => x.n).includes("a")', "true"],
69
+ "nested template": ['`${xs.length} items: ${xs.map(x => `${x.n}`).join()}`', "2 items: a,b"],
70
+ nullish: ['o.z ?? "none"', "none"],
71
+ };
72
+
73
+ describe("JavaScript idioms in the UI language", () => {
74
+ for (const [name, [source, expected]] of Object.entries(CASES)) {
75
+ it(name, () => {
76
+ const lines = source.split("\n");
77
+ const body = lines.pop()!;
78
+ const compiled = compile([PRELUDE, ...lines, `Text(${body})`].join("\n"));
79
+ expect(compiled.diagnostics.filter((d) => d.severity !== "warning")).toEqual([]);
80
+ const { roots, diagnostics } = evaluate(compiled.program!, initialState(compiled.program!));
81
+ expect(diagnostics).toEqual([]);
82
+ expect(roots[0].props.text).toBe(expected);
83
+ });
84
+ }
85
+
86
+ it("explains what a block body cannot hold", () => {
87
+ const { diagnostics } = compile("Text([1].map(x => { if (x) return 1 }).join())");
88
+ expect(diagnostics[0].message).toContain("`{ }` function body holds `const name = ...` lines and one `return ...`");
89
+ });
90
+
91
+ it("rejects spreading into a component", () => {
92
+ const { diagnostics } = compile('Row(...["a"])');
93
+ expect(diagnostics[0].message).toContain("cannot spread into Row");
94
+ });
95
+
96
+ it("does not copy a loaded object's own __proto__ key when spreading it", () => {
97
+ const compiled = compile('o = {...Load("d.json"), b: 2}\nKeyValue(o)');
98
+ const loaded = JSON.parse('{"__proto__": {"polluted": "yes"}, "a": 1}');
99
+ const data = new Map([[dataKey({ path: "d.json", raw: false }), { ok: true as const, value: loaded }]]);
100
+ const { roots } = evaluate(compiled.program!, initialState(compiled.program!, data), data);
101
+ const pairs = roots[0].props.pairs as object;
102
+ expect(Object.keys(pairs)).toEqual(["a", "b"]);
103
+ expect(Object.getPrototypeOf(pairs)).toBe(Object.prototype);
104
+ });
105
+
106
+ it("caps repeat and padStart at the text limit", () => {
107
+ const compiled = compile('Text("ab".repeat(100000))\nText("".padStart(200000))');
108
+ const { diagnostics } = evaluate(compiled.program!, initialState(compiled.program!));
109
+ expect(diagnostics.map((d) => d.message)).toEqual([
110
+ "text longer than 100000 characters",
111
+ "text longer than 100000 characters",
112
+ ]);
113
+ });
114
+ });