-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.ts
More file actions
3655 lines (3452 loc) · 147 KB
/
codegen.ts
File metadata and controls
3655 lines (3452 loc) · 147 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { lookupOperator } from "./operators.ts";
import { closestNameTo } from "./levenshtein.ts";
import type {
BinaryOp,
Expr,
ArrayElement,
ObjectEntry,
CallArg,
SpreadElement,
KeyValueEntry,
MathMethod,
MathConstant,
ObjectMethod,
TypeCastOp,
AssignExpr,
UpdateOp,
UpdateFilter,
} from "./ast.ts";
export class CodegenError extends Error {
readonly pos: number;
constructor(message: string, pos: number = 0) {
super(message);
this.name = "CodegenError";
this.pos = pos;
}
}
/**
* Throw a `CodegenError` flagged as a jsmql bug. Use for invariants the
* parser is supposed to uphold — if a user ever sees one of these messages,
* something has slipped past the parser's validation and we want them to
* report it. Keeps the wording consistent across every internal-only throw
* site so they're trivially greppable.
*/
export function internalError(detail: string, pos: number = 0): never {
throw new CodegenError(`jsmql internal error (please report to the jsmql maintainers): ${detail}`, pos);
}
export class UnknownIdentifierError extends CodegenError {
identifier: string;
constructor(identifier: string, pos: number = 0) {
super(`Unknown identifier '${identifier}'. Did you mean '$.${identifier}'?`, pos);
this.name = "UnknownIdentifierError";
this.identifier = identifier;
}
}
// ── Context ───────────────────────────────────────────────────────────────────
export type GenerateCtx = {
lambdaParams: ReadonlySet<string>;
reduceRemap?: ReadonlyMap<string, string>;
/**
* Pipeline-scoped `let` bindings in scope. Key is the user-facing name; value
* is the field-path string to read it back (e.g. `"__jsmql.subtotal"` — no
* leading `$`, that gets prepended at lookup sites). Threaded through
* pipeline lowering by `pipeline.ts`; ignored in expression-mode codegen.
*/
pipelineLets?: ReadonlyMap<string, string>;
/**
* Names of lets that were dropped by an earlier scope-reshaping stage
* (`$group`, `$replaceRoot`, …). Value is the stage that dropped them, used
* to produce a precise "let X can't be read after $group" error rather than
* the generic "unknown identifier" fallback.
*/
droppedLets?: ReadonlyMap<string, string>;
/**
* Function-form parameter bindings in scope. Key is the destructured binding
* name; value is the raw JS value supplied at call time (already validated
* JSON-safe by `validateInterpolatable`). A `ParamRef` whose name lives here
* emits the value as an inline literal in the MQL output — the same shape
* the template-tag form produces from `${value}` interpolation. Bindings
* are *compile-time constants*, not document state, so unlike `pipelineLets`
* they cross sub-pipeline boundaries; `freshSubPipelineCtx` preserves them.
*/
bindings?: ReadonlyMap<string, unknown>;
/**
* Static type of selected in-scope lambda bindings. Currently populated only
* by the `.reduce()` codegen when both `initialValue` and the lambda body
* are statically the same compound type — see the reduce case below. Read by
* the `IndexAccess` codegen to skip the runtime `$cond` on `$isArray` when
* the receiver is a `ParamRef` whose name is in this map. Keyed by the
* user-facing param name (pre-`reduceRemap`), so the lookup happens on the
* raw AST `ParamRef.name` before any MQL variable-name remap.
*/
bindingTypes?: ReadonlyMap<string, "object" | "array">;
/**
* When true, suppress the auto-`$literal` wrap on `"$..."`-shaped string
* literals. Set by the `$literal(...)` operator codegen on the recursive
* call for its argument — the whole subtree is already inside a `$literal`
* envelope, so MongoDB will not interpret nested strings as field refs and
* a second wrap would produce a literal of a literal. Propagated through
* `extendCtx` so it survives lambda bodies and other ctx-modifying paths.
*/
insideLiteral?: boolean;
};
const EMPTY_CTX: GenerateCtx = { lambdaParams: new Set() };
function extendCtx(ctx: GenerateCtx, params: string[]): GenerateCtx {
return {
lambdaParams: new Set([...ctx.lambdaParams, ...params]),
reduceRemap: ctx.reduceRemap,
pipelineLets: ctx.pipelineLets,
droppedLets: ctx.droppedLets,
bindings: ctx.bindings,
bindingTypes: ctx.bindingTypes,
insideLiteral: ctx.insideLiteral,
};
}
/** Add a new pipeline let to the context. Returns a fresh ctx; never mutates. */
export function extendCtxLets(ctx: GenerateCtx, name: string, fieldPath: string): GenerateCtx {
const next = new Map(ctx.pipelineLets ?? []);
next.set(name, fieldPath);
return { ...ctx, pipelineLets: next };
}
/** Drop all pipeline lets, moving them to `droppedLets` with the stage name. */
export function clearCtxLets(ctx: GenerateCtx, droppedByStage: string): GenerateCtx {
if (!ctx.pipelineLets || ctx.pipelineLets.size === 0) return ctx;
const dropped = new Map(ctx.droppedLets ?? []);
for (const name of ctx.pipelineLets.keys()) dropped.set(name, droppedByStage);
return { ...ctx, pipelineLets: new Map(), droppedLets: dropped };
}
/** Public access for pipeline.ts to read the let-bindings count. */
export function ctxHasLets(ctx: GenerateCtx): boolean {
return (ctx.pipelineLets?.size ?? 0) > 0;
}
/**
* Construct a fresh ctx for sub-pipeline lowering. Outer `let` bindings do NOT
* cross — they're per-document state and the sub-pipeline starts against a
* different document (e.g. `$lookup.pipeline` runs against the foreign
* collection). Function-form `bindings` DO cross: they are compile-time
* constants, not document state, and inlining them inside a sub-pipeline is
* the same shape as the user writing the literal there directly.
*/
export function freshSubPipelineCtx(outer: GenerateCtx): GenerateCtx {
return { lambdaParams: new Set(), bindings: outer.bindings };
}
/** Return a fresh ctx with the given function-form parameter bindings applied. */
export function withBindings(ctx: GenerateCtx, bindings: ReadonlyMap<string, unknown>): GenerateCtx {
return { ...ctx, bindings };
}
/** Public re-export of EMPTY_CTX for pipeline.ts. */
export { EMPTY_CTX };
// ── String-producing helpers ──────────────────────────────────────────────────
// Operators whose return type is always a string — used for string-context + inference.
const STRING_OUTPUT_OPS = new Set([
"$toLower",
"$toUpper",
"$trim",
"$ltrim",
"$rtrim",
"$concat",
"$substrCP",
"$substrBytes",
"$substr",
"$replaceOne",
"$replaceAll",
"$dateToString",
"$type",
"$strcasecmp",
"$toString",
]);
// Method names that always return a string
const STRING_RETURNING_METHODS = new Set([
"trim",
"trimStart",
"trimEnd",
"trimLeft",
"trimRight",
"toLowerCase",
"toUpperCase",
"substr",
"substring",
"replace",
"replaceAll",
"charAt",
"toISOString",
"join",
"padStart",
"padEnd",
"repeat",
]);
// ── Array-producing helpers ───────────────────────────────────────────────────
// Operators whose return type is always an array
const ARRAY_OUTPUT_OPS = new Set([
"$split",
"$range",
"$reverseArray",
"$slice",
"$map",
"$filter",
"$concatArrays",
"$setUnion",
"$setIntersection",
"$setDifference",
"$zip",
"$objectToArray",
]);
// Method names that always return an array
const ARRAY_RETURNING_METHODS = new Set([
"split",
"map",
"filter",
"reverse",
"toReversed",
"toSorted",
"toSpliced",
"with",
"flat",
"flatMap",
]);
function isArrayProducing(expr: Expr): boolean {
switch (expr.type) {
case "ArrayLiteral":
return true;
case "OperatorCall":
return ARRAY_OUTPUT_OPS.has(expr.name);
case "MethodCall":
// `.slice` preserves receiver type — array→array, string→string.
if (expr.method === "slice") return isArrayProducing(expr.object);
return ARRAY_RETURNING_METHODS.has(expr.method);
case "ObjectCall":
return expr.method === "entries" || expr.method === "keys" || expr.method === "values";
default:
return false;
}
}
function isObjectProducing(expr: Expr): boolean {
return expr.type === "ObjectLiteral";
}
function isStringProducing(expr: Expr): boolean {
switch (expr.type) {
case "StringLiteral":
return true;
case "TemplateLiteral":
return true;
case "OperatorCall":
return STRING_OUTPUT_OPS.has(expr.name);
case "MethodCall":
// `.slice` preserves receiver type — array→array, string→string.
if (expr.method === "slice") return isStringProducing(expr.object);
return STRING_RETURNING_METHODS.has(expr.method);
case "TypeCast":
return expr.cast === "String";
case "TypeofExpr":
return true;
case "BinaryExpr":
if (expr.op === "+") {
const chain: Expr[] = [];
collectExprChain("+", expr, chain);
return chain.some((e) => isStringProducing(e));
}
return false;
default:
return false;
}
}
// ── JS truthy/falsy semantics ─────────────────────────────────────────────────
//
// JavaScript treats `false`, `null`, `undefined`, `0`, `""`, and `NaN` as
// falsy; everything else (including `[]` and `{}`) is truthy. MongoDB's
// $cond/$and/$or/$not/$toBool use a different rule (e.g. `""` is truthy in
// MQL). To make `&&`, `||`, `!`, `?:`, `Boolean()`, and predicate-method
// bodies match the JS semantics users expect, we wrap operands in `jsBool`.
//
// NaN: detecting NaN in MongoDB is expensive (its $eq treats NaN==NaN as
// true, so `$ne:[x,x]` does not work). NaN values are vanishingly rare in
// MongoDB collections, so we accept this divergence and document it.
// Operators whose return type is always a boolean — used to elide the jsBool
// wrap when an operand is already a boolean.
const BOOL_OUTPUT_OPS = new Set([
"$eq",
"$ne",
"$gt",
"$gte",
"$lt",
"$lte",
"$and",
"$or",
"$not",
"$in",
"$regexMatch",
"$isNumber",
"$isArray",
"$allElementsTrue",
"$anyElementTrue",
"$setEquals",
"$setIsSubset",
]);
// Method names whose codegen always emits a boolean.
const BOOL_RETURNING_METHODS = new Set(["includes", "startsWith", "endsWith", "every", "some"]);
/** True if the AST node always compiles to an MQL expression that evaluates
* to a boolean. When true we skip the jsBool wrap. */
function isProvablyBool(expr: Expr): boolean {
switch (expr.type) {
case "BooleanLiteral":
return true;
case "UnaryExpr":
return expr.op === "!";
case "BinaryExpr":
switch (expr.op) {
case "==":
case "===":
case "!=":
case "!==":
case "<":
case "<=":
case ">":
case ">=":
case "in":
return true;
case "&&":
case "||":
// JS `&&`/`||` are operand-preserving, so they're bool only when
// every operand is bool. Recurse — this matches the chain-level
// optimization in `generateLogical` which emits `$and`/`$or`
// (a bool) for all-bool chains.
return isProvablyBool(expr.left) && isProvablyBool(expr.right);
default:
return false;
}
case "TypeCast":
return expr.cast === "Boolean";
case "OperatorCall":
return BOOL_OUTPUT_OPS.has(expr.name);
case "MethodCall":
return BOOL_RETURNING_METHODS.has(expr.method);
default:
return false;
}
}
/** Wrap an already-generated MQL expression in a JS-truthy check.
* Returns true iff `value` is truthy under JS rules (false, null, missing,
* 0, "" → false; everything else → true; NaN treated as truthy — see note). */
function jsBool(value: unknown): unknown {
return {
$and: [
{ $ne: [value, null] }, // catches null AND missing — MongoDB treats them equal in $ne
{ $ne: [value, false] },
{ $ne: [value, ""] },
{ $ne: [value, 0] },
],
};
}
/** jsBool around a generated value, but elide if the source AST is already
* provably boolean. The AST is needed to do the elision check; the generated
* value is what gets emitted. Pass them both for the common case where
* callers have already invoked _generate(). */
function jsBoolIfNeeded(srcExpr: Expr, generated: unknown): unknown {
return isProvablyBool(srcExpr) ? generated : jsBool(generated);
}
/** True if `expr` resolves to a stable field/param/path (no computation,
* no side-effects, free to reference twice). Used by `&&`/`||` to decide
* whether the operand-preserving codegen needs a `$let` to bind once. */
function isPureRef(expr: Expr, ctx: GenerateCtx): boolean {
return asFieldPath(expr, ctx) !== null;
}
/** Pick a $let binding name that doesn't shadow any in-scope lambda param. */
function gensymInScope(ctx: GenerateCtx, base: string): string {
if (!ctx.lambdaParams.has(base)) return base;
for (let i = 2; ; i++) {
const name = `${base}${i}`;
if (!ctx.lambdaParams.has(name)) return name;
}
}
/**
* Clamp a string-index AST node to non-negative, matching JS `.substring`
* semantics where negative arguments are treated as 0. Folds at compile time
* when the node is a literal number (or unary-minus of one); otherwise wraps
* the generated value in `$max:[0, …]` so the runtime sees a non-negative
* index.
*/
function clampNonNegativeIndex(node: Expr, ctx: GenerateCtx): unknown {
if (node.type === "NumberLiteral") return Math.max(0, node.value);
if (node.type === "UnaryExpr" && node.op === "-" && node.operand.type === "NumberLiteral") {
return Math.max(0, -node.operand.value);
}
return { $max: [0, _generate(node, ctx)] };
}
/** Clamp a derived length value to non-negative, folding when known. */
function clampNonNegativeLength(value: unknown): unknown {
if (typeof value === "number") return Math.max(0, value);
return { $max: [0, value] };
}
/** Subtract `b` from `a`, folding when both operands are numeric literals. */
function foldedSubtract(a: unknown, b: unknown): unknown {
if (typeof a === "number" && typeof b === "number") return a - b;
return { $subtract: [a, b] };
}
/**
* Normalise a JS-style `.slice` index against a string length. JS treats
* negative indices as `len + idx`; MQL `$substrCP` rejects negatives. Folds
* literal negatives into `$strLenCP - n` at compile time; non-literals expand
* to a `$cond` that picks the form at runtime.
*
* `genObj` is reused for `$strLenCP` rather than re-generating from the
* source AST, so callers should pass the same generated value they use in
* the surrounding `$substrCP` call.
*/
function normaliseSliceIndex(node: Expr, ctx: GenerateCtx, genObj: unknown): unknown {
if (node.type === "NumberLiteral") {
if (node.value >= 0) return node.value;
return foldedSubtract({ $strLenCP: genObj }, -node.value);
}
if (node.type === "UnaryExpr" && node.op === "-" && node.operand.type === "NumberLiteral") {
return foldedSubtract({ $strLenCP: genObj }, node.operand.value);
}
const gen = _generate(node, ctx);
return { $cond: [{ $lt: [gen, 0] }, { $add: [gen, { $strLenCP: genObj }] }, gen] };
}
/** Lower `.slice` on a known-array (or fallback) receiver to MQL `$slice`. */
function sliceArray(genObj: unknown, exprArgs: Expr[], ctx: GenerateCtx): unknown {
if (exprArgs.length === 0) return genObj;
if (exprArgs.length === 1) return { $slice: [genObj, _generate(exprArgs[0], ctx)] };
return { $slice: [genObj, _generate(exprArgs[0], ctx), _generate(exprArgs[1], ctx)] };
}
/** Lower `.slice` on a known-string receiver to MQL `$substrCP`. */
function sliceString(genObj: unknown, exprArgs: Expr[], ctx: GenerateCtx): unknown {
if (exprArgs.length === 0) return genObj;
const start = normaliseSliceIndex(exprArgs[0], ctx, genObj);
if (exprArgs.length === 1) {
// For 1-arg `.slice(-n)` on a string, the length is exactly `n` (JS
// returns the last n characters). Fold that case so the output isn't
// a noisy `strLen - (strLen - n)`.
const negativeLiteral = negativeLiteralValue(exprArgs[0]);
if (negativeLiteral !== null) return { $substrCP: [genObj, start, negativeLiteral] };
return { $substrCP: [genObj, start, foldedSubtract({ $strLenCP: genObj }, start)] };
}
const end = normaliseSliceIndex(exprArgs[1], ctx, genObj);
return { $substrCP: [genObj, start, clampNonNegativeLength(foldedSubtract(end, start))] };
}
/** Return the absolute value of a negative numeric literal AST node, else null. */
function negativeLiteralValue(node: Expr): number | null {
if (node.type === "NumberLiteral" && node.value < 0) return -node.value;
if (node.type === "UnaryExpr" && node.op === "-" && node.operand.type === "NumberLiteral" && node.operand.value > 0) {
return node.operand.value;
}
return null;
}
/**
* Emit a string literal in a value position, auto-wrapping in `$literal` when
* the value would be misread by MongoDB as a field reference / system variable.
*
* In MongoDB aggregation expression context, any string value that starts with
* `$` is interpreted at query time — `"$foo"` reads field `foo`, `"$$NOW"` is
* the system variable. A user who writes the string literal `"$foo"` in jsmql
* source means the literal four-character string, not field access (they'd
* write `$.foo` for that). Wrap in `$literal` so the runtime keeps it intact.
*
* Suppressed when `ctx.insideLiteral` is set — we're already inside a
* `$literal(...)` envelope, MongoDB will not re-evaluate this subtree, and a
* second wrap would produce a literal-of-a-literal.
*/
function literalSafeString(value: string, ctx: GenerateCtx): unknown {
if (ctx.insideLiteral) return value;
if (value.length > 0 && value.charCodeAt(0) === 36 /* $ */) {
return { $literal: value };
}
return value;
}
/**
* Apply the same `$literal` safety net to a `jsmql.compile`/template-tag bound
* value as we do to user-written string literals: any `"$..."`-shaped string,
* at any nesting depth, gets wrapped so MongoDB doesn't read it as a field ref
* at runtime. Plain objects and arrays recurse; primitives pass through.
*
* `validateInterpolatable` has already rejected functions, symbols, BigInt,
* non-finite numbers, and circular references, so this walker only needs to
* handle JSON-shaped data — and opaque BSON instances (Date, RegExp,
* Uint8Array, ObjectId), which are passed through unchanged because they're
* the very values MongoDB's driver expects in-situ; walking them with
* `Object.entries` would silently strip them to `{}`.
*/
function safeBoundValue(value: unknown, ctx: GenerateCtx): unknown {
if (ctx.insideLiteral) return value;
if (typeof value === "string") return literalSafeString(value, ctx);
if (isOpaqueBsonValue(value)) return value;
if (Array.isArray(value)) return value.map((v) => safeBoundValue(v, ctx));
if (value !== null && typeof value === "object") {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value)) {
out[k] = safeBoundValue(v, ctx);
}
return out;
}
return value;
}
/**
* BSON instance values that the MongoDB driver consumes in-situ (i.e. the
* driver expects the actual JS object, not a JSON-shaped surrogate). They
* have no fidelity-preserving JSON representation: `JSON.stringify` returns
* `"{}"` for `RegExp` and `Uint8Array`, an ISO string for `Date` (which
* compares as a string in BSON, not a date), and `{}` for ObjectId.
*
* ObjectId is detected by `_bsontype` because importing the MongoDB driver
* would add a hard dependency the library deliberately avoids; the BSON
* library tags instances with `"ObjectID"` (older versions) or `"ObjectId"`
* (newer versions). Accept both.
*/
export function isOpaqueBsonValue(value: unknown): boolean {
if (value instanceof Date) return true;
if (value instanceof RegExp) return true;
if (value instanceof Uint8Array) return true;
if (typeof value === "object" && value !== null) {
const tag = (value as { _bsontype?: unknown })._bsontype;
if (tag === "ObjectID" || tag === "ObjectId") return true;
}
return false;
}
// ── Public API ────────────────────────────────────────────────────────────────
export function generate(expr: Expr): unknown {
return _generate(expr, EMPTY_CTX);
}
/** Generate an expression with an explicit context (e.g. pipeline-let bindings). */
export function generateWithCtx(expr: Expr, ctx: GenerateCtx): unknown {
return _generate(expr, ctx);
}
// ── Core generator ────────────────────────────────────────────────────────────
function _generate(expr: Expr, ctx: GenerateCtx): unknown {
return _generateBody(expr, ctx);
}
function _generateBody(expr: Expr, ctx: GenerateCtx): unknown {
// Defensive: parseGrouped may surface an AssignExpr through this path when
// it sees `($.x = expr)` — a parenthesized assignment. AssignExpr is not in
// the Expr union, but the cast in parseGrouped lets it flow here. Reject
// with a clear message so users debugging `1 + ($.a = 5)` see what's wrong.
const dynType = (expr as unknown as { type: string }).type;
if (dynType === "AssignExpr" || dynType === "DeleteStmt") {
throw new CodegenError(
`${dynType === "AssignExpr" ? "Assignment" : "delete"} is a statement, not a value. ` +
`It is only valid at the top level or as a pipeline-array element.`,
expr.pos,
);
}
if (dynType === "LetDecl") {
throw new CodegenError(
"`let` is a pipeline statement, not a value. " + "It is only valid at the top level of a pipeline.",
expr.pos,
);
}
switch (expr.type) {
case "NumberLiteral":
return expr.value;
case "BigIntLiteral":
return { $toLong: expr.value };
case "StringLiteral":
return literalSafeString(expr.value, ctx);
case "BooleanLiteral":
return expr.value;
case "NullLiteral":
return null;
case "FieldRef":
// Bare `$` (empty path) is the current document — MQL spells it `$$ROOT`.
// Nested paths (`$.a.b`) lower verbatim to `"$a.b"`.
return expr.path === "" ? "$$ROOT" : `$${expr.path}`;
case "CollectionRef":
// `$$.push(...)` is materialised into `$unionWith` stages,
// `$$.filter(...)` inside `$ = { ... }` is materialised into a `$facet`
// stage, and `$$ = <expr>` is materialised into `$match` (narrow) or
// `$limit: 0` + `$unionWith` (source switch) — all by `pipeline.ts`
// *before* codegen sees the surrounding expression. A bare
// `CollectionRef` reaching this case is a use outside those supported
// shapes — either `$$` was referenced as a value (in arithmetic, a
// Filter, an inline expression) or the statement-shaped form appeared
// in a non-statement position (on a RHS, inside another expression, etc.).
throw new CodegenError(
`'$$' (current collection) is statement-only and supports '.push(...)', '.filter(...)' in the facet pattern, and '$$ = <expr>' as a top-level assignment. ` +
`Write \`$$.push({...})\`, \`$$.push(...$$$.<coll>[.filter(pred)])\`, or \`$$.push($$$.<coll>.find(pred))\` ` +
`as a top-level Pipeline statement to append documents (lowers to '$unionWith'), ` +
`\`$ = { key1: $$.filter(p1), key2: $$.filter(p2), ... }\` to build a '$facet' stage, ` +
`or \`$$ = $$.filter(<pred>)\` / \`$$ = $$$.<coll>.filter(<pred>)\` to replace the current stream. ` +
`Bare '$$' has no value, and these statement shapes cannot appear on a RHS or inside another expression.`,
expr.pos,
);
case "DatabaseRef":
// The two supported uses of `$$$` are both materialised by `pipeline.ts`
// *before* codegen sees the surrounding expression:
// - `$$$.<coll>.find/filter(pred)` → `$lookup` stage (read).
// - `$$$.<coll> = <RHS>` → `$out` stage (write).
// Reaching this case means neither matched: the user wrote `$$$.<coll>`
// as a bare value, used the chain in an expression-only position (a
// Filter, `jsmql.expr`, an arithmetic operand), or used a method other
// than `.find/.filter` that the pre-materialisation walker didn't
// recognise.
throw new CodegenError(
`'$$$.<coll>' must be either followed by .find(pred) / .filter(pred) and consumed as a value (a $lookup read), ` +
`or assigned to as a destination ('$$$.<coll> = $$' → $out write). Bare '$$$' reference is not a value, ` +
`and these sugars are only valid in Pipeline mode (use \`;\`-separated statements or jsmql.pipeline()).`,
expr.pos,
);
case "ClusterRef":
// Like DatabaseRef: the two supported uses of `$$$$.<db>.<coll>` are
// `.find/.filter(pred)` (cross-db lookup) and `= <RHS>` (cross-db $out).
// Both are materialised pre-codegen. Reaching this case means a use
// outside those shapes (bare reference, expression-only position,
// wrong depth, dynamic db/coll names, etc.).
throw new CodegenError(
`'$$$$.<db>.<coll>' must be either followed by .find(pred) / .filter(pred) and consumed as a value (a cross-database $lookup), ` +
`or assigned to as a destination ('$$$$.<db>.<coll> = $$' → cross-database $out). Bare '$$$$' reference is not a value, ` +
`and these sugars are only valid in Pipeline mode (use \`;\`-separated statements or jsmql.pipeline()).`,
expr.pos,
);
case "ArrayLiteral":
return generateArrayLiteral(expr.elements, ctx, expr.pos);
case "ObjectLiteral":
return generateObjectLiteral(expr.entries, ctx, expr.pos);
case "TemplateLiteral":
return generateTemplateLiteral(expr.quasis, expr.expressions, ctx);
case "OperatorCall":
return generateOperatorCall(expr.name, expr.style, expr.args, ctx, expr.pos);
case "BinaryExpr":
return generateBinaryExpr(expr.op, expr.left, expr.right, ctx, expr.pos);
case "UnaryExpr":
return generateUnaryExpr(expr.op, expr.operand, ctx, expr.pos);
case "TernaryExpr":
return {
$cond: [
jsBoolIfNeeded(expr.condition, _generate(expr.condition, ctx)),
_generate(expr.consequent, ctx),
_generate(expr.alternate, ctx),
],
};
case "IndexAccess": {
// `obj[idx]` and `obj?.[idx]` produce the same AST shape; only the
// `optional` flag distinguishes them. Type-aware dispatch:
// known array (structural OR binding-typed) → $arrayElemAt
// known object (binding-typed only) → $getField
// unknown → runtime $cond between the two
// Binding-typed = the receiver is a `ParamRef` whose name lives in
// `ctx.bindingTypes` (populated today by `.reduce()` when initialValue
// and body agree on a compound type). The optional-chain `$ifNull`
// fallback matches the consumer: `[]` for array, `{}` for object so a
// missing path doesn't poison `$getField` with an array.
const rawObj = _generate(expr.object, ctx);
const idx = _generate(expr.index, ctx);
const optional = expr.optional || chainHasOptional(expr.object);
const known: "object" | "array" | undefined = isArrayProducing(expr.object)
? "array"
: expr.object.type === "ParamRef"
? ctx.bindingTypes?.get(expr.object.name)
: undefined;
if (known === "array") {
const obj = optional ? wrapIfNull(rawObj, []) : rawObj;
return { $arrayElemAt: [obj, idx] };
}
if (known === "object") {
const obj = optional ? wrapIfNull(rawObj, {}) : rawObj;
return { $getField: { field: idx, input: obj } };
}
const obj = optional ? wrapIfNull(rawObj, []) : rawObj;
return { $cond: [{ $isArray: obj }, { $arrayElemAt: [obj, idx] }, { $getField: { field: idx, input: obj } }] };
}
case "RegexLiteral":
// Method dispatch (e.g. `.match(/foo/)`, `/foo/.test(s)`) handles regex
// arguments and receivers directly, reading pattern + flags from the AST
// node before recursion. If we land here, the regex showed up in some
// other position (binary operand, ternary branch, $op argument value)
// where MQL has no concept of a regex value — silently returning the
// pattern string would lose the flags and surprise the user.
throw new CodegenError(
`Regex literals are only valid as arguments to .match(), .test(), .exec(), .matchAll(), and .search(). To pass a regex pattern as a string, use a string literal instead.`,
expr.pos,
);
case "ParamRef": {
// Resolution order (innermost wins):
// 1. `.reduce()` parameter remap (renamed to MQL's fixed $$value/$$this)
// 2. lambda parameter — emit `$$name`
// 3. pipeline `let` binding — emit `$<fieldPath>` (document field)
// 4. function-form parameter binding — emit the inlined literal value
// 5. dropped let — precise post-reshape error
// 6. otherwise — unknown identifier
// (3) and (4) are name-disjoint by construction (pipeline.ts rejects a
// `let` that shadows a function-form binding), so their relative order
// affects only the error path, not correctness for valid programs.
if (ctx.reduceRemap?.has(expr.name)) {
return `$$${ctx.reduceRemap.get(expr.name)!}`;
}
if (ctx.lambdaParams.has(expr.name)) {
return `$$${expr.name}`;
}
const letPath = ctx.pipelineLets?.get(expr.name);
if (letPath !== undefined) {
return `$${letPath}`;
}
if (ctx.bindings?.has(expr.name)) {
return safeBoundValue(ctx.bindings.get(expr.name), ctx);
}
const droppedBy = ctx.droppedLets?.get(expr.name);
if (droppedBy !== undefined) {
throw new CodegenError(
`\`${expr.name}\` is a \`let\` binding and can't be read after \`${droppedBy}\` — ` +
`the stage replaces the document. Inline the expression into the \`${droppedBy}\` body, ` +
`or rebind after the stage with another \`let\`.`,
expr.pos,
);
}
throw new UnknownIdentifierError(expr.name, expr.pos);
}
case "MemberAccess": {
if (expr.member === "length") {
const rawObj = _generate(expr.object, ctx);
const optional = expr.optional || chainHasOptional(expr.object);
if (isStringProducing(expr.object)) {
return { $strLenCP: optional ? wrapIfNull(rawObj, "") : rawObj };
}
if (isArrayProducing(expr.object)) {
return { $size: optional ? wrapIfNull(rawObj, []) : rawObj };
}
// Type unknown at compile time — dispatch at runtime. When the chain is
// optional, wrap the receiver with $ifNull(rawObj, []) so `$isArray`
// succeeds, the array branch runs, and `$size([])` returns 0 (matching
// JS short-circuit: `undefined?.length` is undefined; we surface 0).
const obj = optional ? wrapIfNull(rawObj, []) : rawObj;
return { $cond: [{ $isArray: obj }, { $size: obj }, { $strLenCP: obj }] };
}
const path = asFieldPath(expr, ctx);
if (path !== null) return path;
// Receiver isn't a foldable field path (e.g. result of $.items[0], a method call,
// or a ternary). Use $getField, which works on any expression result.
const rawObj = _generate(expr.object, ctx);
const obj = expr.optional || chainHasOptional(expr.object) ? wrapIfNull(rawObj, {}) : rawObj;
return { $getField: { field: expr.member, input: obj } };
}
case "MethodCall":
return generateMethodCall(expr.object, expr.method, expr.args, ctx, expr.pos, !!expr.optional);
case "CallExpression":
return generateCallExpression(expr.callee, expr.args, ctx, expr.pos);
case "Lambda":
throw new CodegenError(
"Lambda expression cannot be used here — only valid as array method argument or $let second argument",
expr.pos,
);
case "TypeofExpr":
return { $type: _generate(expr.operand, ctx) };
case "NewDate":
return generateNewDate(expr.args, ctx);
case "NewSet":
// `new Set(arr)` is a tag for the value — used as a receiver in set-method calls
// (intersection/union/etc.). When evaluated as a standalone value, it just unwraps
// to the underlying array (MQL has no Set type).
return expr.arg === null ? [] : _generate(expr.arg, ctx);
case "ArrayFrom":
return generateArrayFrom(expr.input, expr.mapFn, ctx, expr.pos);
case "NumberStatic":
return generateNumberStatic(expr.method, expr.arg, ctx);
case "DateNow":
// Date.now() returns ms since epoch — match JS semantics
return { $toLong: "$$NOW" };
case "DateUTC":
return generateDateUTC(expr.args, ctx);
case "TypeCast":
return generateTypeCast(expr.cast, expr.arg, ctx, expr.pos);
case "TypeCastRef":
// A bare `Boolean` / `Number` / `String` outside callback position.
// Inside `.filter(Boolean)` etc. this node is desugared away in
// requireLambda(); reaching this case means the user wrote it as a
// value (e.g. `Boolean + 5`), which has no MQL counterpart.
throw new CodegenError(
`'${expr.cast}' used as a value is only valid as a callback to a higher-order array method (e.g. $.items.filter(${expr.cast})). To coerce a single value, write ${expr.cast}(value).`,
expr.pos,
);
case "MathCall":
return generateMathCall(expr.method, expr.args, ctx, expr.pos);
case "MathConst":
return generateMathConst(expr.name);
case "ObjectCall":
return generateObjectCall(expr.method, expr.args, ctx, expr.pos);
}
}
// ── Optional-chaining safety wraps ────────────────────────────────────────────
//
// `?.` in jsmql preserves an `optional: true` flag on the AST node the parser
// produced from it. Codegen consults `chainHasOptional` at every null-unsafe
// consumer site (array spread, array/string method receivers, string `$concat`
// operands, template-literal interpolations, `.length`, `Object.keys`/etc.) and
// wraps the value with `$ifNull(v, neutral)`, where `neutral` is the empty
// value matching the consumer slot:
// - `[]` for array consumers
// - `""` for string consumers
// - `{}` for object consumers
//
// The walker descends only through `MemberAccess` and `IndexAccess` links — it
// stops at `MethodCall` because once a method has been called the value is
// whatever the method returned, not the optional chain that produced its
// receiver. (The method call site itself already wrapped its receiver if its
// own chain was optional, so the result is guaranteed safe.) The walker also
// does not descend into lambda bodies, binary operands, method arguments, or
// `IndexAccess.index` — `?.` buried in those positions belongs to a different
// chain. The current node's own `.optional` flag is consulted separately at
// each consumer site (see `expr.optional ||` checks in `_generate`).
function chainHasOptional(expr: Expr): boolean {
let node: Expr = expr;
while (node.type === "MemberAccess" || node.type === "IndexAccess") {
if (node.optional) return true;
node = node.object;
}
return false;
}
function wrapIfNull(value: unknown, fallback: unknown): unknown {
return { $ifNull: [value, fallback] };
}
// Method-name → "neutral input for the operator this method lowers to".
// Used to pick the `$ifNull` fallback when a `?.` chain feeds the method's
// receiver. Date / Set / Regex methods are intentionally absent: their
// underlying operators (`$year`, set ops, regex ops) handle null cleanly and
// don't poison downstream callers.
const OPTIONAL_STRING_METHODS: ReadonlySet<string> = new Set([
"trim",
"trimStart",
"trimLeft",
"trimEnd",
"trimRight",
"toLowerCase",
"toUpperCase",
"substr",
"substring",
"charAt",
"split",
"startsWith",
"endsWith",
"replace",
"replaceAll",
"match",
"matchAll",
"search",
"padStart",
"padEnd",
"repeat",
]);
const OPTIONAL_ARRAY_METHODS: ReadonlySet<string> = new Set([
"at",
"reverse",
"toReversed",
"toSorted",
"findLast",
"findLastIndex",
"join",
"flat",
"flatMap",
"map",
"filter",
"find",
"some",
"every",
"reduce",
]);
// `indexOf` / `includes` / `concat` dispatch on receiver type at codegen time
// (or at runtime via `$cond` when the type is unknown). For these we pick the
// fallback that matches the chosen branch: `""` when the receiver is provably
// string-producing, `[]` otherwise — `[]` is also safe for the runtime-dispatch
// path because `$isArray([])` is true, sending it down the array branch which
// returns the same sensible empty-array result the JS short-circuit would.
const OPTIONAL_EITHER_METHODS: ReadonlySet<string> = new Set(["indexOf", "includes", "concat", "slice"]);
function neutralForMethod(method: string, object: Expr): unknown | undefined {
if (OPTIONAL_STRING_METHODS.has(method)) return "";
if (OPTIONAL_ARRAY_METHODS.has(method)) return [];
if (OPTIONAL_EITHER_METHODS.has(method)) {
if (isStringProducing(object)) return "";
return [];
}
return undefined;
}
// ── Field path reconstruction ─────────────────────────────────────────────────
function asFieldPath(expr: Expr, ctx: GenerateCtx): string | null {
if (expr.type === "FieldRef") return expr.path === "" ? "$$ROOT" : `$${expr.path}`;
if (expr.type === "ParamRef") {
if (ctx.reduceRemap?.has(expr.name)) {
return `$$${ctx.reduceRemap.get(expr.name)!}`;
}
if (ctx.lambdaParams.has(expr.name)) {
return `$$${expr.name}`;
}
const letPath = ctx.pipelineLets?.get(expr.name);
if (letPath !== undefined) {
return `$${letPath}`;
}
return null;
}
if (expr.type === "MemberAccess") {
const base = asFieldPath(expr.object, ctx);
if (base !== null) return `${base}.${expr.member}`;
}
return null;
}
// ── Binary expressions ────────────────────────────────────────────────────────
function generateBinaryExpr(op: BinaryOp, left: Expr, right: Expr, ctx: GenerateCtx, pos: number): unknown {
switch (op) {
case "+":
return generateAdd(left, right, ctx);
case "-":
return { $subtract: [_generate(left, ctx), _generate(right, ctx)] };
case "*":
return { $multiply: flattenChain("*", left, right, ctx) };
case "/":
return { $divide: [_generate(left, ctx), _generate(right, ctx)] };
case "%":
return { $mod: [_generate(left, ctx), _generate(right, ctx)] };
case "**":
return { $pow: [_generate(left, ctx), _generate(right, ctx)] };
case "==":
case "!=":
return generateLooseEquality(op, left, right, ctx, pos);
case "===":
return { $eq: [_generate(left, ctx), _generate(right, ctx)] };
case "!==":
return { $ne: [_generate(left, ctx), _generate(right, ctx)] };
case ">":
return { $gt: [_generate(left, ctx), _generate(right, ctx)] };
case ">=":
return { $gte: [_generate(left, ctx), _generate(right, ctx)] };
case "<":
return { $lt: [_generate(left, ctx), _generate(right, ctx)] };
case "<=":
return { $lte: [_generate(left, ctx), _generate(right, ctx)] };
case "&&":
return generateLogical("&&", left, right, ctx);
case "||":
return generateLogical("||", left, right, ctx);
case "??":
return { $ifNull: flattenChain("??", left, right, ctx) };
case "&":