Skip to content

fix(sema): reject subscripting zero-length bytes literal#1886

Open
ArshLabs wants to merge 1 commit intohyperledger-solang:mainfrom
ArshLabs:fix/issue-1874-empty-bytes-subscript
Open

fix(sema): reject subscripting zero-length bytes literal#1886
ArshLabs wants to merge 1 commit intohyperledger-solang:mainfrom
ArshLabs:fix/issue-1874-empty-bytes-subscript

Conversation

@ArshLabs
Copy link
Copy Markdown

Fixes #1874

Subscripting an empty bytes literal (""[0]) panics in codegen with
attempt to subtract with overflow. The array_subscript codegen path
in codegen/expression.rs computes array_length - 1 where
array_length is 0 (from Type::Bytes(0)), causing a u8 underflow.

Without overflow checks (release builds), the subtraction silently wraps
to 254, producing an incorrect shift expression instead of panicking.

This patch adds an early check in sema/expression/subscript.rs that
rejects subscripting Type::Bytes(0) with a diagnostic error before it
reaches codegen. Any index into a zero-length bytes value is guaranteed
out of bounds, so this is a compile-time error matching solc's behavior.

Reproduce:

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

Before: thread 'main' panicked at src/codegen/expression.rs:4077:60: attempt to subtract with overflow
After: error: array subscript is out of bounds

Signed-off-by: Arshdeep Singh <arshdeep.ssingh777@gmail.com>
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.

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

1 participant