You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Fold constant expressions on the typed AST instead of the parser AST #25
Evaluate static initializers and case labels by type-checking the expression first, then folding the typed AST, instead of folding the untyped parser AST.
Why
eval_constant_expr (src/validate.rs) folds ParserExpr, which has no types. So it has to re-derive the usual arithmetic conversions itself. Every place it disagreed with typecheck_exp was a bug:
F1: ?: skipped the common-type conversion, so (1 ? -6 : 0u) / 2 folded to -3.
F4: the zero-divisor check ran before conversion, so 1.0 / 0 was rejected.
PR #24 fixed these by moving the type rules into binary_types, which both paths now use. That works, but the folder still keeps its own copy of the type logic, and anything that matters (?:, short-circuit) has to be mirrored by hand.
After typecheck_exp, every conversion is an explicit Cast node and every operand of a binary operator already has the common type. A folder over TypedExpression would need no type rules at all, so this class of bug couldn't happen.
When
Chapter 14: static pointer initializers (static int *p = 0;, null pointer constants) need type information anyway. Same reasoning applies to the Chapter 19 TACKY constant-folding pass: it folds after type checking, so it never needs binary_types.
Things to work out
Case labels are folded in the resolve pass, before symbols exist. They would have to move to type checking. Duplicate detection already happens there.
Warnings:typecheck_exp emits -Wdiv-by-zero and -Wshift-count-*. Make sure they don't fire twice on the same initializer.
Unevaluated operands: the short-circuit / untaken-?: handling (live in fold_constant) still applies to the typed folder.
Error messages: "not a constant expression" now comes from ConstEvalError::NotConstant. A typed folder hits Var / FunctionCall nodes instead, after they've been resolved and typed.
Tests:static_vars/const_eval_conversions.c, conversions/double_to_* and the warning tests should pass unchanged.
Activity