macroforge_ts_quote 0.1.81

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
//! Expression-level control flow parsing.
//!
//! This module implements parsing for control blocks (`{#if}`, `{#for}`, `{#while}`, `{#match}`)
//! when they appear in expression context. Unlike statement-level control blocks that produce
//! `Vec<IrNode>` bodies, expression-level control blocks produce single expressions that
//! evaluate to values.
//!
//! # Examples
//!
//! ```text
//! // If expression (all branches required)
//! const status = {#if cond} "active" {:else} "inactive" {/if};
//!
//! // For expression (produces iterator)
//! const items = [{#for x in list} x.name {/for}];
//!
//! // While expression (produces iterator)
//! const vals = {#while cond} next_val() {/while};
//!
//! // Match expression
//! const val = {#match x}{:case Some(v)} v {:case None} 0 {/match};
//! ```

use super::errors::{ParseError, ParseErrorKind, ParseResult};
use crate::compiler::ir::{IrNode, IrSpan, MatchArmExpr};
use crate::compiler::parser::Parser;
use crate::compiler::syntax::SyntaxKind;

impl Parser {
    /// Parses an if expression: `{#if cond} expr {:else if cond} expr {:else} expr {/if}`
    ///
    /// Unlike statement-level `{#if}`, expression-level if **requires** an `{:else}` branch
    /// because all branches must produce a value.
    pub(super) fn parse_if_expr(&mut self) -> ParseResult<IrNode> {
        let start_byte = self.current_byte_offset();
        // Push TemplateControlBlock context FIRST to preserve parent context (e.g., ObjectLiteral).
        // This must happen before consuming any tokens so that the closing `}` of the header
        // (in `{#if condition}`) doesn't pop the ObjectLiteral context.
        self.push_context(super::super::Context::template_control_block([
            SyntaxKind::BraceColonElseBrace,
            SyntaxKind::BraceColonElseIf,
            SyntaxKind::BraceSlashIfBrace,
        ]));

        // Consume {#if
        self.consume().ok_or_else(|| {
            self.pop_context(); // Clean up on error
            ParseError::unexpected_eof(self.current_byte_offset(), "if-expression opening")
        })?;

        self.skip_whitespace();

        // Parse condition until }
        let condition_str = self.collect_rust_until(SyntaxKind::RBrace);
        if self.expect(SyntaxKind::RBrace).is_none() {
            self.pop_context(); // Clean up on error
            return Err(ParseError::new(
                ParseErrorKind::MissingClosingBrace,
                self.current_byte_offset(),
            )
            .with_context("if-expression condition"));
        }

        // Parse then expression
        let then_expr = self.parse_expr_until_control_continuation()?;

        // Parse else-if branches
        let mut else_if_branches = Vec::new();
        while self.at(SyntaxKind::BraceColonElseIf) {
            self.consume(); // {:else if
            self.skip_whitespace();

            let cond_str = self.collect_rust_until(SyntaxKind::RBrace);
            self.expect(SyntaxKind::RBrace).ok_or_else(|| {
                ParseError::new(
                    ParseErrorKind::MissingClosingBrace,
                    self.current_byte_offset(),
                )
                .with_context("else-if condition")
            })?;

            let expr = self.parse_expr_until_control_continuation()?;
            let cond = Self::str_to_token_stream(&cond_str)
                .map_err(|e| e.with_context("else-if condition"))?;
            else_if_branches.push((cond, Box::new(expr)));
        }

        // Require {:else} in expression context
        if !self.at(SyntaxKind::BraceColonElseBrace) {
            self.pop_context(); // Clean up before error
            return Err(ParseError::new(ParseErrorKind::MissingElseBranch, self.current_byte_offset())
                .with_context("if-expression")
                .with_help("if-expressions require an {:else} branch to produce a value. Add {:else} expr before {/if}."));
        }

        // Parse else branch
        // Note: {:else} is a complete token (includes closing brace), no separate } to expect
        self.consume(); // {:else}
        let else_expr = self.parse_expr_until_control_continuation()?;

        // Skip whitespace before checking for closing tag
        self.skip_whitespace();

        // Pop the TemplateControlBlock context
        self.pop_context();

        // Expect {/if}
        if !self.at(SyntaxKind::BraceSlashIfBrace) {
            return Err(ParseError::new(
                ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["{/if}"])
            .with_context("if-expression"));
        }
        self.consume(); // {/if}

        let condition = Self::str_to_token_stream(&condition_str)
            .map_err(|e| e.with_context("if-expression condition"))?;

        Ok(IrNode::IfExpr {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            condition,
            then_expr: Box::new(then_expr),
            else_if_branches,
            else_expr: Box::new(else_expr),
        })
    }

    /// Parses a for expression: `{#for pattern in iterator} expr {/for}`
    ///
    /// Produces an iterator via `.into_iter().map(|pattern| expr)`.
    pub(super) fn parse_for_expr(&mut self) -> ParseResult<IrNode> {
        let start_byte = self.current_byte_offset();
        // Push TemplateControlBlock context FIRST to preserve parent context (e.g., ObjectLiteral).
        // This must happen before consuming any tokens so that the closing `}` of the header
        // (in `{#for pattern in iter}`) doesn't pop the ObjectLiteral context.
        self.push_context(super::super::Context::template_control_block([
            SyntaxKind::BraceSlashForBrace,
        ]));

        // Consume {#for
        self.consume().ok_or_else(|| {
            self.pop_context(); // Clean up on error
            ParseError::unexpected_eof(self.current_byte_offset(), "for-expression opening")
        })?;

        self.skip_whitespace();

        // Parse pattern until `in` keyword
        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);
            }
        }

        // Expect `in` keyword
        if self.expect(SyntaxKind::InKw).is_none() {
            self.pop_context(); // Clean up on error
            return Err(ParseError::new(
                ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["in"])
            .with_context("for-expression"));
        }

        self.skip_whitespace();

        // Parse iterator until }
        let iterator_str = self.collect_rust_until(SyntaxKind::RBrace);
        if self.expect(SyntaxKind::RBrace).is_none() {
            self.pop_context(); // Clean up on error
            return Err(ParseError::new(
                ParseErrorKind::MissingClosingBrace,
                self.current_byte_offset(),
            )
            .with_context("for-expression iterator"));
        }

        // Parse body expression
        let body_expr = self.parse_expr_until_control_continuation()?;

        // Skip whitespace before checking for closing tag
        self.skip_whitespace();

        // Pop the TemplateControlBlock context
        self.pop_context();

        // Expect {/for}
        if !self.at(SyntaxKind::BraceSlashForBrace) {
            return Err(ParseError::new(
                ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["{/for}"])
            .with_context("for-expression"));
        }
        self.consume(); // {/for}

        let pattern = Self::str_to_token_stream(pattern_str.trim())
            .map_err(|e| e.with_context("for-expression pattern"))?;
        let iterator = Self::str_to_token_stream(&iterator_str)
            .map_err(|e| e.with_context("for-expression iterator"))?;

        Ok(IrNode::ForExpr {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            pattern,
            iterator,
            body_expr: Box::new(body_expr),
        })
    }

    /// Parses a while expression: `{#while condition} expr {/while}`
    ///
    /// Produces an iterator via `std::iter::from_fn(|| if cond { Some(expr) } else { None })`.
    pub(super) fn parse_while_expr(&mut self) -> ParseResult<IrNode> {
        let start_byte = self.current_byte_offset();
        // Push TemplateControlBlock context FIRST to preserve parent context (e.g., ObjectLiteral).
        // This must happen before consuming any tokens so that the closing `}` of the header
        // (in `{#while condition}`) doesn't pop the ObjectLiteral context.
        self.push_context(super::super::Context::template_control_block([
            SyntaxKind::BraceSlashWhileBrace,
        ]));

        // Consume {#while
        self.consume().ok_or_else(|| {
            self.pop_context(); // Clean up on error
            ParseError::unexpected_eof(self.current_byte_offset(), "while-expression opening")
        })?;

        self.skip_whitespace();

        // Parse condition until }
        let condition_str = self.collect_rust_until(SyntaxKind::RBrace);
        if self.expect(SyntaxKind::RBrace).is_none() {
            self.pop_context(); // Clean up on error
            return Err(ParseError::new(
                ParseErrorKind::MissingClosingBrace,
                self.current_byte_offset(),
            )
            .with_context("while-expression condition"));
        }

        // Parse body expression
        let body_expr = self.parse_expr_until_control_continuation()?;

        // Skip whitespace before checking for closing tag
        self.skip_whitespace();

        // Pop the TemplateControlBlock context
        self.pop_context();

        // Expect {/while}
        if !self.at(SyntaxKind::BraceSlashWhileBrace) {
            return Err(ParseError::new(
                ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["{/while}"])
            .with_context("while-expression"));
        }
        self.consume(); // {/while}

        let condition = Self::str_to_token_stream(&condition_str)
            .map_err(|e| e.with_context("while-expression condition"))?;

        Ok(IrNode::WhileExpr {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            condition,
            body_expr: Box::new(body_expr),
        })
    }

    /// Parses a match expression: `{#match expr}{:case pattern} expr {:case pattern} expr {/match}`
    pub(super) fn parse_match_expr(&mut self) -> ParseResult<IrNode> {
        let start_byte = self.current_byte_offset();
        // Push TemplateControlBlock context FIRST to preserve parent context (e.g., ObjectLiteral).
        // This must happen before consuming any tokens so that the closing `}` of the header
        // (in `{#match expr}`) doesn't pop the ObjectLiteral context.
        self.push_context(super::super::Context::template_control_block([
            SyntaxKind::BraceSlashMatchBrace,
            SyntaxKind::BraceColonCase,
        ]));

        // Consume {#match
        self.consume().ok_or_else(|| {
            self.pop_context(); // Clean up on error
            ParseError::unexpected_eof(self.current_byte_offset(), "match-expression opening")
        })?;

        self.skip_whitespace();

        // Parse match expression until }
        let expr_str = self.collect_rust_until(SyntaxKind::RBrace);
        if self.expect(SyntaxKind::RBrace).is_none() {
            self.pop_context(); // Clean up on error
            return Err(ParseError::new(
                ParseErrorKind::MissingClosingBrace,
                self.current_byte_offset(),
            )
            .with_context("match-expression scrutinee"));
        }

        // Parse arms
        let mut arms = Vec::new();
        self.skip_whitespace();

        while self.at(SyntaxKind::BraceColonCase) {
            self.consume(); // {:case
            self.skip_whitespace();

            // Parse pattern (and optional guard) until }
            let raw = self.collect_rust_until(SyntaxKind::RBrace);
            self.expect(SyntaxKind::RBrace).ok_or_else(|| {
                ParseError::new(
                    ParseErrorKind::MissingClosingBrace,
                    self.current_byte_offset(),
                )
                .with_context("match arm pattern")
            })?;

            // Split on ` if ` to extract guard: `Pattern if guard_expr`
            let (pattern_str, guard_str) = if let Some(idx) = raw.find(" if ") {
                (&raw[..idx], Some(&raw[idx + 4..]))
            } else {
                (raw.as_str(), None)
            };

            // Parse body expression
            let body_expr = self.parse_expr_until_control_continuation()?;

            let pattern = Self::str_to_token_stream(pattern_str)
                .map_err(|e| e.with_context("match arm pattern"))?;
            let guard = guard_str
                .map(|g| Self::str_to_token_stream(g.trim()))
                .transpose()
                .map_err(|e| e.with_context("match arm guard"))?;

            arms.push(MatchArmExpr {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                pattern,
                guard,
                body_expr: Box::new(body_expr),
            });

            self.skip_whitespace();
        }

        // Pop the TemplateControlBlock context
        self.pop_context();

        // Expect {/match}
        if !self.at(SyntaxKind::BraceSlashMatchBrace) {
            return Err(ParseError::new(
                ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["{/match}"])
            .with_context("match-expression"));
        }
        self.consume(); // {/match}

        let expr = Self::str_to_token_stream(&expr_str)
            .map_err(|e| e.with_context("match-expression scrutinee"))?;

        Ok(IrNode::MatchExpr {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            expr,
            arms,
        })
    }

    /// Parses an expression until a control flow continuation token.
    ///
    /// Control continuations are: `{:else}`, `{:else if}`, `{/if}`, `{/for}`, `{/while}`, `{/match}`, `{:case}`
    ///
    /// This relies on the TemplateControlBlock context being pushed by the caller, which
    /// preserves the parent context (e.g., ObjectLiteral) so `is_object_literal()` works
    /// correctly by searching the entire context stack.
    fn parse_expr_until_control_continuation(&mut self) -> ParseResult<IrNode> {
        self.skip_whitespace();

        // Define terminators for expression parsing in control flow context
        let terminators = &[
            SyntaxKind::BraceColonElseBrace,
            SyntaxKind::BraceColonElseIf,
            SyntaxKind::BraceSlashIfBrace,
            SyntaxKind::BraceSlashForBrace,
            SyntaxKind::BraceSlashWhileBrace,
            SyntaxKind::BraceSlashMatchBrace,
            SyntaxKind::BraceColonCase,
        ];

        // Check if we're inside an object literal by searching the context stack.
        // is_inside_object_literal() searches the entire stack, so nested contexts
        // (like TemplateControlBlock) can still detect the parent ObjectLiteral.
        let in_object_literal = self.is_inside_object_literal();
        self.parse_expression_until_in_context(terminators, in_object_literal)
    }
}

#[cfg(test)]
mod tests {
    // Integration tests will be in src/test.rs
}