affinirum 1.5.1 → 1.5.3

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 (68) hide show
  1. package/README.md +21 -4
  2. package/dst/Affinirum.d.ts +36 -29
  3. package/dst/Affinirum.js +124 -103
  4. package/dst/CallFrame.d.ts +11 -0
  5. package/dst/CallFrame.js +35 -0
  6. package/dst/LexicalScope.d.ts +13 -0
  7. package/dst/LexicalScope.js +27 -0
  8. package/dst/Node.d.ts +5 -4
  9. package/dst/Node.js +5 -5
  10. package/dst/ParserState.d.ts +3 -3
  11. package/dst/ParserState.js +40 -40
  12. package/dst/ScriptSpan.d.ts +10 -0
  13. package/dst/{ParserFrame.js → ScriptSpan.js} +20 -31
  14. package/dst/Type.d.ts +2 -0
  15. package/dst/Type.js +2 -0
  16. package/dst/Variable.d.ts +0 -4
  17. package/dst/Variable.js +0 -7
  18. package/dst/cjs/Affinirum.js +123 -102
  19. package/dst/cjs/CallFrame.js +39 -0
  20. package/dst/cjs/LexicalScope.js +31 -0
  21. package/dst/cjs/Node.js +5 -5
  22. package/dst/cjs/ParserState.js +40 -40
  23. package/dst/cjs/{ParserFrame.js → ScriptSpan.js} +22 -33
  24. package/dst/cjs/Type.js +2 -0
  25. package/dst/cjs/Variable.js +0 -7
  26. package/dst/cjs/native/Number.js +24 -11
  27. package/dst/cjs/native/notation/AN.js +2 -2
  28. package/dst/cjs/node/ArrayNode.js +4 -11
  29. package/dst/cjs/node/BlockNode.js +10 -6
  30. package/dst/cjs/node/CallNode.js +15 -28
  31. package/dst/cjs/node/CastNode.js +4 -4
  32. package/dst/cjs/node/ConstantNode.js +7 -5
  33. package/dst/cjs/node/JumpNode.js +4 -4
  34. package/dst/cjs/node/LoopNode.js +5 -5
  35. package/dst/cjs/node/ObjectNode.js +6 -12
  36. package/dst/cjs/node/SwitchNode.js +8 -7
  37. package/dst/cjs/node/VariableNode.js +5 -5
  38. package/dst/cjs/node/VariadicNode.js +10 -0
  39. package/dst/native/Number.js +24 -11
  40. package/dst/native/notation/AN.d.ts +1 -1
  41. package/dst/native/notation/AN.js +2 -2
  42. package/dst/node/ArrayNode.d.ts +4 -3
  43. package/dst/node/ArrayNode.js +4 -11
  44. package/dst/node/BlockNode.d.ts +6 -3
  45. package/dst/node/BlockNode.js +10 -6
  46. package/dst/node/CallNode.d.ts +4 -3
  47. package/dst/node/CallNode.js +15 -28
  48. package/dst/node/CastNode.d.ts +4 -3
  49. package/dst/node/CastNode.js +4 -4
  50. package/dst/node/ConstantNode.d.ts +5 -3
  51. package/dst/node/ConstantNode.js +7 -5
  52. package/dst/node/JumpNode.d.ts +4 -3
  53. package/dst/node/JumpNode.js +4 -4
  54. package/dst/node/LoopNode.d.ts +4 -3
  55. package/dst/node/LoopNode.js +5 -5
  56. package/dst/node/ObjectNode.d.ts +4 -3
  57. package/dst/node/ObjectNode.js +6 -12
  58. package/dst/node/SwitchNode.d.ts +4 -3
  59. package/dst/node/SwitchNode.js +8 -7
  60. package/dst/node/VariableNode.d.ts +4 -3
  61. package/dst/node/VariableNode.js +5 -5
  62. package/dst/node/VariadicNode.d.ts +4 -0
  63. package/dst/node/VariadicNode.js +6 -0
  64. package/package.json +10 -9
  65. package/dst/ParserFrame.d.ts +0 -13
  66. package/dst/StaticScope.d.ts +0 -13
  67. package/dst/StaticScope.js +0 -44
  68. package/dst/cjs/StaticScope.js +0 -48
package/README.md CHANGED
@@ -173,7 +173,8 @@ Casts can be followed by property access, index access, function calls, or anoth
173
173
 
174
174
  Native conversions use the following **void** handling:
175
175
 
176
- - `Format` returns an empty string for **void**.
176
+ - General `Format` conversions and `JSON.Format` return an empty string for **void**.
177
+ - `AN.Format` and `Affinirum.format` serialize **void** as the literal `null`, including array elements and object properties.
177
178
  - `Encode` returns a zero-length buffer for **void**.
178
179
  - `Decode` and `Parse` return **void** when their input value is **void**.
179
180
 
@@ -240,7 +241,7 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
240
241
  - **Object.Merge(values: ...(object | [object])):object** — Merge objects and arrays of objects
241
242
 
242
243
  #### AN
243
- - **AN.Format(value: ??, whitespace: string?):string** — Format a value as AN notation
244
+ - **AN.Format(value: ??, whitespace: string?):string** — Format a value as AN notation; **void** values are written as `null`
244
245
 
245
246
  #### JSON
246
247
  - **JSON.Format(value: (void | boolean | timestamp | float | integer | string | array | object), whitespace: string?):string** — Format a value as JSON
@@ -401,9 +402,25 @@ const result = expression.evaluate({ a: 10n, b: 20n }); // 30n
401
402
  During parsing, any valid name that is not recognized as a keyword, constant, or built-in function is treated as an input variable.
402
403
  Use the optional constructor configuration to specify the expected result `type`, enable `strict` handling of undeclared variables,
403
404
  or declare input `variables` and their types. An instance exposes the original `script`, its inferred result `type`,
404
- the inferred input types through `variables()`, and the parsed tree through `toString()`. `Affinirum.format()` formats
405
- a JavaScript value using Affinirum Notation.
405
+ the inferred input types through `variables()`, and the parsed tree through `toString()`.
406
+
407
+ `Affinirum.parse()` parses a single Affinirum Notation value into a JavaScript value. Empty or `undefined` input returns
408
+ `undefined`; invalid input throws an error. `Affinirum.format()` formats a JavaScript value as an Affinirum Notation string:
409
+
410
+ ```ts
411
+ const value = Affinirum.parse('["answer":42,"enabled":true]');
412
+ const notation = Affinirum.format(value);
413
+
414
+ Affinirum.format(undefined); // "null"
415
+ Affinirum.format(null); // "null"
416
+ Affinirum.format([1n, undefined]); // "[1,null]"
417
+ Affinirum.format({ missing: undefined }); // '["missing":null]'
418
+ ```
406
419
 
420
+ Both `Affinirum.format()` and `AN.Format()` write JavaScript `null` and `undefined` as the AN literal `null` at every nesting level.
421
+ Parsing that literal produces JavaScript `undefined`. This preserves array lengths and object properties containing **void** values,
422
+ including trailing array elements. Indented output follows the same rule.
423
+
407
424
  JavaScript `number` values map to **float**, while **integer** values map to `bigint`. Timestamps use `Date`, buffers use
408
425
  `ArrayBuffer`, and a **void** result is returned as `undefined`. Arrays, objects, and functions use their corresponding
409
426
  JavaScript values. Injected non-function values are checked against the types inferred or declared during compilation.
@@ -5,19 +5,20 @@ import { Type } from "./Type.js";
5
5
  import { Node } from "./Node.js";
6
6
  import { LoopNode } from "./node/LoopNode.js";
7
7
  import { SwitchNode } from "./node/SwitchNode.js";
8
- import { ParserFrame } from "./ParserFrame.js";
8
+ import { ScriptSpan } from "./ScriptSpan.js";
9
9
  import { ParserState } from "./ParserState.js";
10
- import { StaticScope } from "./StaticScope.js";
10
+ import { LexicalScope } from "./LexicalScope.js";
11
11
  export declare class Affinirum {
12
12
  static readonly keywords: string[];
13
13
  protected readonly _script: string;
14
14
  protected readonly _strict: boolean;
15
15
  protected readonly _root: Node;
16
- protected readonly _varframes: Map<string, ParserFrame>;
16
+ protected readonly _vartypes: Map<string, Type>;
17
+ protected readonly _varspans: Map<string, ScriptSpan>;
17
18
  protected readonly _variables: Map<string, Variable>;
18
19
  protected readonly _constants: Map<string, Record<string, Constant>>;
19
20
  protected readonly _functions: Map<string, Constant>;
20
- protected readonly _scope: StaticScope;
21
+ protected readonly _scope: LexicalScope;
21
22
  /**
22
23
  Creates compiled expression. Any parsed token not recognized as a constant or a function will be compiled as a variable.
23
24
  @param script Math expression to compile.
@@ -49,33 +50,39 @@ export declare class Affinirum {
49
50
  */
50
51
  variables(): Record<string, Type>;
51
52
  /**
52
- Evaluates compiled expression using provided variable values.
53
- @param values Record with variable names and values.
54
- @returns Calculated value.
53
+ Evaluates the compiled expression using the provided input values.
54
+ @param values Values for the expression's input variables. Omitted when there are no input variables.
55
+ @returns The evaluated result.
56
+ @throws If an input value is missing or evaluation fails.
55
57
  */
56
58
  evaluate(values?: Record<string, Value>): Value;
57
- /**
58
- Produces string in Affinirum Notation.
59
- @param value Value to format.
60
- @param whitespace Optional white space characters for readability.
61
- @returns String formatted in Affinirum Notation.
59
+ /** Parses an Affinirum Notation string into a JavaScript value.
60
+ @param value Affinirum Notation string to parse.
61
+ @returns The parsed value.
62
+ @throws If string is not a valid Affinirum Notation string.
63
+ */
64
+ static parse(value: string | undefined): Value;
65
+ /** Formats a JavaScript value as an Affinirum Notation string.
66
+ @param value Value to format. Null and undefined are formatted as the AN literal null.
67
+ @param whitespace Optional whitespace used for each indentation level.
68
+ @returns Affinirum Notation formatted string.
62
69
  */
63
70
  static format(value: Value, whitespace?: string): string;
64
- protected _list(state: ParserState, scope: StaticScope): Node;
65
- protected _unit(state: ParserState, scope: StaticScope): Node;
66
- protected _coalescence(state: ParserState, scope: StaticScope): Node;
67
- protected _disjunction(state: ParserState, scope: StaticScope): Node;
68
- protected _conjunction(state: ParserState, scope: StaticScope): Node;
69
- protected _negation(state: ParserState, scope: StaticScope): Node;
70
- protected _comparison(state: ParserState, scope: StaticScope): Node;
71
- protected _aggregate(state: ParserState, scope: StaticScope): Node;
72
- protected _product(state: ParserState, scope: StaticScope): Node;
73
- protected _signum(state: ParserState, scope: StaticScope): Node;
74
- protected _factor(state: ParserState, scope: StaticScope): Node;
75
- protected _accessor(state: ParserState, scope: StaticScope): Node;
76
- protected _term(state: ParserState, scope: StaticScope): Node;
77
- protected _function(state: ParserState, scope: StaticScope): Node;
78
- protected _loop(state: ParserState, scope: StaticScope): LoopNode;
79
- protected _switch(state: ParserState, scope: StaticScope): SwitchNode;
80
- protected _type(state: ParserState, scope: StaticScope): Type;
71
+ protected _list(state: ParserState, scope: LexicalScope): Node;
72
+ protected _unit(state: ParserState, scope: LexicalScope): Node;
73
+ protected _coalescence(state: ParserState, scope: LexicalScope): Node;
74
+ protected _disjunction(state: ParserState, scope: LexicalScope): Node;
75
+ protected _conjunction(state: ParserState, scope: LexicalScope): Node;
76
+ protected _negation(state: ParserState, scope: LexicalScope): Node;
77
+ protected _comparison(state: ParserState, scope: LexicalScope): Node;
78
+ protected _aggregate(state: ParserState, scope: LexicalScope): Node;
79
+ protected _product(state: ParserState, scope: LexicalScope): Node;
80
+ protected _signum(state: ParserState, scope: LexicalScope): Node;
81
+ protected _factor(state: ParserState, scope: LexicalScope): Node;
82
+ protected _accessor(state: ParserState, scope: LexicalScope): Node;
83
+ protected _term(state: ParserState, scope: LexicalScope): Node;
84
+ protected _function(state: ParserState, scope: LexicalScope): Node;
85
+ protected _loop(state: ParserState, scope: LexicalScope): LoopNode;
86
+ protected _switch(state: ParserState, scope: LexicalScope): SwitchNode;
87
+ protected _type(state: ParserState, scope: LexicalScope): Type;
81
88
  }
package/dst/Affinirum.js CHANGED
@@ -1,4 +1,4 @@
1
- import { formatAN } from "./native/notation/AN.js";
1
+ import { parseAN, formatAN } from "./native/notation/AN.js";
2
2
  import { funcOr, funcAnd, funcNot } from "./native/Boolean.js";
3
3
  import { funcAdd } from "./native/Aggregable.js";
4
4
  import { funcAt, funcHas } from "./native/Iterable.js";
@@ -22,18 +22,20 @@ import { ObjectNode } from "./node/ObjectNode.js";
22
22
  import { SwitchNode } from "./node/SwitchNode.js";
23
23
  import { VariableNode } from "./node/VariableNode.js";
24
24
  import { ParserState } from "./ParserState.js";
25
- import { StaticScope } from "./StaticScope.js";
25
+ import { LexicalScope } from "./LexicalScope.js";
26
+ import { CallFrame } from "./CallFrame.js";
26
27
  import { JumpException } from "./JumpException.js";
27
28
  export class Affinirum {
28
29
  static keywords = [...Keywords, ...Constants.map((c) => c[0])];
29
30
  _script;
30
31
  _strict;
31
32
  _root;
32
- _varframes = new Map();
33
+ _vartypes = new Map();
34
+ _varspans = new Map();
33
35
  _variables = new Map();
34
36
  _constants = new Map(Constants);
35
37
  _functions = new Map(Functions);
36
- _scope = new StaticScope();
38
+ _scope = new LexicalScope();
37
39
  /**
38
40
  Creates compiled expression. Any parsed token not recognized as a constant or a function will be compiled as a variable.
39
41
  @param script Math expression to compile.
@@ -46,7 +48,7 @@ export class Affinirum {
46
48
  this._strict = config?.strict ?? false;
47
49
  if (config?.variables) {
48
50
  for (const [vname, vtype] of Object.entries(config.variables)) {
49
- this._variables.set(vname, new Variable(vtype));
51
+ this._vartypes.set(vname, vtype);
50
52
  }
51
53
  }
52
54
  const state = new ParserState(this._script);
@@ -81,32 +83,31 @@ export class Affinirum {
81
83
  */
82
84
  variables() {
83
85
  const types = Object.create(null);
84
- const variables = this._scope.variables();
85
- for (const name in variables) {
86
- types[name] = variables[name].type;
86
+ for (const [name, variable] of this._variables) {
87
+ types[name] = variable.type;
87
88
  }
88
89
  return types;
89
90
  }
90
91
  /**
91
- Evaluates compiled expression using provided variable values.
92
- @param values Record with variable names and values.
93
- @returns Calculated value.
92
+ Evaluates the compiled expression using the provided input values.
93
+ @param values Values for the expression's input variables. Omitted when there are no input variables.
94
+ @returns The evaluated result.
95
+ @throws If an input value is missing or evaluation fails.
94
96
  */
95
97
  evaluate(values) {
96
- const variables = this._scope.variables();
97
- for (const name in variables) {
98
- if (!values || !Object.hasOwn(values, name)) {
99
- this._varframes.get(name)?.throwError(`undefined variable ${name}:\n`);
100
- }
101
- const variable = variables[name];
102
- const value = normalize(values?.[name] ?? undefined);
103
- if (!variable.type.acceptValue(value)) {
104
- this._varframes.get(name)?.throwError(`unexpected type ${Type.of(value)} for variable ${name} of type ${variable.type}:\n`);
105
- }
106
- variable.value = value;
107
- }
98
+ const frame = new CallFrame(undefined, this._scope.variables());
108
99
  try {
109
- return normalize(this._root.evaluate() ?? undefined);
100
+ for (const [name, variable] of this._variables) {
101
+ if (!values || !Object.hasOwn(values, name)) {
102
+ this._varspans.get(name)?.throwError(`undefined variable ${name}:\n`);
103
+ }
104
+ const value = normalize(values?.[name] ?? undefined);
105
+ if (!variable.type.acceptValue(value)) {
106
+ this._varspans.get(name)?.throwError(`unexpected type ${Type.of(value)} for variable ${name} of type ${variable.type}:\n`);
107
+ }
108
+ frame.add(variable, value);
109
+ }
110
+ return normalize(this._root.evaluate(frame) ?? undefined);
110
111
  }
111
112
  catch (e) {
112
113
  if (e instanceof JumpException) {
@@ -120,17 +121,24 @@ export class Affinirum {
120
121
  throw e;
121
122
  }
122
123
  }
123
- /**
124
- Produces string in Affinirum Notation.
125
- @param value Value to format.
126
- @param whitespace Optional white space characters for readability.
127
- @returns String formatted in Affinirum Notation.
124
+ /** Parses an Affinirum Notation string into a JavaScript value.
125
+ @param value Affinirum Notation string to parse.
126
+ @returns The parsed value.
127
+ @throws If string is not a valid Affinirum Notation string.
128
+ */
129
+ static parse(value) {
130
+ return parseAN(value);
131
+ }
132
+ /** Formats a JavaScript value as an Affinirum Notation string.
133
+ @param value Value to format. Null and undefined are formatted as the AN literal null.
134
+ @param whitespace Optional whitespace used for each indentation level.
135
+ @returns Affinirum Notation formatted string.
128
136
  */
129
137
  static format(value, whitespace) {
130
138
  return formatAN(value, whitespace);
131
139
  }
132
140
  _list(state, scope) {
133
- const frame = state.starts();
141
+ const span = state.start();
134
142
  const subnodes = [];
135
143
  while (!state.isEmpty) {
136
144
  subnodes.push(this._unit(state, scope));
@@ -141,7 +149,7 @@ export class Affinirum {
141
149
  state.next();
142
150
  }
143
151
  }
144
- return new BlockNode(frame.ends(state), subnodes);
152
+ return new BlockNode(span.end(state), subnodes);
145
153
  }
146
154
  _unit(state, scope) {
147
155
  return this._coalescence(state, scope);
@@ -171,17 +179,17 @@ export class Affinirum {
171
179
  return node;
172
180
  }
173
181
  _negation(state, scope) {
174
- const frame = state.starts();
182
+ const span = state.start();
175
183
  let negate = false;
176
184
  while (state.operator === funcNot) {
177
185
  negate = !negate;
178
- frame.ends(state);
186
+ span.end(state);
179
187
  state.next();
180
188
  }
181
189
  let node = this._comparison(state, scope);
182
190
  if (negate) {
183
- const fnode = new ConstantNode(frame, funcNot);
184
- node = new CallNode(frame, fnode, [node]);
191
+ const fnode = new ConstantNode(span, funcNot);
192
+ node = new CallNode(span, fnode, [node]);
185
193
  }
186
194
  return node;
187
195
  }
@@ -212,19 +220,19 @@ export class Affinirum {
212
220
  return node;
213
221
  }
214
222
  _signum(state, scope) {
215
- const frame = state.starts();
223
+ const span = state.start();
216
224
  let negate = false;
217
225
  while (state.operator === funcAdd || state.operator === funcSubtract) {
218
226
  if (state.operator === funcSubtract) {
219
227
  negate = !negate;
220
228
  }
221
- frame.ends(state);
229
+ span.end(state);
222
230
  state.next();
223
231
  }
224
232
  let node = this._factor(state, scope);
225
233
  if (negate) {
226
- const fnode = new ConstantNode(frame, funcNegate);
227
- node = new CallNode(frame, fnode, [node]);
234
+ const fnode = new ConstantNode(span, funcNegate);
235
+ node = new CallNode(span, fnode, [node]);
228
236
  }
229
237
  return node;
230
238
  }
@@ -237,14 +245,14 @@ export class Affinirum {
237
245
  return node;
238
246
  }
239
247
  _accessor(state, scope) {
240
- const frame = state.starts();
248
+ const span = state.start();
241
249
  let node = this._term(state, scope);
242
250
  while (state.isDot || state.isQuestion || state.isParenthesesOpen || state.isBracketsOpen || state.isCast) {
243
251
  if (state.isDot || state.isQuestion) { // property access or property existance operator
244
252
  const operator = state.isDot ? funcAt : funcHas;
245
253
  if (state.next().isLiteral && (typeof state.literal.value === "string" || typeof state.literal.value === "bigint")) {
246
- const fnode = new ConstantNode(frame.ends(state), operator);
247
- node = new CallNode(frame, fnode, [node, new ConstantNode(state, new Constant(state.literal.value))]);
254
+ const fnode = new ConstantNode(span.end(state), operator);
255
+ node = new CallNode(span, fnode, [node, new ConstantNode(state, new Constant(state.literal.value))]);
248
256
  state.next();
249
257
  }
250
258
  else if (state.isToken) {
@@ -258,18 +266,18 @@ export class Affinirum {
258
266
  break;
259
267
  }
260
268
  }
261
- const fnode = new ConstantNode(frame.ends(state), func);
262
- node = new CallNode(frame, fnode, subnodes);
269
+ const fnode = new ConstantNode(span.end(state), func);
270
+ node = new CallNode(span, fnode, subnodes);
263
271
  state.closeParentheses().next();
264
272
  }
265
273
  else {
266
- const fnode = new ConstantNode(frame.ends(state), func);
267
- node = new CallNode(frame, fnode, [node]);
274
+ const fnode = new ConstantNode(span.end(state), func);
275
+ node = new CallNode(span, fnode, [node]);
268
276
  }
269
277
  }
270
278
  else {
271
- const fnode = new ConstantNode(frame.ends(), operator);
272
- node = new CallNode(frame, fnode, [node, new ConstantNode(state, new Constant(state.token))]);
279
+ const fnode = new ConstantNode(span.end(state), operator);
280
+ node = new CallNode(span, fnode, [node, new ConstantNode(state, new Constant(state.token))]);
273
281
  state.next();
274
282
  }
275
283
  }
@@ -286,32 +294,32 @@ export class Affinirum {
286
294
  }
287
295
  }
288
296
  state.closeParentheses();
289
- node = new CallNode(frame.ends(state), node, subnodes);
297
+ node = new CallNode(span.end(state), node, subnodes);
290
298
  state.next();
291
299
  }
292
300
  else if (state.isBracketsOpen) { // index access operator
293
301
  const subnodes = [node, this._unit(state.next(), scope)];
294
302
  state.closeBrackets();
295
- const fnode = new ConstantNode(frame.ends(state), funcAt);
296
- node = new CallNode(frame, fnode, subnodes);
303
+ const fnode = new ConstantNode(span.end(state), funcAt);
304
+ node = new CallNode(span, fnode, subnodes);
297
305
  state.next();
298
306
  }
299
307
  else if (state.isCast) { // type cast operator
300
308
  const type = this._type(state.next(), scope);
301
- node = new CastNode(frame.ends(state), node, type);
309
+ node = new CastNode(span.end(state), node, type);
302
310
  }
303
311
  }
304
312
  return node;
305
313
  }
306
314
  _term(state, scope) {
307
315
  if (state.isLiteral) { // literal constant
308
- const frame = state.starts();
316
+ const span = state.start();
309
317
  const constant = new Constant(state.literal.value);
310
318
  state.next();
311
- return new ConstantNode(frame, constant);
319
+ return new ConstantNode(span, constant);
312
320
  }
313
321
  else if (state.isToken) { // variable
314
- const frame = state.starts();
322
+ const span = state.start();
315
323
  const constants = this._constants.get(state.token);
316
324
  if (constants != null) {
317
325
  if (!state.next().isDot) {
@@ -325,23 +333,17 @@ export class Affinirum {
325
333
  state.throwError(`unknown constant ${state.token}`);
326
334
  }
327
335
  state.next();
328
- return new ConstantNode(frame, constant);
336
+ return new ConstantNode(span, constant);
329
337
  }
330
- let variable = scope.get(state.token);
338
+ let variable = scope.get(state.token) ?? this._variables.get(state.token);
331
339
  if (variable == null) {
332
- variable = this._variables.get(state.token);
333
- if (variable == null) {
334
- if (this._strict) {
335
- state.throwError(`undefined variable ${state.token} in strict mode`);
336
- }
337
- else {
338
- variable = new Variable();
339
- }
340
+ const type = this._vartypes.get(state.token);
341
+ if (type == null && this._strict) {
342
+ state.throwError(`undefined variable ${state.token} in strict mode`);
340
343
  }
341
- scope.global(state.token, variable);
342
- }
343
- if (!this._varframes.has(state.token)) {
344
- this._varframes.set(state.token, state.starts());
344
+ variable = new Variable(type);
345
+ this._variables.set(state.token, variable);
346
+ this._varspans.set(state.token, state.start());
345
347
  }
346
348
  if (state.next().isAssignment) {
347
349
  if (!variable.assignable) {
@@ -349,29 +351,30 @@ export class Affinirum {
349
351
  }
350
352
  if (state.assignment.operator) {
351
353
  const operator = state.assignment.operator;
352
- const fnode = new ConstantNode(frame, operator);
353
- const subnode = new CallNode(frame, fnode, [new VariableNode(frame, variable), this._unit(state.next(), scope)]);
354
- return new VariableNode(frame, variable, subnode);
354
+ const fnode = new ConstantNode(span, operator);
355
+ const subnode = new CallNode(span, fnode, [new VariableNode(span, variable), this._unit(state.next(), scope)]);
356
+ return new VariableNode(span, variable, subnode);
355
357
  }
356
358
  else {
357
359
  const subnode = this._unit(state.next(), scope);
358
- return new VariableNode(frame, variable, subnode);
360
+ return new VariableNode(span, variable, subnode);
359
361
  }
360
362
  }
361
- return new VariableNode(frame, variable);
363
+ return new VariableNode(span, variable);
362
364
  }
363
365
  else if (state.isBracesOpen) { // code block
364
- const frame = state.starts();
366
+ const span = state.start();
367
+ const subscope = scope.subscope();
365
368
  const subnodes = [];
366
369
  while (!state.next().isBracesClose) {
367
- subnodes.push(this._unit(state, scope));
370
+ subnodes.push(this._unit(state, subscope));
368
371
  if (!state.isSemicolon) {
369
372
  break;
370
373
  }
371
374
  }
372
- frame.ends(state);
375
+ span.end(state);
373
376
  state.closeBraces().next();
374
- return new BlockNode(frame, subnodes);
377
+ return new BlockNode(span, subnodes, [...subscope.variables()]);
375
378
  }
376
379
  else if (state.isBracesClose) {
377
380
  state.throwError("unexpected closing braces");
@@ -385,7 +388,7 @@ export class Affinirum {
385
388
  state.throwError("unexpected closing parentheses");
386
389
  }
387
390
  else if (state.isBracketsOpen) { // array or object
388
- const frame = state.starts();
391
+ const span = state.start();
389
392
  const subnodes = [];
390
393
  let index = 0, colon = false;
391
394
  while (!state.next().isBracketsClose) {
@@ -406,12 +409,12 @@ export class Affinirum {
406
409
  break;
407
410
  }
408
411
  }
409
- frame.ends(state);
412
+ span.end(state);
410
413
  state.closeBrackets().next();
411
414
  if (colon) {
412
- return new ObjectNode(frame, subnodes.map(([k, v]) => [typeof k === "number" ? new ConstantNode(v, new Constant(String(k))) : k, v]));
415
+ return new ObjectNode(span, subnodes.map(([k, v]) => [typeof k === "number" ? new ConstantNode(v, new Constant(String(k))) : k, v]));
413
416
  }
414
- return new ArrayNode(frame, subnodes.map(([, v]) => v));
417
+ return new ArrayNode(span, subnodes.map(([, v]) => v));
415
418
  }
416
419
  else if (state.isBracketsClose) {
417
420
  state.throwError("unexpected closing brackets");
@@ -425,20 +428,20 @@ export class Affinirum {
425
428
  if (scope.has(token)) {
426
429
  state.throwError(`illegal redefinition of variable ${token}`);
427
430
  }
428
- const frame = state.starts();
431
+ const span = state.start();
429
432
  let type;
430
433
  if (state.next().isColon) {
431
434
  type = this._type(state.next(), scope);
432
435
  }
433
436
  const variable = new Variable(type, assignable);
434
- scope.local(token, variable);
437
+ scope.set(token, variable);
435
438
  if (state.isAssignment) {
436
439
  if (state.assignment.operator) {
437
440
  state.throwError(`illegal assignment operator with variable ${token}`);
438
441
  }
439
- return new VariableNode(frame, variable, this._unit(state.next(), scope));
442
+ return new VariableNode(span, variable, this._unit(state.next(), scope));
440
443
  }
441
- return new VariableNode(frame, variable);
444
+ return new VariableNode(span, variable);
442
445
  }
443
446
  else if (state.isTilda) {
444
447
  return this._function(state, scope);
@@ -471,7 +474,7 @@ export class Affinirum {
471
474
  state.throwError("unexpected expression token");
472
475
  }
473
476
  _function(state, scope) {
474
- const frame = state.starts();
477
+ const span = state.start();
475
478
  state.next().openParentheses();
476
479
  let variadic = false;
477
480
  const variables = new Map();
@@ -480,8 +483,11 @@ export class Affinirum {
480
483
  state.throwError("missing function argument name");
481
484
  }
482
485
  const token = state.token;
483
- if (scope.get(token)) {
484
- state.throwError("variable redefinition");
486
+ if (variables.has(token)) {
487
+ state.throwError(`duplicate function argument name ${token}`);
488
+ }
489
+ if (scope.has(token)) {
490
+ state.throwError(`variable ${token} redefinition`);
485
491
  }
486
492
  let argType = Type.Unknown;
487
493
  if (state.next().isColon) {
@@ -506,31 +512,46 @@ export class Affinirum {
506
512
  }
507
513
  state.closeParentheses().next();
508
514
  const retType = state.isColon ? this._type(state.next(), scope) : Type.Unknown;
509
- frame.ends(state);
515
+ span.end(state);
510
516
  const args = Array.from(variables.values());
511
- const subnode = this._unit(state, scope.subscope(variables));
512
- const func = (...values) => {
513
- args.forEach((arg, ix) => arg.value = normalize(values[ix]));
514
- return normalize(subnode.evaluate());
517
+ const subscope = scope.subscope(variables);
518
+ const subnode = this._unit(state, subscope);
519
+ const createFunction = (frame) => (...values) => {
520
+ const subframe = frame.subframe(subscope.variables());
521
+ try {
522
+ args.forEach((arg, ix) => subframe.set(arg, normalize(values[ix])));
523
+ return normalize(subnode.evaluate(subframe));
524
+ }
525
+ catch (e) {
526
+ if (e instanceof JumpException) {
527
+ if (e.jump === "return") {
528
+ return normalize(e.value);
529
+ }
530
+ if (e.jump === "stop" || e.jump === "next") {
531
+ subnode.throwError(`unexpected ${e.jump} jump`);
532
+ }
533
+ }
534
+ throw e;
535
+ }
515
536
  };
516
- const constant = new Constant(func, Type.functionType(retType, args.map((v) => v.type), variadic));
517
- return new ConstantNode(frame, constant, subnode);
537
+ const constant = new Constant(createFunction, Type.functionType(retType, args.map((v) => v.type), variadic));
538
+ return new ConstantNode(span, constant, subnode, createFunction);
518
539
  }
519
540
  _loop(state, scope) {
520
- const frame = state.starts();
541
+ const span = state.start();
521
542
  const cnode = this._unit(state.next(), scope);
522
- frame.ends(state);
523
- return new LoopNode(frame, cnode, this._unit(state, scope));
543
+ span.end(state);
544
+ return new LoopNode(span, cnode, this._unit(state, scope));
524
545
  }
525
546
  _switch(state, scope) {
526
- const frame = state.starts();
547
+ const span = state.start();
527
548
  const cnode = this._unit(state.next(), scope);
528
- frame.ends(state);
549
+ span.end(state);
529
550
  const cthen = this._unit(state, scope);
530
551
  const celse = state.isElse
531
552
  ? this._unit(state.next(), scope)
532
- : new ConstantNode(state.starts(), Constant.Null);
533
- return new SwitchNode(frame, cnode, [cthen, celse]);
553
+ : new ConstantNode(state.start(), Constant.Null);
554
+ return new SwitchNode(span, cnode, [cthen, celse]);
534
555
  }
535
556
  _type(state, scope) {
536
557
  if (state.isType) { // literal type
@@ -0,0 +1,11 @@
1
+ import type { Value } from "./Value.js";
2
+ import type { Variable } from "./Variable.js";
3
+ export declare class CallFrame {
4
+ protected readonly _superframe?: CallFrame;
5
+ protected readonly _values: Map<Variable, Value>;
6
+ constructor(superframe?: CallFrame, variables?: Iterable<Variable>);
7
+ subframe(variables: Iterable<Variable>): CallFrame;
8
+ add(variable: Variable, value?: Value): void;
9
+ get(variable: Variable): Value;
10
+ set(variable: Variable, value: Value): Value;
11
+ }
@@ -0,0 +1,35 @@
1
+ export class CallFrame {
2
+ _superframe;
3
+ _values = new Map();
4
+ constructor(superframe, variables = []) {
5
+ this._superframe = superframe;
6
+ for (const variable of variables) {
7
+ this.add(variable);
8
+ }
9
+ }
10
+ subframe(variables) {
11
+ return new CallFrame(this, variables);
12
+ }
13
+ add(variable, value = undefined) {
14
+ this._values.set(variable, value);
15
+ }
16
+ get(variable) {
17
+ if (this._values.has(variable)) {
18
+ return this._values.get(variable);
19
+ }
20
+ if (this._superframe) {
21
+ return this._superframe.get(variable);
22
+ }
23
+ throw new Error("variable is not declared in call frame");
24
+ }
25
+ set(variable, value) {
26
+ if (this._values.has(variable)) {
27
+ this._values.set(variable, value);
28
+ return value;
29
+ }
30
+ if (this._superframe) {
31
+ return this._superframe.set(variable, value);
32
+ }
33
+ throw new Error("variable is not declared in call frame");
34
+ }
35
+ }