macroforge_ts_quote 0.1.66

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
use super::*;

// =========================================================================
// Control blocks
// =========================================================================

impl Parser {
    /// Dispatch to the appropriate control block parser based on the opening token.
    /// Called when we see BraceHashIf, BraceHashFor, BraceHashWhile, or BraceHashMatch.
    pub(super) fn parse_control_block(&mut self, kind: SyntaxKind) -> super::ParseResult<IrNode> {
        // Consume the opening token (e.g., {#if, {#for, etc.)
        if self.consume().is_none() {
            return Err(ParseError::unexpected_eof(
                self.current_byte_offset(),
                "control block opening",
            ));
        }
        self.skip_whitespace();

        match kind {
            SyntaxKind::BraceHashIf => self.parse_if_block(),
            SyntaxKind::BraceHashFor => self.parse_for_block(),
            SyntaxKind::BraceHashWhile => self.parse_while_block(),
            SyntaxKind::BraceHashMatch => self.parse_match_block(),
            _ => {
                // Unknown control block - consume until }
                self.consume_until_rbrace();
                Err(
                    ParseError::new(ParseErrorKind::UnexpectedToken, self.current_byte_offset())
                        .with_context("control block")
                        .with_help("expected {#if}, {#for}, {#while}, or {#match}"),
                )
            }
        }
    }

    /// Parse control flow inside type context - body content is collected as raw text with placeholders.
    /// Called when we see BraceHashIf, BraceHashFor, or BraceHashWhile in type position.
    pub(super) fn parse_type_control_block(
        &mut self,
        kind: SyntaxKind,
    ) -> super::ParseResult<IrNode> {
        // Consume the opening token (e.g., {#if, {#for, etc.)
        if self.consume().is_none() {
            return Err(ParseError::unexpected_eof(
                self.current_byte_offset(),
                "type control block opening",
            ));
        }
        self.skip_whitespace();

        match kind {
            SyntaxKind::BraceHashIf => self.parse_type_if_block(),
            SyntaxKind::BraceHashFor => self.parse_type_for_block(),
            SyntaxKind::BraceHashWhile => self.parse_type_while_block(),
            _ => {
                self.consume_until_rbrace();
                Err(
                    ParseError::new(ParseErrorKind::UnexpectedToken, self.current_byte_offset())
                        .with_context("type control block")
                        .with_help("expected {#if}, {#for}, or {#while}"),
                )
            }
        }
    }

    fn parse_type_for_block(&mut self) -> super::ParseResult<IrNode> {
        // Note: {#for has already been consumed, we start at the pattern

        // Parse "pattern in iterator"
        let mut pattern_str = String::new();
        while !self.at_eof() && !self.at(SyntaxKind::InKw) && !self.at(SyntaxKind::RBrace) {
            if let Some(token) = self.consume() {
                pattern_str.push_str(&token.text);
            }
        }

        self.expect(SyntaxKind::InKw);
        self.skip_whitespace();

        let iterator_str = self.collect_rust_until(SyntaxKind::RBrace);
        self.expect(SyntaxKind::RBrace);

        // Parse body as type content (raw text with placeholders) until {/for}
        let body = self.parse_type_block_body(&[SyntaxKind::BraceSlashForBrace])?;

        // Consume {/for} - it's a complete token including the closing brace
        if self.at(SyntaxKind::BraceSlashForBrace) {
            self.consume();
        }

        Ok(IrNode::For {
            span: IrSpan::empty(),
            pattern: Self::str_to_token_stream(pattern_str.trim())
                .map_err(|e| e.with_context("type for-loop pattern"))?,
            iterator: Self::str_to_token_stream(&iterator_str)
                .map_err(|e| e.with_context("type for-loop iterator"))?,
            body: Self::merge_adjacent_text(body),
        })
    }

    fn parse_type_if_block(&mut self) -> super::ParseResult<IrNode> {
        // Note: {#if has already been consumed, we start at the condition

        // Parse condition until }
        let condition_str = self.collect_rust_until(SyntaxKind::RBrace);
        let condition = Self::str_to_token_stream(&condition_str)
            .map_err(|e| e.with_context("type if-block condition"))?;
        self.expect(SyntaxKind::RBrace);

        // Parse body as type content until {:else}, {:else if}, or {/if}
        let then_body = self.parse_type_block_body(&[
            SyntaxKind::BraceColonElseBrace,
            SyntaxKind::BraceColonElseIf,
            SyntaxKind::BraceSlashIfBrace,
        ])?;

        // Check for else-if and else clauses
        let mut else_if_branches = Vec::new();
        let mut else_body = None;

        loop {
            match self.current_kind() {
                Some(SyntaxKind::BraceColonElseIf) => {
                    // {:else if condition} - consume the token, then parse condition
                    self.consume();
                    self.skip_whitespace();
                    let cond_str = self.collect_rust_until(SyntaxKind::RBrace);
                    let cond = Self::str_to_token_stream(&cond_str)
                        .map_err(|e| e.with_context("type else-if condition"))?;
                    self.expect(SyntaxKind::RBrace);
                    let body = self.parse_type_block_body(&[
                        SyntaxKind::BraceColonElseBrace,
                        SyntaxKind::BraceColonElseIf,
                        SyntaxKind::BraceSlashIfBrace,
                    ])?;
                    else_if_branches.push((cond, body));
                }
                Some(SyntaxKind::BraceColonElseBrace) => {
                    // {:else} - complete token including closing brace
                    self.consume();
                    else_body = Some(self.parse_type_block_body(&[SyntaxKind::BraceSlashIfBrace])?);
                    break;
                }
                _ => break,
            }
        }

        // Consume {/if} - complete token including closing brace
        if self.at(SyntaxKind::BraceSlashIfBrace) {
            self.consume();
        }

        Ok(IrNode::If {
            span: IrSpan::empty(),
            condition,
            then_body: Self::merge_adjacent_text(then_body),
            else_if_branches: else_if_branches
                .into_iter()
                .map(|(c, b)| (c, Self::merge_adjacent_text(b)))
                .collect(),
            else_body: else_body.map(Self::merge_adjacent_text),
        })
    }

    fn parse_type_while_block(&mut self) -> super::ParseResult<IrNode> {
        // Note: {#while has already been consumed, we start at the condition

        let condition_str = self.collect_rust_until(SyntaxKind::RBrace);
        let condition = Self::str_to_token_stream(&condition_str)
            .map_err(|e| e.with_context("type while-block condition"))?;
        self.expect(SyntaxKind::RBrace);

        let body = self.parse_type_block_body(&[SyntaxKind::BraceSlashWhileBrace])?;

        // Consume {/while} - complete token including closing brace
        if self.at(SyntaxKind::BraceSlashWhileBrace) {
            self.consume();
        }

        Ok(IrNode::While {
            span: IrSpan::empty(),
            condition,
            body: Self::merge_adjacent_text(body),
        })
    }

    /// Parse block body in type context - collects raw text with placeholders and nested control flow
    fn parse_type_block_body(
        &mut self,
        terminators: &[SyntaxKind],
    ) -> super::ParseResult<Vec<IrNode>> {
        let mut nodes = Vec::new();

        while !self.at_eof() {
            if let Some(kind) = self.current_kind() {
                if terminators.contains(&kind) {
                    break;
                }

                match kind {
                    SyntaxKind::At => {
                        // Placeholder
                        let placeholder = self.parse_interpolation()?;
                        // Check for identifier suffix
                        if let Some(token) = self.current() {
                            if token.kind == SyntaxKind::Ident {
                                let suffix_token = self.consume().unwrap();
                                let ident_placeholder = match placeholder {
                                    IrNode::Placeholder { span, expr, .. } => IrNode::Placeholder {
                                        span,
                                        kind: PlaceholderKind::Ident,
                                        expr,
                                    },
                                    other => other,
                                };
                                nodes.push(IrNode::IdentBlock {
                                    span: IrSpan::empty(),
                                    parts: vec![ident_placeholder, IrNode::ident(&suffix_token)],
                                });
                                continue;
                            }
                        }
                        nodes.push(placeholder);
                    }
                    // Nested control flow - handle specific opening tokens
                    SyntaxKind::BraceHashIf
                    | SyntaxKind::BraceHashFor
                    | SyntaxKind::BraceHashWhile => {
                        let control = self.parse_type_control_block(kind)?;
                        nodes.push(control);
                    }
                    _ => {
                        // Raw text
                        if let Some(token) = self.consume() {
                            nodes.push(IrNode::ident(&token));
                        }
                    }
                }
            } else {
                break;
            }
        }

        Ok(nodes)
    }

    fn parse_if_block(&mut self) -> super::ParseResult<IrNode> {
        // Note: {#if has already been consumed, we start at the condition

        // Parse condition until }
        let condition_str = self.collect_rust_until(SyntaxKind::RBrace);
        let condition = Self::str_to_token_stream(&condition_str)
            .map_err(|e| e.with_context("if-block condition"))?;
        self.expect(SyntaxKind::RBrace);

        // Parse body until {:else}, {:else if}, or {/if}
        let then_body = self.parse_block_body(&[
            SyntaxKind::BraceColonElseBrace,
            SyntaxKind::BraceColonElseIf,
            SyntaxKind::BraceSlashIfBrace,
        ])?;

        // Check for else-if and else clauses
        let mut else_if_branches = Vec::new();
        let mut else_body = None;

        loop {
            match self.current_kind() {
                Some(SyntaxKind::BraceColonElseIf) => {
                    // {:else if condition} - consume the token, then parse condition
                    self.consume();
                    self.skip_whitespace();
                    let cond_str = self.collect_rust_until(SyntaxKind::RBrace);
                    let cond = Self::str_to_token_stream(&cond_str)
                        .map_err(|e| e.with_context("else-if condition"))?;
                    self.expect(SyntaxKind::RBrace);
                    let body = self.parse_block_body(&[
                        SyntaxKind::BraceColonElseBrace,
                        SyntaxKind::BraceColonElseIf,
                        SyntaxKind::BraceSlashIfBrace,
                    ])?;
                    else_if_branches.push((cond, body));
                }
                Some(SyntaxKind::BraceColonElseBrace) => {
                    // {:else} - complete token including closing brace
                    self.consume();
                    else_body = Some(self.parse_block_body(&[SyntaxKind::BraceSlashIfBrace])?);
                    break;
                }
                _ => break,
            }
        }

        // Consume {/if} - complete token including closing brace
        if self.at(SyntaxKind::BraceSlashIfBrace) {
            self.consume();
        }

        Ok(IrNode::If {
            span: IrSpan::empty(),
            condition,
            then_body,
            else_if_branches,
            else_body,
        })
    }

    fn parse_for_block(&mut self) -> super::ParseResult<IrNode> {
        // Note: {#for has already been consumed, we start at the pattern

        // Parse "pattern in iterator"
        let mut pattern_str = String::new();
        while !self.at_eof() && !self.at(SyntaxKind::InKw) && !self.at(SyntaxKind::RBrace) {
            if let Some(token) = self.consume() {
                pattern_str.push_str(&token.text);
            }
        }

        self.expect(SyntaxKind::InKw);
        self.skip_whitespace();

        let iterator_str = self.collect_rust_until(SyntaxKind::RBrace);
        self.expect(SyntaxKind::RBrace);

        // Parse body
        let body = self.parse_block_body(&[SyntaxKind::BraceSlashForBrace])?;

        // Consume {/for} - complete token including closing brace
        if self.at(SyntaxKind::BraceSlashForBrace) {
            self.consume();
        }

        Ok(IrNode::For {
            span: IrSpan::empty(),
            pattern: Self::str_to_token_stream(pattern_str.trim())
                .map_err(|e| e.with_context("for-loop pattern"))?,
            iterator: Self::str_to_token_stream(&iterator_str)
                .map_err(|e| e.with_context("for-loop iterator"))?,
            body,
        })
    }

    fn parse_while_block(&mut self) -> super::ParseResult<IrNode> {
        // Note: {#while has already been consumed, we start at the condition

        let condition_str = self.collect_rust_until(SyntaxKind::RBrace);
        self.expect(SyntaxKind::RBrace);

        let body = self.parse_block_body(&[SyntaxKind::BraceSlashWhileBrace])?;

        // Consume {/while} - complete token including closing brace
        if self.at(SyntaxKind::BraceSlashWhileBrace) {
            self.consume();
        }

        Ok(IrNode::While {
            span: IrSpan::empty(),
            condition: Self::str_to_token_stream(&condition_str)
                .map_err(|e| e.with_context("while-block condition"))?,
            body,
        })
    }

    fn parse_match_block(&mut self) -> super::ParseResult<IrNode> {
        // Note: {#match has already been consumed, we start at the expression

        let expr_str = self.collect_rust_until(SyntaxKind::RBrace);
        self.expect(SyntaxKind::RBrace);

        let mut arms = Vec::new();

        // Skip whitespace after the match expression before looking for cases
        self.skip_whitespace();

        // Parse cases
        while self.at(SyntaxKind::BraceColonCase) {
            // Consume {:case - the token contains "{:case" but not the pattern or closing brace
            self.consume();
            self.skip_whitespace();

            let pattern_str = self.collect_rust_until(SyntaxKind::RBrace);
            self.expect(SyntaxKind::RBrace);

            let body = self.parse_block_body(&[
                SyntaxKind::BraceColonCase,
                SyntaxKind::BraceSlashMatchBrace,
            ])?;

            arms.push(MatchArm {
                span: IrSpan::empty(),
                pattern: Self::str_to_token_stream(&pattern_str)
                    .map_err(|e| e.with_context("match case pattern"))?,
                guard: None,
                body,
            });
        }

        // Consume {/match} - complete token including closing brace
        if self.at(SyntaxKind::BraceSlashMatchBrace) {
            self.consume();
        }

        Ok(IrNode::Match {
            span: IrSpan::empty(),
            expr: Self::str_to_token_stream(&expr_str)
                .map_err(|e| e.with_context("match expression"))?,
            arms,
        })
    }

    pub(super) fn parse_block_body(
        &mut self,
        terminators: &[SyntaxKind],
    ) -> super::ParseResult<Vec<IrNode>> {
        let mut nodes = Vec::new();

        // Check context to determine parsing strategy
        let in_interface = self.is_inside_interface();

        while !self.at_eof() {
            self.skip_whitespace();

            if self.at_eof() {
                break;
            }

            if let Some(kind) = self.current_kind() {
                if terminators.contains(&kind) {
                    break;
                }
            }

            // Check for nested control flow (works in all contexts)
            if self.at_brace_hash_open() {
                let kind = self.current_kind().unwrap();
                nodes.push(self.parse_control_block(kind)?);
                continue;
            }

            // Check for directives (works in all contexts)
            if self.at(SyntaxKind::DollarOpen) {
                if let Some(node) = self.parse_directive() {
                    nodes.push(node);
                }
                continue;
            }

            if in_interface {
                // Interface context: parse as interface member
                match self.parse_interface_member()? {
                    Some(member) => nodes.push(member),
                    None => {
                        return Err(super::ParseError::new(
                            super::ParseErrorKind::UnexpectedToken,
                            self.current_byte_offset(),
                        )
                        .with_context("expected interface member in control block body"));
                    }
                }
            } else {
                // Statement context: parse as structured statement
                let stmt = self.parse_stmt()?;
                nodes.push(stmt);
            }
        }

        Ok(nodes)
    }

    pub(super) fn collect_rust_until(&mut self, terminator: SyntaxKind) -> String {
        let mut result = String::new();

        while !self.at_eof() && !self.at(terminator) {
            if let Some(token) = self.consume() {
                result.push_str(&token.text);
            }
        }

        result.trim().to_string()
    }

    /// Convert a string to a TokenStream, returning an error if parsing fails.
    pub(super) fn str_to_token_stream(s: &str) -> ParseResult<TokenStream> {
        TokenStream::from_str(s).map_err(|e| {
            ParseError::new(ParseErrorKind::InvalidRustExpression, 0)
                .with_context("Rust expression")
                .with_found(s)
                .with_help(&format!(
                    "Failed to parse as Rust token stream: {}. \
                     Ensure the expression is valid Rust syntax.",
                    e
                ))
        })
    }

    /// Convert a string to a TokenStream, panicking with a detailed error if parsing fails.
    /// Use this in contexts where returning an error is not possible (e.g., inside control blocks).
    pub(super) fn str_to_token_stream_or_panic(s: &str, context: &str) -> TokenStream {
        Self::str_to_token_stream(s).unwrap_or_else(|e| {
            panic!(
                "Failed to parse Rust expression in {}: '{}'\n{}",
                context,
                s,
                e.to_message()
            )
        })
    }
}