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