trilean 1.5.1 → 1.6.1
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/dist/complex.d.cts +1 -1
- package/dist/complex.d.ts +1 -1
- package/dist/computed-value-CbRF0Izc.d.cts +51 -0
- package/dist/computed-value-CbRF0Izc.d.ts +51 -0
- package/dist/computed-value.cjs +1 -1
- package/dist/computed-value.d.cts +1 -50
- package/dist/computed-value.d.ts +1 -50
- package/dist/computed-value.js +1 -1
- package/dist/evaluator-budget.cjs +24 -0
- package/dist/evaluator-budget.d.cts +21 -0
- package/dist/evaluator-budget.d.ts +21 -0
- package/dist/evaluator-budget.js +20 -0
- package/dist/evaluator-collection.cjs +33 -0
- package/dist/evaluator-collection.d.cts +23 -0
- package/dist/evaluator-collection.d.ts +23 -0
- package/dist/evaluator-collection.js +31 -0
- package/dist/evaluator-factory.cjs +19 -0
- package/dist/evaluator-factory.d.cts +22 -0
- package/dist/evaluator-factory.d.ts +22 -0
- package/dist/evaluator-factory.js +16 -0
- package/dist/evaluator-indeterminacy-helpers.cjs +180 -0
- package/dist/evaluator-indeterminacy-helpers.d.cts +57 -0
- package/dist/evaluator-indeterminacy-helpers.d.ts +57 -0
- package/dist/evaluator-indeterminacy-helpers.js +158 -0
- package/dist/evaluator-operations.cjs +385 -0
- package/dist/evaluator-operations.d.cts +27 -0
- package/dist/evaluator-operations.d.ts +27 -0
- package/dist/evaluator-operations.js +376 -0
- package/dist/evaluator-test-helpers.cjs +40 -0
- package/dist/evaluator-test-helpers.d.cts +13 -0
- package/dist/evaluator-test-helpers.d.ts +13 -0
- package/dist/evaluator-test-helpers.js +35 -0
- package/dist/evaluator.cjs +55 -454
- package/dist/evaluator.d.cts +6 -10
- package/dist/evaluator.d.ts +6 -10
- package/dist/evaluator.js +44 -442
- package/dist/functions.d.cts +2 -2
- package/dist/functions.d.ts +2 -2
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/magic-string.es-BWtG0AyA.js +1017 -0
- package/dist/magic-string.es-BvKy4sJx.cjs +1017 -0
- package/dist/resolvers.d.cts +1 -1
- package/dist/resolvers.d.ts +1 -1
- package/dist/test.DNmyFkvJ-Dasq3mQO.cjs +13578 -0
- package/dist/test.DNmyFkvJ-SCEEf0VK.js +13573 -0
- package/package.json +2 -2
- package/schemas/trilean.schema.json +1 -1
package/dist/evaluator.js
CHANGED
|
@@ -1,433 +1,49 @@
|
|
|
1
1
|
import { complexFromPolar } from "./complex.js";
|
|
2
|
-
import { combineUnitsForDivide, combineUnitsForMultiply, unitsEqual } from "./computed-value.js";
|
|
3
2
|
import { definite, firstIndeterminate, indeterminate } from "./evaluation.js";
|
|
4
|
-
import
|
|
3
|
+
import "./evaluator-budget.js";
|
|
4
|
+
import { firstFilterIndeterminate, resolveParticipatingItems } from "./evaluator-collection.js";
|
|
5
|
+
import { applyArithmetic, applyNegate, checkReferenceUnit, combineAnd, combineOr, compareText, compareValues, computeMembershipMatch, invokeRegisteredFunction } from "./evaluator-operations.js";
|
|
5
6
|
import { ExpressionNodeSchema, PredicateNodeSchema } from "./tree.js";
|
|
6
|
-
import { RegexParseError, compilePattern } from "trilean-regex";
|
|
7
7
|
//#region src/evaluator.ts
|
|
8
8
|
/**
|
|
9
|
-
* `evaluatePredicateInternal` and `evaluateValueInternal` are co-located in this one file, rather than split across `predicate-evaluator.ts`/`value-evaluator.ts`, because they are mutually recursive: a predicate leaf (`compare`, `textCompare`, `memberOf`, `exists`) holds `ExpressionNode` operands, and an expression node (`conditional`'s `when`, a fold's `filter`) holds `PredicateNode` operands. Splitting them across modules would make each half import the other, and whichever module finished loading second would see the other's export as `undefined` at its own module-evaluation time -- a genuine circular-import TDZ hazard, not merely a style preference.
|
|
9
|
+
* `evaluatePredicateInternal` and `evaluateValueInternal` below are co-located in this one file, rather than split across `predicate-evaluator.ts`/`value-evaluator.ts`, because they are mutually recursive: a predicate leaf (`compare`, `textCompare`, `memberOf`, `exists`) holds `ExpressionNode` operands, and an expression node (`conditional`'s `when`, a fold's `filter`) holds `PredicateNode` operands. Splitting them across modules would make each half import the other, and whichever module finished loading second would see the other's export as `undefined` at its own module-evaluation time -- a genuine circular-import TDZ hazard, not merely a style preference. `resolveParticipatingItems` (in `evaluator-collection.ts`) would share that same hazard if it imported `evaluatePredicateInternal` directly, since it calls back into it to evaluate each candidate's filter -- so it instead takes the evaluator as an injected `EvaluatePredicate` parameter (see that type's own doc comment), which is what lets it live in its own file with no circular dependency on this one. The pure, non-recursive value-combination logic (`combineAnd`/`compareValues`/`applyArithmetic` and their siblings) carries no such constraint either and lives in `evaluator-operations.ts`; the resource-limit infrastructure (`EvaluationBudget` and its constants), likewise self-contained, lives in `evaluator-budget.ts`.
|
|
10
10
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
if (
|
|
14
|
-
if (right.status === "definite" && !right.value) return definite(false);
|
|
15
|
-
const reason = firstIndeterminate(left, right);
|
|
16
|
-
if (reason !== void 0) return {
|
|
17
|
-
status: "indeterminate",
|
|
18
|
-
reason
|
|
19
|
-
};
|
|
20
|
-
return definite(true);
|
|
21
|
-
}
|
|
22
|
-
/** The three-valued OR table: mirror image of `combineAnd`, with `true` absorbing. */
|
|
23
|
-
function combineOr(left, right) {
|
|
24
|
-
if (left.status === "definite" && left.value) return definite(true);
|
|
25
|
-
if (right.status === "definite" && right.value) return definite(true);
|
|
26
|
-
const reason = firstIndeterminate(left, right);
|
|
27
|
-
if (reason !== void 0) return {
|
|
28
|
-
status: "indeterminate",
|
|
29
|
-
reason
|
|
30
|
-
};
|
|
31
|
-
return definite(false);
|
|
32
|
-
}
|
|
33
|
-
function applyComparisonOperator(op, left, right) {
|
|
34
|
-
switch (op) {
|
|
35
|
-
case "gt": return left > right;
|
|
36
|
-
case "gte": return left >= right;
|
|
37
|
-
case "lt": return left < right;
|
|
38
|
-
case "lte": return left <= right;
|
|
39
|
-
case "eq": return left === right;
|
|
40
|
-
case "neq": return left !== right;
|
|
41
|
-
default: throw new Error("unreachable comparison operator");
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
const millisecondsPerDurationUnit = {
|
|
45
|
-
ms: 1,
|
|
46
|
-
s: 1e3,
|
|
47
|
-
min: 6e4,
|
|
48
|
-
h: 36e5,
|
|
49
|
-
d: 864e5
|
|
50
|
-
};
|
|
51
|
-
/** Normalises a `duration`'s magnitude to milliseconds, the common base unit for combining or comparing two `duration`s (or an `instant` and a `duration`) of potentially different `DurationUnit`s -- shared by `compareValues`'s own `duration` branch below and by the temporal arithmetic further down. */
|
|
52
|
-
function toMilliseconds(value, unit) {
|
|
53
|
-
return value * millisecondsPerDurationUnit[unit];
|
|
54
|
-
}
|
|
55
|
-
/** `Date.parse` reports an unparseable timestamp as `NaN`, and every downstream use of that `NaN` then fails silently rather than loudly: every comparison against it is `false` (so `neq` between two unparseable instants would come back definitely `true`), a subtraction yields a `NaN`-magnitude duration, and `new Date(NaN).toISOString()` throws a `RangeError` outright -- a thrown exception for a data-quality problem, which this design never does (see `Evaluation<T>`'s own doc comment in evaluation.ts). An `instant` whose string will not parse is a value the operation cannot use, so every caller below reports it as `wrong-type`, exactly like any other unusable operand. */
|
|
56
|
-
function toEpochMilliseconds(value) {
|
|
57
|
-
const epochMilliseconds = Date.parse(value);
|
|
58
|
-
return Number.isNaN(epochMilliseconds) ? void 0 : epochMilliseconds;
|
|
59
|
-
}
|
|
60
|
-
function unparseableInstant(value) {
|
|
61
|
-
return indeterminate("wrong-type", `'${value}' is not a parseable ISO-8601 timestamp`);
|
|
62
|
-
}
|
|
63
|
-
/** The representable timestamp range is finite, so a valid instant shifted by a large enough duration lands outside it, where `new Date(...).toISOString()` throws a `RangeError`. Checking the shifted date against the platform's own notion of a valid time value keeps that inside the three-outcome model as a `domain-error` -- an operation pushed outside its valid domain, the same category as division by zero -- and avoids hardcoding the range bound. */
|
|
64
|
-
function instantFromEpochMilliseconds(epochMilliseconds) {
|
|
65
|
-
const shifted = new Date(epochMilliseconds);
|
|
66
|
-
if (Number.isNaN(shifted.getTime())) return indeterminate("domain-error", "the resulting instant falls outside the representable timestamp range");
|
|
67
|
-
return definite({
|
|
68
|
-
kind: "instant",
|
|
69
|
-
value: shifted.toISOString()
|
|
70
|
-
});
|
|
71
|
-
}
|
|
72
|
-
/** `compare`'s two operands: valid kinds are `number` (matching units required), `instant` (ordered by parsed epoch millisecond), or `duration` (ordered by magnitude normalised to milliseconds) -- `text` is never valid here (see `textCompare`), and a kind mismatch between the two operands is `wrong-type`. Narrowing `right` against a literal `left.kind` case (rather than asserting it) is what lets both sides stay properly typed with no `as`. */
|
|
73
|
-
function compareValues(op, left, right) {
|
|
74
|
-
switch (left.kind) {
|
|
75
|
-
case "number":
|
|
76
|
-
if (right.kind !== "number") return indeterminate("wrong-type", `cannot compare a 'number' value with a '${right.kind}' value`);
|
|
77
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot compare numbers with incompatible units");
|
|
78
|
-
return definite(applyComparisonOperator(op, left.value, right.value));
|
|
79
|
-
case "text": return indeterminate("wrong-type", "text values are not comparable via 'compare'; use 'textCompare'");
|
|
80
|
-
case "boolean":
|
|
81
|
-
if (right.kind !== "boolean") return indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${right.kind}' value`);
|
|
82
|
-
if (op !== "eq" && op !== "neq") return indeterminate("wrong-type", `booleans have no natural ordering; '${op}' is only defined for 'eq'/'neq'`);
|
|
83
|
-
return definite(op === "eq" ? left.value === right.value : left.value !== right.value);
|
|
84
|
-
case "instant": {
|
|
85
|
-
if (right.kind !== "instant") return indeterminate("wrong-type", `cannot compare an 'instant' value with a '${right.kind}' value`);
|
|
86
|
-
const leftEpoch = toEpochMilliseconds(left.value);
|
|
87
|
-
if (leftEpoch === void 0) return unparseableInstant(left.value);
|
|
88
|
-
const rightEpoch = toEpochMilliseconds(right.value);
|
|
89
|
-
if (rightEpoch === void 0) return unparseableInstant(right.value);
|
|
90
|
-
return definite(applyComparisonOperator(op, leftEpoch, rightEpoch));
|
|
91
|
-
}
|
|
92
|
-
case "duration":
|
|
93
|
-
if (right.kind !== "duration") return indeterminate("wrong-type", `cannot compare a 'duration' value with a '${right.kind}' value`);
|
|
94
|
-
return definite(applyComparisonOperator(op, toMilliseconds(left.value, left.unit), toMilliseconds(right.value, right.unit)));
|
|
95
|
-
case "complex":
|
|
96
|
-
if (op !== "eq" && op !== "neq") return indeterminate("wrong-type", `ordering operator '${op}' is not defined for complex values; the complex plane has no total order`);
|
|
97
|
-
if (right.kind !== "complex") return indeterminate("wrong-type", `cannot compare a 'complex' value with a '${right.kind}' value`);
|
|
98
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot compare complex values with incompatible units");
|
|
99
|
-
return definite(op === "eq" ? left.re === right.re && left.im === right.im : left.re !== right.re || left.im !== right.im);
|
|
100
|
-
default: throw new Error("unreachable computed-value kind");
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/** `textCompare`'s two operands must both resolve to the `text` computed-value kind -- any other kind, on either operand, is `wrong-type` (see the `textCompare` section of README.md). `equals`/`notEquals` are exact string equality; `matches`/`notMatches` interpret `right`'s text as an ECMAScript regular expression tested against `left`'s text; `portableMatches`/`portableNotMatches` interpret it as a pattern in `trilean-regex`'s own restricted grammar instead, matched by that package's finite-automaton reference matcher rather than the host's native `RegExp` engine -- see the `textCompare` section of README.md for when to reach for the portable pair instead of the plain one. An invalid pattern is `wrong-type` rather than a thrown exception either way -- every data-quality problem stays inside the `Evaluation` result, per `Evaluation<T>`'s own doc comment in evaluation.ts. */
|
|
104
|
-
function compareText(op, left, right) {
|
|
105
|
-
if (left.kind !== "text") return indeterminate("wrong-type", `'textCompare' requires 'text' operands; the left operand is '${left.kind}'`);
|
|
106
|
-
if (right.kind !== "text") return indeterminate("wrong-type", `'textCompare' requires 'text' operands; the right operand is '${right.kind}'`);
|
|
107
|
-
switch (op) {
|
|
108
|
-
case "equals": return definite(left.value === right.value);
|
|
109
|
-
case "notEquals": return definite(left.value !== right.value);
|
|
110
|
-
case "matches":
|
|
111
|
-
case "notMatches": {
|
|
112
|
-
let pattern;
|
|
113
|
-
try {
|
|
114
|
-
pattern = new RegExp(right.value);
|
|
115
|
-
} catch {
|
|
116
|
-
return indeterminate("wrong-type", `'${right.value}' is not a valid regular expression pattern`);
|
|
117
|
-
}
|
|
118
|
-
const isMatch = pattern.test(left.value);
|
|
119
|
-
return definite(op === "matches" ? isMatch : !isMatch);
|
|
120
|
-
}
|
|
121
|
-
case "portableMatches":
|
|
122
|
-
case "portableNotMatches": {
|
|
123
|
-
let compiled;
|
|
124
|
-
try {
|
|
125
|
-
compiled = compilePattern(right.value);
|
|
126
|
-
} catch (error) {
|
|
127
|
-
const reason = error instanceof RegexParseError ? error.message : String(error);
|
|
128
|
-
return indeterminate("wrong-type", `'${right.value}' is not a valid trilean-regex pattern: ${reason}`);
|
|
129
|
-
}
|
|
130
|
-
const isMatch = compiled.test(left.value);
|
|
131
|
-
return definite(op === "portableMatches" ? isMatch : !isMatch);
|
|
132
|
-
}
|
|
133
|
-
default: throw new Error("unreachable text comparison operator");
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
/** `memberOf`'s own value-equality test between two computed values -- kind-agnostic across `number`/`text`/`instant`/`duration` (see the `memberOf` section of README.md, and its "Derived aggregates" note that this equality is kind-agnostic across every computed-value kind), unlike `compare`'s own `eq`, which rejects a `text` operand outright and directs callers to `textCompare` instead. A kind mismatch, or a `number` pair with an incompatible unit, is `wrong-type` -- never simply "not equal". Narrowing `candidate` against a literal `operand.kind` case (rather than asserting it) is the same technique `compareValues` uses above. */
|
|
137
|
-
function computeMembershipMatch(operand, candidate) {
|
|
138
|
-
switch (operand.kind) {
|
|
139
|
-
case "number":
|
|
140
|
-
if (candidate.kind !== "number") return indeterminate("wrong-type", `cannot compare a 'number' value with a '${candidate.kind}' value for membership`);
|
|
141
|
-
if (!unitsEqual(operand.unit, candidate.unit)) return indeterminate("wrong-type", "cannot compare numbers with incompatible units for membership");
|
|
142
|
-
return definite(operand.value === candidate.value);
|
|
143
|
-
case "text":
|
|
144
|
-
if (candidate.kind !== "text") return indeterminate("wrong-type", `cannot compare a 'text' value with a '${candidate.kind}' value for membership`);
|
|
145
|
-
return definite(operand.value === candidate.value);
|
|
146
|
-
case "boolean":
|
|
147
|
-
if (candidate.kind !== "boolean") return indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${candidate.kind}' value for membership`);
|
|
148
|
-
return definite(operand.value === candidate.value);
|
|
149
|
-
case "instant": {
|
|
150
|
-
if (candidate.kind !== "instant") return indeterminate("wrong-type", `cannot compare an 'instant' value with a '${candidate.kind}' value for membership`);
|
|
151
|
-
const operandEpoch = toEpochMilliseconds(operand.value);
|
|
152
|
-
if (operandEpoch === void 0) return unparseableInstant(operand.value);
|
|
153
|
-
const candidateEpoch = toEpochMilliseconds(candidate.value);
|
|
154
|
-
if (candidateEpoch === void 0) return unparseableInstant(candidate.value);
|
|
155
|
-
return definite(operandEpoch === candidateEpoch);
|
|
156
|
-
}
|
|
157
|
-
case "duration":
|
|
158
|
-
if (candidate.kind !== "duration") return indeterminate("wrong-type", `cannot compare a 'duration' value with a '${candidate.kind}' value for membership`);
|
|
159
|
-
return definite(toMilliseconds(operand.value, operand.unit) === toMilliseconds(candidate.value, candidate.unit));
|
|
160
|
-
case "complex":
|
|
161
|
-
if (candidate.kind !== "complex") return indeterminate("wrong-type", `cannot compare a 'complex' value with a '${candidate.kind}' value for membership`);
|
|
162
|
-
if (!unitsEqual(operand.unit, candidate.unit)) return indeterminate("wrong-type", "cannot compare complex values with incompatible units for membership");
|
|
163
|
-
return definite(operand.re === candidate.re && operand.im === candidate.im);
|
|
164
|
-
default: throw new Error("unreachable computed-value kind");
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
/** `power`/`modulo` have no defined unit-combination rule in this design (unlike `add`/`subtract`'s "identical units" requirement or `multiply`/`divide`'s dimensional-exponent combination) -- scoping them to dimensionless operands avoids inventing an unspecified unit-scaling semantics for a fractional or runtime-determined exponent. */
|
|
168
|
-
function isDimensionless(unit) {
|
|
169
|
-
return unitsEqual(unit, void 0);
|
|
170
|
-
}
|
|
171
|
-
/** `negate` is never sugar for "zero minus the value" (see the `arithmetic`/`negate` section of README.md) -- a `duration`'s magnitude is negated directly, in its own original unit, with no subtraction or millisecond normalisation involved. */
|
|
172
|
-
function applyNegate(operand) {
|
|
173
|
-
switch (operand.kind) {
|
|
174
|
-
case "number": return definite({
|
|
175
|
-
kind: "number",
|
|
176
|
-
value: -operand.value,
|
|
177
|
-
unit: operand.unit
|
|
178
|
-
});
|
|
179
|
-
case "duration": return definite({
|
|
180
|
-
kind: "duration",
|
|
181
|
-
value: -operand.value,
|
|
182
|
-
unit: operand.unit
|
|
183
|
-
});
|
|
184
|
-
case "complex": return definite({
|
|
185
|
-
kind: "complex",
|
|
186
|
-
re: -operand.re,
|
|
187
|
-
im: -operand.im,
|
|
188
|
-
unit: operand.unit
|
|
189
|
-
});
|
|
190
|
-
case "text":
|
|
191
|
-
case "instant":
|
|
192
|
-
case "boolean": return indeterminate("wrong-type", `cannot negate a '${operand.kind}' value`);
|
|
193
|
-
default: throw new Error("unreachable computed-value kind");
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
function applyArithmeticOnNumbers(op, left, right) {
|
|
197
|
-
switch (op) {
|
|
198
|
-
case "add":
|
|
199
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot add numbers with incompatible units");
|
|
200
|
-
return definite({
|
|
201
|
-
kind: "number",
|
|
202
|
-
value: left.value + right.value,
|
|
203
|
-
unit: left.unit
|
|
204
|
-
});
|
|
205
|
-
case "subtract":
|
|
206
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot subtract numbers with incompatible units");
|
|
207
|
-
return definite({
|
|
208
|
-
kind: "number",
|
|
209
|
-
value: left.value - right.value,
|
|
210
|
-
unit: left.unit
|
|
211
|
-
});
|
|
212
|
-
case "multiply": return definite({
|
|
213
|
-
kind: "number",
|
|
214
|
-
value: left.value * right.value,
|
|
215
|
-
unit: combineUnitsForMultiply(left.unit, right.unit)
|
|
216
|
-
});
|
|
217
|
-
case "divide":
|
|
218
|
-
if (right.value === 0) return indeterminate("domain-error", "division by zero");
|
|
219
|
-
return definite({
|
|
220
|
-
kind: "number",
|
|
221
|
-
value: left.value / right.value,
|
|
222
|
-
unit: combineUnitsForDivide(left.unit, right.unit)
|
|
223
|
-
});
|
|
224
|
-
case "power":
|
|
225
|
-
if (!isDimensionless(left.unit) || !isDimensionless(right.unit)) return indeterminate("wrong-type", "'power' requires dimensionless operands");
|
|
226
|
-
if (left.value < 0 && !Number.isInteger(right.value)) return indeterminate("domain-error", "a negative base raised to a non-integer power is not a real number");
|
|
227
|
-
if (left.value === 0 && right.value < 0) return indeterminate("domain-error", "zero raised to a negative power is a division by zero");
|
|
228
|
-
return definite({
|
|
229
|
-
kind: "number",
|
|
230
|
-
value: left.value ** right.value
|
|
231
|
-
});
|
|
232
|
-
case "modulo":
|
|
233
|
-
if (!isDimensionless(left.unit) || !isDimensionless(right.unit)) return indeterminate("wrong-type", "'modulo' requires dimensionless operands");
|
|
234
|
-
if (right.value === 0) return indeterminate("domain-error", "modulo by zero");
|
|
235
|
-
return definite({
|
|
236
|
-
kind: "number",
|
|
237
|
-
value: left.value % right.value
|
|
238
|
-
});
|
|
239
|
-
default: throw new Error("unreachable arithmetic operator");
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
/** The only same-kind, non-`number` arithmetic this design defines: two `duration`s combine by normalising both to milliseconds first (see `toMilliseconds`), reporting the result in milliseconds -- `multiply`/`divide`/`power`/`modulo` have no representable result unit for a `duration` squared or a dimensionless ratio, so they are `wrong-type` rather than invented. */
|
|
243
|
-
function applyArithmeticOnDurations(op, left, right) {
|
|
244
|
-
switch (op) {
|
|
245
|
-
case "add": return definite({
|
|
246
|
-
kind: "duration",
|
|
247
|
-
value: toMilliseconds(left.value, left.unit) + toMilliseconds(right.value, right.unit),
|
|
248
|
-
unit: "ms"
|
|
249
|
-
});
|
|
250
|
-
case "subtract": return definite({
|
|
251
|
-
kind: "duration",
|
|
252
|
-
value: toMilliseconds(left.value, left.unit) - toMilliseconds(right.value, right.unit),
|
|
253
|
-
unit: "ms"
|
|
254
|
-
});
|
|
255
|
-
case "multiply":
|
|
256
|
-
case "divide":
|
|
257
|
-
case "power":
|
|
258
|
-
case "modulo": return indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between two 'duration' values`);
|
|
259
|
-
default: throw new Error("unreachable arithmetic operator");
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
/** Every real number is a complex number with a zero imaginary part, so promoting one is exact and total -- unlike the temporal cross-kind combinations above, which each had to be enumerated because no such embedding exists between an `instant` and a `duration`. This is what lets a tree mix real and complex terms freely instead of forcing every real literal to be written as a complex one. */
|
|
263
|
-
function toComplexValue(value) {
|
|
264
|
-
if (value.kind === "complex") return value;
|
|
265
|
-
return {
|
|
266
|
-
kind: "complex",
|
|
267
|
-
re: value.value,
|
|
268
|
-
im: 0,
|
|
269
|
-
unit: value.unit
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
/** The complex product, as its own component-level helper rather than only a branch of the operator switch below, because `power`'s repeated multiplication needs exactly this and must not re-derive it. */
|
|
273
|
-
function multiplyComplexValues(left, right) {
|
|
274
|
-
return {
|
|
275
|
-
kind: "complex",
|
|
276
|
-
re: left.re * right.re - left.im * right.im,
|
|
277
|
-
im: left.re * right.im + left.im * right.re,
|
|
278
|
-
unit: combineUnitsForMultiply(left.unit, right.unit)
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
/** Complex arithmetic, over the one canonical rectangular representation the `complex` kind stores (see the "Complex values" section of README.md). `add`/`subtract` are component-wise and carry the same identical-units requirement real numbers already have. `power` is deliberately excluded from this operator set rather than handled and rejected here: its exponent must stay an un-promoted real number, so the dispatcher routes it to `applyComplexPower` first, and excluding it from the type is what makes the compiler enforce that routing instead of leaving a dead branch behind. */
|
|
282
|
-
function applyArithmeticOnComplex(op, left, right) {
|
|
283
|
-
switch (op) {
|
|
284
|
-
case "add":
|
|
285
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot add complex values with incompatible units");
|
|
286
|
-
return definite({
|
|
287
|
-
kind: "complex",
|
|
288
|
-
re: left.re + right.re,
|
|
289
|
-
im: left.im + right.im,
|
|
290
|
-
unit: left.unit
|
|
291
|
-
});
|
|
292
|
-
case "subtract":
|
|
293
|
-
if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot subtract complex values with incompatible units");
|
|
294
|
-
return definite({
|
|
295
|
-
kind: "complex",
|
|
296
|
-
re: left.re - right.re,
|
|
297
|
-
im: left.im - right.im,
|
|
298
|
-
unit: left.unit
|
|
299
|
-
});
|
|
300
|
-
case "multiply": return definite(multiplyComplexValues(left, right));
|
|
301
|
-
case "divide": {
|
|
302
|
-
const divisorSquaredMagnitude = right.re * right.re + right.im * right.im;
|
|
303
|
-
if (divisorSquaredMagnitude === 0) return indeterminate("domain-error", "division by zero");
|
|
304
|
-
return definite({
|
|
305
|
-
kind: "complex",
|
|
306
|
-
re: (left.re * right.re + left.im * right.im) / divisorSquaredMagnitude,
|
|
307
|
-
im: (left.im * right.re - left.re * right.im) / divisorSquaredMagnitude,
|
|
308
|
-
unit: combineUnitsForDivide(left.unit, right.unit)
|
|
309
|
-
});
|
|
310
|
-
}
|
|
311
|
-
case "modulo": return indeterminate("domain-error", "'modulo' is undefined for complex values");
|
|
312
|
-
default: throw new Error("unreachable arithmetic operator");
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
/** `power` with a complex operand on either side, defined for exactly one case: a real integer exponent, evaluated as the repeated multiplication that integer exponentiation *is* (see the "Complex values" section of README.md for why an arbitrary complex exponent stays out of scope). */
|
|
316
|
-
function applyComplexPower(base, exponent) {
|
|
317
|
-
if (exponent.kind !== "number" || !Number.isInteger(exponent.value)) return indeterminate("wrong-type", "'power' with a complex operand requires a real integer exponent");
|
|
318
|
-
if (!isDimensionless(base.unit) || !isDimensionless(exponent.unit)) return indeterminate("wrong-type", "'power' requires dimensionless operands");
|
|
319
|
-
const complexUnit = {
|
|
320
|
-
kind: "complex",
|
|
321
|
-
re: 1,
|
|
322
|
-
im: 0,
|
|
323
|
-
unit: {}
|
|
324
|
-
};
|
|
325
|
-
const complexBase = toComplexValue(base);
|
|
326
|
-
let repeatedProduct = complexUnit;
|
|
327
|
-
for (let applied = 0; applied < Math.abs(exponent.value); applied += 1) repeatedProduct = multiplyComplexValues(repeatedProduct, complexBase);
|
|
328
|
-
if (exponent.value >= 0) return definite(repeatedProduct);
|
|
329
|
-
return applyArithmeticOnComplex("divide", complexUnit, repeatedProduct);
|
|
330
|
-
}
|
|
331
|
-
/**
|
|
332
|
-
* Dispatches `arithmetic` by operand kind. The three cross-kind temporal combinations this design defines (`instant - instant`, `instant + duration`, `duration + instant`) are checked explicitly first, in that order, against the exact operator each requires; any other combination touching an `instant` is `wrong-type` (see "Temporal values" in README.md -- e.g. adding two instants, or subtracting a `duration` from an `instant`, are deliberately *not* defined). Same-kind `duration`/`duration` combinations are delegated to `applyArithmeticOnDurations`; a `duration` paired with anything other than an `instant` or another `duration` is `wrong-type`. Everything remaining requires two `number` operands.
|
|
333
|
-
*/
|
|
334
|
-
function applyArithmetic(op, left, right) {
|
|
335
|
-
if (left.kind === "instant" && right.kind === "instant" && op === "subtract") {
|
|
336
|
-
const leftEpoch = toEpochMilliseconds(left.value);
|
|
337
|
-
if (leftEpoch === void 0) return unparseableInstant(left.value);
|
|
338
|
-
const rightEpoch = toEpochMilliseconds(right.value);
|
|
339
|
-
if (rightEpoch === void 0) return unparseableInstant(right.value);
|
|
340
|
-
return definite({
|
|
341
|
-
kind: "duration",
|
|
342
|
-
value: leftEpoch - rightEpoch,
|
|
343
|
-
unit: "ms"
|
|
344
|
-
});
|
|
345
|
-
}
|
|
346
|
-
if (left.kind === "instant" && right.kind === "duration" && op === "add") {
|
|
347
|
-
const leftEpoch = toEpochMilliseconds(left.value);
|
|
348
|
-
if (leftEpoch === void 0) return unparseableInstant(left.value);
|
|
349
|
-
return instantFromEpochMilliseconds(leftEpoch + toMilliseconds(right.value, right.unit));
|
|
350
|
-
}
|
|
351
|
-
if (left.kind === "duration" && right.kind === "instant" && op === "add") {
|
|
352
|
-
const rightEpoch = toEpochMilliseconds(right.value);
|
|
353
|
-
if (rightEpoch === void 0) return unparseableInstant(right.value);
|
|
354
|
-
return instantFromEpochMilliseconds(rightEpoch + toMilliseconds(left.value, left.unit));
|
|
355
|
-
}
|
|
356
|
-
if (left.kind === "instant" || right.kind === "instant") return indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
|
|
357
|
-
if (left.kind === "duration" && right.kind === "duration") return applyArithmeticOnDurations(op, left, right);
|
|
358
|
-
if (left.kind === "duration" || right.kind === "duration") return indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
|
|
359
|
-
if (left.kind !== "number" && left.kind !== "complex") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${left.kind}' value`);
|
|
360
|
-
if (right.kind !== "number" && right.kind !== "complex") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
|
|
361
|
-
if (left.kind === "complex" || right.kind === "complex") {
|
|
362
|
-
if (op === "power") return applyComplexPower(left, right);
|
|
363
|
-
return applyArithmeticOnComplex(op, toComplexValue(left), toComplexValue(right));
|
|
364
|
-
}
|
|
365
|
-
return applyArithmeticOnNumbers(op, left, right);
|
|
366
|
-
}
|
|
367
|
-
/** A defense-in-depth guard against a long acyclic `treeReference` chain exhausting the call stack -- distinct from, and layered on top of, the cycle detector below (`visitedTreeKeys`), which catches an actual repeat immediately and more precisely. */
|
|
368
|
-
const MAX_TREE_REFERENCE_DEPTH = 100;
|
|
369
|
-
/**
|
|
370
|
-
* Collection resolution shared by the quantifiers (`some`/`every`, below) and by `fold` (a later phase): resolves the opaque `collection` reference to its concrete candidate list via `resolvers.resolveCollection`, then evaluates each candidate's optional `filter` with that candidate as its own evaluation context and the accumulator reset to `undefined` -- see the README's "Evaluation context" and "Pre-filtering which items participate" sections. Deliberately stops short of deciding how an indeterminate filter combines with the rest of the surrounding node: `some`/`every` fold a filter-indeterminate item in as its own vote via the surrounding OR/AND absorption, while `fold` has no absorbing value at all and goes indeterminate outright on the same condition -- the two callers need genuinely different combination logic over these same per-item outcomes, so this helper only produces the outcomes and leaves combining them to the caller.
|
|
371
|
-
*/
|
|
372
|
-
async function resolveParticipatingItems(collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth) {
|
|
373
|
-
const candidates = await resolvers.resolveCollection(collection, context);
|
|
374
|
-
return Promise.all(candidates.map(async (item) => {
|
|
375
|
-
if (filter === void 0) return {
|
|
376
|
-
item,
|
|
377
|
-
filterOutcome: "include"
|
|
378
|
-
};
|
|
379
|
-
const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
|
|
380
|
-
if (filterResult.status === "indeterminate") return {
|
|
381
|
-
item,
|
|
382
|
-
filterOutcome: filterResult
|
|
383
|
-
};
|
|
384
|
-
return {
|
|
385
|
-
item,
|
|
386
|
-
filterOutcome: filterResult.value ? "include" : "exclude"
|
|
387
|
-
};
|
|
388
|
-
}));
|
|
389
|
-
}
|
|
390
|
-
/** The first participating item (in declared collection order) whose `filter` evaluation was itself indeterminate, or `undefined` if every participating item's filter resolved definitely -- a filter-excluded item's own `"exclude"` outcome never counts here. Used only by `fold`, which -- unlike `some`/`every`'s OR/AND absorption -- has no absorbing value at all: any participating item's indeterminate filter makes the whole fold indeterminate outright, with no other item's outcome able to override it. */
|
|
391
|
-
function firstFilterIndeterminate(participating) {
|
|
392
|
-
for (const { filterOutcome } of participating) {
|
|
393
|
-
if (filterOutcome === "include" || filterOutcome === "exclude") continue;
|
|
394
|
-
if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
|
|
11
|
+
async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
|
|
12
|
+
const budgetExceeded = budget.checkNode(nestingDepth);
|
|
13
|
+
if (budgetExceeded !== void 0) return budgetExceeded;
|
|
398
14
|
switch (node.kind) {
|
|
399
15
|
case "not": {
|
|
400
|
-
const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
16
|
+
const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
401
17
|
if (operand.status === "indeterminate") return operand;
|
|
402
18
|
return definite(!operand.value);
|
|
403
19
|
}
|
|
404
20
|
case "and": {
|
|
405
|
-
const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
|
|
21
|
+
const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
|
|
406
22
|
return combineAnd(left, right);
|
|
407
23
|
}
|
|
408
24
|
case "or": {
|
|
409
|
-
const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
|
|
25
|
+
const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
|
|
410
26
|
return combineOr(left, right);
|
|
411
27
|
}
|
|
412
|
-
case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)))).reduce(combineAnd, definite(true));
|
|
413
|
-
case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)))).reduce(combineOr, definite(false));
|
|
28
|
+
case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)))).reduce(combineAnd, definite(true));
|
|
29
|
+
case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)))).reduce(combineOr, definite(false));
|
|
414
30
|
case "compare": {
|
|
415
|
-
const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
|
|
31
|
+
const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
|
|
416
32
|
if (left.status === "indeterminate") return left;
|
|
417
33
|
if (right.status === "indeterminate") return right;
|
|
418
34
|
return compareValues(node.op, left.value, right.value);
|
|
419
35
|
}
|
|
420
36
|
case "textCompare": {
|
|
421
|
-
const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
|
|
37
|
+
const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
|
|
422
38
|
if (left.status === "indeterminate") return left;
|
|
423
39
|
if (right.status === "indeterminate") return right;
|
|
424
40
|
return compareText(node.op, left.value, right.value);
|
|
425
41
|
}
|
|
426
42
|
case "memberOf": {
|
|
427
|
-
const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
43
|
+
const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
428
44
|
if (operandResult.status === "indeterminate") return operandResult;
|
|
429
45
|
const candidateOutcomes = await Promise.all(node.candidates.map(async (candidate) => {
|
|
430
|
-
const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
46
|
+
const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
431
47
|
if (candidateResult.status === "indeterminate") return candidateResult;
|
|
432
48
|
return computeMembershipMatch(operandResult.value, candidateResult.value);
|
|
433
49
|
}));
|
|
@@ -440,17 +56,17 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
|
|
|
440
56
|
return definite(node.op === "notIn");
|
|
441
57
|
}
|
|
442
58
|
case "exists": {
|
|
443
|
-
const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
59
|
+
const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
444
60
|
if (operandResult.status === "indeterminate" && operandResult.reason.code === "not-found") return definite(false);
|
|
445
61
|
return definite(true);
|
|
446
62
|
}
|
|
447
63
|
case "some":
|
|
448
64
|
case "every": {
|
|
449
|
-
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
|
|
65
|
+
const participating = await resolveParticipatingItems(evaluatePredicateInternal, node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
450
66
|
const votes = (await Promise.all(participating.map(async ({ item, filterOutcome }) => {
|
|
451
67
|
if (filterOutcome === "exclude") return void 0;
|
|
452
68
|
if (filterOutcome !== "include") return filterOutcome;
|
|
453
|
-
return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
|
|
69
|
+
return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
454
70
|
}))).filter((vote) => vote !== void 0);
|
|
455
71
|
const combine = node.kind === "some" ? combineOr : combineAnd;
|
|
456
72
|
const identity = node.kind === "some" ? definite(false) : definite(true);
|
|
@@ -460,42 +76,38 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
|
|
|
460
76
|
if (resolvers.resolveTree === void 0) return indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
|
|
461
77
|
const keyString = JSON.stringify(node.key);
|
|
462
78
|
if (visitedTreeKeys.has(keyString)) return indeterminate("domain-error", "circular treeReference detected");
|
|
463
|
-
if (treeReferenceDepth >=
|
|
79
|
+
if (treeReferenceDepth >= 100) return indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
|
|
464
80
|
const resolution = await resolvers.resolveTree(node.key, context);
|
|
465
81
|
if (!resolution.found) return indeterminate("not-found", "treeReference key did not resolve to a tree");
|
|
466
82
|
const parsed = PredicateNodeSchema.safeParse(resolution.node);
|
|
467
83
|
if (!parsed.success) return indeterminate("wrong-type", "the referenced tree is not a valid PredicateNode");
|
|
468
|
-
return evaluatePredicateInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
|
|
84
|
+
return evaluatePredicateInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1, budget, nestingDepth + 1);
|
|
469
85
|
}
|
|
470
86
|
default: throw new Error("unreachable predicate node kind");
|
|
471
87
|
}
|
|
472
88
|
}
|
|
473
|
-
async function evaluateValueInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
|
|
89
|
+
async function evaluateValueInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
|
|
90
|
+
const budgetExceeded = budget.checkNode(nestingDepth);
|
|
91
|
+
if (budgetExceeded !== void 0) return budgetExceeded;
|
|
474
92
|
switch (node.kind) {
|
|
475
93
|
case "reference": {
|
|
476
94
|
const resolution = await resolvers.resolveValue(node.key, context);
|
|
477
95
|
if (!resolution.found) return indeterminate("not-found", `no value found for reference key ${JSON.stringify(node.key)}`);
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
if (!unitsEqual(node.unit, resolution.value.unit)) return indeterminate("wrong-type", "the resolved value's unit does not match the reference's expected unit");
|
|
481
|
-
}
|
|
96
|
+
const unitError = checkReferenceUnit(node.unit, resolution.value);
|
|
97
|
+
if (unitError !== void 0) return unitError;
|
|
482
98
|
return definite(resolution.value);
|
|
483
99
|
}
|
|
484
100
|
case "accumulator":
|
|
485
101
|
if (accumulator === void 0) return indeterminate("wrong-type", "accumulator used outside a reduce fold's combine expression");
|
|
486
102
|
return definite(accumulator);
|
|
487
103
|
case "call": {
|
|
488
|
-
const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
|
|
104
|
+
const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)));
|
|
489
105
|
const args = [];
|
|
490
106
|
for (const result of argResults) {
|
|
491
107
|
if (result.status === "indeterminate") return result;
|
|
492
108
|
args.push(result.value);
|
|
493
109
|
}
|
|
494
|
-
|
|
495
|
-
if (fn === void 0) return indeterminate("wrong-type", `no function registered under the name '${node.fn}'`);
|
|
496
|
-
const outcome = fn(args);
|
|
497
|
-
if ("domainError" in outcome) return indeterminate("domain-error", outcome.domainError);
|
|
498
|
-
return definite(outcome);
|
|
110
|
+
return invokeRegisteredFunction(functions, node.fn, args);
|
|
499
111
|
}
|
|
500
112
|
case "numberLiteral": return definite({
|
|
501
113
|
kind: "number",
|
|
@@ -528,18 +140,18 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
528
140
|
});
|
|
529
141
|
return definite(complexFromPolar(node.magnitude, node.phase, node.unit));
|
|
530
142
|
case "arithmetic": {
|
|
531
|
-
const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
|
|
143
|
+
const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
|
|
532
144
|
if (left.status === "indeterminate") return left;
|
|
533
145
|
if (right.status === "indeterminate") return right;
|
|
534
146
|
return applyArithmetic(node.op, left.value, right.value);
|
|
535
147
|
}
|
|
536
148
|
case "negate": {
|
|
537
|
-
const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
149
|
+
const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
538
150
|
if (operand.status === "indeterminate") return operand;
|
|
539
151
|
return applyNegate(operand.value);
|
|
540
152
|
}
|
|
541
153
|
case "lookup": {
|
|
542
|
-
const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
|
|
154
|
+
const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)));
|
|
543
155
|
const keyValues = [];
|
|
544
156
|
for (const result of keyResults) {
|
|
545
157
|
if (result.status === "indeterminate") return result;
|
|
@@ -552,15 +164,15 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
552
164
|
case "conditional": {
|
|
553
165
|
if ((node.hitPolicy ?? "first") === "first") {
|
|
554
166
|
for (const { when, then } of node.cases) {
|
|
555
|
-
const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
167
|
+
const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
556
168
|
if (whenResult.status === "indeterminate") return whenResult;
|
|
557
|
-
if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
169
|
+
if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
558
170
|
}
|
|
559
|
-
return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
171
|
+
return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
560
172
|
}
|
|
561
173
|
const evaluatedCases = await Promise.all(node.cases.map(async ({ when, then }) => ({
|
|
562
174
|
then,
|
|
563
|
-
whenResult: await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)
|
|
175
|
+
whenResult: await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)
|
|
564
176
|
})));
|
|
565
177
|
const matches = evaluatedCases.filter(({ whenResult }) => whenResult.status === "definite" && whenResult.value);
|
|
566
178
|
if (matches.length >= 2) return indeterminate("domain-error", "more than one case matched under the 'unique' hit policy");
|
|
@@ -570,11 +182,11 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
570
182
|
reason
|
|
571
183
|
};
|
|
572
184
|
const [match] = matches;
|
|
573
|
-
if (match === void 0) return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
574
|
-
return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
185
|
+
if (match === void 0) return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
186
|
+
return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
575
187
|
}
|
|
576
188
|
case "fold": {
|
|
577
|
-
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
|
|
189
|
+
const participating = await resolveParticipatingItems(evaluatePredicateInternal, node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
578
190
|
const filterIndeterminateReason = firstFilterIndeterminate(participating);
|
|
579
191
|
if (filterIndeterminateReason !== void 0) return {
|
|
580
192
|
status: "indeterminate",
|
|
@@ -582,11 +194,11 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
582
194
|
};
|
|
583
195
|
const includedItems = participating.filter(({ filterOutcome }) => filterOutcome === "include").map(({ item }) => item);
|
|
584
196
|
if (node.combiner.mode === "reduce") {
|
|
585
|
-
const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
|
|
197
|
+
const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
586
198
|
if (initialResult.status === "indeterminate") return initialResult;
|
|
587
199
|
let runningAccumulator = initialResult.value;
|
|
588
200
|
for (const item of includedItems) {
|
|
589
|
-
const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
201
|
+
const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
590
202
|
if (stepResult.status === "indeterminate") return stepResult;
|
|
591
203
|
runningAccumulator = stepResult.value;
|
|
592
204
|
}
|
|
@@ -596,7 +208,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
596
208
|
const dominatesOp = node.combiner.mode === "max" ? "gt" : "lt";
|
|
597
209
|
let runningExtremum;
|
|
598
210
|
for (const item of includedItems) {
|
|
599
|
-
const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
|
|
211
|
+
const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
|
|
600
212
|
if (itemResult.status === "indeterminate") return itemResult;
|
|
601
213
|
if (runningExtremum === void 0) {
|
|
602
214
|
runningExtremum = itemResult.value;
|
|
@@ -619,25 +231,15 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
619
231
|
if (resolvers.resolveTree === void 0) return indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
|
|
620
232
|
const keyString = JSON.stringify(node.key);
|
|
621
233
|
if (visitedTreeKeys.has(keyString)) return indeterminate("domain-error", "circular treeReference detected");
|
|
622
|
-
if (treeReferenceDepth >=
|
|
234
|
+
if (treeReferenceDepth >= 100) return indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
|
|
623
235
|
const resolution = await resolvers.resolveTree(node.key, context);
|
|
624
236
|
if (!resolution.found) return indeterminate("not-found", "treeReference key did not resolve to a tree");
|
|
625
237
|
const parsed = ExpressionNodeSchema.safeParse(resolution.node);
|
|
626
238
|
if (!parsed.success) return indeterminate("wrong-type", "the referenced tree is not a valid ExpressionNode");
|
|
627
|
-
return evaluateValueInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
|
|
239
|
+
return evaluateValueInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1, budget, nestingDepth + 1);
|
|
628
240
|
}
|
|
629
241
|
default: throw new Error("unreachable expression node kind");
|
|
630
242
|
}
|
|
631
243
|
}
|
|
632
|
-
/**
|
|
633
|
-
* Builds a bound `{ evaluatePredicate, evaluateValue }` pair over a caller-supplied function registry for `call` nodes -- the registry is bound once, at construction time, unlike `resolvers`, which are supplied fresh to every call. The bare module-level `evaluatePredicate`/`evaluateValue` exports below are `createEvaluator({})`'s output.
|
|
634
|
-
*/
|
|
635
|
-
function createEvaluator({ functions = emptyFunctionRegistry }) {
|
|
636
|
-
return {
|
|
637
|
-
evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0),
|
|
638
|
-
evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0)
|
|
639
|
-
};
|
|
640
|
-
}
|
|
641
|
-
const { evaluatePredicate, evaluateValue } = createEvaluator({});
|
|
642
244
|
//#endregion
|
|
643
|
-
export {
|
|
245
|
+
export { evaluatePredicateInternal, evaluateValueInternal };
|