valua-codegen 0.1.0

Lua 5.1 code emitter for the valua transpiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Lua 5.1 code emitter — walks a transformed AST and produces formatted source.
// emit_statement and emit_expr_inner are large dispatch functions — splitting them would
// scatter the grammar and hurt readability.
#![allow(clippy::too_many_lines)]

use valua_ast::{BinaryOp, Block, Call, Expression, FunctionBody, Statement, TableField, UnaryOp};

pub use error::CodeGenError;

mod error;

// ── Configuration ─────────────────────────────────────────────────────────────

// `LuaTarget` is defined in `valua-ast` (the common dep layer) and re-exported
// here so that existing `valua_codegen::LuaTarget` paths continue to compile.
pub use valua_ast::LuaTarget;

/// Options that control how the emitted Lua source is formatted.
#[derive(Debug, Clone)]
pub struct EmitOptions {
    /// String used for each indentation level (default: four spaces).
    pub indent: String,
    /// Target runtime.
    pub target: LuaTarget,
    /// Emit a `-- Generated by valua` header comment.
    pub emit_header_comment: bool,
}

impl Default for EmitOptions {
    fn default() -> Self {
        Self {
            indent: "    ".to_string(),
            target: LuaTarget::default(),
            emit_header_comment: false,
        }
    }
}

// ── Trait ─────────────────────────────────────────────────────────────────────

/// A code-generation backend that can emit a `Block` to a `String`.
pub trait CodeGen {
    /// Emit the entire `block` and return the formatted Lua source.
    ///
    /// # Errors
    /// Returns `CodeGenError` if the AST contains a node that cannot be
    /// represented in the target Lua version.
    fn emit(&self, block: &Block) -> Result<String, CodeGenError>;
}

// ── Emitter ───────────────────────────────────────────────────────────────────

/// Concrete Lua 5.1 / `LuaJIT` emitter.
pub struct LuaEmitter {
    pub options: EmitOptions,
}

impl LuaEmitter {
    #[must_use]
    pub fn new(options: EmitOptions) -> Self {
        Self { options }
    }

    #[must_use]
    pub fn lua51() -> Self {
        Self::new(EmitOptions {
            target: LuaTarget::Lua51,
            ..EmitOptions::default()
        })
    }

    #[must_use]
    pub fn luajit() -> Self {
        Self::new(EmitOptions {
            target: LuaTarget::LuaJIT,
            ..EmitOptions::default()
        })
    }
}

impl CodeGen for LuaEmitter {
    fn emit(&self, block: &Block) -> Result<String, CodeGenError> {
        let mut ctx = EmitContext::new(&self.options);
        if self.options.emit_header_comment {
            ctx.push("-- Generated by valua v");
            ctx.push(env!("CARGO_PKG_VERSION"));
            ctx.push("\n");
        }
        ctx.emit_block(block)?;
        Ok(ctx.finish())
    }
}

// ── Operator helpers ──────────────────────────────────────────────────────────

fn binary_op_str(op: BinaryOp) -> &'static str {
    match op {
        BinaryOp::Add => "+",
        BinaryOp::Sub => "-",
        BinaryOp::Mul => "*",
        BinaryOp::Div => "/",
        BinaryOp::Mod => "%",
        BinaryOp::Pow => "^",
        BinaryOp::IDiv => "//",
        BinaryOp::Concat => "..",
        BinaryOp::Lt => "<",
        BinaryOp::Le => "<=",
        BinaryOp::Gt => ">",
        BinaryOp::Ge => ">=",
        BinaryOp::Eq => "==",
        BinaryOp::Ne => "~=",
        BinaryOp::And => "and",
        BinaryOp::Or => "or",
        BinaryOp::BitwiseAnd => "&",
        BinaryOp::BitwiseOr => "|",
        BinaryOp::BitwiseXor => "~",
        BinaryOp::Shl => "<<",
        BinaryOp::Shr => ">>",
    }
}

fn binary_op_prec(op: BinaryOp) -> u8 {
    match op {
        BinaryOp::Or => 1,
        BinaryOp::And => 3,
        BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge | BinaryOp::Eq | BinaryOp::Ne => {
            5
        }
        BinaryOp::BitwiseOr => 7,
        BinaryOp::BitwiseXor => 9,
        BinaryOp::BitwiseAnd => 11,
        BinaryOp::Shl | BinaryOp::Shr => 13,
        BinaryOp::Concat => 16,
        BinaryOp::Add | BinaryOp::Sub => 17,
        BinaryOp::Mul | BinaryOp::Div | BinaryOp::IDiv | BinaryOp::Mod => 19,
        BinaryOp::Pow => 24,
    }
}

fn is_right_assoc(op: BinaryOp) -> bool {
    matches!(op, BinaryOp::Pow | BinaryOp::Concat)
}

fn expr_outer_prec(expr: &Expression) -> u8 {
    match expr {
        Expression::BinOp(_, op, _, _) => binary_op_prec(*op),
        Expression::UnOp(_, _, _) => 21,
        _ => u8::MAX,
    }
}

// ── Emit context ──────────────────────────────────────────────────────────────

pub(crate) struct EmitContext<'opts> {
    options: &'opts EmitOptions,
    buf: String,
    depth: usize,
}

impl<'opts> EmitContext<'opts> {
    pub(crate) fn new(options: &'opts EmitOptions) -> Self {
        Self {
            options,
            buf: String::new(),
            depth: 0,
        }
    }

    pub(crate) fn finish(self) -> String {
        self.buf
    }

    fn push(&mut self, s: &str) {
        self.buf.push_str(s);
    }

    fn push_indent(&mut self) {
        self.buf.push_str(&self.options.indent.repeat(self.depth));
    }

    pub(crate) fn emit_block(&mut self, block: &Block) -> Result<(), CodeGenError> {
        for stmt in &block.stmts {
            self.emit_statement(stmt)?;
        }
        Ok(())
    }

    pub(crate) fn emit_statement(&mut self, stmt: &Statement) -> Result<(), CodeGenError> {
        match stmt {
            Statement::LocalDecl(d) => {
                self.push_indent();
                self.push("local ");
                for (i, name) in d.names.iter().enumerate() {
                    if i > 0 {
                        self.push(", ");
                    }
                    self.push(&name.name);
                }
                if !d.values.is_empty() {
                    self.push(" = ");
                    for (i, val) in d.values.iter().enumerate() {
                        if i > 0 {
                            self.push(", ");
                        }
                        self.emit_expression(val)?;
                    }
                }
                self.push("\n");
            }
            Statement::Assign(a) => {
                self.push_indent();
                for (i, target) in a.targets.iter().enumerate() {
                    if i > 0 {
                        self.push(", ");
                    }
                    self.emit_expression(target)?;
                }
                self.push(" = ");
                for (i, val) in a.values.iter().enumerate() {
                    if i > 0 {
                        self.push(", ");
                    }
                    self.emit_expression(val)?;
                }
                self.push("\n");
            }
            Statement::ExprStmt(e) => {
                self.push_indent();
                self.emit_expression(e)?;
                self.push("\n");
            }
            Statement::Return(r) => {
                self.push_indent();
                self.push("return");
                if !r.values.is_empty() {
                    self.push(" ");
                    for (i, val) in r.values.iter().enumerate() {
                        if i > 0 {
                            self.push(", ");
                        }
                        self.emit_expression(val)?;
                    }
                }
                self.push("\n");
            }
            Statement::Break(_) => {
                self.push_indent();
                self.push("break\n");
            }
            Statement::Goto(g) => {
                self.push_indent();
                self.push("goto ");
                self.push(&g.label);
                self.push("\n");
            }
            Statement::Label(l) => {
                self.push_indent();
                self.push("::");
                self.push(&l.name);
                self.push("::\n");
            }
            Statement::Do(d) => {
                self.push_indent();
                self.push("do\n");
                self.depth += 1;
                self.emit_block(&d.body)?;
                self.depth -= 1;
                self.push_indent();
                self.push("end\n");
            }
            Statement::While(w) => {
                self.push_indent();
                self.push("while ");
                self.emit_expression(&w.condition)?;
                self.push(" do\n");
                self.depth += 1;
                self.emit_block(&w.body)?;
                self.depth -= 1;
                self.push_indent();
                self.push("end\n");
            }
            Statement::Repeat(r) => {
                self.push_indent();
                self.push("repeat\n");
                self.depth += 1;
                self.emit_block(&r.body)?;
                self.depth -= 1;
                self.push_indent();
                self.push("until ");
                self.emit_expression(&r.condition)?;
                self.push("\n");
            }
            Statement::If(i) => {
                self.push_indent();
                self.push("if ");
                self.emit_expression(&i.condition)?;
                self.push(" then\n");
                self.depth += 1;
                self.emit_block(&i.then_block)?;
                self.depth -= 1;
                for elseif in &i.elseif_clauses {
                    self.push_indent();
                    self.push("elseif ");
                    self.emit_expression(&elseif.condition)?;
                    self.push(" then\n");
                    self.depth += 1;
                    self.emit_block(&elseif.body)?;
                    self.depth -= 1;
                }
                if let Some(ref else_block) = i.else_block {
                    self.push_indent();
                    self.push("else\n");
                    self.depth += 1;
                    self.emit_block(else_block)?;
                    self.depth -= 1;
                }
                self.push_indent();
                self.push("end\n");
            }
            Statement::NumericFor(f) => {
                self.push_indent();
                self.push("for ");
                self.push(&f.var);
                self.push(" = ");
                self.emit_expression(&f.start)?;
                self.push(", ");
                self.emit_expression(&f.limit)?;
                if let Some(ref step) = f.step {
                    self.push(", ");
                    self.emit_expression(step)?;
                }
                self.push(" do\n");
                self.depth += 1;
                self.emit_block(&f.body)?;
                self.depth -= 1;
                self.push_indent();
                self.push("end\n");
            }
            Statement::GenericFor(f) => {
                self.push_indent();
                self.push("for ");
                for (i, var) in f.vars.iter().enumerate() {
                    if i > 0 {
                        self.push(", ");
                    }
                    self.push(var);
                }
                self.push(" in ");
                for (i, iter) in f.iterators.iter().enumerate() {
                    if i > 0 {
                        self.push(", ");
                    }
                    self.emit_expression(iter)?;
                }
                self.push(" do\n");
                self.depth += 1;
                self.emit_block(&f.body)?;
                self.depth -= 1;
                self.push_indent();
                self.push("end\n");
            }
            Statement::FunctionDecl(f) => {
                self.push_indent();
                self.push("function ");
                let parts = f.name.parts.join(".");
                self.push(&parts);
                if let Some(ref method) = f.name.method {
                    self.push(":");
                    self.push(method);
                }
                self.emit_function_body(&f.func)?;
                self.push("\n");
            }
            Statement::LocalFunctionDecl(f) => {
                self.push_indent();
                self.push("local function ");
                self.push(&f.name);
                self.emit_function_body(&f.func)?;
                self.push("\n");
            }
        }
        Ok(())
    }

    fn emit_function_body(&mut self, func: &FunctionBody) -> Result<(), CodeGenError> {
        self.push("(");
        for (i, param) in func.params.iter().enumerate() {
            if i > 0 {
                self.push(", ");
            }
            self.push(&param.name);
        }
        if func.is_vararg {
            if !func.params.is_empty() {
                self.push(", ");
            }
            self.push("...");
        }
        self.push(")\n");
        self.depth += 1;
        self.emit_block(&func.body)?;
        self.depth -= 1;
        self.push_indent();
        self.push("end");
        Ok(())
    }

    pub(crate) fn emit_expression(&mut self, expr: &Expression) -> Result<(), CodeGenError> {
        self.emit_expr_prec(expr, 0)
    }

    fn emit_expr_prec(&mut self, expr: &Expression, min_prec: u8) -> Result<(), CodeGenError> {
        let ep = expr_outer_prec(expr);
        let needs_parens = ep < min_prec;
        if needs_parens {
            self.push("(");
        }
        self.emit_expr_inner(expr)?;
        if needs_parens {
            self.push(")");
        }
        Ok(())
    }

    fn emit_expr_inner(&mut self, expr: &Expression) -> Result<(), CodeGenError> {
        match expr {
            Expression::Nil(_) => self.push("nil"),
            Expression::True(_) => self.push("true"),
            Expression::False(_) => self.push("false"),
            Expression::Vararg(_) => self.push("..."),
            Expression::Integer(v, _) => {
                let s = v.to_string();
                self.push(&s);
            }
            Expression::Float(f, span) => {
                // NaN and Inf have no Lua literal syntax. Emitting "NaN" or "inf"
                // produces a bare identifier that Lua treats as a variable name, not
                // a numeric value — silent correctness failure. Reject early.
                if f.is_nan() {
                    return Err(CodeGenError::UnsupportedNode {
                        target: "Lua 5.1",
                        detail: "NaN has no literal representation; use `0/0` or avoid NaN"
                            .to_string(),
                        span: *span,
                    });
                }
                if f.is_infinite() {
                    return Err(CodeGenError::UnsupportedNode {
                        target: "Lua 5.1",
                        detail: "Infinity has no literal representation; use `math.huge`"
                            .to_string(),
                        span: *span,
                    });
                }
                let s = f.to_string();
                self.push(&s);
                if !s.contains('.') && !s.contains('e') && !s.contains('E') {
                    self.push(".0");
                }
            }
            Expression::String(s, _) => {
                self.push("\"");
                let escaped = emit_string_content(s);
                self.push(&escaped);
                self.push("\"");
            }
            Expression::Name(n, _) => self.push(n),
            Expression::Index(base, field, _) => {
                // Base may need parens if it's a binary/unary op (unlikely but correct).
                self.emit_expr_prec(base, u8::MAX)?;
                self.push(".");
                self.push(field);
            }
            Expression::IndexExpr(base, key, _) => {
                self.emit_expr_prec(base, u8::MAX)?;
                self.push("[");
                self.emit_expression(key)?;
                self.push("]");
            }
            Expression::BinOp(lhs, op, rhs, _) => {
                let prec = binary_op_prec(*op);
                let ra = is_right_assoc(*op);
                let lhs_min = if ra { prec + 1 } else { prec };
                let rhs_min = if ra { prec } else { prec + 1 };
                self.emit_expr_prec(lhs, lhs_min)?;
                self.push(" ");
                self.push(binary_op_str(*op));
                self.push(" ");
                self.emit_expr_prec(rhs, rhs_min)?;
            }
            Expression::UnOp(op, operand, _) => {
                match op {
                    UnaryOp::Neg => self.push("- "),
                    UnaryOp::Not => self.push("not "),
                    UnaryOp::Len => self.push("#"),
                    UnaryOp::BitwiseNot => self.push("~ "),
                }
                // Unary prec is 21; operand needs >= 21 to omit parens.
                self.emit_expr_prec(operand, 21)?;
            }
            Expression::Call(call) => match call {
                Call::Call { func, args, .. } => {
                    self.emit_expr_prec(func, u8::MAX)?;
                    self.push("(");
                    for (i, arg) in args.iter().enumerate() {
                        if i > 0 {
                            self.push(", ");
                        }
                        self.emit_expression(arg)?;
                    }
                    self.push(")");
                }
                Call::MethodCall {
                    obj, method, args, ..
                } => {
                    self.emit_expr_prec(obj, u8::MAX)?;
                    self.push(":");
                    self.push(method);
                    self.push("(");
                    for (i, arg) in args.iter().enumerate() {
                        if i > 0 {
                            self.push(", ");
                        }
                        self.emit_expression(arg)?;
                    }
                    self.push(")");
                }
            },
            Expression::Function(func) => {
                self.push("function");
                self.emit_function_body(func)?;
            }
            Expression::Table(t) => {
                self.push("{");
                for (i, field) in t.fields.iter().enumerate() {
                    if i > 0 {
                        self.push(", ");
                    }
                    match field {
                        TableField::ExprKey { key, value, .. } => {
                            self.push("[");
                            self.emit_expression(key)?;
                            self.push("] = ");
                            self.emit_expression(value)?;
                        }
                        TableField::NameKey { key, value, .. } => {
                            self.push(key);
                            self.push(" = ");
                            self.emit_expression(value)?;
                        }
                        TableField::Positional(val) => {
                            self.emit_expression(val)?;
                        }
                    }
                }
                self.push("}");
            }
        }
        Ok(())
    }
}

fn emit_string_content(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\x07' => out.push_str("\\a"),
            '\x08' => out.push_str("\\b"),
            '\x0C' => out.push_str("\\f"),
            '\x0B' => out.push_str("\\v"),
            c if (c as u32) < 32 => {
                out.push('\\');
                out.push_str(&(c as u32).to_string());
            }
            c => out.push(c),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_emit_options_default() {
        let opts = EmitOptions::default();
        assert_eq!(opts.indent, "    ");
        assert_eq!(opts.target, LuaTarget::Lua51);
        assert!(!opts.emit_header_comment);
    }

    #[test]
    fn test_emit_empty_block() {
        let block = valua_ast::Block {
            stmts: vec![],
            span: valua_diagnostics::Span::dummy(),
        };
        let out = LuaEmitter::lua51().emit(&block).unwrap();
        assert_eq!(out, "");
    }

    #[test]
    fn test_luajit_target_assumed() {
        let emitter = LuaEmitter::luajit();
        assert_eq!(emitter.options.target, LuaTarget::LuaJIT);
    }

    #[test]
    fn test_emit_string_content_escapes() {
        assert_eq!(emit_string_content("hello"), "hello");
        assert_eq!(emit_string_content("a\"b"), "a\\\"b");
        assert_eq!(emit_string_content("a\\b"), "a\\\\b");
        assert_eq!(emit_string_content("a\nb"), "a\\nb");
    }

    // ── Numeric emission invariants ───────────────────────────────────────────

    fn emit_expr(expr: Expression) -> Result<String, CodeGenError> {
        let opts = EmitOptions::default();
        let mut ctx = EmitContext::new(&opts);
        ctx.emit_expression(&expr)?;
        Ok(ctx.finish())
    }

    fn int_expr(v: i64) -> Expression {
        Expression::Integer(v, valua_diagnostics::Span::dummy())
    }

    fn float_expr(v: f64) -> Expression {
        Expression::Float(v, valua_diagnostics::Span::dummy())
    }

    #[test]
    fn integer_emitted_as_plain_decimal() {
        assert_eq!(emit_expr(int_expr(0)).unwrap(), "0");
        assert_eq!(emit_expr(int_expr(42)).unwrap(), "42");
        assert_eq!(emit_expr(int_expr(-1)).unwrap(), "-1");
        assert_eq!(emit_expr(int_expr(255)).unwrap(), "255");
        // Source hex literal 0xFF → stored as i64(255) → emitted as "255", never "0xff".
        // This is the decimal-only invariant (PRD §TD1).
    }

    #[test]
    fn integer_max_emitted_as_decimal_not_hex() {
        let s = emit_expr(int_expr(i64::MAX)).unwrap();
        assert!(
            !s.contains("0x") && !s.contains("0X"),
            "must not emit hex: {s}"
        );
        assert_eq!(s, i64::MAX.to_string());
    }

    #[test]
    fn float_with_fractional_part_emitted_verbatim() {
        assert_eq!(emit_expr(float_expr(1.5)).unwrap(), "1.5");
        assert_eq!(emit_expr(float_expr(3.14)).unwrap(), "3.14");
    }

    #[test]
    fn float_without_fractional_part_gets_dot_zero_suffix() {
        // Ensures Lua treats the value as float, not integer.
        let s = emit_expr(float_expr(1.0)).unwrap();
        assert!(
            s.contains('.') || s.contains('e') || s.contains('E'),
            "float 1.0 must have fractional marker: {s}"
        );
        assert_eq!(s, "1.0");
    }

    #[test]
    fn float_every_emitted_value_has_decimal_marker() {
        // Rust Display for f64 uses full decimal notation (not 'e'). For any
        // finite float that lacks a '.' in its Display string, the emitter
        // appends ".0". This test verifies no finite float escapes without a
        // decimal marker — which would cause Lua to treat it as an identifier.
        let cases = [0.0_f64, 1.0, -1.0, 42.0, 1e10, 1e15, 1e-10, 1e-300];
        for v in cases {
            let s = emit_expr(float_expr(v)).unwrap();
            assert!(
                s.contains('.') || s.contains('e') || s.contains('E'),
                "float {v} emitted without decimal marker: {s}"
            );
        }
    }

    #[test]
    fn float_nan_returns_unsupported_node_error() {
        let err = emit_expr(float_expr(f64::NAN)).unwrap_err();
        match err {
            CodeGenError::UnsupportedNode { ref detail, .. } => {
                assert!(detail.contains("NaN"), "error must mention NaN: {detail}");
            }
            other => panic!("expected UnsupportedNode, got: {other}"),
        }
    }

    #[test]
    fn float_positive_infinity_returns_unsupported_node_error() {
        let err = emit_expr(float_expr(f64::INFINITY)).unwrap_err();
        assert!(matches!(err, CodeGenError::UnsupportedNode { .. }));
    }

    #[test]
    fn float_negative_infinity_returns_unsupported_node_error() {
        let err = emit_expr(float_expr(f64::NEG_INFINITY)).unwrap_err();
        assert!(matches!(err, CodeGenError::UnsupportedNode { .. }));
    }

    #[test]
    fn float_no_runtime_type_wrapper_in_output() {
        // Emitting a float must produce a plain literal — no math.type, no
        // runtime dispatch, no wrapping call. This is the Case C compliance check.
        let s = emit_expr(float_expr(3.14)).unwrap();
        assert!(
            !s.contains("math"),
            "emitted float must not reference math.*: {s}"
        );
        assert!(
            !s.contains("type"),
            "emitted float must not call type(): {s}"
        );
        assert!(
            !s.contains("("),
            "emitted float literal must not contain a call: {s}"
        );
    }

    #[test]
    fn integer_no_runtime_type_wrapper_in_output() {
        let s = emit_expr(int_expr(42)).unwrap();
        assert!(
            !s.contains("math"),
            "emitted integer must not reference math.*: {s}"
        );
        assert!(
            !s.contains("("),
            "emitted integer literal must not contain a call: {s}"
        );
    }
}