Loading the code workspace…
Implement constant folding as an AST optimization pass.
Implement fold_expression() that:
Handle these operations:
Handle edge cases:
Fold nested expressions:
(1 + 2) * (3 + 4) → 212 + 3 → 5 (literal node)x + 0 → x (identity optimization)x * 1 → x (identity optimization)0 * x → 0 (if no side effects)Constant folding runs in every compiler at every optimization level — even -O0 Clang folds 2+3 — and JavaScript minifiers like Terser apply it to shrink every production bundle on the web. It is also the canonical example of compile-time evaluation, the idea that grew into C++ constexpr and Rust const fn.