Skip to main content

js2zig_core/zigir/passes/
constant_fold.rs

1// zigir/passes/constant_fold.rs
2// ConstantFoldPass — fold constant arithmetic and string expressions.
3//
4// Supported folds:
5//   - Integer arithmetic: 1 + 2 → 3
6//   - Float arithmetic: 1.5 + 2.5 → 4.0
7//   - Boolean logic on constants: true && false → false
8//   - String concatenation of literals: "a" ++ "b" → "ab"
9//   - Unary on constants: -42 → -42, !true → false
10//   - typeof on literals: typeof 42 → "number"
11
12use crate::zigir::ops::{BinOp, LogicalOp, UnaOp};
13use crate::zigir::passes::{IrPass, PassResult};
14use crate::zigir::types::{IrExpr, IrModule};
15
16/// Constant folding pass.
17///
18/// Replaces constant expressions with their computed values.
19/// Does NOT fold expressions that might have side effects.
20pub struct ConstantFoldPass;
21
22impl ConstantFoldPass {
23    pub fn new() -> Self {
24        Self
25    }
26
27    /// Try to fold an expression into a simpler constant form.
28    /// Returns Some(folded_expr) if a fold was possible, None otherwise.
29    fn try_fold(expr: &mut IrExpr) -> bool {
30        match expr {
31            IrExpr::Binary {
32                op, left, right, ..
33            } => {
34                // First, recursively fold children
35                let mut changed = false;
36                if Self::try_fold(left) {
37                    changed = true;
38                }
39                if Self::try_fold(right) {
40                    changed = true;
41                }
42                // Then try to fold this binary operation
43                if let Some(result) = fold_binary(*op, left, right) {
44                    *expr = result;
45                    true
46                } else {
47                    changed
48                }
49            }
50            IrExpr::Unary { op, operand } => {
51                let changed = Self::try_fold(operand);
52                if let Some(result) = fold_unary(*op, operand) {
53                    *expr = result;
54                    true
55                } else {
56                    changed
57                }
58            }
59            IrExpr::Logical { op, left, right } => {
60                let mut changed = false;
61                if Self::try_fold(left) {
62                    changed = true;
63                }
64                if Self::try_fold(right) {
65                    changed = true;
66                }
67                if let Some(result) = fold_logical(*op, left, right) {
68                    *expr = result;
69                    true
70                } else {
71                    changed
72                }
73            }
74            IrExpr::Conditional { cond, then, else_ } => {
75                let mut changed = false;
76                if Self::try_fold(cond) {
77                    changed = true;
78                }
79                // Check condition before mutating then/else_
80                let cond_bool = if let IrExpr::BoolLiteral(b) = cond.as_ref() {
81                    Some(*b)
82                } else {
83                    None
84                };
85                if Self::try_fold(then) {
86                    changed = true;
87                }
88                if Self::try_fold(else_) {
89                    changed = true;
90                }
91                // If condition is a known boolean, eliminate the branch
92                if let Some(b) = cond_bool {
93                    let replacement = if b {
94                        (**then).clone()
95                    } else {
96                        (**else_).clone()
97                    };
98                    *expr = replacement;
99                    return true;
100                }
101                changed
102            }
103            IrExpr::Paren(inner) => {
104                let mut changed = Self::try_fold(inner);
105                // Unwrap paren around a literal
106                if matches!(
107                    inner.as_ref(),
108                    IrExpr::IntLiteral(_)
109                        | IrExpr::FloatLiteral(_)
110                        | IrExpr::BoolLiteral(_)
111                        | IrExpr::BigIntLiteral(_)
112                ) {
113                    *expr = (**inner).clone();
114                    changed = true;
115                }
116                changed
117            }
118            IrExpr::Sequence(exprs) => {
119                let mut changed = false;
120                for e in exprs {
121                    if Self::try_fold(e) {
122                        changed = true;
123                    }
124                }
125                changed
126            }
127            IrExpr::AllocPrint { fmt, args } => {
128                let mut changed = false;
129                for a in args.iter_mut() {
130                    if Self::try_fold(a) {
131                        changed = true;
132                    }
133                }
134                // If allocPrint has zero interpolation args, it's just a string literal
135                if args.is_empty() {
136                    let s = fmt.clone();
137                    *expr = IrExpr::StringLiteral(s);
138                    return true;
139                }
140                changed
141            }
142            IrExpr::Typeof(inner) => {
143                // Check typeof before mutating, since we might replace the expr
144                let typeof_result = typeof_literal(inner);
145                let changed = Self::try_fold(inner);
146                if let Some(s) = typeof_result {
147                    *expr = IrExpr::StringLiteral(s);
148                    return true;
149                }
150                changed
151            }
152            // Recurse into compound expressions
153            IrExpr::ArrayLiteral(arr) => {
154                let mut changed = false;
155                for e in &mut arr.elements {
156                    if Self::try_fold(e) {
157                        changed = true;
158                    }
159                }
160                changed
161            }
162            IrExpr::ObjectLiteral(obj) => {
163                use crate::zigir::types::IrObjectItem;
164                let mut changed = false;
165                for item in &mut obj.items {
166                    match item {
167                        IrObjectItem::Field(f) => {
168                            if Self::try_fold(&mut f.value) {
169                                changed = true;
170                            }
171                        }
172                        IrObjectItem::Spread(e) => {
173                            if Self::try_fold(e) {
174                                changed = true;
175                            }
176                        }
177                    }
178                }
179                changed
180            }
181            IrExpr::TemplateLiteral { exprs, .. } => {
182                let mut changed = false;
183                for e in exprs {
184                    if Self::try_fold(e) {
185                        changed = true;
186                    }
187                }
188                changed
189            }
190            IrExpr::Spread(e) | IrExpr::Void(e) => Self::try_fold(e),
191            _ => false,
192        }
193    }
194
195    /// Fold constants in a statement.
196    fn fold_stmt(stmt: &mut crate::zigir::types::IrStmt) -> bool {
197        match stmt {
198            crate::zigir::types::IrStmt::VarDecl(v) => {
199                if let Some(e) = &mut v.init {
200                    Self::try_fold(e)
201                } else {
202                    false
203                }
204            }
205            crate::zigir::types::IrStmt::Assign { value, .. } => Self::try_fold(value),
206            crate::zigir::types::IrStmt::If { cond, then, else_ } => {
207                let mut changed = Self::try_fold(cond);
208                if Self::fold_block(then) {
209                    changed = true;
210                }
211                if let Some(e) = else_
212                    && Self::fold_block(e)
213                {
214                    changed = true;
215                }
216                changed
217            }
218            crate::zigir::types::IrStmt::While { cond, body, .. } => {
219                let mut changed = Self::try_fold(cond);
220                if Self::fold_block(body) {
221                    changed = true;
222                }
223                changed
224            }
225            crate::zigir::types::IrStmt::DoWhile { body, cond, .. } => {
226                let mut changed = Self::fold_block(body);
227                if Self::try_fold(cond) {
228                    changed = true;
229                }
230                changed
231            }
232            crate::zigir::types::IrStmt::For {
233                init,
234                cond,
235                update,
236                body,
237                ..
238            } => {
239                let mut changed = false;
240                if let Some(i) = init
241                    && Self::fold_stmt(i)
242                {
243                    changed = true;
244                }
245                if let Some(c) = cond
246                    && Self::try_fold(c)
247                {
248                    changed = true;
249                }
250                if let Some(u) = update
251                    && Self::fold_stmt(u)
252                {
253                    changed = true;
254                }
255                if Self::fold_block(body) {
256                    changed = true;
257                }
258                changed
259            }
260            crate::zigir::types::IrStmt::Switch { expr, cases } => {
261                let mut changed = Self::try_fold(expr);
262                for case in cases {
263                    for s in &mut case.body {
264                        if Self::fold_stmt(s) {
265                            changed = true;
266                        }
267                    }
268                }
269                changed
270            }
271            crate::zigir::types::IrStmt::Try {
272                try_block,
273                catch_block,
274                finally,
275                ..
276            } => {
277                let mut changed = Self::fold_block(try_block);
278                if Self::fold_block(catch_block) {
279                    changed = true;
280                }
281                if let Some(f) = finally
282                    && Self::fold_block(f)
283                {
284                    changed = true;
285                }
286                changed
287            }
288            crate::zigir::types::IrStmt::Throw { value } => Self::try_fold(value),
289            crate::zigir::types::IrStmt::Return { value } => {
290                if let Some(v) = value {
291                    Self::try_fold(v)
292                } else {
293                    false
294                }
295            }
296            crate::zigir::types::IrStmt::Expr(e) => Self::try_fold(e),
297            crate::zigir::types::IrStmt::Block(b) => Self::fold_block(b),
298            crate::zigir::types::IrStmt::ForIn { iterable, body, .. } => {
299                let mut changed = Self::try_fold(iterable);
300                if Self::fold_block(body) {
301                    changed = true;
302                }
303                changed
304            }
305            crate::zigir::types::IrStmt::ForOf { iterable, body, .. } => {
306                let mut changed = Self::try_fold(iterable);
307                if Self::fold_block(body) {
308                    changed = true;
309                }
310                changed
311            }
312            crate::zigir::types::IrStmt::Break { .. }
313            | crate::zigir::types::IrStmt::Continue { .. }
314            | crate::zigir::types::IrStmt::CompileError { .. }
315            | crate::zigir::types::IrStmt::Comment(_)
316            | crate::zigir::types::IrStmt::DestructureDecl(_)
317            | crate::zigir::types::IrStmt::NestedFnDecl { .. } => false,
318        }
319    }
320
321    fn fold_block(block: &mut crate::zigir::types::IrBlock) -> bool {
322        let mut changed = false;
323        for stmt in &mut block.stmts {
324            if Self::fold_stmt(stmt) {
325                changed = true;
326            }
327        }
328        changed
329    }
330}
331
332impl IrPass for ConstantFoldPass {
333    fn name(&self) -> &'static str {
334        "constant-fold"
335    }
336
337    fn description(&self) -> &'static str {
338        "Folds constant arithmetic, string, and boolean expressions"
339    }
340
341    fn run(&mut self, module: &mut IrModule) -> PassResult {
342        let mut changed = false;
343
344        // Fold in all declarations
345        for decl in &mut module.declarations {
346            match decl {
347                crate::zigir::types::IrDecl::Fn(f) => {
348                    if Self::fold_block(&mut f.body) {
349                        changed = true;
350                    }
351                }
352                crate::zigir::types::IrDecl::Var(v) => {
353                    if let Some(e) = &mut v.init
354                        && Self::try_fold(e)
355                    {
356                        changed = true;
357                    }
358                }
359                crate::zigir::types::IrDecl::Class(c) => {
360                    if let Some(ctor) = &mut c.constructor
361                        && Self::fold_block(&mut ctor.body)
362                    {
363                        changed = true;
364                    }
365                    for m in &mut c.methods {
366                        if Self::fold_block(&mut m.body) {
367                            changed = true;
368                        }
369                    }
370                    for init in &mut c.static_inits {
371                        if Self::try_fold(init) {
372                            changed = true;
373                        }
374                    }
375                }
376                crate::zigir::types::IrDecl::CompileError { .. } => {}
377            }
378        }
379
380        // Fold in closure structs
381        for cs in &mut module.closure_structs {
382            if Self::fold_block(&mut cs.body) {
383                changed = true;
384            }
385        }
386
387        if changed {
388            PassResult::changed()
389        } else {
390            PassResult::unchanged()
391        }
392    }
393}
394
395impl Default for ConstantFoldPass {
396    fn default() -> Self {
397        Self::new()
398    }
399}
400
401// ═══════════════════════════════════════════════════════
402//  Fold helpers
403// ═══════════════════════════════════════════════════════
404
405fn fold_binary(op: BinOp, left: &IrExpr, right: &IrExpr) -> Option<IrExpr> {
406    match (left, right) {
407        // Integer arithmetic
408        (IrExpr::IntLiteral(a), IrExpr::IntLiteral(b)) => {
409            let result = match op {
410                BinOp::Add => a.checked_add(*b)?,
411                BinOp::Sub => a.checked_sub(*b)?,
412                BinOp::Mul => a.checked_mul(*b)?,
413                BinOp::Div => {
414                    if *b == 0 {
415                        return None;
416                    }
417                    a.checked_div(*b)?
418                }
419                BinOp::Mod => {
420                    if *b == 0 {
421                        return None;
422                    }
423                    *a % *b
424                }
425                BinOp::BitAnd => a & b,
426                BinOp::BitOr => a | b,
427                BinOp::BitXor => a ^ b,
428                BinOp::Shl => {
429                    if *b < 0 || *b >= 64 {
430                        return None;
431                    }
432                    a << *b
433                }
434                BinOp::Shr => {
435                    if *b < 0 || *b >= 64 {
436                        return None;
437                    }
438                    a >> *b
439                }
440                BinOp::Eq | BinOp::StrictEq => return Some(IrExpr::BoolLiteral(a == b)),
441                BinOp::Ne | BinOp::StrictNe => return Some(IrExpr::BoolLiteral(a != b)),
442                BinOp::Lt => return Some(IrExpr::BoolLiteral(a < b)),
443                BinOp::Le => return Some(IrExpr::BoolLiteral(a <= b)),
444                BinOp::Gt => return Some(IrExpr::BoolLiteral(a > b)),
445                BinOp::Ge => return Some(IrExpr::BoolLiteral(a >= b)),
446                _ => return None,
447            };
448            Some(IrExpr::IntLiteral(result))
449        }
450        // Float arithmetic
451        (IrExpr::FloatLiteral(a), IrExpr::FloatLiteral(b)) => {
452            let result = match op {
453                BinOp::Add => a + b,
454                BinOp::Sub => a - b,
455                BinOp::Mul => a * b,
456                BinOp::Div => {
457                    if *b == 0.0 {
458                        return None;
459                    }
460                    a / b
461                }
462                BinOp::Mod => a % b,
463                BinOp::Eq | BinOp::StrictEq => return Some(IrExpr::BoolLiteral(a == b)),
464                BinOp::Ne | BinOp::StrictNe => return Some(IrExpr::BoolLiteral(a != b)),
465                BinOp::Lt => return Some(IrExpr::BoolLiteral(a < b)),
466                BinOp::Le => return Some(IrExpr::BoolLiteral(a <= b)),
467                BinOp::Gt => return Some(IrExpr::BoolLiteral(a > b)),
468                BinOp::Ge => return Some(IrExpr::BoolLiteral(a >= b)),
469                _ => return None,
470            };
471            Some(IrExpr::FloatLiteral(result))
472        }
473        // Mixed int + float → promote to float
474        (IrExpr::IntLiteral(a), IrExpr::FloatLiteral(b)) => {
475            let a_f = *a as f64;
476            let result = match op {
477                BinOp::Add => a_f + b,
478                BinOp::Sub => a_f - b,
479                BinOp::Mul => a_f * b,
480                BinOp::Div => a_f / b,
481                _ => return None,
482            };
483            Some(IrExpr::FloatLiteral(result))
484        }
485        (IrExpr::FloatLiteral(a), IrExpr::IntLiteral(b)) => {
486            let b_f = *b as f64;
487            let result = match op {
488                BinOp::Add => a + b_f,
489                BinOp::Sub => a - b_f,
490                BinOp::Mul => a * b_f,
491                BinOp::Div => a / b_f,
492                _ => return None,
493            };
494            Some(IrExpr::FloatLiteral(result))
495        }
496        // String concatenation
497        (IrExpr::StringLiteral(a), IrExpr::StringLiteral(b)) => {
498            if op == BinOp::Add {
499                Some(IrExpr::StringLiteral(format!("{}{}", a, b)))
500            } else {
501                None
502            }
503        }
504        // Boolean comparisons
505        (IrExpr::BoolLiteral(a), IrExpr::BoolLiteral(b)) => {
506            let result = match op {
507                BinOp::Eq | BinOp::StrictEq => a == b,
508                BinOp::Ne | BinOp::StrictNe => a != b,
509                _ => return None,
510            };
511            Some(IrExpr::BoolLiteral(result))
512        }
513        // Null comparisons
514        (IrExpr::Null, IrExpr::Null) => {
515            if op == BinOp::Eq || op == BinOp::StrictEq {
516                Some(IrExpr::BoolLiteral(true))
517            } else if op == BinOp::Ne || op == BinOp::StrictNe {
518                Some(IrExpr::BoolLiteral(false))
519            } else {
520                None
521            }
522        }
523        _ => None,
524    }
525}
526
527fn fold_unary(op: UnaOp, operand: &IrExpr) -> Option<IrExpr> {
528    match (op, operand) {
529        (UnaOp::Neg, IrExpr::IntLiteral(n)) => Some(IrExpr::IntLiteral(-n)),
530        (UnaOp::Neg, IrExpr::FloatLiteral(n)) => Some(IrExpr::FloatLiteral(-n)),
531        (UnaOp::Not, IrExpr::BoolLiteral(b)) => Some(IrExpr::BoolLiteral(!b)),
532        (UnaOp::BitNot, IrExpr::IntLiteral(n)) => Some(IrExpr::IntLiteral(!n)),
533        // Double negation: !!x → x (when inner is already a bool)
534        (
535            UnaOp::Not,
536            IrExpr::Unary {
537                op: UnaOp::Not,
538                operand: inner,
539            },
540        ) => {
541            if matches!(inner.as_ref(), IrExpr::BoolLiteral(_)) {
542                // We can't take ownership from &, so clone
543                Some((**inner).clone())
544            } else {
545                None
546            }
547        }
548        _ => None,
549    }
550}
551
552fn fold_logical(op: LogicalOp, left: &IrExpr, right: &IrExpr) -> Option<IrExpr> {
553    match (op, left, right) {
554        // Short-circuit on known booleans
555        (LogicalOp::And, IrExpr::BoolLiteral(false), _) => Some(IrExpr::BoolLiteral(false)),
556        (LogicalOp::And, IrExpr::BoolLiteral(true), _) => {
557            // true && right → right
558            Some(right.clone())
559        }
560        (LogicalOp::Or, IrExpr::BoolLiteral(true), _) => Some(IrExpr::BoolLiteral(true)),
561        (LogicalOp::Or, IrExpr::BoolLiteral(false), _) => {
562            // false || right → right
563            Some(right.clone())
564        }
565        (LogicalOp::Nullish, IrExpr::Null, right) => Some(right.clone()),
566        (LogicalOp::Nullish, IrExpr::Undefined, right) => Some(right.clone()),
567        _ => None,
568    }
569}
570
571/// Compute the `typeof` result string for literal expressions.
572fn typeof_literal(expr: &IrExpr) -> Option<String> {
573    match expr {
574        IrExpr::IntLiteral(_) | IrExpr::FloatLiteral(_) => Some("number".to_string()),
575        IrExpr::StringLiteral(_) => Some("string".to_string()),
576        IrExpr::BoolLiteral(_) => Some("boolean".to_string()),
577        IrExpr::Null => Some("object".to_string()), // JS typeof null === "object"
578        IrExpr::Undefined => Some("undefined".to_string()),
579        IrExpr::ArrowFn(_) | IrExpr::Closure(_) | IrExpr::FnExpr(_) => Some("function".to_string()),
580        _ => None,
581    }
582}
583
584// ═══════════════════════════════════════════════════════
585//  Tests
586// ═══════════════════════════════════════════════════════
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591    use crate::types::ZigType;
592    use crate::zigir::ident::IrIdent;
593    use crate::zigir::types::{IrBlock, IrDecl, IrFnDecl, IrStmt};
594
595    #[test]
596    fn test_fold_int_add() {
597        let mut module = make_module_with_body(vec![IrStmt::Return {
598            value: Some(IrExpr::Binary {
599                op: BinOp::Add,
600                left: Box::new(IrExpr::IntLiteral(1)),
601                right: Box::new(IrExpr::IntLiteral(2)),
602                left_type: None,
603                right_type: None,
604            }),
605        }]);
606        let mut pass = ConstantFoldPass::new();
607        let result = pass.run(&mut module);
608        assert!(result.changed);
609        if let IrDecl::Fn(f) = &module.declarations[0] {
610            if let IrStmt::Return {
611                value: Some(IrExpr::IntLiteral(n)),
612            } = &f.body.stmts[0]
613            {
614                assert_eq!(*n, 3);
615            } else {
616                panic!("expected IntLiteral(3)");
617            }
618        }
619    }
620
621    #[test]
622    fn test_fold_float_mul() {
623        let mut module = make_module_with_body(vec![IrStmt::Return {
624            value: Some(IrExpr::Binary {
625                op: BinOp::Mul,
626                left: Box::new(IrExpr::FloatLiteral(1.5)),
627                right: Box::new(IrExpr::FloatLiteral(2.0)),
628                left_type: None,
629                right_type: None,
630            }),
631        }]);
632        let mut pass = ConstantFoldPass::new();
633        let result = pass.run(&mut module);
634        assert!(result.changed);
635        if let IrDecl::Fn(f) = &module.declarations[0] {
636            if let IrStmt::Return {
637                value: Some(IrExpr::FloatLiteral(n)),
638            } = &f.body.stmts[0]
639            {
640                assert_eq!(*n, 3.0);
641            } else {
642                panic!("expected FloatLiteral(3.0)");
643            }
644        }
645    }
646
647    #[test]
648    fn test_fold_string_concat() {
649        let mut module = make_module_with_body(vec![IrStmt::Return {
650            value: Some(IrExpr::Binary {
651                op: BinOp::Add,
652                left: Box::new(IrExpr::StringLiteral("Hello, ".to_string())),
653                right: Box::new(IrExpr::StringLiteral("world!".to_string())),
654                left_type: None,
655                right_type: None,
656            }),
657        }]);
658        let mut pass = ConstantFoldPass::new();
659        let result = pass.run(&mut module);
660        assert!(result.changed);
661        if let IrDecl::Fn(f) = &module.declarations[0] {
662            if let IrStmt::Return {
663                value: Some(IrExpr::StringLiteral(s)),
664            } = &f.body.stmts[0]
665            {
666                assert_eq!(s, "Hello, world!");
667            } else {
668                panic!("expected StringLiteral");
669            }
670        }
671    }
672
673    #[test]
674    fn test_fold_unary_negate() {
675        let mut module = make_module_with_body(vec![IrStmt::Return {
676            value: Some(IrExpr::Unary {
677                op: UnaOp::Neg,
678                operand: Box::new(IrExpr::IntLiteral(42)),
679            }),
680        }]);
681        let mut pass = ConstantFoldPass::new();
682        let result = pass.run(&mut module);
683        assert!(result.changed);
684        if let IrDecl::Fn(f) = &module.declarations[0] {
685            if let IrStmt::Return {
686                value: Some(IrExpr::IntLiteral(n)),
687            } = &f.body.stmts[0]
688            {
689                assert_eq!(*n, -42);
690            } else {
691                panic!("expected IntLiteral(-42)");
692            }
693        }
694    }
695
696    #[test]
697    fn test_fold_not_bool() {
698        let mut module = make_module_with_body(vec![IrStmt::Return {
699            value: Some(IrExpr::Unary {
700                op: UnaOp::Not,
701                operand: Box::new(IrExpr::BoolLiteral(true)),
702            }),
703        }]);
704        let mut pass = ConstantFoldPass::new();
705        let result = pass.run(&mut module);
706        assert!(result.changed);
707        if let IrDecl::Fn(f) = &module.declarations[0] {
708            if let IrStmt::Return {
709                value: Some(IrExpr::BoolLiteral(b)),
710            } = &f.body.stmts[0]
711            {
712                assert!(!b);
713            } else {
714                panic!("expected BoolLiteral(false)");
715            }
716        }
717    }
718
719    #[test]
720    fn test_fold_conditional_true() {
721        let mut module = make_module_with_body(vec![IrStmt::Return {
722            value: Some(IrExpr::Conditional {
723                cond: Box::new(IrExpr::BoolLiteral(true)),
724                then: Box::new(IrExpr::IntLiteral(1)),
725                else_: Box::new(IrExpr::IntLiteral(2)),
726            }),
727        }]);
728        let mut pass = ConstantFoldPass::new();
729        let result = pass.run(&mut module);
730        assert!(result.changed);
731        if let IrDecl::Fn(f) = &module.declarations[0] {
732            if let IrStmt::Return {
733                value: Some(IrExpr::IntLiteral(n)),
734            } = &f.body.stmts[0]
735            {
736                assert_eq!(*n, 1);
737            } else {
738                panic!("expected IntLiteral(1)");
739            }
740        }
741    }
742
743    #[test]
744    fn test_fold_and_false() {
745        let mut module = make_module_with_body(vec![IrStmt::Return {
746            value: Some(IrExpr::Logical {
747                op: LogicalOp::And,
748                left: Box::new(IrExpr::BoolLiteral(false)),
749                right: Box::new(IrExpr::Ident(IrIdent::new("x"))),
750            }),
751        }]);
752        let mut pass = ConstantFoldPass::new();
753        let result = pass.run(&mut module);
754        assert!(result.changed);
755        if let IrDecl::Fn(f) = &module.declarations[0] {
756            if let IrStmt::Return {
757                value: Some(IrExpr::BoolLiteral(b)),
758            } = &f.body.stmts[0]
759            {
760                assert!(!b);
761            } else {
762                panic!("expected BoolLiteral(false)");
763            }
764        }
765    }
766
767    #[test]
768    fn test_fold_typeof_int() {
769        let mut module = make_module_with_body(vec![IrStmt::Return {
770            value: Some(IrExpr::Typeof(Box::new(IrExpr::IntLiteral(42)))),
771        }]);
772        let mut pass = ConstantFoldPass::new();
773        let result = pass.run(&mut module);
774        assert!(result.changed);
775        if let IrDecl::Fn(f) = &module.declarations[0] {
776            if let IrStmt::Return {
777                value: Some(IrExpr::StringLiteral(s)),
778            } = &f.body.stmts[0]
779            {
780                assert_eq!(s, "number");
781            } else {
782                panic!("expected StringLiteral(\"number\")");
783            }
784        }
785    }
786
787    #[test]
788    fn test_no_fold_dynamic() {
789        let mut module = make_module_with_body(vec![IrStmt::Return {
790            value: Some(IrExpr::Binary {
791                op: BinOp::Add,
792                left: Box::new(IrExpr::Ident(IrIdent::new("x"))),
793                right: Box::new(IrExpr::IntLiteral(1)),
794                left_type: None,
795                right_type: None,
796            }),
797        }]);
798        let mut pass = ConstantFoldPass::new();
799        let result = pass.run(&mut module);
800        assert!(!result.changed); // can't fold: x is dynamic
801    }
802
803    #[test]
804    fn test_fold_nested() {
805        // (1 + 2) + (3 + 4) → 10
806        let mut module = make_module_with_body(vec![IrStmt::Return {
807            value: Some(IrExpr::Binary {
808                op: BinOp::Add,
809                left: Box::new(IrExpr::Binary {
810                    op: BinOp::Add,
811                    left: Box::new(IrExpr::IntLiteral(1)),
812                    right: Box::new(IrExpr::IntLiteral(2)),
813                    left_type: None,
814                    right_type: None,
815                }),
816                right: Box::new(IrExpr::Binary {
817                    op: BinOp::Add,
818                    left: Box::new(IrExpr::IntLiteral(3)),
819                    right: Box::new(IrExpr::IntLiteral(4)),
820                    left_type: None,
821                    right_type: None,
822                }),
823                left_type: None,
824                right_type: None,
825            }),
826        }]);
827        let mut pass = ConstantFoldPass::new();
828        let result = pass.run(&mut module);
829        assert!(result.changed);
830        if let IrDecl::Fn(f) = &module.declarations[0] {
831            if let IrStmt::Return {
832                value: Some(IrExpr::IntLiteral(n)),
833            } = &f.body.stmts[0]
834            {
835                assert_eq!(*n, 10);
836            } else {
837                panic!("expected IntLiteral(10)");
838            }
839        }
840    }
841
842    #[test]
843    fn test_fold_allocprint_no_args() {
844        let mut module = make_module_with_body(vec![IrStmt::Return {
845            value: Some(IrExpr::AllocPrint {
846                fmt: "hello".to_string(),
847                args: vec![],
848            }),
849        }]);
850        let mut pass = ConstantFoldPass::new();
851        let result = pass.run(&mut module);
852        assert!(result.changed);
853        if let IrDecl::Fn(f) = &module.declarations[0] {
854            if let IrStmt::Return {
855                value: Some(IrExpr::StringLiteral(s)),
856            } = &f.body.stmts[0]
857            {
858                assert_eq!(s, "hello");
859            } else {
860                panic!("expected StringLiteral(\"hello\")");
861            }
862        }
863    }
864
865    #[test]
866    fn test_fold_null_equality() {
867        let mut module = make_module_with_body(vec![IrStmt::Return {
868            value: Some(IrExpr::Binary {
869                op: BinOp::Eq,
870                left: Box::new(IrExpr::Null),
871                right: Box::new(IrExpr::Null),
872                left_type: None,
873                right_type: None,
874            }),
875        }]);
876        let mut pass = ConstantFoldPass::new();
877        let result = pass.run(&mut module);
878        assert!(result.changed);
879        if let IrDecl::Fn(f) = &module.declarations[0] {
880            if let IrStmt::Return {
881                value: Some(IrExpr::BoolLiteral(b)),
882            } = &f.body.stmts[0]
883            {
884                assert!(b);
885            } else {
886                panic!("expected BoolLiteral(true)");
887            }
888        }
889    }
890
891    // Helper to create a module with a function wrapping the given body
892    fn make_module_with_body(body: Vec<IrStmt>) -> IrModule {
893        let mut module = IrModule::new("test".to_string());
894        module.declarations.push(IrDecl::Fn(IrFnDecl {
895            name: IrIdent::new("test_fn"),
896            params: vec![],
897            return_type: ZigType::I64,
898            body: IrBlock::new(body),
899            is_export: false,
900            is_async: false,
901            can_throw: false,
902            is_cabi: false,
903            typeof_return_body: None,
904        }));
905        module
906    }
907}