-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.ts
More file actions
2157 lines (2024 loc) · 83.5 KB
/
parser.ts
File metadata and controls
2157 lines (2024 loc) · 83.5 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 { Lexer, TokenType, type Token } from "./lexer.ts";
import { closestNameTo } from "./levenshtein.ts";
import type {
Expr,
BinaryOp,
ArrayElement,
ObjectEntry,
KeyValueEntry,
SpreadElement,
TypeCastOp,
BareCastOp,
MathMethod,
MathConstant,
ObjectMethod,
ObjectKey,
CallArg,
AssignExpr,
DeleteStmt,
LetDecl,
UpdateOp,
UpdateFilter,
Pipeline,
PipelineStmt,
Program,
} from "./ast.ts";
export class ParseError extends Error {
readonly pos: number;
constructor(message: string, pos: number) {
super(message);
this.name = "ParseError";
this.pos = pos;
}
}
/**
* Raised by `Parser.parseFunctionInput()` when the source given to
* `jsmql(($) => …)` is not a valid arrow function shape — `async`
* arrows, `function` declarations, missing arrow operator, unbalanced
* params, `return` inside a block body, etc. Distinct from `ParseError`
* because the failure is in the function-shape adapter, not in jsmql's
* own grammar; `validate()` maps both to `SYNTAX_ERROR`.
*/
export class FunctionInputError extends Error {
readonly pos: number;
constructor(message: string, pos: number = 0) {
super(message);
this.name = "FunctionInputError";
this.pos = pos;
}
}
/**
* One entry in the params destructure of a function-form arrow.
* - `key` is the property looked up on the params object at call time
* (the *outer* destructure key).
* - `name` is the identifier used in the function body (the *inner* alias if
* the user wrote `{ key: alias }`, or the same as `key` otherwise).
*
* Most users never alias and both fields are identical; aliasing exists so a
* verbose public param name can have a short body-local synonym.
*/
export type ParamBinding = { key: string; name: string };
/**
* Result of `Parser.parseFunctionInput()`. The function source is split into a
* parsed body (`program`) and the parameter bindings extracted from the params
* slot (`bindings`, empty when the arrow has no params destructure). The two
* pieces travel together because codegen needs the binding names to interpret
* bare identifiers in the body as parameter references rather than unknown
* idents.
*/
export type FunctionInputResult = { program: Program; bindings: ParamBinding[] };
const MATH_METHODS = new Set<string>([
"abs",
"ceil",
"floor",
"round",
"pow",
"sqrt",
"exp",
"log",
"log2",
"log10",
"trunc",
"min",
"max",
"sign",
"hypot",
"cbrt",
"random",
"sin",
"cos",
"tan",
"asin",
"acos",
"atan",
"atan2",
"sinh",
"cosh",
"tanh",
"asinh",
"acosh",
"atanh",
]);
const MATH_CONSTANTS = new Set<string>(["PI", "E"]);
const OBJECT_METHODS = new Set<string>(["keys", "values", "entries", "assign", "fromEntries", "groupBy"]);
const TYPE_CAST_NAMES = new Set<string>(["Number", "String", "Boolean", "parseInt", "parseFloat"]);
// Subset of TYPE_CAST_NAMES that are also valid as bare callbacks:
// $.items.filter(Boolean) === $.items.filter(x => Boolean(x))
// parseInt / parseFloat are excluded so we don't import the JS
// `arr.map(parseInt)` index-as-radix footgun — users opt in explicitly with
// `x => parseInt(x)`.
const BARE_CAST_NAMES = new Set<BareCastOp>(["Number", "String", "Boolean"]);
function compoundBinaryOp(op: "+=" | "-=" | "*=" | "/="): BinaryOp {
switch (op) {
case "+=":
return "+";
case "-=":
return "-";
case "*=":
return "*";
case "/=":
return "/";
}
}
// Recursion-depth cap for the recursive-descent parser. Each user-visible
// nest level burns ~17 stack frames as the precedence cascade walks from
// parseExpression down to parsePrimary; 200 levels stays well within Node's
// default stack budget while comfortably above any realistic expression.
// Exceeding it surfaces a structured ParseError instead of an uncaught
// V8 RangeError. Mirrored in codegen.ts.
export const MAX_RECURSION_DEPTH = 200;
export class Parser {
private readonly lexer: Lexer;
private depth = 0;
constructor(src: string) {
this.lexer = new Lexer(src);
}
parse(): Program {
// Top-level grammar:
// program := stmt (";" stmt)* ";"?
// where each `stmt` is either an expression or a update op chain (one or
// more comma-separated update ops). Any presence of `;` — including a
// single trailing one — flips the input to pipeline mode (`Pipeline`),
// and each `;`-separated chunk becomes its own stage(s) in the lowerer
// with no cross-coalescing. Without any `;`, behaviour is unchanged:
// the single statement is returned as `Expr` or `UpdateFilter`.
const stmts: PipelineStmt[] = [this.collectStatement()];
let sawSemi = false;
while (this.lexer.peek().type === TokenType.Semi) {
this.lexer.next(); // consume `;`
sawSemi = true;
if (this.lexer.peek().type === TokenType.EOF) break; // trailing `;`
stmts.push(this.collectStatement());
}
const eof = this.lexer.peek();
if (eof.type !== TokenType.EOF) {
throw new ParseError(`Unexpected token '${eof.value}' at position ${eof.pos}`, eof.pos);
}
if (!sawSemi) {
const only = stmts[0];
if (only.type === "LetDecl") this.throwLetOutsidePipeline(only.name, only.pos);
return only;
}
return { type: "Pipeline", stmts, pos: stmts[0].pos };
}
/**
* Entry point for the function-input form (`jsmql(($) => …)`). The source
* is the result of `Function.prototype.toString.call(fn)` — a full arrow
* function expression. We consume the parameter list and `=>`, then dispatch
* to either a block-body parser (`{ stmt; stmt; }`, the function-form mirror
* of the implicit `;`-separated pipeline) or an expression-body parser (a
* single jsmql expression / update op, with one optional trailing `;` allowed
* as a formatter artifact — single-statement bodies do NOT flip into pipeline
* mode here).
*
* Raises `FunctionInputError` for shape problems specific to the adapter
* (`async`, `function`, missing arrow, `return` in a block body, …) and
* `ParseError`/`LexError` for grammar problems inside the body itself.
*/
parseFunctionInput(): FunctionInputResult {
const first = this.lexer.peek();
if (first.type === TokenType.Ident && first.value === "async") {
throw new FunctionInputError(
"jsmql does not support async functions. Use a synchronous arrow: `($) => …`",
first.pos,
);
}
if (first.type === TokenType.Ident && first.value === "function") {
throw new FunctionInputError(
"jsmql expects an arrow function, got a `function` declaration. Use: `($) => …`",
first.pos,
);
}
if (first.type !== TokenType.LParen) {
throw new FunctionInputError("jsmql expects an arrow function `($) => …` as the function-form input.", first.pos);
}
const bindings = this.parseParameterList();
const arrowTok = this.lexer.peek();
if (arrowTok.type !== TokenType.Arrow) {
throw new FunctionInputError(
"jsmql could not find an arrow operator (`=>`) in the function source. Use: `($) => …`",
arrowTok.pos,
);
}
this.lexer.next(); // consume `=>`
const program = this.lexer.peek().type === TokenType.LBrace ? this.parseBlockBody() : this.parseExpressionBody();
return { program, bindings };
}
/**
* Parse and classify the parenthesised parameter list of the function-form
* arrow. Each top-level parameter slot is one of three *shapes*:
*
* - **Plain identifier** (`$`, `doc`, anything) — the document-context slot.
* Discarded; the body parser doesn't need the name.
* - **Destructure pattern with all keys starting with `$`** (`{ $dateDiff }`,
* `{ $match, $project }`) — the ops-hint slot (types-only IDE
* autocomplete). Discarded; the keys don't reach codegen.
* - **Destructure pattern with at least one non-`$` key** (`{ minAge }`) —
* the function-form parameter bindings. Names are returned so codegen can
* inline values supplied at `jsmql.compile()` call time.
*
* The legal slot orderings are: `()`, `(doc)`, `(ops)`, `(params)`,
* `(doc, ops)`, `(params, doc)`, `(params, ops)`, `(params, doc, ops)`.
* Anything else throws `FunctionInputError` with a precise message.
*
* Returns the binding names extracted from the params slot (in source
* order). Cursor is left immediately after the closing `)`.
*/
private parseParameterList(): ParamBinding[] {
this.lexer.next(); // consume opening `(`
type Slot =
| { kind: "doc"; pos: number }
| { kind: "ops"; pos: number }
| { kind: "params"; bindings: ParamBinding[]; pos: number };
const slots: Slot[] = [];
if (this.lexer.peek().type !== TokenType.RParen) {
while (true) {
slots.push(this.parseParameterSlot());
const sep = this.lexer.peek();
if (sep.type === TokenType.Comma) {
this.lexer.next();
continue;
}
if (sep.type === TokenType.RParen) break;
throw new FunctionInputError(
`jsmql could not parse the function parameter list — expected ',' or ')' at position ${sep.pos}, got '${sep.value}'.`,
sep.pos,
);
}
}
const closeParen = this.lexer.next(); // consume `)`
if (slots.length > 3) {
throw new FunctionInputError(
`jsmql's compile-form arrow takes at most three parameters in the order \`(params, $, opsHint)\`. ` +
`Got ${slots.length} parameters. Reorder to \`(params, $, opsHint)\` and drop any extras.`,
closeParen.pos,
);
}
// Validate slot ordering. The legal orderings are: each slot kind appears
// at most once, and the order (when all present) is params → doc → ops.
let sawParams = false;
let sawDoc = false;
let sawOps = false;
let bindings: ParamBinding[] = [];
for (const slot of slots) {
if (slot.kind === "params") {
if (sawParams) {
throw new FunctionInputError(
"jsmql params destructure may only appear once. Combine the bindings into a single parameter: `({ a, b }, …) => …`.",
slot.pos,
);
}
if (sawDoc || sawOps) {
throw new FunctionInputError(
"jsmql expects the params destructure to appear before the `$` doc-context parameter and the ops-hint destructure. " +
"Reorder to `(params, $, opsHint)`.",
slot.pos,
);
}
sawParams = true;
bindings = slot.bindings;
} else if (slot.kind === "doc") {
if (sawDoc) {
throw new FunctionInputError(
"jsmql's compile-form arrow takes at most one document-context parameter (`$`).",
slot.pos,
);
}
if (sawOps) {
throw new FunctionInputError(
"jsmql expects the `$` doc-context parameter to appear before the ops-hint destructure. " +
"Reorder to `(params, $, opsHint)`.",
slot.pos,
);
}
sawDoc = true;
} else {
if (sawOps) {
throw new FunctionInputError(
"jsmql's compile-form arrow takes at most one ops-hint destructure (e.g. `{ $match }`).",
slot.pos,
);
}
sawOps = true;
}
}
return bindings;
}
/**
* Parse a single parameter slot and classify it by shape. Called by
* `parseParameterList`; advances the lexer past the slot.
*/
private parseParameterSlot():
| { kind: "doc"; pos: number }
| { kind: "ops"; pos: number }
| { kind: "params"; bindings: ParamBinding[]; pos: number } {
const head = this.lexer.peek();
if (head.type === TokenType.LBracket) {
throw new FunctionInputError(
"jsmql params must be an object destructure pattern: `{ a, b }`. " +
"Array destructure is not accepted — params are always named, never positional.",
head.pos,
);
}
if (head.type === TokenType.Ident) {
// Plain-identifier slot — discard the name.
this.lexer.next();
return { kind: "doc", pos: head.pos };
}
if (head.type === TokenType.Dollar) {
// Plain `$` identifier in the doc slot.
this.lexer.next();
return { kind: "doc", pos: head.pos };
}
if (head.type !== TokenType.LBrace) {
throw new FunctionInputError(
`jsmql expects each parameter to be an identifier or an object destructure pattern. Got '${head.value}' at position ${head.pos}.`,
head.pos,
);
}
return this.parseDestructureSlot();
}
/**
* Parse `{ key (: alias)? (, key)* (,)? }` and classify the slot as `ops`
* (every key starts with `$`) or `params` (at least one non-`$` key).
* Rejects defaults, nested destructure, rest, and mixed `$`/non-`$` keys
* with the user-facing error messages from `docs/LANGUAGE.md`.
*/
private parseDestructureSlot():
| { kind: "ops"; pos: number }
| { kind: "params"; bindings: ParamBinding[]; pos: number } {
const openBrace = this.lexer.next(); // consume `{`
const opsKeys: string[] = [];
const paramBindings: ParamBinding[] = [];
if (this.lexer.peek().type === TokenType.RBrace) {
// Empty destructure — treat as ops-hint (no-op).
this.lexer.next();
return { kind: "ops", pos: openBrace.pos };
}
while (true) {
const key = this.lexer.peek();
if (key.type === TokenType.Spread) {
throw new FunctionInputError(
"jsmql does not support rest patterns in params: `{ ...rest }`. " +
"The set of bindings must be statically known at compile time so the generated MQL can reference each by name. " +
"List each binding explicitly: `{ a, b, c }`.",
key.pos,
);
}
// Either `$name` (Dollar followed by Ident) for ops-hint keys, or
// `name` (Ident) for params keys.
let keyName: string;
let isOpsKey: boolean;
if (key.type === TokenType.Dollar) {
this.lexer.next();
const ident = this.lexer.peek();
if (ident.type !== TokenType.Ident) {
throw new FunctionInputError(
`jsmql expected an identifier after '$' in the destructure key at position ${ident.pos}.`,
ident.pos,
);
}
this.lexer.next();
keyName = `$${ident.value}`;
isOpsKey = true;
} else if (key.type === TokenType.Ident) {
this.lexer.next();
keyName = key.value;
isOpsKey = false;
} else {
throw new FunctionInputError(
`jsmql expected an identifier in the destructure pattern at position ${key.pos}, got '${key.value}'.`,
key.pos,
);
}
// Optional alias: `{ key: alias }`. Used for params keys to give the
// body identifier a different (usually shorter) name than the param
// object property name. Ignored for ops keys — the alias would only
// serve IDE autocomplete, which the original key already provides.
let bindingName = keyName;
if (this.lexer.peek().type === TokenType.Colon) {
this.lexer.next(); // consume `:`
const alias = this.lexer.peek();
if (alias.type === TokenType.LBrace || alias.type === TokenType.LBracket) {
throw new FunctionInputError(
"jsmql does not support nested destructure in params: `{ <name>: { … } }`. " +
"Params is a flat key→value map at the MQL level. Use a single level of destructure and reference nested fields explicitly at the call site, e.g. `q({ b: source.a.b })`.",
alias.pos,
);
}
if (alias.type !== TokenType.Ident) {
throw new FunctionInputError(
`jsmql expected an alias identifier after ':' in the destructure pattern at position ${alias.pos}, got '${alias.value}'.`,
alias.pos,
);
}
this.lexer.next();
bindingName = alias.value;
}
// Optional default: `{ key = expr }` — always rejected.
if (this.lexer.peek().type === TokenType.Eq) {
const defaultTok = this.lexer.peek();
throw new FunctionInputError(
"jsmql does not support default values in the params destructure: `{ <name> = <expr> }`.\n\n" +
"jsmql compiles your function to MQL at parse time. It reads the function's source text but cannot evaluate the default expression — for `= config.minAge` or `= Date.now()` there is no runtime to ask, since jsmql never actually calls your arrow. Restricting defaults to literals (`= 18`) would make the rule silently inconsistent with the rest of the destructure, where any value is fine at call time.\n\n" +
"Instead:\n" +
" - For a runtime fallback, use JS's `??` at the call site: `q({ minAge: input ?? 18 })`.\n" +
" - For a value that's always the same and never overridden, the template-tag form already inlines hardcoded values: `` jsmql`$.age > ${18}` ``.",
defaultTok.pos,
);
}
if (isOpsKey) opsKeys.push(keyName);
else paramBindings.push({ key: keyName, name: bindingName });
const sep = this.lexer.peek();
if (sep.type === TokenType.Comma) {
this.lexer.next();
// Allow trailing comma.
if (this.lexer.peek().type === TokenType.RBrace) break;
continue;
}
if (sep.type === TokenType.RBrace) break;
throw new FunctionInputError(
`jsmql could not parse the destructure pattern — expected ',' or '}' at position ${sep.pos}, got '${sep.value}'.`,
sep.pos,
);
}
this.lexer.next(); // consume `}`
if (opsKeys.length > 0 && paramBindings.length > 0) {
throw new FunctionInputError(
"jsmql expects the operator-hint destructure (e.g. `{ $match, $project }`) to be separate from the params destructure (e.g. `{ minAge }`). " +
"Split into two parameters: `(params, $, opsHint) => …`.",
openBrace.pos,
);
}
if (paramBindings.length > 0) return { kind: "params", bindings: paramBindings, pos: openBrace.pos };
return { kind: "ops", pos: openBrace.pos };
}
/**
* Parse the body of a block-body arrow: `{ stmt (; stmt)* ;? }`. This is
* structurally the same as the top-level `;`-separated pipeline form
* (see `parse()`), terminated by `}` instead of EOF. A single-statement
* block body without `;` returns the underlying `Expr`/`UpdateFilter`
* unchanged; any `;` (including a trailing one) wraps as a `Pipeline`.
*
* `return` is rejected up front with a precise `FunctionInputError` so the
* user gets a clear pointer to either the `;`-separated form or an
* expression-body arrow, instead of the parser's generic "unknown
* identifier" message.
*/
private parseBlockBody(): Program {
const openBrace = this.lexer.next(); // consume `{`
if (this.lexer.peek().type === TokenType.RBrace) {
throw new FunctionInputError("jsmql expects at least one statement inside a block-body arrow.", openBrace.pos);
}
this.rejectReturn();
const stmts: PipelineStmt[] = [this.collectStatement()];
let sawSemi = false;
while (this.lexer.peek().type === TokenType.Semi) {
this.lexer.next();
sawSemi = true;
if (this.lexer.peek().type === TokenType.RBrace) break;
this.rejectReturn();
stmts.push(this.collectStatement());
}
const closeTok = this.lexer.peek();
if (closeTok.type !== TokenType.RBrace) {
throw new ParseError(`Expected '}' to close the block body at position ${closeTok.pos}`, closeTok.pos);
}
this.lexer.next();
const eof = this.lexer.peek();
if (eof.type !== TokenType.EOF) {
throw new ParseError(`Unexpected token after function body at position ${eof.pos}`, eof.pos);
}
if (!sawSemi) {
const only = stmts[0];
if (only.type === "LetDecl") this.throwLetOutsidePipeline(only.name, only.pos);
return only;
}
return { type: "Pipeline", stmts, pos: stmts[0].pos };
}
/**
* Parse the body of an expression-body arrow: a single jsmql statement,
* with one optional trailing `;` consumed as a formatter artifact. The
* trailing `;` does NOT trigger pipeline mode here — single-statement
* expression bodies preserve their object-shaped output, matching the
* documented contract for `jsmql(($) => …)`.
*/
private parseExpressionBody(): Program {
const stmt = this.collectStatement();
if (this.lexer.peek().type === TokenType.Semi) {
this.lexer.next();
}
const eof = this.lexer.peek();
if (eof.type !== TokenType.EOF) {
throw new ParseError(`Unexpected token after function body at position ${eof.pos}`, eof.pos);
}
if (stmt.type === "LetDecl") this.throwLetOutsidePipeline(stmt.name, stmt.pos);
return stmt;
}
/**
* Raised when a `let` declaration appears at the top of an input that turns
* out to be expression-mode (no `;` separator, not a bracketed pipeline).
* `let` only makes sense as a pipeline statement — there's no enclosing
* scope for the binding to live in otherwise.
*/
private throwLetOutsidePipeline(name: string, pos: number): never {
throw new ParseError(
`\`let ${name} = …\` is only valid inside a pipeline. ` +
`Add at least one more statement separated by \`;\` to flip into pipeline mode ` +
`(e.g. \`let ${name} = …; { $project: … }\`). ` +
`The bracketed pipeline form \`[ let ${name} = …, … ]\` works too.`,
pos,
);
}
/**
* Throw a precise `FunctionInputError` if the next token is the bare
* identifier `return`. Called at every statement-start position inside
* a block body, so a `return` token *inside* a string or expression
* (where it would just be a property name like `obj.return`) doesn't
* false-fire — only true statement-leading `return`s reach this check.
*/
private rejectReturn(): void {
const tok = this.lexer.peek();
if (tok.type === TokenType.Ident && tok.value === "return") {
throw new FunctionInputError(
"jsmql block-body arrows are a sequence of jsmql statements, not JavaScript control flow. " +
"Remove `return` — write the body as `;`-separated jsmql statements, or switch to an " +
"expression-body arrow `($) => EXPR`.",
tok.pos,
);
}
}
/**
* Parse one top-level statement: either an expression or a update op chain
* (one or more comma-separated update ops sharing a stage). Stops at the
* first `;` or EOF; the caller (`parse()`) handles the `;` boundary.
*/
private collectStatement(): PipelineStmt {
const first = this.lexer.peek();
// `let <ident> = <expr>` — pipeline-scoped local binding. Only legal in a
// pipeline context; codegen errors if it shows up in expression-mode input
// (no `;` boundary and not inside a bracketed pipeline).
if (first.type === TokenType.Let) {
return this.parseLetDecl();
}
// Tokens that can ONLY start a update op program: `delete`, `++`, `--`.
// Their presence at the start of a statement unambiguously commits us
// to update op parsing. Other update op forms (=, +=, x++, …) reveal
// themselves only after a target expression has been parsed — below.
if (first.type === TokenType.Delete || first.type === TokenType.PlusPlus || first.type === TokenType.MinusMinus) {
return this.parseUpdateFilter();
}
// Speculative: parse a single expression first.
const expr = this.parseExpression();
// If an assignment operator follows, the expression we just parsed was
// actually a update op target — treat the rest of the statement as a
// update op chain.
if (this.peekAssignOp() !== null) {
this.validateUpdateTarget(expr);
return this.parseUpdateFilterFrom(expr);
}
// Postfix `x++` / `x--`.
if (this.peekIncDecOp() !== null) {
this.validateUpdateTarget(expr);
return this.parseUpdateFilterFromPostfix(expr);
}
// `parseExpression` may have surfaced an `AssignExpr` from a parenthesized
// top-level assignment (`($.a = 5)`). Wrap it in a UpdateFilter so
// codegen routes through the update op path.
if ((expr as unknown as { type: string }).type === "AssignExpr") {
const ops: UpdateOp[] = [expr as unknown as AssignExpr];
this.parseUpdateFilterRest(ops);
return { type: "UpdateFilter", ops, pos: ops[0].pos };
}
return expr;
}
// ── Let declaration ──────────────────────────────────────────────────────
/**
* Parse `let <ident> = <expr>`. The leading `let` token must already be the
* current peek; this consumes it and the rest of the declaration. The cursor
* is left at whatever follows the value expression (typically `;` or `,` in
* the array-pipeline form). No re-declaration check here — that needs a
* pipeline-level view and lives in codegen.
*/
private parseLetDecl(): LetDecl {
const letTok = this.lexer.next(); // consume `let`
const ident = this.lexer.peek();
if (ident.type !== TokenType.Ident) {
throw new ParseError(
`Expected an identifier after \`let\` at position ${ident.pos}, got '${ident.value}'`,
ident.pos,
);
}
this.lexer.next(); // consume the identifier
const eq = this.lexer.peek();
if (eq.type !== TokenType.Eq) {
throw new ParseError(
`Expected '=' after \`let ${ident.value}\` at position ${eq.pos}, got '${eq.value}'. ` +
`\`let\` requires an initialiser — write \`let ${ident.value} = <expr>\`.`,
eq.pos,
);
}
this.lexer.next(); // consume `=`
const value = this.parseExpression();
return { type: "LetDecl", name: ident.value, value, pos: letTok.pos };
}
// ── UpdateOp program ─────────────────────────────────────────────────────
/** Entry when the input starts with a update op token (`delete`). */
private parseUpdateFilter(): UpdateFilter {
const ops: UpdateOp[] = [];
ops.push(...this.parseUpdateOp());
this.parseUpdateFilterRest(ops);
return { type: "UpdateFilter", ops, pos: ops[0].pos };
}
/** Entry when the first target was already parsed as an expression. */
private parseUpdateFilterFrom(firstTarget: Expr): UpdateFilter {
const ops: UpdateOp[] = [];
ops.push(...this.parseAssignmentChainFrom(firstTarget));
this.parseUpdateFilterRest(ops);
return { type: "UpdateFilter", ops, pos: ops[0].pos };
}
/**
* Entry when the first target was parsed and is followed by `++` or `--`
* (postfix inc/dec). Validation must already have happened.
*/
private parseUpdateFilterFromPostfix(firstTarget: Expr): UpdateFilter {
const op = this.peekIncDecOp();
if (op === null) {
const tok = this.lexer.peek();
throw new ParseError(`Expected '++' or '--' at position ${tok.pos}`, tok.pos);
}
this.lexer.next(); // consume the operator
const ops: UpdateOp[] = [this.makeIncDecUpdateOp(firstTarget, op)];
this.parseUpdateFilterRest(ops);
return { type: "UpdateFilter", ops, pos: ops[0].pos };
}
/**
* After the first update op is parsed, consume any `,`-separated tail.
* Stops at the first non-`,` token (typically `;` or EOF) and leaves
* the cursor there for the caller to handle.
*/
private parseUpdateFilterRest(ops: UpdateOp[]): void {
while (this.peekUpdateOpSeparator()) {
this.lexer.next(); // consume `,`
const next = this.lexer.peek().type;
if (next === TokenType.EOF || next === TokenType.Semi) break; // trailing separator
ops.push(...this.parseUpdateOp());
}
}
/**
* Parse a single update op. Returns an array because a chained assignment
* (`$.a = $.b = expr`) flattens to multiple `AssignExpr` nodes here, all
* sharing the deepest RHS.
*/
private parseUpdateOp(): UpdateOp[] {
if (this.lexer.peek().type === TokenType.Delete) {
return [this.parseDeleteStmt()];
}
// Prefix increment/decrement: `++$.x` / `--$.x`.
if (this.peekIncDecOp() !== null) {
return [this.parsePrefixIncDec()];
}
const target = this.parsePostfix();
// `parsePostfix` may have already returned a fully-formed update op when the
// input was wrapped in parens — `($.a = 1)` / `($.a++)`. Prettier and oxfmt
// emit this shape when a top-level assignment chains with `,`. Surface it
// as-is so a chain like `($.a = 1), ($.b = 2)` round-trips.
if ((target as unknown as { type: string }).type === "AssignExpr") {
return [target as unknown as AssignExpr];
}
this.validateUpdateTarget(target);
// Postfix increment/decrement: `$.x++` / `$.x--`.
const postfix = this.peekIncDecOp();
if (postfix !== null) {
this.lexer.next();
return [this.makeIncDecUpdateOp(target, postfix)];
}
return this.parseAssignmentChainFrom(target);
}
private parseDeleteStmt(): DeleteStmt {
const delTok = this.lexer.next(); // consume `delete`
const target = this.parsePostfix();
this.validateUpdateTarget(target);
return { type: "DeleteStmt", target, pos: delTok.pos };
}
/**
* Given a target already parsed and validated, expect an assignment operator
* and parse the RHS. Handles right-associative chains for `=`; rejects them
* for compound operators because `a += b += 1` is too easy to misread.
*/
private parseAssignmentChainFrom(target: Expr): AssignExpr[] {
const opTok = this.lexer.peek();
const op = this.peekAssignOp();
if (op === null) {
throw new ParseError(`Expected assignment operator at position ${opTok.pos}`, opTok.pos);
}
this.lexer.next(); // consume the assignment op
if (op === "=") {
// Try to peek a chained target: `<target> = <target> = …`. The peek-ahead
// is bounded (DollarDot, Ident segments, dots) so this is cheap.
if (this.peekIsAssignmentChainStart()) {
const subTarget = this.parsePostfix();
this.validateUpdateTarget(subTarget);
const sub = this.parseAssignmentChainFrom(subTarget);
const deepestValue = sub[sub.length - 1].value;
return [{ type: "AssignExpr", target, value: deepestValue, pos: target.pos }, ...sub];
}
const value = this.parseExpression();
return [{ type: "AssignExpr", target, value, pos: target.pos }];
}
// Compound op (+=, -=, *=, /=). Reject chained.
if (this.peekIsAssignmentChainStart()) {
const tok = this.lexer.peek();
throw new ParseError(
`Compound assignment cannot be chained at position ${tok.pos} — split into separate statements`,
tok.pos,
);
}
const rhs = this.parseExpression();
const desugared: Expr = { type: "BinaryExpr", op: compoundBinaryOp(op), left: target, right: rhs, pos: target.pos };
return [{ type: "AssignExpr", target, value: desugared, pos: target.pos }];
}
/**
* Returns the assignment operator string at the current position, or null
* if the next token is not an assignment operator.
*/
private peekAssignOp(): "=" | "+=" | "-=" | "*=" | "/=" | null {
switch (this.lexer.peek().type) {
case TokenType.Eq:
return "=";
case TokenType.PlusEq:
return "+=";
case TokenType.MinusEq:
return "-=";
case TokenType.StarEq:
return "*=";
case TokenType.SlashEq:
return "/=";
default:
return null;
}
}
private isAssignOpType(t: TokenType): boolean {
return (
t === TokenType.Eq ||
t === TokenType.PlusEq ||
t === TokenType.MinusEq ||
t === TokenType.StarEq ||
t === TokenType.SlashEq
);
}
private peekUpdateOpSeparator(): boolean {
return this.lexer.peek().type === TokenType.Comma;
}
/**
* Returns "++" or "--" if the next token is an inc/dec operator, else null.
* Used at both prefix (start of update op) and postfix (after a target)
* positions; the caller decides which.
*/
private peekIncDecOp(): "++" | "--" | null {
switch (this.lexer.peek().type) {
case TokenType.PlusPlus:
return "++";
case TokenType.MinusMinus:
return "--";
default:
return null;
}
}
/**
* Parse a prefix `++<target>` or `--<target>`. The prefix vs postfix
* distinction is irrelevant in MQL pipeline context — both forms compile
* to the same `$set: { x: { $add|$subtract: ["$x", 1] } }` shape, since
* pipeline stages don't carry "value of expression" semantics.
*/
private parsePrefixIncDec(): AssignExpr {
const op = this.peekIncDecOp();
if (op === null) {
const tok = this.lexer.peek();
throw new ParseError(`Expected '++' or '--' at position ${tok.pos}`, tok.pos);
}
this.lexer.next(); // consume `++` or `--`
const target = this.parsePostfix();
this.validateUpdateTarget(target);
return this.makeIncDecUpdateOp(target, op);
}
/** Build the desugared AssignExpr for `target++` / `target--` / `++target` / `--target`. */
private makeIncDecUpdateOp(target: Expr, op: "++" | "--"): AssignExpr {
const value: Expr = {
type: "BinaryExpr",
op: op === "++" ? "+" : "-",
left: target,
right: { type: "NumberLiteral", value: 1, pos: target.pos },
pos: target.pos,
};
return { type: "AssignExpr", target, value, pos: target.pos };
}
/**
* Lookahead: do the next tokens look like `$.path[.path]* <assignOp>`?
* Used to detect the start of a chained assignment's RHS when we're at
* the right of a `=` operator. Bounded by the length of the field path
* so it's cheap and never false-positive on regular RHS expressions.
*/
private peekIsAssignmentChainStart(): boolean {
if (this.lexer.peek().type !== TokenType.DollarDot) return false;
let offset = 1;
if (!this.isIdentOrKeyword(this.lexer.lookahead(offset))) return false;
offset++;
while (this.lexer.lookahead(offset).type === TokenType.Dot) {
offset++;
if (!this.isIdentOrKeyword(this.lexer.lookahead(offset))) return false;
offset++;
}
return this.isAssignOpType(this.lexer.lookahead(offset).type);
}
/**
* UpdateOp targets are restricted to field paths: a `FieldRef` (`$.x`) or
* a chain of `MemberAccess` nodes rooted at one (`$.x.y.z`). Anything else
* — index access, function calls, parameter refs, parenthesized expressions
* containing operators — is rejected with a precise error.
*/
private validateUpdateTarget(target: Expr): void {
if (this.isFieldPathTarget(target)) return;
// `$out` sugar: `$$$.<coll> = …`, `$$$$.<db>.<coll> = …`, and their bracket
// variants. Shape-only check here — segment-count, computed-bracket, and
// any other malformations are diagnosed at codegen time in
// `detectOutAssign` (src/out-translation.ts) so the error message can
// suggest the right corrective form.
if (this.isOutTarget(target)) return;
const pos = this.lexer.peek().pos;
if (target.type === "ParamRef") {
throw new ParseError(
`UpdateOp target must be a field path like '$.${target.name}', not a bare identifier (at position ${pos})`,
pos,
);
}
if (target.type === "IndexAccess") {
throw new ParseError(
`UpdateOp target must be a static field path; computed/index access ('[…]') is not supported (at position ${pos})`,
pos,
);
}
throw new ParseError(
`Cannot assign to ${describeUpdateTarget(target)} at position ${pos} — only field paths like '$.x' or '$.x.y' are assignable.`,
pos,
);
}
private isFieldPathTarget(target: Expr): boolean {
if (target.type === "FieldRef") return true;
// Bare `$$` is a valid assignment target for the stream-level
// root-replacement form (`$$ = <expr>`). The parser accepts the shape
// here; pipeline lowering enforces the supported RHS forms.
if (target.type === "CollectionRef") return true;
if (target.type === "MemberAccess") return this.isFieldPathTarget(target.object);
return false;
}
/**
* Accept the `$out` sugar LHS shape: one or two static (dot or bracket)
* accesses rooted at `DatabaseRef` (`$$$`) or `ClusterRef` (`$$$$`). The
* detailed validation (right segment count, no computed bracket) lives in
* codegen — at parse time we only commit to "this looks like a write
* destination" so the assignment can be built and routed.
*/
private isOutTarget(target: Expr): boolean {
if (target.type === "DatabaseRef" || target.type === "ClusterRef") return true;
if (target.type === "MemberAccess") return this.isOutTarget(target.object);
if (target.type === "IndexAccess") return this.isOutTarget(target.object);
return false;
}
// ── Precedence hierarchy (low → high) ────────────────────────────────────
private parseExpression(): Expr {
if (++this.depth > MAX_RECURSION_DEPTH) {
this.depth--;
const pos = this.lexer.peek().pos;
throw new ParseError(`Expression nests too deeply (max ${MAX_RECURSION_DEPTH} levels) at position ${pos}`, pos);
}
try {
return this.parseTernary();
} finally {
this.depth--;
}
}
/** ternary: nullish ("?" expression ":" ternary)? — right-associative */
private parseTernary(): Expr {
const condition = this.parseNullish();
if (this.lexer.peek().type !== TokenType.Quest) return condition;
this.lexer.next(); // consume ?
const consequent = this.parseExpression(); // full expr for consequent
const colon = this.lexer.peek();
if (colon.type !== TokenType.Colon) {
throw new ParseError(`Expected ':' in ternary expression at position ${colon.pos}`, colon.pos);
}
this.lexer.next(); // consume :
const alternate = this.parseTernary(); // right-associative
return { type: "TernaryExpr", condition, consequent, alternate, pos: condition.pos };
}
/** nullish: or ("??" or)* — left-associative, flattened later */
private parseNullish(): Expr {
let left = this.parseOr();
while (this.lexer.peek().type === TokenType.QuestQuest) {
this.lexer.next();
const right = this.parseOr();
left = { type: "BinaryExpr", op: "??", left, right, pos: left.pos };
}
return left;
}