macroforge_ts_quote 0.1.82

Quote macro for generating TypeScript code at compile time
Documentation
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
//! Postfix and infix expression parsing.
//!
//! This module handles the "continuation" part of expression parsing:
//! - Postfix operators (++, --, !)
//! - Member access (.property, [computed], ?.)
//! - Function calls and type instantiation
//! - Binary operators
//! - Ternary conditional
//! - Assignment operators
//! - Sequence expressions (comma operator)
//! - TypeScript type assertions (as, satisfies)
//! - Tagged template literals

use super::errors::{ParseError, ParseErrorKind, ParseResult};
use super::operators::{keyword_to_binary_op, text_to_assign_op, text_to_binary_op, to_update_op};
use super::precedence::{infix_binding_power, is_assignment_operator, is_postfix_operator, prec};
use crate::compiler::ir::{IrNode, IrSpan};
use crate::compiler::parser::Parser;
use crate::compiler::syntax::SyntaxKind;

impl Parser {
    /// Parses postfix and infix operations on a left-hand expression.
    ///
    /// This is the main infix parsing loop of the Pratt parser. It handles:
    /// - Postfix update (x++, x--)
    /// - TypeScript non-null assertion (x!)
    /// - Member access (x.y, x[y])
    /// - Optional chaining (x?.y, x?.[y], x?.())
    /// - Function calls (x(args))
    /// - Type instantiation (x<T>)
    /// - Type assertions (x as T, x satisfies T)
    /// - Binary operators (x + y)
    /// - Ternary conditional (x ? y : z)
    /// - Assignment (x = y)
    /// - Sequence (x, y)
    /// - Tagged templates (x`...`)
    pub(super) fn parse_postfix_and_infix(
        &mut self,
        mut left: IrNode,
        min_bp: u8,
    ) -> ParseResult<IrNode> {
        loop {
            self.skip_whitespace();

            // Check if we've hit a terminator (from context stack)
            if self.at_terminator() {
                break;
            }

            let Some(token) = self.current() else {
                break;
            };

            let kind = token.kind;
            let text = token.text.clone();

            // =========================================================================
            // Postfix operators (highest precedence, no binding power comparison)
            // =========================================================================

            // Postfix update: x++, x--
            if is_postfix_operator(kind) {
                // Check if this could be a postfix operator (no newline between)
                if prec::POSTFIX >= min_bp {
                    let op = to_update_op(kind).ok_or_else(|| {
                        ParseError::new(
                            ParseErrorKind::InvalidPostfixOperator,
                            self.current_byte_offset(),
                        )
                    })?;
                    let start = left.span().start;
                    self.consume();
                    left = IrNode::UpdateExpr {
                        span: IrSpan::new(start, self.current_byte_offset()),
                        op,
                        prefix: false,
                        arg: Box::new(left),
                    };
                    continue;
                }
            }

            // TypeScript non-null assertion: x!
            // Must not be followed by = (which would be x !== ...)
            if kind == SyntaxKind::Exclaim && prec::TS_NON_NULL >= min_bp {
                // Peek ahead to make sure it's not !== or !=
                let next_text = self.peek_text(1);
                if next_text != Some("=") && next_text != Some("==") {
                    let start = left.span().start;
                    self.consume();
                    left = IrNode::TsNonNullExpr {
                        span: IrSpan::new(start, self.current_byte_offset()),
                        expr: Box::new(left),
                    };
                    continue;
                }
            }

            // =========================================================================
            // Member access and calls (very high precedence)
            // =========================================================================

            // Member access: x.y
            if kind == SyntaxKind::Dot && prec::CALL.left >= min_bp {
                let start = left.span().start;
                self.consume();
                self.skip_whitespace();

                let prop = self.parse_member_property()?;
                left = IrNode::MemberExpr {
                    span: IrSpan::new(start, self.current_byte_offset()),
                    obj: Box::new(left),
                    prop: Box::new(prop),
                    computed: false,
                };
                continue;
            }

            // Computed member access: x[y]
            if kind == SyntaxKind::LBracket && prec::CALL.left >= min_bp {
                let start_pos = self.pos;
                let start = left.span().start;
                self.consume();
                self.skip_whitespace();

                let prop = self.parse_expression_with_precedence(0)?;

                self.skip_whitespace();
                if !self.at(SyntaxKind::RBracket) {
                    return Err(ParseError::missing_closing(
                        ParseErrorKind::MissingClosingBracket,
                        self.current_byte_offset(),
                        start_pos,
                    ));
                }
                self.consume();

                left = IrNode::MemberExpr {
                    span: IrSpan::new(start, self.current_byte_offset()),
                    obj: Box::new(left),
                    prop: Box::new(prop),
                    computed: true,
                };
                continue;
            }

            // Optional chaining: x?.y, x?.[y], x?.()
            if kind == SyntaxKind::Question && prec::CALL.left >= min_bp {
                if let Some(next) = self.peek_kind(1) {
                    if next == SyntaxKind::Dot || text == "?." {
                        left = self.parse_optional_chain(left)?;
                        continue;
                    }
                }
            }

            // Check for ?. as a single token
            if text == "?." && prec::CALL.left >= min_bp {
                left = self.parse_optional_chain(left)?;
                continue;
            }

            // Function call: x(args)
            if kind == SyntaxKind::LParen && prec::CALL.left >= min_bp {
                let start = left.span().start;
                let args = self.parse_call_arguments()?;
                left = IrNode::CallExpr {
                    span: IrSpan::new(start, self.current_byte_offset()),
                    callee: Box::new(left),
                    type_args: None,
                    args,
                };
                continue;
            }

            // Type instantiation: x<T> - this is tricky as < could be comparison
            if kind == SyntaxKind::Lt && prec::CALL.left >= min_bp {
                let start = left.span().start;
                // Try to parse as type arguments
                if let Some(type_args) = self.try_parse_type_args_for_call()? {
                    self.skip_whitespace();

                    // If followed by ( it's a call with type args
                    if self.at(SyntaxKind::LParen) {
                        let args = self.parse_call_arguments()?;
                        left = IrNode::CallExpr {
                            span: IrSpan::new(start, self.current_byte_offset()),
                            callee: Box::new(left),
                            type_args: Some(Box::new(type_args)),
                            args,
                        };
                        continue;
                    }

                    // Otherwise it's a type instantiation (x<T> without call)
                    left = IrNode::TsInstantiation {
                        span: IrSpan::new(start, self.current_byte_offset()),
                        expr: Box::new(left),
                        type_args: Box::new(type_args),
                    };
                    continue;
                }
                // Not type args, fall through to comparison operator handling
            }

            // Tagged template literal: x`...`
            if kind == SyntaxKind::Backtick && prec::CALL.left >= min_bp {
                let start = left.span().start;
                let tpl = self.parse_template_literal()?;
                left = IrNode::TaggedTpl {
                    span: IrSpan::new(start, self.current_byte_offset()),
                    tag: Box::new(left),
                    type_args: None,
                    tpl: Box::new(tpl),
                };
                continue;
            }

            // =========================================================================
            // TypeScript type assertions
            // =========================================================================

            // Type assertion: x as T
            if kind == SyntaxKind::AsKw && prec::TS_AS.left >= min_bp {
                let start = left.span().start;
                self.consume();
                self.skip_whitespace();

                // Check for 'as const'
                if self.at(SyntaxKind::ConstKw) {
                    self.consume();
                    left = IrNode::TsConstAssertion {
                        span: IrSpan::new(start, self.current_byte_offset()),
                        expr: Box::new(left),
                    };
                    continue;
                }

                let type_ann = self.parse_type()?;
                left = IrNode::TsAsExpr {
                    span: IrSpan::new(start, self.current_byte_offset()),
                    expr: Box::new(left),
                    type_ann: Box::new(type_ann),
                };
                continue;
            }

            // Satisfies expression: x satisfies T
            if kind == SyntaxKind::SatisfiesKw && prec::TS_AS.left >= min_bp {
                let start = left.span().start;
                self.consume();
                self.skip_whitespace();

                let type_ann = self.parse_type()?;
                left = IrNode::TsSatisfiesExpr {
                    span: IrSpan::new(start, self.current_byte_offset()),
                    expr: Box::new(left),
                    type_ann: Box::new(type_ann),
                };
                continue;
            }

            // =========================================================================
            // Ternary conditional operator
            // =========================================================================

            if kind == SyntaxKind::Question && prec::CONDITIONAL.left >= min_bp {
                // Make sure it's not optional chaining
                let next = self.peek_kind(1);
                if next != Some(SyntaxKind::Dot) && text != "?." {
                    let start = left.span().start;
                    self.consume(); // ?
                    self.skip_whitespace();

                    // Parse consequent with lowest precedence (can contain commas inside)
                    let consequent = self.parse_expression_with_precedence(0)?;

                    self.skip_whitespace();

                    // Expect colon
                    if !self.at(SyntaxKind::Colon) {
                        return Err(ParseError::new(
                            ParseErrorKind::MissingConditionalColon,
                            self.current_byte_offset(),
                        )
                        .with_expected(&[":"]));
                    }
                    self.consume(); // :

                    self.skip_whitespace();

                    // Parse alternate with conditional precedence (right associative)
                    let alternate =
                        self.parse_expression_with_precedence(prec::CONDITIONAL.right)?;

                    left = IrNode::CondExpr {
                        span: IrSpan::new(start, self.current_byte_offset()),
                        test: Box::new(left),
                        consequent: Box::new(consequent),
                        alternate: Box::new(alternate),
                    };
                    continue;
                }
            }

            // =========================================================================
            // Assignment operators
            // =========================================================================

            if is_assignment_operator(&text) && prec::ASSIGN.left >= min_bp {
                let start = left.span().start;
                let op = text_to_assign_op(&text).ok_or_else(|| {
                    ParseError::new(ParseErrorKind::InvalidOperator, self.current_byte_offset())
                        .with_found(&text)
                })?;

                self.consume();
                self.skip_whitespace();

                // Right-associative: parse with lower precedence
                let right = self.parse_expression_with_precedence(prec::ASSIGN.right)?;

                left = IrNode::AssignExpr {
                    span: IrSpan::new(start, self.current_byte_offset()),
                    op,
                    left: Box::new(left),
                    right: Box::new(right),
                };
                continue;
            }

            // =========================================================================
            // Binary operators (including comma/sequence)
            // =========================================================================

            // Check for binary operator by SyntaxKind first
            // Note: Comma is handled separately below via parse_sequence_expr
            if kind != SyntaxKind::Comma
                && let Some(bp) = infix_binding_power(kind, &text)
            {
                if bp.left >= min_bp {
                    let start = left.span().start;
                    // Get the operator
                    let op = if let Some(op) = text_to_binary_op(&text) {
                        op
                    } else if let Some(op) = keyword_to_binary_op(kind) {
                        op
                    } else {
                        // Should not happen if infix_binding_power returned Some
                        return Err(ParseError::new(
                            ParseErrorKind::InvalidBinaryOperator,
                            self.current_byte_offset(),
                        )
                        .with_found(&text));
                    };

                    self.consume();
                    self.skip_whitespace();

                    let right = self.parse_expression_with_precedence(bp.right)?;

                    left = IrNode::BinExpr {
                        span: IrSpan::new(start, self.current_byte_offset()),
                        op,
                        left: Box::new(left),
                        right: Box::new(right),
                    };
                    continue;
                }
            }

            // Check for comma (sequence expression)
            if kind == SyntaxKind::Comma && prec::COMMA.left >= min_bp {
                left = self.parse_sequence_expr(left)?;
                continue;
            }

            // =========================================================================
            // No more infix operations at this precedence level
            // =========================================================================

            break;
        }

        Ok(left)
    }

    /// Parses an optional chain expression: x?.y, x?.[y], x?.()
    fn parse_optional_chain(&mut self, obj: IrNode) -> ParseResult<IrNode> {
        let start = obj.span().start;
        // Consume ?. or ? followed by .
        if self.at_text("?.") {
            self.consume();
        } else {
            self.expect(SyntaxKind::Question);
            if self.at(SyntaxKind::Dot) {
                self.consume();
            }
        }

        self.skip_whitespace();

        // Determine what follows the ?.
        let Some(token) = self.current() else {
            return Err(ParseError::unexpected_eof(
                self.current_byte_offset(),
                "optional chain",
            ));
        };

        match token.kind {
            // x?.() - optional call
            SyntaxKind::LParen => {
                let args = self.parse_call_arguments()?;
                let end = self.current_byte_offset();
                Ok(IrNode::OptChainExpr {
                    span: IrSpan::new(start, end),
                    base: Box::new(obj),
                    expr: Box::new(IrNode::CallExpr {
                        span: IrSpan::new(start, end),
                        callee: Box::new(IrNode::Placeholder {
                            span: IrSpan::empty(),
                            kind: crate::compiler::ir::PlaceholderKind::Expr,
                            expr: proc_macro2::TokenStream::new(), // sentinel placeholder, actual callee is the base
                        }),
                        type_args: None,
                        args,
                    }),
                })
            }
            // x?.[y] - optional computed access
            SyntaxKind::LBracket => {
                let start_pos = self.pos;
                self.consume();
                self.skip_whitespace();

                let prop = self.parse_expression_with_precedence(0)?;

                self.skip_whitespace();
                if !self.at(SyntaxKind::RBracket) {
                    return Err(ParseError::missing_closing(
                        ParseErrorKind::MissingClosingBracket,
                        self.current_byte_offset(),
                        start_pos,
                    ));
                }
                self.consume();
                let end = self.current_byte_offset();

                Ok(IrNode::OptChainExpr {
                    span: IrSpan::new(start, end),
                    base: Box::new(obj),
                    expr: Box::new(IrNode::MemberExpr {
                        span: IrSpan::new(start, end),
                        obj: Box::new(IrNode::Placeholder {
                            span: IrSpan::empty(),
                            kind: crate::compiler::ir::PlaceholderKind::Expr,
                            expr: proc_macro2::TokenStream::new(), // sentinel placeholder
                        }),
                        prop: Box::new(prop),
                        computed: true,
                    }),
                })
            }
            // x?.y - optional property access
            _ => {
                let prop = self.parse_member_property()?;
                let end = self.current_byte_offset();
                Ok(IrNode::OptChainExpr {
                    span: IrSpan::new(start, end),
                    base: Box::new(obj),
                    expr: Box::new(IrNode::MemberExpr {
                        span: IrSpan::new(start, end),
                        obj: Box::new(IrNode::Placeholder {
                            span: IrSpan::empty(),
                            kind: crate::compiler::ir::PlaceholderKind::Expr,
                            expr: proc_macro2::TokenStream::new(), // sentinel placeholder
                        }),
                        prop: Box::new(prop),
                        computed: false,
                    }),
                })
            }
        }
    }

    /// Parses a property name after a dot.
    fn parse_member_property(&mut self) -> ParseResult<IrNode> {
        let Some(token) = self.current() else {
            return Err(ParseError::new(
                ParseErrorKind::MissingPropertyName,
                self.current_byte_offset(),
            ));
        };

        match token.kind {
            SyntaxKind::Ident => {
                let t = self.consume().ok_or_else(|| {
                    ParseError::unexpected_eof(self.current_byte_offset(), "identifier")
                })?;
                Ok(IrNode::ident(&t))
            }
            // Private identifier: #name
            SyntaxKind::Hash => self.parse_private_name(),
            // Keywords can be used as property names
            _ if token.kind.is_ts_keyword() => {
                let t = self.consume().ok_or_else(|| {
                    ParseError::unexpected_eof(
                        self.current_byte_offset(),
                        "keyword as property name",
                    )
                })?;
                Ok(IrNode::ident(&t))
            }
            // Placeholder in property position
            SyntaxKind::At => self.parse_interpolation(),
            _ => Err(ParseError::new(
                ParseErrorKind::MissingPropertyName,
                self.current_byte_offset(),
            )
            .with_found(&token.text)),
        }
    }

    /// Tries to parse type arguments for a call expression.
    ///
    /// Returns `Some(type_args)` if successful, `None` if this doesn't look like type args.
    /// This uses lookahead to distinguish `x<T>()` from `x < T`.
    fn try_parse_type_args_for_call(&mut self) -> ParseResult<Option<IrNode>> {
        // Save position for backtracking
        let saved_pos = self.pos;

        if !self.at(SyntaxKind::Lt) {
            return Ok(None);
        }
        self.consume(); // <

        // Try to parse type arguments
        let mut types = Vec::new();
        let mut depth = 1;

        loop {
            self.skip_whitespace();

            if self.at_eof() {
                // Hit EOF, backtrack
                self.restore_pos(saved_pos);
                return Ok(None);
            }

            if self.at(SyntaxKind::Gt) {
                depth -= 1;
                self.consume();
                if depth == 0 {
                    break;
                }
            } else if self.at(SyntaxKind::Lt) {
                depth += 1;
                self.consume();
            } else if self.at(SyntaxKind::Comma) && depth == 1 {
                self.consume();
            } else {
                // Try to parse a type
                match self.parse_type() {
                    Ok(ty) => types.push(ty),
                    Err(_) => {
                        // Doesn't look like type args, backtrack
                        self.restore_pos(saved_pos);
                        return Ok(None);
                    }
                }
            }
        }

        self.skip_whitespace();

        // After >, should see ( or ` or . or another valid continuation
        // If we see something that doesn't make sense, backtrack
        if let Some(token) = self.current() {
            let valid_after = matches!(
                token.kind,
                SyntaxKind::LParen
                    | SyntaxKind::Backtick
                    | SyntaxKind::Dot
                    | SyntaxKind::Semicolon
                    | SyntaxKind::RParen
                    | SyntaxKind::RBracket
                    | SyntaxKind::RBrace
                    | SyntaxKind::Comma
            ) || token.text == "=>"
                || token.text == "?"
                || is_assignment_operator(&token.text);

            if !valid_after {
                // Doesn't look like type args, probably comparison
                self.restore_pos(saved_pos);
                return Ok(None);
            }
        }

        Ok(Some(IrNode::TypeArgs {
            span: IrSpan::new(saved_pos, self.current_byte_offset()),
            args: types,
        }))
    }

    /// Parses a sequence expression: x, y, z
    fn parse_sequence_expr(&mut self, first: IrNode) -> ParseResult<IrNode> {
        let start = first.span().start;
        let mut exprs = vec![first];

        while self.at(SyntaxKind::Comma) {
            self.consume();
            self.skip_whitespace();

            // Parse next expression with assignment precedence
            // (each element in sequence can be an assignment)
            let expr = self.parse_expression_with_precedence(prec::ASSIGN.right)?;
            exprs.push(expr);

            self.skip_whitespace();
        }

        if exprs.len() == 1 {
            Ok(exprs.remove(0))
        } else {
            Ok(IrNode::SeqExpr {
                span: IrSpan::new(start, self.current_byte_offset()),
                exprs,
            })
        }
    }

    /// Parses call arguments: (arg1, arg2, ...)
    pub(super) fn parse_call_arguments(&mut self) -> ParseResult<Vec<IrNode>> {
        let start_pos = self.pos;

        self.expect(SyntaxKind::LParen).ok_or_else(|| {
            ParseError::new(ParseErrorKind::UnexpectedToken, self.current_byte_offset())
                .with_expected(&["("])
        })?;

        let mut args = Vec::new();

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::RParen) {
                break;
            }

            // Check for spread argument: ...expr
            if self.at(SyntaxKind::DotDotDot) {
                let spread_start = self.current_byte_offset();
                self.consume();
                self.skip_whitespace();
                let expr = self.parse_expression_with_precedence(prec::ASSIGN.right)?;
                args.push(IrNode::SpreadElement {
                    span: IrSpan::new(spread_start, self.current_byte_offset()),
                    expr: Box::new(expr),
                });
            } else {
                // Regular argument
                let expr = self.parse_expression_with_precedence(prec::ASSIGN.right)?;
                args.push(expr);
            }

            self.skip_whitespace();

            if self.at(SyntaxKind::Comma) {
                self.consume();
            } else {
                break;
            }
        }

        if !self.at(SyntaxKind::RParen) {
            return Err(ParseError::missing_closing(
                ParseErrorKind::MissingClosingParen,
                self.current_byte_offset(),
                start_pos,
            ));
        }
        self.consume(); // )

        Ok(args)
    }

    /// Peeks at the text of a token at the given offset.
    fn peek_text(&self, offset: usize) -> Option<&str> {
        self.tokens.get(self.pos + offset).map(|t| t.text.as_str())
    }

    /// Peeks at the kind of a token at the given offset.
    pub(in crate::compiler::parser) fn peek_kind(&self, offset: usize) -> Option<SyntaxKind> {
        self.tokens.get(self.pos + offset).map(|t| t.kind)
    }

    /// Restores the parser position (for backtracking).
    fn restore_pos(&mut self, pos: usize) {
        self.pos = pos;
    }
}

#[cfg(test)]
mod tests {
    // Tests will be added with the integration
}