Repository navigation
[mypyc] Allow abs() on native int types - #22367
Conversation
This comment has been minimized.
This comment has been minimized.
JukkaL
left a comment
There was a problem hiding this comment.
This makes abs() work, but it's very slow with native integers since it uses the generic slow path. Since native integers are entirely performance focused, we should instead add a new primitive that gets lowered to efficient IR in the lowering pass instead, so that this would be fast, as is reasonable to expect.
|
Ah rebasing on top of #22363 would fix much of the performance issue. This will also need support for the recently added |
The u16, u32, u64 and i8 stub classes (added in python#22368, python#22373, python#22384 and python#22447) also lack __abs__.
|
Rebased, and added One side effect of converting back is that |
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
|
Probably the best way to do this is to to generate lowered IR for native integer |
JukkaL
left a comment
There was a problem hiding this comment.
This improves things significantly, so we can merge this, and my comment suggests a follow-up improvement if you are interested in.
Follow-up to #22367, as suggested in #22367 (comment). This generates lowered IR for native integer `abs()` with a generic primitive op, `int_abs`, that gets lowered via `@lower_primitive_op` in `mypyc/lower/int_ops.py` (kind of like `vec_get_item_unsafe_op`). Before, mypyc converted the value to a tagged int, called `CPyTagged_Absolute` and converted the result back. `abs()` of the minimum value of a signed type, such as `abs(i8(-128))`, now overflows like `-x` instead of raising `ValueError`. `mypyc/doc/int_operations.rst` says operations between native integer types don't check for overflow, and there's no run test for `-x` overflow either, so I didn't add one for `abs()`. The new lowering tests fail on master.
Follow-up to #22363.
abs()on a native int type failed to type check (Argument 1 to "abs" has incompatible type "i64"), because the native int classes in mypy's ownmypy_extensionsstubs define__neg__,__pos__and__invert__but not__abs__. This adds it for all eight types (i8,i16,i32,i64,u8,u16,u32,u64) to the bundled stubs and to the test stubs. The new asserts in therun-*.testfiles fail to type check on master.mypyc compiles the call with the
abs(int)primitive from #22363: the value is converted to a tagged int, passed toCPyTagged_Absolute, and converted back. Onlyi64andu64values that don't fit in a short tagged int fall back toPyNumber_Absolute.