Skip to content

[mypyc] Give defined semantics for native int shifts - #22547

Merged
JukkaL merged 1 commit into
masterfrom
mypyc-native-int-shift
Nov 24, 2026
Merged

JukkaL merged 1 commit into
masterfrom
mypyc-native-int-shift

Conversation

@JukkaL

@JukkaL JukkaL commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

In C, a left shift that overflows a signed type (also u8 and u16, which are promoted to int) is undefined behavior. A shift by a negative count or a count that at least the bit width of the type is also undefined.

Left shifts now wrap around (two's complement), by shifting using an unsigned type and converting the result back. The shift count is treated as unsigned (similar to NumPy). A count that is negative or at least the bit width evaluates to 0, or -1 for a right shift of a negative value. A constant count within range is compiled into a plain C shift as before.

Python int objects raise ValueError on negative shift count, but I didn't want to match this since I wanted to keep the generated code for such a fundamental, low-level operation compact. Also, in my experience negative shift counts rarely cause issues, so the lack of runtime error checking likely has only very minor impact.

In C, a left shift that overflows a signed type (also u8 and u16,
which are promoted to int) is undefined behavior. A shift by a
negative count or a count that at least the bit width of the type is
also undefined.

Left shifts now wrap around (two's complement), by shifting using an
unsigned type and converting the result back. The shift count is
treated as unsigned (similar to NumPy). A count that is negative or at
least the bit width evaluates to 0, or -1 for a right shift of a
negative value. A constant count within range is compiled into a
plain C shift as before.
@JukkaL
JukkaL merged commit b3b2e1d into master Nov 24, 2026
19 checks passed
@JukkaL
JukkaL deleted the mypyc-native-int-shift branch November 24, 2026 16:15
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.

2 participants