affinirum 1.6.0 → 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.
Potentially problematic release.
This version of affinirum might be problematic. Click here for more details.
- package/.cache/arrow-preview-vWvB5K/affinirum-arrow-functions.patch +155 -0
- package/.cache/function-syntax-tests.log +20 -0
- package/README.md +483 -186
- package/dst/Affinirum.d.ts +29 -19
- package/dst/Affinirum.js +398 -336
- 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 +397 -335
- 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 -23
- package/dst/cjs/native/Aggregable.js +10 -2
- package/dst/cjs/native/Array.d.ts +2 -1
- package/dst/cjs/native/Array.js +35 -28
- 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 +5 -4
- package/dst/cjs/node/JumpNode.js +8 -4
- package/dst/cjs/node/LoopNode.d.ts +7 -5
- package/dst/cjs/node/LoopNode.js +32 -21
- 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} +16 -14
- package/dst/cjs/node/ObjectNode.d.ts +7 -4
- package/dst/cjs/node/ObjectNode.js +42 -11
- package/dst/cjs/node/TernaryNode.d.ts +5 -5
- package/dst/cjs/node/TernaryNode.js +18 -22
- 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 -22
- package/dst/native/Aggregable.js +11 -3
- package/dst/native/Array.d.ts +2 -1
- package/dst/native/Array.js +34 -27
- 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 +5 -4
- package/dst/node/JumpNode.js +8 -4
- package/dst/node/LoopNode.d.ts +7 -5
- package/dst/node/LoopNode.js +32 -21
- 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/TernaryNode.d.ts +5 -5
- package/dst/node/TernaryNode.js +18 -22
- package/dst/node/VariableNode.d.ts +10 -6
- package/dst/node/VariableNode.js +50 -16
- package/package.json +2 -2
- 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/Keywords.d.ts +0 -1
- package/dst/Keywords.js +0 -18
- package/dst/Node.d.ts +0 -14
- package/dst/Node.js +0 -26
- 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/Keywords.d.ts +0 -1
- package/dst/cjs/Keywords.js +0 -21
- package/dst/cjs/Node.d.ts +0 -14
- package/dst/cjs/ScriptSpan.d.ts +0 -10
- package/dst/cjs/node/ReturnNode.d.ts +0 -18
- package/dst/cjs/node/ReturnNode.js +0 -38
- package/dst/cjs/node/VariadicNode.d.ts +0 -4
- package/dst/cjs/node/VariadicNode.js +0 -10
- package/dst/node/ReturnNode.d.ts +0 -18
- package/dst/node/ReturnNode.js +0 -34
- 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
|
@@ -4,11 +4,11 @@ Affinirum is an embeddable scripting language for expressions, rules, and algori
|
|
|
4
4
|
It supports variables, conditionals, loops, first-class functions, and a standard library for numbers, timestamps,
|
|
5
5
|
buffers, strings, arrays, and objects. The host application supplies input values and functions.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Affinirum runs in browsers and Node.js with an ES2022 runtime. The package provides ESM, CommonJS, and TypeScript declarations.
|
|
8
8
|
|
|
9
9
|
- Parse once and evaluate repeatedly with different inputs.
|
|
10
10
|
- Infer types and fold constant expressions during compilation.
|
|
11
|
-
- Use
|
|
11
|
+
- Use reassignable `var` bindings and indexed array and object updates.
|
|
12
12
|
- Define typed functions, callbacks, and variadic parameters.
|
|
13
13
|
|
|
14
14
|
## Contents
|
|
@@ -16,13 +16,15 @@ Runs in browsers and Node.js with an ES2022 runtime. The package provides ESM, C
|
|
|
16
16
|
- [Install and quick start](#install-and-quick-start)
|
|
17
17
|
- [Language basics](#language-basics)
|
|
18
18
|
- [Statements and literals](#statements-and-literals)
|
|
19
|
-
- [Variables and
|
|
19
|
+
- [Variables and values](#variables-and-values)
|
|
20
20
|
- [Conditionals](#conditionals)
|
|
21
|
+
- [Matches](#matches)
|
|
21
22
|
- [Loops](#loops)
|
|
22
23
|
- [Functions and returns](#functions-and-returns)
|
|
23
24
|
- [Arrays and objects](#arrays-and-objects)
|
|
24
25
|
- [Method calls and chaining](#method-calls-and-chaining)
|
|
25
26
|
- [Types](#types)
|
|
27
|
+
- [Array, object, and variadic types](#array-object-and-variadic-types)
|
|
26
28
|
- [Operators and precedence](#operators-and-precedence)
|
|
27
29
|
- [Embedding API](#embedding-api)
|
|
28
30
|
- [Typed inputs and strict mode](#typed-inputs-and-strict-mode)
|
|
@@ -70,8 +72,8 @@ Scripts without external inputs can be evaluated with `evaluate()`.
|
|
|
70
72
|
### Statements and literals
|
|
71
73
|
|
|
72
74
|
Separate statements with semicolons; a newline alone does not separate them. A script or `{ ... }` block returns the
|
|
73
|
-
value of its last expression. An empty block has type `
|
|
74
|
-
Use parentheses to group expressions
|
|
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.
|
|
75
77
|
|
|
76
78
|
```text
|
|
77
79
|
val base = 10;
|
|
@@ -87,7 +89,7 @@ base + extra // 16
|
|
|
87
89
|
| String | `'hello'`, `"hello"` |
|
|
88
90
|
| Timestamp | `@2025-05-11T19:09:21.320Z` |
|
|
89
91
|
| Buffer | `` `10ab0901` `` (hexadecimal bytes) |
|
|
90
|
-
|
|
|
92
|
+
| Null | `null` |
|
|
91
93
|
| Array | `[1, 2, 3]`, `[]` |
|
|
92
94
|
| Object | `["name": "Ada", "score": 10]`, `[:]` |
|
|
93
95
|
|
|
@@ -96,11 +98,17 @@ Integer division truncates toward zero: `7 / 2` is `3`, while `7.0 / 2` is `3.5`
|
|
|
96
98
|
Arithmetic involving a float produces a float.
|
|
97
99
|
|
|
98
100
|
Whitespace outside literals and comments is ignored. Names are case-sensitive. Line comments start with `//`;
|
|
99
|
-
block comments are enclosed in `/// ...
|
|
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.
|
|
100
104
|
|
|
101
|
-
|
|
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`.
|
|
102
108
|
|
|
103
|
-
|
|
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:
|
|
104
112
|
|
|
105
113
|
```text
|
|
106
114
|
val step = 2;
|
|
@@ -109,28 +117,53 @@ count += step;
|
|
|
109
117
|
count // 3
|
|
110
118
|
```
|
|
111
119
|
|
|
112
|
-
|
|
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 `_`,
|
|
113
132
|
followed by any combination of those characters and digits, such as `x`, `_a1$`, or `abc25`.
|
|
114
|
-
Language keywords, including `var`, `val`, `if`, `else`, `while`, `next`, and `exit`,
|
|
115
|
-
|
|
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.
|
|
116
135
|
|
|
117
|
-
|
|
118
|
-
|
|
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:
|
|
119
139
|
|
|
120
140
|
```text
|
|
121
|
-
var items = [1];
|
|
141
|
+
var items: [...integer] = [1];
|
|
122
142
|
val original = items;
|
|
123
143
|
items += [2];
|
|
124
144
|
[items, original] // [[1,2],[1]]
|
|
125
145
|
```
|
|
126
146
|
|
|
127
|
-
Array items and object properties
|
|
128
|
-
|
|
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]`.
|
|
129
160
|
|
|
130
161
|
### Conditionals
|
|
131
162
|
|
|
132
163
|
`if condition { ... } else { ... }` is a conditional expression: it evaluates only the selected branch and returns
|
|
133
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.
|
|
134
167
|
|
|
135
168
|
```text
|
|
136
169
|
val score = 82;
|
|
@@ -138,10 +171,47 @@ val category = if score >= 60 { "pass" } else { "fail" };
|
|
|
138
171
|
category // "pass"
|
|
139
172
|
```
|
|
140
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
|
+
|
|
141
210
|
### Loops
|
|
142
211
|
|
|
143
|
-
`while condition { ... }` repeats while its boolean condition is true.
|
|
144
|
-
|
|
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.
|
|
145
215
|
|
|
146
216
|
```text
|
|
147
217
|
var i = 0;
|
|
@@ -155,34 +225,66 @@ while i < 10 {
|
|
|
155
225
|
total // 12
|
|
156
226
|
```
|
|
157
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
|
+
|
|
158
247
|
A loop returns its last completed iteration's value, or `null` if no iteration completes. An iteration interrupted
|
|
159
|
-
by `next` or `exit` does not replace that result.
|
|
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.
|
|
160
250
|
|
|
161
251
|
### Functions and returns
|
|
162
252
|
|
|
163
|
-
Define a function with
|
|
164
|
-
|
|
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.
|
|
165
259
|
|
|
166
260
|
```text
|
|
167
|
-
val absolute =
|
|
168
|
-
if value < 0 {
|
|
261
|
+
val absolute = func(value: integer): integer {
|
|
262
|
+
if value < 0 { -> -value };
|
|
169
263
|
value
|
|
170
264
|
};
|
|
171
265
|
absolute(-5) // 5
|
|
172
266
|
```
|
|
173
267
|
|
|
268
|
+
A return annotation can be a union, as in `func(value: integer): integer | string { value }`.
|
|
269
|
+
|
|
174
270
|
Functions are values and can be passed as callbacks. A final variadic parameter collects the remaining arguments into
|
|
175
|
-
an array.
|
|
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`.
|
|
176
273
|
|
|
177
274
|
```text
|
|
178
|
-
val sum =
|
|
275
|
+
val sum = func(values: ...integer): integer {
|
|
276
|
+
values.Reduce(func(total: integer, item: integer): integer { total + item}, 0)
|
|
277
|
+
};
|
|
179
278
|
sum(1, 2, 3) // 6
|
|
180
279
|
```
|
|
181
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
|
+
|
|
182
284
|
Use the global return operator `=>value` to finish the entire script evaluation, including from inside a function or callback:
|
|
183
285
|
|
|
184
286
|
```text
|
|
185
|
-
val stop =
|
|
287
|
+
val stop = func(): integer { =>42 };
|
|
186
288
|
stop();
|
|
187
289
|
0 // The script returns 42 before reaching this expression.
|
|
188
290
|
```
|
|
@@ -190,13 +292,15 @@ stop();
|
|
|
190
292
|
### Arrays and objects
|
|
191
293
|
|
|
192
294
|
Arrays hold ordered values of any type and use zero-based indexes. Access an item with brackets or a dot followed by
|
|
193
|
-
an integer.
|
|
295
|
+
an integer. Use `.?` to check whether an index exists. Write an empty array as `[]`.
|
|
194
296
|
|
|
195
297
|
```text
|
|
196
298
|
val items = [10, 20, 30];
|
|
197
|
-
[items[0], items.1, items
|
|
299
|
+
[items[0], items.1, items.?2, items.?3] // [10,20,true,false]
|
|
198
300
|
```
|
|
199
301
|
|
|
302
|
+
Prefer brackets for consecutive numeric indexes: `matrix.0.1` reads `0.1` as one decimal token.
|
|
303
|
+
|
|
200
304
|
Use `+` to concatenate arrays. Wrap an individual item in an array when adding it:
|
|
201
305
|
|
|
202
306
|
```text
|
|
@@ -205,9 +309,10 @@ Use `+` to concatenate arrays. Wrap an individual item in an array when adding i
|
|
|
205
309
|
[1] + [[2, 3]] // [1,[2,3]]
|
|
206
310
|
```
|
|
207
311
|
|
|
208
|
-
Objects hold named values. Define them with string keys and colons inside brackets
|
|
209
|
-
|
|
210
|
-
|
|
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"`.
|
|
211
316
|
|
|
212
317
|
```text
|
|
213
318
|
val original = ["name": "Ada", "score": 10];
|
|
@@ -218,6 +323,21 @@ val updated = Object.Merge(original, ["score": 20, "active": true]);
|
|
|
218
323
|
`Object.Merge` creates a new object; later arguments take precedence for duplicate keys. Array concatenation and
|
|
219
324
|
object merging are shallow: nested values are shared by reference, with their contents preserved at the script level.
|
|
220
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
|
+
|
|
221
341
|
### Method calls and chaining
|
|
222
342
|
|
|
223
343
|
Built-in methods use `value.Method(arguments)`. Parentheses can be omitted when no explicit arguments are needed:
|
|
@@ -227,89 +347,197 @@ Built-in methods use `value.Method(arguments)`. Parentheses can be omitted when
|
|
|
227
347
|
" hello ".Trim.UpperCase // "HELLO"
|
|
228
348
|
```
|
|
229
349
|
|
|
230
|
-
Callbacks
|
|
350
|
+
Callbacks can transform arrays in successive steps:
|
|
231
351
|
|
|
232
352
|
```text
|
|
233
353
|
val values = [1, 2, 3];
|
|
234
|
-
values.Derive(
|
|
235
|
-
.Filter(
|
|
354
|
+
values.Derive(func(item: integer): integer { item * 2 })
|
|
355
|
+
.Filter(func(item: integer): boolean { item > 3 }) // [4,6]
|
|
236
356
|
```
|
|
237
357
|
|
|
238
358
|
After a dot, a built-in method name takes precedence over an object property with the same name.
|
|
239
|
-
Use brackets or a quoted key to read such a property, for example `
|
|
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`.
|
|
240
364
|
|
|
241
365
|
### Types
|
|
242
366
|
|
|
243
367
|
| Type | Meaning |
|
|
244
368
|
| --- | --- |
|
|
245
|
-
| `
|
|
369
|
+
| `null` | The type whose only script value is `null` |
|
|
370
|
+
| `never` | A type with no values, used for expressions that cannot complete normally |
|
|
246
371
|
| `boolean` / `bool` | `true` or `false` |
|
|
247
372
|
| `timestamp` / `time` | Date and time |
|
|
248
373
|
| `float` / `f64` | 64-bit floating-point number |
|
|
249
374
|
| `integer` / `i64` | Signed 64-bit integer |
|
|
250
375
|
| `buffer` | Sequence of bytes |
|
|
251
376
|
| `string` | Text |
|
|
252
|
-
| `
|
|
253
|
-
| `
|
|
254
|
-
| `
|
|
255
|
-
|
|
|
256
|
-
| `
|
|
257
|
-
| `
|
|
258
|
-
| `["name": string]` | Object with a required string property named `name` |
|
|
259
|
-
| `~(integer): string` | Function taking an integer and returning a string |
|
|
260
|
-
| `integer?` | Optional integer: `void` or `integer` |
|
|
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` |
|
|
261
383
|
| `integer \| string` | Union of types |
|
|
262
384
|
|
|
263
|
-
|
|
264
|
-
|
|
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.
|
|
265
404
|
|
|
266
|
-
A
|
|
405
|
+
A cast, `(expression:type)`, checks an expected type without converting the value:
|
|
267
406
|
|
|
268
407
|
```text
|
|
269
408
|
val parsed = JSON.Parse('{"answer":42}');
|
|
270
|
-
parsed
|
|
409
|
+
(parsed:[:]).answer // 42.0
|
|
271
410
|
```
|
|
272
411
|
|
|
273
412
|
Standard JSON numbers are floats. Use conversion methods such as `.Integer()` or `.Float()` to convert numeric types.
|
|
274
|
-
An incompatible cast raises an error.
|
|
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.
|
|
275
464
|
|
|
276
465
|
### Operators and precedence
|
|
277
466
|
|
|
278
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).
|
|
279
470
|
|
|
280
471
|
| Precedence | Operators | Meaning |
|
|
281
472
|
| --- | --- | --- |
|
|
282
|
-
| Highest | `.`, `[]`,
|
|
283
|
-
| |
|
|
473
|
+
| Highest | `.`, `[]`, `.?`, `?.`, `?[]`, `?.?`, `()`, `(value:type)` | Access, presence checks, calls, and casts |
|
|
474
|
+
| | `**` | Exponentiation |
|
|
284
475
|
| | Unary `+`, `-` | Arithmetic sign |
|
|
285
476
|
| | `*`, `/`, `%` | Multiplication, division, remainder |
|
|
286
477
|
| | `+`, `-` | Addition or concatenation; subtraction |
|
|
478
|
+
| | `..` | Inclusive ascending integer range |
|
|
287
479
|
| | `>`, `<`, `>=`, `<=`, `==`, `!=` | Comparison and equality |
|
|
288
|
-
| |
|
|
289
|
-
| |
|
|
290
|
-
| |
|
|
480
|
+
| | `!`, `not` | Boolean negation |
|
|
481
|
+
| | `&`, `and` | Boolean AND |
|
|
482
|
+
| | `\|`, `or` | Boolean OR |
|
|
291
483
|
| Lowest | `?:` | Null coalescing |
|
|
292
484
|
|
|
293
|
-
Binary operators at the same precedence group left to right, including exponentiation:
|
|
294
|
-
`2
|
|
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`.
|
|
295
487
|
Boolean negation binds after comparisons: `!a == b` means `!(a == b)`.
|
|
296
488
|
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
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.
|
|
300
511
|
|
|
301
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.
|
|
302
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.
|
|
303
520
|
|
|
304
521
|
## Embedding API
|
|
305
522
|
|
|
306
|
-
`new Affinirum(script, config?)` parses and compiles the script. `evaluate(inputs?)` executes it with the current inputs.
|
|
307
|
-
|
|
308
|
-
|
|
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.
|
|
309
537
|
|
|
310
538
|
### Typed inputs and strict mode
|
|
311
539
|
|
|
312
|
-
Use constructor configuration to declare input types, require declarations, and constrain the result type:
|
|
540
|
+
Use constructor configuration to declare input value types, require declarations, and constrain the result type:
|
|
313
541
|
|
|
314
542
|
```js
|
|
315
543
|
import { Affinirum, Type } from "affinirum";
|
|
@@ -326,26 +554,29 @@ const expression = new Affinirum("price * quantity", {
|
|
|
326
554
|
console.log(expression.evaluate({ price: 12.5, quantity: 3n })); // 37.5
|
|
327
555
|
```
|
|
328
556
|
|
|
329
|
-
- `variables` declares input types; structured types can be built with helpers such as `Type.arrayType(
|
|
557
|
+
- `variables` declares input value types; structured types can be built with helpers such as `Type.arrayType(Type.Integer)`
|
|
330
558
|
and `Type.objectType([["name", Type.String]])`.
|
|
559
|
+
- A referenced input declared as `Type.Never` causes a compilation error.
|
|
331
560
|
- `strict: true` rejects undeclared input names during compilation. It does not change the language's type compatibility rules.
|
|
332
|
-
- `type` specifies the expected result type
|
|
561
|
+
- `type` specifies the expected result type to be checked during compilation.
|
|
333
562
|
|
|
334
563
|
Every referenced input must be supplied as an own property of the object passed to `evaluate`, even if its value is `undefined`.
|
|
335
|
-
|
|
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.
|
|
336
566
|
|
|
337
567
|
| Instance member | Result |
|
|
338
568
|
| --- | --- |
|
|
339
569
|
| `script` | Original script text |
|
|
340
570
|
| `type` | Inferred result `Type`; use `.toString()` for its readable form |
|
|
341
|
-
| `variables()` | Record of referenced input names and their inferred types |
|
|
571
|
+
| `variables()` | Record of referenced input names and their inferred or declared types |
|
|
342
572
|
| `toString()` | Compiled tree representation |
|
|
343
|
-
| `evaluate(inputs?)` | Script result as a JavaScript value |
|
|
573
|
+
| `evaluate(inputs?, timeout?)` | Script result as a JavaScript value |
|
|
344
574
|
|
|
345
575
|
### Host functions
|
|
346
576
|
|
|
347
577
|
Declare a function's type in `variables`, then supply its JavaScript implementation on evaluation.
|
|
348
|
-
`Type.functionType` takes the return type
|
|
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.
|
|
349
580
|
|
|
350
581
|
```ts
|
|
351
582
|
import { Affinirum, Type } from "affinirum";
|
|
@@ -355,7 +586,7 @@ const expression = new Affinirum("discount(total)", {
|
|
|
355
586
|
type: Type.Float,
|
|
356
587
|
variables: {
|
|
357
588
|
total: Type.Float,
|
|
358
|
-
discount: Type.functionType(Type.Float, [Type.Float]),
|
|
589
|
+
discount: Type.functionType([[Type.Float, [Type.Float]]]),
|
|
359
590
|
},
|
|
360
591
|
});
|
|
361
592
|
|
|
@@ -365,23 +596,41 @@ const result = expression.evaluate({
|
|
|
365
596
|
}); // 90
|
|
366
597
|
```
|
|
367
598
|
|
|
368
|
-
|
|
369
|
-
|
|
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.
|
|
370
619
|
|
|
371
620
|
### JavaScript value mapping
|
|
372
621
|
|
|
373
622
|
| Affinirum type | JavaScript value |
|
|
374
623
|
| --- | --- |
|
|
375
|
-
| `
|
|
624
|
+
| `null` | Returns `undefined` and accepts `null` or `undefined` as input |
|
|
376
625
|
| `boolean` | `boolean` |
|
|
377
626
|
| `float` | `number` |
|
|
378
627
|
| `integer` | `bigint` |
|
|
379
628
|
| `timestamp` | `Date` |
|
|
380
629
|
| `buffer` | `ArrayBuffer` |
|
|
381
630
|
| `string` | `string` |
|
|
382
|
-
| `
|
|
383
|
-
| `
|
|
384
|
-
| `
|
|
631
|
+
| `[]` | Array of supported values |
|
|
632
|
+
| `[:]` | Object containing supported values |
|
|
633
|
+
| `{:}` | Synchronous JavaScript function |
|
|
385
634
|
|
|
386
635
|
For example, supply `quantity: 3n` for an integer input; `quantity: 3` supplies a float.
|
|
387
636
|
|
|
@@ -407,9 +656,10 @@ try {
|
|
|
407
656
|
|
|
408
657
|
### Affinirum Notation
|
|
409
658
|
|
|
410
|
-
Affinirum Notation (AN)
|
|
411
|
-
|
|
412
|
-
|
|
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:
|
|
413
663
|
|
|
414
664
|
```js
|
|
415
665
|
import { Affinirum } from "affinirum";
|
|
@@ -425,33 +675,43 @@ Affinirum.format({ missing: undefined }); // '["missing":null]'
|
|
|
425
675
|
|
|
426
676
|
Both `Affinirum.format(value, whitespace?)` and the script function `AN.Format(value, whitespace?)` accept optional
|
|
427
677
|
indentation text. They write JavaScript `null` and `undefined` as the AN literal `null` at every nesting level.
|
|
428
|
-
Parsing that literal produces JavaScript `undefined`, preserving array lengths and object properties containing `
|
|
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
|
+
```
|
|
429
688
|
|
|
430
689
|
## Standard library
|
|
431
690
|
|
|
432
691
|
Global functions use namespaces such as `Integer.Sum(...)`. Method functions use `value.Method(...)`.
|
|
433
|
-
In the signatures below, `T?` means `T` or `
|
|
434
|
-
|
|
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.
|
|
435
694
|
|
|
436
695
|
### Global functions
|
|
437
696
|
|
|
438
|
-
Native conversions use the following
|
|
697
|
+
Native conversions use the following `null` handling:
|
|
439
698
|
|
|
440
|
-
- General `Format` conversions
|
|
441
|
-
- `
|
|
442
|
-
- `
|
|
443
|
-
- `
|
|
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`.
|
|
444
704
|
|
|
445
|
-
Empty strings and zero-length buffers remain ordinary values; they are not serialized
|
|
446
|
-
Invalid
|
|
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.
|
|
447
707
|
|
|
448
708
|
#### Boolean
|
|
449
709
|
|
|
450
|
-
- **Boolean.Or(values: ...
|
|
451
|
-
- **Boolean.And(values: ...
|
|
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`
|
|
452
712
|
- **Boolean.Not(value: boolean):boolean** — Boolean negation
|
|
453
|
-
- **Boolean.Decode(value: buffer?, offset: integer?):boolean?** — Decode a byte at the optional offset; missing or out-of-range input returns
|
|
454
|
-
- **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`
|
|
455
715
|
|
|
456
716
|
#### Timestamp
|
|
457
717
|
|
|
@@ -466,9 +726,9 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
|
|
|
466
726
|
- **Float.PositiveInfinity** — Positive infinity
|
|
467
727
|
- **Float.NegativeInfinity** — Negative infinity
|
|
468
728
|
- **Float.Epsilon** — Difference between `1` and the next larger representable float (`2.220446049250313e-16`)
|
|
469
|
-
- **Float.Sum(values: ...(float | integer
|
|
470
|
-
- **Float.Min(values: ...(float | integer
|
|
471
|
-
- **Float.Max(values: ...(float | integer
|
|
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
|
|
472
732
|
- **Float.Exponent(value: float | integer):float** — Natural exponential
|
|
473
733
|
- **Float.Logarithm(value: float | integer):float** — Natural logarithm
|
|
474
734
|
- **Float.Abs(value: float | integer):float** — Absolute value
|
|
@@ -482,16 +742,16 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
|
|
|
482
742
|
|
|
483
743
|
#### Integer
|
|
484
744
|
|
|
485
|
-
- **Integer.Sum(values: ...
|
|
486
|
-
- **Integer.Min(values: ...
|
|
487
|
-
- **Integer.Max(values: ...
|
|
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
|
|
488
748
|
- **Integer.Random(exclusiveTo: integer):integer** — Random integer up to value
|
|
489
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`
|
|
490
750
|
- **Integer.Parse(value: string?):integer?** — Parse a string as an integer
|
|
491
751
|
|
|
492
752
|
#### String
|
|
493
753
|
|
|
494
|
-
- **String.
|
|
754
|
+
- **String.Alphanumeric(value: string):string** — Keep ASCII letters and digits, converting letters to lowercase. An empty input returns `""`.
|
|
495
755
|
- **String.Random(length: integer):string** — Random alphanumeric string
|
|
496
756
|
- **String.Decode(value: buffer?, encoding: string?, offset: integer?, length: integer?):string?** — Decode using `utf8` (default), `sbcs`, `ucs2`, or `ucs2le`
|
|
497
757
|
|
|
@@ -502,11 +762,11 @@ Invalid non-void inputs are function-specific and may raise an evaluation error.
|
|
|
502
762
|
|
|
503
763
|
#### Array
|
|
504
764
|
|
|
505
|
-
- **Array.Join(values: ...
|
|
506
|
-
- **Array.Range(a: integer, b: integer):
|
|
507
|
-
- **Array.Unique(value:
|
|
508
|
-
- **Array.Intersection(a1:
|
|
509
|
-
- **Array.Difference(a1:
|
|
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
|
|
510
770
|
|
|
511
771
|
`Array.Join(a,b,c)` has the same shallow concatenation behavior as `a+b+c`. Inputs are preserved, and nested arrays
|
|
512
772
|
and objects are shared by reference. Use `array.Flatten(depth)` to flatten nested array elements.
|
|
@@ -518,34 +778,46 @@ Array.Join([[1,2]],[3]) // [[1,2],3]
|
|
|
518
778
|
|
|
519
779
|
#### Object
|
|
520
780
|
|
|
521
|
-
- **Object.Merge(values: ...
|
|
781
|
+
- **Object.Merge(values: ...[:]):[:]** — Shallow merge into a new object; later arguments take precedence
|
|
522
782
|
|
|
523
783
|
#### AN
|
|
524
784
|
|
|
525
|
-
- **AN.Format(value:
|
|
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`
|
|
526
787
|
|
|
527
788
|
#### JSON
|
|
528
789
|
|
|
529
|
-
- **JSON.Format(value: (
|
|
530
|
-
- **JSON.Parse(value: string?):(
|
|
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
|
|
792
|
+
|
|
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
|
+
```
|
|
531
803
|
|
|
532
804
|
#### IP
|
|
533
805
|
|
|
534
|
-
- **IP.Match(values: [string], search: ...
|
|
535
|
-
- **IP.Encode(value: string?):buffer** — Encode an IPv4, IPv6, or CIDR string as a network-byte-order buffer; malformed or
|
|
536
|
-
- **IP.Decode(value: buffer?):string?** — Decode a 4-, 5-, 16-, or 17-byte buffer as canonical IPv4, IPv6, or CIDR notation; malformed or
|
|
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`
|
|
537
809
|
|
|
538
810
|
### Method functions
|
|
539
811
|
|
|
540
812
|
#### General Functions
|
|
541
813
|
|
|
542
|
-
-
|
|
543
|
-
-
|
|
544
|
-
-
|
|
545
|
-
- **(boolean | buffer |
|
|
546
|
-
- **(
|
|
547
|
-
- **(boolean | string |
|
|
548
|
-
- **(
|
|
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`
|
|
549
821
|
|
|
550
822
|
#### Aggregable Functions
|
|
551
823
|
|
|
@@ -555,53 +827,64 @@ Array.Join([[1,2]],[3]) // [[1,2],3]
|
|
|
555
827
|
- **integer.Add(value: integer):integer** — Add an integer
|
|
556
828
|
- **buffer.Add(value: buffer):buffer** — Concatenate buffers
|
|
557
829
|
- **string.Add(value: string):string** — Concatenate strings
|
|
558
|
-
- **
|
|
830
|
+
- **[].Add(value: []):[]** — Concatenate arrays
|
|
559
831
|
|
|
560
832
|
#### Array Functions
|
|
561
833
|
|
|
562
|
-
- **
|
|
563
|
-
- **
|
|
564
|
-
- **
|
|
565
|
-
- **
|
|
566
|
-
- **
|
|
567
|
-
- **
|
|
568
|
-
- **
|
|
569
|
-
- **
|
|
570
|
-
- **
|
|
571
|
-
- **
|
|
572
|
-
- **
|
|
573
|
-
- **
|
|
574
|
-
|
|
575
|
-
`
|
|
576
|
-
|
|
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.
|
|
577
852
|
|
|
578
853
|
#### Buffer Functions
|
|
579
854
|
|
|
580
|
-
- **buffer.
|
|
855
|
+
- **buffer.ByteAt(pos: integer):buffer?** — One-byte slice at position; an empty slice returns a zero-length buffer
|
|
581
856
|
|
|
582
857
|
#### Enumerable Functions
|
|
583
858
|
|
|
584
859
|
- **buffer.Slice(start: integer?, end: integer?):buffer** — Slice section
|
|
585
860
|
- **string.Slice(start: integer?, end: integer?):string** — Slice section
|
|
586
|
-
- **
|
|
861
|
+
- **[].Slice(start: integer?, end: integer?):[]** — Slice section
|
|
587
862
|
- **buffer.Splice(start: integer, remove: integer, inject: ...buffer):buffer** — Splice section
|
|
588
863
|
- **string.Splice(start: integer, remove: integer, inject: ...string):string** — Splice section
|
|
589
|
-
- **
|
|
864
|
+
- **[].Splice(start: integer, remove: integer, inject: ...[]):[]** — Splice section
|
|
590
865
|
- **buffer.Inject(start: integer, inject: ...buffer):buffer** — Inject section
|
|
591
866
|
- **string.Inject(start: integer, inject: ...string):string** — Inject section
|
|
592
|
-
- **
|
|
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.
|
|
593
872
|
|
|
594
873
|
#### Iterable Functions
|
|
595
874
|
|
|
596
|
-
- **(buffer | string |
|
|
875
|
+
- **(buffer | string | [] | [:] | null).Length():integer** — Get length, or zero for `null`
|
|
597
876
|
- **buffer.Contains(search: buffer, startPos: integer?):boolean** — Check if buffer contains another buffer
|
|
598
877
|
- **string.Contains(search: string, startPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Check if string contains another string
|
|
599
|
-
- **
|
|
600
|
-
- **
|
|
601
|
-
- **
|
|
602
|
-
- **
|
|
603
|
-
- **
|
|
604
|
-
- **
|
|
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`
|
|
605
888
|
|
|
606
889
|
#### Number Functions
|
|
607
890
|
|
|
@@ -629,34 +912,43 @@ Retaining that snapshot preserves its contents as subsequent properties are adde
|
|
|
629
912
|
- **float.Power(exponent: float | integer):float** — Raise to a numeric power
|
|
630
913
|
- **integer.Power(exponent: float):float** — Raise to a float power
|
|
631
914
|
- **integer.Power(exponent: integer):integer** — Raise to an integer power
|
|
632
|
-
- **float.Root(index: float | integer):float
|
|
633
|
-
- **integer.Root(index: float):float
|
|
634
|
-
- **integer.Root(index: integer):integer
|
|
635
|
-
- **
|
|
636
|
-
- **
|
|
637
|
-
- **
|
|
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.
|
|
638
930
|
|
|
639
931
|
#### Object Functions
|
|
640
932
|
|
|
641
|
-
- **
|
|
642
|
-
- **
|
|
643
|
-
- **
|
|
933
|
+
- **[:].Entries():[]** — Key-value pairs
|
|
934
|
+
- **[:].Keys():[...string]** — Object keys
|
|
935
|
+
- **[:].Values():[]** — Object values
|
|
644
936
|
|
|
645
937
|
#### String Functions
|
|
646
938
|
|
|
647
939
|
- **string.Like(value: string):boolean** — Alphanumeric equality
|
|
648
|
-
- **string.
|
|
940
|
+
- **string.NotLike(value: string):boolean** — Alphanumeric inequality
|
|
649
941
|
- **string.StartsWith(search: string, startPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Prefix check
|
|
650
942
|
- **string.EndsWith(search: string, endPos: integer?, ignoreCaseSpaceEtc: boolean?):boolean** — Suffix check
|
|
651
|
-
- **string.
|
|
652
|
-
- **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
|
|
653
945
|
- **string.Trim():string** — Trim whitespace
|
|
654
946
|
- **string.TrimStart():string** — Trim leading whitespace
|
|
655
947
|
- **string.TrimEnd():string** — Trim trailing whitespace
|
|
656
948
|
- **string.LowerCase():string** — To lowercase
|
|
657
949
|
- **string.UpperCase():string** — To uppercase
|
|
658
|
-
- **string.Split(separator: string = ' '):[string]** — Split into an array of strings
|
|
659
|
-
- **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
|
|
660
952
|
|
|
661
953
|
#### Timestamp Functions
|
|
662
954
|
|
|
@@ -681,33 +973,36 @@ Affinirum uses intentionally permissive type checking. Type information helps re
|
|
|
681
973
|
select function overloads, and report compilation errors. It does not prove that every accepted expression is safe
|
|
682
974
|
for every possible runtime value.
|
|
683
975
|
|
|
684
|
-
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
-
|
|
689
|
-
|
|
690
|
-
-
|
|
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
|
|
691
987
|
properties are allowed.
|
|
692
988
|
- Tuple types are prefix constraints: declared item types are checked in order, optional trailing items may be
|
|
693
989
|
omitted, and additional items are allowed.
|
|
694
|
-
-
|
|
695
|
-
one function's complete range does not need to contain the other's.
|
|
990
|
+
- A replacement function may require at most as many arguments as the declared signature requires.
|
|
696
991
|
- A callback may declare fewer parameters than the caller provides. Additional arguments are ignored at runtime,
|
|
697
992
|
following JavaScript function-call behavior.
|
|
698
|
-
- Function parameter types are checked contravariantly where both signatures declare a parameter
|
|
699
|
-
function must accept the expected parameter type. Return types are checked
|
|
700
|
-
the expected result type.
|
|
701
|
-
-
|
|
702
|
-
|
|
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.
|
|
703
998
|
|
|
704
|
-
For example, a callback
|
|
705
|
-
|
|
706
|
-
|
|
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.
|
|
707
1002
|
|
|
708
|
-
For a variadic host function, set the third
|
|
709
|
-
|
|
710
|
-
|
|
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.
|
|
711
1006
|
|
|
712
1007
|
```ts
|
|
713
1008
|
import { Affinirum, Type } from "affinirum";
|
|
@@ -715,14 +1010,16 @@ import { Affinirum, Type } from "affinirum";
|
|
|
715
1010
|
const expression = new Affinirum("sum(1, 2, 3)", {
|
|
716
1011
|
strict: true,
|
|
717
1012
|
variables: {
|
|
718
|
-
sum: Type.functionType(Type.Integer, [Type.arrayType(
|
|
1013
|
+
sum: Type.functionType([[Type.Integer, [Type.arrayType(Type.Integer)], true]]),
|
|
719
1014
|
},
|
|
720
1015
|
});
|
|
721
1016
|
|
|
722
1017
|
const result = expression.evaluate({
|
|
723
|
-
sum: (values: bigint[]) => values.reduce((total, value) => total + value, 0n),
|
|
1018
|
+
sum: (...values: bigint[]) => values.reduce((total, value) => total + value, 0n),
|
|
724
1019
|
}); // 6n
|
|
725
1020
|
```
|
|
726
1021
|
|
|
727
|
-
|
|
728
|
-
|
|
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.
|