affinirum 1.5.0 → 1.5.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 (54) hide show
  1. package/README.md +30 -14
  2. package/dst/Affinirum.d.ts +33 -26
  3. package/dst/Affinirum.js +58 -44
  4. package/dst/ParserState.js +23 -79
  5. package/dst/Scope.d.ts +16 -0
  6. package/dst/Scope.js +49 -0
  7. package/dst/atom/ArrayAtom.js +4 -1
  8. package/dst/cjs/Affinirum.js +57 -43
  9. package/dst/cjs/ParserState.js +22 -78
  10. package/dst/cjs/Scope.js +53 -0
  11. package/dst/cjs/atom/ArrayAtom.js +4 -1
  12. package/dst/cjs/native/Aggregable.js +1 -1
  13. package/dst/cjs/native/Boolean.js +3 -1
  14. package/dst/cjs/native/Buffer.js +32 -3
  15. package/dst/cjs/native/Enumerable.js +5 -3
  16. package/dst/cjs/native/Float.js +17 -5
  17. package/dst/cjs/native/Integer.js +41 -13
  18. package/dst/cjs/native/Iterable.js +6 -4
  19. package/dst/cjs/native/Number.js +45 -1
  20. package/dst/cjs/native/String.js +68 -22
  21. package/dst/cjs/native/Timestamp.js +74 -17
  22. package/dst/cjs/native/Unknown.js +1 -1
  23. package/dst/cjs/native/notation/AN.js +152 -11
  24. package/dst/cjs/native/notation/IP.js +1 -1
  25. package/dst/cjs/native/notation/JSON.js +1 -1
  26. package/dst/cjs/node/BlockNode.js +5 -4
  27. package/dst/cjs/node/CallNode.js +7 -5
  28. package/dst/cjs/node/SwitchNode.js +7 -9
  29. package/dst/native/Aggregable.js +1 -1
  30. package/dst/native/Boolean.js +3 -1
  31. package/dst/native/Buffer.d.ts +2 -0
  32. package/dst/native/Buffer.js +29 -2
  33. package/dst/native/Enumerable.js +5 -3
  34. package/dst/native/Float.js +17 -5
  35. package/dst/native/Integer.js +41 -13
  36. package/dst/native/Iterable.js +6 -4
  37. package/dst/native/Number.d.ts +4 -0
  38. package/dst/native/Number.js +40 -0
  39. package/dst/native/String.d.ts +2 -7
  40. package/dst/native/String.js +65 -14
  41. package/dst/native/Timestamp.d.ts +4 -2
  42. package/dst/native/Timestamp.js +71 -16
  43. package/dst/native/Unknown.js +1 -1
  44. package/dst/native/notation/AN.d.ts +1 -0
  45. package/dst/native/notation/AN.js +152 -12
  46. package/dst/native/notation/IP.js +1 -1
  47. package/dst/native/notation/JSON.js +1 -1
  48. package/dst/node/BlockNode.js +5 -4
  49. package/dst/node/CallNode.js +7 -5
  50. package/dst/node/SwitchNode.js +7 -9
  51. package/package.json +1 -1
  52. package/dst/StaticScope.d.ts +0 -13
  53. package/dst/StaticScope.js +0 -44
  54. package/dst/cjs/StaticScope.js +0 -48
package/README.md CHANGED
@@ -23,7 +23,7 @@ Target: ES2022 [browser+Node.js][ESM+CJS].
23
23
  ## Specifications
24
24
 
25
25
  A script may contain multiple expressions separated by semicolons, as well as blocks of statements.
26
- The value of a block is defined by the value of its last expression.
26
+ The value of a block is defined by the value of its last expression. An empty block has type **void** and evaluates to JavaScript `undefined`.
27
27
  - Scientific notation is supported for floating point numbers, like *0.1281e+2*.
28
28
  - ISO Timestamps prefixed with **@**, like *@2025-05-11T19:09:21.320Z*.
29
29
  - Hexadecimal buffer values are enclosed in backticks (**\`**), like *\`10ab0901\`*.
@@ -94,6 +94,12 @@ substitutability or prove that every accepted expression is safe for every possi
94
94
  function parameter may receive **null**, `undefined`, or be omitted.
95
95
  - An optional type such as **integer?** is the union **void | integer**. Optional parameters may receive **null**, `undefined`,
96
96
  or be omitted.
97
+ - A call with known argument types must match one complete function overload. Parameter matches from separate overloads
98
+ are not combined to accept a call.
99
+ - Object types are open structural constraints: required properties and their values are checked, while additional
100
+ properties are allowed.
101
+ - Tuple types are prefix constraints: the declared item types are checked in order, optional trailing items may be
102
+ omitted, and additional items are allowed.
97
103
  - Function compatibility is deliberately flexible. The accepted argument-count ranges only need to overlap;
98
104
  one function's complete arity range does not need to contain the other's.
99
105
  - A callback may declare fewer parameters than the caller provides. Additional arguments are ignored at runtime,
@@ -159,7 +165,7 @@ Casts can be followed by property access, index access, function calls, or anoth
159
165
  - Boolean conjunction (Logical AND) assignment: **&=**
160
166
  - Arithmetic addition assignment: **+=**
161
167
  - Arithmetic subtraction assignment: **-=**
162
- - Arithmetic multiplication assignment: ***=**
168
+ - Arithmetic multiplication assignment: **\*=**
163
169
  - Arithmetic division assignment: **/=**
164
170
  - Arithmetic remainder assignment: **%=**
165
171
 
@@ -184,7 +190,7 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
184
190
  #### Timestamp
185
191
  - **Timestamp.Now():timestamp** — Current date and time
186
192
  - **Timestamp.Epoch(value: float | integer, epoch: timestamp?):timestamp** — Create timestamp from milliseconds
187
- - **Timestamp.Decode(value: buffer?, encoding: string?, offset: integer?):timestamp?** — Decode a timestamp using `i64` (default) or `i64le`
193
+ - **Timestamp.Decode(value: buffer?, encoding: string?, offset: integer?):timestamp?** — Decode a timestamp using `i32` or `i32le` minutes, or `i64` (default) or `i64le` milliseconds since the Unix epoch
188
194
  - **Timestamp.Parse(value: string?):timestamp?** — Parse a string as a timestamp
189
195
 
190
196
  #### Float
@@ -225,7 +231,7 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
225
231
 
226
232
  #### Array
227
233
  - **Array.Join(values: ...array):array** — Join arrays of any depths into a single array
228
- - **Array.Range(inclusiveFrom: integer, exclusiveTo: integer):array** — New array filled with integers in range
234
+ - **Array.Range(a: integer, b: integer):array** — Integers from the lower endpoint (inclusive) to the higher endpoint (exclusive)
229
235
  - **Array.Unique(value: array):array** — Array of unique values
230
236
  - **Array.Intersection(a1: array, a2: array):array** — Common values from two arrays
231
237
  - **Array.Difference(a1: array, a2: array):array** — Symmetrical difference between arrays
@@ -252,11 +258,12 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
252
258
  - **??.Equal(value: ??):boolean** — Equals to
253
259
  - **??.Unequal(value: ??):boolean** — Not equals to
254
260
  - **(boolean | buffer | function).Encode():buffer** — Encode value to buffer
255
- - **(void | timestamp | float | integer | string | array | object).Encode(encoding: string?):buffer** — Encode a value; defaults are `i64` for timestamps and integers, `f64` for floats, and `utf8` for strings
261
+ - **(void | timestamp | float | integer | string | array | object).Encode(encoding: string?):buffer** — Encode a value; timestamps support `i32` and `i32le` minutes or `i64` and `i64le` milliseconds, while defaults are `i64` for timestamps and integers, `f64` for floats, and `utf8` for strings
256
262
  - **(boolean | string | function).Format():string** — Format value to string
257
263
  - **(void | timestamp | float | integer | buffer | array | object).Format(formatting: string?):string** — Format a value; buffers use `hex` by default and also support `base64`
258
264
 
259
265
  #### Aggregable Functions
266
+ - **float.Add(value: float):float** — Add a float
260
267
  - **float.Add(value: integer):float** — Add an integer
261
268
  - **integer.Add(value: float):float** — Add a float
262
269
  - **integer.Add(value: integer):integer** — Add an integer
@@ -287,12 +294,12 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
287
294
  - **buffer.Slice(start: integer?, end: integer?):buffer** — Slice section
288
295
  - **string.Slice(start: integer?, end: integer?):string** — Slice section
289
296
  - **array.Slice(start: integer?, end: integer?):array** — Slice section
290
- - **buffer.Splice(start: integer, remove: integer, inject: ...(buffer | string | array)):buffer** — Splice section
291
- - **string.Splice(start: integer, remove: integer, inject: ...(buffer | string | array)):string** — Splice section
292
- - **array.Splice(start: integer, remove: integer, inject: ...(buffer | string | array)):array** — Splice section
293
- - **buffer.Inject(start: integer, inject: ...(buffer | string | array)):buffer** — Inject section
294
- - **string.Inject(start: integer, inject: ...(buffer | string | array)):string** — Inject section
295
- - **array.Inject(start: integer, inject: ...(buffer | string | array)):array** — Inject section
297
+ - **buffer.Splice(start: integer, remove: integer, inject: ...buffer):buffer** — Splice section
298
+ - **string.Splice(start: integer, remove: integer, inject: ...string):string** — Splice section
299
+ - **array.Splice(start: integer, remove: integer, inject: ...array):array** — Splice section
300
+ - **buffer.Inject(start: integer, inject: ...buffer):buffer** — Inject section
301
+ - **string.Inject(start: integer, inject: ...string):string** — Inject section
302
+ - **array.Inject(start: integer, inject: ...array):array** — Inject section
296
303
 
297
304
  #### Iterable Functions
298
305
  - **(buffer | string | array | object).Length():integer** — Get length
@@ -394,12 +401,21 @@ const result = expression.evaluate({ a: 10n, b: 20n }); // 30n
394
401
  During parsing, any valid name that is not recognized as a keyword, constant, or built-in function is treated as an input variable.
395
402
  Use the optional constructor configuration to specify the expected result `type`, enable `strict` handling of undeclared variables,
396
403
  or declare input `variables` and their types. An instance exposes the original `script`, its inferred result `type`,
397
- the inferred input types through `variables()`, and the parsed tree through `toString()`. `Affinirum.format()` formats
398
- a JavaScript value using Affinirum Notation.
404
+ the inferred input types through `variables()`, and the parsed tree through `toString()`.
405
+
406
+ `Affinirum.parse()` parses a single Affinirum Notation value into a JavaScript value. Empty or `undefined` input returns
407
+ `undefined`; invalid input throws an error. `Affinirum.format()` formats a JavaScript value as an Affinirum Notation string:
408
+
409
+ ```ts
410
+ const value = Affinirum.parse('["answer":42,"enabled":true]');
411
+ const notation = Affinirum.format(value);
412
+ ```
399
413
 
400
414
  JavaScript `number` values map to **float**, while **integer** values map to `bigint`. Timestamps use `Date`, buffers use
401
415
  `ArrayBuffer`, and a **void** result is returned as `undefined`. Arrays, objects, and functions use their corresponding
402
- JavaScript values. Injected values are checked against the types inferred or declared during compilation.
416
+ JavaScript values. Injected non-function values are checked against the types inferred or declared during compilation.
417
+ Injected functions are checked to be callable; their JavaScript parameter behavior and return values are trusted according
418
+ to their declared Affinirum types.
403
419
 
404
420
  Use **val** for a local value that cannot be reassigned and **var** for a reassignable local variable. Statements are
405
421
  separated with semicolons.
@@ -7,17 +7,18 @@ import { LoopNode } from "./node/LoopNode.js";
7
7
  import { SwitchNode } from "./node/SwitchNode.js";
8
8
  import { ParserFrame } from "./ParserFrame.js";
9
9
  import { ParserState } from "./ParserState.js";
10
- import { StaticScope } from "./StaticScope.js";
10
+ import { Scope } from "./Scope.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 _vartypes: Map<string, Type>;
16
17
  protected readonly _varframes: Map<string, ParserFrame>;
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: Scope;
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
+ /** 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.
59
66
  @param value Value to format.
60
- @param whitespace Optional white space characters for readability.
61
- @returns String formatted in Affinirum Notation.
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: Scope): Node;
72
+ protected _unit(state: ParserState, scope: Scope): Node;
73
+ protected _coalescence(state: ParserState, scope: Scope): Node;
74
+ protected _disjunction(state: ParserState, scope: Scope): Node;
75
+ protected _conjunction(state: ParserState, scope: Scope): Node;
76
+ protected _negation(state: ParserState, scope: Scope): Node;
77
+ protected _comparison(state: ParserState, scope: Scope): Node;
78
+ protected _aggregate(state: ParserState, scope: Scope): Node;
79
+ protected _product(state: ParserState, scope: Scope): Node;
80
+ protected _signum(state: ParserState, scope: Scope): Node;
81
+ protected _factor(state: ParserState, scope: Scope): Node;
82
+ protected _accessor(state: ParserState, scope: Scope): Node;
83
+ protected _term(state: ParserState, scope: Scope): Node;
84
+ protected _function(state: ParserState, scope: Scope): Node;
85
+ protected _loop(state: ParserState, scope: Scope): LoopNode;
86
+ protected _switch(state: ParserState, scope: Scope): SwitchNode;
87
+ protected _type(state: ParserState, scope: Scope): 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,19 @@ 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 { Scope } from "./Scope.js";
26
26
  import { JumpException } from "./JumpException.js";
27
27
  export class Affinirum {
28
28
  static keywords = [...Keywords, ...Constants.map((c) => c[0])];
29
29
  _script;
30
30
  _strict;
31
31
  _root;
32
+ _vartypes = new Map();
32
33
  _varframes = new Map();
33
34
  _variables = new Map();
34
35
  _constants = new Map(Constants);
35
36
  _functions = new Map(Functions);
36
- _scope = new StaticScope();
37
+ _scope = new Scope();
37
38
  /**
38
39
  Creates compiled expression. Any parsed token not recognized as a constant or a function will be compiled as a variable.
39
40
  @param script Math expression to compile.
@@ -46,7 +47,7 @@ export class Affinirum {
46
47
  this._strict = config?.strict ?? false;
47
48
  if (config?.variables) {
48
49
  for (const [vname, vtype] of Object.entries(config.variables)) {
49
- this._variables.set(vname, new Variable(vtype));
50
+ this._vartypes.set(vname, vtype);
50
51
  }
51
52
  }
52
53
  const state = new ParserState(this._script);
@@ -81,31 +82,29 @@ export class Affinirum {
81
82
  */
82
83
  variables() {
83
84
  const types = Object.create(null);
84
- const variables = this._scope.variables();
85
- for (const name in variables) {
86
- types[name] = variables[name].type;
85
+ for (const [name, variable] of this._variables) {
86
+ types[name] = variable.type;
87
87
  }
88
88
  return types;
89
89
  }
90
90
  /**
91
- Evaluates compiled expression using provided variable values.
92
- @param values Record with variable names and values.
93
- @returns Calculated value.
91
+ Evaluates the compiled expression using the provided input values.
92
+ @param values Values for the expression's input variables. Omitted when there are no input variables.
93
+ @returns The evaluated result.
94
+ @throws If an input value is missing or evaluation fails.
94
95
  */
95
96
  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
- }
108
97
  try {
98
+ for (const [name, variable] of this._variables) {
99
+ if (!values || !Object.hasOwn(values, name)) {
100
+ this._varframes.get(name)?.throwError(`undefined variable ${name}:\n`);
101
+ }
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
+ }
109
108
  return normalize(this._root.evaluate() ?? undefined);
110
109
  }
111
110
  catch (e) {
@@ -119,12 +118,25 @@ export class Affinirum {
119
118
  }
120
119
  throw e;
121
120
  }
121
+ finally {
122
+ for (const variable of this._variables.values()) {
123
+ variable.value = undefined;
124
+ }
125
+ this._scope.clear();
126
+ }
122
127
  }
123
- /**
124
- Produces string in Affinirum Notation.
128
+ /** Parses an Affinirum Notation string into a JavaScript value.
129
+ @param value Affinirum Notation string to parse.
130
+ @returns The parsed value.
131
+ @throws If string is not a valid Affinirum Notation string.
132
+ */
133
+ static parse(value) {
134
+ return parseAN(value);
135
+ }
136
+ /** Formats a JavaScript value as an Affinirum Notation string.
125
137
  @param value Value to format.
126
- @param whitespace Optional white space characters for readability.
127
- @returns String formatted in Affinirum Notation.
138
+ @param whitespace Optional whitespace used for each indentation level.
139
+ @returns Affinirum Notation formatted string.
128
140
  */
129
141
  static format(value, whitespace) {
130
142
  return formatAN(value, whitespace);
@@ -327,20 +339,14 @@ export class Affinirum {
327
339
  state.next();
328
340
  return new ConstantNode(frame, constant);
329
341
  }
330
- let variable = scope.get(state.token);
342
+ let variable = scope.get(state.token) ?? this._variables.get(state.token);
331
343
  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
- }
344
+ const type = this._vartypes.get(state.token);
345
+ if (type == null && this._strict) {
346
+ state.throwError(`undefined variable ${state.token} in strict mode`);
340
347
  }
341
- scope.global(state.token, variable);
342
- }
343
- if (!this._varframes.has(state.token)) {
348
+ variable = new Variable(type);
349
+ this._variables.set(state.token, variable);
344
350
  this._varframes.set(state.token, state.starts());
345
351
  }
346
352
  if (state.next().isAssignment) {
@@ -362,9 +368,10 @@ export class Affinirum {
362
368
  }
363
369
  else if (state.isBracesOpen) { // code block
364
370
  const frame = state.starts();
371
+ const subscope = scope.subscope();
365
372
  const subnodes = [];
366
373
  while (!state.next().isBracesClose) {
367
- subnodes.push(this._unit(state, scope));
374
+ subnodes.push(this._unit(state, subscope));
368
375
  if (!state.isSemicolon) {
369
376
  break;
370
377
  }
@@ -431,7 +438,7 @@ export class Affinirum {
431
438
  type = this._type(state.next(), scope);
432
439
  }
433
440
  const variable = new Variable(type, assignable);
434
- scope.local(token, variable);
441
+ scope.set(token, variable);
435
442
  if (state.isAssignment) {
436
443
  if (state.assignment.operator) {
437
444
  state.throwError(`illegal assignment operator with variable ${token}`);
@@ -480,7 +487,7 @@ export class Affinirum {
480
487
  state.throwError("missing function argument name");
481
488
  }
482
489
  const token = state.token;
483
- if (scope.get(token)) {
490
+ if (scope.has(token)) {
484
491
  state.throwError("variable redefinition");
485
492
  }
486
493
  let argType = Type.Unknown;
@@ -508,10 +515,17 @@ export class Affinirum {
508
515
  const retType = state.isColon ? this._type(state.next(), scope) : Type.Unknown;
509
516
  frame.ends(state);
510
517
  const args = Array.from(variables.values());
511
- const subnode = this._unit(state, scope.subscope(variables));
518
+ const subscope = scope.subscope(variables);
519
+ const subnode = this._unit(state, subscope);
512
520
  const func = (...values) => {
513
- args.forEach((arg, ix) => arg.value = normalize(values[ix]));
514
- return normalize(subnode.evaluate());
521
+ const previous = subscope.enter();
522
+ try {
523
+ args.forEach((arg, ix) => arg.value = normalize(values[ix]));
524
+ return normalize(subnode.evaluate());
525
+ }
526
+ finally {
527
+ subscope.leave(previous);
528
+ }
515
529
  };
516
530
  const constant = new Constant(func, Type.functionType(retType, args.map((v) => v.type), variadic));
517
531
  return new ConstantNode(frame, constant, subnode);
@@ -1,11 +1,11 @@
1
1
  import { funcOr, funcAnd, funcNot } from "./native/Boolean.js";
2
- import { parseBuffer } from "./native/Buffer.js";
2
+ import { parseLiteralBuffer } from "./native/Buffer.js";
3
3
  import { funcAdd } from "./native/Aggregable.js";
4
- import { isSignSymbol, isTokenStartSymbol, isNumericSymbol, isTokenSymbol, isDateSymbol, isTimeSymbol, isDateTimeSeparatorSymbol, replaceWith } from "./native/String.js";
5
- import { Constant } from "./Constant.js";
6
- import { funcGreaterThan, funcLessThan, funcGreaterOrEqual, funcLessOrEqual, funcSubtract, funcMultiply, funcDivide, funcRemainder, funcPower } from "./native/Number.js";
4
+ import { funcGreaterThan, funcLessThan, funcGreaterOrEqual, funcLessOrEqual, funcSubtract, funcMultiply, funcDivide, funcRemainder, funcPower, isNumericSymbol, parseLiteralNumber } from "./native/Number.js";
7
5
  import { funcCoalesce, funcEqual, funcNotEqual } from "./native/Unknown.js";
8
- import { boundInteger } from "./native/Integer.js";
6
+ import { isTokenStartSymbol, isTokenSymbol, parseLiteralString } from "./native/String.js";
7
+ import { parseLiteralTimestamp } from "./native/Timestamp.js";
8
+ import { Constant } from "./Constant.js";
9
9
  import { Type } from "./Type.js";
10
10
  import { ParserFrame } from "./ParserFrame.js";
11
11
  class Literal {
@@ -450,53 +450,25 @@ export class ParserState extends ParserFrame {
450
450
  break;
451
451
  }
452
452
  break;
453
- case "@":
454
- while (isDateSymbol(this._expr.charAt(this._end))) {
455
- ++this._end;
456
- }
457
- if (isDateTimeSeparatorSymbol(this._expr.charAt(this._end))) {
458
- ++this._end;
459
- while (isTimeSymbol(this._expr.charAt(this._end))) {
460
- ++this._end;
461
- }
462
- if (this._expr.charAt(this._end) === "."
463
- && isNumericSymbol(this._expr.charAt(this._end + 1))) {
464
- ++this._end;
465
- while (isNumericSymbol(this._expr.charAt(this._end))) {
466
- ++this._end;
467
- }
468
- if (this._expr.charAt(this._end) === "Z") {
469
- ++this._end;
470
- }
471
- }
472
- }
473
- this._fragment = new Literal(new Date(this._expr.substring(this._start + 1, this._end)));
453
+ case "@": {
454
+ const [ts, tsEnd] = parseLiteralTimestamp(this._expr, this._start);
455
+ this._fragment = new Literal(ts);
456
+ this._end = tsEnd;
474
457
  break;
475
- case "`":
476
- while (this._expr.charAt(this._end) !== ""
477
- && this._expr.charAt(this._end) !== c) {
478
- ++this._end;
479
- }
480
- if (this._end >= this._expr.length) {
481
- this._start = this._expr.length;
482
- throw new Error(`missing closing buffer quotation mark ${c}`);
483
- }
484
- this._fragment = new Literal(parseBuffer(replaceWith(this._expr.substring(this._start + 1, this._end), "", " ", "\t", "\n")));
485
- ++this._end;
458
+ }
459
+ case "`": {
460
+ const [buf, bufEnd] = parseLiteralBuffer(this._expr, this._start);
461
+ this._fragment = new Literal(buf);
462
+ this._end = bufEnd;
486
463
  break;
464
+ }
487
465
  case "\"":
488
- case "'":
489
- while (this._expr.charAt(this._end) !== ""
490
- && this._expr.charAt(this._end) !== c) {
491
- ++this._end;
492
- }
493
- if (this._end >= this._expr.length) {
494
- this._start = this._expr.length;
495
- throw new Error(`missing closing string quotation mark ${c}`);
496
- }
497
- this._fragment = new Literal(replaceWith(this._expr.substring(this._start + 1, this._end), "", "\\\n"));
498
- ++this._end;
466
+ case "'": {
467
+ const [str, strEnd] = parseLiteralString(this._expr, this._start);
468
+ this._fragment = new Literal(str);
469
+ this._end = strEnd;
499
470
  break;
471
+ }
500
472
  default:
501
473
  if (isTokenStartSymbol(c)) {
502
474
  while (isTokenSymbol(this._expr.charAt(this._end))) {
@@ -574,37 +546,9 @@ export class ParserState extends ParserFrame {
574
546
  }
575
547
  }
576
548
  else if (isNumericSymbol(c)) {
577
- let integer = true;
578
- while (isNumericSymbol(this._expr.charAt(this._end))) {
579
- ++this._end;
580
- }
581
- if (this._expr.charAt(this._end) === ".") {
582
- ++this._end;
583
- if (isNumericSymbol(this._expr.charAt(this._end))) {
584
- ++this._end;
585
- while (isNumericSymbol(this._expr.charAt(this._end))) {
586
- ++this._end;
587
- }
588
- integer = false;
589
- }
590
- else {
591
- --this._end;
592
- }
593
- }
594
- if (this._expr.charAt(this._end) === "e") {
595
- ++this._end;
596
- if (isNumericSymbol(this._expr.charAt(this._end))
597
- || isSignSymbol(this._expr.charAt(this._end))) {
598
- ++this._end;
599
- while (isNumericSymbol(this._expr.charAt(this._end))) {
600
- ++this._end;
601
- }
602
- }
603
- integer = false;
604
- }
605
- this._fragment = integer
606
- ? new Literal(boundInteger(BigInt(this._expr.substring(this._start, this._end))))
607
- : new Literal(parseFloat(this._expr.substring(this._start, this._end)));
549
+ const [num, numEnd] = parseLiteralNumber(this._expr, this._start);
550
+ this._fragment = new Literal(num);
551
+ this._end = numEnd;
608
552
  }
609
553
  else {
610
554
  throw new Error(`unknown symbol ${c}`);
package/dst/Scope.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { Value } from "./Value.js";
2
+ import { Variable } from "./Variable.js";
3
+ export declare class Scope {
4
+ protected readonly _subscopes: Scope[];
5
+ protected readonly _superscope?: Scope;
6
+ protected readonly _variables: Map<string, Variable>;
7
+ protected readonly _boundary: boolean;
8
+ constructor(superscope?: Scope, variables?: Map<string, Variable>);
9
+ has(name: string): boolean;
10
+ get(name: string): Variable | undefined;
11
+ set(name: string, variable: Variable): void;
12
+ subscope(variables?: Map<string, Variable>): Scope;
13
+ enter(values?: Map<Variable, Value>): Map<Variable, Value>;
14
+ leave(values: Map<Variable, Value>): void;
15
+ clear(): void;
16
+ }
package/dst/Scope.js ADDED
@@ -0,0 +1,49 @@
1
+ export class Scope {
2
+ _subscopes = [];
3
+ _superscope;
4
+ _variables;
5
+ _boundary;
6
+ constructor(superscope, variables) {
7
+ superscope?._subscopes.push(this);
8
+ this._superscope = superscope;
9
+ this._variables = variables ?? new Map();
10
+ this._boundary = Boolean(variables);
11
+ }
12
+ has(name) {
13
+ return this._variables.has(name) || Boolean(this._superscope?.has(name));
14
+ }
15
+ get(name) {
16
+ return this._variables.get(name) ?? this._superscope?.get(name);
17
+ }
18
+ set(name, variable) {
19
+ this._variables.set(name, variable);
20
+ }
21
+ subscope(variables) {
22
+ return new Scope(this, variables);
23
+ }
24
+ enter(values = new Map()) {
25
+ for (const variable of this._variables.values()) {
26
+ values.set(variable, variable.value);
27
+ variable.value = undefined;
28
+ }
29
+ for (const subscope of this._subscopes) {
30
+ if (!subscope._boundary) {
31
+ subscope.enter(values);
32
+ }
33
+ }
34
+ return values;
35
+ }
36
+ leave(values) {
37
+ for (const [variable, value] of values) {
38
+ variable.value = value;
39
+ }
40
+ }
41
+ clear() {
42
+ for (const variable of this._variables.values()) {
43
+ variable.value = undefined;
44
+ }
45
+ for (const subscope of this._subscopes) {
46
+ subscope.clear();
47
+ }
48
+ }
49
+ }
@@ -1,3 +1,4 @@
1
+ import { Type } from "../Type.js";
1
2
  export class ArrayAtom {
2
3
  _valTypes;
3
4
  constructor(_valTypes = []) {
@@ -30,7 +31,9 @@ export class ArrayAtom {
30
31
  }
31
32
  if (this.isTuple) {
32
33
  for (let i = 0; i < this._valTypes.length; ++i) {
33
- const vtype = atom.isTuple ? atom.valType(i) : atom.valType(0);
34
+ const vtype = atom.isTuple
35
+ ? atom.valType(i) ?? Type.Void
36
+ : atom.valType(0);
34
37
  if (!vtype || !this._valTypes[i].accept(vtype)) {
35
38
  return false;
36
39
  }