Repository navigation
[mypyc] Give defined semantics for native int shifts - #22547
Merged
Merged
Conversation
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.
p-sawicki
approved these changes
Nov 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.