Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
WIP faster ord(str[i])
  • Loading branch information
JukkaL committed Jan 13, 2026
commit 9e75d865475fbbe2c929a14f72a94f19a46dca10
16 changes: 16 additions & 0 deletions mypyc/irbuild/specialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
DictExpr,
Expression,
GeneratorExpr,
IndexExpr,
IntExpr,
ListExpr,
MemberExpr,
Expand Down Expand Up @@ -1129,6 +1130,21 @@ def translate_ord(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value
arg = constant_fold_expr(builder, expr.args[0])
if isinstance(arg, (str, bytes)) and len(arg) == 1:
return Integer(ord(arg))

# Check for ord(s[i]) pattern where s is str and i is a native integer
arg_expr = expr.args[0]
if isinstance(arg_expr, IndexExpr):
# Check if base is a string
base_type = builder.node_type(arg_expr.base)
if base_type == str_rprimitive:
# Check if the index has one argument and it's a native integer type
index_expr = arg_expr.index
index_type = builder.node_type(index_expr)
if is_int_rprimitive(index_type) or is_fixed_width_rtype(index_type):
# This is ord(s[i]) where s is str and i is a native integer
# TODO: Generate specialized code here
assert False, "ord(s[i]) specialization not yet implemented"

return None


Expand Down
9 changes: 9 additions & 0 deletions mypyc/test-data/irbuild-str.test
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,15 @@ L0:
r6 = unbox(int, r5)
return r6

[case testOrdOfStrIndex]
from mypy_extensions import i64
def ord_str_index(s: str, i: int) -> int:
return ord(s[i])
def ord_str_index_i64(s: str, i: i64) -> int:
return ord(s[i])
[typing fixtures/typing-full.pyi]
[out]

[case testStrip]
from typing import NewType, Union
NewStr = NewType("NewStr", str)
Expand Down