Skip to content

vec.len() - 1 panics 'integer overflow' on empty Vec (unsigned underflow) #630

Closed

Description

@ehartford

Summary

some_vec.len() - 1 when the Vec is empty panics with 'integer overflow' — len() is unsigned and 0-1 underflows rather than giving -1 or a clean diagnostic. Hit in a countdown loop; restructured to var i = len; while i > 0: i = i - 1.

Spec §4 numeric / §20b

Either len() should return a signed type in arithmetic context, or len()-1 in a loop-bound idiom needs to not trap — at minimum the overflow message should name the real cause. Found 2026-07-03 during #623 work.

Activity

  1. ehartford commented on Jul 16, 2026

    @ehartford
    ContributorAuthor

    The minimum ask is delivered in f0c627c: overflow panics now name the real cause. The repro's panic reads:

    panic: integer overflow: u64 subtraction wrapped below zero
    

    (and generally: i32 addition out of range, i32 minimum divided by -1, negating i32 minimum value — all checked-arithmetic panic sites in CodegenDispatch now include type, operation, and wrap direction. behav_unsigned_underflow_panic_message.w pins the unsigned-sub message. Full battery green.)

    The remaining question in this issue — should len() be signed — is a spec-level design fork, so I did not act on it. The fact base:

    Spec status: §18.6 is explicit and deliberate: "All collection types provide .len() returning usize, plus convenience narrowing methods (.len32(), .len64(), .ulen32()) that panic on overflow." The whole narrowing family was built end-to-end in 28d6343. Flipping len() to signed reverses explicit spec text → needs a BDFL ruling, not a bug fix.

    Inconsistency evidence (either way, something needs fixing): lib/std/collections.w declares BTreeMap.len() -> i64 and BTreeSet.len() -> i64 — violating §18.6 as written. Sema's builtin path (collection_len_method_return_type) returns usize for Vec/str/slice. So today's surface is mixed: builtin collections trap on len()-1, BTree collections don't.

    Reference survey:

    • Signed: Go (len() -> int — chosen deliberately to kill this exact underflow-trap class), Swift (count: Int — API guidelines say use Int even for known-non-negative values), Vale (func len(...) int throughout — our ownership-model reference)
    • Unsigned: Rust (usize — the 0..v.len()-1 panic is a famous, clippy-linted wart), Zig (usize, with @intCast ceremony accepted as philosophy)

    Mission lens (docs/mission.md): app devs are the 100% optimization target; v.len() - 1 and countdown loops are app-dev bread and butter. The languages that chose signed lengths did it for exactly With's stated reason — remove the suffering. The languages that chose unsigned accept ceremony With rejects. On the other side: usize is the C-interop/indexing-width-honest choice, and §18.6 already gives len64() as the signed escape hatch.

    If the ruling is keep usize (spec as written): the two BTree decls should be fixed to usize for conformance, and this issue can close on the panic-message fix. If the ruling is go signed (Go/Swift/Vale side): that's a spec amendment + a coordinated builtin/type change worth its own decisions.md entry — happy to run it either way.

  2. ehartford commented on Jul 17, 2026

    @ehartford
    ContributorAuthor

    Ruling: len() is signed — canonized as D11 (BDFL, 2026-07-17)

    .len() on every collection returns Int (i64), never usize, and is never wrapped in Option. Full reasoning in decisions.md D11; §18.6 amended (ad6912c). The panic-message fix (f0c627c) handled the symptom; this ruling removes the trap.

    Why signed (the filter): references split along stated values — Go/Swift/Vale signed, Rust/Zig unsigned-with-the-trap; With is ergonomics-first (mission: "remove the suffering", and v.len()-1 is a named suffering). Why no Option: a held container always has a length; ownership + init rules make a null/uninitialized container unrepresentable in safe code, so an Option wrapper would force .unwrap() at every call site for a case the compiler already proved impossible. C's -1/size_t conventions live at the modeled-C binding layer (the with_net -errno precedent), never in core types.

    This issue is now the implementation vehicle (spec-ahead; not yet coded)

    §18.6 says Int; the compiler still returns usize. Spec leads — do not revert §18.6. The flip:

    • SemaCheck.collection_len_method_return_type → i64; the iterator count → i64 and position → Option[i64]; StringBuilder capacity → i64. size/align stay usize (layout constants, FFI — deliberately excluded).
    • lib/std BTreeMap/BTreeSet len() -> i64 become conformant (were a §18.6 violation).
    • Parser: inner if-chain ending in 'else if' swallows the outer chain's next else at the same column #629 self-host flip sweep — length typing threads through the compiler's own sources; instrument both decisions, diff the tree, reseed so the pre-fix seed doesn't miscompile the fixed shape.
    • Fixtures: v.len() - 1 == -1 on empty, countdown idiom, BTree/builtin agreement; rework behav_unsigned_underflow_panic_message.w to a pure-u64 repro (it currently traps via len()-1, which stops trapping).
    • Full battery.
  3. ehartford commented on Jul 19, 2026

    @ehartford
    ContributorAuthor

    D11 IMPLEMENTED (a80c38c, full battery GATES EXIT: 0 — fixpoint byte-identical, audit violations=0, all 9 targets / 1,878 files green; reseeded ga80c38c0c on both seed paths + release asset).

    len() now returns Int (i64) on every collection — never usize, never Option — per the canonized ruling (spec §18.6, decisions.md D11). The full consistent surface landed with it: iterator count → i64, position → Option[i64], StringBuilder capacity → i64. size/align layout methods deliberately stay usize (FFI constants, the excluded category).

    Notable: the compiler's own sources and all of lib/std needed zero changes — the surface was dual-compatible under both seeds (field-form .len was already i64; method uses go through as casts), so the #629 self-host flip protocol completed with just the immediate reseed and no source sweep.

    Fixtures: behav_len_signed.w pins v.len() - 1 == -1 on empty, the cast-free countdown idiom, no-cast get(len()-1) indexing, and BTree/builtin agreement; behav_unsigned_underflow_panic_message.w re-pins the overflow message via a pure u64 underflow (the len-based repro no longer traps — that's the point of D11); spec 18.6 + two §10.3 combinator tests updated to the Int surface.

    Live on the daily driver: with -e 'let v: Vec[i32] = Vec.new()\nprint_i64(v.len() - 1)' → -1.

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

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