Skip to content

Commit 29ee9c2

Browse files
[mypyc] feat: support constant folding in IRBuilder.extract_int [1/1] (#19969)
This PR adds support for constant folding inside of `IRBuilder.extract_int`
1 parent bf0a60c commit 29ee9c2

File tree

2 files changed

+7
-9
lines changed

2 files changed

+7
-9
lines changed

mypyc/irbuild/builder.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@
4040
TypeAlias,
4141
TypeInfo,
4242
TypeParam,
43-
UnaryExpr,
4443
Var,
4544
)
4645
from mypy.types import (
@@ -106,6 +105,7 @@
106105
object_rprimitive,
107106
str_rprimitive,
108107
)
108+
from mypyc.irbuild.constant_fold import constant_fold_expr
109109
from mypyc.irbuild.context import FuncInfo, ImplicitClass
110110
from mypyc.irbuild.ll_builder import LowLevelIRBuilder
111111
from mypyc.irbuild.mapper import Mapper
@@ -965,12 +965,8 @@ def maybe_spill_assignable(self, value: Value) -> Register | AssignmentTarget:
965965
return reg
966966

967967
def extract_int(self, e: Expression) -> int | None:
968-
if isinstance(e, IntExpr):
969-
return e.value
970-
elif isinstance(e, UnaryExpr) and e.op == "-" and isinstance(e.expr, IntExpr):
971-
return -e.expr.value
972-
else:
973-
return None
968+
folded = constant_fold_expr(self, e)
969+
return folded if isinstance(folded, int) else None
974970

975971
def get_sequence_type(self, expr: Expression) -> RType:
976972
return self.get_sequence_type_from_type(self.types[expr])

mypyc/irbuild/constant_fold.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from __future__ import annotations
1212

13-
from typing import Final, Union
13+
from typing import TYPE_CHECKING, Final, Union
1414

1515
from mypy.constant_fold import constant_fold_binary_op, constant_fold_unary_op
1616
from mypy.nodes import (
@@ -26,9 +26,11 @@
2626
UnaryExpr,
2727
Var,
2828
)
29-
from mypyc.irbuild.builder import IRBuilder
3029
from mypyc.irbuild.util import bytes_from_str
3130

31+
if TYPE_CHECKING:
32+
from mypyc.irbuild.builder import IRBuilder
33+
3234
# All possible result types of constant folding
3335
ConstantValue = Union[int, float, complex, str, bytes]
3436
CONST_TYPES: Final = (int, float, complex, str, bytes)

0 commit comments

Comments
 (0)