metano-runtime 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +139 -0
- package/dist/system/equality.d.ts +8 -0
- package/dist/system/equality.js +13 -5
- package/dist/system/json/index.d.ts +1 -0
- package/dist/system/json/index.js +1 -0
- package/dist/system/json/union-guard-registry.d.ts +30 -0
- package/dist/system/json/union-guard-registry.js +34 -0
- package/dist/system/linq/expr-tree-visitor.d.ts +173 -0
- package/dist/system/linq/expr-tree-visitor.js +417 -0
- package/dist/system/linq/expr-tree.d.ts +56 -8
- package/dist/system/linq/index.d.ts +3 -1
- package/dist/system/linq/index.js +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -65,6 +65,145 @@ const result = Enumerable.from([1, 2, 3, 4, 5])
|
|
|
65
65
|
`lastOrDefault`, `single`, `singleOrDefault`, `any`, `all`, `count`, `sum`, `average`,
|
|
66
66
|
`min`, `max`, `minBy`, `maxBy`, `contains`, `aggregate`
|
|
67
67
|
|
|
68
|
+
### `linq()` — descriptor-based pipeline + provider introspection
|
|
69
|
+
|
|
70
|
+
For IQueryable-style scenarios, the runtime also exposes a tagged-descriptor
|
|
71
|
+
pipeline: each operator (`where`, `select`, `orderBy`, …) is a standalone
|
|
72
|
+
factory that returns a `{ kind, …closures, apply, queryable? }` descriptor.
|
|
73
|
+
`linq(source, ...stages)` runs the chain by calling each stage's `apply`,
|
|
74
|
+
returning a lazy `Iterable<T>` (or a scalar, for terminal-bearing chains).
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
import { getStages, linq, select, where } from "metano-runtime";
|
|
78
|
+
|
|
79
|
+
const query = linq(
|
|
80
|
+
users,
|
|
81
|
+
where((u) => u.age >= 18),
|
|
82
|
+
select((u) => u.name),
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
for (const name of query) {
|
|
86
|
+
console.log(name);
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
When the result is an object (the lazy `Iterable<T>` from a composition chain,
|
|
91
|
+
or any object-typed terminal result like `toArray`), the runtime attaches the
|
|
92
|
+
descriptor list at a non-enumerable symbol-keyed slot — `LINQ_STAGES`,
|
|
93
|
+
registered via `Symbol.for("metano-runtime/system/linq:stages")`. An
|
|
94
|
+
introspecting consumer (IQueryable provider, query planner, debugger) reads
|
|
95
|
+
it via `getStages`:
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
import { getStages, linq, select, where } from "metano-runtime";
|
|
99
|
+
|
|
100
|
+
const query = linq(items, where((x) => x.active), select((x) => x.name));
|
|
101
|
+
const stages = getStages(query); // [WhereOp, SelectOp] | undefined
|
|
102
|
+
|
|
103
|
+
if (stages) {
|
|
104
|
+
// walk `stages[i].queryable` (ExprTree) to translate into SQL / GraphQL / …
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Contract:
|
|
109
|
+
|
|
110
|
+
- The slot is **non-enumerable**, so `JSON.stringify`, `{ ...spread }`, and
|
|
111
|
+
`Object.keys` do not leak the chain into the wire shape.
|
|
112
|
+
- `getStages` returns `undefined` for primitive results (scalar terminals
|
|
113
|
+
like `count` / `sum`) and for values produced outside this runtime.
|
|
114
|
+
- The slot is scoped via `Symbol.for`, so multiple module copies (duplicate
|
|
115
|
+
npm resolutions) share the same key — `getStages` from any copy sees the
|
|
116
|
+
stages attached by any other.
|
|
117
|
+
- The closure side-channel (`stage.apply`) keeps working in parallel; a
|
|
118
|
+
provider that cannot introspect a given stage may fall back to it.
|
|
119
|
+
|
|
120
|
+
### `ExprTree` — queryable expression trees
|
|
121
|
+
|
|
122
|
+
When a LINQ chain opts into queryable mode (`IQueryable<T>` receiver or a
|
|
123
|
+
`[Queryable]` parameter on the C# side), the transpiler emits a paired
|
|
124
|
+
expression tree (`QueryableMeta`) alongside the closure. Providers walk the
|
|
125
|
+
tree by `kind` to translate predicates into SQL, OData, GraphQL, etc.
|
|
126
|
+
|
|
127
|
+
Supported node kinds today: `param`, `capture`, `literal`, `member`, `call`,
|
|
128
|
+
`binary`, `unary`, `conditional`, `new` (object-initializer projections
|
|
129
|
+
such as `select(u => new UserDto { Name = u.Name })`), and `lambda`
|
|
130
|
+
(nested arrows like `where(u => u.orders.some(o => o.active))`).
|
|
131
|
+
|
|
132
|
+
Param, capture, literal, and `new` nodes carry an optional **qualified**
|
|
133
|
+
`type` field shaped `{ name, from? }` — `name` is the simple identifier
|
|
134
|
+
the provider dispatches on, and `from` is the cross-package origin (the
|
|
135
|
+
`[EmitPackage]` id) when the type lives in another package. Local and
|
|
136
|
+
primitive types omit `from`. This disambiguates same-named types defined
|
|
137
|
+
in different packages without forcing providers to parse module paths.
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
// where((p: Product) => p.unitPrice >= minPrice)
|
|
141
|
+
//
|
|
142
|
+
// `Product` lives in another package consumed via [EmitPackage("inventory")];
|
|
143
|
+
// `number` is a primitive (no origin), so `from` is omitted.
|
|
144
|
+
{
|
|
145
|
+
kind: "binary",
|
|
146
|
+
op: ">=",
|
|
147
|
+
left: {
|
|
148
|
+
kind: "member",
|
|
149
|
+
target: { kind: "param", name: "p", type: { name: "Product", from: "inventory" } },
|
|
150
|
+
member: "unitPrice",
|
|
151
|
+
},
|
|
152
|
+
right: { kind: "capture", name: "minPrice", type: { name: "number" } },
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### `ExprTreeVisitor` — generic walker for IQueryable provider authors
|
|
157
|
+
|
|
158
|
+
`metano-runtime/system/linq` ships a stable visitor surface so providers
|
|
159
|
+
that translate `QueryableMeta` into another dialect (SQL, GraphQL, OData,
|
|
160
|
+
HTTP query strings) do **not** need to reimplement parameter scoping, the
|
|
161
|
+
recursive walker, captures lookup, or the primitive comparator. Three
|
|
162
|
+
entry points cover the common cases:
|
|
163
|
+
|
|
164
|
+
- `evaluateExprTree(tree, scope)` — pure JS evaluation. Default behavior
|
|
165
|
+
for mock / in-memory providers; resolves the param, looks up captures,
|
|
166
|
+
short-circuits boolean ops, mirrors JS semantics on arithmetic.
|
|
167
|
+
- `compileLambdaBody(meta, fallbackParamName?)` — wraps the evaluator
|
|
168
|
+
into a `(item) => unknown` predicate by closing over `meta.captures`.
|
|
169
|
+
Pass `fallbackParamName` (defaults to `"x"`) for literal-only bodies
|
|
170
|
+
that never mention the param.
|
|
171
|
+
- `ExprTreeVisitor<R>` — abstract base with one `visitX` method per node
|
|
172
|
+
kind. Default implementations recurse, so subclasses override only the
|
|
173
|
+
nodes they translate. Helpers `readParamName` and `compareValues` are
|
|
174
|
+
exported for providers that bypass the visitor.
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
import {
|
|
178
|
+
ExprTreeVisitor,
|
|
179
|
+
type ExprBinary,
|
|
180
|
+
type ExprLiteral,
|
|
181
|
+
type ExprMember,
|
|
182
|
+
type ExprParam,
|
|
183
|
+
} from "metano-runtime";
|
|
184
|
+
|
|
185
|
+
class SqlPredicate extends ExprTreeVisitor<string> {
|
|
186
|
+
protected override visitParam(node: ExprParam): string {
|
|
187
|
+
return node.name;
|
|
188
|
+
}
|
|
189
|
+
protected override visitLiteral(node: ExprLiteral): string {
|
|
190
|
+
return JSON.stringify(node.value);
|
|
191
|
+
}
|
|
192
|
+
protected override visitMember(node: ExprMember): string {
|
|
193
|
+
return `${this.visit(node.target)}.${node.member}`;
|
|
194
|
+
}
|
|
195
|
+
protected override visitBinary(node: ExprBinary): string {
|
|
196
|
+
return `(${this.visit(node.left)} ${node.op} ${this.visit(node.right)})`;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// new SqlPredicate().visit(meta.tree) → "(u.age >= 18)"
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
The array-backed sample (`targets/js/sample-queryable-arrays`) uses
|
|
204
|
+
`compileLambdaBody` directly — its provider is now ~50 LOC of stage
|
|
205
|
+
dispatch with all generic walker concerns delegated to the runtime.
|
|
206
|
+
|
|
68
207
|
### `UUID` — branded UUID type
|
|
69
208
|
|
|
70
209
|
A branded primitive that `System.Guid` maps to. At runtime it's literally a
|
|
@@ -36,3 +36,11 @@ export declare function equals(a: unknown, b: unknown): boolean;
|
|
|
36
36
|
* Cycle handling matches `equals` — undefined behavior on cyclic graphs.
|
|
37
37
|
*/
|
|
38
38
|
export declare function hashCode(value: unknown): number;
|
|
39
|
+
/**
|
|
40
|
+
* Alias the compiler emits inside synthesized record `equals` methods.
|
|
41
|
+
* Same contract as {@link equals}; the rename keeps the call
|
|
42
|
+
* sites readable next to the surrounding `equals(other)` method
|
|
43
|
+
* declaration (a bare `equals(this.x, other.x)` would shadow into a
|
|
44
|
+
* recursive method-call ambiguity for human readers).
|
|
45
|
+
*/
|
|
46
|
+
export declare const valueEquals: typeof equals;
|
package/dist/system/equality.js
CHANGED
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
* Mirror the C# .NET semantics: structural equality for compounds, NaN-equals-NaN for
|
|
4
4
|
* floats, custom `equals(other)` / `hashCode()` methods on user types take precedence.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
6
|
+
* The compiler also calls into {@link valueEquals} from synthesized record
|
|
7
|
+
* `equals` methods whenever a constructor parameter has a non-primitive type that
|
|
8
|
+
* exposes a value-equality contract (Decimal, Temporal types, nested records, …).
|
|
9
|
+
* The previous lowering used `===` for every field which silently diverged from C#
|
|
10
|
+
* semantics for value-wrapper types — see #202.
|
|
11
11
|
*/
|
|
12
12
|
import { HashCode } from "./hash-code.js";
|
|
13
13
|
/**
|
|
@@ -176,3 +176,11 @@ export function hashCode(value) {
|
|
|
176
176
|
// Primitives.
|
|
177
177
|
return HashCode.combine(value);
|
|
178
178
|
}
|
|
179
|
+
/**
|
|
180
|
+
* Alias the compiler emits inside synthesized record `equals` methods.
|
|
181
|
+
* Same contract as {@link equals}; the rename keeps the call
|
|
182
|
+
* sites readable next to the surrounding `equals(other)` method
|
|
183
|
+
* declaration (a bare `equals(this.x, other.x)` would shadow into a
|
|
184
|
+
* recursive method-call ambiguity for human readers).
|
|
185
|
+
*/
|
|
186
|
+
export const valueEquals = equals;
|
|
@@ -3,3 +3,4 @@ export { SerializerContext } from "./serializer-context.ts";
|
|
|
3
3
|
export { JsonSerializer, BoundSerializer } from "./json-serializer.ts";
|
|
4
4
|
export { PropertyNamingPolicy } from "./property-naming-policy.ts";
|
|
5
5
|
export { collectProperties } from "./converters.ts";
|
|
6
|
+
export { UnionGuardRegistry, registerUnionGuard, getUnionGuard, } from "./union-guard-registry.ts";
|
|
@@ -2,3 +2,4 @@ export { SerializerContext } from "./serializer-context.js";
|
|
|
2
2
|
export { JsonSerializer, BoundSerializer } from "./json-serializer.js";
|
|
3
3
|
export { PropertyNamingPolicy } from "./property-naming-policy.js";
|
|
4
4
|
export { collectProperties } from "./converters.js";
|
|
5
|
+
export { UnionGuardRegistry, registerUnionGuard, getUnionGuard, } from "./union-guard-registry.js";
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Late-bound dispatch table backing the `[StrictUnionGuard]` opt-in path
|
|
3
|
+
* for sealed-hierarchy guards.
|
|
4
|
+
*
|
|
5
|
+
* Generated code for an abstract base with `[StrictUnionGuard]` looks
|
|
6
|
+
* the variant guard up by discriminator value and delegates to it,
|
|
7
|
+
* giving callers full shape validation without forcing the base file to
|
|
8
|
+
* import every variant module (which would create an ESM cycle).
|
|
9
|
+
*
|
|
10
|
+
* Each variant module registers its guard at load time via
|
|
11
|
+
* `registerUnionGuard("Circle", isCircle)`. If a discriminator value has
|
|
12
|
+
* no entry — e.g., the variant module hasn't been loaded yet — the
|
|
13
|
+
* generated base guard falls back to accepting the discriminator-only
|
|
14
|
+
* narrow so the strict path is never more restrictive than the default.
|
|
15
|
+
*/
|
|
16
|
+
export declare const UnionGuardRegistry: Map<string, (value: unknown) => boolean>;
|
|
17
|
+
/**
|
|
18
|
+
* Registers a variant guard under its discriminator value. Idempotent:
|
|
19
|
+
* a re-registration overwrites the previous entry, which lets HMR and
|
|
20
|
+
* test fixtures replace a guard without resetting the whole map.
|
|
21
|
+
*/
|
|
22
|
+
export declare function registerUnionGuard(discriminator: string, guard: (value: unknown) => boolean): void;
|
|
23
|
+
/**
|
|
24
|
+
* Returns the variant guard registered for the given discriminator
|
|
25
|
+
* value, or `undefined` when no variant module has registered for it.
|
|
26
|
+
* Callers should treat the missing case as "fall back to a looser
|
|
27
|
+
* narrow" — never as a hard failure — so the strict path degrades
|
|
28
|
+
* gracefully when variant modules aren't loaded.
|
|
29
|
+
*/
|
|
30
|
+
export declare function getUnionGuard(discriminator: string): ((value: unknown) => boolean) | undefined;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Late-bound dispatch table backing the `[StrictUnionGuard]` opt-in path
|
|
3
|
+
* for sealed-hierarchy guards.
|
|
4
|
+
*
|
|
5
|
+
* Generated code for an abstract base with `[StrictUnionGuard]` looks
|
|
6
|
+
* the variant guard up by discriminator value and delegates to it,
|
|
7
|
+
* giving callers full shape validation without forcing the base file to
|
|
8
|
+
* import every variant module (which would create an ESM cycle).
|
|
9
|
+
*
|
|
10
|
+
* Each variant module registers its guard at load time via
|
|
11
|
+
* `registerUnionGuard("Circle", isCircle)`. If a discriminator value has
|
|
12
|
+
* no entry — e.g., the variant module hasn't been loaded yet — the
|
|
13
|
+
* generated base guard falls back to accepting the discriminator-only
|
|
14
|
+
* narrow so the strict path is never more restrictive than the default.
|
|
15
|
+
*/
|
|
16
|
+
export const UnionGuardRegistry = new Map();
|
|
17
|
+
/**
|
|
18
|
+
* Registers a variant guard under its discriminator value. Idempotent:
|
|
19
|
+
* a re-registration overwrites the previous entry, which lets HMR and
|
|
20
|
+
* test fixtures replace a guard without resetting the whole map.
|
|
21
|
+
*/
|
|
22
|
+
export function registerUnionGuard(discriminator, guard) {
|
|
23
|
+
UnionGuardRegistry.set(discriminator, guard);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Returns the variant guard registered for the given discriminator
|
|
27
|
+
* value, or `undefined` when no variant module has registered for it.
|
|
28
|
+
* Callers should treat the missing case as "fall back to a looser
|
|
29
|
+
* narrow" — never as a hard failure — so the strict path degrades
|
|
30
|
+
* gracefully when variant modules aren't loaded.
|
|
31
|
+
*/
|
|
32
|
+
export function getUnionGuard(discriminator) {
|
|
33
|
+
return UnionGuardRegistry.get(discriminator);
|
|
34
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic visitor surface over {@link ExprTree} — the IR shape the
|
|
3
|
+
* compiler emits next to every `[Queryable]` lambda. IQueryable
|
|
4
|
+
* provider authors extend this layer to translate the tree into SQL,
|
|
5
|
+
* GraphQL, OData, HTTP query strings, or any other dialect; they do
|
|
6
|
+
* **not** need to reimplement the recursive walker, parameter scoping,
|
|
7
|
+
* or the primitive comparator.
|
|
8
|
+
*
|
|
9
|
+
* Three entry points cover the common cases:
|
|
10
|
+
*
|
|
11
|
+
* - {@link evaluateExprTree} — pure JS evaluator. Resolves the param,
|
|
12
|
+
* reads captures, applies operators with the same semantics the
|
|
13
|
+
* closure path would have used. Mock / in-memory providers can use
|
|
14
|
+
* it as-is.
|
|
15
|
+
* - {@link compileLambdaBody} — wraps {@link evaluateExprTree} into a
|
|
16
|
+
* `(item) => unknown` predicate/selector by closing over the
|
|
17
|
+
* captures bundle and the lambda's first parameter name.
|
|
18
|
+
* - {@link ExprTreeVisitor} — abstract base with one `visitX` per node
|
|
19
|
+
* kind. The default implementations recurse, so subclasses override
|
|
20
|
+
* only the nodes they care about (e.g. a SQL emitter overrides
|
|
21
|
+
* {@link ExprTreeVisitor.visitBinary} to produce operators).
|
|
22
|
+
*
|
|
23
|
+
* The scope helpers ({@link readParamName}, {@link compareValues}) are
|
|
24
|
+
* exported because real providers usually need a parameter alias and a
|
|
25
|
+
* heterogeneous primitive ordering that matches the JS engine.
|
|
26
|
+
*/
|
|
27
|
+
import type { ExprBinary, ExprCall, ExprCapture, ExprConditional, ExprLambda, ExprLet, ExprLiteral, ExprMember, ExprNew, ExprParam, ExprRef, ExprTree, ExprUnary, QueryableMeta } from "./expr-tree.ts";
|
|
28
|
+
/**
|
|
29
|
+
* Lexical scope passed to {@link evaluateExprTree}. Mirrors the way
|
|
30
|
+
* the closure path resolved the lambda body: the param name is bound
|
|
31
|
+
* to the current item, captures are looked up by name in a flat
|
|
32
|
+
* record (the same shape the compiler emits in `QueryableMeta`).
|
|
33
|
+
*
|
|
34
|
+
* `refs` carries the values introduced by enclosing {@link ExprLet}
|
|
35
|
+
* bindings — the evaluator pushes one entry per binding when it
|
|
36
|
+
* descends into a `let` node and looks `ref` nodes up against this
|
|
37
|
+
* record. Callers normally leave it `undefined`; the evaluator
|
|
38
|
+
* materializes it on demand.
|
|
39
|
+
*/
|
|
40
|
+
export interface ExprTreeScope {
|
|
41
|
+
readonly paramName: string;
|
|
42
|
+
readonly paramValue: unknown;
|
|
43
|
+
readonly captures: Readonly<Record<string, unknown>>;
|
|
44
|
+
readonly refs?: Readonly<Record<string, unknown>>;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Recursive scan for the first {@link ExprParam} node bound at the
|
|
48
|
+
* *current* lambda level. Visits every child of every node kind so a
|
|
49
|
+
* predicate that mentions the parameter inside a conditional branch,
|
|
50
|
+
* a method-call argument, or any other nested position still
|
|
51
|
+
* resolves. Returns `null` when the body has no param reference —
|
|
52
|
+
* callers default to a fallback (typically `"x"`) so a literal-only
|
|
53
|
+
* body still materializes.
|
|
54
|
+
*
|
|
55
|
+
* Lambda / new boundaries are NOT crossed: a nested lambda binds its
|
|
56
|
+
* own param symbol, and walking through it would shadow the outer
|
|
57
|
+
* binding with the inner one. The outer caller (e.g.
|
|
58
|
+
* {@link compileLambdaBody}) is responsible for resolving the body
|
|
59
|
+
* of a top-level lambda before consulting this helper, if applicable.
|
|
60
|
+
*/
|
|
61
|
+
export declare function readParamName(tree: ExprTree): string | null;
|
|
62
|
+
/**
|
|
63
|
+
* Generic ordering comparator for heterogeneous primitives. Numbers,
|
|
64
|
+
* strings, and bigints fall through to the native `<`/`>` operators
|
|
65
|
+
* after a uniform cast — the same approach the runtime's `compareKeys`
|
|
66
|
+
* helper uses. Lets the dynamic evaluator compare values without
|
|
67
|
+
* burning `as any` casts into every binary branch.
|
|
68
|
+
*/
|
|
69
|
+
export declare function compareValues(left: unknown, right: unknown): number;
|
|
70
|
+
/**
|
|
71
|
+
* Evaluates an {@link ExprTree} against a scope and returns the JS
|
|
72
|
+
* value the tree denotes. Default behavior for mock providers; same
|
|
73
|
+
* semantics the closure path would have produced for the same lambda.
|
|
74
|
+
*
|
|
75
|
+
* Throws when the tree mentions a kind the MVP evaluator does not
|
|
76
|
+
* support (currently `lambda` / `new`) or when a `param` node's name
|
|
77
|
+
* does not match {@link ExprTreeScope.paramName}.
|
|
78
|
+
*/
|
|
79
|
+
export declare function evaluateExprTree(tree: ExprTree, scope: ExprTreeScope): unknown;
|
|
80
|
+
/**
|
|
81
|
+
* Closes over the captures bundle and returns a `(item) => unknown`
|
|
82
|
+
* function the caller can apply directly — predicate for `where`,
|
|
83
|
+
* projector for `select`, key selector for `orderBy`, etc.
|
|
84
|
+
*
|
|
85
|
+
* The parameter name is read from the first {@link ExprParam} node in
|
|
86
|
+
* `meta.tree`; pass {@link fallbackParamName} (defaults to `"x"`) to
|
|
87
|
+
* support literal-only bodies that never mention the param.
|
|
88
|
+
*/
|
|
89
|
+
export declare function compileLambdaBody(meta: QueryableMeta, fallbackParamName?: string): (item: unknown) => unknown;
|
|
90
|
+
/**
|
|
91
|
+
* Abstract visitor over {@link ExprTree}. Each `visitX` method handles
|
|
92
|
+
* one node kind. Default implementations recurse via {@link visit},
|
|
93
|
+
* so a subclass only overrides the methods it needs.
|
|
94
|
+
*
|
|
95
|
+
* Generic parameter `R` is the value the visitor produces — a SQL
|
|
96
|
+
* fragment, a GraphQL field, a JS value, an AST node in another IR,
|
|
97
|
+
* etc. Implementations decide how children's results combine in their
|
|
98
|
+
* override (e.g. a SQL emitter's `visitBinary` calls `this.visit(left)`
|
|
99
|
+
* and `this.visit(right)` and emits `(left) op (right)`).
|
|
100
|
+
*
|
|
101
|
+
* Example:
|
|
102
|
+
*
|
|
103
|
+
* ```ts
|
|
104
|
+
* class SqlPredicate extends ExprTreeVisitor<string> {
|
|
105
|
+
* protected visitBinary(node: ExprBinary): string {
|
|
106
|
+
* return `(${this.visit(node.left)} ${node.op} ${this.visit(node.right)})`;
|
|
107
|
+
* }
|
|
108
|
+
* protected visitMember(node: ExprMember): string {
|
|
109
|
+
* return `${this.visit(node.target)}.${node.member}`;
|
|
110
|
+
* }
|
|
111
|
+
* protected visitParam(node: ExprParam): string {
|
|
112
|
+
* return node.name;
|
|
113
|
+
* }
|
|
114
|
+
* protected visitLiteral(node: ExprLiteral): string {
|
|
115
|
+
* return JSON.stringify(node.value);
|
|
116
|
+
* }
|
|
117
|
+
* // capture / call / unary / conditional inherit the default recurse
|
|
118
|
+
* // behavior; override the ones the dialect actually translates.
|
|
119
|
+
* }
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
export declare abstract class ExprTreeVisitor<R> {
|
|
123
|
+
/**
|
|
124
|
+
* Dispatches to the appropriate `visitX` method. Subclasses can
|
|
125
|
+
* override to add tracing or to short-circuit on a specific node
|
|
126
|
+
* shape, but the default implementation is usually enough.
|
|
127
|
+
*/
|
|
128
|
+
visit(tree: ExprTree): R;
|
|
129
|
+
/**
|
|
130
|
+
* Combines the results of recursing into multiple children. Default
|
|
131
|
+
* returns the **last** result, which suits visitors that produce a
|
|
132
|
+
* value per node and only need the final aggregate (e.g. a side-effect
|
|
133
|
+
* collector). When the child list is empty (e.g. a free-function
|
|
134
|
+
* call with no args, an empty `new` expression), the visitor falls
|
|
135
|
+
* back to {@link leaf} so subclasses still get one well-defined
|
|
136
|
+
* extension point. Override to fold lists, concatenate strings, etc.
|
|
137
|
+
*/
|
|
138
|
+
protected combine(results: readonly R[]): R;
|
|
139
|
+
protected visitParam(_node: ExprParam): R;
|
|
140
|
+
protected visitCapture(_node: ExprCapture): R;
|
|
141
|
+
protected visitLiteral(_node: ExprLiteral): R;
|
|
142
|
+
protected visitMember(node: ExprMember): R;
|
|
143
|
+
protected visitCall(node: ExprCall): R;
|
|
144
|
+
protected visitBinary(node: ExprBinary): R;
|
|
145
|
+
protected visitUnary(node: ExprUnary): R;
|
|
146
|
+
protected visitConditional(node: ExprConditional): R;
|
|
147
|
+
protected visitLambda(node: ExprLambda): R;
|
|
148
|
+
protected visitNew(node: ExprNew): R;
|
|
149
|
+
/**
|
|
150
|
+
* Hoisted common-subexpression wrapper produced by the compiler
|
|
151
|
+
* (#209). Default behavior recurses through every binding value
|
|
152
|
+
* (in declaration order) and then the body, threading the children
|
|
153
|
+
* through {@link combine}.
|
|
154
|
+
*/
|
|
155
|
+
protected visitLet(node: ExprLet): R;
|
|
156
|
+
/**
|
|
157
|
+
* Reference to a binding introduced by an enclosing {@link ExprLet}.
|
|
158
|
+
* Default behavior is to treat it as a leaf — subclasses that build
|
|
159
|
+
* a SQL/expression dialect should override and emit the alias the
|
|
160
|
+
* matching binding generated.
|
|
161
|
+
*/
|
|
162
|
+
protected visitRef(_node: ExprRef): R;
|
|
163
|
+
/**
|
|
164
|
+
* Default result for true leaf nodes ({@link visitParam},
|
|
165
|
+
* {@link visitCapture}, {@link visitLiteral}) AND for interior
|
|
166
|
+
* nodes whose recurse-list is empty (e.g. a zero-arg method call,
|
|
167
|
+
* a `new` expression with no args and no initializers). Subclasses
|
|
168
|
+
* that inherit the default recurse must override <c>leaf</c> so
|
|
169
|
+
* {@link combine} has something to fold — the base throws to
|
|
170
|
+
* force a deliberate choice.
|
|
171
|
+
*/
|
|
172
|
+
protected leaf(): R;
|
|
173
|
+
}
|
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
/** Default fallback name used when a meta tree has no `param` node. */
|
|
2
|
+
const DEFAULT_PARAM_NAME = "x";
|
|
3
|
+
/**
|
|
4
|
+
* Recursive scan for the first {@link ExprParam} node bound at the
|
|
5
|
+
* *current* lambda level. Visits every child of every node kind so a
|
|
6
|
+
* predicate that mentions the parameter inside a conditional branch,
|
|
7
|
+
* a method-call argument, or any other nested position still
|
|
8
|
+
* resolves. Returns `null` when the body has no param reference —
|
|
9
|
+
* callers default to a fallback (typically `"x"`) so a literal-only
|
|
10
|
+
* body still materializes.
|
|
11
|
+
*
|
|
12
|
+
* Lambda / new boundaries are NOT crossed: a nested lambda binds its
|
|
13
|
+
* own param symbol, and walking through it would shadow the outer
|
|
14
|
+
* binding with the inner one. The outer caller (e.g.
|
|
15
|
+
* {@link compileLambdaBody}) is responsible for resolving the body
|
|
16
|
+
* of a top-level lambda before consulting this helper, if applicable.
|
|
17
|
+
*/
|
|
18
|
+
export function readParamName(tree) {
|
|
19
|
+
switch (tree.kind) {
|
|
20
|
+
case "param":
|
|
21
|
+
return tree.name;
|
|
22
|
+
case "capture":
|
|
23
|
+
case "literal":
|
|
24
|
+
case "lambda":
|
|
25
|
+
case "new":
|
|
26
|
+
case "ref":
|
|
27
|
+
return null;
|
|
28
|
+
case "member":
|
|
29
|
+
return readParamName(tree.target);
|
|
30
|
+
case "call":
|
|
31
|
+
return (tree.target ? readParamName(tree.target) : null) ?? firstParamName(tree.args);
|
|
32
|
+
case "binary":
|
|
33
|
+
return readParamName(tree.left) ?? readParamName(tree.right);
|
|
34
|
+
case "unary":
|
|
35
|
+
return readParamName(tree.operand);
|
|
36
|
+
case "conditional":
|
|
37
|
+
return (readParamName(tree.condition) ??
|
|
38
|
+
readParamName(tree.whenTrue) ??
|
|
39
|
+
readParamName(tree.whenFalse));
|
|
40
|
+
case "let":
|
|
41
|
+
// Bindings are pre-computed subtrees that may contain the param
|
|
42
|
+
// reference too (e.g. `$0 = x.profile.age`); scan them before
|
|
43
|
+
// falling through to the body so a hoisted root still produces
|
|
44
|
+
// the right parameter name.
|
|
45
|
+
for (const binding of tree.bindings) {
|
|
46
|
+
const found = readParamName(binding.value);
|
|
47
|
+
if (found !== null)
|
|
48
|
+
return found;
|
|
49
|
+
}
|
|
50
|
+
return readParamName(tree.body);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function firstParamName(args) {
|
|
54
|
+
for (const arg of args) {
|
|
55
|
+
const found = readParamName(arg);
|
|
56
|
+
if (found !== null)
|
|
57
|
+
return found;
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Generic ordering comparator for heterogeneous primitives. Numbers,
|
|
63
|
+
* strings, and bigints fall through to the native `<`/`>` operators
|
|
64
|
+
* after a uniform cast — the same approach the runtime's `compareKeys`
|
|
65
|
+
* helper uses. Lets the dynamic evaluator compare values without
|
|
66
|
+
* burning `as any` casts into every binary branch.
|
|
67
|
+
*/
|
|
68
|
+
export function compareValues(left, right) {
|
|
69
|
+
const a = left;
|
|
70
|
+
const b = right;
|
|
71
|
+
if (a < b)
|
|
72
|
+
return -1;
|
|
73
|
+
if (a > b)
|
|
74
|
+
return 1;
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Evaluates an {@link ExprTree} against a scope and returns the JS
|
|
79
|
+
* value the tree denotes. Default behavior for mock providers; same
|
|
80
|
+
* semantics the closure path would have produced for the same lambda.
|
|
81
|
+
*
|
|
82
|
+
* Throws when the tree mentions a kind the MVP evaluator does not
|
|
83
|
+
* support (currently `lambda` / `new`) or when a `param` node's name
|
|
84
|
+
* does not match {@link ExprTreeScope.paramName}.
|
|
85
|
+
*/
|
|
86
|
+
export function evaluateExprTree(tree, scope) {
|
|
87
|
+
switch (tree.kind) {
|
|
88
|
+
case "param":
|
|
89
|
+
return evaluateParam(tree, scope);
|
|
90
|
+
case "capture":
|
|
91
|
+
return evaluateCapture(tree, scope);
|
|
92
|
+
case "literal":
|
|
93
|
+
return tree.value;
|
|
94
|
+
case "member":
|
|
95
|
+
return evaluateMember(tree, scope);
|
|
96
|
+
case "call":
|
|
97
|
+
return evaluateCall(tree, scope);
|
|
98
|
+
case "binary":
|
|
99
|
+
return evaluateBinary(tree, scope);
|
|
100
|
+
case "unary":
|
|
101
|
+
return evaluateUnary(tree, scope);
|
|
102
|
+
case "conditional":
|
|
103
|
+
return evaluateExprTree(tree.condition, scope)
|
|
104
|
+
? evaluateExprTree(tree.whenTrue, scope)
|
|
105
|
+
: evaluateExprTree(tree.whenFalse, scope);
|
|
106
|
+
case "let":
|
|
107
|
+
return evaluateLet(tree, scope);
|
|
108
|
+
case "ref":
|
|
109
|
+
return evaluateRef(tree, scope);
|
|
110
|
+
case "lambda":
|
|
111
|
+
case "new":
|
|
112
|
+
throw new Error(`evaluateExprTree: kind '${tree.kind}' not supported in MVP`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Closes over the captures bundle and returns a `(item) => unknown`
|
|
117
|
+
* function the caller can apply directly — predicate for `where`,
|
|
118
|
+
* projector for `select`, key selector for `orderBy`, etc.
|
|
119
|
+
*
|
|
120
|
+
* The parameter name is read from the first {@link ExprParam} node in
|
|
121
|
+
* `meta.tree`; pass {@link fallbackParamName} (defaults to `"x"`) to
|
|
122
|
+
* support literal-only bodies that never mention the param.
|
|
123
|
+
*/
|
|
124
|
+
export function compileLambdaBody(meta, fallbackParamName = DEFAULT_PARAM_NAME) {
|
|
125
|
+
const captures = meta.captures ?? {};
|
|
126
|
+
// Top-level lambda meta: bind to the outer lambda's first param so
|
|
127
|
+
// nested lambdas (whose `params` would shadow it) cannot hijack the
|
|
128
|
+
// resolution via the body scan.
|
|
129
|
+
const topLevelParam = meta.tree.kind === "lambda" ? meta.tree.params[0]?.name : null;
|
|
130
|
+
const paramName = topLevelParam ?? readParamName(meta.tree) ?? fallbackParamName;
|
|
131
|
+
return (item) => evaluateExprTree(meta.tree, { paramName, paramValue: item, captures });
|
|
132
|
+
}
|
|
133
|
+
function evaluateParam(node, scope) {
|
|
134
|
+
if (node.name !== scope.paramName) {
|
|
135
|
+
throw new Error(`evaluateExprTree: param '${node.name}' does not match scope '${scope.paramName}'`);
|
|
136
|
+
}
|
|
137
|
+
return scope.paramValue;
|
|
138
|
+
}
|
|
139
|
+
function evaluateCapture(node, scope) {
|
|
140
|
+
if (!(node.name in scope.captures)) {
|
|
141
|
+
throw new Error(`evaluateExprTree: capture '${node.name}' missing from captures bundle`);
|
|
142
|
+
}
|
|
143
|
+
return scope.captures[node.name];
|
|
144
|
+
}
|
|
145
|
+
function evaluateMember(node, scope) {
|
|
146
|
+
const target = evaluateExprTree(node.target, scope);
|
|
147
|
+
if (target === null || target === undefined) {
|
|
148
|
+
// Mirror plain JS property-access semantics: reading a member off
|
|
149
|
+
// null/undefined throws a TypeError. The closure path the provider
|
|
150
|
+
// cross-checks against behaves the same way, so divergence here
|
|
151
|
+
// would silently mask bugs.
|
|
152
|
+
throw new TypeError(`evaluateExprTree: cannot read member '${node.member}' from ${target === null ? "null" : "undefined"}`);
|
|
153
|
+
}
|
|
154
|
+
return target[node.member];
|
|
155
|
+
}
|
|
156
|
+
function evaluateCall(node, scope) {
|
|
157
|
+
// Free-function calls (`target === null`) lack a runtime receiver in
|
|
158
|
+
// the MVP shape — providers that care can resolve them via captures
|
|
159
|
+
// or a global-scope override. Surfacing as unsupported here lets the
|
|
160
|
+
// surrounding stage fall back to the closure rather than guess.
|
|
161
|
+
if (node.target === null) {
|
|
162
|
+
throw new Error(`evaluateExprTree: free-function call '${node.method}' is not supported by the default evaluator`);
|
|
163
|
+
}
|
|
164
|
+
const target = evaluateExprTree(node.target, scope);
|
|
165
|
+
const args = node.args.map((a) => evaluateExprTree(a, scope));
|
|
166
|
+
if (target === null || target === undefined) {
|
|
167
|
+
throw new TypeError(`evaluateExprTree: cannot invoke '${node.method}' on ${target === null ? "null" : "undefined"}`);
|
|
168
|
+
}
|
|
169
|
+
const fn = target[node.method];
|
|
170
|
+
if (typeof fn !== "function") {
|
|
171
|
+
throw new Error(`evaluateExprTree: '${node.method}' is not callable on the resolved target`);
|
|
172
|
+
}
|
|
173
|
+
return fn.apply(target, args);
|
|
174
|
+
}
|
|
175
|
+
function evaluateBinary(node, scope) {
|
|
176
|
+
// Short-circuit boolean ops keep semantics aligned with the closure
|
|
177
|
+
// path; lazy evaluation matters when one side has side effects.
|
|
178
|
+
if (node.op === "&&") {
|
|
179
|
+
return (Boolean(evaluateExprTree(node.left, scope)) && Boolean(evaluateExprTree(node.right, scope)));
|
|
180
|
+
}
|
|
181
|
+
if (node.op === "||") {
|
|
182
|
+
return (Boolean(evaluateExprTree(node.left, scope)) || Boolean(evaluateExprTree(node.right, scope)));
|
|
183
|
+
}
|
|
184
|
+
const left = evaluateExprTree(node.left, scope);
|
|
185
|
+
const right = evaluateExprTree(node.right, scope);
|
|
186
|
+
switch (node.op) {
|
|
187
|
+
case "==":
|
|
188
|
+
// biome-ignore lint/suspicious/noDoubleEquals: predicate parity with C# == comparison
|
|
189
|
+
return left == right;
|
|
190
|
+
case "!=":
|
|
191
|
+
// biome-ignore lint/suspicious/noDoubleEquals: predicate parity with C# != comparison
|
|
192
|
+
return left != right;
|
|
193
|
+
case "<":
|
|
194
|
+
return compareValues(left, right) < 0;
|
|
195
|
+
case "<=":
|
|
196
|
+
return compareValues(left, right) <= 0;
|
|
197
|
+
case ">":
|
|
198
|
+
return compareValues(left, right) > 0;
|
|
199
|
+
case ">=":
|
|
200
|
+
return compareValues(left, right) >= 0;
|
|
201
|
+
case "+":
|
|
202
|
+
// `+` overloads on string concatenation in both C# and JS. The
|
|
203
|
+
// cast satisfies the type checker — the JS runtime falls back to
|
|
204
|
+
// string concatenation automatically when either operand is a
|
|
205
|
+
// string, matching the closure path.
|
|
206
|
+
return left + right;
|
|
207
|
+
case "-":
|
|
208
|
+
return left - right;
|
|
209
|
+
case "*":
|
|
210
|
+
return left * right;
|
|
211
|
+
case "/":
|
|
212
|
+
// C# `int / int` is integer division; JS `/` is always float.
|
|
213
|
+
// Bridging requires per-node int-vs-double type info the IR does
|
|
214
|
+
// not currently distinguish. The default evaluator mirrors JS
|
|
215
|
+
// semantics — float division — which matches what the closure
|
|
216
|
+
// path emits for the same predicate today.
|
|
217
|
+
return left / right;
|
|
218
|
+
case "%":
|
|
219
|
+
return left % right;
|
|
220
|
+
default:
|
|
221
|
+
throw new Error(`evaluateExprTree: unsupported binary op '${node.op}'`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
function evaluateLet(node, scope) {
|
|
225
|
+
// Evaluate bindings in declaration order so an earlier binding's
|
|
226
|
+
// value is visible to a later binding (matches how the compiler
|
|
227
|
+
// emits the $0/$1/… sequence).
|
|
228
|
+
const refs = { ...(scope.refs ?? {}) };
|
|
229
|
+
for (const binding of node.bindings) {
|
|
230
|
+
refs[binding.name] = evaluateExprTree(binding.value, { ...scope, refs });
|
|
231
|
+
}
|
|
232
|
+
return evaluateExprTree(node.body, { ...scope, refs });
|
|
233
|
+
}
|
|
234
|
+
function evaluateRef(node, scope) {
|
|
235
|
+
const refs = scope.refs;
|
|
236
|
+
if (refs === undefined || !(node.name in refs)) {
|
|
237
|
+
throw new Error(`evaluateExprTree: ref '${node.name}' resolves outside any enclosing let binding`);
|
|
238
|
+
}
|
|
239
|
+
return refs[node.name];
|
|
240
|
+
}
|
|
241
|
+
function evaluateUnary(node, scope) {
|
|
242
|
+
const operand = evaluateExprTree(node.operand, scope);
|
|
243
|
+
switch (node.op) {
|
|
244
|
+
case "!":
|
|
245
|
+
return !operand;
|
|
246
|
+
case "-":
|
|
247
|
+
return -operand;
|
|
248
|
+
case "+":
|
|
249
|
+
return +operand;
|
|
250
|
+
default:
|
|
251
|
+
throw new Error(`evaluateExprTree: unsupported unary op '${node.op}'`);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Abstract visitor over {@link ExprTree}. Each `visitX` method handles
|
|
256
|
+
* one node kind. Default implementations recurse via {@link visit},
|
|
257
|
+
* so a subclass only overrides the methods it needs.
|
|
258
|
+
*
|
|
259
|
+
* Generic parameter `R` is the value the visitor produces — a SQL
|
|
260
|
+
* fragment, a GraphQL field, a JS value, an AST node in another IR,
|
|
261
|
+
* etc. Implementations decide how children's results combine in their
|
|
262
|
+
* override (e.g. a SQL emitter's `visitBinary` calls `this.visit(left)`
|
|
263
|
+
* and `this.visit(right)` and emits `(left) op (right)`).
|
|
264
|
+
*
|
|
265
|
+
* Example:
|
|
266
|
+
*
|
|
267
|
+
* ```ts
|
|
268
|
+
* class SqlPredicate extends ExprTreeVisitor<string> {
|
|
269
|
+
* protected visitBinary(node: ExprBinary): string {
|
|
270
|
+
* return `(${this.visit(node.left)} ${node.op} ${this.visit(node.right)})`;
|
|
271
|
+
* }
|
|
272
|
+
* protected visitMember(node: ExprMember): string {
|
|
273
|
+
* return `${this.visit(node.target)}.${node.member}`;
|
|
274
|
+
* }
|
|
275
|
+
* protected visitParam(node: ExprParam): string {
|
|
276
|
+
* return node.name;
|
|
277
|
+
* }
|
|
278
|
+
* protected visitLiteral(node: ExprLiteral): string {
|
|
279
|
+
* return JSON.stringify(node.value);
|
|
280
|
+
* }
|
|
281
|
+
* // capture / call / unary / conditional inherit the default recurse
|
|
282
|
+
* // behavior; override the ones the dialect actually translates.
|
|
283
|
+
* }
|
|
284
|
+
* ```
|
|
285
|
+
*/
|
|
286
|
+
export class ExprTreeVisitor {
|
|
287
|
+
/**
|
|
288
|
+
* Dispatches to the appropriate `visitX` method. Subclasses can
|
|
289
|
+
* override to add tracing or to short-circuit on a specific node
|
|
290
|
+
* shape, but the default implementation is usually enough.
|
|
291
|
+
*/
|
|
292
|
+
visit(tree) {
|
|
293
|
+
switch (tree.kind) {
|
|
294
|
+
case "param":
|
|
295
|
+
return this.visitParam(tree);
|
|
296
|
+
case "capture":
|
|
297
|
+
return this.visitCapture(tree);
|
|
298
|
+
case "literal":
|
|
299
|
+
return this.visitLiteral(tree);
|
|
300
|
+
case "member":
|
|
301
|
+
return this.visitMember(tree);
|
|
302
|
+
case "call":
|
|
303
|
+
return this.visitCall(tree);
|
|
304
|
+
case "binary":
|
|
305
|
+
return this.visitBinary(tree);
|
|
306
|
+
case "unary":
|
|
307
|
+
return this.visitUnary(tree);
|
|
308
|
+
case "conditional":
|
|
309
|
+
return this.visitConditional(tree);
|
|
310
|
+
case "lambda":
|
|
311
|
+
return this.visitLambda(tree);
|
|
312
|
+
case "new":
|
|
313
|
+
return this.visitNew(tree);
|
|
314
|
+
case "let":
|
|
315
|
+
return this.visitLet(tree);
|
|
316
|
+
case "ref":
|
|
317
|
+
return this.visitRef(tree);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Combines the results of recursing into multiple children. Default
|
|
322
|
+
* returns the **last** result, which suits visitors that produce a
|
|
323
|
+
* value per node and only need the final aggregate (e.g. a side-effect
|
|
324
|
+
* collector). When the child list is empty (e.g. a free-function
|
|
325
|
+
* call with no args, an empty `new` expression), the visitor falls
|
|
326
|
+
* back to {@link leaf} so subclasses still get one well-defined
|
|
327
|
+
* extension point. Override to fold lists, concatenate strings, etc.
|
|
328
|
+
*/
|
|
329
|
+
combine(results) {
|
|
330
|
+
if (results.length === 0) {
|
|
331
|
+
return this.leaf();
|
|
332
|
+
}
|
|
333
|
+
// Non-null assertion is safe — we just guarded the empty case.
|
|
334
|
+
return results[results.length - 1];
|
|
335
|
+
}
|
|
336
|
+
visitParam(_node) {
|
|
337
|
+
return this.leaf();
|
|
338
|
+
}
|
|
339
|
+
visitCapture(_node) {
|
|
340
|
+
return this.leaf();
|
|
341
|
+
}
|
|
342
|
+
visitLiteral(_node) {
|
|
343
|
+
return this.leaf();
|
|
344
|
+
}
|
|
345
|
+
visitMember(node) {
|
|
346
|
+
// Single-child interior node still routes through `combine` so a
|
|
347
|
+
// subclass that overrides only `combine` (e.g. a SQL emitter that
|
|
348
|
+
// parenthesizes every interior node) sees every recurse path
|
|
349
|
+
// consistently — including the unary/member/lambda branches.
|
|
350
|
+
return this.combine([this.visit(node.target)]);
|
|
351
|
+
}
|
|
352
|
+
visitCall(node) {
|
|
353
|
+
const results = [];
|
|
354
|
+
if (node.target !== null)
|
|
355
|
+
results.push(this.visit(node.target));
|
|
356
|
+
for (const arg of node.args)
|
|
357
|
+
results.push(this.visit(arg));
|
|
358
|
+
return this.combine(results);
|
|
359
|
+
}
|
|
360
|
+
visitBinary(node) {
|
|
361
|
+
return this.combine([this.visit(node.left), this.visit(node.right)]);
|
|
362
|
+
}
|
|
363
|
+
visitUnary(node) {
|
|
364
|
+
return this.combine([this.visit(node.operand)]);
|
|
365
|
+
}
|
|
366
|
+
visitConditional(node) {
|
|
367
|
+
return this.combine([
|
|
368
|
+
this.visit(node.condition),
|
|
369
|
+
this.visit(node.whenTrue),
|
|
370
|
+
this.visit(node.whenFalse),
|
|
371
|
+
]);
|
|
372
|
+
}
|
|
373
|
+
visitLambda(node) {
|
|
374
|
+
return this.combine([this.visit(node.body)]);
|
|
375
|
+
}
|
|
376
|
+
visitNew(node) {
|
|
377
|
+
const results = node.args.map((a) => this.visit(a));
|
|
378
|
+
for (const init of node.initializers ?? []) {
|
|
379
|
+
results.push(this.visit(init.value));
|
|
380
|
+
}
|
|
381
|
+
return this.combine(results);
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Hoisted common-subexpression wrapper produced by the compiler
|
|
385
|
+
* (#209). Default behavior recurses through every binding value
|
|
386
|
+
* (in declaration order) and then the body, threading the children
|
|
387
|
+
* through {@link combine}.
|
|
388
|
+
*/
|
|
389
|
+
visitLet(node) {
|
|
390
|
+
const results = [];
|
|
391
|
+
for (const binding of node.bindings)
|
|
392
|
+
results.push(this.visit(binding.value));
|
|
393
|
+
results.push(this.visit(node.body));
|
|
394
|
+
return this.combine(results);
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Reference to a binding introduced by an enclosing {@link ExprLet}.
|
|
398
|
+
* Default behavior is to treat it as a leaf — subclasses that build
|
|
399
|
+
* a SQL/expression dialect should override and emit the alias the
|
|
400
|
+
* matching binding generated.
|
|
401
|
+
*/
|
|
402
|
+
visitRef(_node) {
|
|
403
|
+
return this.leaf();
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Default result for true leaf nodes ({@link visitParam},
|
|
407
|
+
* {@link visitCapture}, {@link visitLiteral}) AND for interior
|
|
408
|
+
* nodes whose recurse-list is empty (e.g. a zero-arg method call,
|
|
409
|
+
* a `new` expression with no args and no initializers). Subclasses
|
|
410
|
+
* that inherit the default recurse must override <c>leaf</c> so
|
|
411
|
+
* {@link combine} has something to fold — the base throws to
|
|
412
|
+
* force a deliberate choice.
|
|
413
|
+
*/
|
|
414
|
+
leaf() {
|
|
415
|
+
throw new Error("ExprTreeVisitor.leaf: no default leaf value — override visitParam/visitCapture/visitLiteral or leaf()");
|
|
416
|
+
}
|
|
417
|
+
}
|
|
@@ -18,12 +18,24 @@
|
|
|
18
18
|
*/
|
|
19
19
|
export type BinaryOp = "==" | "!=" | "<" | "<=" | ">" | ">=" | "+" | "-" | "*" | "/" | "%" | "&&" | "||" | "&" | "|" | "^" | "<<" | ">>";
|
|
20
20
|
export type UnaryOp = "!" | "-" | "+" | "~";
|
|
21
|
+
/**
|
|
22
|
+
* Qualified type reference attached to {@link ExprParam}, {@link ExprCapture},
|
|
23
|
+
* and {@link ExprLiteral} nodes. `name` is the simple identifier the provider
|
|
24
|
+
* uses for dispatch / column resolution; `from` is the cross-package origin
|
|
25
|
+
* (the `[EmitPackage]` id on the C# side) so providers can disambiguate two
|
|
26
|
+
* same-named types coming from different packages. Local and primitive types
|
|
27
|
+
* omit `from`.
|
|
28
|
+
*/
|
|
29
|
+
export interface ExprTypeRef {
|
|
30
|
+
readonly name: string;
|
|
31
|
+
readonly from?: string;
|
|
32
|
+
}
|
|
21
33
|
/** Reference to a lambda parameter — `(u) => …` introduces `u`. */
|
|
22
34
|
export interface ExprParam {
|
|
23
35
|
readonly kind: "param";
|
|
24
36
|
readonly name: string;
|
|
25
|
-
/**
|
|
26
|
-
readonly type?:
|
|
37
|
+
/** Qualified type emitted by the compiler when known. */
|
|
38
|
+
readonly type?: ExprTypeRef;
|
|
27
39
|
}
|
|
28
40
|
/**
|
|
29
41
|
* Reference to a closure-captured local — `(u) => u.age > minAge`
|
|
@@ -35,15 +47,15 @@ export interface ExprParam {
|
|
|
35
47
|
export interface ExprCapture {
|
|
36
48
|
readonly kind: "capture";
|
|
37
49
|
readonly name: string;
|
|
38
|
-
/**
|
|
39
|
-
readonly type?:
|
|
50
|
+
/** Qualified type emitted by the compiler when known. */
|
|
51
|
+
readonly type?: ExprTypeRef;
|
|
40
52
|
}
|
|
41
53
|
/** Constant value: literal, captured const, default. */
|
|
42
54
|
export interface ExprLiteral {
|
|
43
55
|
readonly kind: "literal";
|
|
44
56
|
readonly value: unknown;
|
|
45
|
-
/**
|
|
46
|
-
readonly type?:
|
|
57
|
+
/** Qualified type emitted by the compiler when known. */
|
|
58
|
+
readonly type?: ExprTypeRef;
|
|
47
59
|
}
|
|
48
60
|
/** Property / field access: `target.member`. */
|
|
49
61
|
export interface ExprMember {
|
|
@@ -87,15 +99,51 @@ export interface ExprLambda {
|
|
|
87
99
|
/** New-object: `new T { p = v, … }` or `new T(args)`. */
|
|
88
100
|
export interface ExprNew {
|
|
89
101
|
readonly kind: "new";
|
|
90
|
-
|
|
102
|
+
/**
|
|
103
|
+
* Qualified type emitted by the compiler when known. Same shape as the
|
|
104
|
+
* `type` field on {@link ExprParam} / {@link ExprCapture} / {@link ExprLiteral}
|
|
105
|
+
* so a provider can dispatch DTO constructors across packages via the
|
|
106
|
+
* combined `name + from` key.
|
|
107
|
+
*/
|
|
108
|
+
readonly type?: ExprTypeRef;
|
|
91
109
|
readonly args: readonly ExprTree[];
|
|
92
110
|
readonly initializers?: readonly {
|
|
93
111
|
readonly name: string;
|
|
94
112
|
readonly value: ExprTree;
|
|
95
113
|
}[];
|
|
96
114
|
}
|
|
115
|
+
/**
|
|
116
|
+
* Single `name = value` binding inside an {@link ExprLet}. Names are
|
|
117
|
+
* synthetic identifiers (`$0`, `$1`, …) chosen by the compiler's
|
|
118
|
+
* hoisting pass; their scope is the surrounding {@link ExprLet.body}.
|
|
119
|
+
*/
|
|
120
|
+
export interface ExprLetBinding {
|
|
121
|
+
readonly name: string;
|
|
122
|
+
readonly value: ExprTree;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Common-subexpression wrapper introduced by the compiler when a pure
|
|
126
|
+
* subtree repeats inside `body` — every previous occurrence is
|
|
127
|
+
* rewritten as an {@link ExprRef} pointing at the binding's `name`.
|
|
128
|
+
* Mirrors `let bindings in body` from functional IRs.
|
|
129
|
+
*/
|
|
130
|
+
export interface ExprLet {
|
|
131
|
+
readonly kind: "let";
|
|
132
|
+
readonly bindings: readonly ExprLetBinding[];
|
|
133
|
+
readonly body: ExprTree;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Reference to an {@link ExprLetBinding} introduced by an enclosing
|
|
137
|
+
* {@link ExprLet}. The evaluator resolves `name` against the nearest
|
|
138
|
+
* binding scope; providers translate it to the dialect's name for the
|
|
139
|
+
* shared value (a SQL alias, a query-string variable, …).
|
|
140
|
+
*/
|
|
141
|
+
export interface ExprRef {
|
|
142
|
+
readonly kind: "ref";
|
|
143
|
+
readonly name: string;
|
|
144
|
+
}
|
|
97
145
|
/** Discriminated union of every supported node. */
|
|
98
|
-
export type ExprTree = ExprParam | ExprCapture | ExprLiteral | ExprMember | ExprCall | ExprBinary | ExprUnary | ExprConditional | ExprLambda | ExprNew;
|
|
146
|
+
export type ExprTree = ExprParam | ExprCapture | ExprLiteral | ExprMember | ExprCall | ExprBinary | ExprUnary | ExprConditional | ExprLambda | ExprNew | ExprLet | ExprRef;
|
|
99
147
|
/**
|
|
100
148
|
* Bundle threaded by the compiler when an opt-in queryable surface is
|
|
101
149
|
* detected (`IQueryable<T>` receiver or `[Queryable]` attribute).
|
|
@@ -21,7 +21,9 @@
|
|
|
21
21
|
*/
|
|
22
22
|
export { LINQ_STAGES, getStages, linq, stages } from "./linq.ts";
|
|
23
23
|
export type { Stage } from "./linq.ts";
|
|
24
|
-
export type { BinaryOp, ExprBinary, ExprCall, ExprCapture, ExprConditional, ExprLambda, ExprLiteral, ExprMember, ExprNew, ExprParam, ExprTree, ExprUnary, QueryableMeta, UnaryOp, } from "./expr-tree.ts";
|
|
24
|
+
export type { BinaryOp, ExprBinary, ExprCall, ExprCapture, ExprConditional, ExprLambda, ExprLiteral, ExprMember, ExprNew, ExprParam, ExprTree, ExprTypeRef, ExprUnary, QueryableMeta, UnaryOp, } from "./expr-tree.ts";
|
|
25
|
+
export { ExprTreeVisitor, compareValues, compileLambdaBody, evaluateExprTree, readParamName, } from "./expr-tree-visitor.ts";
|
|
26
|
+
export type { ExprTreeScope } from "./expr-tree-visitor.ts";
|
|
25
27
|
export type { AnyOperator, AnyTerminal, OperatorBase, OperatorKind, TerminalBase, TerminalKind, AppendOp, ConcatOp, DistinctByOp, DistinctOp, GroupByOp, Grouping, OrderByDescendingOp, OrderByOp, ThenByDescendingOp, ThenByOp, PrependOp, ReverseOp, SelectManyOp, SelectOp, SkipOp, SkipWhileOp, TakeOp, TakeWhileOp, WhereOp, ZipOp, AggregateTerm, AllTerm, AnyTerm, AverageTerm, ContainsTerm, CountTerm, FirstOrDefaultTerm, FirstTerm, LastOrDefaultTerm, LastTerm, MaxTerm, MaxByTerm, MinTerm, MinByTerm, SingleTerm, SingleOrDefaultTerm, SumTerm, ToArrayTerm, ToMapTerm, ToSetTerm, } from "./types.ts";
|
|
26
28
|
export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, zip, } from "./operators.ts";
|
|
27
29
|
export { toArray, toMap, toSet, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, max, minBy, maxBy, average, contains, aggregate, } from "./terminals.ts";
|
|
@@ -20,5 +20,6 @@
|
|
|
20
20
|
* ```
|
|
21
21
|
*/
|
|
22
22
|
export { LINQ_STAGES, getStages, linq, stages } from "./linq.js";
|
|
23
|
+
export { ExprTreeVisitor, compareValues, compileLambdaBody, evaluateExprTree, readParamName, } from "./expr-tree-visitor.js";
|
|
23
24
|
export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, zip, } from "./operators.js";
|
|
24
25
|
export { toArray, toMap, toSet, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, max, minBy, maxBy, average, contains, aggregate, } from "./terminals.js";
|