Skip to content

Sema: arithmetic of unsuffixed literals is typed from the literal defaults, not the destination (spec 4.2.1 rule 1); let x: u8 = 1 + 2 is rejected, and the LLVM constant folder substitutes the context #1820

Closed

Description

@ehartford

Spec: types.md §4.2.1 "Contextual numeric inference": unsuffixed numeric literals are resolved from surrounding type context before the defaults (i32 / f64); rule 1 is "the target type of a typed binding or assignment" (var acc: u64 = 0).

check_binary (src/SemaCheck.w) checks two literal operands with check_expr_value_context, so the destination type never reaches them: 1 + 2 is i32, 9223372036854775807 * 2 is i64. Verified on with v0.15.2.1-g99939352f:

program verdict
let x: u8 = 1 + 2 (local) error: implicit integer narrowing or sign change
let x: u8 = 3 (local) ok
top-level let U: u64 = (9223372036854775807 * 2 + 1) 18446744073709551615, only because the LLVM constant folder (CodegenTraits.try_eval_const_result_type) folds literal arithmetic at the binding's type; a runtime evaluation of the same MIR multiplies in i64 and panics

The global case matters beyond synthetic code: c_import renders limits.h's ULONG_LONG_MAX (__LONG_LONG_MAX__*2ULL+1ULL) with the ULL suffixes dropped, as 9223372036854775807 * 2 + 1 into c_ulonglong, and every program that c_imports a header reaching limits.h (the libcurl facade tests) depends on the folder's substitution.

Fixing #1773 made Sema record an arithmetic node's type so the folder stops re-deriving it from context (D65). That had to exclude literal-only arithmetic (expr_is_untyped_literal_arith), or ULONG_LONG_MAX became a startup i64 overflow: the fold for literal-only arithmetic still reads the destination's type, a downstream derivation of a fact Sema should own.

Recommended ruling (for Eric): rule 1 reaches through arithmetic operators whose operands are all unsuffixed literals (Go's untyped constants, Rust's inference, Zig's comptime_int all accept u8 = 1 + 2): Sema checks such operands with the expected numeric type, records the result, and the folder's context fallback is deleted. That also makes pcre2's migrated coptable: [173]u8 = [..., (1 + 2), ...] legal once #1803 closes the narrowing gap. Separately, c_import should keep a C integer suffix (2ULL → 2u64/c_ulonglong) so the translation does not depend on context at all.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions