affinirum 1.5.4 → 1.6.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 (44) hide show
  1. package/README.md +589 -316
  2. package/dst/Affinirum.d.ts +2 -2
  3. package/dst/Affinirum.js +22 -19
  4. package/dst/Functions.js +1 -3
  5. package/dst/Keywords.js +2 -1
  6. package/dst/Node.d.ts +1 -1
  7. package/dst/Node.js +4 -0
  8. package/dst/ParserState.d.ts +2 -2
  9. package/dst/ParserState.js +10 -10
  10. package/dst/cjs/Affinirum.d.ts +2 -2
  11. package/dst/cjs/Affinirum.js +22 -19
  12. package/dst/cjs/Functions.js +0 -2
  13. package/dst/cjs/Keywords.js +2 -1
  14. package/dst/cjs/Node.d.ts +1 -1
  15. package/dst/cjs/Node.js +4 -0
  16. package/dst/cjs/ParserState.d.ts +2 -2
  17. package/dst/cjs/ParserState.js +10 -10
  18. package/dst/cjs/native/Array.d.ts +0 -2
  19. package/dst/cjs/native/Array.js +5 -13
  20. package/dst/cjs/node/JumpNode.d.ts +5 -8
  21. package/dst/cjs/node/JumpNode.js +9 -20
  22. package/dst/cjs/node/LoopNode.js +4 -4
  23. package/dst/cjs/node/ReturnNode.d.ts +18 -0
  24. package/dst/cjs/node/ReturnNode.js +38 -0
  25. package/dst/cjs/node/{SwitchNode.d.ts → TernaryNode.d.ts} +1 -1
  26. package/dst/cjs/node/{SwitchNode.js → TernaryNode.js} +3 -3
  27. package/dst/native/Array.d.ts +0 -2
  28. package/dst/native/Array.js +4 -12
  29. package/dst/node/JumpNode.d.ts +5 -8
  30. package/dst/node/JumpNode.js +9 -20
  31. package/dst/node/LoopNode.js +4 -4
  32. package/dst/node/ReturnNode.d.ts +18 -0
  33. package/dst/node/ReturnNode.js +34 -0
  34. package/dst/node/{SwitchNode.d.ts → TernaryNode.d.ts} +1 -1
  35. package/dst/node/{SwitchNode.js → TernaryNode.js} +1 -1
  36. package/package.json +3 -3
  37. package/dst/Jump.d.ts +0 -1
  38. package/dst/Jump.js +0 -1
  39. package/dst/JumpException.d.ts +0 -9
  40. package/dst/JumpException.js +0 -14
  41. package/dst/cjs/Jump.d.ts +0 -1
  42. package/dst/cjs/Jump.js +0 -2
  43. package/dst/cjs/JumpException.d.ts +0 -9
  44. package/dst/cjs/JumpException.js +0 -18
package/README.md CHANGED
@@ -1,207 +1,474 @@
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, 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
-
8
- Supports algebraic and boolean expressions, variables, conditionals, loops, and a rich standard library for working with numbers, buffers, strings, arrays, and objects.
9
-
10
- Runs in browsers and Node.js.
11
-
12
- Target: ES2022 [browser+Node.js][ESM+CJS].
13
-
14
- ## Features
15
-
16
- - Efficient execution: Parse once, execute many times with different variable values.
17
- - Variable support: Input and statement-scoped variables.
18
- - Function support: Variadic and first-class functions for expressive scripting.
19
- - Optimized evaluation: Constant expression folding with type checks.
20
- - Comprehensive set of operators: Boolean, arithmetic, buffer, string, comparison, and indexing support.
21
- - Built-in functions: Rich set of mathematical and composition utilities.
22
-
23
- ## Specifications
24
-
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. An empty block has type **void** and evaluates to JavaScript `undefined`.
27
- - Scientific notation is supported for floating point numbers, like *0.1281e+2*.
28
- - ISO Timestamps prefixed with **@**, like *@2025-05-11T19:09:21.320Z*.
29
- - Hexadecimal buffer values are enclosed in backticks (**\`**), like *\`10ab0901\`*.
30
- - String literals may be enclosed in single (**'**), or double (**"**) quotes, like *'string value1'*, or *"string value2"*.
31
- - Line comments begin with a double slash (**//**), while block comments are enclosed in triple slashes (**///**).
32
-
33
- ### Arrays
34
- Array is an ordered sequence of values of any type.
35
- It is defined by comma-separated values enclosed in brackets (**[]**),
36
- like *[0,1,2]*, *["a","b","c"]*.
37
- <br>An empty array is represented as **[]**.
38
-
39
- Array elements can be accessed using the access operator (**.**),
40
- or using brackets with a zero-based numeric index, like *theArray.23*, *theArray[0]*, *theArray[10]*, *theArray[indexVar]*.
41
-
42
- An easy way to check whether an array contains an index is to use the presence operator (**?**), like *theArray?50*.
43
-
44
- ### Objects
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
- <br>An empty object is represented as **[\:]**.
49
-
50
- Object properties can be accessed using the access operator (**.**) with a string literal, token,
51
- or with brackets containing a string key,
52
- like *theObject."key"*, *theObject.key*, or *theObject["key"]*.
53
-
54
- An easy way to check whether an object contains a key is to use the presence operator (**?**), like *theObject?myKey*.
55
-
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
-
61
- ### Variables
62
- Valid variable and function names must start with a letter, number sign (**\#**), dollar sign (**\$**), or underscore (**\_**)
63
- and can be followed by any combination of alphanumeric characters, number signs, dollar signs, or underscores,
64
- like *x*, *\_a1$*, *abc25*.
65
-
66
- Whitespace characters are ignored.
67
-
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
- - **buffer** for ordered sequences of bytes
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
- - **[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
82
- - Type grouping: **(...)**
83
- - Type union: **|**
84
- - Type optionality modifier: **?**
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
- - 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.
103
- - Function compatibility is deliberately flexible. The accepted argument-count ranges only need to overlap;
104
- one function's complete arity range does not need to contain the other's.
105
- - A callback may declare fewer parameters than the caller provides. Additional arguments are ignored at runtime,
106
- following JavaScript function-call behavior.
107
- - Function parameter types are checked contravariantly where both signatures declare a parameter, while **??**
108
- remains compatible with any parameter type. Return types are checked covariantly.
109
- - Fixed and variadic signatures are not interchangeable. Variadic arguments use a distinct packed-array calling
110
- convention and are only compatible with corresponding variadic signatures.
111
2
 
112
- For example, a callback declared as `~(value: float):boolean` is compatible with an expected callback type such as
113
- `~(value: ??, index: integer?, values: array?):boolean`: the arities overlap, **??** accepts the concrete value type,
114
- and the callback may ignore the additional arguments. This behavior is intentional. Affinirum does not enforce strict
115
- function subtyping.
116
-
117
- ### Type casting
118
- A postfix type cast declares the expected type of an expression using **::type**,
119
- like `value::object` or `JSON.Parse(json)::object.property`.
120
-
121
- A cast does not convert the value. The source and target types must be compatible at compile time,
122
- and the evaluated value must satisfy the target type at runtime. An incompatible cast raises an error.
123
- Casts can be followed by property access, index access, function calls, or another cast.
124
-
125
- ### Definitions
126
- - Unit grouping: **{...}**
127
- - Unit separator: **;**
128
- - Value grouping: **(...)**
129
- - Value separator: **,**
130
- - Array element at numeric index, or object property by string key: **[]**
131
- - Object property by string key or method function call: **.**
132
- - Array definition: **[item1, ...]**
133
- - Object definition: **[property1-key: property1-value, ...]**
134
- - Subroutine definition: **~(argument1-name: argument1-type, ...):return-type {...}**
135
- - Conditional switch definition, returns first or second value if prefix is true or false: **if condition {value1} else {value2}**,
136
- and if the **else** clause is omitted, the second value is **void**
137
- - Loop definition, iteratively evaluates suffix while prefix is true, returns last evaluated value: **while condition {...}**
138
- - Stop iteration: **stop**
139
- - Proceed to next iteration: **next**
140
- - Function return operator: **~>value**
141
- - Execution exit operator: **=>value**
142
-
143
- ### Operators
144
- - Boolean negation (Logical NOT): **!**
145
- - Boolean disjunction (Logical OR): **|**
146
- - Boolean conjunction (Logical AND): **&**
147
- - Greater than: **>**
148
- - Less than: **<**
149
- - Greater than or equals to: **>=**
150
- - Less than or equals to: **<=**
151
- - Equals to: **==**
152
- - Not equals to: **!=**
153
- - Arithmetic addition, or buffer, string, and array concatenation: **+**
154
- - Arithmetic subtraction or negation: **-**
155
- - Arithmetic multiplication: **\***
156
- - Arithmetic division: **/**
157
- - Arithmetic remainder: **%**
158
- - Exponentiation operator: **^**
159
- - Property access operator: **.**
160
- - Property existence operator: **?**
161
- - Null coalescence operator: **?:**
162
- - Type cast operator: **::**
163
- - Assignment: **=**
164
- - Boolean disjunction (Logical OR) assignment: **|=**
165
- - Boolean conjunction (Logical AND) assignment: **&=**
166
- - Arithmetic addition assignment: **+=**
167
- - Arithmetic subtraction assignment: **-=**
168
- - Arithmetic multiplication assignment: **\*=**
169
- - Arithmetic division assignment: **/=**
170
- - Arithmetic remainder assignment: **%=**
171
-
172
- ### Native Global Functions
173
-
174
- Native conversions use the following **void** handling:
175
-
3
+ Affinirum is an embeddable scripting language for expressions, rules, and algorithmic logic in JavaScript applications.
4
+ It supports variables, conditionals, loops, first-class functions, and a standard library for numbers, timestamps,
5
+ buffers, strings, arrays, and objects. The host application supplies input values and functions.
6
+
7
+ Runs in browsers and Node.js with an ES2022 runtime. The package provides ESM, CommonJS, and TypeScript declarations.
8
+
9
+ - Parse once and evaluate repeatedly with different inputs.
10
+ - Infer types and fold constant expressions during compilation.
11
+ - Use immutable data values with reassignable `var` bindings.
12
+ - Define typed functions, callbacks, and variadic parameters.
13
+
14
+ ## Contents
15
+
16
+ - [Install and quick start](#install-and-quick-start)
17
+ - [Language basics](#language-basics)
18
+ - [Statements and literals](#statements-and-literals)
19
+ - [Variables and immutable values](#variables-and-immutable-values)
20
+ - [Conditionals](#conditionals)
21
+ - [Loops](#loops)
22
+ - [Functions and returns](#functions-and-returns)
23
+ - [Arrays and objects](#arrays-and-objects)
24
+ - [Method calls and chaining](#method-calls-and-chaining)
25
+ - [Types](#types)
26
+ - [Operators and precedence](#operators-and-precedence)
27
+ - [Embedding API](#embedding-api)
28
+ - [Typed inputs and strict mode](#typed-inputs-and-strict-mode)
29
+ - [Host functions](#host-functions)
30
+ - [JavaScript value mapping](#javascript-value-mapping)
31
+ - [Errors](#errors)
32
+ - [Affinirum Notation](#affinirum-notation)
33
+ - [Standard library](#standard-library)
34
+ - [Global functions](#global-functions)
35
+ - [Method functions](#method-functions)
36
+ - [Detailed type rules](#detailed-type-rules)
37
+
38
+ ## Install and quick start
39
+
40
+ ```sh
41
+ npm install affinirum
42
+ ```
43
+
44
+ Create an instance to compile a script, then call `evaluate` with its inputs. Reuse the instance to avoid parsing again:
45
+
46
+ ```js
47
+ import { Affinirum } from "affinirum";
48
+
49
+ const expression = new Affinirum("a + b");
50
+ console.log(expression.evaluate({ a: 10n, b: 20n })); // 30n
51
+ console.log(expression.evaluate({ a: 40n, b: 2n })); // 42n
52
+ ```
53
+
54
+ The `n` suffix belongs to JavaScript's `bigint` syntax. Inside an Affinirum script, write integers as `10`, not `10n`.
55
+ JavaScript `number` inputs represent Affinirum floats; `bigint` inputs represent integers.
56
+
57
+ CommonJS applications can use `require`:
58
+
59
+ ```js
60
+ const { Affinirum } = require("affinirum");
61
+
62
+ console.log(new Affinirum("1 + 2").evaluate()); // 3n
63
+ ```
64
+
65
+ The examples under **Language basics** contain Affinirum source. Pass them as strings to `new Affinirum(script)`.
66
+ Scripts without external inputs can be evaluated with `evaluate()`.
67
+
68
+ ## Language basics
69
+
70
+ ### Statements and literals
71
+
72
+ Separate statements with semicolons; a newline alone does not separate them. A script or `{ ... }` block returns the
73
+ value of its last expression. An empty block has type `void` and evaluates to JavaScript `undefined`.
74
+ Use parentheses to group expressions and commas to separate arguments or collection items.
75
+
76
+ ```text
77
+ val base = 10;
78
+ val extra = { val factor = 2; factor * 3 };
79
+ base + extra // 16
80
+ ```
81
+
82
+ | Kind | Literal examples |
83
+ | --- | --- |
84
+ | Integer | `42`, `-7` |
85
+ | Float | `42.0`, `0.5`, `1e3`, `0.1281e+2` |
86
+ | Boolean | `true`, `false` |
87
+ | String | `'hello'`, `"hello"` |
88
+ | Timestamp | `@2025-05-11T19:09:21.320Z` |
89
+ | Buffer | `` `10ab0901` `` (hexadecimal bytes) |
90
+ | Void | `null` |
91
+ | Array | `[1, 2, 3]`, `[]` |
92
+ | Object | `["name": "Ada", "score": 10]`, `[:]` |
93
+
94
+ Integers are signed 64-bit values; overflow wraps to that range. Floats use IEEE 754 binary64.
95
+ Integer division truncates toward zero: `7 / 2` is `3`, while `7.0 / 2` is `3.5`.
96
+ Arithmetic involving a float produces a float.
97
+
98
+ Whitespace outside literals and comments is ignored. Names are case-sensitive. Line comments start with `//`;
99
+ block comments are enclosed in `/// ... ///`. Strings support escapes such as `\n`, `\r`, `\t`, `\\`, and escaped quotes.
100
+
101
+ ### Variables and immutable values
102
+
103
+ Use `val` for a binding that cannot be reassigned and `var` for one that can. Types can be inferred or declared after a colon:
104
+
105
+ ```text
106
+ val step = 2;
107
+ var count: integer = 1;
108
+ count += step;
109
+ count // 3
110
+ ```
111
+
112
+ Bindings declared inside a block are local to that block. Names must start with an ASCII letter, `#`, `$`, or `_`,
113
+ followed by any combination of those characters and digits, such as `x`, `_a1$`, or `abc25`.
114
+ Language keywords, including `var`, `val`, `if`, `else`, `while`, `next`, and `exit`, as well as type names and their
115
+ aliases, are reserved.
116
+
117
+ All values in Affinirum are immutable at the script level. Collection operations produce replacement values while
118
+ preserving their inputs. Reassigning a `var` preserves the value held by other bindings:
119
+
120
+ ```text
121
+ var items = [1];
122
+ val original = items;
123
+ items += [2];
124
+ [items, original] // [[1,2],[1]]
125
+ ```
126
+
127
+ Array items and object properties cannot be assigned in place. Use concatenation, collection methods, or `Object.Merge`
128
+ to create an updated value.
129
+
130
+ ### Conditionals
131
+
132
+ `if condition { ... } else { ... }` is a conditional expression: it evaluates only the selected branch and returns
133
+ that branch's value. The condition must be boolean. If `else` is omitted and the condition is false, the result is `null`.
134
+
135
+ ```text
136
+ val score = 82;
137
+ val category = if score >= 60 { "pass" } else { "fail" };
138
+ category // "pass"
139
+ ```
140
+
141
+ ### Loops
142
+
143
+ `while condition { ... }` repeats while its boolean condition is true. Use `next` to skip the rest of the current
144
+ iteration and check the condition again, or `exit` to leave the innermost loop:
145
+
146
+ ```text
147
+ var i = 0;
148
+ var total = 0;
149
+ while i < 10 {
150
+ i += 1;
151
+ if i == 3 { next };
152
+ if i == 6 { exit };
153
+ total += i
154
+ };
155
+ total // 12
156
+ ```
157
+
158
+ A loop returns its last completed iteration's value, or `null` if no iteration completes. An iteration interrupted
159
+ by `next` or `exit` does not replace that result. Neither keyword can jump from a called function into its caller's loop.
160
+
161
+ ### Functions and returns
162
+
163
+ Define a function with `~(name: type, ...): return-type { ... }`. Its last expression is its result; use `~>value`
164
+ to return from the current function early:
165
+
166
+ ```text
167
+ val absolute = ~(value: integer): integer {
168
+ if value < 0 { ~> -value };
169
+ value
170
+ };
171
+ absolute(-5) // 5
172
+ ```
173
+
174
+ Functions are values and can be passed as callbacks. A final variadic parameter collects the remaining arguments into
175
+ an array. Declare it with `...` followed by an array type:
176
+
177
+ ```text
178
+ val sum = ~(values: ...[integer]): integer { Integer.Sum(values) };
179
+ sum(1, 2, 3) // 6
180
+ ```
181
+
182
+ Use the global return operator `=>value` to finish the entire script evaluation, including from inside a function or callback:
183
+
184
+ ```text
185
+ val stop = ~(): integer { =>42 };
186
+ stop();
187
+ 0 // The script returns 42 before reaching this expression.
188
+ ```
189
+
190
+ ### Arrays and objects
191
+
192
+ Arrays hold ordered values of any type and use zero-based indexes. Access an item with brackets or a dot followed by
193
+ an integer. The presence operator `?` checks whether an index exists:
194
+
195
+ ```text
196
+ val items = [10, 20, 30];
197
+ [items[0], items.1, items?2, items?3] // [10,20,true,false]
198
+ ```
199
+
200
+ Use `+` to concatenate arrays. Wrap an individual item in an array when adding it:
201
+
202
+ ```text
203
+ [1, 2] + [3, 4]; // [1,2,3,4]
204
+ [0] + [1, 2]; // [0,1,2]
205
+ [1] + [[2, 3]] // [1,[2,3]]
206
+ ```
207
+
208
+ Objects hold named values. Define them with string keys and colons inside brackets; `[:]` is an empty object.
209
+ Access properties with `record.key`, `record."key"`, or `record["key"]`. Use `record?key` to check for a literal key,
210
+ or `record.Has(keyVariable)` for a computed key.
211
+
212
+ ```text
213
+ val original = ["name": "Ada", "score": 10];
214
+ val updated = Object.Merge(original, ["score": 20, "active": true]);
215
+ [original.score, updated.score, updated.active] // [10,20,true]
216
+ ```
217
+
218
+ `Object.Merge` creates a new object; later arguments take precedence for duplicate keys. Array concatenation and
219
+ object merging are shallow: nested values are shared by reference, with their contents preserved at the script level.
220
+
221
+ ### Method calls and chaining
222
+
223
+ Built-in methods use `value.Method(arguments)`. Parentheses can be omitted when no explicit arguments are needed:
224
+ `items.Length` and `items.Length()` are equivalent. Method results can be chained:
225
+
226
+ ```text
227
+ " hello ".Trim.UpperCase // "HELLO"
228
+ ```
229
+
230
+ Callbacks make collection transformations composable:
231
+
232
+ ```text
233
+ val values = [1, 2, 3];
234
+ values.Derive(~(item: integer): integer { item * 2 })
235
+ .Filter(~(item: integer): boolean { item > 3 }) // [4,6]
236
+ ```
237
+
238
+ After a dot, a built-in method name takes precedence over an object property with the same name.
239
+ Use brackets or a quoted key to read such a property, for example `record["Length"]` or `record."Length"`.
240
+
241
+ ### Types
242
+
243
+ | Type | Meaning |
244
+ | --- | --- |
245
+ | `void` | Absence of a value; the script literal is `null` |
246
+ | `boolean` / `bool` | `true` or `false` |
247
+ | `timestamp` / `time` | Date and time |
248
+ | `float` / `f64` | 64-bit floating-point number |
249
+ | `integer` / `i64` | Signed 64-bit integer |
250
+ | `buffer` | Sequence of bytes |
251
+ | `string` | Text |
252
+ | `array` | Sequence of values |
253
+ | `object` | Named values |
254
+ | `function` | Built-in, host-provided, or script-defined function |
255
+ | `??` | Unknown or variant type, compatible with every type |
256
+ | `[string]` | Array of strings |
257
+ | `[integer, string]` | Tuple with integer and string entries |
258
+ | `["name": string]` | Object with a required string property named `name` |
259
+ | `~(integer): string` | Function taking an integer and returning a string |
260
+ | `integer?` | Optional integer: `void` or `integer` |
261
+ | `integer \| string` | Union of types |
262
+
263
+ Parentheses group types, for example `(integer | string)?`. Type checking is intentionally permissive; see
264
+ [Detailed type rules](#detailed-type-rules) for structural types, callback compatibility, and variadic signatures.
265
+
266
+ A postfix cast, `expression::type`, checks an expected type without converting the value:
267
+
268
+ ```text
269
+ val parsed = JSON.Parse('{"answer":42}');
270
+ parsed::object.answer // 42.0
271
+ ```
272
+
273
+ Standard JSON numbers are floats. Use conversion methods such as `.Integer()` or `.Float()` to convert numeric types.
274
+ An incompatible cast raises an error. Casts can be followed by property access, indexing, calls, or another cast.
275
+
276
+ ### Operators and precedence
277
+
278
+ Expression operators are listed from highest precedence to lowest. Parentheses override grouping.
279
+
280
+ | Precedence | Operators | Meaning |
281
+ | --- | --- | --- |
282
+ | Highest | `.`, `[]`, `?`, `()`, `::` | Access, presence, calls, and casts |
283
+ | | `^` | Exponentiation |
284
+ | | Unary `+`, `-` | Arithmetic sign |
285
+ | | `*`, `/`, `%` | Multiplication, division, remainder |
286
+ | | `+`, `-` | Addition or concatenation; subtraction |
287
+ | | `>`, `<`, `>=`, `<=`, `==`, `!=` | Comparison and equality |
288
+ | | `!` | Boolean negation |
289
+ | | `&` | Boolean AND |
290
+ | | `\|` | Boolean OR |
291
+ | Lowest | `?:` | Null coalescing |
292
+
293
+ Binary operators at the same precedence group left to right, including exponentiation:
294
+ `2 ^ 3 ^ 2` means `(2 ^ 3) ^ 2` and produces `64`. Exponentiation binds before arithmetic sign, so `-2 ^ 2` is `-4`.
295
+ Boolean negation binds after comparisons: `!a == b` means `!(a == b)`.
296
+
297
+ `+` adds numbers or concatenates strings, buffers, and arrays. `value ?: fallback` returns `fallback` when `value` is
298
+ `void`, otherwise `value`. Operators evaluate their operands eagerly, including `&`, `|`, and `?:`.
299
+ Use `if` when only one branch should run.
300
+
301
+ Assign with `=` or combine assignment with an operation: `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, and `|=`.
302
+ Assignments and returns consume the expression that follows them; separate them into statements for clarity.
303
+
304
+ ## Embedding API
305
+
306
+ `new Affinirum(script, config?)` parses and compiles the script. `evaluate(inputs?)` executes it with the current inputs.
307
+ By default, a name that is not a local binding, keyword, or built-in is treated as an input variable, and its type is inferred
308
+ from how it is used.
309
+
310
+ ### Typed inputs and strict mode
311
+
312
+ Use constructor configuration to declare input types, require declarations, and constrain the result type:
313
+
314
+ ```js
315
+ import { Affinirum, Type } from "affinirum";
316
+
317
+ const expression = new Affinirum("price * quantity", {
318
+ strict: true,
319
+ type: Type.Float,
320
+ variables: {
321
+ price: Type.Float,
322
+ quantity: Type.Integer,
323
+ },
324
+ });
325
+
326
+ console.log(expression.evaluate({ price: 12.5, quantity: 3n })); // 37.5
327
+ ```
328
+
329
+ - `variables` declares input types; structured types can be built with helpers such as `Type.arrayType([Type.Integer])`
330
+ and `Type.objectType([["name", Type.String]])`.
331
+ - `strict: true` rejects undeclared input names during compilation. It does not change the language's type compatibility rules.
332
+ - `type` specifies the expected result type and is checked during compilation.
333
+
334
+ Every referenced input must be supplied as an own property of the object passed to `evaluate`, even if its value is `undefined`.
335
+ Non-function input values are checked against their inferred or declared types, including array items and object properties.
336
+
337
+ | Instance member | Result |
338
+ | --- | --- |
339
+ | `script` | Original script text |
340
+ | `type` | Inferred result `Type`; use `.toString()` for its readable form |
341
+ | `variables()` | Record of referenced input names and their inferred types |
342
+ | `toString()` | Compiled tree representation |
343
+ | `evaluate(inputs?)` | Script result as a JavaScript value |
344
+
345
+ ### Host functions
346
+
347
+ Declare a function's type in `variables`, then supply its JavaScript implementation on evaluation.
348
+ `Type.functionType` takes the return type first and the parameter types second:
349
+
350
+ ```ts
351
+ import { Affinirum, Type } from "affinirum";
352
+
353
+ const expression = new Affinirum("discount(total)", {
354
+ strict: true,
355
+ type: Type.Float,
356
+ variables: {
357
+ total: Type.Float,
358
+ discount: Type.functionType(Type.Float, [Type.Float]),
359
+ },
360
+ });
361
+
362
+ const result = expression.evaluate({
363
+ total: 100,
364
+ discount: (amount: number) => amount * 0.9,
365
+ }); // 90
366
+ ```
367
+
368
+ Injected functions are checked to be callable. Their JavaScript parameter behavior and return values are trusted
369
+ according to their declared Affinirum types. Supply synchronous functions that return supported values.
370
+
371
+ ### JavaScript value mapping
372
+
373
+ | Affinirum type | JavaScript value |
374
+ | --- | --- |
375
+ | `void` | `undefined` on output; `null` or `undefined` accepted as input |
376
+ | `boolean` | `boolean` |
377
+ | `float` | `number` |
378
+ | `integer` | `bigint` |
379
+ | `timestamp` | `Date` |
380
+ | `buffer` | `ArrayBuffer` |
381
+ | `string` | `string` |
382
+ | `array` | Array of supported values |
383
+ | `object` | Object containing supported values |
384
+ | `function` | Synchronous JavaScript function |
385
+
386
+ For example, supply `quantity: 3n` for an integer input; `quantity: 3` supplies a float.
387
+
388
+ ### Errors
389
+
390
+ Syntax and compilation errors are thrown by the constructor. Missing inputs, incompatible input values, and other
391
+ evaluation failures are thrown by `evaluate`. Errors reported by the parser or type checker include a source position
392
+ and an excerpt. Catch errors around both construction and evaluation:
393
+
394
+ ```js
395
+ import { Affinirum, Type } from "affinirum";
396
+
397
+ try {
398
+ const expression = new Affinirum("quantity + 1", {
399
+ strict: true,
400
+ variables: { quantity: Type.Integer },
401
+ });
402
+ expression.evaluate({ quantity: "three" }); // Throws: an integer was expected.
403
+ } catch (error) {
404
+ console.error(error instanceof Error ? error.message : String(error));
405
+ }
406
+ ```
407
+
408
+ ### Affinirum Notation
409
+
410
+ Affinirum Notation (AN) uses the language's literal syntax to represent values, including integers, timestamps,
411
+ buffers, arrays, and objects. `Affinirum.parse()` reads a single notation value; it does not execute a script.
412
+ Empty or `undefined` input returns `undefined`, and invalid input throws. `Affinirum.format()` writes a notation string:
413
+
414
+ ```js
415
+ import { Affinirum } from "affinirum";
416
+
417
+ const value = Affinirum.parse('["answer":42,"enabled":true]');
418
+ const notation = Affinirum.format(value); // '["answer":42,"enabled":true]'
419
+
420
+ Affinirum.format(undefined); // "null"
421
+ Affinirum.format(null); // "null"
422
+ Affinirum.format([1n, undefined]); // "[1,null]"
423
+ Affinirum.format({ missing: undefined }); // '["missing":null]'
424
+ ```
425
+
426
+ Both `Affinirum.format(value, whitespace?)` and the script function `AN.Format(value, whitespace?)` accept optional
427
+ indentation text. They write JavaScript `null` and `undefined` as the AN literal `null` at every nesting level.
428
+ Parsing that literal produces JavaScript `undefined`, preserving array lengths and object properties containing `void`.
429
+
430
+ ## Standard library
431
+
432
+ Global functions use namespaces such as `Integer.Sum(...)`. Method functions use `value.Method(...)`.
433
+ In the signatures below, `T?` means `T` or `void`, `...` marks variadic arguments, and `??` means any type.
434
+ Parameters whose type includes `void` can be omitted. Parameter names are explanatory; arguments are positional.
435
+
436
+ ### Global functions
437
+
438
+ Native conversions use the following **void** handling:
439
+
176
440
  - General `Format` conversions and `JSON.Format` return an empty string for **void**.
177
441
  - `AN.Format` and `Affinirum.format` serialize **void** as the literal `null`, including array elements and object properties.
178
- - `Encode` returns a zero-length buffer for **void**.
179
- - `Decode` and `Parse` return **void** when their input value is **void**.
180
-
181
- Empty strings and zero-length buffers remain ordinary values; they are not serialized void markers.
182
- Invalid non-void inputs are function-specific and may raise an evaluation error.
183
-
184
- #### Boolean
185
- - **Boolean.Or(values: ...(boolean | [boolean])):boolean** — Boolean disjunction of booleans and arrays of booleans
186
- - **Boolean.And(values: ...(boolean | [boolean])):boolean** — Boolean conjunction of booleans and arrays of booleans
442
+ - `Encode` returns a zero-length buffer for **void**.
443
+ - `Decode` and `Parse` return **void** when their input value is **void**.
444
+
445
+ Empty strings and zero-length buffers remain ordinary values; they are not serialized void markers.
446
+ Invalid non-void inputs are function-specific and may raise an evaluation error.
447
+
448
+ #### Boolean
449
+
450
+ - **Boolean.Or(values: ...(boolean | [boolean])):boolean** — Boolean disjunction of booleans and arrays of booleans
451
+ - **Boolean.And(values: ...(boolean | [boolean])):boolean** — Boolean conjunction of booleans and arrays of booleans
187
452
  - **Boolean.Not(value: boolean):boolean** — Boolean negation
188
453
  - **Boolean.Decode(value: buffer?, offset: integer?):boolean?** — Decode a byte at the optional offset; missing or out-of-range input returns **void**
189
454
  - **Boolean.Parse(value: string?):boolean?** — Parse case-insensitive `true` or `false`; other values return **void**
190
455
 
191
456
  #### Timestamp
457
+
192
458
  - **Timestamp.Now():timestamp** — Current date and time
193
459
  - **Timestamp.Epoch(value: float | integer, epoch: timestamp?):timestamp** — Create timestamp from milliseconds
194
460
  - **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
195
461
  - **Timestamp.Parse(value: string?):timestamp?** — Parse a string as a timestamp
196
462
 
197
463
  #### Float
464
+
198
465
  - **Float.NAN** — Not-a-number
199
466
  - **Float.PositiveInfinity** — Positive infinity
200
467
  - **Float.NegativeInfinity** — Negative infinity
201
- - **Float.Epsilon** — Smallest positive float
202
- - **Float.Sum(values: ...(float | integer | [float | integer])):float** — Numeric sum
203
- - **Float.Min(values: ...(float | integer | [float | integer])):float** — Numeric minimum
204
- - **Float.Max(values: ...(float | integer | [float | integer])):float** — Numeric maximum
468
+ - **Float.Epsilon** — Difference between `1` and the next larger representable float (`2.220446049250313e-16`)
469
+ - **Float.Sum(values: ...(float | integer | [float | integer])):float** — Numeric sum
470
+ - **Float.Min(values: ...(float | integer | [float | integer])):float** — Numeric minimum
471
+ - **Float.Max(values: ...(float | integer | [float | integer])):float** — Numeric maximum
205
472
  - **Float.Exponent(value: float | integer):float** — Natural exponential
206
473
  - **Float.Logarithm(value: float | integer):float** — Natural logarithm
207
474
  - **Float.Abs(value: float | integer):float** — Absolute value
@@ -214,47 +481,64 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
214
481
  - **Float.Parse(value: string?):float?** — Parse a string as a float
215
482
 
216
483
  #### Integer
217
- - **Integer.Sum(values: ...(integer | [integer])):integer** — Numeric sum
218
- - **Integer.Min(values: ...(integer | [integer])):integer** — Numeric minimum
219
- - **Integer.Max(values: ...(integer | [integer])):integer** — Numeric maximum
484
+
485
+ - **Integer.Sum(values: ...(integer | [integer])):integer** — Numeric sum
486
+ - **Integer.Min(values: ...(integer | [integer])):integer** — Numeric minimum
487
+ - **Integer.Max(values: ...(integer | [integer])):integer** — Numeric maximum
220
488
  - **Integer.Random(exclusiveTo: integer):integer** — Random integer up to value
221
489
  - **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`
222
490
  - **Integer.Parse(value: string?):integer?** — Parse a string as an integer
223
491
 
224
492
  #### String
493
+
225
494
  - **String.Alphanum(value: string):string** — Keep only ASCII letters and digits
226
495
  - **String.Random(length: integer):string** — Random alphanumeric string
227
496
  - **String.Decode(value: buffer?, encoding: string?, offset: integer?, length: integer?):string?** — Decode using `utf8` (default), `sbcs`, `ucs2`, or `ucs2le`
228
497
 
229
498
  #### Buffer
499
+
230
500
  - **Buffer.Random(length: integer):buffer** — Buffer of given length filled with random bytes
231
501
  - **Buffer.Parse(value: string?):buffer?** — Parse a hexadecimal string as a buffer
232
502
 
233
503
  #### Array
234
- - **Array.Join(values: ...array):array** — Join arrays of any depths into a single array
504
+
505
+ - **Array.Join(values: ...array):array** — Concatenate arrays in argument order into a new array, preserving nested arrays
235
506
  - **Array.Range(a: integer, b: integer):array** — Integers from the lower endpoint (inclusive) to the higher endpoint (exclusive)
236
507
  - **Array.Unique(value: array):array** — Array of unique values
237
508
  - **Array.Intersection(a1: array, a2: array):array** — Common values from two arrays
238
- - **Array.Difference(a1: array, a2: array):array** — Symmetrical difference between arrays
509
+ - **Array.Difference(a1: array, a2: array):array** — Symmetric difference between arrays
510
+
511
+ `Array.Join(a,b,c)` has the same shallow concatenation behavior as `a+b+c`. Inputs are preserved, and nested arrays
512
+ and objects are shared by reference. Use `array.Flatten(depth)` to flatten nested array elements.
513
+
514
+ ```text
515
+ Array.Join([1,2],[3],[4,5]); // [1,2,3,4,5]
516
+ Array.Join([[1,2]],[3]) // [[1,2],3]
517
+ ```
518
+
519
+ #### Object
239
520
 
240
- #### Object
241
- - **Object.Merge(values: ...(object | [object])):object** — Merge objects and arrays of objects
521
+ - **Object.Merge(values: ...(object | [object])):object** — Shallow merge into a new object; later arguments take precedence
242
522
 
243
523
  #### AN
524
+
244
525
  - **AN.Format(value: ??, whitespace: string?):string** — Format a value as AN notation; **void** values are written as `null`
245
526
 
246
527
  #### JSON
528
+
247
529
  - **JSON.Format(value: (void | boolean | timestamp | float | integer | string | array | object), whitespace: string?):string** — Format a value as JSON
248
530
  - **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
249
531
 
250
- #### IP
251
- - **IP.Match(values: [string], search: ...(string | [string])):boolean** — Check whether any searched IPv4 or IPv6 address belongs to the supplied addresses or CIDR ranges
532
+ #### IP
533
+
534
+ - **IP.Match(values: [string], search: ...(string | [string])):boolean** — Check whether any searched IPv4 or IPv6 address belongs to the supplied addresses or CIDR ranges
252
535
  - **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
253
536
  - **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**
254
537
 
255
- ### Native Method Functions
538
+ ### Method functions
256
539
 
257
540
  #### General Functions
541
+
258
542
  - **??.Coalesce(otherwise: ??):??** — Null coalescence
259
543
  - **??.Equal(value: ??):boolean** — Equals to
260
544
  - **??.Unequal(value: ??):boolean** — Not equals to
@@ -264,6 +548,7 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
264
548
  - **(void | timestamp | float | integer | buffer | array | object).Format(formatting: string?):string** — Format a value; buffers use `hex` by default and also support `base64`
265
549
 
266
550
  #### Aggregable Functions
551
+
267
552
  - **float.Add(value: float):float** — Add a float
268
553
  - **float.Add(value: integer):float** — Add an integer
269
554
  - **integer.Add(value: float):float** — Add a float
@@ -272,26 +557,30 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
272
557
  - **string.Add(value: string):string** — Concatenate strings
273
558
  - **array.Add(value: array):array** — Concatenate arrays
274
559
 
275
- #### Array Functions
276
- - **array.First(condition: ~(??, integer?, array?):boolean):??** — First item satisfying condition
277
- - **array.Last(condition: ~(??, integer?, array?):boolean):??** — Last item satisfying condition
278
- - **array.FirstIndex(condition: ~(??, integer?, array?):boolean):integer?** — First index satisfying condition, or **void** if none does
279
- - **array.LastIndex(condition: ~(??, integer?, array?):boolean):integer?** — Last index satisfying condition, or **void** if none does
280
- - **array.Every(condition: ~(??, integer?, array?):boolean):boolean** — All items satisfy condition
281
- - **array.Any(condition: ~(??, integer?, array?):boolean):boolean** — Any item satisfies condition
282
- - **array.Reverse():array** — Reversed array
283
- - **array.Flatten(depth: integer = 1):array** — Flatten array
284
- - **array.Derive(transformation: ~(??, integer?, array?):??):array** — Derived array
285
- - **array.Filter(condition: ~(??, integer?, array?):boolean):array** — Filtered array
286
- - **array.Reduce(reducer: ~(??, ??, integer?, array?):??, initial: ?? = void):??** — Reduced value
287
- - **array.Compose(generator: ~(object, string, integer?, array?):??):object** — Compose object from array
288
- - **array.Prepend(items: ...??):array** — Prepend items
289
- - **array.Append(items: ...??):array** — Append items
560
+ #### Array Functions
561
+
562
+ - **array.First(condition: ~(??, integer?, array?):boolean):??** — First item satisfying condition
563
+ - **array.Last(condition: ~(??, integer?, array?):boolean):??** — Last item satisfying condition
564
+ - **array.FirstIndex(condition: ~(??, integer?, array?):boolean):integer?** — First index satisfying condition, or **void** if none does
565
+ - **array.LastIndex(condition: ~(??, integer?, array?):boolean):integer?** — Last index satisfying condition, or **void** if none does
566
+ - **array.Every(condition: ~(??, integer?, array?):boolean):boolean** — All items satisfy condition
567
+ - **array.Any(condition: ~(??, integer?, array?):boolean):boolean** — Any item satisfies condition
568
+ - **array.Reverse():array** — Reversed array
569
+ - **array.Flatten(depth: integer = 1):array** — Flatten array
570
+ - **array.Derive(transformation: ~(??, integer?, array?):??):array** — Derived array
571
+ - **array.Filter(condition: ~(??, integer?, array?):boolean):array** — Filtered array
572
+ - **array.Reduce(reducer: ~(??, ??, integer?, array?):??, initial: ?? = void):??** — Reduced value
573
+ - **array.Compose(generator: ~(object, string, integer?, array?):??):object** — Compose object from array
574
+
575
+ `Compose` builds a new object. Each callback receives an immutable snapshot of the properties produced by earlier callbacks.
576
+ Retaining that snapshot preserves its contents as subsequent properties are added to the result.
290
577
 
291
578
  #### Buffer Functions
579
+
292
580
  - **buffer.Byte(pos: integer):buffer?** — Byte at position, or **void** when unavailable
293
581
 
294
582
  #### Enumerable Functions
583
+
295
584
  - **buffer.Slice(start: integer?, end: integer?):buffer** — Slice section
296
585
  - **string.Slice(start: integer?, end: integer?):string** — Slice section
297
586
  - **array.Slice(start: integer?, end: integer?):array** — Slice section
@@ -303,6 +592,7 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
303
592
  - **array.Inject(start: integer, inject: ...array):array** — Inject section
304
593
 
305
594
  #### Iterable Functions
595
+
306
596
  - **(buffer | string | array | object).Length():integer** — Get length
307
597
  - **buffer.Contains(search: buffer, startPos: integer?):boolean** — Check if buffer contains another buffer
308
598
  - **string.Contains(search: string, startPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Check if string contains another string
@@ -313,59 +603,63 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
313
603
  - **array.Has(index: integer):boolean** — Identify if array has index
314
604
  - **object.Has(index: string):boolean** — Identify if object has key
315
605
 
316
- #### Number Functions
317
- - **(float | integer).GreaterThan(value: float | integer):boolean** — Greater than
318
- - **(float | integer).LessThan(value: float | integer):boolean** — Less than
319
- - **(float | integer).GreaterOrEqual(value: float | integer):boolean** — Greater or equal
320
- - **(float | integer).LessOrEqual(value: float | integer):boolean** — Less or equal
321
- - **float.Subtract(subtrahend: integer):float** — Subtract an integer
322
- - **integer.Subtract(subtrahend: float):float** — Subtract a float
323
- - **integer.Subtract(subtrahend: integer):integer** — Subtract an integer
324
- - **float.Negate():float** — Negate number
325
- - **integer.Negate():integer** — Negate number
326
- - **float.Multiply(value: integer):float** — Multiply by an integer
327
- - **integer.Multiply(value: float):float** — Multiply by a float
328
- - **integer.Multiply(value: integer):integer** — Multiply by an integer
329
- - **float.Divide(divisor: integer):float** — Divide by an integer
330
- - **integer.Divide(divisor: float):float** — Divide by a float
331
- - **integer.Divide(divisor: integer):integer** — Divide by an integer
332
- - **float.Remainder(divisor: integer):float** — Remainder after division by an integer
333
- - **integer.Remainder(divisor: float):float** — Remainder after division by a float
334
- - **integer.Remainder(divisor: integer):integer** — Remainder after division by an integer
335
- - **float.Modulo(divisor: integer):float** — Modulo by an integer
336
- - **integer.Modulo(divisor: float):float** — Modulo by a float
337
- - **integer.Modulo(divisor: integer):integer** — Modulo by an integer
338
- - **float.Power(exponent: integer):float** — Raise to an integer power
339
- - **integer.Power(exponent: float):float** — Raise to a float power
340
- - **integer.Power(exponent: integer):integer** — Raise to an integer power
341
- - **float.Root(index: integer):float** — Take an integer root
342
- - **integer.Root(index: float):float** — Take a float root
343
- - **integer.Root(index: integer):integer** — Take an integer root
606
+ #### Number Functions
607
+
608
+ - **(float | integer).GreaterThan(value: float | integer):boolean** — Greater than
609
+ - **(float | integer).LessThan(value: float | integer):boolean** — Less than
610
+ - **(float | integer).GreaterOrEqual(value: float | integer):boolean** — Greater or equal
611
+ - **(float | integer).LessOrEqual(value: float | integer):boolean** — Less or equal
612
+ - **float.Subtract(subtrahend: float | integer):float** — Subtract a number
613
+ - **integer.Subtract(subtrahend: float):float** — Subtract a float
614
+ - **integer.Subtract(subtrahend: integer):integer** — Subtract an integer
615
+ - **float.Negate():float** — Negate number
616
+ - **integer.Negate():integer** — Negate number
617
+ - **float.Multiply(value: float | integer):float** — Multiply by a number
618
+ - **integer.Multiply(value: float):float** — Multiply by a float
619
+ - **integer.Multiply(value: integer):integer** — Multiply by an integer
620
+ - **float.Divide(divisor: float | integer):float** — Divide by a number
621
+ - **integer.Divide(divisor: float):float** — Divide by a float
622
+ - **integer.Divide(divisor: integer):integer** — Divide by an integer
623
+ - **float.Remainder(divisor: float | integer):float** — Remainder after division by a number
624
+ - **integer.Remainder(divisor: float):float** — Remainder after division by a float
625
+ - **integer.Remainder(divisor: integer):integer** — Remainder after division by an integer
626
+ - **float.Modulo(divisor: float | integer):float** — Modulo by a number
627
+ - **integer.Modulo(divisor: float):float** — Modulo by a float
628
+ - **integer.Modulo(divisor: integer):integer** — Modulo by an integer
629
+ - **float.Power(exponent: float | integer):float** — Raise to a numeric power
630
+ - **integer.Power(exponent: float):float** — Raise to a float power
631
+ - **integer.Power(exponent: integer):integer** — Raise to an integer power
632
+ - **float.Root(index: float | integer):float** — Take a root with the specified index
633
+ - **integer.Root(index: float):float** — Take a float root
634
+ - **integer.Root(index: integer):integer** — Take an integer root
344
635
  - **(boolean | timestamp | integer).Float():float** — Convert to a float; timestamps use milliseconds since the Unix epoch
345
636
  - **(boolean | timestamp | float).Integer():integer** — Convert to an integer; timestamps use milliseconds since the Unix epoch
346
637
  - **(timestamp | float | integer).Boolean():boolean** — Convert to a boolean by testing whether the numeric or epoch value is non-zero
347
638
 
348
- #### Object Functions
349
- - **object.Entries():array** — Key-value pairs
350
- - **object.Keys():[string]** — Object keys
351
- - **object.Values():array** — Object values
639
+ #### Object Functions
640
+
641
+ - **object.Entries():array** — Key-value pairs
642
+ - **object.Keys():[string]** — Object keys
643
+ - **object.Values():array** — Object values
352
644
 
353
645
  #### String Functions
646
+
354
647
  - **string.Like(value: string):boolean** — Alphanumeric equality
355
648
  - **string.Unlike(value: string):boolean** — Alphanumeric inequality
356
649
  - **string.StartsWith(search: string, startPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Prefix check
357
650
  - **string.EndsWith(search: string, endPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Suffix check
358
- - **string.Char(pos: integer):string?** — Character at position, or **void** when unavailable
359
- - **string.CharCode(pos: integer):integer?** — Character code, or **void** when unavailable
651
+ - **string.Char(pos: integer):string?** — Character at position, or **void** when unavailable
652
+ - **string.CharCode(pos: integer):integer?** — Character code, or **void** when unavailable
360
653
  - **string.Trim():string** — Trim whitespace
361
654
  - **string.TrimStart():string** — Trim leading whitespace
362
655
  - **string.TrimEnd():string** — Trim trailing whitespace
363
656
  - **string.LowerCase():string** — To lowercase
364
657
  - **string.UpperCase():string** — To uppercase
365
- - **string.Split(separator: string = ' '):[string]** — Split into an array of strings
366
- - **string.ReplaceWith(replacement: string, search: ...(string | [string])):string** — Replace all instances of the searched strings
658
+ - **string.Split(separator: string = ' '):[string]** — Split into an array of strings
659
+ - **string.ReplaceWith(replacement: string, search: ...(string | [string])):string** — Replace all instances of the searched strings
367
660
 
368
661
  #### Timestamp Functions
662
+
369
663
  - **timestamp.Year(utc: boolean?):integer** — Get year
370
664
  - **timestamp.Month(utc: boolean?):integer** — Get month
371
665
  - **timestamp.MonthIndex(utc: boolean?):integer** — Month index
@@ -381,75 +675,54 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
381
675
  - **timestamp.MinutesSince(value: timestamp):float** — Difference from another timestamp in minutes
382
676
  - **timestamp.SecondsSince(value: timestamp):float** — Difference from another timestamp in seconds
383
677
 
384
- ## Reference
385
-
386
- Install the package:
387
-
388
- ```sh
389
- npm install affinirum
390
- ```
391
-
392
- Create an `Affinirum` instance with a script and optional compilation configuration, then call `evaluate`
393
- with the script's input variables:
394
-
395
- ```ts
396
- import { Affinirum } from "affinirum";
397
-
398
- const expression = new Affinirum("a + b");
399
- const result = expression.evaluate({ a: 10n, b: 20n }); // 30n
400
- ```
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.
403
- Use the optional constructor configuration to specify the expected result `type`, enable `strict` handling of undeclared variables,
404
- or declare input `variables` and their types. An instance exposes the original `script`, its inferred result `type`,
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:
678
+ ## Detailed type rules
409
679
 
410
- ```ts
411
- const value = Affinirum.parse('["answer":42,"enabled":true]');
412
- const notation = Affinirum.format(value);
680
+ Affinirum uses intentionally permissive type checking. Type information helps reject clearly incompatible expressions,
681
+ select function overloads, and report compilation errors. It does not prove that every accepted expression is safe
682
+ for every possible runtime value.
683
+
684
+ - `??` is the unknown or variant type and is compatible with every type, including `void`. A `??` function parameter
685
+ may receive `null`, JavaScript `undefined`, or be omitted.
686
+ - An optional type such as `integer?` is the union `void | integer`. Optional function parameters may receive `null`,
687
+ JavaScript `undefined`, or be omitted.
688
+ - A call with known argument types must match one complete function overload. Parameter matches from separate
689
+ overloads are not combined to accept a call.
690
+ - Object types are open structural constraints: required properties and their values are checked, while additional
691
+ properties are allowed.
692
+ - Tuple types are prefix constraints: declared item types are checked in order, optional trailing items may be
693
+ omitted, and additional items are allowed.
694
+ - Function compatibility is deliberately flexible. Accepted argument-count ranges only need to overlap;
695
+ one function's complete range does not need to contain the other's.
696
+ - A callback may declare fewer parameters than the caller provides. Additional arguments are ignored at runtime,
697
+ following JavaScript function-call behavior.
698
+ - Function parameter types are checked contravariantly where both signatures declare a parameter: the receiving
699
+ function must accept the expected parameter type. Return types are checked covariantly: the returned type must fit
700
+ the expected result type. `??` remains compatible with any parameter type.
701
+ - Fixed and variadic signatures are not interchangeable. Variadic arguments use a distinct packed-array calling
702
+ convention and are only compatible with corresponding variadic signatures.
413
703
 
414
- Affinirum.format(undefined); // "null"
415
- Affinirum.format(null); // "null"
416
- Affinirum.format([1n, undefined]); // "[1,null]"
417
- Affinirum.format({ missing: undefined }); // '["missing":null]'
704
+ For example, a callback declared as `~(value: float):boolean` is compatible with an expected callback type such as
705
+ `~(??, integer?, array?):boolean`: their argument-count ranges overlap, `??` accepts the concrete value type,
706
+ and the callback may ignore the additional arguments. Affinirum does not enforce strict function subtyping.
707
+
708
+ For a variadic host function, set the third argument of `Type.functionType` to `true` and declare the last parameter
709
+ as an array type. The JavaScript implementation receives the trailing arguments as one packed array, rather than
710
+ separate JavaScript rest arguments:
711
+
712
+ ```ts
713
+ import { Affinirum, Type } from "affinirum";
714
+
715
+ const expression = new Affinirum("sum(1, 2, 3)", {
716
+ strict: true,
717
+ variables: {
718
+ sum: Type.functionType(Type.Integer, [Type.arrayType([Type.Integer])], true),
719
+ },
720
+ });
721
+
722
+ const result = expression.evaluate({
723
+ sum: (values: bigint[]) => values.reduce((total, value) => total + value, 0n),
724
+ }); // 6n
418
725
  ```
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
-
424
- JavaScript `number` values map to **float**, while **integer** values map to `bigint`. Timestamps use `Date`, buffers use
425
- `ArrayBuffer`, and a **void** result is returned as `undefined`. Arrays, objects, and functions use their corresponding
426
- JavaScript values. Injected non-function values are checked against the types inferred or declared during compilation.
427
- Injected functions are checked to be callable; their JavaScript parameter behavior and return values are trusted according
428
- to their declared Affinirum types.
429
-
430
- Use **val** for a local value that cannot be reassigned and **var** for a reassignable local variable. Statements are
431
- separated with semicolons.
432
-
433
- Sample code:
434
-
435
- ```ts
436
- const expr = new Affinirum("x * (y + abc / 5) > 10");
437
- const value1 = expr.evaluate({ x: 10, y: 20, abc: 10 }); // true
438
- const value2 = expr.evaluate({ x: 1, y: 4, abc: 5 }); // false
439
-
440
- const arrExpr = new Affinirum("Integer.Sum([1, 2, 3, a, b, c])");
441
- const valueSum = arrExpr.evaluate({ a: 10n, b: 20n, c: 30n }); // 66n
442
-
443
- const objExpr = new Affinirum('["prop1":a, "prop2":"abc"].prop1 + 10');
444
- const oValue = objExpr.evaluate({ a: 50n }); // 60n
445
-
446
- const iteratorExpr = new Affinirum(
447
- "Float.Sum(arr1.Derive(~(a:float):float{a*2}).Filter(~(a:float):boolean{a>3}))"
448
- );
449
- const iValue = iteratorExpr.evaluate({ arr1: [1, 2, 3] }); // 10
450
-
451
- const complexExpr = new Affinirum(
452
- "var a = myvar1 / 10; val b = myvar2 - 100; a / b + b * a + 600"
453
- );
454
- const value = complexExpr.evaluate({ myvar1: 40, myvar2: 104 }); // 617
455
- ```
726
+
727
+ Casts require compatible source and target types at compile time, and the evaluated value must satisfy the target
728
+ type at runtime. A cast checks the value; it does not perform a conversion.