Skip to content

#943: comptime integer arithmetic evaluates at the declared width - #1080

Merged
ehartford merged 6 commits into
mainfrom
issue943
Sep 5, 2026
Merged

ehartford merged 6 commits into
mainfrom
issue943

Conversation

@migueldecimal128

Copy link
Copy Markdown
Contributor

Fixes #943.

Summary

The comptime evaluator performed integer arithmetic at 32 bits regardless of
declared type, suffix, annotation, or return type. Operands were truncated to
width before the overflow check ran, so an out-of-range operand was silently
normalized rather than diagnosed — an identity operation was enough to corrupt
its own input:

comptime fn ident -> i64: 3000000001i64 + 0i64
const I: i64 = comptime ident()      // -1294967295

Both operands carry i64 suffixes, the function returns i64, and the const is
annotated i64. -1294967295 is exactly 3000000001 - 2^32.

This was a soundness problem, not only a wrong answer: a comptime fn is also
callable at runtime, where the same expression evaluated correctly. One function,
one argument, two answers depending on where it was called.

Root cause

Sema had the correct type throughout. The evaluator's type lookup missed it and
fell back to ty_i32 (ComptimeEval.w, the fast literal path), and every
consumer of a typed integer payload had independently re-implemented the same
narrowing. Nine sites in total, each narrowing or re-interpreting a payload
before measuring it.

The governing rule this implements, from plans/comptime-int-width.md:

For any expression comptime evaluates, it must produce the value the runtime
would produce and detect exactly the same overflow conditions. Where comptime
cannot faithfully reproduce runtime behavior, it must refuse to evaluate —
never approximate.

Truncation is a semantic operation the programmer asks for (as, *%, +%).
It is never a repair applied to make an invalid internal state look valid.

What changed

commit
e71f221f S0 — failing tests and the implementation plan
cf489049 literal type from suffix + sema's value-based default; local let/var annotation applied at binding
bc5182a1 value write-back to the AST (ct_build_value_tree); unsigned OP_DIV/OP_MOD; unsigned ordering < > <= >=
e8b63425 negated literals in comptime, via int_literal_expr_bits on the unary node
195e2c92 #914 D2 — sema check_unary, the negation-aware fit check, both MIR lowering paths
d4dd34c1 S4 — checked_int_value asserts a payload is canonical in its own type_id, aborts with a BUG: diagnostic otherwise

195e2c92 belongs to #914 rather than #943: making signed MIN spellable
(-2147483648i32) was a prerequisite, because negating the operand cannot
express MIN — the magnitude and the sign have to stay apart until the width is
applied.

Before / after

expression before after
3000000001i64 + 0i64 -1294967295 3000000001
0i64 - 3000000000i64 1294967296 -3000000000
4294967296u64 + 0u64 0 4294967296
4294967301u64 * 1u64 5 4294967301
1i64 << 40 0 1099511627776
2147483647i64 + 1i64 error: integer overflow in comptime 2147483648

Tests

test/behavior/behav_comptime_int_width.w is a four-term differential oracle:

comptime E  ==  plain-const-fold E  ==  runtime E  ==  expected literal

The fourth term is not redundant — plain const folding runs through the same
evaluator as an explicit comptime and shares its ceiling, so a three-way check
can pass unanimously while every term is wrong. Runtime is the independent term.

Every operation in the oracle is an identity (+ 0, - 0, * 1, / 1,
<< 0), so a correct evaluator cannot overflow at any width — which isolates
operand truncation specifically, since an identity can never trip an overflow
check.

behav_comptime_overflow_wrap.w and behav_comptime_overflow_saturate.w pin
the wrap and saturate modes.

The two compile_errors fixtures added in S0 were deleted once the spurious
diagnostics stopped firing and their cases were promoted into the oracle,
exactly as their own comments instructed.

Verification

Full battery, every target re-run rather than cached:

with build            all targets green
with build :fixpoint  FIXPOINT — stage2 byte-identical to stage3
with build :test      all targets green, 0 failures

Also verified: a 55-case comptime-vs-runtime range differential across
i32/u32/i64/u64 — MAX, MIN, identity ops, + - * / % with negative
operands, shifts, bitwise, and ordering across the sign bit — all matching.

Scope and known limitations

  • The 64-bit ceiling is still open. 18446744073709551616 + 1 folds to 1.
    The payload is one i64; widening it belongs to i128/u128 end to end: wide literals, formatting, boundary tests, spec §4.1 #914, not here.
  • S1 deliberately not done. Its value was converting silent corruption into
    loud errors while the width bug was live; S2 fixed the widths, so by its own
    acceptance criterion it now changes no observable behavior, while touching six
    helpers reached by Sema, the evaluator, and both codegens. S4 is strictly
    upstream of it and catches the cases S1 structurally cannot — including a real
    regression made during this campaign, where a sign-extension slip made
    -2147483647i32 / 3 return +715827883 through OP_DIV, a path S1 never
    enters. The reasoning is recorded in the plan; recommendation is to fold S1
    into i128/u128 end to end: wide literals, formatting, boundary tests, spec §4.1 #914's word-pair work on Overflow.w.
  • S4 is partial by choice. 25 of 102 comptime_value_int call sites are
    routed through the checked constructor — the 21 building computed arithmetic
    results plus the literal and annotation constructions, where every defect in
    this campaign originated. The remaining 77 construct trivially canonical
    values; mechanical edits at that scale in a self-hosting compiler cost more
    risk than the coverage is worth. Anyone extending this should convert the rest
    rather than assume it is total.

Notes for the reviewer

The comptime evaluator does integer arithmetic at 32 bits regardless of
declared type, suffix, annotation, or return type. Identity operations
corrupt their operand:

    3000000001i64 + 0i64   -> -1294967295
    4294967296u64 + 0u64   -> 0
    1i64 << 40             -> 0

Operands are truncated to width before the overflow check runs
(Overflow.w:152-215), so adding zero cannot trip the check and the
corruption is silent. A comptime fn is also callable at runtime, where
the same expression is correct, so one function returns two answers
depending on where it is called.

No fix here — this commit adds the tests that pin the behavior and the
plan for repairing it.

Tests (behavior, marked known-issue #943 so they are tolerated red and
fail the file if they ever pass):
  behav_comptime_int_width.w        four-term oracle across all eight
                                    integer widths, identity operations
                                    only, so a correct evaluator cannot
                                    overflow at any width
  behav_comptime_overflow_wrap.w    comptime applies i32 wrap semantics
  behav_comptime_overflow_saturate.w  ... and i32 saturation

Tests (compile_errors, green today, pinning current diagnostics):
  comptime_int_width_overflow.w     spurious "integer overflow in comptime"
  comptime_int_width_unsigned_fit.w misleading "integer literal does not
                                    fit expected type" — no literal is at
                                    fault

Measured boundary: every width at or below 32 bits is correct today,
including u32 at 4294967295; only i64 and u64 corrupt. Division escapes
because the OP_DIV arm computes on raw operands.

plans/comptime-int-width.md carries the root cause, the semantic model,
and staged fixes S1-S5.

Verified on a compiler built from 22e534c (v0.15.1.7-g22e534c6c);
build, :fixpoint, and :test all green with these files added.
Comptime folding runs before sema — Frontend.compile_source calls
comptime_transform_module against a Sema prepared only by
prepare_for_comptime_transform, which never runs check_expr — so
typed_expr_types is empty for the nodes being folded. node_type_or then
fell through to a hardcoded i32 default, discarding the width the
programmer wrote, and every later operation inherited it.

Two changes in src/ComptimeEval.w, both recovering the declared width
from information that is available pre-sema:

  comptime_int_literal_type  resolves an integer literal as sema's table
                             if present, then the literal's own suffix,
                             then sema's value-based default for
                             unsuffixed literals (i64 outside i32 range,
                             i32 otherwise) instead of hardcoding i32.
                             Mirrors SemaCheck's NK_INT_LIT precedence,
                             so a node folded early gets the type it is
                             later assigned.

  local_annotation_int_type  reads a local let/var annotation, which
                             pre-sema is the only place a width like
                             `var h: u64 = 5381` is written, and retypes
                             the bound value. Retypes only when the value
                             fits: a value that does not fit is left
                             alone so sema still reports the mismatch,
                             since narrowing here would convert a
                             reportable error into a masked one.

Fixed:

    3000000001i64 + 0i64          -> 3000000001      (was -1294967295)
    4294967296u64 + 0u64          -> 4294967296      (was 0)
    1i64 << 40                    -> 1099511627776   (was 0)
    2147483647i64 + 1i64          -> 2147483648      (was a spurious
                                                      overflow error)
    3000000001u64 + 0u64          -> 3000000001      (was a misleading
                                                      fit error)
    var x: i64 = 3000000001; x+0  -> 3000000001
    djb2 accumulator over u64     -> matches runtime exactly

NOT fixed — u64 above i64::MAX still does not work:

    9223372036854775808u64 + 0u64   error
    18446744073709551615u64 + 0u64  error

Those literals miss int_literal_fast_i64, take the exact path, and land
in ComptimeValue.data0 (an i64) as a two's-complement bit pattern; the
fit check at materialization then reads that payload as signed. Separate
defect, pre-existing — the v0.15.1.7 seed fails identically — and it
needs the data0 widening plans/comptime-int-width.md argues is
structurally forced. The upper half of u64 is unusable from comptime.

behav_comptime_int_width.w does NOT cover that hole: its u64 cases use
4294967296, below 2^63, so it passes while half the type is broken. The
file's claim to span all eight widths is true only of the lower half of
the unsigned ones.

Tests: known-issue directives removed from the three behavior files, now
green. The two compile_errors fixtures no longer error, so their cases
are promoted into behav_comptime_int_width.w and the files deleted, as
their own comments instructed.

Gates on 22e534c + this change: build green, :fixpoint FIXPOINT
(stage2 byte-identical to stage3), :test all green — 977 behavior, 749
compile-error, 210 spec, 51 phase, 16 codegen, 6 comptime-diff, all
re-run rather than cached. Nothing in the suite depended on the old
32-bit truncation.
Follow-on to f668e4f, which fixed width resolution but left u64 above
i64::MAX broken. ComptimeValue.data0 is an i64, so an unsigned value in
the top half of its range is a two's-complement bit pattern rather than
a number — u64::MAX is -1, 2^63 is -9223372036854775808. Three consumers
read that payload without knowing it:

  ct_build_value_tree (ComptimeTransform.w) wrote a folded value back to
    the AST as a bare NK_INT_LIT, dropping type_id. int_literal_fits_type
    then took its non-exact path, reached `if bits >= 64 ... return
    value >= 0`, and rejected the value for the type it came from. Now
    records the true magnitude as exact digits when the type is unsigned
    and the sign bit is set, routing the check through
    exact_int_fits_unsigned_bits.

  OP_DIV / OP_MOD (ComptimeEval.w) divided signed: u64::MAX / 3 was
    -1 / 3 = 0, and u64::MAX % 7 was -1 % 7 = -1. Now dispatches on the
    result type's signedness.

  OP_LT / OP_GT / OP_LTE / OP_GTE (ComptimeEval.w) compared signed, so
    u64::MAX < 1 was -1 < 1, i.e. true. Now uses exact_int_uword_lt /
    _lte for unsigned operands. OP_EQ and OP_NEQ are unchanged — bit
    equality is correct either way.

The ordering defect was found by reading the compare arm, not by the
tests; an eight-case operator sweep at the top of the range missed it
entirely. Both the ordering cases and signed controls are now in the
test, the latter because these fixes branch on signedness and making
unsigned right by making signed wrong would otherwise pass.

Verified against runtime, 15 cases, all matching: + - * / % << >> & | ^
at the top of u64's range, the four orderings across the sign bit, and
-1i64 < 1i64 / -9i64 / 3i64 / -9i64 % 7i64 unchanged.

behav_comptime_int_width.w loses the known-issue directive added for
this hole and gains the div/mod/ordering and signed-control cases.

NOT yet run on this commit: :fixpoint and the full :test suite. Both
were green on f668e4f. This change touches ComptimeTransform.w, which
the compiler uses on its own source, so fixpoint is the gate that
matters and is running now.
`-2147483648i32` is i32::MIN and must evaluate, but the comptime
evaluator reported "integer overflow in comptime" for it. Negating the
*operand* cannot express MIN: int_eval_unary_neg narrows the operand to
the target width first, and 2147483648 is 2^31, whose low 32 bits read
as signed are -2147483648. The operand became MIN and the "negating MIN
is unrepresentable" guard fired on a MIN the source never contained —
the evaluator diagnosing its own artifact.

The magnitude and the sign have to stay apart until the width is
applied. int_literal_exact_expr already keeps them apart across
UOP_NEGATE, and int_literal_expr_bits applies the width once through
exact_int_fits_signed_negative_bits, which accepts magnitude 2^(bits-1)
when negative and rejects it when positive. Both codegens already lower
negated literals this way; eval_unary now does too, for signed types at
64 bits or narrower. Non-literal operands, unsigned negation, and the
128-bit case (#914) fall through to the existing path unchanged.

The stored payload is sign-extended through int_truncate_to_width before
binding. int_literal_expr_bits returns the two's-complement pattern
*within* the requested width, so at 32 bits -2147483647 comes back as
0x80000001 = +2147483649; storing that unextended made every later
operation read a large positive number and turned -2147483647i32 / 3
into +715827883. Caught by the range differential, not by inspection —
and it was a violation of the same canonical-payload invariant this
whole campaign exists to enforce.

This fixes the comptime half only. `-2147483648i32` now fails in sema
instead:

    error: integer literal does not fit suffix type

SemaCheck's NK_INT_LIT arm checks the literal against its suffix type in
isolation, without knowing it is the operand of a negation. That is
#914's D2, it lives in a different file, and it rejects the same
expression with no `comptime` involved at all:

    var a: i32 = -2147483648i32     // same error, no comptime

So suffixed signed MIN remains unspellable language-wide for i8/i16/i32/
i64. Unsuffixed `-2147483648` works everywhere. The fix is the same
machinery applied in check_unary, which touches every negated literal in
the language and is deliberately not attempted here.

Verified: 55-case comptime-vs-runtime differential across i32/u32/i64/
u64 — MAX, MIN, identity ops, +-*/% with negative operands, shifts,
bitwise, and ordering across the sign bit — all matching. The three
committed behavior tests stay green.

NOT yet run on this commit: :fixpoint and the full :test suite, both
green on ff07cf5. Running now.
…nitudes

Before this, `i64::MIN` could not be written anywhere in the language:

    var b: i64 = -9223372036854775808
    error: integer literal does not fit default type ('9223372036854775808', ...)

and the suffixed form failed for every signed width:

    var a: i32 = -2147483648i32
    error: integer literal does not fit suffix type

A literal under a unary `-` is a *magnitude*, not a value, and the two
ranges are not symmetric: at `bits` the largest magnitude is 2^(bits-1)
negative but 2^(bits-1)-1 positive. Checking the literal in isolation
therefore rejects exactly MIN. Every consumer of a negated literal had
re-derived the interpretation for itself, and each one got it wrong the
same way — by narrowing the operand before measuring it.

Five pieces, because the defect was five-fold:

  Sema.w        in_negated_literal_context, a counter mirroring
                in_bitwise_literal_context, saved/restored around the
                operand check.
  Sema.w        int_literal_fits_type_negated — the magnitude-aware range
                check, routing exact literals through
                exact_int_fits_signed_negative_bits. Unsigned defers to
                the ordinary check so the diagnostic stays "cannot negate
                an unsigned value" rather than becoming a fit error.
  SemaCheck.w   a UOP_NEGATE arm in check_unary threading a *signed*
                integer expectation into the operand — the treatment `~`
                received in #767 — and checking that operand inside the
                negation context.
  SemaCheck.w   the NK_INT_LIT suffix branch consults the negation-aware
                check when that context is set.
  MirLower.w    try_eval_const folds the whole negation instead of
                negating a narrowed operand.
  MirLower.w    lower_un_op emits CK_INT_EXACT carrying the unary node
                rather than a runtime RK_UN_OP.

That last piece was exposed only by fixing sema. With sema rejecting the
expression, lowering never saw it; once accepted, lower_un_op emitted a
runtime negate that trapped:

    panic: integer overflow: negating i32 minimum value

i.e. the sema fix alone traded a clean compile error for a crash. It is
not shippable without the lowering half, and CK_INT_EXACT was already the
right vehicle — codegen resolves it via int_literal_expr_bits, which
keeps magnitude and sign apart until the width applies, and handles both
words for the eventual 128-bit case.

Now working, runtime and comptime:

    i8::MIN  -128i8                    -128
    i16::MIN -32768i16                 -32768
    i32::MIN -2147483648i32            -2147483648
    i64::MIN -9223372036854775808i64   -9223372036854775808

Guarded regression, verified: `-x` on a u32 still reports "cannot negate
an unsigned value", not a fit error.

Gates: :fixpoint FIXPOINT (stage2 byte-identical to stage3, with the
compiler's own negated literals routed through the new path), and the
full suite green with every target re-run rather than cached — 977
behavior, 749 compile-error, 210 spec, 51 phase, 16 codegen, 6
comptime-diff, 14 internals, 7 lexer, 9 parser. The 749 compile-error
fixtures are the ones that pin diagnostics, and none moved: the
negation-aware path is additive, accepting what was wrongly rejected
without loosening anything that should still be rejected.

The 55-case comptime-vs-runtime range differential across i32/u32/i64/u64
still matches everywhere.
Invariant 2 of the plan, enforced. `(type_id = i32, data0 = 3000000001)`
is not a value of any i32 — it is the state every defect in this
campaign passed through, and truncating it to fit is what made the
corruption silent rather than loud.

checked_int_value (ComptimeEval.w) verifies the payload survives a
round trip through its own width and signedness before constructing,
and aborts with a BUG: diagnostic otherwise, matching the
ast_pool_phase_bug idiom. Truncation is an identity on a canonical
payload, so this fires only on a compiler bug, never on user input.
Width >= 64 always passes: any i64 payload is canonical for a 64-bit
type, signed or unsigned.

It catches both real bugs from this campaign at the point of
construction, before the value reaches any operator:

  (i32, 3000000001)   the original defect
  (i32, 2147483649)   the sign-extension regression introduced in
                      4c6f87e, which surfaced as -2147483647i32 / 3
                      returning +715827883

PARTIAL BY CHOICE: 25 of 102 comptime_value_int call sites are routed
through it — the 21 that build computed arithmetic results plus the
literal and annotation constructions. Those are where every defect
originated. The remaining 77 construct trivially canonical values such
as comptime_value_int(ty_i32, 0), and mechanical edits at that scale in
a self-hosting compiler cost more risk than the coverage is worth.
Anyone extending this should convert the rest rather than assume it is
total.

S1 is deliberately not done, and the plan now records why. Its value was
converting silent corruption into loud errors *while the width bug was
live*, which is why it was ordered first; S2 fixed the widths, so S1 now
changes no observable behavior by its own acceptance criterion, while
touching six helpers reached by Sema, the comptime evaluator, and both
codegens. The 4c6f87e regression is the evidence: S1 could not have
caught it, because it surfaced through OP_DIV, which computes lv / rv
directly and never enters the helpers S1 modifies. S4 catches it at
construction. S4 is strictly upstream. Recommendation in the plan is to
fold S1 into #914's word-pair work on Overflow.w.

plans/comptime-int-width.md: Status rewritten to record S0/S2/S4 as done
with the sites each covered, S1 reassessed with the argument rather than
just the verdict, and three stale references cleared — "Current state"
and "Root cause" now carry a Historical banner so a top-down reader does
not think the compiler still behaves that way, the `as u64` workaround
is marked superseded, and the 64-bit ceiling is stated as still open
(2^64 + 1 folds to 1; the payload is still one i64, and widening belongs
to #914).

Verified: build green with the guard active — the compiler compiles its
own source without tripping it. 55-case range differential, suffixed
signed MIN across i8/i16/i32/i64, and the djb2 accumulator all still
match runtime.

NOT yet run on this commit: :fixpoint and the full :test suite, running
now. Both were green on ff20194. This change aborts on violation, so a
suite failure here would be the guard finding a real non-canonical
construction rather than a regression — either way it needs resolving
before this is relied on.
@ehartford
ehartford merged commit 57adebb into main Sep 5, 2026
3 of 5 checks passed
@ehartford
ehartford deleted the issue943 branch September 5, 2026 23:37
@ehartford

Copy link
Copy Markdown
Contributor

thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

comptime integer arithmetic evaluates at 32 bits — 3000000001i64 + 0i64 silently yields -1294967295

2 participants