@opencode/codemode 2.0.0 → 2.0.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.
Files changed (62) hide show
  1. package/dist/data.d.ts +6 -5
  2. package/dist/data.js +47 -44
  3. package/dist/index.d.ts +0 -1
  4. package/dist/index.js +0 -1
  5. package/dist/interpreter/errors.d.ts +5 -3
  6. package/dist/interpreter/errors.js +51 -22
  7. package/dist/interpreter/execute.js +5 -3
  8. package/dist/interpreter/generators.d.ts +4 -0
  9. package/dist/interpreter/generators.js +25 -0
  10. package/dist/interpreter/globals.js +69 -47
  11. package/dist/interpreter/intrinsics.d.ts +13 -0
  12. package/dist/interpreter/intrinsics.js +82 -0
  13. package/dist/interpreter/model.d.ts +13 -36
  14. package/dist/interpreter/model.js +15 -45
  15. package/dist/interpreter/native.d.ts +19 -0
  16. package/dist/interpreter/native.js +40 -0
  17. package/dist/interpreter/objects.d.ts +106 -13
  18. package/dist/interpreter/objects.js +192 -65
  19. package/dist/interpreter/promises.d.ts +12 -13
  20. package/dist/interpreter/promises.js +59 -54
  21. package/dist/interpreter/references.d.ts +1 -0
  22. package/dist/interpreter/references.js +20 -33
  23. package/dist/interpreter/runner.d.ts +15 -11
  24. package/dist/interpreter/runner.js +21 -21
  25. package/dist/interpreter/runtime.d.ts +3 -3
  26. package/dist/interpreter/runtime.js +165 -327
  27. package/dist/interpreter/scope.js +6 -6
  28. package/dist/stdlib/array.d.ts +4 -2
  29. package/dist/stdlib/array.js +424 -32
  30. package/dist/stdlib/collections.d.ts +3 -7
  31. package/dist/stdlib/collections.js +291 -119
  32. package/dist/stdlib/console.d.ts +3 -2
  33. package/dist/stdlib/console.js +35 -30
  34. package/dist/stdlib/date.d.ts +1 -7
  35. package/dist/stdlib/date.js +93 -188
  36. package/dist/stdlib/json.d.ts +2 -2
  37. package/dist/stdlib/json.js +27 -27
  38. package/dist/stdlib/math.d.ts +2 -2
  39. package/dist/stdlib/math.js +96 -76
  40. package/dist/stdlib/number.d.ts +3 -4
  41. package/dist/stdlib/number.js +95 -60
  42. package/dist/stdlib/object.d.ts +4 -4
  43. package/dist/stdlib/object.js +128 -54
  44. package/dist/stdlib/regexp.d.ts +6 -8
  45. package/dist/stdlib/regexp.js +76 -68
  46. package/dist/stdlib/string.d.ts +2 -2
  47. package/dist/stdlib/string.js +213 -50
  48. package/dist/stdlib/url.d.ts +5 -13
  49. package/dist/stdlib/url.js +202 -102
  50. package/dist/stdlib/value.d.ts +5 -9
  51. package/dist/stdlib/value.js +16 -38
  52. package/dist/stdlib/web.d.ts +4 -4
  53. package/dist/stdlib/web.js +12 -10
  54. package/dist/tool-runtime.d.ts +2 -1
  55. package/dist/tool-runtime.js +2 -2
  56. package/package.json +1 -1
  57. package/dist/interpreter/host.d.ts +0 -41
  58. package/dist/interpreter/host.js +0 -44
  59. package/dist/interpreter/methods.d.ts +0 -4
  60. package/dist/interpreter/methods.js +0 -837
  61. package/dist/values.d.ts +0 -37
  62. package/dist/values.js +0 -56
@@ -1,56 +1,14 @@
1
- import { toProgram } from "../data.js";
2
- import { sync } from "../interpreter/host.js";
3
- import { InterpreterRuntimeError } from "../interpreter/model.js";
1
+ import { constructor, constants, methods } from "../interpreter/native.js";
2
+ import { InterpreterRuntimeError, rangeError } from "../interpreter/model.js";
4
3
  import { coercion, coerceToString } from "./value.js";
5
- export const numberMethods = new Set(["toFixed", "toPrecision", "toExponential", "toString", "valueOf"]);
6
- export const invokeNumberMethod = (value, name, args, node) => {
7
- const optNum = (index) => {
8
- const arg = args[index];
9
- if (arg === undefined)
10
- return undefined;
11
- if (typeof arg !== "number")
12
- throw new InterpreterRuntimeError(`Number.${name} expects a number argument.`, node);
13
- return arg;
14
- };
15
- let result;
16
- switch (name) {
17
- case "toFixed":
18
- result = value.toFixed(optNum(0));
19
- break;
20
- case "toExponential":
21
- result = value.toExponential(optNum(0));
22
- break;
23
- case "toPrecision": {
24
- const digits = optNum(0);
25
- result = digits === undefined ? value.toString() : value.toPrecision(digits);
26
- break;
27
- }
28
- case "toString": {
29
- const radix = optNum(0);
30
- if (radix !== undefined && (radix < 2 || radix > 36)) {
31
- throw new InterpreterRuntimeError("Number.toString radix must be between 2 and 36.", node);
32
- }
33
- result = value.toString(radix);
34
- break;
35
- }
36
- case "valueOf":
37
- result = value;
38
- break;
39
- default:
40
- throw new InterpreterRuntimeError(`Number method '${name}' is not available.`, node);
41
- }
42
- return toProgram(result, `Number.${name} result`);
43
- };
44
- const parseIntStatic = sync("Number.parseInt", (args, node) => {
45
- const radix = args[1];
46
- if (radix !== undefined && typeof radix !== "number") {
47
- throw new InterpreterRuntimeError("Number.parseInt expects a numeric radix.", node);
48
- }
49
- return parseInt(coerceToString(args[0]), radix);
50
- });
51
- export const numberGlobal = coercion("Number", {
52
- instanceOf: () => false,
53
- members: {
4
+ export const numberGlobal = (runner) => {
5
+ const protos = runner.prototypes;
6
+ const number = constructor(protos, protos.Number, {
7
+ name: "Number",
8
+ length: 1,
9
+ call: coercion(runner, "Number").call,
10
+ });
11
+ constants(number, {
54
12
  MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
55
13
  MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
56
14
  MAX_VALUE: Number.MAX_VALUE,
@@ -59,11 +17,88 @@ export const numberGlobal = coercion("Number", {
59
17
  NaN: Number.NaN,
60
18
  POSITIVE_INFINITY: Number.POSITIVE_INFINITY,
61
19
  NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY,
62
- isInteger: sync("Number.isInteger", (args) => Number.isInteger(args[0])),
63
- isFinite: sync("Number.isFinite", (args) => Number.isFinite(args[0])),
64
- isNaN: sync("Number.isNaN", (args) => Number.isNaN(args[0])),
65
- isSafeInteger: sync("Number.isSafeInteger", (args) => Number.isSafeInteger(args[0])),
66
- parseInt: parseIntStatic,
67
- parseFloat: sync("Number.parseFloat", (args) => parseFloat(coerceToString(args[0]))),
68
- },
69
- });
20
+ });
21
+ methods(protos, number, [
22
+ ["isInteger", 1, (_, args) => Number.isInteger(args[0])],
23
+ ["isFinite", 1, (_, args) => Number.isFinite(args[0])],
24
+ ["isNaN", 1, (_, args) => Number.isNaN(args[0])],
25
+ ["isSafeInteger", 1, (_, args) => Number.isSafeInteger(args[0])],
26
+ [
27
+ "parseInt",
28
+ 2,
29
+ (_, args, node) => {
30
+ const radix = args[1];
31
+ if (radix !== undefined && typeof radix !== "number") {
32
+ throw new InterpreterRuntimeError("Number.parseInt expects a numeric radix.", node);
33
+ }
34
+ return parseInt(coerceToString(args[0]), radix);
35
+ },
36
+ ],
37
+ ["parseFloat", 1, (_, args) => parseFloat(coerceToString(args[0]))],
38
+ ]);
39
+ const self = (thisValue, name, node) => {
40
+ if (typeof thisValue === "number")
41
+ return thisValue;
42
+ throw new InterpreterRuntimeError(`Number.prototype.${name} requires that 'this' be a Number.`, node);
43
+ };
44
+ const optNum = (name, arg, node) => {
45
+ if (arg === undefined)
46
+ return undefined;
47
+ if (typeof arg !== "number")
48
+ throw new InterpreterRuntimeError(`Number.${name} expects a number argument.`, node);
49
+ return arg;
50
+ };
51
+ methods(protos, protos.Number, [
52
+ [
53
+ "toFixed",
54
+ 1,
55
+ (thisValue, args, node) => self(thisValue, "toFixed", node).toFixed(optNum("toFixed", args[0], node)),
56
+ ],
57
+ [
58
+ "toExponential",
59
+ 1,
60
+ (thisValue, args, node) => self(thisValue, "toExponential", node).toExponential(optNum("toExponential", args[0], node)),
61
+ ],
62
+ [
63
+ "toPrecision",
64
+ 1,
65
+ (thisValue, args, node) => {
66
+ const value = self(thisValue, "toPrecision", node);
67
+ const digits = optNum("toPrecision", args[0], node);
68
+ return digits === undefined ? value.toString() : value.toPrecision(digits);
69
+ },
70
+ ],
71
+ [
72
+ "toString",
73
+ 1,
74
+ (thisValue, args, node) => {
75
+ const value = self(thisValue, "toString", node);
76
+ const radix = optNum("toString", args[0], node);
77
+ if (radix !== undefined && (radix < 2 || radix > 36)) {
78
+ throw rangeError("Number.toString radix must be between 2 and 36.", node);
79
+ }
80
+ return value.toString(radix);
81
+ },
82
+ ],
83
+ ["valueOf", 0, (thisValue, _, node) => self(thisValue, "valueOf", node)],
84
+ ]);
85
+ return number;
86
+ };
87
+ export const booleanGlobal = (runner) => {
88
+ const protos = runner.prototypes;
89
+ const boolean = constructor(protos, protos.Boolean, {
90
+ name: "Boolean",
91
+ length: 1,
92
+ call: coercion(runner, "Boolean").call,
93
+ });
94
+ const self = (thisValue, name, node) => {
95
+ if (typeof thisValue === "boolean")
96
+ return thisValue;
97
+ throw new InterpreterRuntimeError(`Boolean.prototype.${name} requires that 'this' be a Boolean.`, node);
98
+ };
99
+ methods(protos, protos.Boolean, [
100
+ ["toString", 0, (thisValue, _, node) => String(self(thisValue, "toString", node))],
101
+ ["valueOf", 0, (thisValue, _, node) => self(thisValue, "valueOf", node)],
102
+ ]);
103
+ return boolean;
104
+ };
@@ -1,7 +1,7 @@
1
- import { HostFunction } from "../interpreter/host.js";
2
1
  import { type AstNode } from "../interpreter/model.js";
3
2
  import { ProgramObject } from "../interpreter/objects.js";
4
3
  import { type Runner } from "../interpreter/runner.js";
5
- export declare const enumerableSource: (label: string, value: unknown, node: AstNode) => ProgramObject;
6
- export declare const objectAssign: (args: Array<unknown>, node: AstNode) => unknown;
7
- export declare const objectGlobal: <R>(runner: Runner<R>, toolKeys: (path: ReadonlyArray<string>) => ReadonlyArray<string>) => HostFunction<R>;
4
+ export declare const enumerableSource: <R>(runner: Runner<R>, label: string, value: unknown, node: AstNode) => ProgramObject;
5
+ export declare const objectAssign: <R>(runner: Runner<R>, args: Array<unknown>, node: AstNode) => unknown;
6
+ export declare const classTag: (value: unknown) => string;
7
+ export declare const objectGlobal: <R>(runner: Runner<R>, toolKeys: (path: ReadonlyArray<string>) => ReadonlyArray<string>) => import("../interpreter/objects.js").NativeFunction<R>;
@@ -1,59 +1,58 @@
1
1
  import { Effect } from "effect";
2
2
  import { toProgram } from "../data.js";
3
- import { HostFunction, sync, syncCall } from "../interpreter/host.js";
4
- import { AsyncIteratorSymbol, InterpreterRuntimeError, IteratorSymbol } from "../interpreter/model.js";
5
- import { getOwn, hasOwn, ownEntries, ownKeys, ProgramArray, ProgramObject, set } from "../interpreter/objects.js";
6
- import { containsOpaqueReference, describeValue, rejectCircularInsertion, typeofValue, } from "../interpreter/references.js";
3
+ import { constructor, methods, receiver } from "../interpreter/native.js";
4
+ import { AsyncIteratorSymbol, InterpreterRuntimeError, IteratorSymbol, rangeError, } from "../interpreter/model.js";
5
+ import { Callable, define, entries, enumerableKeys, getOwn, hasOwn, hasPrototype, hidden, keys, own, ProgramArray, ProgramDate, ProgramError, ProgramObject, ProgramPromise, ProgramRegExp, set, } from "../interpreter/objects.js";
6
+ import { containsOpaqueReference, describeValue, rejectCircularInsertion } from "../interpreter/references.js";
7
7
  import { preserveConsumerError } from "../interpreter/runner.js";
8
8
  import { ToolReference } from "../tool-runtime.js";
9
- import { Values } from "../values.js";
10
9
  import { groupBy } from "./collections.js";
11
10
  import { coerceToString } from "./value.js";
12
11
  // ToObject for enumeration.
13
- export const enumerableSource = (label, value, node) => {
12
+ export const enumerableSource = (runner, label, value, node) => {
14
13
  if (value === null || value === undefined) {
15
- throw new InterpreterRuntimeError(`${label} cannot convert ${describeValue(value)} to an object.`, node).as("TypeError");
14
+ throw new InterpreterRuntimeError(`${label} cannot convert ${describeValue(value)} to an object.`, node);
16
15
  }
17
- if (value instanceof Values.Promise) {
16
+ if (value instanceof ProgramPromise) {
18
17
  throw new InterpreterRuntimeError(`${label} received an un-awaited Promise; await it before inspecting the result.`, node, "InvalidDataValue");
19
18
  }
20
19
  if (value instanceof ToolReference) {
21
20
  throw new InterpreterRuntimeError(`${label} cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or search({ query }) for signatures.`, node, "InvalidDataValue");
22
21
  }
23
22
  if (typeof value === "string")
24
- return new ProgramArray([...value]);
23
+ return new ProgramArray(runner.prototypes.Array, [...value]);
25
24
  if (value instanceof ProgramObject)
26
25
  return value;
27
- return new ProgramObject();
26
+ return new ProgramObject(runner.prototypes.Object);
28
27
  };
29
- export const objectAssign = (args, node) => {
28
+ export const objectAssign = (runner, args, node) => {
30
29
  const target = args[0];
31
30
  // JS would box a primitive target; wrappers and primitives cannot hold fields here.
32
31
  if (!(target instanceof ProgramObject)) {
33
- throw new InterpreterRuntimeError(`Object.assign expects a data object or array target, received ${describeValue(target)}.`, node).as("TypeError");
32
+ throw new InterpreterRuntimeError(`Object.assign expects a data object or array target, received ${describeValue(target)}.`, node);
34
33
  }
35
34
  const seen = new Set();
36
35
  for (const source of args.slice(1)) {
37
36
  if (source === null || source === undefined)
38
37
  continue;
39
- const from = enumerableSource("Object.assign(...)", source, node);
40
- for (const key of ownKeys(from)) {
41
- if (typeof key === "symbol" && key !== AsyncIteratorSymbol && key !== IteratorSymbol)
42
- continue;
38
+ const from = enumerableSource(runner, "Object.assign(...)", source, node);
39
+ for (const key of enumerableKeys(from)) {
43
40
  rejectCircularInsertion(target, getOwn(from, key), "Object.assign result", node, seen);
44
41
  if (!set(target, key, getOwn(from, key))) {
45
- throw new InterpreterRuntimeError("Invalid array length", node).as("RangeError");
42
+ if (target instanceof ProgramArray && key === "length")
43
+ throw rangeError("Invalid array length", node);
44
+ throw new InterpreterRuntimeError(`Cannot assign to read only property '${String(key)}'.`, node);
46
45
  }
47
46
  }
48
47
  }
49
48
  return target;
50
49
  };
51
50
  const objectFromEntries = (runner, source, node) => {
52
- const out = new ProgramObject();
51
+ const out = new ProgramObject(runner.prototypes.Object);
53
52
  return Effect.gen(function* () {
54
53
  const cursor = yield* runner.syncIterator(source, node);
55
54
  if (cursor === undefined) {
56
- throw new InterpreterRuntimeError("Object.fromEntries expects a synchronous iterable of entries.", node).as("TypeError");
55
+ throw new InterpreterRuntimeError("Object.fromEntries expects a synchronous iterable of entries.", node);
57
56
  }
58
57
  while (true) {
59
58
  const step = yield* cursor.next;
@@ -61,46 +60,121 @@ const objectFromEntries = (runner, source, node) => {
61
60
  return out;
62
61
  yield* preserveConsumerError(cursor, Effect.sync(() => {
63
62
  if (!(step.value instanceof ProgramObject) || containsOpaqueReference(step.value)) {
64
- throw new InterpreterRuntimeError("Object.fromEntries expects [key, value] entry objects.", node).as("TypeError");
63
+ throw new InterpreterRuntimeError("Object.fromEntries expects [key, value] entry objects.", node);
65
64
  }
66
- set(out, coerceToString(getOwn(step.value, 0)), getOwn(step.value, 1));
65
+ define(out, coerceToString(getOwn(step.value, 0)), getOwn(step.value, 1));
67
66
  }));
68
67
  }
69
68
  });
70
69
  };
71
- const constructObject = (args, node) => {
72
- const first = args[0];
73
- if (first === null || first === undefined)
74
- return new ProgramObject();
75
- if (typeof first === "object")
76
- return first;
77
- throw new InterpreterRuntimeError(`Object(${typeof first}) wrapper objects are not supported; use the primitive value directly.`, node);
70
+ export const classTag = (value) => {
71
+ if (value === null)
72
+ return "Null";
73
+ if (value === undefined)
74
+ return "Undefined";
75
+ if (value instanceof ProgramArray)
76
+ return "Array";
77
+ if (value instanceof Callable)
78
+ return "Function";
79
+ if (value instanceof ProgramError)
80
+ return "Error";
81
+ if (value instanceof ProgramDate)
82
+ return "Date";
83
+ if (value instanceof ProgramRegExp)
84
+ return "RegExp";
85
+ if (typeof value === "string")
86
+ return "String";
87
+ if (typeof value === "number")
88
+ return "Number";
89
+ if (typeof value === "boolean")
90
+ return "Boolean";
91
+ return "Object";
78
92
  };
93
+ const propertyKey = (value) => value === AsyncIteratorSymbol || value === IteratorSymbol ? value : coerceToString(value);
79
94
  // Object constructs identically with or without new, like JS. Only `keys` copies its result into the
80
95
  // program; `values`, `entries`, `assign`, and `fromEntries` hand back the program's own values.
81
- export const objectGlobal = (runner, toolKeys) => new HostFunction({
82
- name: "Object",
83
- call: syncCall(constructObject),
84
- construct: syncCall(constructObject),
85
- instanceOf: (value) => value !== null && (typeof value === "object" || typeofValue(value) === "function"),
86
- members: {
87
- keys: sync("Object.keys", (args, node) => toProgram(args[0] instanceof ToolReference
88
- ? [...toolKeys(args[0].path)]
89
- : ownKeys(enumerableSource("Object.keys(...)", args[0], node)).filter((key) => typeof key === "string"), "Object.keys result")),
90
- values: sync("Object.values", (args, node) => new ProgramArray(ownEntries(enumerableSource("Object.values(...)", args[0], node)).map((entry) => entry[1]))),
91
- entries: sync("Object.entries", (args, node) => new ProgramArray(ownEntries(enumerableSource("Object.entries(...)", args[0], node)).map((entry) => new ProgramArray(entry)))),
92
- hasOwn: sync("Object.hasOwn", (args, node) => hasOwn(enumerableSource("Object.hasOwn(...)", args[0], node), args[1] === AsyncIteratorSymbol || args[1] === IteratorSymbol ? args[1] : String(args[1]))),
93
- is: sync("Object.is", (args, node) => {
94
- if (containsOpaqueReference(args[0]) || containsOpaqueReference(args[1])) {
95
- throw new InterpreterRuntimeError("Object.is requires data values.", node, "InvalidDataValue");
96
- }
97
- return Object.is(args[0], args[1]);
98
- }),
99
- assign: sync("Object.assign", objectAssign),
100
- fromEntries: new HostFunction({
101
- name: "Object.fromEntries",
102
- call: (args, node) => Effect.suspend(() => objectFromEntries(runner, args[0], node)),
103
- }),
104
- groupBy: groupBy(runner, "Object"),
105
- },
106
- });
96
+ export const objectGlobal = (runner, toolKeys) => {
97
+ const protos = runner.prototypes;
98
+ const construct = (args, node) => {
99
+ const first = args[0];
100
+ if (first === null || first === undefined)
101
+ return new ProgramObject(protos.Object);
102
+ if (typeof first === "object")
103
+ return first;
104
+ throw new InterpreterRuntimeError(`Object(${typeof first}) wrapper objects are not supported; use the primitive value directly.`, node);
105
+ };
106
+ const object = constructor(protos, protos.Object, {
107
+ name: "Object",
108
+ length: 1,
109
+ call: (_, args, node) => Effect.sync(() => construct(args, node)),
110
+ construct: (args, _, node) => Effect.sync(() => construct(args, node)),
111
+ });
112
+ methods(protos, object, [
113
+ [
114
+ "keys",
115
+ 1,
116
+ (_, args, node) => toProgram(protos, args[0] instanceof ToolReference
117
+ ? [...toolKeys(args[0].path)]
118
+ : keys(enumerableSource(runner, "Object.keys(...)", args[0], node)), "Object.keys result"),
119
+ ],
120
+ [
121
+ "values",
122
+ 1,
123
+ (_, args, node) => new ProgramArray(protos.Array, entries(enumerableSource(runner, "Object.values(...)", args[0], node)).map((entry) => entry[1])),
124
+ ],
125
+ [
126
+ "entries",
127
+ 1,
128
+ (_, args, node) => new ProgramArray(protos.Array, entries(enumerableSource(runner, "Object.entries(...)", args[0], node)).map((entry) => new ProgramArray(protos.Array, entry))),
129
+ ],
130
+ [
131
+ "hasOwn",
132
+ 2,
133
+ (_, args, node) => hasOwn(enumerableSource(runner, "Object.hasOwn(...)", args[0], node), propertyKey(args[1])),
134
+ ],
135
+ [
136
+ "is",
137
+ 2,
138
+ (_, args, node) => {
139
+ if (containsOpaqueReference(args[0]) || containsOpaqueReference(args[1])) {
140
+ throw new InterpreterRuntimeError("Object.is requires data values.", node, "InvalidDataValue");
141
+ }
142
+ return Object.is(args[0], args[1]);
143
+ },
144
+ ],
145
+ ["assign", 2, (_, args, node) => objectAssign(runner, args, node)],
146
+ ["fromEntries", 1, (_, args, node) => objectFromEntries(runner, args[0], node)],
147
+ ]);
148
+ define(object, "groupBy", groupBy(runner, "Object"), hidden);
149
+ methods(protos, protos.Object, [
150
+ [
151
+ "hasOwnProperty",
152
+ 1,
153
+ (thisValue, args, node) => hasOwn(receiver(ProgramObject, thisValue, "Object.prototype.hasOwnProperty", node), propertyKey(args[0])),
154
+ ],
155
+ [
156
+ "isPrototypeOf",
157
+ 1,
158
+ (thisValue, args, node) => hasPrototype(args[0], receiver(ProgramObject, thisValue, "Object.prototype.isPrototypeOf", node)),
159
+ ],
160
+ [
161
+ "propertyIsEnumerable",
162
+ 1,
163
+ (thisValue, args, node) => own(receiver(ProgramObject, thisValue, "Object.prototype.propertyIsEnumerable", node), propertyKey(args[0]))
164
+ ?.enumerable === true,
165
+ ],
166
+ ["toString", 0, (thisValue) => `[object ${classTag(thisValue)}]`],
167
+ ["toLocaleString", 0, (thisValue) => `[object ${classTag(thisValue)}]`],
168
+ [
169
+ "valueOf",
170
+ 0,
171
+ (thisValue, _, node) => {
172
+ if (thisValue === null || thisValue === undefined) {
173
+ throw new InterpreterRuntimeError("Object.prototype.valueOf called on null or undefined.", node);
174
+ }
175
+ return thisValue;
176
+ },
177
+ ],
178
+ ]);
179
+ return object;
180
+ };
@@ -1,10 +1,8 @@
1
+ import type { Prototypes } from "../interpreter/intrinsics.js";
1
2
  import { type AstNode } from "../interpreter/model.js";
2
- import { ProgramArray } from "../interpreter/objects.js";
3
- import { Values } from "../values.js";
4
- export declare const regexpMethods: Set<string>;
5
- export declare const regexpProperties: Set<string>;
3
+ import { ProgramArray, ProgramObject, ProgramRegExp } from "../interpreter/objects.js";
4
+ import type { Runner } from "../interpreter/runner.js";
6
5
  export declare const toHostRegex: (arg: unknown, method: string, node: AstNode, extraFlags?: string) => RegExp;
7
- export declare const matchToValue: (match: RegExpMatchArray) => ProgramArray;
8
- export declare const constructRegExp: (args: Array<unknown>, node: AstNode) => Values.RegExp;
9
- export declare const regexpGlobal: import("../interpreter/host.js").HostFunction<never>;
10
- export declare const invokeRegExpMethod: (value: Values.RegExp, name: string, args: Array<unknown>, node: AstNode) => unknown;
6
+ export declare const matchToValue: (protos: Prototypes, match: RegExpMatchArray) => ProgramArray;
7
+ export declare const constructRegExp: (protos: Prototypes, args: Array<unknown>, node: AstNode, proto?: ProgramObject) => ProgramRegExp;
8
+ export declare const regexpGlobal: <R>(runner: Runner<R>) => import("../interpreter/objects.js").NativeFunction<R>;
@@ -1,13 +1,9 @@
1
- import { sync, syncCall } from "../interpreter/host.js";
2
- import { InterpreterRuntimeError } from "../interpreter/model.js";
3
- import { ProgramArray, record, set } from "../interpreter/objects.js";
4
- import { Values } from "../values.js";
1
+ import { Effect } from "effect";
2
+ import { constructor, methods, prototypeFrom, receiver } from "../interpreter/native.js";
3
+ import { InterpreterRuntimeError, syntaxError } from "../interpreter/model.js";
4
+ import { define, defineAccessor, getOwn, ProgramArray, ProgramObject, ProgramRegExp, record, set, } from "../interpreter/objects.js";
5
5
  import { coerceToNumber, coerceToString } from "./value.js";
6
- export const regexpMethods = new Set(["test", "exec", "toString"]);
7
- export const regexpProperties = new Set([
8
- "source",
9
- "flags",
10
- "lastIndex",
6
+ const flagProperties = [
11
7
  "hasIndices",
12
8
  "global",
13
9
  "ignoreCase",
@@ -16,91 +12,53 @@ export const regexpProperties = new Set([
16
12
  "unicode",
17
13
  "unicodeSets",
18
14
  "dotAll",
19
- ]);
15
+ ];
20
16
  const regexFailureReason = (error) => (error instanceof Error ? error.message : String(error)).replace(/^Invalid regular expression:\s*/i, "");
21
17
  const escapeRegexHint = 'To match special characters like ( ) [ ] { } + * ? . literally, escape them with a backslash (e.g. "\\\\(") or test for them with String.includes instead.';
22
18
  export const toHostRegex = (arg, method, node, extraFlags = "") => {
23
19
  // Native parity: an undefined pattern behaves as an empty pattern.
24
20
  if (arg === undefined)
25
21
  return new RegExp("", extraFlags);
26
- if (arg instanceof Values.RegExp)
22
+ if (arg instanceof ProgramRegExp)
27
23
  return arg.regex;
28
24
  if (typeof arg === "string") {
29
25
  try {
30
26
  return new RegExp(arg, extraFlags);
31
27
  }
32
28
  catch (error) {
33
- throw new InterpreterRuntimeError(`String.${method} received the string ${JSON.stringify(arg)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`, node).as("SyntaxError");
29
+ throw syntaxError(`String.${method} received the string ${JSON.stringify(arg)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`, node);
34
30
  }
35
31
  }
36
32
  throw new InterpreterRuntimeError(`String.${method} expects a regular expression (a /pattern/flags literal or new RegExp(...)) or a string pattern, not ${arg === null ? "null" : typeof arg}.`, node);
37
33
  };
38
- export const matchToValue = (match) => {
39
- const result = new ProgramArray(Array.from(match, (group) => group));
34
+ export const matchToValue = (protos, match) => {
35
+ const result = new ProgramArray(protos.Array, Array.from(match, (group) => group));
40
36
  if (match.index !== undefined)
41
- set(result, "index", match.index);
37
+ define(result, "index", match.index);
42
38
  if (match.input !== undefined)
43
- set(result, "input", match.input);
39
+ define(result, "input", match.input);
44
40
  if (match.groups)
45
- set(result, "groups", record(match.groups));
41
+ define(result, "groups", record(protos.Object, match.groups));
46
42
  if (match.indices)
47
- set(result, "indices", indicesToValue(match.indices));
43
+ define(result, "indices", indicesToValue(protos, match.indices));
48
44
  return result;
49
45
  };
50
- export const constructRegExp = (args, node) => {
46
+ export const constructRegExp = (protos, args, node, proto = protos.RegExp) => {
51
47
  const first = args[0];
52
- const pattern = first instanceof Values.RegExp ? first.regex.source : first === undefined ? "" : coerceToString(first);
48
+ const pattern = first instanceof ProgramRegExp ? first.regex.source : first === undefined ? "" : coerceToString(first);
53
49
  const flagsArg = args[1];
54
50
  if (flagsArg !== undefined && typeof flagsArg !== "string") {
55
- throw new InterpreterRuntimeError(`RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`, node).as("SyntaxError");
51
+ throw syntaxError(`RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`, node);
56
52
  }
57
- const flags = flagsArg ?? (first instanceof Values.RegExp ? first.regex.flags : "");
53
+ const flags = flagsArg ?? (first instanceof ProgramRegExp ? first.regex.flags : "");
58
54
  try {
59
- return new Values.RegExp(pattern, flags);
55
+ return new ProgramRegExp(proto, pattern, flags);
60
56
  }
61
57
  catch (error) {
62
58
  const reason = regexFailureReason(error);
63
- throw new InterpreterRuntimeError(/flag/i.test(reason)
59
+ throw syntaxError(/flag/i.test(reason)
64
60
  ? `new RegExp(...) received invalid flags ${JSON.stringify(flags)} (${reason}). Valid flags are d, g, i, m, s, u, v, and y.`
65
- : `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`, node).as("SyntaxError");
66
- }
67
- };
68
- // RegExp constructs identically with or without new, like JS.
69
- export const regexpGlobal = sync("RegExp", constructRegExp, {
70
- construct: syncCall(constructRegExp),
71
- instanceOf: (value) => value instanceof Values.RegExp,
72
- members: {
73
- escape: sync("RegExp.escape", (args, node) => {
74
- if (typeof args[0] !== "string") {
75
- throw new InterpreterRuntimeError("RegExp.escape expects a string.", node).as("TypeError");
76
- }
77
- return RegExp.escape(args[0]);
78
- }),
79
- },
80
- });
81
- export const invokeRegExpMethod = (value, name, args, node) => {
82
- switch (name) {
83
- case "test":
84
- case "exec": {
85
- const input = coerceToString(args[0]);
86
- const lastIndex = value.lastIndex;
87
- const stateful = value.regex.global || value.regex.sticky;
88
- value.regex.lastIndex = toLength(lastIndex);
89
- if (name === "test") {
90
- const matched = value.regex.test(input);
91
- if (!stateful)
92
- value.lastIndex = lastIndex;
93
- return matched;
94
- }
95
- const matched = value.regex.exec(input);
96
- if (!stateful)
97
- value.lastIndex = lastIndex;
98
- return matched === null ? null : matchToValue(matched);
99
- }
100
- case "toString":
101
- return coerceToString(value);
102
- default:
103
- throw new InterpreterRuntimeError(`RegExp method '${name}' is not available.`, node);
61
+ : `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`, node);
104
62
  }
105
63
  };
106
64
  const toLength = (value) => {
@@ -109,12 +67,62 @@ const toLength = (value) => {
109
67
  return 0;
110
68
  return Math.min(Math.floor(number), Number.MAX_SAFE_INTEGER);
111
69
  };
112
- const indicesToValue = (indices) => {
113
- const range = (pair) => (pair === undefined ? undefined : new ProgramArray([...pair]));
114
- const result = new ProgramArray(Array.from(indices, range));
70
+ // RegExp constructs identically with or without new, like JS.
71
+ export const regexpGlobal = (runner) => {
72
+ const protos = runner.prototypes;
73
+ const proto = protos.RegExp;
74
+ const regexp = constructor(protos, proto, {
75
+ name: "RegExp",
76
+ length: 2,
77
+ call: (_, args, node) => Effect.sync(() => constructRegExp(protos, args, node)),
78
+ construct: (args, newTarget, node) => Effect.sync(() => constructRegExp(protos, args, node, prototypeFrom(newTarget, proto))),
79
+ });
80
+ methods(protos, regexp, [
81
+ [
82
+ "escape",
83
+ 1,
84
+ (_, args, node) => {
85
+ if (typeof args[0] !== "string")
86
+ throw new InterpreterRuntimeError("RegExp.escape expects a string.", node);
87
+ return RegExp.escape(args[0]);
88
+ },
89
+ ],
90
+ ]);
91
+ const self = (thisValue, name, node) => receiver(ProgramRegExp, thisValue, `RegExp.prototype.${name}`, node);
92
+ defineAccessor(proto, "source", (thisValue) => self(thisValue, "source").regex.source);
93
+ defineAccessor(proto, "flags", (thisValue) => self(thisValue, "flags").regex.flags);
94
+ for (const name of flagProperties)
95
+ defineAccessor(proto, name, (thisValue) => self(thisValue, name).regex[name]);
96
+ // exec/test run the host regex from the program-visible lastIndex and write it back only when g or y is set.
97
+ const run = (name) => [
98
+ name,
99
+ 1,
100
+ (thisValue, args, node) => {
101
+ const value = self(thisValue, name, node);
102
+ const input = coerceToString(args[0]);
103
+ const stateful = value.regex.global || value.regex.sticky;
104
+ value.regex.lastIndex = toLength(getOwn(value, "lastIndex"));
105
+ const matched = value.regex.exec(input);
106
+ if (stateful)
107
+ set(value, "lastIndex", value.regex.lastIndex);
108
+ if (name === "test")
109
+ return matched !== null;
110
+ return matched === null ? null : matchToValue(protos, matched);
111
+ },
112
+ ];
113
+ methods(protos, proto, [
114
+ run("exec"),
115
+ run("test"),
116
+ ["toString", 0, (thisValue, _, node) => coerceToString(self(thisValue, "toString", node))],
117
+ ]);
118
+ return regexp;
119
+ };
120
+ const indicesToValue = (protos, indices) => {
121
+ const range = (pair) => pair === undefined ? undefined : new ProgramArray(protos.Array, [...pair]);
122
+ const result = new ProgramArray(protos.Array, Array.from(indices, range));
115
123
  const groups = indices.groups;
116
- set(result, "groups", groups === undefined
124
+ define(result, "groups", groups === undefined
117
125
  ? undefined
118
- : record(Object.fromEntries(Object.entries(groups).map(([key, pair]) => [key, range(pair)]))));
126
+ : record(protos.Object, Object.fromEntries(Object.entries(groups).map(([key, pair]) => [key, range(pair)]))));
119
127
  return result;
120
128
  };
@@ -1,2 +1,2 @@
1
- export declare const stringMethods: Set<string>;
2
- export declare const stringGlobal: import("../interpreter/host.js").HostFunction<never>;
1
+ import { type Runner } from "../interpreter/runner.js";
2
+ export declare const stringGlobal: <R>(runner: Runner<R>) => import("../interpreter/objects.js").NativeFunction<R>;