Skip to main content

mq_lang/ast/
code.rs

1use crate::{IMPLICIT_FN_ARG, Ident, Program, Shared};
2
3use super::node::{AccessTarget, Args, BinaryOp, Expr, Literal, Node, Param, Pattern, StringSegment, UnaryOp};
4use std::fmt::Write;
5
6impl Node {
7    /// Converts the AST node back to mq code code.
8    pub fn to_code(&self) -> String {
9        let mut output = String::new();
10        self.format_to_code(&mut output, 0);
11        output
12    }
13
14    fn format_to_code(&self, buf: &mut String, indent: usize) {
15        match &self.expr {
16            Expr::Literal(lit) => {
17                format_literal(lit, buf);
18            }
19            Expr::Ident(ident) => {
20                write!(buf, "{}", ident).unwrap();
21            }
22            Expr::Self_ => {
23                buf.push_str("self");
24            }
25            Expr::Env(name) => {
26                write!(buf, "${}", name).unwrap();
27            }
28            Expr::Nodes => {
29                buf.push_str("nodes");
30            }
31            Expr::Selector(selector) => {
32                write!(buf, "{}", selector).unwrap();
33            }
34            Expr::SelectorCall(selector, args) => {
35                write!(buf, "{}", selector).unwrap();
36                buf.push('(');
37                format_args(args, buf, indent);
38                buf.push(')');
39            }
40            Expr::Break(None) => {
41                buf.push_str("break");
42            }
43            Expr::Break(Some(value)) => {
44                buf.push_str("break: ");
45                value.format_to_code(buf, indent);
46            }
47            Expr::Continue => {
48                buf.push_str("continue");
49            }
50            Expr::Yield(None) => {
51                buf.push_str("yield");
52            }
53            Expr::Yield(Some(value)) => {
54                buf.push_str("yield: ");
55                value.format_to_code(buf, indent);
56            }
57            Expr::Paren(node) => {
58                buf.push('(');
59                node.format_to_code(buf, indent);
60                buf.push(')');
61            }
62            Expr::And(operands) => {
63                for (i, op) in operands.iter().enumerate() {
64                    if i > 0 {
65                        buf.push_str(" && ");
66                    }
67                    op.format_to_code(buf, indent);
68                }
69            }
70            Expr::Or(operands) => {
71                for (i, op) in operands.iter().enumerate() {
72                    if i > 0 {
73                        buf.push_str(" || ");
74                    }
75                    op.format_to_code(buf, indent);
76                }
77            }
78            Expr::Call(func, args) => {
79                write!(buf, "{}", func).unwrap();
80                buf.push('(');
81                format_args(args, buf, indent);
82                buf.push(')');
83            }
84            Expr::BinaryOp(op, lhs, rhs) => {
85                format_binary_operand(lhs, *op, buf, indent, false);
86                write!(buf, " {} ", op.as_str()).unwrap();
87                format_binary_operand(rhs, *op, buf, indent, true);
88            }
89            Expr::Index(target, index) => {
90                format_index_target(target, buf, indent);
91                buf.push('[');
92                index.format_to_code(buf, indent);
93                buf.push(']');
94            }
95            Expr::Slice(target, start, end) => {
96                format_index_target(target, buf, indent);
97                buf.push('[');
98                start.format_to_code(buf, indent);
99                buf.push(':');
100                if let Some(end) = end {
101                    end.format_to_code(buf, indent);
102                }
103                buf.push(']');
104            }
105            Expr::UnaryOp(op, operand) => {
106                buf.push_str(op.as_str());
107                let needs_parens = match &operand.expr {
108                    Expr::BinaryOp(..) | Expr::And(_) | Expr::Or(_) => true,
109                    // `--x` and `!-x` do not parse.
110                    Expr::UnaryOp(inner_op, ..) => *op == UnaryOp::Neg || *inner_op == UnaryOp::Neg,
111                    _ => false,
112                };
113                if needs_parens {
114                    buf.push('(');
115                    operand.format_to_code(buf, indent);
116                    buf.push(')');
117                } else {
118                    operand.format_to_code(buf, indent);
119                }
120            }
121            Expr::Array(args) => {
122                buf.push('[');
123                format_args(args, buf, indent);
124                buf.push(']');
125            }
126            Expr::Dict(pairs) => {
127                buf.push('{');
128                for (i, pair) in pairs.iter().enumerate() {
129                    if i > 0 {
130                        buf.push_str(", ");
131                    }
132                    if let Expr::Array(kv) = &pair.expr {
133                        kv[0].format_to_code(buf, indent);
134                        buf.push_str(": ");
135                        kv[1].format_to_code(buf, indent);
136                    } else {
137                        pair.format_to_code(buf, indent);
138                    }
139                }
140                buf.push('}');
141            }
142            Expr::CallDynamic(func, args) => {
143                func.format_to_code(buf, indent);
144                buf.push('(');
145                format_args(args, buf, indent);
146                buf.push(')');
147            }
148            Expr::As(ident, value) => {
149                value.format_to_code(buf, indent);
150                write!(buf, " as {}", ident).unwrap();
151            }
152            Expr::Let(pattern, value) => {
153                buf.push_str("let ");
154                format_pattern(pattern, buf);
155                buf.push_str(" = ");
156                value.format_to_code(buf, indent);
157            }
158            Expr::Var(pattern, value) => {
159                buf.push_str("var ");
160                format_pattern(pattern, buf);
161                buf.push_str(" = ");
162                value.format_to_code(buf, indent);
163            }
164            Expr::Assign(ident, value) => {
165                write!(buf, "{} = ", ident).unwrap();
166                value.format_to_code(buf, indent);
167            }
168            Expr::IndexAssign(ident, index, value) => {
169                write!(buf, "{}[", ident).unwrap();
170                index.format_to_code(buf, indent);
171                buf.push_str("] = ");
172                value.format_to_code(buf, indent);
173            }
174            Expr::PathAssign(ident, keys, value) => {
175                write!(buf, "{}", ident).unwrap();
176                for key in keys {
177                    buf.push('[');
178                    key.format_to_code(buf, indent);
179                    buf.push(']');
180                }
181                buf.push_str(" = ");
182                value.format_to_code(buf, indent);
183            }
184            Expr::If(branches) => {
185                for (i, (cond_opt, body)) in branches.iter().enumerate() {
186                    if i == 0 {
187                        buf.push_str("if ");
188                        if let Some(cond) = cond_opt {
189                            buf.push('(');
190                            cond.format_to_code(buf, indent);
191                            buf.push(')');
192                        }
193                        buf.push_str(": ");
194                        body.format_to_code(buf, indent);
195                    } else if let Some(cond) = cond_opt {
196                        buf.push_str(" elif (");
197                        cond.format_to_code(buf, indent);
198                        buf.push_str("): ");
199                        body.format_to_code(buf, indent);
200                    } else {
201                        buf.push_str(" else: ");
202                        body.format_to_code(buf, indent);
203                    }
204                }
205            }
206            Expr::While(cond, program) => {
207                buf.push_str("while (");
208                cond.format_to_code(buf, indent);
209                buf.push(')');
210                if needs_block_syntax(program) {
211                    format_program_block(program, buf, indent);
212                } else if let Some(stmt) = program.first() {
213                    buf.push_str(": ");
214                    stmt.format_to_code(buf, indent);
215                }
216            }
217            Expr::Loop(program) => {
218                buf.push_str("loop");
219                format_program_block(program, buf, indent);
220            }
221            Expr::Until(cond, program) => {
222                buf.push_str("until (");
223                cond.format_to_code(buf, indent);
224                buf.push(')');
225                if needs_block_syntax(program) {
226                    format_program_block(program, buf, indent);
227                } else if let Some(stmt) = program.first() {
228                    buf.push_str(": ");
229                    stmt.format_to_code(buf, indent);
230                }
231            }
232            Expr::Unless(branches) => {
233                if let Some((cond_opt, body)) = branches.first() {
234                    buf.push_str("unless ");
235                    if let Some(cond) = cond_opt {
236                        buf.push('(');
237                        cond.format_to_code(buf, indent);
238                        buf.push(')');
239                    }
240                    buf.push_str(": ");
241                    body.format_to_code(buf, indent);
242                }
243            }
244            Expr::Foreach(item, iter, program) => {
245                write!(buf, "foreach({}, ", item).unwrap();
246                iter.format_to_code(buf, indent);
247                buf.push(')');
248                if needs_block_syntax(program) {
249                    format_program_block(program, buf, indent);
250                } else if let Some(stmt) = program.first() {
251                    buf.push_str(": ");
252                    stmt.format_to_code(buf, indent);
253                }
254            }
255            Expr::Block(program) => {
256                // Remove leading space from format_program_block output
257                let start_len = buf.len();
258                format_program_block(program, buf, indent);
259                // format_program_block adds " do", but Block doesn't need leading space
260                if buf[start_len..].starts_with(' ') {
261                    buf.replace_range(start_len..start_len + 1, "");
262                }
263            }
264            Expr::Def(name, params, program) => {
265                write!(buf, "def {}(", name).unwrap();
266                format_params(params, buf, indent);
267                buf.push(')');
268                if needs_block_syntax(program) {
269                    format_program_block(program, buf, indent);
270                } else if let Some(stmt) = program.first() {
271                    buf.push_str(": ");
272                    stmt.format_to_code(buf, indent);
273                }
274            }
275            Expr::Fn(params, program) => {
276                if let Some(body) = implicit_fn_body(params, program) {
277                    buf.push_str("fn: ");
278                    for (i, stmt) in body.iter().enumerate() {
279                        if i > 0 {
280                            buf.push_str(" | ");
281                        }
282                        stmt.format_to_code(buf, indent);
283                    }
284                    buf.push(';');
285                } else {
286                    buf.push_str("fn(");
287                    format_params(params, buf, indent);
288                    buf.push(')');
289                    if needs_block_syntax(program) {
290                        format_program_block(program, buf, indent);
291                    } else if let Some(stmt) = program.first() {
292                        buf.push_str(": ");
293                        stmt.format_to_code(buf, indent);
294                    }
295                }
296            }
297            Expr::Match(value, arms) => {
298                buf.push_str("match (");
299                value.format_to_code(buf, indent);
300                buf.push_str(") do");
301                for arm in arms.iter() {
302                    buf.push('\n');
303                    buf.push_str(&"  ".repeat(indent + 1));
304                    buf.push_str("| ");
305                    format_pattern(&arm.pattern, buf);
306                    if let Some(guard) = &arm.guard {
307                        buf.push_str(" if ");
308                        guard.format_to_code(buf, indent + 1);
309                    }
310                    buf.push_str(": ");
311                    arm.body.format_to_code(buf, indent + 1);
312                }
313                buf.push('\n');
314                buf.push_str(&"  ".repeat(indent));
315                buf.push_str("end");
316            }
317            Expr::InterpolatedString(segments) => {
318                buf.push_str("s\"");
319                for segment in segments.iter() {
320                    match segment {
321                        StringSegment::Text(text) => {
322                            buf.push_str(&escape_string(text));
323                        }
324                        StringSegment::Expr(expr) => {
325                            buf.push_str("${");
326                            expr.format_to_code(buf, indent);
327                            buf.push('}');
328                        }
329                        StringSegment::Env(name) => {
330                            write!(buf, "${{{}}}", name).unwrap();
331                        }
332                        StringSegment::Self_ => {
333                            buf.push_str("${self}");
334                        }
335                    }
336                }
337                buf.push('"');
338            }
339            Expr::Try(try_expr, error_binder, catch_expr) => {
340                buf.push_str("try ");
341                try_expr.format_to_code(buf, indent);
342                match error_binder {
343                    Some(binder) => write!(buf, " catch({}): ", binder).unwrap(),
344                    None => buf.push_str(" catch: "),
345                }
346                catch_expr.format_to_code(buf, indent);
347            }
348            Expr::Module(name, program) => {
349                write!(buf, "module {}", name).unwrap();
350                format_program_block(program, buf, indent);
351            }
352            Expr::QualifiedAccess(path, target) => {
353                for (i, part) in path.iter().enumerate() {
354                    if i > 0 {
355                        buf.push_str("::");
356                    }
357                    write!(buf, "{}", part).unwrap();
358                }
359                match target {
360                    AccessTarget::Call(func, args) => {
361                        write!(buf, "::{}", func).unwrap();
362                        buf.push('(');
363                        format_args(args, buf, indent);
364                        buf.push(')');
365                    }
366                    AccessTarget::Ident(ident) => {
367                        write!(buf, "::{}", ident).unwrap();
368                    }
369                }
370            }
371            Expr::Include(path) => {
372                buf.push_str("include ");
373                format_literal(path, buf);
374            }
375            Expr::Import(path, alias) => {
376                buf.push_str("import ");
377                format_literal(path, buf);
378                if let Some(alias) = alias {
379                    write!(buf, " as {}", alias).unwrap();
380                }
381            }
382        }
383    }
384}
385
386fn escape_string(s: &str) -> String {
387    let mut result = String::with_capacity(s.len());
388    for ch in s.chars() {
389        match ch {
390            '\\' => result.push_str("\\\\"),
391            '"' => result.push_str("\\\""),
392            '\n' => result.push_str("\\n"),
393            '\t' => result.push_str("\\t"),
394            '\r' => result.push_str("\\r"),
395            _ => result.push(ch),
396        }
397    }
398    result
399}
400
401/// Matches `TokenKind::binary_op_precedence` so generated code re-parses into the same tree.
402pub(super) fn binary_op_precedence(op: BinaryOp) -> u8 {
403    match op {
404        BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge => 0,
405        BinaryOp::Add | BinaryOp::Sub => 1,
406        BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod => 2,
407    }
408}
409
410/// Parenthesizes an indexed target that would otherwise re-parse with the index binding tighter.
411fn format_index_target(target: &Node, buf: &mut String, indent: usize) {
412    if matches!(
413        &target.expr,
414        Expr::BinaryOp(..) | Expr::UnaryOp(..) | Expr::And(_) | Expr::Or(_)
415    ) {
416        buf.push('(');
417        target.format_to_code(buf, indent);
418        buf.push(')');
419    } else {
420        target.format_to_code(buf, indent);
421    }
422}
423
424/// Parenthesizes an operand when printing it bare would re-parse into a different tree
425/// (lower precedence, or equal precedence on the right since these ops are left-associative).
426/// `&&`/`||` always need parens since they bind looser than every `BinaryOp`.
427fn format_binary_operand(operand: &Node, parent_op: BinaryOp, buf: &mut String, indent: usize, is_right: bool) {
428    let needs_parens = match &operand.expr {
429        Expr::BinaryOp(child_op, ..) => {
430            if is_right {
431                binary_op_precedence(*child_op) <= binary_op_precedence(parent_op)
432            } else {
433                binary_op_precedence(*child_op) < binary_op_precedence(parent_op)
434            }
435        }
436        Expr::And(_) | Expr::Or(_) => true,
437        _ => false,
438    };
439    if needs_parens {
440        buf.push('(');
441        operand.format_to_code(buf, indent);
442        buf.push(')');
443        return;
444    }
445    operand.format_to_code(buf, indent);
446}
447
448fn format_literal(literal: &Literal, buf: &mut String) {
449    match literal {
450        Literal::String(s) => {
451            buf.push('"');
452            buf.push_str(&escape_string(s));
453            buf.push('"');
454        }
455        Literal::Bytes(b) => {
456            buf.push_str("b\"");
457            for byte in b {
458                if byte.is_ascii_graphic() && *byte != b'"' && *byte != b'\\' {
459                    buf.push(*byte as char);
460                } else {
461                    write!(buf, "\\x{:02x}", byte).unwrap();
462                }
463            }
464            buf.push('"');
465        }
466        Literal::Number(n) => {
467            write!(buf, "{}", n).unwrap();
468        }
469        Literal::Symbol(ident) => {
470            write!(buf, ":{}", ident).unwrap();
471        }
472        Literal::Bool(b) => {
473            buf.push_str(if *b { "true" } else { "false" });
474        }
475        Literal::None => {
476            buf.push_str("none");
477        }
478    }
479}
480
481fn format_args(args: &Args, buf: &mut String, indent: usize) {
482    for (i, arg) in args.iter().enumerate() {
483        if i > 0 {
484            buf.push_str(", ");
485        }
486        arg.format_to_code(buf, indent);
487    }
488}
489
490fn format_params(params: &[Param], buf: &mut String, indent: usize) {
491    for (i, param) in params.iter().enumerate() {
492        if i > 0 {
493            buf.push_str(", ");
494        }
495
496        write!(buf, "{}", param.ident).unwrap();
497        if let Some(default) = &param.default {
498            buf.push_str(" = ");
499            default.format_to_code(buf, indent);
500        }
501    }
502}
503
504fn format_program_block(program: &[Shared<Node>], buf: &mut String, indent: usize) {
505    buf.push_str(" do\n");
506    buf.push_str(&"  ".repeat(indent + 1));
507    for (i, stmt) in program.iter().enumerate() {
508        if i > 0 {
509            buf.push_str(" | ");
510        }
511        stmt.format_to_code(buf, indent + 1);
512    }
513    buf.push('\n');
514    buf.push_str(&"  ".repeat(indent));
515    buf.push_str("end");
516}
517
518fn format_pattern(pattern: &Pattern, buf: &mut String) {
519    match pattern {
520        Pattern::Literal(lit) => {
521            format_literal(lit, buf);
522        }
523        Pattern::Ident(ident) => {
524            write!(buf, "{}", ident).unwrap();
525        }
526        Pattern::Wildcard => {
527            buf.push('_');
528        }
529        Pattern::Array(patterns) => {
530            buf.push('[');
531            for (i, p) in patterns.iter().enumerate() {
532                if i > 0 {
533                    buf.push_str(", ");
534                }
535                format_pattern(p, buf);
536            }
537            buf.push(']');
538        }
539        Pattern::ArrayRest(patterns, rest) => {
540            buf.push('[');
541            for (i, p) in patterns.iter().enumerate() {
542                if i > 0 {
543                    buf.push_str(", ");
544                }
545                format_pattern(p, buf);
546            }
547            if !patterns.is_empty() {
548                buf.push_str(", ");
549            }
550            write!(buf, "..{}", rest).unwrap();
551            buf.push(']');
552        }
553        Pattern::Dict(entries) => {
554            buf.push('{');
555            for (i, (key, value)) in entries.iter().enumerate() {
556                if i > 0 {
557                    buf.push_str(", ");
558                }
559                write!(buf, "{}: ", key).unwrap();
560                format_pattern(value, buf);
561            }
562            buf.push('}');
563        }
564        Pattern::Type(type_name) => {
565            write!(buf, ":{}", type_name).unwrap();
566        }
567        Pattern::Or(patterns) => {
568            for (i, p) in patterns.iter().enumerate() {
569                if i > 0 {
570                    buf.push_str(" || ");
571                }
572                format_pattern(p, buf);
573            }
574        }
575    }
576}
577
578/// The statements of `fn: body` after the synthetic leading argument reference.
579fn implicit_fn_body<'a>(params: &[Param], program: &'a Program) -> Option<&'a [Shared<Node>]> {
580    let arg = Ident::new(IMPLICIT_FN_ARG);
581    let [param] = params else {
582        return None;
583    };
584    match program.split_first() {
585        Some((first, body)) if param.ident.name == arg && matches!(&first.expr, Expr::Ident(i) if i.name == arg) => {
586            Some(body)
587        }
588        _ => None,
589    }
590}
591
592fn needs_block_syntax(program: &[Shared<Node>]) -> bool {
593    program.len() > 1
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599    use crate::{
600        Ident, IdentWithToken, Shared,
601        arena::ArenaId,
602        ast::node::{MatchArm, Param, Pattern},
603        number::Number,
604    };
605    use rstest::rstest;
606    use smallvec::smallvec;
607    use thin_vec::{ThinVec, thin_vec};
608
609    // Helper function to create a Node from an Expr
610    fn create_node(expr: Expr) -> Node {
611        Node {
612            token_id: ArenaId::new(0),
613            expr,
614        }
615    }
616
617    #[rstest]
618    #[case::string(Literal::String("hello".into()), r#""hello""#)]
619    #[case::string_with_quote(Literal::String(r#"hello"world"#.into()), r#""hello\"world""#)]
620    #[case::string_with_backslash(Literal::String(r"hello\world".into()), r#""hello\\world""#)]
621    #[case::string_with_newline(Literal::String("hello\nworld".into()), r#""hello\nworld""#)]
622    #[case::string_with_tab(Literal::String("hello\tworld".into()), r#""hello\tworld""#)]
623    #[case::number_int(Literal::Number(Number::new(42.0)), "42")]
624    #[case::number_float(Literal::Number(Number::new(42.5)), "42.5")]
625    #[case::symbol(Literal::Symbol(Ident::new("test")), ":test")]
626    #[case::bool_true(Literal::Bool(true), "true")]
627    #[case::bool_false(Literal::Bool(false), "false")]
628    #[case::none(Literal::None, "none")]
629    fn test_to_code_literals(#[case] literal: Literal, #[case] expected: &str) {
630        let node = create_node(Expr::Literal(literal));
631        assert_eq!(node.to_code(), expected);
632    }
633
634    #[rstest]
635    #[case::ident(Expr::Ident(IdentWithToken::new("foo")), "foo")]
636    #[case::self_(Expr::Self_, "self")]
637    #[case::nodes(Expr::Nodes, "nodes")]
638    #[case::break_(Expr::Break(None), "break")]
639    #[case::continue_(Expr::Continue, "continue")]
640    fn test_to_code_simple_expressions(#[case] expr: Expr, #[case] expected: &str) {
641        let node = create_node(expr);
642        assert_eq!(node.to_code(), expected);
643    }
644
645    #[rstest]
646    #[case::simple(Expr::Literal(Literal::Number(Number::new(42.0))), "(42)")]
647    #[case::ident(Expr::Ident(IdentWithToken::new("x")), "(x)")]
648    fn test_to_code_paren(#[case] inner_expr: Expr, #[case] expected: &str) {
649        let inner_node = Shared::new(create_node(inner_expr));
650        let node = create_node(Expr::Paren(inner_node));
651        assert_eq!(node.to_code(), expected);
652    }
653
654    #[rstest]
655    #[case::and(
656        Expr::And(thin_vec![
657            Shared::new(create_node(Expr::Ident(IdentWithToken::new("x")))),
658            Shared::new(create_node(Expr::Ident(IdentWithToken::new("y")))),
659        ]),
660        "x && y"
661    )]
662    #[case::or(
663        Expr::Or(thin_vec![
664            Shared::new(create_node(Expr::Ident(IdentWithToken::new("a")))),
665            Shared::new(create_node(Expr::Ident(IdentWithToken::new("b")))),
666        ]),
667        "a || b"
668    )]
669    #[case::and_three_operands(
670        Expr::And(thin_vec![
671            Shared::new(create_node(Expr::Ident(IdentWithToken::new("x")))),
672            Shared::new(create_node(Expr::Ident(IdentWithToken::new("y")))),
673            Shared::new(create_node(Expr::Ident(IdentWithToken::new("z")))),
674        ]),
675        "x && y && z"
676    )]
677    #[case::or_three_operands(
678        Expr::Or(thin_vec![
679            Shared::new(create_node(Expr::Ident(IdentWithToken::new("a")))),
680            Shared::new(create_node(Expr::Ident(IdentWithToken::new("b")))),
681            Shared::new(create_node(Expr::Ident(IdentWithToken::new("c")))),
682        ]),
683        "a || b || c"
684    )]
685    #[case::or_with_nested_and(
686        // Or([And([a, b]), c])
687        Expr::Or(thin_vec![
688            Shared::new(create_node(Expr::And(thin_vec![
689                Shared::new(create_node(Expr::Ident(IdentWithToken::new("a")))),
690                Shared::new(create_node(Expr::Ident(IdentWithToken::new("b")))),
691            ]))),
692            Shared::new(create_node(Expr::Ident(IdentWithToken::new("c")))),
693        ]),
694        "a && b || c"
695    )]
696    #[case::or_with_and_in_middle(
697        // Or([a, And([b, c]), d])
698        Expr::Or(thin_vec![
699            Shared::new(create_node(Expr::Ident(IdentWithToken::new("a")))),
700            Shared::new(create_node(Expr::And(thin_vec![
701                Shared::new(create_node(Expr::Ident(IdentWithToken::new("b")))),
702                Shared::new(create_node(Expr::Ident(IdentWithToken::new("c")))),
703            ]))),
704            Shared::new(create_node(Expr::Ident(IdentWithToken::new("d")))),
705        ]),
706        "a || b && c || d"
707    )]
708    fn test_to_code_operators(#[case] expr: Expr, #[case] expected: &str) {
709        let node = create_node(expr);
710        assert_eq!(node.to_code(), expected);
711    }
712
713    fn ident_node(name: &str) -> Shared<Node> {
714        Shared::new(create_node(Expr::Ident(IdentWithToken::new(name))))
715    }
716
717    fn number_node(n: f64) -> Shared<Node> {
718        Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(n)))))
719    }
720
721    fn binary_op_node(op: BinaryOp, lhs: Shared<Node>, rhs: Shared<Node>) -> Shared<Node> {
722        Shared::new(create_node(Expr::BinaryOp(op, lhs, rhs)))
723    }
724
725    fn bool_node(b: bool) -> Shared<Node> {
726        Shared::new(create_node(Expr::Literal(Literal::Bool(b))))
727    }
728
729    fn and_node(operands: ThinVec<Shared<Node>>) -> Shared<Node> {
730        Shared::new(create_node(Expr::And(operands)))
731    }
732
733    fn or_node(operands: ThinVec<Shared<Node>>) -> Shared<Node> {
734        Shared::new(create_node(Expr::Or(operands)))
735    }
736
737    fn unary_op_node(op: UnaryOp, operand: Shared<Node>) -> Shared<Node> {
738        Shared::new(create_node(Expr::UnaryOp(op, operand)))
739    }
740
741    #[rstest]
742    #[case::not_ident(Expr::UnaryOp(UnaryOp::Not, ident_node("x")), "!x")]
743    #[case::negate_ident(Expr::UnaryOp(UnaryOp::Neg, ident_node("x")), "-x")]
744    #[case::double_not_stays_bare(Expr::UnaryOp(UnaryOp::Not, unary_op_node(UnaryOp::Not, ident_node("x"))), "!!x")]
745    // `--x` does not parse.
746    #[case::double_negate_needs_parens(
747        Expr::UnaryOp(UnaryOp::Neg, unary_op_node(UnaryOp::Neg, ident_node("x"))),
748        "-(-x)"
749    )]
750    // `!-x` does not parse.
751    #[case::not_negate_needs_parens(Expr::UnaryOp(UnaryOp::Not, unary_op_node(UnaryOp::Neg, ident_node("x"))), "!(-x)")]
752    #[case::not_wraps_binary_operand(
753        Expr::UnaryOp(UnaryOp::Not, binary_op_node(BinaryOp::Lt, ident_node("a"), ident_node("b"))),
754        "!(a < b)"
755    )]
756    #[case::not_wraps_and_operand(
757        Expr::UnaryOp(UnaryOp::Not, and_node(thin_vec![ident_node("a"), ident_node("b")])),
758        "!(a && b)"
759    )]
760    #[case::higher_precedence_op_wraps_lower_precedence_rhs(
761        Expr::BinaryOp(
762            BinaryOp::Mul,
763            ident_node("x"),
764            binary_op_node(BinaryOp::Add, number_node(2.0), number_node(3.0))
765        ),
766        "x * (2 + 3)"
767    )]
768    #[case::higher_precedence_op_wraps_lower_precedence_lhs(
769        Expr::BinaryOp(
770            BinaryOp::Mul,
771            binary_op_node(BinaryOp::Add, ident_node("a"), ident_node("b")),
772            ident_node("c")
773        ),
774        "(a + b) * c"
775    )]
776    #[case::lower_precedence_op_keeps_higher_precedence_children_bare(
777        Expr::BinaryOp(
778            BinaryOp::Add,
779            binary_op_node(BinaryOp::Mul, ident_node("a"), ident_node("b")),
780            ident_node("c")
781        ),
782        "a * b + c"
783    )]
784    #[case::same_precedence_lhs_stays_bare(
785        Expr::BinaryOp(
786            BinaryOp::Sub,
787            binary_op_node(BinaryOp::Sub, ident_node("a"), ident_node("b")),
788            ident_node("c")
789        ),
790        "a - b - c"
791    )]
792    // Same precedence on the right needs parens or it re-parses as `(a - b) - c`.
793    #[case::same_precedence_rhs_needs_parens(
794        Expr::BinaryOp(
795            BinaryOp::Sub,
796            ident_node("a"),
797            binary_op_node(BinaryOp::Sub, ident_node("b"), ident_node("c"))
798        ),
799        "a - (b - c)"
800    )]
801    // `&&` binds looser than `==`, so a bare And lhs would re-parse under the wrong grouping.
802    #[case::and_lhs_needs_parens(
803        Expr::BinaryOp(
804            BinaryOp::Eq,
805            and_node(thin_vec![bool_node(false), bool_node(false)]),
806            bool_node(false)
807        ),
808        "(false && false) == false"
809    )]
810    #[case::or_rhs_needs_parens(
811        Expr::BinaryOp(
812            BinaryOp::Eq,
813            ident_node("a"),
814            or_node(thin_vec![ident_node("b"), ident_node("c")])
815        ),
816        "a == (b || c)"
817    )]
818    fn test_to_code_binary_op_precedence(#[case] expr: Expr, #[case] expected: &str) {
819        let node = create_node(expr);
820        assert_eq!(node.to_code(), expected);
821    }
822
823    #[rstest]
824    #[case::no_args(
825        Expr::Call(IdentWithToken::new("test"), smallvec![]),
826        "test()"
827    )]
828    #[case::one_arg(
829        Expr::Call(
830            IdentWithToken::new("add"),
831            smallvec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]
832        ),
833        "add(1)"
834    )]
835    #[case::two_args(
836        Expr::Call(
837            IdentWithToken::new("add"),
838            smallvec![
839                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0))))),
840                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0)))))
841            ]
842        ),
843        "add(1, 2)"
844    )]
845    fn test_to_code_call(#[case] expr: Expr, #[case] expected: &str) {
846        let node = create_node(expr);
847        assert_eq!(node.to_code(), expected);
848    }
849
850    #[rstest]
851    #[case::empty_array(Expr::Array(smallvec![]), "[]")]
852    #[case::single_element(
853        Expr::Array(smallvec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]),
854        "[1]"
855    )]
856    #[case::multiple_elements(
857        Expr::Array(smallvec![
858            Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0))))),
859            Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0))))),
860            Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(3.0))))),
861        ]),
862        "[1, 2, 3]"
863    )]
864    #[case::nested_array(
865        Expr::Array(smallvec![
866            Shared::new(create_node(Expr::Array(smallvec![
867                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))
868            ]))),
869            Shared::new(create_node(Expr::Array(smallvec![
870                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0)))))
871            ]))),
872        ]),
873        "[[1], [2]]"
874    )]
875    #[case::mixed_elements(
876        Expr::Array(smallvec![
877            Shared::new(create_node(Expr::Literal(Literal::String("text".into())))),
878            Shared::new(create_node(Expr::Literal(Literal::Bool(true)))),
879            Shared::new(create_node(Expr::Literal(Literal::None))),
880        ]),
881        r#"["text", true, none]"#
882    )]
883    #[case::empty_dict(Expr::Dict(smallvec![]), "{}")]
884    #[case::single_pair(
885        Expr::Dict(smallvec![Shared::new(create_node(Expr::Array(smallvec![
886            Shared::new(create_node(Expr::Literal(Literal::Symbol(Ident::new("key"))))),
887            Shared::new(create_node(Expr::Literal(Literal::String("value".into())))),
888        ])))]),
889        r#"{:key: "value"}"#
890    )]
891    #[case::multiple_pairs(
892        Expr::Dict(smallvec![
893            Shared::new(create_node(Expr::Array(smallvec![
894                Shared::new(create_node(Expr::Literal(Literal::Symbol(Ident::new("a"))))),
895                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0))))),
896            ]))),
897            Shared::new(create_node(Expr::Array(smallvec![
898                Shared::new(create_node(Expr::Literal(Literal::Symbol(Ident::new("b"))))),
899                Shared::new(create_node(Expr::Literal(Literal::Bool(true)))),
900            ]))),
901        ]),
902        "{:a: 1, :b: true}"
903    )]
904    #[case::dict_with_array_value(
905        Expr::Dict(smallvec![Shared::new(create_node(Expr::Array(smallvec![
906            Shared::new(create_node(Expr::Literal(Literal::Symbol(Ident::new("items"))))),
907            Shared::new(create_node(Expr::Array(smallvec![
908                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0))))),
909                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0))))),
910            ]))),
911        ])))]),
912        "{:items: [1, 2]}"
913    )]
914    fn test_to_code_array_dict(#[case] expr: Expr, #[case] expected: &str) {
915        let node = create_node(expr);
916        assert_eq!(node.to_code(), expected);
917    }
918
919    #[rstest]
920    #[case::simple(
921        Expr::CallDynamic(
922            Shared::new(create_node(Expr::Ident(IdentWithToken::new("func")))),
923            smallvec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(42.0)))))]
924        ),
925        "func(42)"
926    )]
927    fn test_to_code_call_dynamic(#[case] expr: Expr, #[case] expected: &str) {
928        let node = create_node(expr);
929        assert_eq!(node.to_code(), expected);
930    }
931
932    #[rstest]
933    #[case::let_simple(
934        Expr::Let(
935            Pattern::Ident(IdentWithToken::new("x")),
936            Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(42.0)))))
937        ),
938        "let x = 42"
939    )]
940    #[case::let_array_pattern(
941        Expr::Let(
942            Pattern::Array(thin_vec![
943                Pattern::Ident(IdentWithToken::new("a")),
944                Pattern::Ident(IdentWithToken::new("b")),
945            ]),
946            Shared::new(create_node(Expr::Ident(IdentWithToken::new("arr"))))
947        ),
948        "let [a, b] = arr"
949    )]
950    #[case::let_dict_pattern(
951        Expr::Let(
952            Pattern::Dict(thin_vec![
953                (IdentWithToken::new("x"), Pattern::Ident(IdentWithToken::new("x"))),
954                (IdentWithToken::new("y"), Pattern::Ident(IdentWithToken::new("y"))),
955            ]),
956            Shared::new(create_node(Expr::Ident(IdentWithToken::new("d"))))
957        ),
958        "let {x: x, y: y} = d"
959    )]
960    #[case::var_simple(
961        Expr::Var(
962            Pattern::Ident(IdentWithToken::new("y")),
963            Shared::new(create_node(Expr::Literal(Literal::String("hello".into()))))
964        ),
965        r#"var y = "hello""#
966    )]
967    #[case::assign_simple(
968        Expr::Assign(
969            IdentWithToken::new("z"),
970            Shared::new(create_node(Expr::Ident(IdentWithToken::new("value"))))
971        ),
972        "z = value"
973    )]
974    #[case::index_assign(
975        Expr::IndexAssign(
976            IdentWithToken::new("xs"),
977            Shared::new(create_node(Expr::Literal(Literal::Number(0.into())))),
978            Shared::new(create_node(Expr::Ident(IdentWithToken::new("value"))))
979        ),
980        "xs[0] = value"
981    )]
982    #[case::path_assign(
983        Expr::PathAssign(
984            IdentWithToken::new("xs"),
985            thin_vec![
986                Shared::new(create_node(Expr::Literal(Literal::Number(0.into())))),
987                Shared::new(create_node(Expr::Ident(IdentWithToken::new("j")))),
988            ],
989            Shared::new(create_node(Expr::Ident(IdentWithToken::new("value"))))
990        ),
991        "xs[0][j] = value"
992    )]
993    fn test_to_code_variables(#[case] expr: Expr, #[case] expected: &str) {
994        let node = create_node(expr);
995        assert_eq!(node.to_code(), expected);
996    }
997
998    #[rstest]
999    #[case::if_simple(
1000        Expr::If(thin_vec![
1001            (
1002                Some(Shared::new(create_node(Expr::Ident(IdentWithToken::new("x"))))),
1003                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))
1004            )
1005        ]),
1006        "if (x): 1"
1007    )]
1008    #[case::if_else(
1009        Expr::If(thin_vec![
1010            (
1011                Some(Shared::new(create_node(Expr::Ident(IdentWithToken::new("x"))))),
1012                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))
1013            ),
1014            (
1015                None,
1016                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0)))))
1017            )
1018        ]),
1019        "if (x): 1 else: 2"
1020    )]
1021    #[case::if_elif_else(
1022        Expr::If(thin_vec![
1023            (
1024                Some(Shared::new(create_node(Expr::Ident(IdentWithToken::new("x"))))),
1025                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))
1026            ),
1027            (
1028                Some(Shared::new(create_node(Expr::Ident(IdentWithToken::new("y"))))),
1029                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0)))))
1030            ),
1031            (
1032                None,
1033                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(3.0)))))
1034            )
1035        ]),
1036        "if (x): 1 elif (y): 2 else: 3"
1037    )]
1038    fn test_to_code_if(#[case] expr: Expr, #[case] expected: &str) {
1039        let node = create_node(expr);
1040        assert_eq!(node.to_code(), expected);
1041    }
1042
1043    #[rstest]
1044    #[case::unless_simple(
1045        Expr::Unless(thin_vec![
1046            (
1047                Some(Shared::new(create_node(Expr::Ident(IdentWithToken::new("x"))))),
1048                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))
1049            )
1050        ]),
1051        "unless (x): 1"
1052    )]
1053    fn test_to_code_unless(#[case] expr: Expr, #[case] expected: &str) {
1054        let node = create_node(expr);
1055        assert_eq!(node.to_code(), expected);
1056    }
1057
1058    #[rstest]
1059    #[case::while_inline(
1060        Expr::While(
1061            Shared::new(create_node(Expr::Ident(IdentWithToken::new("x")))),
1062            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]
1063        ),
1064        "while (x): 1"
1065    )]
1066    #[case::while_block(
1067        Expr::While(
1068            Shared::new(create_node(Expr::Ident(IdentWithToken::new("x")))),
1069            thin_vec![
1070                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0))))),
1071                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0)))))
1072            ]
1073        ),
1074        "while (x) do\n  1 | 2\nend"
1075    )]
1076    fn test_to_code_while(#[case] expr: Expr, #[case] expected: &str) {
1077        let node = create_node(expr);
1078        assert_eq!(node.to_code(), expected);
1079    }
1080
1081    #[rstest]
1082    #[case::until_inline(
1083        Expr::Until(
1084            Shared::new(create_node(Expr::Ident(IdentWithToken::new("x")))),
1085            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]
1086        ),
1087        "until (x): 1"
1088    )]
1089    #[case::until_block(
1090        Expr::Until(
1091            Shared::new(create_node(Expr::Ident(IdentWithToken::new("x")))),
1092            thin_vec![
1093                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0))))),
1094                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0)))))
1095            ]
1096        ),
1097        "until (x) do\n  1 | 2\nend"
1098    )]
1099    fn test_to_code_until(#[case] expr: Expr, #[case] expected: &str) {
1100        let node = create_node(expr);
1101        assert_eq!(node.to_code(), expected);
1102    }
1103
1104    #[rstest]
1105    #[case::loop_single(
1106        Expr::Loop(thin_vec![Shared::new(create_node(Expr::Break(None)))]),
1107        "loop do\n  break\nend"
1108    )]
1109    fn test_to_code_loop(#[case] expr: Expr, #[case] expected: &str) {
1110        let node = create_node(expr);
1111        assert_eq!(node.to_code(), expected);
1112    }
1113
1114    #[rstest]
1115    #[case::foreach_inline(
1116        Expr::Foreach(
1117            IdentWithToken::new("item"),
1118            Shared::new(create_node(Expr::Ident(IdentWithToken::new("items")))),
1119            thin_vec![Shared::new(create_node(Expr::Ident(IdentWithToken::new("item"))))]
1120        ),
1121        "foreach(item, items): item"
1122    )]
1123    #[case::foreach_block(
1124        Expr::Foreach(
1125            IdentWithToken::new("x"),
1126            Shared::new(create_node(Expr::Ident(IdentWithToken::new("arr")))),
1127            thin_vec![
1128                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0))))),
1129                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0)))))
1130            ]
1131        ),
1132        "foreach(x, arr) do\n  1 | 2\nend"
1133    )]
1134    fn test_to_code_foreach(#[case] expr: Expr, #[case] expected: &str) {
1135        let node = create_node(expr);
1136        assert_eq!(node.to_code(), expected);
1137    }
1138
1139    #[rstest]
1140    #[case::single(
1141        Expr::Block(thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]),
1142        "do\n  1\nend"
1143    )]
1144    #[case::multiple(
1145        Expr::Block(thin_vec![
1146            Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0))))),
1147            Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0))))),
1148            Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(3.0)))))
1149        ]),
1150        "do\n  1 | 2 | 3\nend"
1151    )]
1152    fn test_to_code_block(#[case] expr: Expr, #[case] expected: &str) {
1153        let node = create_node(expr);
1154        assert_eq!(node.to_code(), expected);
1155    }
1156
1157    #[rstest]
1158    #[case::no_params_inline(
1159        Expr::Def(
1160            IdentWithToken::new("test"),
1161            thin_vec![],
1162            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(42.0)))))]
1163        ),
1164        "def test(): 42"
1165    )]
1166    #[case::with_params_inline(
1167        Expr::Def(
1168            IdentWithToken::new("add"),
1169            thin_vec![
1170                Param::new(IdentWithToken::new("x")),
1171                Param::new(IdentWithToken::new("y"))
1172            ],
1173            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]
1174        ),
1175        "def add(x, y): 1"
1176    )]
1177    #[case::with_default_value(
1178        Expr::Def(
1179            IdentWithToken::new("greet"),
1180            thin_vec![
1181                Param::new(IdentWithToken::new("name")),
1182                Param::with_default(
1183                    IdentWithToken::new("greeting"),
1184                    Some(Shared::new(create_node(Expr::Literal(Literal::String("Hello".into())))))
1185                )
1186            ],
1187            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]
1188        ),
1189        r#"def greet(name, greeting = "Hello"): 1"#
1190    )]
1191    #[case::with_multiple_defaults(
1192        Expr::Def(
1193            IdentWithToken::new("foo"),
1194            thin_vec![
1195                Param::new(IdentWithToken::new("a")),
1196                Param::with_default(
1197                    IdentWithToken::new("b"),
1198                    Some(Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0))))))
1199                ),
1200                Param::with_default(
1201                    IdentWithToken::new("c"),
1202                    Some(Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(3.0))))))
1203                )
1204            ],
1205            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]
1206        ),
1207        "def foo(a, b = 2, c = 3): 1"
1208    )]
1209    #[case::block(
1210        Expr::Def(
1211            IdentWithToken::new("test"),
1212            thin_vec![Param::new(IdentWithToken::new("x"))],
1213            thin_vec![
1214                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0))))),
1215                Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(2.0)))))
1216            ]
1217        ),
1218        "def test(x) do\n  1 | 2\nend"
1219    )]
1220    fn test_to_code_def(#[case] expr: Expr, #[case] expected: &str) {
1221        let node = create_node(expr);
1222        assert_eq!(node.to_code(), expected);
1223    }
1224
1225    #[rstest]
1226    #[case::no_params_inline(
1227        Expr::Fn(
1228            thin_vec![],
1229            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(42.0)))))]
1230        ),
1231        "fn(): 42"
1232    )]
1233    #[case::with_params_inline(
1234        Expr::Fn(
1235            thin_vec![
1236                Param::new(IdentWithToken::new("x")),
1237                Param::new(IdentWithToken::new("y"))
1238            ],
1239            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]
1240        ),
1241        "fn(x, y): 1"
1242    )]
1243    #[case::with_default_value(
1244        Expr::Fn(
1245            thin_vec![
1246                Param::new(IdentWithToken::new("x")),
1247                Param::with_default(
1248                    IdentWithToken::new("y"),
1249                    Some(Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(10.0))))))
1250                )
1251            ],
1252            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]
1253        ),
1254        "fn(x, y = 10): 1"
1255    )]
1256    fn test_to_code_fn(#[case] expr: Expr, #[case] expected: &str) {
1257        let node = create_node(expr);
1258        assert_eq!(node.to_code(), expected);
1259    }
1260
1261    #[rstest]
1262    #[case::simple(
1263        Expr::Match(
1264            Shared::new(create_node(Expr::Ident(IdentWithToken::new("x")))),
1265            thin_vec![
1266                MatchArm {
1267                    pattern: Pattern::Literal(Box::new(Literal::Number(Number::new(1.0)))),
1268                    guard: None,
1269                    body: Shared::new(create_node(Expr::Literal(Literal::String("one".into()))))
1270                },
1271                MatchArm {
1272                    pattern: Pattern::Wildcard,
1273                    guard: None,
1274                    body: Shared::new(create_node(Expr::Literal(Literal::String("other".into()))))
1275                }
1276            ]
1277        ),
1278        "match (x) do\n  | 1: \"one\"\n  | _: \"other\"\nend"
1279    )]
1280    fn test_to_code_match(#[case] expr: Expr, #[case] expected: &str) {
1281        let node = create_node(expr);
1282        assert_eq!(node.to_code(), expected);
1283    }
1284
1285    #[rstest]
1286    #[case::text_only(
1287        Expr::InterpolatedString(thin_vec![StringSegment::Text("hello".to_string())]),
1288        r#"s"hello""#
1289    )]
1290    #[case::with_expr(
1291        Expr::InterpolatedString(thin_vec![
1292            StringSegment::Text("Hello ".to_string()),
1293            StringSegment::Expr(Shared::new(create_node(Expr::Ident(IdentWithToken::new("name"))))),
1294            StringSegment::Text("!".to_string())
1295        ]),
1296        r#"s"Hello ${name}!""#
1297    )]
1298    fn test_to_code_interpolated_string(#[case] expr: Expr, #[case] expected: &str) {
1299        let node = create_node(expr);
1300        assert_eq!(node.to_code(), expected);
1301    }
1302
1303    #[rstest]
1304    #[case::simple(
1305        Expr::Try(
1306            Shared::new(create_node(Expr::Ident(IdentWithToken::new("risky")))),
1307            None,
1308            Shared::new(create_node(Expr::Literal(Literal::String("error".into()))))
1309        ),
1310        r#"try risky catch: "error""#
1311    )]
1312    #[case::with_binder(
1313        Expr::Try(
1314            Shared::new(create_node(Expr::Ident(IdentWithToken::new("risky")))),
1315            Some(IdentWithToken::new("e")),
1316            Shared::new(create_node(Expr::Ident(IdentWithToken::new("e"))))
1317        ),
1318        "try risky catch(e): e"
1319    )]
1320    fn test_to_code_try(#[case] expr: Expr, #[case] expected: &str) {
1321        let node = create_node(expr);
1322        assert_eq!(node.to_code(), expected);
1323    }
1324
1325    #[rstest]
1326    #[case::simple(
1327        Expr::Module(
1328            IdentWithToken::new("math"),
1329            thin_vec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))]
1330        ),
1331        "module math do\n  1\nend"
1332    )]
1333    fn test_to_code_module(#[case] expr: Expr, #[case] expected: &str) {
1334        let node = create_node(expr);
1335        assert_eq!(node.to_code(), expected);
1336    }
1337
1338    #[rstest]
1339    #[case::ident(
1340        Expr::QualifiedAccess(
1341            thin_vec![IdentWithToken::new("module"), IdentWithToken::new("submodule")],
1342            AccessTarget::Ident(IdentWithToken::new("func"))
1343        ),
1344        "module::submodule::func"
1345    )]
1346    #[case::call(
1347        Expr::QualifiedAccess(
1348            thin_vec![IdentWithToken::new("module")],
1349            AccessTarget::Call(
1350                IdentWithToken::new("func"),
1351                Box::new(smallvec![Shared::new(create_node(Expr::Literal(Literal::Number(Number::new(1.0)))))])
1352            )
1353        ),
1354        "module::func(1)"
1355    )]
1356    fn test_to_code_qualified_access(#[case] expr: Expr, #[case] expected: &str) {
1357        let node = create_node(expr);
1358        assert_eq!(node.to_code(), expected);
1359    }
1360
1361    #[rstest]
1362    #[case::include(
1363        Expr::Include(Literal::String("file.mq".into())),
1364        r#"include "file.mq""#
1365    )]
1366    #[case::import(
1367        Expr::Import(Literal::String("module.mq".into()), None),
1368        r#"import "module.mq""#
1369    )]
1370    #[case::import_as(
1371        Expr::Import(
1372            Literal::String("module.mq".into()),
1373            Some(IdentWithToken::new("m"))
1374        ),
1375        r#"import "module.mq" as m"#
1376    )]
1377    fn test_to_code_include_import(#[case] expr: Expr, #[case] expected: &str) {
1378        let node = create_node(expr);
1379        assert_eq!(node.to_code(), expected);
1380    }
1381
1382    // Complex expression tests
1383    #[rstest]
1384    #[case::nested_call(
1385        Expr::Call(
1386            IdentWithToken::new("map"),
1387            smallvec![
1388                Shared::new(create_node(Expr::Call(
1389                    IdentWithToken::new("filter"),
1390                    smallvec![Shared::new(create_node(Expr::Ident(IdentWithToken::new("items"))))]
1391                )))
1392            ]
1393        ),
1394        "map(filter(items))"
1395    )]
1396    fn test_to_code_complex(#[case] expr: Expr, #[case] expected: &str) {
1397        let node = create_node(expr);
1398        assert_eq!(node.to_code(), expected);
1399    }
1400
1401    #[rstest]
1402    #[case::not_negate(Expr::UnaryOp(UnaryOp::Not, unary_op_node(UnaryOp::Neg, ident_node("x"))))]
1403    #[case::negate_not(Expr::UnaryOp(UnaryOp::Neg, unary_op_node(UnaryOp::Not, ident_node("x"))))]
1404    #[case::negate_negate(Expr::UnaryOp(UnaryOp::Neg, unary_op_node(UnaryOp::Neg, ident_node("x"))))]
1405    #[case::not_not(Expr::UnaryOp(UnaryOp::Not, unary_op_node(UnaryOp::Not, ident_node("x"))))]
1406    #[case::not_not_negate(Expr::UnaryOp(
1407        UnaryOp::Not,
1408        unary_op_node(UnaryOp::Not, unary_op_node(UnaryOp::Neg, ident_node("x")))
1409    ))]
1410    fn test_to_code_unary_op_reparses(#[case] expr: Expr) {
1411        let code = create_node(expr).to_code();
1412        let tokens = crate::Lexer::new(crate::lexer::Options::default())
1413            .tokenize(&code, crate::Module::TOP_LEVEL_MODULE_ID)
1414            .unwrap_or_else(|e| panic!("`{code}` failed to lex: {e:?}"));
1415        let mut arena = crate::arena::Arena::new(16);
1416        let program = crate::ast::parser::Parser::new(tokens.iter(), &mut arena, crate::Module::TOP_LEVEL_MODULE_ID)
1417            .parse()
1418            .unwrap_or_else(|e| panic!("`{code}` failed to parse: {e:?}"));
1419
1420        assert_eq!(program.len(), 1, "`{code}` should parse to one expression");
1421        assert_eq!(program[0].to_code(), code);
1422    }
1423
1424    fn parse_code(code: &str) -> Program {
1425        let tokens = crate::Lexer::new(crate::lexer::Options::default())
1426            .tokenize(code, crate::Module::TOP_LEVEL_MODULE_ID)
1427            .unwrap_or_else(|e| panic!("`{code}` failed to lex: {e:?}"));
1428        let mut arena = crate::arena::Arena::new(16);
1429        crate::ast::parser::Parser::new(tokens.iter(), &mut arena, crate::Module::TOP_LEVEL_MODULE_ID)
1430            .parse()
1431            .unwrap_or_else(|e| panic!("`{code}` failed to parse: {e:?}"))
1432    }
1433
1434    #[rstest]
1435    #[case::in_call_arg("f(fn: self + 1)", "f(fn: self + 1;)")]
1436    #[case::multiple_statements("f(fn: self + 1 | self * 2)", "f(fn: self + 1 | self * 2;)")]
1437    #[case::let_value("let g = fn: self;", "let g = fn: self;")]
1438    #[case::nested("f(fn: g(fn: self + 1))", "f(fn: g(fn: self + 1;);)")]
1439    #[case::explicit_params_unchanged("f(fn(x): x + 1)", "f(fn(x): x + 1)")]
1440    fn test_to_code_implicit_fn_reparses(#[case] source: &str, #[case] expected: &str) {
1441        let code = parse_code(source)[0].to_code();
1442        assert_eq!(code, expected);
1443        assert_eq!(parse_code(&code)[0].to_code(), code);
1444    }
1445}