affinirum 1.4.2 → 1.5.0

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 (75) hide show
  1. package/README.md +214 -151
  2. package/dst/Affinirum.js +24 -15
  3. package/dst/Atom.d.ts +3 -1
  4. package/dst/Constant.js +1 -1
  5. package/dst/Functions.js +7 -4
  6. package/dst/Keywords.js +4 -4
  7. package/dst/ParserState.d.ts +2 -1
  8. package/dst/ParserState.js +22 -5
  9. package/dst/Type.d.ts +11 -7
  10. package/dst/Type.js +113 -38
  11. package/dst/Value.d.ts +1 -0
  12. package/dst/Value.js +19 -1
  13. package/dst/atom/ArrayAtom.d.ts +7 -3
  14. package/dst/atom/ArrayAtom.js +50 -8
  15. package/dst/atom/FunctionAtom.d.ts +4 -1
  16. package/dst/atom/FunctionAtom.js +65 -15
  17. package/dst/atom/ObjectAtom.d.ts +7 -5
  18. package/dst/atom/ObjectAtom.js +35 -13
  19. package/dst/atom/PrimitiveAtom.d.ts +3 -1
  20. package/dst/atom/PrimitiveAtom.js +10 -1
  21. package/dst/cjs/Affinirum.js +24 -15
  22. package/dst/cjs/Constant.js +1 -1
  23. package/dst/cjs/Functions.js +6 -3
  24. package/dst/cjs/Keywords.js +4 -4
  25. package/dst/cjs/ParserState.js +22 -5
  26. package/dst/cjs/Type.js +113 -38
  27. package/dst/cjs/Value.js +21 -0
  28. package/dst/cjs/atom/ArrayAtom.js +50 -8
  29. package/dst/cjs/atom/FunctionAtom.js +65 -15
  30. package/dst/cjs/atom/ObjectAtom.js +35 -13
  31. package/dst/cjs/atom/PrimitiveAtom.js +10 -1
  32. package/dst/cjs/native/Aggregable.js +2 -1
  33. package/dst/cjs/native/Array.js +10 -8
  34. package/dst/cjs/native/Boolean.js +5 -4
  35. package/dst/cjs/native/Enumerable.js +5 -4
  36. package/dst/cjs/native/Float.js +9 -8
  37. package/dst/cjs/native/Integer.js +23 -15
  38. package/dst/cjs/native/Iterable.js +2 -1
  39. package/dst/cjs/native/Number.js +18 -33
  40. package/dst/cjs/native/Object.js +2 -1
  41. package/dst/cjs/native/String.js +3 -2
  42. package/dst/cjs/native/Timestamp.js +2 -1
  43. package/dst/cjs/native/notation/IP.js +3 -2
  44. package/dst/cjs/node/ArrayNode.js +6 -6
  45. package/dst/cjs/node/CallNode.js +27 -23
  46. package/dst/cjs/node/CastNode.js +42 -0
  47. package/dst/cjs/node/ObjectNode.js +2 -4
  48. package/dst/cjs/node/SwitchNode.js +3 -1
  49. package/dst/cjs/node/VariableNode.js +3 -1
  50. package/dst/native/Aggregable.js +2 -1
  51. package/dst/native/Array.js +10 -8
  52. package/dst/native/Boolean.d.ts +1 -0
  53. package/dst/native/Boolean.js +4 -3
  54. package/dst/native/Enumerable.js +5 -4
  55. package/dst/native/Float.d.ts +2 -0
  56. package/dst/native/Float.js +8 -7
  57. package/dst/native/Integer.d.ts +5 -1
  58. package/dst/native/Integer.js +20 -14
  59. package/dst/native/Iterable.js +2 -1
  60. package/dst/native/Number.d.ts +0 -3
  61. package/dst/native/Number.js +17 -32
  62. package/dst/native/Object.js +2 -1
  63. package/dst/native/String.js +3 -2
  64. package/dst/native/Timestamp.js +2 -1
  65. package/dst/native/notation/IP.js +3 -2
  66. package/dst/node/ArrayNode.d.ts +1 -1
  67. package/dst/node/ArrayNode.js +6 -6
  68. package/dst/node/CallNode.js +27 -23
  69. package/dst/node/CastNode.d.ts +15 -0
  70. package/dst/node/CastNode.js +38 -0
  71. package/dst/node/ObjectNode.d.ts +1 -1
  72. package/dst/node/ObjectNode.js +2 -4
  73. package/dst/node/SwitchNode.js +3 -1
  74. package/dst/node/VariableNode.js +3 -1
  75. package/package.json +5 -4
package/README.md CHANGED
@@ -1,21 +1,21 @@
1
1
  # Affinirum
2
- A fast, embeddable scripting language powered by a lightweight recursive descent parser,
3
- designed to evaluate complex algorithmic logic with precision and flexibility.
4
- Ideal for embedding in host applications, it offers clear syntax, dynamic typing,
5
- and extensibility for custom operations—enabling rapid prototyping, advanced rule evaluation,
6
- and safe script execution in constrained environments.
2
+ A fast, embeddable scripting language powered by a lightweight recursive descent parser,
3
+ designed to evaluate complex algorithmic logic with precision and flexibility.
4
+ Ideal for embedding in host applications, it offers clear syntax, type inference, permissive type checking,
5
+ and support for host-provided values and functions—enabling rapid prototyping and advanced rule evaluation
6
+ in applications that control which capabilities are exposed to scripts.
7
7
 
8
8
  Supports algebraic and boolean expressions, variables, conditionals, loops, and a rich standard library for working with numbers, buffers, strings, arrays, and objects.
9
9
 
10
- Runs in browser and NodeJS.
10
+ Runs in browsers and Node.js.
11
11
 
12
- Target: ES2022 [browser+NodeJS][ESM+CJS].
12
+ Target: ES2022 [browser+Node.js][ESM+CJS].
13
13
 
14
14
  ## Features
15
15
 
16
16
  - Efficient execution: Parse once, execute many times with different variable values.
17
17
  - Variable support: Input and statement-scoped variables.
18
- - Function support: Variadic and first-order function support for expressive scripting.
18
+ - Function support: Variadic and first-class functions for expressive scripting.
19
19
  - Optimized evaluation: Constant expression folding with type checks.
20
20
  - Comprehensive set of operators: Boolean, arithmetic, buffer, string, comparison, and indexing support.
21
21
  - Built-in functions: Rich set of mathematical and composition utilities.
@@ -39,24 +39,24 @@ It is defined by comma-separated values enclosed in brackets (**[]**),
39
39
  Array elements can be accessed using the access operator (**.**),
40
40
  or using brackets with a zero-based numeric index, like *theArray.23*, *theArray[0]*, *theArray[10]*, *theArray[indexVar]*.
41
41
 
42
- Easy way to check if array contains an index is to use presence operator (**?**), like *theArray?50*.
42
+ An easy way to check whether an array contains an index is to use the presence operator (**?**), like *theArray?50*.
43
43
 
44
44
  ### Objects
45
- Object is a container of named values of any type.
46
- It is defined by comma-separated key-value pair enclosed in brackets (**[]**) where key is separated from value by colon (**:**),
47
- like *["key1":100, "key2":"abc"]*, *["a":0,"b":"str":"c":valueVar]*.
45
+ Object is a container of named values of any type.
46
+ It is defined by comma-separated key-value pairs enclosed in brackets (**[]**), where each key is separated from its value by a colon (**:**),
47
+ like *["key1":100, "key2":"abc"]*, *["a":0, "b":"str", "c":valueVar]*.
48
48
  <br>An empty object is represented as **[\:]**.
49
49
 
50
50
  Object properties can be accessed using the access operator (**.**) with a string literal, token,
51
51
  or with brackets containing a string key,
52
52
  like *theObject."key"*, *theObject.key*, or *theObject["key"]*.
53
53
 
54
- Easy way to check if object contains a key is to use presence operator (**?**), like *theObject?myKey*.
54
+ An easy way to check whether an object contains a key is to use the presence operator (**?**), like *theObject?myKey*.
55
55
 
56
- ### Functions
57
- A function is a callable code unit that produces a value.
58
- The set of built-in functions can be extended through configuration entries.
59
- Additionally, subroutines (functions defined in code) can be created.
56
+ ### Functions
57
+ A function is a callable code unit that produces a value.
58
+ The standard library provides built-in functions. Host functions can be supplied as typed input variables,
59
+ and subroutines can be defined in Affinirum code.
60
60
 
61
61
  ### Variables
62
62
  Valid variable and function names must start with a letter, number sign (**\#**), dollar sign (**\$**), or underscore (**\_**)
@@ -65,22 +65,57 @@ Valid variable and function names must start with a letter, number sign (**\#**)
65
65
 
66
66
  Whitespace characters are ignored.
67
67
 
68
- ### Types
69
- - **void** for value **null**
70
- - **boolean** for values **true** and **false**
71
- - **timestamp** for date-time values, millisecons since Unix epoch
72
- - **float** for 64-bit floating point values in binary64, IEEE 754 binary floating-point format
73
- - **integer** for 64-bit integer values
68
+ ### Types
69
+ - **void** for the absence of a value; the **null** literal and injected JavaScript `null` or `undefined` values have this type, and a **void** result is returned as JavaScript `undefined`
70
+ - **boolean** (alias **bool**) for values **true** and **false**
71
+ - **timestamp** (alias **time**) for date-time values backed by JavaScript `Date` objects
72
+ - **float** (alias **f64**) for 64-bit floating point values in binary64, IEEE 754 binary floating-point format
73
+ - **integer** (alias **i64**) for signed 64-bit integer values; arithmetic overflow wraps to the signed 64-bit range
74
74
  - **buffer** for ordered sequences of bytes
75
75
  - **string** for ordered sequences of characters, text strings
76
- - **array** for ordered sequences of values
77
- - **object** for collections of named values
78
- - **function** for built-in, injected or script-defined subroutines
79
- - **??** for unknown or variant type
76
+ - **array** for ordered sequences of values
77
+ - **object** for collections of named values
78
+ - **function** for built-in, injected or script-defined subroutines
79
+ - **[type]** for a homogeneous array whose items have the specified type, such as **[string]**
80
+ - **[type1, type2, ...]** for a tuple whose items have the corresponding types
81
+ - **??** for unknown or variant type
80
82
  - Type grouping: **(...)**
81
83
  - Type union: **|**
82
84
  - Type optionality modifier: **?**
83
85
 
86
+ Canonical type names and their aliases are reserved and cannot be used as variable or function names.
87
+
88
+ ### Type-checking policy
89
+ Affinirum uses intentionally permissive type checking. Type information helps reject clearly incompatible expressions,
90
+ select function overloads, and report useful compilation errors; it is not intended to enforce strict static
91
+ substitutability or prove that every accepted expression is safe for every possible runtime value.
92
+
93
+ - **??** is the unknown or variant type and is compatible with every type. It includes **void**, so a **??**
94
+ function parameter may receive **null**, `undefined`, or be omitted.
95
+ - An optional type such as **integer?** is the union **void | integer**. Optional parameters may receive **null**, `undefined`,
96
+ or be omitted.
97
+ - Function compatibility is deliberately flexible. The accepted argument-count ranges only need to overlap;
98
+ one function's complete arity range does not need to contain the other's.
99
+ - A callback may declare fewer parameters than the caller provides. Additional arguments are ignored at runtime,
100
+ following JavaScript function-call behavior.
101
+ - Function parameter types are checked contravariantly where both signatures declare a parameter, while **??**
102
+ remains compatible with any parameter type. Return types are checked covariantly.
103
+ - Fixed and variadic signatures are not interchangeable. Variadic arguments use a distinct packed-array calling
104
+ convention and are only compatible with corresponding variadic signatures.
105
+
106
+ For example, a callback declared as `~(value: float):boolean` is compatible with an expected callback type such as
107
+ `~(value: ??, index: integer?, values: array?):boolean`: the arities overlap, **??** accepts the concrete value type,
108
+ and the callback may ignore the additional arguments. This behavior is intentional. Affinirum does not enforce strict
109
+ function subtyping.
110
+
111
+ ### Type casting
112
+ A postfix type cast declares the expected type of an expression using **::type**,
113
+ like `value::object` or `JSON.Parse(json)::object.property`.
114
+
115
+ A cast does not convert the value. The source and target types must be compatible at compile time,
116
+ and the evaluated value must satisfy the target type at runtime. An incompatible cast raises an error.
117
+ Casts can be followed by property access, index access, function calls, or another cast.
118
+
84
119
  ### Definitions
85
120
  - Unit grouping: **{...}**
86
121
  - Unit separator: **;**
@@ -88,11 +123,11 @@ Whitespace characters are ignored.
88
123
  - Value separator: **,**
89
124
  - Array element at numeric index, or object property by string key: **[]**
90
125
  - Object property by string key or method function call: **.**
91
- - Array definiton: **[item1, ...]**
92
- - Object definition: **[propery1-key: property1-value, ...]**
126
+ - Array definition: **[item1, ...]**
127
+ - Object definition: **[property1-key: property1-value, ...]**
93
128
  - Subroutine definition: **~(argument1-name: argument1-type, ...):return-type {...}**
94
- - Conditional switch definition, returns first or second value if prefix is true or false: **if condition {value1} else {value2}**,
95
- and if **else** clause is ommited second value deemed *null*
129
+ - Conditional switch definition, returns first or second value if prefix is true or false: **if condition {value1} else {value2}**,
130
+ and if the **else** clause is omitted, the second value is **void**
96
131
  - Loop definition, iteratively evaluates suffix while prefix is true, returns last evaluated value: **while condition {...}**
97
132
  - Stop iteration: **stop**
98
133
  - Proceed to next iteration: **next**
@@ -109,15 +144,16 @@ Whitespace characters are ignored.
109
144
  - Less than or equals to: **<=**
110
145
  - Equals to: **==**
111
146
  - Not equals to: **!=**
112
- - Null coalescence: **?:**
113
- - Arithmetic addition, or buffer, string, and array concatination: **+**
147
+ - Arithmetic addition, or buffer, string, and array concatenation: **+**
114
148
  - Arithmetic subtraction or negation: **-**
115
149
  - Arithmetic multiplication: **\***
116
150
  - Arithmetic division: **/**
117
151
  - Arithmetic remainder: **%**
118
152
  - Exponentiation operator: **^**
119
153
  - Property access operator: **.**
120
- - Property existance operator: **?**
154
+ - Property existence operator: **?**
155
+ - Null coalescence operator: **?:**
156
+ - Type cast operator: **::**
121
157
  - Assignment: **=**
122
158
  - Boolean disjunction (Logical OR) assignment: **|=**
123
159
  - Boolean conjunction (Logical AND) assignment: **&=**
@@ -129,18 +165,18 @@ Whitespace characters are ignored.
129
165
 
130
166
  ### Native Global Functions
131
167
 
132
- Native conversions use the following null handling:
133
-
134
- - `Format` returns an empty string for a **null**.
135
- - `Encode` returns a zero-length buffer for a **null**.
136
- - `Decode` and `Parse` return **null** when their input value is **null**.
137
-
138
- Empty strings and zero-length buffers remain ordinary values; they are not serialized null markers.
139
- Invalid non-null inputs are function-specific and may raise an evaluation error.
140
-
141
- #### Boolean
142
- - **Boolean.Or(values: ...(boolean | array)):boolean** — Boolean disjunction of booleans and arrays of booleans
143
- - **Boolean.And(values: ...(boolean | array)):boolean** — Boolean conjunction of booleans and arrays of booleans
168
+ Native conversions use the following **void** handling:
169
+
170
+ - `Format` returns an empty string for **void**.
171
+ - `Encode` returns a zero-length buffer for **void**.
172
+ - `Decode` and `Parse` return **void** when their input value is **void**.
173
+
174
+ Empty strings and zero-length buffers remain ordinary values; they are not serialized void markers.
175
+ Invalid non-void inputs are function-specific and may raise an evaluation error.
176
+
177
+ #### Boolean
178
+ - **Boolean.Or(values: ...(boolean | [boolean])):boolean** — Boolean disjunction of booleans and arrays of booleans
179
+ - **Boolean.And(values: ...(boolean | [boolean])):boolean** — Boolean conjunction of booleans and arrays of booleans
144
180
  - **Boolean.Not(value: boolean):boolean** — Boolean negation
145
181
  - **Boolean.Decode(value: buffer?, offset: integer?):boolean?** — Decode a byte at the optional offset; missing or out-of-range input returns **void**
146
182
  - **Boolean.Parse(value: string?):boolean?** — Parse case-insensitive `true` or `false`; other values return **void**
@@ -156,26 +192,26 @@ Invalid non-null inputs are function-specific and may raise an evaluation error.
156
192
  - **Float.PositiveInfinity** — Positive infinity
157
193
  - **Float.NegativeInfinity** — Negative infinity
158
194
  - **Float.Epsilon** — Smallest positive float
159
- - **Float.Sum(values: ...(float | array)):float** — Numeric sum
160
- - **Float.Min(values: ...(float | array)):float** — Numeric minimum
161
- - **Float.Max(values: ...(float | array)):float** — Numeric maximum
162
- - **Float.Exponent(value: float):float** — Natural exponential
163
- - **Float.Logarithm(value: float):float** — Natural logarithm
164
- - **Float.Abs(value: float):float** — Absolute value
165
- - **Float.Ceil(value: float):float** — Smallest integer greater than or equal to the value
166
- - **Float.Floor(value: float):float** — Largest integer less than or equal to the value
167
- - **Float.Round(value: float):float** — Rounded value
168
- - **Float.Truncate(value: float):float** — Integer portion of the value
169
- - **Float.Random(exclusiveTo: float):float** — Random float up to value
195
+ - **Float.Sum(values: ...(float | integer | [float | integer])):float** — Numeric sum
196
+ - **Float.Min(values: ...(float | integer | [float | integer])):float** — Numeric minimum
197
+ - **Float.Max(values: ...(float | integer | [float | integer])):float** — Numeric maximum
198
+ - **Float.Exponent(value: float | integer):float** — Natural exponential
199
+ - **Float.Logarithm(value: float | integer):float** — Natural logarithm
200
+ - **Float.Abs(value: float | integer):float** — Absolute value
201
+ - **Float.Ceil(value: float | integer):float** — Smallest integer greater than or equal to the value
202
+ - **Float.Floor(value: float | integer):float** — Largest integer less than or equal to the value
203
+ - **Float.Round(value: float | integer):float** — Rounded value
204
+ - **Float.Truncate(value: float | integer):float** — Integer portion of the value
205
+ - **Float.Random(exclusiveTo: float | integer):float** — Random float up to value
170
206
  - **Float.Decode(value: buffer?, encoding: string?, offset: integer?):float?** — Decode using `f64` (default), `f64le`, `f32`, or `f32le`
171
207
  - **Float.Parse(value: string?):float?** — Parse a string as a float
172
208
 
173
209
  #### Integer
174
- - **Integer.Sum(values: ...(integer | array)):integer** — Numeric sum
175
- - **Integer.Min(values: ...(integer | array)):integer** — Numeric minimum
176
- - **Integer.Max(values: ...(integer | array)):integer** — Numeric maximum
210
+ - **Integer.Sum(values: ...(integer | [integer])):integer** — Numeric sum
211
+ - **Integer.Min(values: ...(integer | [integer])):integer** — Numeric minimum
212
+ - **Integer.Max(values: ...(integer | [integer])):integer** — Numeric maximum
177
213
  - **Integer.Random(exclusiveTo: integer):integer** — Random integer up to value
178
- - **Integer.Decode(value: buffer?, encoding: string?, offset: integer?):integer?** — Decode using signed `i8`, `i16`, `i16le`, `i32`, `i32le`, `i64` (default), or `i64le`, or unsigned `n8`, `n16`, `n16le`, `n32`, `n32le`, `n64`, or `n64le`
214
+ - **Integer.Decode(value: buffer?, encoding: string?, offset: integer?):integer?** — Decode using signed `i8`, `i16`, `i16le`, `i32`, `i32le`, `i64` (default), or `i64le`, or unsigned `n8`, `n16`, `n16le`, `n32`, `n32le`
179
215
  - **Integer.Parse(value: string?):integer?** — Parse a string as an integer
180
216
 
181
217
  #### String
@@ -194,8 +230,8 @@ Invalid non-null inputs are function-specific and may raise an evaluation error.
194
230
  - **Array.Intersection(a1: array, a2: array):array** — Common values from two arrays
195
231
  - **Array.Difference(a1: array, a2: array):array** — Symmetrical difference between arrays
196
232
 
197
- #### Object
198
- - **Object.Merge(values: ...(object | array)):object** — Merge objects and arrays of objects
233
+ #### Object
234
+ - **Object.Merge(values: ...(object | [object])):object** — Merge objects and arrays of objects
199
235
 
200
236
  #### AN
201
237
  - **AN.Format(value: ??, whitespace: string?):string** — Format a value as AN notation
@@ -204,8 +240,8 @@ Invalid non-null inputs are function-specific and may raise an evaluation error.
204
240
  - **JSON.Format(value: (void | boolean | timestamp | float | integer | string | array | object), whitespace: string?):string** — Format a value as JSON
205
241
  - **JSON.Parse(value: string?):(void | boolean | timestamp | float | integer | string | array | object)** — Parse a JSON-formatted string; standard JSON values are not revived as timestamps or integers
206
242
 
207
- #### IP
208
- - **IP.Match(values: array, search: ...(string | array)):boolean** — Check whether any searched IPv4 or IPv6 address belongs to the supplied addresses or CIDR ranges
243
+ #### IP
244
+ - **IP.Match(values: [string], search: ...(string | [string])):boolean** — Check whether any searched IPv4 or IPv6 address belongs to the supplied addresses or CIDR ranges
209
245
  - **IP.Encode(value: string?):buffer** — Encode an IPv4, IPv6, or CIDR string as a network-byte-order buffer; malformed or **void** input returns a zero-length buffer
210
246
  - **IP.Decode(value: buffer?):string?** — Decode a 4-, 5-, 16-, or 17-byte buffer as canonical IPv4, IPv6, or CIDR notation; malformed or **void** input returns **void**
211
247
 
@@ -228,19 +264,19 @@ Invalid non-null inputs are function-specific and may raise an evaluation error.
228
264
  - **string.Add(value: string):string** — Concatenate strings
229
265
  - **array.Add(value: array):array** — Concatenate arrays
230
266
 
231
- #### Array Functions
232
- - **array.First(condition: function):??** — First item satisfying condition
233
- - **array.Last(condition: function):??** — Last item satisfying condition
234
- - **array.FirstIndex(condition: function):integer?** — First index satisfying condition, or **void** if none does
235
- - **array.LastIndex(condition: function):integer?** — Last index satisfying condition, or **void** if none does
236
- - **array.Every(condition: function):boolean** — All items satisfy condition
237
- - **array.Any(condition: function):boolean** — Any item satisfies condition
238
- - **array.Reverse():array** — Reversed array
239
- - **array.Flatten(depth: integer = 1):array** — Flatten array
240
- - **array.Derive(transformation: function):array** — Derived array
241
- - **array.Filter(condition: function):array** — Filtered array
242
- - **array.Reduce(reducer: function, initial: ?? = void):??** — Reduced value
243
- - **array.Compose(generator: function):object** — Compose object from array
267
+ #### Array Functions
268
+ - **array.First(condition: ~(??, integer?, array?):boolean):??** — First item satisfying condition
269
+ - **array.Last(condition: ~(??, integer?, array?):boolean):??** — Last item satisfying condition
270
+ - **array.FirstIndex(condition: ~(??, integer?, array?):boolean):integer?** — First index satisfying condition, or **void** if none does
271
+ - **array.LastIndex(condition: ~(??, integer?, array?):boolean):integer?** — Last index satisfying condition, or **void** if none does
272
+ - **array.Every(condition: ~(??, integer?, array?):boolean):boolean** — All items satisfy condition
273
+ - **array.Any(condition: ~(??, integer?, array?):boolean):boolean** — Any item satisfies condition
274
+ - **array.Reverse():array** — Reversed array
275
+ - **array.Flatten(depth: integer = 1):array** — Flatten array
276
+ - **array.Derive(transformation: ~(??, integer?, array?):??):array** — Derived array
277
+ - **array.Filter(condition: ~(??, integer?, array?):boolean):array** — Filtered array
278
+ - **array.Reduce(reducer: ~(??, ??, integer?, array?):??, initial: ?? = void):??** — Reduced value
279
+ - **array.Compose(generator: ~(object, string, integer?, array?):??):object** — Compose object from array
244
280
  - **array.Prepend(items: ...??):array** — Prepend items
245
281
  - **array.Append(items: ...??):array** — Append items
246
282
 
@@ -251,12 +287,12 @@ Invalid non-null inputs are function-specific and may raise an evaluation error.
251
287
  - **buffer.Slice(start: integer?, end: integer?):buffer** — Slice section
252
288
  - **string.Slice(start: integer?, end: integer?):string** — Slice section
253
289
  - **array.Slice(start: integer?, end: integer?):array** — Slice section
254
- - **buffer.Splice(start: integer, remove: integer, inject: ...array):buffer** — Splice section
255
- - **string.Splice(start: integer, remove: integer, inject: ...array):string** — Splice section
256
- - **array.Splice(start: integer, remove: integer, inject: ...array):array** — Splice section
257
- - **buffer.Inject(start: integer, inject: ...array):buffer** — Inject section
258
- - **string.Inject(start: integer, inject: ...array):string** — Inject section
259
- - **array.Inject(start: integer, inject: ...array):array** — Inject 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
260
296
 
261
297
  #### Iterable Functions
262
298
  - **(buffer | string | array | object).Length():integer** — Get length
@@ -269,52 +305,57 @@ Invalid non-null inputs are function-specific and may raise an evaluation error.
269
305
  - **array.Has(index: integer):boolean** — Identify if array has index
270
306
  - **object.Has(index: string):boolean** — Identify if object has key
271
307
 
272
- #### Number Functions
273
- - **(float | integer).GreaterThan(value):boolean** — Greater than
274
- - **(float | integer).LessThan(value):boolean** — Less than
275
- - **(float | integer).GreaterOrEqual(value):boolean** — Greater or equal
276
- - **(float | integer).LessOrEqual(value):boolean** — Less or equal
277
- - **float.Subtract(subtrahend):float** — Subtract value
278
- - **integer.Subtract(subtrahend):integer** — Subtract value
279
- - **float.Negate():float** — Negate number
280
- - **integer.Negate():integer** — Negate number
281
- - **float.Multiply(value: integer):float** — Multiply by an integer
282
- - **integer.Multiply(value: float):float** — Multiply by a float
283
- - **integer.Multiply(value: integer):integer** — Multiply by an integer
284
- - **float.Divide(divisor):float** — Divide value
285
- - **integer.Divide(divisor):integer** — Divide value
286
- - **float.Remainder(divisor):float** — Remainder
287
- - **integer.Remainder(divisor):integer** — Remainder
288
- - **float.Modulo(divisor):float** — Modulo
289
- - **integer.Modulo(divisor):integer** — Modulo
290
- - **float.Power(exponent):float** — Power
291
- - **integer.Power(exponent):integer** — Power
292
- - **float.Root(index):float** — Root
293
- - **integer.Root(index):integer** — Root
294
- - **float.Cast():integer** — Cast to integer
295
- - **integer.Cast():float** — Cast to float
296
- - **integer.CastToFloat():float** — Cast to float
297
- - **float.CastToInteger():integer** — Cast to integer
298
-
299
- #### Object Functions
300
- - **object.Entries():array** — Key-value pairs
301
- - **object.Keys():array** — Object keys
302
- - **object.Values():array** — Object values
308
+ #### Number Functions
309
+ - **(float | integer).GreaterThan(value: float | integer):boolean** — Greater than
310
+ - **(float | integer).LessThan(value: float | integer):boolean** — Less than
311
+ - **(float | integer).GreaterOrEqual(value: float | integer):boolean** — Greater or equal
312
+ - **(float | integer).LessOrEqual(value: float | integer):boolean** — Less or equal
313
+ - **float.Subtract(subtrahend: integer):float** — Subtract an integer
314
+ - **integer.Subtract(subtrahend: float):float** — Subtract a float
315
+ - **integer.Subtract(subtrahend: integer):integer** — Subtract an integer
316
+ - **float.Negate():float** — Negate number
317
+ - **integer.Negate():integer** — Negate number
318
+ - **float.Multiply(value: integer):float** — Multiply by an integer
319
+ - **integer.Multiply(value: float):float** — Multiply by a float
320
+ - **integer.Multiply(value: integer):integer** — Multiply by an integer
321
+ - **float.Divide(divisor: integer):float** — Divide by an integer
322
+ - **integer.Divide(divisor: float):float** — Divide by a float
323
+ - **integer.Divide(divisor: integer):integer** — Divide by an integer
324
+ - **float.Remainder(divisor: integer):float** — Remainder after division by an integer
325
+ - **integer.Remainder(divisor: float):float** — Remainder after division by a float
326
+ - **integer.Remainder(divisor: integer):integer** — Remainder after division by an integer
327
+ - **float.Modulo(divisor: integer):float** — Modulo by an integer
328
+ - **integer.Modulo(divisor: float):float** — Modulo by a float
329
+ - **integer.Modulo(divisor: integer):integer** — Modulo by an integer
330
+ - **float.Power(exponent: integer):float** — Raise to an integer power
331
+ - **integer.Power(exponent: float):float** — Raise to a float power
332
+ - **integer.Power(exponent: integer):integer** — Raise to an integer power
333
+ - **float.Root(index: integer):float** — Take an integer root
334
+ - **integer.Root(index: float):float** — Take a float root
335
+ - **integer.Root(index: integer):integer** — Take an integer root
336
+ - **(boolean | timestamp | integer).Float():float** — Convert to a float; timestamps use milliseconds since the Unix epoch
337
+ - **(boolean | timestamp | float).Integer():integer** — Convert to an integer; timestamps use milliseconds since the Unix epoch
338
+ - **(timestamp | float | integer).Boolean():boolean** — Convert to a boolean by testing whether the numeric or epoch value is non-zero
339
+
340
+ #### Object Functions
341
+ - **object.Entries():array** — Key-value pairs
342
+ - **object.Keys():[string]** — Object keys
343
+ - **object.Values():array** — Object values
303
344
 
304
345
  #### String Functions
305
346
  - **string.Like(value: string):boolean** — Alphanumeric equality
306
347
  - **string.Unlike(value: string):boolean** — Alphanumeric inequality
307
348
  - **string.StartsWith(search: string, startPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Prefix check
308
349
  - **string.EndsWith(search: string, endPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Suffix check
309
- - **string.Char(pos: integer):string** — Character at position
310
- - **string.CharCode(pos: integer):integer** — Character code
350
+ - **string.Char(pos: integer):string?** — Character at position, or **void** when unavailable
351
+ - **string.CharCode(pos: integer):integer?** — Character code, or **void** when unavailable
311
352
  - **string.Trim():string** — Trim whitespace
312
353
  - **string.TrimStart():string** — Trim leading whitespace
313
354
  - **string.TrimEnd():string** — Trim trailing whitespace
314
355
  - **string.LowerCase():string** — To lowercase
315
356
  - **string.UpperCase():string** — To uppercase
316
- - **string.Split(separator: string = ' '):array** — Split into array
317
- - **string.ReplaceWith(replacement: string, search: ...(string | array)):string** — Replace all instances of the searched strings
357
+ - **string.Split(separator: string = ' '):[string]** — Split into an array of strings
358
+ - **string.ReplaceWith(replacement: string, search: ...(string | [string])):string** — Replace all instances of the searched strings
318
359
 
319
360
  #### Timestamp Functions
320
361
  - **timestamp.Year(utc: boolean?):integer** — Get year
@@ -332,35 +373,57 @@ Invalid non-null inputs are function-specific and may raise an evaluation error.
332
373
  - **timestamp.MinutesSince(value: timestamp):float** — Difference from another timestamp in minutes
333
374
  - **timestamp.SecondsSince(value: timestamp):float** — Difference from another timestamp in seconds
334
375
 
335
- ## Reference
336
-
337
- Create instance of Affinirum class with a string containing script and optional compilation configuration.
338
- During the parsing any alphanumeric sequence not identified as
339
- number value, string value, operator, or a function name is assumed to be variable.
340
- Evaluate the expression by providing variable values.
341
-
342
- Sample code:
343
-
344
- ```ts
345
- ...
346
- const expr = new Affinirum( 'x * (y + abc / 5) > 10' );
347
- const value1 = expr.evaluate( { x: 10, y: 20, abc: 10 } ); // true
348
- const value2 = expr.evaluate( { x: 1, y: 4, abc: 5 } ); // false
349
- ...
350
- const arrExpr = new Affinirum( 'Integer.Sum([ 1, 2, 3, a, b, c ])' );
351
- const valueSum = arrExpr.evaluate( { a: 10, b: 20, c: 30 } ); // 66
352
- ...
353
- const objExpr = new Affinirum( '[`prop1`:a,`prop2`:`abc`].prop1+10' );
354
- const oValue = objExpr.evaluate( { a: 50 } ); // 60
355
- ...
356
- const iteratorExpr = new Affinirum(
357
- 'Float.Sum(arr1.Derive(~(a:float):float{a*2}).Filter(~(a:float):boolean{a>3}))'
358
- );
359
- const iValue = iteratorExpr.evaluate( { arr1: [ 1, 2, 3 ] } ); // 10
360
- ...
361
- const complexExpr = new Affinirum(
362
- 'var a=myvar1/10, val b=myvar2-100, a/b + b*a + 600'
363
- );
364
- const value = complexExpr.evaluate( { myvar1: 40, myvar2: 104 } ); // 4761
365
- ...
366
- ```
376
+ ## Reference
377
+
378
+ Install the package:
379
+
380
+ ```sh
381
+ npm install affinirum
382
+ ```
383
+
384
+ Create an `Affinirum` instance with a script and optional compilation configuration, then call `evaluate`
385
+ with the script's input variables:
386
+
387
+ ```ts
388
+ import { Affinirum } from "affinirum";
389
+
390
+ const expression = new Affinirum("a + b");
391
+ const result = expression.evaluate({ a: 10n, b: 20n }); // 30n
392
+ ```
393
+
394
+ During parsing, any valid name that is not recognized as a keyword, constant, or built-in function is treated as an input variable.
395
+ Use the optional constructor configuration to specify the expected result `type`, enable `strict` handling of undeclared variables,
396
+ 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.
399
+
400
+ JavaScript `number` values map to **float**, while **integer** values map to `bigint`. Timestamps use `Date`, buffers use
401
+ `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.
403
+
404
+ Use **val** for a local value that cannot be reassigned and **var** for a reassignable local variable. Statements are
405
+ separated with semicolons.
406
+
407
+ Sample code:
408
+
409
+ ```ts
410
+ const expr = new Affinirum("x * (y + abc / 5) > 10");
411
+ const value1 = expr.evaluate({ x: 10, y: 20, abc: 10 }); // true
412
+ const value2 = expr.evaluate({ x: 1, y: 4, abc: 5 }); // false
413
+
414
+ const arrExpr = new Affinirum("Integer.Sum([1, 2, 3, a, b, c])");
415
+ const valueSum = arrExpr.evaluate({ a: 10n, b: 20n, c: 30n }); // 66n
416
+
417
+ const objExpr = new Affinirum('["prop1":a, "prop2":"abc"].prop1 + 10');
418
+ const oValue = objExpr.evaluate({ a: 50n }); // 60n
419
+
420
+ const iteratorExpr = new Affinirum(
421
+ "Float.Sum(arr1.Derive(~(a:float):float{a*2}).Filter(~(a:float):boolean{a>3}))"
422
+ );
423
+ const iValue = iteratorExpr.evaluate({ arr1: [1, 2, 3] }); // 10
424
+
425
+ const complexExpr = new Affinirum(
426
+ "var a = myvar1 / 10; val b = myvar2 - 100; a / b + b * a + 600"
427
+ );
428
+ const value = complexExpr.evaluate({ myvar1: 40, myvar2: 104 }); // 617
429
+ ```
package/dst/Affinirum.js CHANGED
@@ -6,6 +6,7 @@ import { funcGreaterThan, funcLessThan, funcGreaterOrEqual, funcLessOrEqual, fun
6
6
  import { funcCoalesce, funcEqual, funcNotEqual } from "./native/Unknown.js";
7
7
  import { Constant } from "./Constant.js";
8
8
  import { Variable } from "./Variable.js";
9
+ import { normalize } from "./Value.js";
9
10
  import { Type } from "./Type.js";
10
11
  import { Keywords } from "./Keywords.js";
11
12
  import { Constants } from "./Constants.js";
@@ -13,6 +14,7 @@ import { Functions } from "./Functions.js";
13
14
  import { ArrayNode } from "./node/ArrayNode.js";
14
15
  import { BlockNode } from "./node/BlockNode.js";
15
16
  import { CallNode } from "./node/CallNode.js";
17
+ import { CastNode } from "./node/CastNode.js";
16
18
  import { ConstantNode } from "./node/ConstantNode.js";
17
19
  import { JumpNode } from "./node/JumpNode.js";
18
20
  import { LoopNode } from "./node/LoopNode.js";
@@ -93,23 +95,23 @@ export class Affinirum {
93
95
  evaluate(values) {
94
96
  const variables = this._scope.variables();
95
97
  for (const name in variables) {
96
- if (!Object.prototype.hasOwnProperty.call(values, name)) {
98
+ if (!values || !Object.hasOwn(values, name)) {
97
99
  this._varframes.get(name)?.throwError(`undefined variable ${name}:\n`);
98
100
  }
99
101
  const variable = variables[name];
100
- const value = values?.[name] ?? undefined;
101
- if (!variable.type.match(Type.of(value))) {
102
+ const value = normalize(values?.[name] ?? undefined);
103
+ if (!variable.type.acceptValue(value)) {
102
104
  this._varframes.get(name)?.throwError(`unexpected type ${Type.of(value)} for variable ${name} of type ${variable.type}:\n`);
103
105
  }
104
106
  variable.value = value;
105
107
  }
106
108
  try {
107
- return this._root.evaluate();
109
+ return normalize(this._root.evaluate() ?? undefined);
108
110
  }
109
111
  catch (e) {
110
112
  if (e instanceof JumpException) {
111
113
  if (e.jump === "exit") {
112
- return e.value;
114
+ return normalize(e.value ?? undefined);
113
115
  }
114
116
  else {
115
117
  throw this._root.throwError(`unexpected ${e.jump} jump`);
@@ -235,9 +237,9 @@ export class Affinirum {
235
237
  return node;
236
238
  }
237
239
  _accessor(state, scope) {
240
+ const frame = state.starts();
238
241
  let node = this._term(state, scope);
239
- while (state.isDot || state.isQuestion || state.isParenthesesOpen || state.isBracketsOpen) {
240
- const frame = state.starts();
242
+ while (state.isDot || state.isQuestion || state.isParenthesesOpen || state.isBracketsOpen || state.isCast) {
241
243
  if (state.isDot || state.isQuestion) { // property access or property existance operator
242
244
  const operator = state.isDot ? funcAt : funcHas;
243
245
  if (state.next().isLiteral && (typeof state.literal.value === "string" || typeof state.literal.value === "bigint")) {
@@ -283,13 +285,20 @@ export class Affinirum {
283
285
  break;
284
286
  }
285
287
  }
288
+ state.closeParentheses();
286
289
  node = new CallNode(frame.ends(state), node, subnodes);
287
- state.closeParentheses().next();
290
+ state.next();
288
291
  }
289
292
  else if (state.isBracketsOpen) { // index access operator
290
- const fnode = new ConstantNode(frame, funcAt);
291
- node = new CallNode(frame, fnode, [node, this._unit(state.next(), scope)]);
292
- state.closeBrackets().next();
293
+ const subnodes = [node, this._unit(state.next(), scope)];
294
+ state.closeBrackets();
295
+ const fnode = new ConstantNode(frame.ends(state), funcAt);
296
+ node = new CallNode(frame, fnode, subnodes);
297
+ state.next();
298
+ }
299
+ else if (state.isCast) { // type cast operator
300
+ const type = this._type(state.next(), scope);
301
+ node = new CastNode(frame.ends(state), node, type);
293
302
  }
294
303
  }
295
304
  return node;
@@ -462,8 +471,8 @@ export class Affinirum {
462
471
  state.throwError("unexpected expression token");
463
472
  }
464
473
  _function(state, scope) {
465
- state.next().openParentheses();
466
474
  const frame = state.starts();
475
+ state.next().openParentheses();
467
476
  let variadic = false;
468
477
  const variables = new Map();
469
478
  while (!state.next().isParenthesesClose) {
@@ -501,8 +510,8 @@ export class Affinirum {
501
510
  const args = Array.from(variables.values());
502
511
  const subnode = this._unit(state, scope.subscope(variables));
503
512
  const func = (...values) => {
504
- args.forEach((arg, ix) => arg.value = values[ix]);
505
- return subnode.evaluate();
513
+ args.forEach((arg, ix) => arg.value = normalize(values[ix]));
514
+ return normalize(subnode.evaluate());
506
515
  };
507
516
  const constant = new Constant(func, Type.functionType(retType, args.map((v) => v.type), variadic));
508
517
  return new ConstantNode(frame, constant, subnode);
@@ -554,7 +563,7 @@ export class Affinirum {
554
563
  }
555
564
  state.closeBrackets().next();
556
565
  return colon
557
- ? Type.objectType(Object.fromEntries(itemKeyTypes.map(([key, type]) => [key, type])))
566
+ ? Type.objectType(itemKeyTypes.map(([key, type]) => [key, type]))
558
567
  : Type.arrayType(itemKeyTypes.map(([, v]) => v));
559
568
  }
560
569
  else if (state.isTilda) { // function type
package/dst/Atom.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export interface IAtom {
2
- match(atom: IAtom): boolean;
2
+ equate(atom: IAtom): boolean;
3
+ accept(atom: IAtom): boolean;
4
+ intersect(atom: IAtom): boolean;
3
5
  weight(): number;
4
6
  toString(): string;
5
7
  }
package/dst/Constant.js CHANGED
@@ -12,7 +12,7 @@ export class Constant {
12
12
  return this._value;
13
13
  }
14
14
  get type() {
15
- return Type.isPrimitiveType(this._value) ? Type.of(this._value) : this._type;
15
+ return Type.isPrimitive(this._value) ? Type.of(this._value) : this._type;
16
16
  }
17
17
  set type(type) {
18
18
  this._type = type;