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.
- package/.cache/arrow-preview-vWvB5K/affinirum-arrow-functions.patch +155 -0
- package/.cache/function-syntax-tests.log +20 -0
- package/README.md +925 -355
- package/dst/Affinirum.d.ts +29 -19
- package/dst/Affinirum.js +399 -334
- package/dst/CallFrame.d.ts +12 -3
- package/dst/CallFrame.js +49 -10
- package/dst/Constant.d.ts +1 -3
- package/dst/Constant.js +3 -8
- package/dst/LexicalScope.d.ts +11 -9
- package/dst/LexicalScope.js +10 -6
- package/dst/ParserSpan.d.ts +11 -0
- package/dst/{ScriptSpan.js → ParserSpan.js} +8 -5
- package/dst/ParserState.d.ts +28 -49
- package/dst/ParserState.js +256 -489
- package/dst/Type.d.ts +34 -17
- package/dst/Type.js +211 -115
- package/dst/TypeParser.d.ts +9 -0
- package/dst/TypeParser.js +127 -0
- package/dst/Value.d.ts +1 -1
- package/dst/Value.js +21 -10
- package/dst/Variable.d.ts +16 -5
- package/dst/Variable.js +32 -7
- package/dst/atom/ArrayAtom.d.ts +10 -10
- package/dst/atom/ArrayAtom.js +62 -55
- package/dst/atom/Atom.d.ts +7 -0
- package/dst/atom/FunctionAtom.d.ts +13 -15
- package/dst/atom/FunctionAtom.js +53 -104
- package/dst/atom/FunctionSignature.d.ts +23 -0
- package/dst/atom/FunctionSignature.js +124 -0
- package/dst/atom/ObjectAtom.d.ts +11 -9
- package/dst/atom/ObjectAtom.js +73 -33
- package/dst/atom/PrimitiveAtom.d.ts +6 -7
- package/dst/atom/PrimitiveAtom.js +7 -10
- package/dst/cjs/Affinirum.d.ts +29 -19
- package/dst/cjs/Affinirum.js +398 -333
- package/dst/cjs/CallFrame.d.ts +12 -3
- package/dst/cjs/CallFrame.js +49 -10
- package/dst/cjs/Constant.d.ts +1 -3
- package/dst/cjs/Constant.js +3 -8
- package/dst/cjs/LexicalScope.d.ts +11 -9
- package/dst/cjs/LexicalScope.js +10 -6
- package/dst/cjs/ParserSpan.d.ts +11 -0
- package/dst/cjs/{ScriptSpan.js → ParserSpan.js} +10 -7
- package/dst/cjs/ParserState.d.ts +28 -49
- package/dst/cjs/ParserState.js +255 -488
- package/dst/cjs/Type.d.ts +34 -17
- package/dst/cjs/Type.js +211 -115
- package/dst/cjs/TypeParser.d.ts +9 -0
- package/dst/cjs/TypeParser.js +131 -0
- package/dst/cjs/Value.d.ts +1 -1
- package/dst/cjs/Value.js +21 -10
- package/dst/cjs/Variable.d.ts +16 -5
- package/dst/cjs/Variable.js +36 -9
- package/dst/cjs/atom/ArrayAtom.d.ts +10 -10
- package/dst/cjs/atom/ArrayAtom.js +62 -55
- package/dst/cjs/atom/Atom.d.ts +7 -0
- package/dst/cjs/atom/FunctionAtom.d.ts +13 -15
- package/dst/cjs/atom/FunctionAtom.js +54 -105
- package/dst/cjs/atom/FunctionSignature.d.ts +23 -0
- package/dst/cjs/atom/FunctionSignature.js +128 -0
- package/dst/cjs/atom/ObjectAtom.d.ts +11 -9
- package/dst/cjs/atom/ObjectAtom.js +73 -33
- package/dst/cjs/atom/PrimitiveAtom.d.ts +6 -7
- package/dst/cjs/atom/PrimitiveAtom.js +7 -10
- package/dst/cjs/dictionary/Constants.d.ts +2 -0
- package/dst/cjs/dictionary/Constants.js +27 -0
- package/dst/cjs/dictionary/Functions.d.ts +2 -0
- package/dst/cjs/{Functions.js → dictionary/Functions.js} +27 -25
- package/dst/cjs/native/Aggregable.js +10 -2
- package/dst/cjs/native/Array.d.ts +2 -3
- package/dst/cjs/native/Array.js +38 -39
- package/dst/cjs/native/Boolean.d.ts +1 -1
- package/dst/cjs/native/Boolean.js +13 -10
- package/dst/cjs/native/Buffer.d.ts +5 -5
- package/dst/cjs/native/Buffer.js +70 -46
- package/dst/cjs/native/Composite.d.ts +5 -0
- package/dst/cjs/native/Composite.js +35 -0
- package/dst/cjs/native/Enumerable.js +20 -8
- package/dst/cjs/native/Float.d.ts +3 -1
- package/dst/cjs/native/Float.js +51 -12
- package/dst/cjs/native/Integer.d.ts +4 -2
- package/dst/cjs/native/Integer.js +60 -25
- package/dst/cjs/native/Iterable.d.ts +0 -2
- package/dst/cjs/native/Iterable.js +9 -28
- package/dst/cjs/native/Number.d.ts +0 -2
- package/dst/cjs/native/Number.js +34 -48
- package/dst/cjs/native/Object.d.ts +1 -1
- package/dst/cjs/native/Object.js +5 -6
- package/dst/cjs/native/String.d.ts +7 -6
- package/dst/cjs/native/String.js +28 -27
- package/dst/cjs/native/Timestamp.d.ts +3 -3
- package/dst/cjs/native/Timestamp.js +34 -36
- package/dst/cjs/native/Unknown.d.ts +3 -3
- package/dst/cjs/native/Unknown.js +48 -17
- package/dst/cjs/native/notation/AN.d.ts +1 -1
- package/dst/cjs/native/notation/AN.js +37 -35
- package/dst/cjs/native/notation/IP.d.ts +1 -1
- package/dst/cjs/native/notation/IP.js +11 -12
- package/dst/cjs/native/notation/JSON.d.ts +1 -1
- package/dst/cjs/native/notation/JSON.js +7 -6
- package/dst/cjs/node/AccessNode.d.ts +24 -0
- package/dst/cjs/node/AccessNode.js +193 -0
- package/dst/cjs/node/ArrayNode.d.ts +7 -4
- package/dst/cjs/node/ArrayNode.js +26 -15
- package/dst/cjs/node/AssignableNode.d.ts +16 -0
- package/dst/cjs/node/AssignableNode.js +18 -0
- package/dst/cjs/node/AssignmentNode.d.ts +20 -0
- package/dst/cjs/node/AssignmentNode.js +66 -0
- package/dst/cjs/node/BlockNode.d.ts +5 -4
- package/dst/cjs/node/BlockNode.js +18 -11
- package/dst/cjs/node/CallNode.d.ts +7 -5
- package/dst/cjs/node/CallNode.js +40 -41
- package/dst/cjs/node/CastNode.d.ts +5 -6
- package/dst/cjs/node/CastNode.js +16 -17
- package/dst/cjs/node/ConstantNode.d.ts +4 -6
- package/dst/cjs/node/ConstantNode.js +9 -17
- package/dst/cjs/node/FinalNode.d.ts +19 -0
- package/dst/cjs/node/FinalNode.js +41 -0
- package/dst/cjs/node/FunctionNode.d.ts +17 -0
- package/dst/cjs/node/FunctionNode.js +51 -0
- package/dst/cjs/node/InvocationNode.d.ts +5 -0
- package/dst/cjs/node/InvocationNode.js +34 -0
- package/dst/cjs/node/JumpNode.d.ts +7 -9
- package/dst/cjs/node/JumpNode.js +12 -19
- package/dst/cjs/node/LoopNode.d.ts +7 -5
- package/dst/cjs/node/LoopNode.js +33 -22
- package/dst/cjs/node/MatchNode.d.ts +17 -0
- package/dst/cjs/node/MatchNode.js +65 -0
- package/dst/cjs/node/Node.d.ts +14 -0
- package/dst/cjs/{Node.js → node/Node.js} +17 -11
- package/dst/cjs/node/ObjectNode.d.ts +7 -4
- package/dst/cjs/node/ObjectNode.js +42 -11
- package/dst/cjs/node/{SwitchNode.d.ts → TernaryNode.d.ts} +6 -6
- package/dst/cjs/node/TernaryNode.js +45 -0
- package/dst/cjs/node/VariableNode.d.ts +10 -6
- package/dst/cjs/node/VariableNode.js +50 -16
- package/dst/dictionary/Constants.d.ts +2 -0
- package/dst/dictionary/Constants.js +24 -0
- package/dst/dictionary/Functions.d.ts +2 -0
- package/dst/{Functions.js → dictionary/Functions.js} +26 -24
- package/dst/native/Aggregable.js +11 -3
- package/dst/native/Array.d.ts +2 -3
- package/dst/native/Array.js +37 -38
- package/dst/native/Boolean.d.ts +1 -1
- package/dst/native/Boolean.js +12 -9
- package/dst/native/Buffer.d.ts +5 -5
- package/dst/native/Buffer.js +66 -42
- package/dst/native/Composite.d.ts +5 -0
- package/dst/native/Composite.js +32 -0
- package/dst/native/Enumerable.js +20 -8
- package/dst/native/Float.d.ts +3 -1
- package/dst/native/Float.js +48 -11
- package/dst/native/Integer.d.ts +4 -2
- package/dst/native/Integer.js +56 -23
- package/dst/native/Iterable.d.ts +0 -2
- package/dst/native/Iterable.js +8 -27
- package/dst/native/Number.d.ts +0 -2
- package/dst/native/Number.js +34 -46
- package/dst/native/Object.d.ts +1 -1
- package/dst/native/Object.js +4 -5
- package/dst/native/String.d.ts +7 -6
- package/dst/native/String.js +24 -24
- package/dst/native/Timestamp.d.ts +3 -3
- package/dst/native/Timestamp.js +31 -33
- package/dst/native/Unknown.d.ts +3 -3
- package/dst/native/Unknown.js +49 -18
- package/dst/native/notation/AN.d.ts +1 -1
- package/dst/native/notation/AN.js +37 -35
- package/dst/native/notation/IP.d.ts +1 -1
- package/dst/native/notation/IP.js +10 -11
- package/dst/native/notation/JSON.d.ts +1 -1
- package/dst/native/notation/JSON.js +6 -5
- package/dst/node/AccessNode.d.ts +24 -0
- package/dst/node/AccessNode.js +189 -0
- package/dst/node/ArrayNode.d.ts +7 -4
- package/dst/node/ArrayNode.js +26 -15
- package/dst/node/AssignableNode.d.ts +16 -0
- package/dst/node/AssignableNode.js +14 -0
- package/dst/node/AssignmentNode.d.ts +20 -0
- package/dst/node/AssignmentNode.js +62 -0
- package/dst/node/BlockNode.d.ts +5 -4
- package/dst/node/BlockNode.js +18 -11
- package/dst/node/CallNode.d.ts +7 -5
- package/dst/node/CallNode.js +40 -41
- package/dst/node/CastNode.d.ts +5 -6
- package/dst/node/CastNode.js +16 -17
- package/dst/node/ConstantNode.d.ts +4 -6
- package/dst/node/ConstantNode.js +9 -17
- package/dst/node/FinalNode.d.ts +19 -0
- package/dst/node/FinalNode.js +37 -0
- package/dst/node/FunctionNode.d.ts +17 -0
- package/dst/node/FunctionNode.js +47 -0
- package/dst/node/InvocationNode.d.ts +5 -0
- package/dst/node/InvocationNode.js +30 -0
- package/dst/node/JumpNode.d.ts +7 -9
- package/dst/node/JumpNode.js +12 -19
- package/dst/node/LoopNode.d.ts +7 -5
- package/dst/node/LoopNode.js +33 -22
- package/dst/node/MatchNode.d.ts +17 -0
- package/dst/node/MatchNode.js +61 -0
- package/dst/node/Node.d.ts +14 -0
- package/dst/node/Node.js +28 -0
- package/dst/node/ObjectNode.d.ts +7 -4
- package/dst/node/ObjectNode.js +42 -11
- package/dst/node/{SwitchNode.d.ts → TernaryNode.d.ts} +6 -6
- package/dst/node/TernaryNode.js +41 -0
- package/dst/node/VariableNode.d.ts +10 -6
- package/dst/node/VariableNode.js +50 -16
- package/package.json +4 -4
- package/dst/Atom.d.ts +0 -7
- package/dst/Constants.d.ts +0 -2
- package/dst/Constants.js +0 -24
- package/dst/Functions.d.ts +0 -2
- package/dst/Jump.d.ts +0 -1
- package/dst/Jump.js +0 -1
- package/dst/JumpException.d.ts +0 -9
- package/dst/JumpException.js +0 -14
- package/dst/Keywords.d.ts +0 -1
- package/dst/Keywords.js +0 -17
- package/dst/Node.d.ts +0 -14
- package/dst/Node.js +0 -22
- package/dst/ScriptSpan.d.ts +0 -10
- package/dst/cjs/Atom.d.ts +0 -7
- package/dst/cjs/Constants.d.ts +0 -2
- package/dst/cjs/Constants.js +0 -27
- package/dst/cjs/Functions.d.ts +0 -2
- package/dst/cjs/Jump.d.ts +0 -1
- package/dst/cjs/Jump.js +0 -2
- package/dst/cjs/JumpException.d.ts +0 -9
- package/dst/cjs/JumpException.js +0 -18
- package/dst/cjs/Keywords.d.ts +0 -1
- package/dst/cjs/Keywords.js +0 -20
- package/dst/cjs/Node.d.ts +0 -14
- package/dst/cjs/ScriptSpan.d.ts +0 -10
- package/dst/cjs/node/SwitchNode.js +0 -49
- package/dst/cjs/node/VariadicNode.d.ts +0 -4
- package/dst/cjs/node/VariadicNode.js +0 -10
- package/dst/node/SwitchNode.js +0 -45
- package/dst/node/VariadicNode.d.ts +0 -4
- package/dst/node/VariadicNode.js +0 -6
- /package/dst/{Atom.js → atom/Atom.js} +0 -0
- /package/dst/cjs/{Atom.js → atom/Atom.js} +0 -0
package/README.md
CHANGED
|
@@ -1,207 +1,734 @@
|
|
|
1
1
|
# Affinirum
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
and
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
##
|
|
15
|
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
-
|
|
28
|
-
-
|
|
29
|
-
-
|
|
30
|
-
-
|
|
31
|
-
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
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
|
|
189
|
-
- **Boolean.Parse(value: string?):boolean?** — Parse case-insensitive `true` or `false`; other values return
|
|
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** —
|
|
202
|
-
- **Float.Sum(values: ...(float | integer
|
|
203
|
-
- **Float.Min(values: ...(float | integer
|
|
204
|
-
- **Float.Max(values: ...(float | integer
|
|
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
|
-
|
|
218
|
-
- **Integer.
|
|
219
|
-
- **Integer.
|
|
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
|
-
|
|
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
|
-
|
|
241
|
-
- **
|
|
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
|
-
|
|
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
|
-
|
|
251
|
-
- **
|
|
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
|
-
|
|
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
|
-
|
|
259
|
-
-
|
|
260
|
-
-
|
|
261
|
-
- **(
|
|
262
|
-
- **(
|
|
263
|
-
- **(
|
|
264
|
-
- **(
|
|
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
|
-
- **
|
|
274
|
-
|
|
275
|
-
#### Array Functions
|
|
276
|
-
|
|
277
|
-
- **
|
|
278
|
-
- **
|
|
279
|
-
- **
|
|
280
|
-
- **
|
|
281
|
-
- **
|
|
282
|
-
- **
|
|
283
|
-
- **
|
|
284
|
-
- **
|
|
285
|
-
- **
|
|
286
|
-
- **
|
|
287
|
-
- **
|
|
288
|
-
- **
|
|
289
|
-
|
|
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
|
-
|
|
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
|
-
- **
|
|
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
|
-
- **
|
|
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
|
-
- **
|
|
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
|
-
|
|
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
|
-
- **
|
|
310
|
-
- **
|
|
311
|
-
- **
|
|
312
|
-
- **
|
|
313
|
-
- **
|
|
314
|
-
- **
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
- **(
|
|
318
|
-
- **(
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
- **integer.
|
|
323
|
-
- **integer.
|
|
324
|
-
- **float.
|
|
325
|
-
- **integer.
|
|
326
|
-
- **float.
|
|
327
|
-
- **integer.
|
|
328
|
-
- **integer.
|
|
329
|
-
- **float.
|
|
330
|
-
- **integer.
|
|
331
|
-
- **
|
|
332
|
-
- **
|
|
333
|
-
- **integer.
|
|
334
|
-
- **
|
|
335
|
-
- **
|
|
336
|
-
- **integer.
|
|
337
|
-
- **
|
|
338
|
-
- **
|
|
339
|
-
- **integer.
|
|
340
|
-
- **
|
|
341
|
-
- **
|
|
342
|
-
- **integer.
|
|
343
|
-
- **
|
|
344
|
-
- **
|
|
345
|
-
- **(
|
|
346
|
-
- **(
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
- **
|
|
350
|
-
- **
|
|
351
|
-
- **
|
|
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.
|
|
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.
|
|
359
|
-
- **string.
|
|
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: ...
|
|
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
|
-
##
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
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
|
-
|
|
412
|
-
const notation = Affinirum.format(value);
|
|
1008
|
+
import { Affinirum, Type } from "affinirum";
|
|
413
1009
|
|
|
414
|
-
Affinirum
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
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
|
-
|
|
421
|
-
|
|
422
|
-
|
|
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.
|