affinirum 1.5.4 → 2.0.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 (243) hide show
  1. package/.cache/arrow-preview-vWvB5K/affinirum-arrow-functions.patch +155 -0
  2. package/.cache/function-syntax-tests.log +20 -0
  3. package/README.md +925 -355
  4. package/dst/Affinirum.d.ts +29 -19
  5. package/dst/Affinirum.js +399 -334
  6. package/dst/CallFrame.d.ts +12 -3
  7. package/dst/CallFrame.js +49 -10
  8. package/dst/Constant.d.ts +1 -3
  9. package/dst/Constant.js +3 -8
  10. package/dst/LexicalScope.d.ts +11 -9
  11. package/dst/LexicalScope.js +10 -6
  12. package/dst/ParserSpan.d.ts +11 -0
  13. package/dst/{ScriptSpan.js → ParserSpan.js} +8 -5
  14. package/dst/ParserState.d.ts +28 -49
  15. package/dst/ParserState.js +256 -489
  16. package/dst/Type.d.ts +34 -17
  17. package/dst/Type.js +211 -115
  18. package/dst/TypeParser.d.ts +9 -0
  19. package/dst/TypeParser.js +127 -0
  20. package/dst/Value.d.ts +1 -1
  21. package/dst/Value.js +21 -10
  22. package/dst/Variable.d.ts +16 -5
  23. package/dst/Variable.js +32 -7
  24. package/dst/atom/ArrayAtom.d.ts +10 -10
  25. package/dst/atom/ArrayAtom.js +62 -55
  26. package/dst/atom/Atom.d.ts +7 -0
  27. package/dst/atom/FunctionAtom.d.ts +13 -15
  28. package/dst/atom/FunctionAtom.js +53 -104
  29. package/dst/atom/FunctionSignature.d.ts +23 -0
  30. package/dst/atom/FunctionSignature.js +124 -0
  31. package/dst/atom/ObjectAtom.d.ts +11 -9
  32. package/dst/atom/ObjectAtom.js +73 -33
  33. package/dst/atom/PrimitiveAtom.d.ts +6 -7
  34. package/dst/atom/PrimitiveAtom.js +7 -10
  35. package/dst/cjs/Affinirum.d.ts +29 -19
  36. package/dst/cjs/Affinirum.js +398 -333
  37. package/dst/cjs/CallFrame.d.ts +12 -3
  38. package/dst/cjs/CallFrame.js +49 -10
  39. package/dst/cjs/Constant.d.ts +1 -3
  40. package/dst/cjs/Constant.js +3 -8
  41. package/dst/cjs/LexicalScope.d.ts +11 -9
  42. package/dst/cjs/LexicalScope.js +10 -6
  43. package/dst/cjs/ParserSpan.d.ts +11 -0
  44. package/dst/cjs/{ScriptSpan.js → ParserSpan.js} +10 -7
  45. package/dst/cjs/ParserState.d.ts +28 -49
  46. package/dst/cjs/ParserState.js +255 -488
  47. package/dst/cjs/Type.d.ts +34 -17
  48. package/dst/cjs/Type.js +211 -115
  49. package/dst/cjs/TypeParser.d.ts +9 -0
  50. package/dst/cjs/TypeParser.js +131 -0
  51. package/dst/cjs/Value.d.ts +1 -1
  52. package/dst/cjs/Value.js +21 -10
  53. package/dst/cjs/Variable.d.ts +16 -5
  54. package/dst/cjs/Variable.js +36 -9
  55. package/dst/cjs/atom/ArrayAtom.d.ts +10 -10
  56. package/dst/cjs/atom/ArrayAtom.js +62 -55
  57. package/dst/cjs/atom/Atom.d.ts +7 -0
  58. package/dst/cjs/atom/FunctionAtom.d.ts +13 -15
  59. package/dst/cjs/atom/FunctionAtom.js +54 -105
  60. package/dst/cjs/atom/FunctionSignature.d.ts +23 -0
  61. package/dst/cjs/atom/FunctionSignature.js +128 -0
  62. package/dst/cjs/atom/ObjectAtom.d.ts +11 -9
  63. package/dst/cjs/atom/ObjectAtom.js +73 -33
  64. package/dst/cjs/atom/PrimitiveAtom.d.ts +6 -7
  65. package/dst/cjs/atom/PrimitiveAtom.js +7 -10
  66. package/dst/cjs/dictionary/Constants.d.ts +2 -0
  67. package/dst/cjs/dictionary/Constants.js +27 -0
  68. package/dst/cjs/dictionary/Functions.d.ts +2 -0
  69. package/dst/cjs/{Functions.js → dictionary/Functions.js} +27 -25
  70. package/dst/cjs/native/Aggregable.js +10 -2
  71. package/dst/cjs/native/Array.d.ts +2 -3
  72. package/dst/cjs/native/Array.js +38 -39
  73. package/dst/cjs/native/Boolean.d.ts +1 -1
  74. package/dst/cjs/native/Boolean.js +13 -10
  75. package/dst/cjs/native/Buffer.d.ts +5 -5
  76. package/dst/cjs/native/Buffer.js +70 -46
  77. package/dst/cjs/native/Composite.d.ts +5 -0
  78. package/dst/cjs/native/Composite.js +35 -0
  79. package/dst/cjs/native/Enumerable.js +20 -8
  80. package/dst/cjs/native/Float.d.ts +3 -1
  81. package/dst/cjs/native/Float.js +51 -12
  82. package/dst/cjs/native/Integer.d.ts +4 -2
  83. package/dst/cjs/native/Integer.js +60 -25
  84. package/dst/cjs/native/Iterable.d.ts +0 -2
  85. package/dst/cjs/native/Iterable.js +9 -28
  86. package/dst/cjs/native/Number.d.ts +0 -2
  87. package/dst/cjs/native/Number.js +34 -48
  88. package/dst/cjs/native/Object.d.ts +1 -1
  89. package/dst/cjs/native/Object.js +5 -6
  90. package/dst/cjs/native/String.d.ts +7 -6
  91. package/dst/cjs/native/String.js +28 -27
  92. package/dst/cjs/native/Timestamp.d.ts +3 -3
  93. package/dst/cjs/native/Timestamp.js +34 -36
  94. package/dst/cjs/native/Unknown.d.ts +3 -3
  95. package/dst/cjs/native/Unknown.js +48 -17
  96. package/dst/cjs/native/notation/AN.d.ts +1 -1
  97. package/dst/cjs/native/notation/AN.js +37 -35
  98. package/dst/cjs/native/notation/IP.d.ts +1 -1
  99. package/dst/cjs/native/notation/IP.js +11 -12
  100. package/dst/cjs/native/notation/JSON.d.ts +1 -1
  101. package/dst/cjs/native/notation/JSON.js +7 -6
  102. package/dst/cjs/node/AccessNode.d.ts +24 -0
  103. package/dst/cjs/node/AccessNode.js +193 -0
  104. package/dst/cjs/node/ArrayNode.d.ts +7 -4
  105. package/dst/cjs/node/ArrayNode.js +26 -15
  106. package/dst/cjs/node/AssignableNode.d.ts +16 -0
  107. package/dst/cjs/node/AssignableNode.js +18 -0
  108. package/dst/cjs/node/AssignmentNode.d.ts +20 -0
  109. package/dst/cjs/node/AssignmentNode.js +66 -0
  110. package/dst/cjs/node/BlockNode.d.ts +5 -4
  111. package/dst/cjs/node/BlockNode.js +18 -11
  112. package/dst/cjs/node/CallNode.d.ts +7 -5
  113. package/dst/cjs/node/CallNode.js +40 -41
  114. package/dst/cjs/node/CastNode.d.ts +5 -6
  115. package/dst/cjs/node/CastNode.js +16 -17
  116. package/dst/cjs/node/ConstantNode.d.ts +4 -6
  117. package/dst/cjs/node/ConstantNode.js +9 -17
  118. package/dst/cjs/node/FinalNode.d.ts +19 -0
  119. package/dst/cjs/node/FinalNode.js +41 -0
  120. package/dst/cjs/node/FunctionNode.d.ts +17 -0
  121. package/dst/cjs/node/FunctionNode.js +51 -0
  122. package/dst/cjs/node/InvocationNode.d.ts +5 -0
  123. package/dst/cjs/node/InvocationNode.js +34 -0
  124. package/dst/cjs/node/JumpNode.d.ts +7 -9
  125. package/dst/cjs/node/JumpNode.js +12 -19
  126. package/dst/cjs/node/LoopNode.d.ts +7 -5
  127. package/dst/cjs/node/LoopNode.js +33 -22
  128. package/dst/cjs/node/MatchNode.d.ts +17 -0
  129. package/dst/cjs/node/MatchNode.js +65 -0
  130. package/dst/cjs/node/Node.d.ts +14 -0
  131. package/dst/cjs/{Node.js → node/Node.js} +17 -11
  132. package/dst/cjs/node/ObjectNode.d.ts +7 -4
  133. package/dst/cjs/node/ObjectNode.js +42 -11
  134. package/dst/cjs/node/{SwitchNode.d.ts → TernaryNode.d.ts} +6 -6
  135. package/dst/cjs/node/TernaryNode.js +45 -0
  136. package/dst/cjs/node/VariableNode.d.ts +10 -6
  137. package/dst/cjs/node/VariableNode.js +50 -16
  138. package/dst/dictionary/Constants.d.ts +2 -0
  139. package/dst/dictionary/Constants.js +24 -0
  140. package/dst/dictionary/Functions.d.ts +2 -0
  141. package/dst/{Functions.js → dictionary/Functions.js} +26 -24
  142. package/dst/native/Aggregable.js +11 -3
  143. package/dst/native/Array.d.ts +2 -3
  144. package/dst/native/Array.js +37 -38
  145. package/dst/native/Boolean.d.ts +1 -1
  146. package/dst/native/Boolean.js +12 -9
  147. package/dst/native/Buffer.d.ts +5 -5
  148. package/dst/native/Buffer.js +66 -42
  149. package/dst/native/Composite.d.ts +5 -0
  150. package/dst/native/Composite.js +32 -0
  151. package/dst/native/Enumerable.js +20 -8
  152. package/dst/native/Float.d.ts +3 -1
  153. package/dst/native/Float.js +48 -11
  154. package/dst/native/Integer.d.ts +4 -2
  155. package/dst/native/Integer.js +56 -23
  156. package/dst/native/Iterable.d.ts +0 -2
  157. package/dst/native/Iterable.js +8 -27
  158. package/dst/native/Number.d.ts +0 -2
  159. package/dst/native/Number.js +34 -46
  160. package/dst/native/Object.d.ts +1 -1
  161. package/dst/native/Object.js +4 -5
  162. package/dst/native/String.d.ts +7 -6
  163. package/dst/native/String.js +24 -24
  164. package/dst/native/Timestamp.d.ts +3 -3
  165. package/dst/native/Timestamp.js +31 -33
  166. package/dst/native/Unknown.d.ts +3 -3
  167. package/dst/native/Unknown.js +49 -18
  168. package/dst/native/notation/AN.d.ts +1 -1
  169. package/dst/native/notation/AN.js +37 -35
  170. package/dst/native/notation/IP.d.ts +1 -1
  171. package/dst/native/notation/IP.js +10 -11
  172. package/dst/native/notation/JSON.d.ts +1 -1
  173. package/dst/native/notation/JSON.js +6 -5
  174. package/dst/node/AccessNode.d.ts +24 -0
  175. package/dst/node/AccessNode.js +189 -0
  176. package/dst/node/ArrayNode.d.ts +7 -4
  177. package/dst/node/ArrayNode.js +26 -15
  178. package/dst/node/AssignableNode.d.ts +16 -0
  179. package/dst/node/AssignableNode.js +14 -0
  180. package/dst/node/AssignmentNode.d.ts +20 -0
  181. package/dst/node/AssignmentNode.js +62 -0
  182. package/dst/node/BlockNode.d.ts +5 -4
  183. package/dst/node/BlockNode.js +18 -11
  184. package/dst/node/CallNode.d.ts +7 -5
  185. package/dst/node/CallNode.js +40 -41
  186. package/dst/node/CastNode.d.ts +5 -6
  187. package/dst/node/CastNode.js +16 -17
  188. package/dst/node/ConstantNode.d.ts +4 -6
  189. package/dst/node/ConstantNode.js +9 -17
  190. package/dst/node/FinalNode.d.ts +19 -0
  191. package/dst/node/FinalNode.js +37 -0
  192. package/dst/node/FunctionNode.d.ts +17 -0
  193. package/dst/node/FunctionNode.js +47 -0
  194. package/dst/node/InvocationNode.d.ts +5 -0
  195. package/dst/node/InvocationNode.js +30 -0
  196. package/dst/node/JumpNode.d.ts +7 -9
  197. package/dst/node/JumpNode.js +12 -19
  198. package/dst/node/LoopNode.d.ts +7 -5
  199. package/dst/node/LoopNode.js +33 -22
  200. package/dst/node/MatchNode.d.ts +17 -0
  201. package/dst/node/MatchNode.js +61 -0
  202. package/dst/node/Node.d.ts +14 -0
  203. package/dst/node/Node.js +28 -0
  204. package/dst/node/ObjectNode.d.ts +7 -4
  205. package/dst/node/ObjectNode.js +42 -11
  206. package/dst/node/{SwitchNode.d.ts → TernaryNode.d.ts} +6 -6
  207. package/dst/node/TernaryNode.js +41 -0
  208. package/dst/node/VariableNode.d.ts +10 -6
  209. package/dst/node/VariableNode.js +50 -16
  210. package/package.json +4 -4
  211. package/dst/Atom.d.ts +0 -7
  212. package/dst/Constants.d.ts +0 -2
  213. package/dst/Constants.js +0 -24
  214. package/dst/Functions.d.ts +0 -2
  215. package/dst/Jump.d.ts +0 -1
  216. package/dst/Jump.js +0 -1
  217. package/dst/JumpException.d.ts +0 -9
  218. package/dst/JumpException.js +0 -14
  219. package/dst/Keywords.d.ts +0 -1
  220. package/dst/Keywords.js +0 -17
  221. package/dst/Node.d.ts +0 -14
  222. package/dst/Node.js +0 -22
  223. package/dst/ScriptSpan.d.ts +0 -10
  224. package/dst/cjs/Atom.d.ts +0 -7
  225. package/dst/cjs/Constants.d.ts +0 -2
  226. package/dst/cjs/Constants.js +0 -27
  227. package/dst/cjs/Functions.d.ts +0 -2
  228. package/dst/cjs/Jump.d.ts +0 -1
  229. package/dst/cjs/Jump.js +0 -2
  230. package/dst/cjs/JumpException.d.ts +0 -9
  231. package/dst/cjs/JumpException.js +0 -18
  232. package/dst/cjs/Keywords.d.ts +0 -1
  233. package/dst/cjs/Keywords.js +0 -20
  234. package/dst/cjs/Node.d.ts +0 -14
  235. package/dst/cjs/ScriptSpan.d.ts +0 -10
  236. package/dst/cjs/node/SwitchNode.js +0 -49
  237. package/dst/cjs/node/VariadicNode.d.ts +0 -4
  238. package/dst/cjs/node/VariadicNode.js +0 -10
  239. package/dst/node/SwitchNode.js +0 -45
  240. package/dst/node/VariadicNode.d.ts +0 -4
  241. package/dst/node/VariadicNode.js +0 -6
  242. /package/dst/{Atom.js → atom/Atom.js} +0 -0
  243. /package/dst/cjs/{Atom.js → atom/Atom.js} +0 -0
package/README.md CHANGED
@@ -1,207 +1,734 @@
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
-
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
-
176
- - General `Format` conversions and `JSON.Format` return an empty string for **void**.
177
- - `AN.Format` and `Affinirum.format` serialize **void** as the literal `null`, including array elements and object properties.
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
2
+
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
+ Affinirum 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 reassignable `var` bindings and indexed array and object updates.
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 values](#variables-and-values)
20
+ - [Conditionals](#conditionals)
21
+ - [Matches](#matches)
22
+ - [Loops](#loops)
23
+ - [Functions and returns](#functions-and-returns)
24
+ - [Arrays and objects](#arrays-and-objects)
25
+ - [Method calls and chaining](#method-calls-and-chaining)
26
+ - [Types](#types)
27
+ - [Array, object, and variadic types](#array-object-and-variadic-types)
28
+ - [Operators and precedence](#operators-and-precedence)
29
+ - [Embedding API](#embedding-api)
30
+ - [Typed inputs and strict mode](#typed-inputs-and-strict-mode)
31
+ - [Host functions](#host-functions)
32
+ - [JavaScript value mapping](#javascript-value-mapping)
33
+ - [Errors](#errors)
34
+ - [Affinirum Notation](#affinirum-notation)
35
+ - [Standard library](#standard-library)
36
+ - [Global functions](#global-functions)
37
+ - [Method functions](#method-functions)
38
+ - [Detailed type rules](#detailed-type-rules)
39
+
40
+ ## Install and quick start
41
+
42
+ ```sh
43
+ npm install affinirum
44
+ ```
45
+
46
+ Create an instance to compile a script, then call `evaluate` with its inputs. Reuse the instance to avoid parsing again:
47
+
48
+ ```js
49
+ import { Affinirum } from "affinirum";
50
+
51
+ const expression = new Affinirum("a + b");
52
+ console.log(expression.evaluate({ a: 10n, b: 20n })); // 30n
53
+ console.log(expression.evaluate({ a: 40n, b: 2n })); // 42n
54
+ ```
55
+
56
+ The `n` suffix belongs to JavaScript's `bigint` syntax. Inside an Affinirum script, write integers as `10`, not `10n`.
57
+ JavaScript `number` inputs represent Affinirum floats; `bigint` inputs represent integers.
58
+
59
+ CommonJS applications can use `require`:
60
+
61
+ ```js
62
+ const { Affinirum } = require("affinirum");
63
+
64
+ console.log(new Affinirum("1 + 2").evaluate()); // 3n
65
+ ```
66
+
67
+ The examples under **Language basics** contain Affinirum source. Pass them as strings to `new Affinirum(script)`.
68
+ Scripts without external inputs can be evaluated with `evaluate()`.
69
+
70
+ ## Language basics
71
+
72
+ ### Statements and literals
73
+
74
+ Separate statements with semicolons; a newline alone does not separate them. A script or `{ ... }` block returns the
75
+ value of its last expression. An empty block has type `null` and evaluates to JavaScript `undefined`.
76
+ Use parentheses to group expressions. Commas separate arguments and entries in arrays and objects.
77
+
78
+ ```text
79
+ val base = 10;
80
+ val extra = { val factor = 2; factor * 3 };
81
+ base + extra // 16
82
+ ```
83
+
84
+ | Kind | Literal examples |
85
+ | --- | --- |
86
+ | Integer | `42`, `-7` |
87
+ | Float | `42.0`, `0.5`, `1e3`, `0.1281e+2` |
88
+ | Boolean | `true`, `false` |
89
+ | String | `'hello'`, `"hello"` |
90
+ | Timestamp | `@2025-05-11T19:09:21.320Z` |
91
+ | Buffer | `` `10ab0901` `` (hexadecimal bytes) |
92
+ | Null | `null` |
93
+ | Array | `[1, 2, 3]`, `[]` |
94
+ | Object | `["name": "Ada", "score": 10]`, `[:]` |
95
+
96
+ Integers are signed 64-bit values; overflow wraps to that range. Floats use IEEE 754 binary64.
97
+ Integer division truncates toward zero: `7 / 2` is `3`, while `7.0 / 2` is `3.5`.
98
+ Arithmetic involving a float produces a float.
99
+
100
+ Whitespace outside literals and comments is ignored. Names are case-sensitive. Line comments start with `//`;
101
+ block comments are enclosed in `/// ... ///` and do not nest. Strings decode `\n`, `\r`, and `\t`;
102
+ use `\\` for a backslash and `\'` or `\"` for quotes. Other escapes insert the following character without the
103
+ backslash, so Unicode and hexadecimal escape sequences are not decoded.
104
+
105
+ Buffer literals also allow whitespace and both comment forms between hexadecimal digits. Inside a buffer, a line
106
+ comment ends at a newline or the closing backtick. A final unpaired hexadecimal digit becomes a byte with a leading
107
+ zero: `` `abc` `` contains the bytes `ab 0c`.
108
+
109
+ ### Variables and values
110
+
111
+ Use `var` for a reassignable binding and `val` for a fixed binding. Types can be inferred or declared after a colon:
112
+
113
+ ```text
114
+ val step = 2;
115
+ var count: integer = 1;
116
+ count += step;
117
+ count // 3
118
+ ```
119
+
120
+ Variables follow these rules.
121
+
122
+ - An explicit type annotation fixes the variable's type, including an explicit `any`.
123
+ - A non-optional type requires an initial value in the declaration. A variable declared with an optional type or `any`
124
+ can omit its initializer and starts at `null`.
125
+ - A variable without an annotation takes its type from its initializer. Later assignments must be compatible with that type.
126
+ - A variable with neither an annotation nor an initializer, or a parameter without an annotation, has type `any`.
127
+ Later reads and assignments leave that binding type unchanged.
128
+
129
+ A read or assignment expression can have a more specific type than the binding. That type applies only to the expression.
130
+
131
+ Bindings declared inside a block are local to that block. Names must start with an ASCII letter, `$`, or `_`,
132
+ followed by any combination of those characters and digits, such as `x`, `_a1$`, or `abc25`.
133
+ Language keywords, including `var`, `val`, `func`, `function`, `if`, `else`, `match`, `while`, `do`, `until`, `next`, and `exit`, are reserved,
134
+ as are type names and their aliases.
135
+
136
+ Built-in methods that transform arrays or objects produce replacement values while preserving their inputs.
137
+ Concatenation follows the same rule.
138
+ Reassigning a `var` preserves the value held by other bindings:
139
+
140
+ ```text
141
+ var items: [...integer] = [1];
142
+ val original = items;
143
+ items += [2];
144
+ [items, original] // [[1,2],[1]]
145
+ ```
146
+
147
+ Array items and object properties support `=` and compound assignment. Indexed writes update the existing array or object,
148
+ so other bindings holding that value observe the change. Direct writes through `val` or external input bindings
149
+ are rejected. Array writes require an existing index; object writes can create own properties. Negative array indexes
150
+ count from the end. Compound assignment resolves the container and key and reads the current value once, before
151
+ evaluating the right-hand side.
152
+
153
+ Optional targets such as `entry?.name` and `items?[index]` also support `=` and compound assignment. When the receiver
154
+ is `null`, the assignment returns `null` and skips the key or index and the right-hand side at runtime. A successful
155
+ assignment returns the assigned value.
156
+
157
+ Array and object literals retain their compiled types as constraints on indexed writes. These constraints apply through
158
+ wider bindings and casts that reference the same array or object. After `var items: [] = [1]`, assigning `'two'` to
159
+ `items[0]` raises a runtime type error because the literal has type `[integer]`.
160
+
161
+ ### Conditionals
162
+
163
+ `if condition { ... } else { ... }` is a conditional expression: it evaluates only the selected branch and returns
164
+ that branch's value. The condition must be boolean. If `else` is omitted and the condition is false, the result is `null`.
165
+ An unbraced first branch requires `then`, as in `if score >= 60 then "pass" else "fail"`.
166
+ Before `{`, `then` is optional and is usually omitted. An `else` branch can use either a block or a single expression.
167
+
168
+ ```text
169
+ val score = 82;
170
+ val category = if score >= 60 { "pass" } else { "fail" };
171
+ category // "pass"
172
+ ```
173
+
174
+ ### Matches
175
+
176
+ Use `match value { key: result, else: fallback }` to choose a result by value. Each comma-separated
177
+ `key: result` pair is called an arm. Both the key and the result can be expressions. A trailing comma is allowed.
178
+
179
+ Parentheses around the subject are optional, so `match status { ... }` and `match(status) { ... }` are equivalent.
180
+ The subject can be a full expression, as in `match status + 1 { ... }`.
181
+
182
+ `match` evaluates `value` once, then evaluates keys from left to right, comparing each with `==`. At the first
183
+ equal key, it evaluates that arm's result and skips the remaining arms. Array and object keys use the same
184
+ structural equality as `==`.
185
+ If every key misses, the optional final `else:` arm supplies the result.
186
+
187
+ ```text
188
+ val status = 404;
189
+ val label = match status {
190
+ 200: "OK",
191
+ 404: "Not found",
192
+ else: "Unknown"
193
+ };
194
+ label // "Not found"
195
+ ```
196
+
197
+ The result type is the union of the reachable arm result types, including the fallback. If no key matches
198
+ and `else:` is omitted, the result is `null`. In the example below, the two integer results and the
199
+ implicit `null` give the match expression type `integer?`.
200
+
201
+ ```text
202
+ val retryDelay = func(status:integer):integer? {
203
+ match status { 429: 60, 503: 10 }
204
+ };
205
+ [retryDelay(503), retryDelay(404)] // [10, null]
206
+ ```
207
+
208
+ `match value {}` evaluates `value` and returns `null`. Use `"else"` as a key to match the literal string.
209
+
210
+ ### Loops
211
+
212
+ `while condition { ... }` repeats while its boolean condition is true. An unbraced body requires `do`, as in
213
+ `while i < 10 do i += 1`. Before `{`, `do` is optional and is usually omitted.
214
+ Use `next` to skip the rest of the current iteration, or `exit` to leave the innermost loop.
215
+
216
+ ```text
217
+ var i = 0;
218
+ var total = 0;
219
+ while i < 10 {
220
+ i += 1;
221
+ if i == 3 { next };
222
+ if i == 6 { exit };
223
+ total += i
224
+ };
225
+ total // 12
226
+ ```
227
+
228
+ `do { ... } until condition` runs the body before testing a boolean stop condition. It repeats until the condition
229
+ is true. An unbraced body is also allowed, as in `do i += 1 until i == 3`.
230
+
231
+ ```text
232
+ var i = 0;
233
+ do {
234
+ i += 1;
235
+ i * 10
236
+ } until i == 3 // 30
237
+ ```
238
+
239
+ A `while` loop can also end with `until`, as in `while i < 10 { i += 1 } until i == 3`.
240
+ The `while` condition runs before each iteration; `until` runs afterward. A false `while` condition skips both the body
241
+ and `until`. `next` still checks `until` before starting another iteration, while `exit` skips it.
242
+ Without either condition, `do { ... }` repeats until an explicit jump stops it.
243
+
244
+ Declare variables needed by `until` outside the body block; body-local bindings are not visible in the condition.
245
+ Use braces around a body containing a nested loop so a trailing `until` belongs to the intended loop.
246
+
247
+ A loop returns its last completed iteration's value, or `null` if no iteration completes. An iteration interrupted
248
+ by `next` or `exit` does not replace that result. The inferred result type includes `null`, including for `do` loops.
249
+ Neither keyword can jump from a called function into its caller's loop.
250
+
251
+ ### Functions and returns
252
+
253
+ Define a function with `func(name: type, ...): return-type { ... }`. The keyword `function` is a synonym for `func`.
254
+ Braces around the body are required.
255
+ Omit the colon and return type to use `any`, as in `func(value) { value }`.
256
+ Braces containing a parenthesized expression, such as `{(value)}`, are ordinary code blocks.
257
+ The last expression supplies the function's result. Use `-> value` to return early from the current function,
258
+ or `=> value` to finish the entire script.
259
+
260
+ ```text
261
+ val absolute = func(value: integer): integer {
262
+ if value < 0 { -> -value };
263
+ value
264
+ };
265
+ absolute(-5) // 5
266
+ ```
267
+
268
+ A return annotation can be a union, as in `func(value: integer): integer | string { value }`.
269
+
270
+ Functions are values and can be passed as callbacks. A final variadic parameter collects the remaining arguments into
271
+ an array. Use `...integer` for integer arguments and `...any` for arguments of any type.
272
+ In a function literal, `values: ...` is shorthand for `values: ...any`; function types require the explicit `...any`.
273
+
274
+ ```text
275
+ val sum = func(values: ...integer): integer {
276
+ values.Reduce(func(total: integer, item: integer): integer { total + item}, 0)
277
+ };
278
+ sum(1, 2, 3) // 6
279
+ ```
280
+
281
+ Built-in variadic functions accept individual arguments of their declared type. For example, use
282
+ `Integer.Sum(1, 2, 3)`; `Integer.Sum([1, 2, 3])` is invalid. Use `Reduce` to aggregate an existing array, as above.
283
+
284
+ Use the global return operator `=>value` to finish the entire script evaluation, including from inside a function or callback:
285
+
286
+ ```text
287
+ val stop = func(): integer { =>42 };
288
+ stop();
289
+ 0 // The script returns 42 before reaching this expression.
290
+ ```
291
+
292
+ ### Arrays and objects
293
+
294
+ Arrays hold ordered values of any type and use zero-based indexes. Access an item with brackets or a dot followed by
295
+ an integer. Use `.?` to check whether an index exists. Write an empty array as `[]`.
296
+
297
+ ```text
298
+ val items = [10, 20, 30];
299
+ [items[0], items.1, items.?2, items.?3] // [10,20,true,false]
300
+ ```
301
+
302
+ Prefer brackets for consecutive numeric indexes: `matrix.0.1` reads `0.1` as one decimal token.
303
+
304
+ Use `+` to concatenate arrays. Wrap an individual item in an array when adding it:
305
+
306
+ ```text
307
+ [1, 2] + [3, 4]; // [1,2,3,4]
308
+ [0] + [1, 2]; // [0,1,2]
309
+ [1] + [[2, 3]] // [1,[2,3]]
310
+ ```
311
+
312
+ Objects hold named values. Define them with string keys and colons inside brackets. Write an empty object as `[:]`.
313
+ Object literals reject duplicate keys that are known at compile time.
314
+ Access properties with `entry.key`, `entry."key"`, or `entry["key"]`. Use `entry.?key` to check for a literal key,
315
+ or `entry.Has(keyVariable)` for a computed key. Quote keys that are reserved words, as in `entry."until"`.
316
+
317
+ ```text
318
+ val original = ["name": "Ada", "score": 10];
319
+ val updated = Object.Merge(original, ["score": 20, "active": true]);
320
+ [original.score, updated.score, updated.active] // [10,20,true]
321
+ ```
322
+
323
+ `Object.Merge` creates a new object; later arguments take precedence for duplicate keys. Array concatenation and
324
+ object merging are shallow: nested values are shared by reference, with their contents preserved at the script level.
325
+
326
+ Missing indexes and properties read as `null`. A typed indexed read includes `null` in its result type, even for a
327
+ declared tuple item or record property. Use optional access for subsequent steps, as in `matrix[0]?[1]`.
328
+
329
+ Use `?.` for optional dot access, as in `entry?.name` or `items?.0`, and `?[...]` for optional access with a
330
+ computed key or index. Both return `null` when the receiver is `null` or the entry is missing. For a null
331
+ receiver, `?[...]` skips evaluating the key or index at runtime.
332
+
333
+ Use `?.?` for optional presence checks, as in `entry?.?name` or `items?.?0`. The result is `null` for a null
334
+ receiver, `true` for an existing key or an in-range index, and `false` otherwise.
335
+
336
+ ```text
337
+ val entry: [:]? = null;
338
+ [entry?.name, entry?["name"], entry?.?name, [:]?.?name] // [null,null,null,false]
339
+ ```
340
+
341
+ ### Method calls and chaining
342
+
343
+ Built-in methods use `value.Method(arguments)`. Parentheses can be omitted when no explicit arguments are needed:
344
+ `items.Length` and `items.Length()` are equivalent. Method results can be chained:
345
+
346
+ ```text
347
+ " hello ".Trim.UpperCase // "HELLO"
348
+ ```
349
+
350
+ Callbacks can transform arrays in successive steps:
351
+
352
+ ```text
353
+ val values = [1, 2, 3];
354
+ values.Derive(func(item: integer): integer { item * 2 })
355
+ .Filter(func(item: integer): boolean { item > 3 }) // [4,6]
356
+ ```
357
+
358
+ After a dot, a built-in method name takes precedence over an object property with the same name.
359
+ Use brackets or a quoted key to read such a property, for example `entry["Length"]` or `entry."Length"`.
360
+
361
+ Use `receiver?.Method(arguments)` for an optional built-in method call. If the receiver is `null`, the call
362
+ returns `null` and skips its arguments during evaluation. A call without explicit arguments can use `receiver?.Method`.
363
+ Each `?.` applies to one step, so use it at each step that can receive `null`, as in `text?.Trim?.UpperCase`.
364
+
365
+ ### Types
366
+
367
+ | Type | Meaning |
368
+ | --- | --- |
369
+ | `null` | The type whose only script value is `null` |
370
+ | `never` | A type with no values, used for expressions that cannot complete normally |
371
+ | `boolean` / `bool` | `true` or `false` |
372
+ | `timestamp` / `time` | Date and time |
373
+ | `float` / `f64` | 64-bit floating-point number |
374
+ | `integer` / `i64` | Signed 64-bit integer |
375
+ | `buffer` | Sequence of bytes |
376
+ | `string` | Text |
377
+ | `[]` | A sequence whose items can have any type |
378
+ | `[:]` | Named properties whose values can have any type |
379
+ | `{:}` | Function with an unspecified signature |
380
+ | `any` | A type that accepts any value |
381
+ | `{(integer): string}` | Function taking an integer and returning a string |
382
+ | `integer?` | An integer or `null` |
383
+ | `integer \| string` | Union of types |
384
+
385
+ Append `?` to a named, array, object, function, or parenthesized type to include `null`. For example, `[]?`, `[:]?`,
386
+ `{:}?`, and `(integer | string)?` are optional types. The suffix is invalid on `null` and `never`, including when
387
+ parenthesized. `{(): integer}?` is a nullable function, and `{(): integer?}` is a function with a nullable result.
388
+
389
+ Parentheses group types, as in `(integer | string)`. Write a function type as `{(parameter-types): return-type}`.
390
+ The return type is required. For example, `{():any}` describes a zero-argument function that may return any value.
391
+ The generic type `{:}` accepts functions of any signature.
392
+
393
+ The closing `}` marks the end of a function type. `{(integer): string | null}` describes a function that can
394
+ return `null`, while `{(integer): string} | null` describes a function or `null`. In `{(): [...string | null]}`,
395
+ the brackets enclose the union of array item types.
396
+
397
+ Combine function types with `&` to declare overloads, as in `{(integer):string}&{(string):integer}`.
398
+ A call must match one of the signatures. In type expressions, `?` binds more tightly than `&`, and `&` binds
399
+ more tightly than `|`. Group an overloaded type before `?` to make the whole function nullable, as in
400
+ `({(integer):string}&{(string):integer})?`. Overload operands must be function types.
401
+
402
+ Type checking is intentionally permissive. See [Detailed type rules](#detailed-type-rules) for structural types,
403
+ callback compatibility, and variadic signatures.
404
+
405
+ A cast, `(expression:type)`, checks an expected type without converting the value:
406
+
407
+ ```text
408
+ val parsed = JSON.Parse('{"answer":42}');
409
+ (parsed:[:]).answer // 42.0
410
+ ```
411
+
412
+ Standard JSON numbers are floats. Use conversion methods such as `.Integer()` or `.Float()` to convert numeric types.
413
+ An incompatible cast raises an error. A cast result can be accessed, indexed, or called. Casts can also be nested.
414
+
415
+ The parentheses are required and enclose the entire expression being checked: `(a + b:integer)` checks the sum.
416
+ Write `(value:integer | string)` to cast to a union, and `(value:boolean) | other` for Boolean OR after a cast.
417
+ Inside a call, a cast needs its own parentheses, as in `f((value:integer))`.
418
+
419
+ Casts reject operands of type `never`, which cannot produce a value. Write `->(value:integer)` to check a value before
420
+ returning it; `(->value:integer)` is invalid.
421
+
422
+ #### Array, object, and variadic types
423
+
424
+ Uniform types apply one allowed type to every item or property value. Tuple and record types describe individual
425
+ positions and named properties in ordinary arrays and objects.
426
+
427
+ | Type | Meaning |
428
+ | --- | --- |
429
+ | `[...float]` | Uniform array. Every item is a float. |
430
+ | `[float]` | Tuple with a float at index 0. Extra items may have any type. |
431
+ | `[float, string]` | Tuple with a float at index 0 and a string at index 1. Extra items may have any type. |
432
+ | `[float, string?]` | Tuple with a required float and an optional trailing string. |
433
+ | `[...:float]` | Uniform object. Every property value is a float. |
434
+ | `["a": float]` | Record with a float property named `a`. Extra properties may have any type. |
435
+ | `["a": float, "b": string]` | Record with a float property named `a` and a string property named `b`. Extra properties may have any type. |
436
+ | `["a": float?]` | Record with an optional float property named `a`. Extra properties may have any type. |
437
+
438
+ The ellipsis marks a uniform array or object type. For example, `[...integer | string]` is an array whose items may be
439
+ integers or strings. Add a colon after the ellipsis for objects, as in `[...:string]` for string-valued properties.
440
+ Both uniform types allow zero or more entries. As types, `[]` and `[...any]` are aliases for uniform `any` arrays;
441
+ `[:]` and `[...:any]` are aliases for uniform `any` objects. Formatted types use `[]` and `[:]`.
442
+
443
+ Tuples and records specify a minimum shape and allow additional entries. An entry whose type excludes `null` is required;
444
+ optional trailing tuple items and optional record properties may be absent. Since `any` includes `null`, an entry of
445
+ type `any` does not enforce presence. A uniform type does not guarantee any positions or keys, so it cannot implicitly
446
+ satisfy a tuple or record with required entries. A cast can check the actual value against the required shape.
447
+
448
+ Without an ellipsis, nonempty array literals infer tuples, and object literals with known keys infer records.
449
+ Uniform array or object literals require the ellipsis before the first entry, as in `[...1,2]` and `[..."a":1,"b":2]`.
450
+ Their item or value type is inferred from all entries. The marker does not spread or flatten an array or object value.
451
+
452
+ In expressions, `[]` and `[:]` create empty arrays and objects with generic types.
453
+ The literals `[...never]` and `[...:never]` have the same types and empty values as `([]:[...never])` and
454
+ `([:]:[...:never])`, respectively. An exact-empty literal may share its value across function calls and evaluations.
455
+ Writes through broader array or object aliases still enforce the literal's empty type.
456
+
457
+ Argument lists, fixed parameter lists, array or object entry lists, and tuple or record type lists allow a trailing comma.
458
+ A variadic parameter must be last, without a trailing comma. Uniform array and object types close immediately after
459
+ their item or value type; tuple or record prefixes with uniform tails are not supported.
460
+
461
+ A final variadic parameter collects zero or more arguments into an array. `{(...integer):null}` is the function
462
+ type, and `func(a: ...integer):null {}` is a function value of that type. Each collected argument must be an integer,
463
+ and `a` has type `[...integer]` inside the function.
464
+
465
+ ### Operators and precedence
466
+
467
+ Expression operators are listed from highest precedence to lowest. Parentheses override grouping.
468
+ The closing brace completes a match expression, so its result can be used directly as an operand, as in
469
+ `match code { 200: 1 } ?: 0`. See [Match operator](#matches).
470
+
471
+ | Precedence | Operators | Meaning |
472
+ | --- | --- | --- |
473
+ | Highest | `.`, `[]`, `.?`, `?.`, `?[]`, `?.?`, `()`, `(value:type)` | Access, presence checks, calls, and casts |
474
+ | | `**` | Exponentiation |
475
+ | | Unary `+`, `-` | Arithmetic sign |
476
+ | | `*`, `/`, `%` | Multiplication, division, remainder |
477
+ | | `+`, `-` | Addition or concatenation; subtraction |
478
+ | | `..` | Inclusive ascending integer range |
479
+ | | `>`, `<`, `>=`, `<=`, `==`, `!=` | Comparison and equality |
480
+ | | `!`, `not` | Boolean negation |
481
+ | | `&`, `and` | Boolean AND |
482
+ | | `\|`, `or` | Boolean OR |
483
+ | Lowest | `?:` | Null coalescing |
484
+
485
+ Binary operators other than `..` at the same precedence group left to right, including exponentiation:
486
+ `2 ** 3 ** 2` means `(2 ** 3) ** 2` and produces `64`. Exponentiation binds before arithmetic sign, so `-2 ** 2` is `-4`.
487
+ Boolean negation binds after comparisons: `!a == b` means `!(a == b)`.
488
+
489
+ `a..b` is equivalent to `Array.Range(a,b)` and produces an array of type `[...integer]`. Both bounds must be integers
490
+ and are included. Values are always ascending, even when the bounds are reversed. Arithmetic binds more tightly
491
+ than `..`, so `1..2+2` means `1..(2+2)`. Ranges cannot be chained: `1..2..3` is invalid.
492
+
493
+ ```text
494
+ 1..3; // [1,2,3]
495
+ 3..1; // [1,2,3]
496
+ 3..3; // [3]
497
+ 1..2+2; // [1,2,3,4]
498
+ (1..3).Length // 3
499
+ ```
500
+
501
+ A range is already an array, so `[1..3]` contains one nested array: `[[1,2,3]]`.
502
+
503
+ `+` adds numbers or concatenates strings, buffers, and arrays. `&` and `and` skip the right operand when the left
504
+ operand is `false`; `|` and `or` skip it when the left operand is `true`.
505
+
506
+ `value ?: fallback` evaluates `value` first and evaluates `fallback` only when `value` is `null`.
507
+ `value.Coalesce(fallback)` follows the same rule.
508
+
509
+ Constant folding can evaluate subexpressions during compilation, including within code that would be skipped at runtime.
510
+ For example, `false and (1 / 0 == 0)` fails during compilation even though the right operand would be skipped at runtime.
511
+
512
+ Assign with `=` or combine assignment with an operation: `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, and `|=`.
513
+ `&=` skips the right-hand side and the write when the current value is `false`; `|=` skips them when it is `true`.
514
+ The short-circuited expression returns the current Boolean value. Otherwise, the right-hand side is evaluated once
515
+ and the Boolean result is assigned.
516
+ Assigning to an external input variable with any of these operators causes a compilation error.
517
+ Assignments and returns consume the expression that follows them; separate them into statements for clarity.
518
+ Assignment can also appear inside another expression: `a + b = 3` means `a + (b = 3)`, and
519
+ `1..b = 3` means `1..(b = 3)`. Use parentheses to make such assignments explicit.
520
+
521
+ ## Embedding API
522
+
523
+ `new Affinirum(script, config?)` parses and compiles the script. `evaluate(inputs?, timeout?)` executes it with the current inputs.
524
+ An input variable is a name that resolves to neither a scope variable nor a built-in. The host supplies its value, and the
525
+ script can only read the binding.
526
+
527
+ Set `config.timeout` to a positive number of milliseconds to give each evaluation a default deadline. The default is `0`,
528
+ which disables the deadline. A positive `timeout` passed to `evaluate` overrides the configured value for that call.
529
+ Omitting the override or passing zero or a negative value uses the configured default. The evaluator checks the deadline
530
+ before each loop condition and when entering a script function.
531
+
532
+ - A type supplied in `config.variables` stays fixed in either mode.
533
+ - Strict mode requires a configured type for every referenced input.
534
+ - Non-strict mode allows implicit inputs. An implicit input starts at `any` and accumulates the union of the types expected
535
+ at its uses. This includes uses in skipped branches, skipped loop bodies, and functions that are never called.
536
+ An unconstrained use contributes no type information.
537
+
538
+ ### Typed inputs and strict mode
539
+
540
+ Use constructor configuration to declare input value types, require declarations, and constrain the result type:
541
+
542
+ ```js
543
+ import { Affinirum, Type } from "affinirum";
544
+
545
+ const expression = new Affinirum("price * quantity", {
546
+ strict: true,
547
+ type: Type.Float,
548
+ variables: {
549
+ price: Type.Float,
550
+ quantity: Type.Integer,
551
+ },
552
+ });
553
+
554
+ console.log(expression.evaluate({ price: 12.5, quantity: 3n })); // 37.5
555
+ ```
556
+
557
+ - `variables` declares input value types; structured types can be built with helpers such as `Type.arrayType(Type.Integer)`
558
+ and `Type.objectType([["name", Type.String]])`.
559
+ - A referenced input declared as `Type.Never` causes a compilation error.
560
+ - `strict: true` rejects undeclared input names during compilation. It does not change the language's type compatibility rules.
561
+ - `type` specifies the expected result type to be checked during compilation.
562
+
563
+ Every referenced input must be supplied as an own property of the object passed to `evaluate`, even if its value is `undefined`.
564
+ Before checking input values against their inferred or declared types, `evaluate()` wraps input `bigint` values to the signed
565
+ 64-bit range. Shared references are preserved within the copy.
566
+
567
+ | Instance member | Result |
568
+ | --- | --- |
569
+ | `script` | Original script text |
570
+ | `type` | Inferred result `Type`; use `.toString()` for its readable form |
571
+ | `variables()` | Record of referenced input names and their inferred or declared types |
572
+ | `toString()` | Compiled tree representation |
573
+ | `evaluate(inputs?, timeout?)` | Script result as a JavaScript value |
574
+
575
+ ### Host functions
576
+
577
+ Declare a function's type in `variables`, then supply its JavaScript implementation on evaluation.
578
+ `Type.functionType` takes an array of signatures. Each signature lists the return type and parameter types.
579
+ The optional third entry defaults to `false`. Set it to `true` for a variadic signature.
580
+
581
+ ```ts
582
+ import { Affinirum, Type } from "affinirum";
583
+
584
+ const expression = new Affinirum("discount(total)", {
585
+ strict: true,
586
+ type: Type.Float,
587
+ variables: {
588
+ total: Type.Float,
589
+ discount: Type.functionType([[Type.Float, [Type.Float]]]),
590
+ },
591
+ });
592
+
593
+ const result = expression.evaluate({
594
+ total: 100,
595
+ discount: (amount: number) => amount * 0.9,
596
+ }); // 90
597
+ ```
598
+
599
+ Affinirum checks that injected functions are callable and trusts their behavior and return values. Supply synchronous
600
+ functions that return values matching their declared Affinirum types. Every returned `bigint` must be in the signed 64-bit
601
+ range, including integers inside arrays and objects. Supply ordinary arrays with data elements and records created with
602
+ `Object.create(null)` and enumerable string data fields. The same requirements apply to arguments when JavaScript calls a
603
+ script function directly. `evaluate()` passes the final result through unchanged, with a top-level `null` returned as
604
+ `undefined`.
605
+
606
+ List multiple signatures in one `Type.functionType` call when the implementation supports overloads:
607
+
608
+ ```ts
609
+ const identityType = Type.functionType([
610
+ [Type.Integer, [Type.Integer]],
611
+ [Type.String, [Type.String]],
612
+ ]);
613
+ ```
614
+
615
+ The equivalent script type is `{(integer):integer}&{(string):string}`.
616
+
617
+ Pass `true` as the second argument to `Type.functionType` for a volatile function, whose calls are excluded from
618
+ constant folding.
619
+
620
+ ### JavaScript value mapping
621
+
622
+ | Affinirum type | JavaScript value |
623
+ | --- | --- |
624
+ | `null` | Returns `undefined` and accepts `null` or `undefined` as input |
625
+ | `boolean` | `boolean` |
626
+ | `float` | `number` |
627
+ | `integer` | `bigint` |
628
+ | `timestamp` | `Date` |
629
+ | `buffer` | `ArrayBuffer` |
630
+ | `string` | `string` |
631
+ | `[]` | Array of supported values |
632
+ | `[:]` | Object containing supported values |
633
+ | `{:}` | Synchronous JavaScript function |
634
+
635
+ For example, supply `quantity: 3n` for an integer input; `quantity: 3` supplies a float.
636
+
637
+ ### Errors
638
+
639
+ Syntax and compilation errors are thrown by the constructor. Missing inputs, incompatible input values, and other
640
+ evaluation failures are thrown by `evaluate`. Errors reported by the parser or type checker include a source position
641
+ and an excerpt. Catch errors around both construction and evaluation:
642
+
643
+ ```js
644
+ import { Affinirum, Type } from "affinirum";
645
+
646
+ try {
647
+ const expression = new Affinirum("quantity + 1", {
648
+ strict: true,
649
+ variables: { quantity: Type.Integer },
650
+ });
651
+ expression.evaluate({ quantity: "three" }); // Throws: an integer was expected.
652
+ } catch (error) {
653
+ console.error(error instanceof Error ? error.message : String(error));
654
+ }
655
+ ```
656
+
657
+ ### Affinirum Notation
658
+
659
+ Affinirum Notation (AN) represents data using the language's literals, including integers, timestamps, buffers,
660
+ arrays, and objects. `Affinirum.parse(value)` reads a single notation value without executing a script;
661
+ `Affinirum.format(value)` writes a notation string. Their script equivalents are `AN.Parse` and `AN.Format`.
662
+ Empty or `undefined` input returns `undefined`, and invalid input throws:
663
+
664
+ ```js
665
+ import { Affinirum } from "affinirum";
666
+
667
+ const value = Affinirum.parse('["answer":42,"enabled":true]');
668
+ const notation = Affinirum.format(value); // '["answer":42,"enabled":true]'
669
+
670
+ Affinirum.format(undefined); // "null"
671
+ Affinirum.format(null); // "null"
672
+ Affinirum.format([1n, undefined]); // "[1,null]"
673
+ Affinirum.format({ missing: undefined }); // '["missing":null]'
674
+ ```
675
+
676
+ Both `Affinirum.format(value, whitespace?)` and the script function `AN.Format(value, whitespace?)` accept optional
677
+ indentation text. They write JavaScript `null` and `undefined` as the AN literal `null` at every nesting level.
678
+ Parsing that literal produces JavaScript `undefined`, preserving array lengths and object properties containing `undefined`.
679
+
680
+ AN stores values without type annotations or uniformity markers, so formatting and parsing do not preserve uniform,
681
+ tuple, record, or exact-empty type constraints. `AN.Parse` declares a union of all supported types, with generic array
682
+ and object members, even for a constant string. Use a cast to validate a desired shape after parsing:
683
+
684
+ ```text
685
+ val notation = AN.Format([..."answer":42]);
686
+ (AN.Parse(notation):["answer":integer]).answer // 42
687
+ ```
688
+
689
+ ## Standard library
690
+
691
+ Global functions use namespaces such as `Integer.Sum(...)`. Method functions use `value.Method(...)`.
692
+ In the signatures below, `T?` means `T` or `null`, `...` marks variadic arguments, and `any` accepts any value.
693
+ Trailing parameters whose type includes `null` can be omitted. Parameter names are explanatory; arguments are positional.
694
+
695
+ ### Global functions
696
+
697
+ Native conversions use the following `null` handling:
698
+
699
+ - General `Format` conversions return an empty string for `null`.
700
+ - `JSON.Format` serializes JavaScript `null` and `undefined` as JSON `null`, including array elements and object properties.
701
+ - `AN.Format` and `Affinirum.format` serialize JavaScript `null` and `undefined` as the literal `null`, including array elements and object properties.
702
+ - `Encode` returns a zero-length buffer for `null`.
703
+ - `Decode` and `Parse` return `null` when their input value is `null`.
704
+
705
+ Empty strings and zero-length buffers remain ordinary values; they are not serialized null markers.
706
+ Invalid inputs other than `null` may raise an evaluation error, depending on the function.
707
+
708
+ #### Boolean
709
+
710
+ - **Boolean.Or(values: ...boolean):boolean** — Boolean disjunction; stop evaluating arguments at the first `true`
711
+ - **Boolean.And(values: ...boolean):boolean** — Boolean conjunction; stop evaluating arguments at the first `false`
187
712
  - **Boolean.Not(value: boolean):boolean** — Boolean negation
188
- - **Boolean.Decode(value: buffer?, offset: integer?):boolean?** — Decode a byte at the optional offset; missing or out-of-range input returns **void**
189
- - **Boolean.Parse(value: string?):boolean?** — Parse case-insensitive `true` or `false`; other values return **void**
713
+ - **Boolean.Decode(value: buffer?, offset: integer?):boolean?** — Decode a byte at the optional offset; missing or out-of-range input returns `null`
714
+ - **Boolean.Parse(value: string?):boolean?** — Parse case-insensitive `true` or `false`; other values return `null`
190
715
 
191
716
  #### Timestamp
717
+
192
718
  - **Timestamp.Now():timestamp** — Current date and time
193
719
  - **Timestamp.Epoch(value: float | integer, epoch: timestamp?):timestamp** — Create timestamp from milliseconds
194
720
  - **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
721
  - **Timestamp.Parse(value: string?):timestamp?** — Parse a string as a timestamp
196
722
 
197
723
  #### Float
724
+
198
725
  - **Float.NAN** — Not-a-number
199
726
  - **Float.PositiveInfinity** — Positive infinity
200
727
  - **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
728
+ - **Float.Epsilon** — Difference between `1` and the next larger representable float (`2.220446049250313e-16`)
729
+ - **Float.Sum(values: ...(float | integer)):float** — Numeric sum
730
+ - **Float.Min(values: ...(float | integer)):float** — Numeric minimum; requires at least one argument
731
+ - **Float.Max(values: ...(float | integer)):float** — Numeric maximum; requires at least one argument
205
732
  - **Float.Exponent(value: float | integer):float** — Natural exponential
206
733
  - **Float.Logarithm(value: float | integer):float** — Natural logarithm
207
734
  - **Float.Abs(value: float | integer):float** — Absolute value
@@ -214,158 +741,217 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
214
741
  - **Float.Parse(value: string?):float?** — Parse a string as a float
215
742
 
216
743
  #### 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
744
+
745
+ - **Integer.Sum(values: ...integer):integer** — Numeric sum
746
+ - **Integer.Min(values: ...integer):integer** — Numeric minimum; requires at least one argument
747
+ - **Integer.Max(values: ...integer):integer** — Numeric maximum; requires at least one argument
220
748
  - **Integer.Random(exclusiveTo: integer):integer** — Random integer up to value
221
749
  - **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
750
  - **Integer.Parse(value: string?):integer?** — Parse a string as an integer
223
751
 
224
752
  #### String
225
- - **String.Alphanum(value: string):string** — Keep only ASCII letters and digits
753
+
754
+ - **String.Alphanumeric(value: string):string** — Keep ASCII letters and digits, converting letters to lowercase. An empty input returns `""`.
226
755
  - **String.Random(length: integer):string** — Random alphanumeric string
227
756
  - **String.Decode(value: buffer?, encoding: string?, offset: integer?, length: integer?):string?** — Decode using `utf8` (default), `sbcs`, `ucs2`, or `ucs2le`
228
757
 
229
758
  #### Buffer
759
+
230
760
  - **Buffer.Random(length: integer):buffer** — Buffer of given length filled with random bytes
231
761
  - **Buffer.Parse(value: string?):buffer?** — Parse a hexadecimal string as a buffer
232
762
 
233
763
  #### Array
234
- - **Array.Join(values: ...array):array** — Join arrays of any depths into a single array
235
- - **Array.Range(a: integer, b: integer):array** — Integers from the lower endpoint (inclusive) to the higher endpoint (exclusive)
236
- - **Array.Unique(value: array):array** — Array of unique values
237
- - **Array.Intersection(a1: array, a2: array):array** — Common values from two arrays
238
- - **Array.Difference(a1: array, a2: array):array** — Symmetrical difference between arrays
239
764
 
240
- #### Object
241
- - **Object.Merge(values: ...(object | [object])):object** — Merge objects and arrays of objects
765
+ - **Array.Join(values: ...[]):[]** — Concatenate arrays in argument order into a new array, preserving nested arrays
766
+ - **Array.Range(a: integer, b: integer):[...integer]** — Ascending integers including both endpoints, regardless of argument order; equivalent to `a..b`
767
+ - **Array.Unique(value: []):[]** — Array of unique values
768
+ - **Array.Intersection(a1: [], a2: []):[]** — Common values from two arrays
769
+ - **Array.Difference(a1: [], a2: []):[]** — Symmetric difference between arrays
770
+
771
+ `Array.Join(a,b,c)` has the same shallow concatenation behavior as `a+b+c`. Inputs are preserved, and nested arrays
772
+ and objects are shared by reference. Use `array.Flatten(depth)` to flatten nested array elements.
773
+
774
+ ```text
775
+ Array.Join([1,2],[3],[4,5]); // [1,2,3,4,5]
776
+ Array.Join([[1,2]],[3]) // [[1,2],3]
777
+ ```
778
+
779
+ #### Object
780
+
781
+ - **Object.Merge(values: ...[:]):[:]** — Shallow merge into a new object; later arguments take precedence
242
782
 
243
783
  #### AN
244
- - **AN.Format(value: ??, whitespace: string?):string** — Format a value as AN notation; **void** values are written as `null`
784
+
785
+ - **AN.Format(value: any, whitespace: string?):string** — Format a value as AN notation, including `null` values in arrays and objects
786
+ - **AN.Parse(value: string?):(null | boolean | timestamp | float | integer | buffer | string | [] | [:])** — Parse an AN-formatted string; empty or `null` input returns `null`
245
787
 
246
788
  #### JSON
247
- - **JSON.Format(value: (void | boolean | timestamp | float | integer | string | array | object), whitespace: string?):string** — Format a value as JSON
248
- - **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
789
 
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
252
- - **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
- - **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**
790
+ - **JSON.Format(value: (null | boolean | timestamp | float | integer | string | [] | [:]), whitespace: string?):string** — Format a value as JSON
791
+ - **JSON.Parse(value: string?):(null | boolean | timestamp | float | integer | string | [] | [:])** — Parse a JSON-formatted string; standard JSON values are not revived as timestamps or integers
254
792
 
255
- ### Native Method Functions
793
+ `JSON.Format` uses JavaScript `JSON.stringify`, with integers converted to decimal strings and JavaScript `null` or
794
+ `undefined` values serialized as JSON `null` at every nesting level. Object keys and array positions are preserved.
795
+ The optional `whitespace` controls indentation.
796
+
797
+ ```text
798
+ JSON.Format(null); // "null"
799
+ JSON.Format(JSON.Parse("null")); // "null"
800
+ JSON.Format([null, 1]); // '[null,"1"]'
801
+ JSON.Format(["missing": null, "count": 1]) // '{"missing":null,"count":"1"}'
802
+ ```
803
+
804
+ #### IP
805
+
806
+ - **IP.Match(values: [...string], search: ...string):boolean** — Check whether any searched IPv4 or IPv6 address belongs to the supplied addresses or CIDR ranges
807
+ - **IP.Encode(value: string?):buffer** — Encode an IPv4, IPv6, or CIDR string as a network-byte-order buffer; malformed or `null` input returns a zero-length buffer
808
+ - **IP.Decode(value: buffer?):string?** — Decode a 4-, 5-, 16-, or 17-byte buffer as canonical IPv4, IPv6, or CIDR notation; malformed or `null` input returns `null`
809
+
810
+ ### Method functions
256
811
 
257
812
  #### General Functions
258
- - **??.Coalesce(otherwise: ??):??** — Null coalescence
259
- - **??.Equal(value: ??):boolean** — Equals to
260
- - **??.Unequal(value: ??):boolean** — Not equals to
261
- - **(boolean | buffer | function).Encode():buffer** — Encode value to buffer
262
- - **(void | timestamp | float | integer | string | array | object).Encode(encoding: string?):buffer** — Encode a value; timestamps support `i32` and `i32le` minutes or `i64` and `i64le` milliseconds, while defaults are `i64` for timestamps and integers, `f64` for floats, and `utf8` for strings
263
- - **(boolean | string | function).Format():string** — Format value to string
264
- - **(void | timestamp | float | integer | buffer | array | object).Format(formatting: string?):string** — Format a value; buffers use `hex` by default and also support `base64`
813
+
814
+ - **any.Coalesce(otherwise: any):any** — Return the receiver, or evaluate and return `otherwise` when the receiver is `null`
815
+ - **any.Equals(value: any):boolean** — Test whether the values are equal
816
+ - **any.NotEquals(value: any):boolean** — Test whether the values differ
817
+ - **(boolean | buffer | {:}).Encode():buffer** — Encode value to buffer
818
+ - **(null | timestamp | float | integer | string | [] | [:]).Encode(encoding: string?):buffer** — Encode a value; timestamps support `i32` and `i32le` minutes or `i64` and `i64le` milliseconds, while defaults are `i64` for timestamps and integers, `f64` for floats, and `utf8` for strings
819
+ - **(boolean | string | {:}).Format():string** — Format value to string
820
+ - **(null | timestamp | float | integer | buffer | [] | [:]).Format(formatting: string?):string** — Format a value; buffers use `hex` by default and also support `base64`
265
821
 
266
822
  #### Aggregable Functions
823
+
267
824
  - **float.Add(value: float):float** — Add a float
268
825
  - **float.Add(value: integer):float** — Add an integer
269
826
  - **integer.Add(value: float):float** — Add a float
270
827
  - **integer.Add(value: integer):integer** — Add an integer
271
828
  - **buffer.Add(value: buffer):buffer** — Concatenate buffers
272
829
  - **string.Add(value: string):string** — Concatenate strings
273
- - **array.Add(value: array):array** — Concatenate arrays
274
-
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
830
+ - **[].Add(value: []):[]** — Concatenate arrays
831
+
832
+ #### Array Functions
833
+
834
+ - **[].First(condition: {(any, integer, []):boolean}):any** — First item satisfying condition, or `null` if none does
835
+ - **[].Last(condition: {(any, integer, []):boolean}):any** — Last item satisfying condition, or `null` if none does
836
+ - **[].FirstIndex(condition: {(any, integer, []):boolean}):integer?** — First index satisfying condition, or `null` if none does
837
+ - **[].LastIndex(condition: {(any, integer, []):boolean}):integer?** — Last index satisfying condition, or `null` if none does
838
+ - **[].Every(condition: {(any, integer, []):boolean}):boolean** — All items satisfy condition
839
+ - **[].Any(condition: {(any, integer, []):boolean}):boolean** — Any item satisfies condition
840
+ - **[].Reverse():[]** — Reversed array
841
+ - **[].Flatten(depth: integer = 1):[]** — Flatten array
842
+ - **[].Derive(transformation: {(any, integer, []):any}):[]** — Derived array
843
+ - **[].Filter(condition: {(any, integer, []):boolean}):[]** — Filtered array
844
+ - **[].Reduce(reducer: {(any, any, integer, []):any}, initial: any = null):any** — Reduced value
845
+ - **[].Compose(generator: {([:], string, integer, []):any}):[:]** — Compose object from array
846
+
847
+ `Reduce` uses `initial` as the accumulator when it is non-null. If `initial` is omitted or `null`, it starts with the
848
+ first item and raises an error for an empty array.
849
+
850
+ `Compose` builds a new object. Each callback receives a writable snapshot of the properties produced by earlier callbacks.
851
+ After the callback, the snapshot's properties and the generated property are shallow-copied into a new object.
290
852
 
291
853
  #### Buffer Functions
292
- - **buffer.Byte(pos: integer):buffer?** — Byte at position, or **void** when unavailable
854
+
855
+ - **buffer.ByteAt(pos: integer):buffer?** — One-byte slice at position; an empty slice returns a zero-length buffer
293
856
 
294
857
  #### Enumerable Functions
858
+
295
859
  - **buffer.Slice(start: integer?, end: integer?):buffer** — Slice section
296
860
  - **string.Slice(start: integer?, end: integer?):string** — Slice section
297
- - **array.Slice(start: integer?, end: integer?):array** — Slice section
861
+ - **[].Slice(start: integer?, end: integer?):[]** — Slice section
298
862
  - **buffer.Splice(start: integer, remove: integer, inject: ...buffer):buffer** — Splice section
299
863
  - **string.Splice(start: integer, remove: integer, inject: ...string):string** — Splice section
300
- - **array.Splice(start: integer, remove: integer, inject: ...array):array** — Splice section
864
+ - **[].Splice(start: integer, remove: integer, inject: ...[]):[]** — Splice section
301
865
  - **buffer.Inject(start: integer, inject: ...buffer):buffer** — Inject section
302
866
  - **string.Inject(start: integer, inject: ...string):string** — Inject section
303
- - **array.Inject(start: integer, inject: ...array):array** — Inject section
867
+ - **[].Inject(start: integer, inject: ...[]):[]** — Inject section
868
+
869
+ `Slice` includes `start` and excludes `end`; omitted bounds mean zero and the length, respectively. Negative bounds
870
+ count from the end. `Splice` removes `remove` entries at `start` and inserts the variadic arguments there;
871
+ `Inject` inserts without removing. Both return new values.
304
872
 
305
873
  #### Iterable Functions
306
- - **(buffer | string | array | object).Length():integer** — Get length
874
+
875
+ - **(buffer | string | [] | [:] | null).Length():integer** — Get length, or zero for `null`
307
876
  - **buffer.Contains(search: buffer, startPos: integer?):boolean** — Check if buffer contains another buffer
308
877
  - **string.Contains(search: string, startPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Check if string contains another string
309
- - **array.Contains(search: ??, startPos: integer?):boolean** — Check if array contains value
310
- - **object.Contains(search: ??):boolean** — Check if object contains value
311
- - **array.At(index: integer):??** — Access item in array by index
312
- - **object.At(index: string):??** — Access item in object by key
313
- - **array.Has(index: integer):boolean** — Identify if array has index
314
- - **object.Has(index: string):boolean** — Identify if object has key
315
-
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
344
- - **(boolean | timestamp | integer).Float():float** — Convert to a float; timestamps use milliseconds since the Unix epoch
345
- - **(boolean | timestamp | float).Integer():integer** — Convert to an integer; timestamps use milliseconds since the Unix epoch
346
- - **(timestamp | float | integer).Boolean():boolean** — Convert to a boolean by testing whether the numeric or epoch value is non-zero
347
-
348
- #### Object Functions
349
- - **object.Entries():array** — Key-value pairs
350
- - **object.Keys():[string]** — Object keys
351
- - **object.Values():array** — Object values
878
+ - **[].Contains(search: any, startPos: integer?):boolean** — Check if array contains value
879
+ - **[:].Contains(search: any):boolean** — Check if object contains value
880
+ - **[].At(index: integer):any** — Access item in array by index
881
+ - **[:].At(index: string):any** — Access item in object by key
882
+ - **([] | null).OptionalAt(index: integer):any** — Access item by index; a `null` receiver or missing index returns `null`
883
+ - **([:] | null).OptionalAt(index: string):any** — Access item by key; a `null` receiver or missing key returns `null`
884
+ - **[].Has(index: integer):boolean** — Identify if array has index
885
+ - **[:].Has(index: string):boolean** — Identify if object has key
886
+ - **([] | null).OptionalHas(index: integer):boolean?** — Check whether an index exists; a `null` receiver returns `null`
887
+ - **([:] | null).OptionalHas(index: string):boolean?** — Check whether a key exists; a `null` receiver returns `null`
888
+
889
+ #### Number Functions
890
+
891
+ - **(float | integer).GreaterThan(value: float | integer):boolean** — Greater than
892
+ - **(float | integer).LessThan(value: float | integer):boolean** — Less than
893
+ - **(float | integer).GreaterOrEqual(value: float | integer):boolean** — Greater or equal
894
+ - **(float | integer).LessOrEqual(value: float | integer):boolean** — Less or equal
895
+ - **float.Subtract(subtrahend: float | integer):float** — Subtract a number
896
+ - **integer.Subtract(subtrahend: float):float** — Subtract a float
897
+ - **integer.Subtract(subtrahend: integer):integer** — Subtract an integer
898
+ - **float.Negate():float** — Negate number
899
+ - **integer.Negate():integer** — Negate number
900
+ - **float.Multiply(value: float | integer):float** — Multiply by a number
901
+ - **integer.Multiply(value: float):float** — Multiply by a float
902
+ - **integer.Multiply(value: integer):integer** — Multiply by an integer
903
+ - **float.Divide(divisor: float | integer):float** — Divide by a number
904
+ - **integer.Divide(divisor: float):float** — Divide by a float
905
+ - **integer.Divide(divisor: integer):integer** — Divide by an integer
906
+ - **float.Remainder(divisor: float | integer):float** — Remainder after division by a number
907
+ - **integer.Remainder(divisor: float):float** — Remainder after division by a float
908
+ - **integer.Remainder(divisor: integer):integer** — Remainder after division by an integer
909
+ - **float.Modulo(divisor: float | integer):float** — Modulo by a number
910
+ - **integer.Modulo(divisor: float):float** — Modulo by a float
911
+ - **integer.Modulo(divisor: integer):integer** — Modulo by an integer
912
+ - **float.Power(exponent: float | integer):float** — Raise to a numeric power
913
+ - **integer.Power(exponent: float):float** — Raise to a float power
914
+ - **integer.Power(exponent: integer):integer** — Raise to an integer power
915
+ - **float.Root(index: float | integer):float?** — Take a root with the specified index
916
+ - **integer.Root(index: float):float?** — Take a float root
917
+ - **integer.Root(index: integer):integer?** — Take an integer root
918
+ - **boolean.Float():float** — Convert to a float
919
+ - **timestamp.Float():float** — Convert to milliseconds since the Unix epoch
920
+ - **integer.Float():float** — Convert to a float
921
+ - **boolean.Integer():integer** — Convert to an integer
922
+ - **timestamp.Integer():integer** — Convert to milliseconds since the Unix epoch
923
+ - **float.Integer():integer** — Convert to an integer
924
+ - **timestamp.Boolean():boolean** — Test whether the epoch value is non-zero
925
+ - **float.Boolean():boolean** — Test whether the numeric value is non-zero
926
+ - **integer.Boolean():boolean** — Test whether the numeric value is non-zero
927
+
928
+ `Root` returns `null` for a nonpositive index. With integer operands, even roots of negative values also return `null`.
929
+ Floating-point root calculations can return `NaN`, which is a float.
930
+
931
+ #### Object Functions
932
+
933
+ - **[:].Entries():[]** — Key-value pairs
934
+ - **[:].Keys():[...string]** — Object keys
935
+ - **[:].Values():[]** — Object values
352
936
 
353
937
  #### String Functions
938
+
354
939
  - **string.Like(value: string):boolean** — Alphanumeric equality
355
- - **string.Unlike(value: string):boolean** — Alphanumeric inequality
940
+ - **string.NotLike(value: string):boolean** — Alphanumeric inequality
356
941
  - **string.StartsWith(search: string, startPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Prefix check
357
942
  - **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
943
+ - **string.CharAt(pos: integer):string?** — Character at position, or `""` when out of range
944
+ - **string.CharCodeAt(pos: integer):integer?** — Character code, or `null` when unavailable
360
945
  - **string.Trim():string** — Trim whitespace
361
946
  - **string.TrimStart():string** — Trim leading whitespace
362
947
  - **string.TrimEnd():string** — Trim trailing whitespace
363
948
  - **string.LowerCase():string** — To lowercase
364
949
  - **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
950
+ - **string.Split(separator: string = ' '):[...string]** — Split into an array of strings
951
+ - **string.ReplaceWith(replacement: string, search: ...string):string** — Replace all instances of the searched strings
367
952
 
368
953
  #### Timestamp Functions
954
+
369
955
  - **timestamp.Year(utc: boolean?):integer** — Get year
370
956
  - **timestamp.Month(utc: boolean?):integer** — Get month
371
957
  - **timestamp.MonthIndex(utc: boolean?):integer** — Month index
@@ -381,75 +967,59 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
381
967
  - **timestamp.MinutesSince(value: timestamp):float** — Difference from another timestamp in minutes
382
968
  - **timestamp.SecondsSince(value: timestamp):float** — Difference from another timestamp in seconds
383
969
 
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:
970
+ ## Detailed type rules
971
+
972
+ Affinirum uses intentionally permissive type checking. Type information helps reject clearly incompatible expressions,
973
+ select function overloads, and report compilation errors. It does not prove that every accepted expression is safe
974
+ for every possible runtime value.
975
+
976
+ - `any` accepts every type, including `null`. An expression of type `any` fits every expected type except `never`.
977
+ - An expression of type `never` cannot complete with a value. The compiler rejects `never`-typed cast operands, call
978
+ arguments, and index expressions, including in optional calls and accesses. For example, `Integer.Sum({=>7}, 1)` and
979
+ `[10][(=>0)]` both cause compilation errors.
980
+ - An optional type such as `integer?` is the union `null | integer`. Write `null` for a type that only accepts `null`.
981
+ Optional parameters, including `any`, accept `null` or JavaScript `undefined`. Only trailing optional parameters can be omitted.
982
+ - A call to an overloaded function must match one complete signature. A call through a union of functions must match
983
+ one complete signature for each possible function. For typed calls, the full argument types must fit the signature
984
+ at compile time. The first matching overload determines the result type for each callable. Implicit arguments can
985
+ remain `any` when the overloads leave their types ambiguous. Evaluation uses the function directly.
986
+ - Record types are open structural constraints: required properties and their values are checked, while additional
987
+ properties are allowed.
988
+ - Tuple types are prefix constraints: declared item types are checked in order, optional trailing items may be
989
+ omitted, and additional items are allowed.
990
+ - A replacement function may require at most as many arguments as the declared signature requires.
991
+ - A callback may declare fewer parameters than the caller provides. Additional arguments are ignored at runtime,
992
+ following JavaScript function-call behavior.
993
+ - Function parameter types are checked contravariantly where both signatures declare a parameter. The receiving
994
+ function must accept the full expected parameter type, including `null` when present. Return types are checked
995
+ covariantly: the returned type must fit the expected result type. `any` remains compatible with any parameter type.
996
+ - Function-type compatibility distinguishes fixed and variadic signatures. Two non-generic variadic signatures must
997
+ declare their variadic parameter in the same position to be compatible.
998
+
999
+ For example, a callback `func(value: float):boolean { value > 0}` is compatible with an expected callback type such as
1000
+ `{(any, integer, []):boolean}`. The array method supplies all three arguments, and the callback can ignore
1001
+ the index and array. `any` keeps the item type flexible.
1002
+
1003
+ For a variadic host function, set the third entry of the signature to `true` and declare its last parameter as a uniform
1004
+ array type. Use `Type.Array` to accept arguments of any type. Affinirum passes the arguments
1005
+ individually. The JavaScript implementation collects the trailing arguments with a rest parameter.
409
1006
 
410
1007
  ```ts
411
- const value = Affinirum.parse('["answer":42,"enabled":true]');
412
- const notation = Affinirum.format(value);
1008
+ import { Affinirum, Type } from "affinirum";
413
1009
 
414
- Affinirum.format(undefined); // "null"
415
- Affinirum.format(null); // "null"
416
- Affinirum.format([1n, undefined]); // "[1,null]"
417
- Affinirum.format({ missing: undefined }); // '["missing":null]'
1010
+ const expression = new Affinirum("sum(1, 2, 3)", {
1011
+ strict: true,
1012
+ variables: {
1013
+ sum: Type.functionType([[Type.Integer, [Type.arrayType(Type.Integer)], true]]),
1014
+ },
1015
+ });
1016
+
1017
+ const result = expression.evaluate({
1018
+ sum: (...values: bigint[]) => values.reduce((total, value) => total + value, 0n),
1019
+ }); // 6n
418
1020
  ```
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
- ```
1021
+
1022
+ When JavaScript calls a variadic script function returned by `evaluate()`, pass the arguments individually as well.
1023
+
1024
+ Casts require source and target types to overlap at compile time. At runtime, the evaluated value must satisfy the
1025
+ target type.