Skip to content

Compiler panic in codegen: attempt to subtract with overflow when subscripting an empty bytes literal #1874

@jubnzv

Description

@jubnzv

The compiler panics with attempt to subtract with overflow in src/codegen/expression.rs:4077 when ""[i] (or any bytes<N> subscript with N == 0) is lowered. array_subscript matches Type::Bytes(array_length) (where array_length: u8) and computes BigInt::from_u8(array_length - 1) — for the empty literal "" / Type::Bytes(0) the 0u8 - 1 subtraction underflows.

MRE:

contract C {
    function f() public pure returns (bytes1) {
        return ""[0];
    }
}

Reproduce: save as mre.sol, build solang with overflow checks on (RUSTFLAGS='-C overflow-checks=on' cargo build --release --bin solang ...), run solang compile --target polkadot mre.sol. Without overflow checks the panic silently wraps to 254, producing an incorrect shift expression.

Output:

thread 'main' panicked at src/codegen/expression.rs:4077:60:
attempt to subtract with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Expected behavior: sema rejects subscripting a zero-length bytes literal with an out-of-bounds diagnostic (matching solc: "Out of bounds array access"), instead of reaching codegen with Type::Bytes(0).

Reproduces on all four targets (solana, polkadot, evm, soroban).

Git commit: 901bfb9
Build: release with -C overflow-checks=on
rustc 1.96.0-nightly (562dee482 2026-03-21)

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