| 1 |
"""Helpers for generating for loops and comprehensions. |
| 2 |
|
| 3 |
We special case certain kinds for loops such as "for x in range(...)" |
| 4 |
for better efficiency. Each for loop generator class below deals one |
| 5 |
such special case. |
| 6 |
""" |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
from collections.abc import Callable |
| 11 |
from typing import ClassVar, cast |
| 12 |
|
| 13 |
from mypy.nodes import ( |
| 14 |
ARG_POS, |
| 15 |
CallExpr, |
| 16 |
DictionaryComprehension, |
| 17 |
Expression, |
| 18 |
GeneratorExpr, |
| 19 |
ListExpr, |
| 20 |
Lvalue, |
| 21 |
MemberExpr, |
| 22 |
NameExpr, |
| 23 |
RefExpr, |
| 24 |
SetExpr, |
| 25 |
StarExpr, |
| 26 |
TupleExpr, |
| 27 |
TypeAlias, |
| 28 |
Var, |
| 29 |
) |
| 30 |
from mypy.types import LiteralType, TupleType, get_proper_type, get_proper_types |
| 31 |
from mypyc.common import IS_FREE_THREADED |
| 32 |
from mypyc.ir.ops import ( |
| 33 |
ERR_NEVER, |
| 34 |
BasicBlock, |
| 35 |
Branch, |
| 36 |
Integer, |
| 37 |
IntOp, |
| 38 |
LoadAddress, |
| 39 |
LoadErrorValue, |
| 40 |
LoadGlobal, |
| 41 |
LoadLiteral, |
| 42 |
MethodCall, |
| 43 |
RaiseStandardError, |
| 44 |
Register, |
| 45 |
TupleGet, |
| 46 |
TupleSet, |
| 47 |
Value, |
| 48 |
) |
| 49 |
from mypyc.ir.rtypes import ( |
| 50 |
RInstance, |
| 51 |
RTuple, |
| 52 |
RType, |
| 53 |
RVec, |
| 54 |
bool_rprimitive, |
| 55 |
c_pyssize_t_rprimitive, |
| 56 |
int_rprimitive, |
| 57 |
is_dict_rprimitive, |
| 58 |
is_fixed_width_rtype, |
| 59 |
is_immutable_rprimitive, |
| 60 |
is_list_rprimitive, |
| 61 |
is_sequence_rprimitive, |
| 62 |
is_short_int_rprimitive, |
| 63 |
is_str_rprimitive, |
| 64 |
is_tuple_rprimitive, |
| 65 |
object_pointer_rprimitive, |
| 66 |
object_rprimitive, |
| 67 |
short_int_rprimitive, |
| 68 |
) |
| 69 |
from mypyc.irbuild.builder import IRBuilder |
| 70 |
from mypyc.irbuild.constant_fold import constant_fold_expr |
| 71 |
from mypyc.irbuild.prepare import GENERATOR_HELPER_NAME |
| 72 |
from mypyc.irbuild.targets import AssignmentTarget, AssignmentTargetTuple |
| 73 |
from mypyc.irbuild.vec import vec_append, vec_create, vec_get_item_unsafe, vec_init_item_unsafe |
| 74 |
from mypyc.primitives.dict_ops import ( |
| 75 |
dict_check_size_op, |
| 76 |
dict_item_iter_op, |
| 77 |
dict_key_iter_op, |
| 78 |
dict_next_item_op, |
| 79 |
dict_next_key_op, |
| 80 |
dict_next_value_op, |
| 81 |
dict_value_iter_op, |
| 82 |
) |
| 83 |
from mypyc.primitives.exc_ops import no_err_occurred_op, propagate_if_error_op |
| 84 |
from mypyc.primitives.generic_ops import aiter_op, anext_op, iter_op, next_op |
| 85 |
from mypyc.primitives.list_ops import ( |
| 86 |
list_append_op, |
| 87 |
list_get_item_int64_op, |
| 88 |
list_get_item_unsafe_op, |
| 89 |
new_list_set_item_op, |
| 90 |
) |
| 91 |
from mypyc.primitives.misc_ops import stop_async_iteration_op |
| 92 |
from mypyc.primitives.registry import CFunctionDescription |
| 93 |
from mypyc.primitives.set_ops import set_add_op |
| 94 |
from mypyc.primitives.str_ops import str_get_item_unsafe_op |
| 95 |
from mypyc.primitives.tuple_ops import tuple_get_item_unsafe_op |
| 96 |
|
| 97 |
GenFunc = Callable[[], None] |
| 98 |
|
| 99 |
|
| 100 |
def for_loop_helper( |
| 101 |
builder: IRBuilder, |
| 102 |
index: Lvalue, |
| 103 |
expr: Expression, |
| 104 |
body_insts: GenFunc, |
| 105 |
else_insts: GenFunc | None, |
| 106 |
is_async: bool, |
| 107 |
line: int, |
| 108 |
) -> None: |
| 109 |
"""Generate IR for a loop. |
| 110 |
|
| 111 |
Args: |
| 112 |
index: the loop index Lvalue |
| 113 |
expr: the expression to iterate over |
| 114 |
body_insts: a function that generates the body of the loop |
| 115 |
else_insts: a function that generates the else block instructions |
| 116 |
""" |
| 117 |
# Body of the loop |
| 118 |
body_block = BasicBlock() |
| 119 |
# Block that steps to the next item |
| 120 |
step_block = BasicBlock() |
| 121 |
# Block for the else clause, if we need it |
| 122 |
else_block = BasicBlock() |
| 123 |
# Block executed after the loop |
| 124 |
exit_block = BasicBlock() |
| 125 |
|
| 126 |
# Determine where we want to exit, if our condition check fails. |
| 127 |
normal_loop_exit = else_block if else_insts is not None else exit_block |
| 128 |
|
| 129 |
for_gen = make_for_loop_generator( |
| 130 |
builder, index, expr, body_block, normal_loop_exit, line, is_async=is_async |
| 131 |
) |
| 132 |
|
| 133 |
builder.push_loop_stack(step_block, exit_block) |
| 134 |
condition_block = BasicBlock() |
| 135 |
builder.goto_and_activate(condition_block) |
| 136 |
|
| 137 |
# Add loop condition check. |
| 138 |
for_gen.gen_condition() |
| 139 |
|
| 140 |
# Generate loop body. |
| 141 |
builder.activate_block(body_block) |
| 142 |
for_gen.begin_body() |
| 143 |
body_insts() |
| 144 |
|
| 145 |
# We generate a separate step block (which might be empty). |
| 146 |
builder.goto_and_activate(step_block) |
| 147 |
for_gen.gen_step() |
| 148 |
# Go back to loop condition. |
| 149 |
builder.goto(condition_block) |
| 150 |
|
| 151 |
for_gen.add_cleanup(normal_loop_exit) |
| 152 |
builder.pop_loop_stack() |
| 153 |
|
| 154 |
if else_insts is not None: |
| 155 |
builder.activate_block(else_block) |
| 156 |
else_insts() |
| 157 |
builder.goto(exit_block) |
| 158 |
|
| 159 |
builder.activate_block(exit_block) |
| 160 |
|
| 161 |
|
| 162 |
def for_loop_helper_with_index( |
| 163 |
builder: IRBuilder, |
| 164 |
index: Lvalue, |
| 165 |
expr: Expression, |
| 166 |
expr_reg: Value, |
| 167 |
body_insts: Callable[[Value], None], |
| 168 |
line: int, |
| 169 |
length: Value, |
| 170 |
) -> None: |
| 171 |
"""Generate IR for a sequence iteration. |
| 172 |
|
| 173 |
This function only works for sequence type. Compared to for_loop_helper, |
| 174 |
it would feed iteration index to body_insts. |
| 175 |
|
| 176 |
Args: |
| 177 |
index: the loop index Lvalue |
| 178 |
expr: the expression to iterate over |
| 179 |
body_insts: a function that generates the body of the loop. |
| 180 |
It needs a index as parameter. |
| 181 |
""" |
| 182 |
assert is_sequence_rprimitive(expr_reg.type) or isinstance(expr_reg.type, RVec), ( |
| 183 |
expr_reg, |
| 184 |
expr_reg.type, |
| 185 |
) |
| 186 |
target_type = builder.get_sequence_type(expr) |
| 187 |
|
| 188 |
body_block = BasicBlock() |
| 189 |
step_block = BasicBlock() |
| 190 |
exit_block = BasicBlock() |
| 191 |
condition_block = BasicBlock() |
| 192 |
|
| 193 |
for_gen = ForSequence(builder, index, body_block, exit_block, line, False) |
| 194 |
for_gen.init(expr_reg, target_type, reverse=False, length=length) |
| 195 |
|
| 196 |
builder.push_loop_stack(step_block, exit_block) |
| 197 |
|
| 198 |
if isinstance(length, Integer) and length.value > 0: |
| 199 |
builder.goto(body_block) |
| 200 |
builder.activate_block(condition_block) |
| 201 |
else: |
| 202 |
builder.goto_and_activate(condition_block) |
| 203 |
|
| 204 |
for_gen.gen_condition() |
| 205 |
|
| 206 |
builder.activate_block(body_block) |
| 207 |
for_gen.begin_body() |
| 208 |
body_insts(builder.read(for_gen.index_target, line)) |
| 209 |
|
| 210 |
builder.goto_and_activate(step_block) |
| 211 |
for_gen.gen_step() |
| 212 |
builder.goto(condition_block) |
| 213 |
|
| 214 |
for_gen.add_cleanup(exit_block) |
| 215 |
builder.pop_loop_stack() |
| 216 |
|
| 217 |
builder.activate_block(exit_block) |
| 218 |
|
| 219 |
|
| 220 |
def sequence_from_generator_preallocate_helper( |
| 221 |
builder: IRBuilder, |
| 222 |
gen: GeneratorExpr, |
| 223 |
empty_op_llbuilder: Callable[[Value, int], Value], |
| 224 |
set_item_op: Callable[[Value, Value, Value, int], None], |
| 225 |
) -> Value | None: |
| 226 |
"""Generate a new tuple or list from a simple generator expression. |
| 227 |
|
| 228 |
Currently we only optimize for simplest generator expression, which means that |
| 229 |
there is no condition list in the generator and only one original sequence with |
| 230 |
one index is allowed. |
| 231 |
|
| 232 |
e.g. (1) tuple(f(x) for x in a_list/a_tuple/a_str/a_bytes/an_rtuple) |
| 233 |
(2) list(f(x) for x in a_list/a_tuple/a_str/a_bytes/an_rtuple) |
| 234 |
(3) [f(x) for x in a_list/a_tuple/a_str/a_bytes/an_rtuple] |
| 235 |
|
| 236 |
Args: |
| 237 |
empty_op_llbuilder: A function that can generate an empty sequence op when |
| 238 |
passed in length. See `new_list_op_with_length` and `new_tuple_op_with_length` |
| 239 |
for detailed implementation. |
| 240 |
set_item_op: A primitive that can modify an arbitrary position of a sequence. |
| 241 |
The op should have three arguments: |
| 242 |
- Self |
| 243 |
- Target position |
| 244 |
- New Value |
| 245 |
See `new_list_set_item_op` and `new_tuple_set_item_op` for detailed |
| 246 |
implementation. |
| 247 |
""" |
| 248 |
if len(gen.sequences) == 1 and len(gen.indices) == 1 and len(gen.condlists[0]) == 0: |
| 249 |
line = gen.line |
| 250 |
sequence_expr = gen.sequences[0] |
| 251 |
rtype = builder.node_type(sequence_expr) |
| 252 |
if not (is_sequence_rprimitive(rtype) or isinstance(rtype, (RTuple, RVec))): |
| 253 |
return None |
| 254 |
|
| 255 |
if isinstance(rtype, RTuple): |
| 256 |
# If input is RTuple, box it to tuple_rprimitive for generic iteration |
| 257 |
# TODO: this can be optimized a bit better with an unrolled ForRTuple helper |
| 258 |
proper_type = get_proper_type(builder.types[sequence_expr]) |
| 259 |
assert isinstance(proper_type, TupleType), proper_type |
| 260 |
|
| 261 |
# the for_loop_helper_with_index crashes for empty tuples, bail out |
| 262 |
if not proper_type.items: |
| 263 |
return None |
| 264 |
|
| 265 |
proper_types = get_proper_types(proper_type.items) |
| 266 |
|
| 267 |
get_item_ops: list[LoadLiteral | TupleGet] |
| 268 |
if all(isinstance(typ, LiteralType) for typ in proper_types): |
| 269 |
get_item_ops = [ |
| 270 |
LoadLiteral(cast(LiteralType, typ).value, object_rprimitive) |
| 271 |
for typ in proper_types |
| 272 |
] |
| 273 |
|
| 274 |
else: |
| 275 |
sequence = builder.accept(sequence_expr) |
| 276 |
get_item_ops = [ |
| 277 |
( |
| 278 |
LoadLiteral(typ.value, object_rprimitive) |
| 279 |
if isinstance(typ, LiteralType) |
| 280 |
else TupleGet(sequence, i, line) |
| 281 |
) |
| 282 |
for i, typ in enumerate(proper_types) |
| 283 |
] |
| 284 |
|
| 285 |
items = list(map(builder.add, get_item_ops)) |
| 286 |
sequence = builder.new_tuple(items, line) |
| 287 |
|
| 288 |
else: |
| 289 |
sequence = builder.accept(sequence_expr) |
| 290 |
|
| 291 |
length = get_expr_length_value(builder, sequence_expr, sequence, line, use_pyssize_t=True) |
| 292 |
|
| 293 |
target_op = empty_op_llbuilder(length, line) |
| 294 |
|
| 295 |
def set_item(item_index: Value) -> None: |
| 296 |
with builder.enter_borrow_scope(line): |
| 297 |
e = builder.accept(gen.left_expr) |
| 298 |
set_item_op(target_op, item_index, e, line) |
| 299 |
|
| 300 |
for_loop_helper_with_index( |
| 301 |
builder, gen.indices[0], sequence_expr, sequence, set_item, line, length |
| 302 |
) |
| 303 |
|
| 304 |
return target_op |
| 305 |
return None |
| 306 |
|
| 307 |
|
| 308 |
def translate_list_comprehension(builder: IRBuilder, gen: GeneratorExpr) -> Value: |
| 309 |
if raise_error_if_contains_unreachable_names(builder, gen): |
| 310 |
return builder.none() |
| 311 |
|
| 312 |
def set_item(x: Value, y: Value, z: Value, line: int) -> None: |
| 313 |
builder.call_c(new_list_set_item_op, [x, y, z], line) |
| 314 |
|
| 315 |
# Try simplest list comprehension, otherwise fall back to general one |
| 316 |
val = sequence_from_generator_preallocate_helper( |
| 317 |
builder, |
| 318 |
gen, |
| 319 |
empty_op_llbuilder=builder.builder.new_list_op_with_length, |
| 320 |
set_item_op=set_item, |
| 321 |
) |
| 322 |
if val is not None: |
| 323 |
return val |
| 324 |
|
| 325 |
list_ops = builder.maybe_spill(builder.new_list_op([], gen.line)) |
| 326 |
|
| 327 |
loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async)) |
| 328 |
|
| 329 |
def gen_inner_stmts() -> None: |
| 330 |
e = builder.accept(gen.left_expr) |
| 331 |
builder.primitive_op(list_append_op, [builder.read(list_ops, gen.line), e], gen.line) |
| 332 |
|
| 333 |
comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line) |
| 334 |
return builder.read(list_ops, gen.line) |
| 335 |
|
| 336 |
|
| 337 |
def raise_error_if_contains_unreachable_names( |
| 338 |
builder: IRBuilder, gen: GeneratorExpr | DictionaryComprehension |
| 339 |
) -> bool: |
| 340 |
"""Raise a runtime error and return True if generator contains unreachable names. |
| 341 |
|
| 342 |
False is returned if the generator can be safely transformed without crashing. |
| 343 |
(It may still be unreachable!) |
| 344 |
""" |
| 345 |
if any(isinstance(s, NameExpr) and s.node is None for s in gen.indices): |
| 346 |
error = RaiseStandardError( |
| 347 |
RaiseStandardError.RUNTIME_ERROR, |
| 348 |
"mypyc internal error: should be unreachable", |
| 349 |
gen.line, |
| 350 |
) |
| 351 |
builder.add(error) |
| 352 |
return True |
| 353 |
|
| 354 |
return False |
| 355 |
|
| 356 |
|
| 357 |
def translate_set_comprehension(builder: IRBuilder, gen: GeneratorExpr) -> Value: |
| 358 |
if raise_error_if_contains_unreachable_names(builder, gen): |
| 359 |
return builder.none() |
| 360 |
|
| 361 |
set_ops = builder.maybe_spill(builder.new_set_op([], gen.line)) |
| 362 |
loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async)) |
| 363 |
|
| 364 |
def gen_inner_stmts() -> None: |
| 365 |
e = builder.accept(gen.left_expr) |
| 366 |
builder.primitive_op(set_add_op, [builder.read(set_ops, gen.line), e], gen.line) |
| 367 |
|
| 368 |
comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line) |
| 369 |
return builder.read(set_ops, gen.line) |
| 370 |
|
| 371 |
|
| 372 |
def translate_vec_comprehension( |
| 373 |
builder: IRBuilder, vec_type: RVec, gen: GeneratorExpr, *, capacity: Value | None = None |
| 374 |
) -> Value: |
| 375 |
def set_item(x: Value, y: Value, z: Value, line: int) -> None: |
| 376 |
vec_init_item_unsafe(builder.builder, x, y, z, line) |
| 377 |
|
| 378 |
# Try simplest comprehension, otherwise fall back to general one |
| 379 |
val = sequence_from_generator_preallocate_helper( |
| 380 |
builder, |
| 381 |
gen, |
| 382 |
empty_op_llbuilder=lambda length, line: vec_create( |
| 383 |
builder.builder, vec_type, length, line, capacity=capacity |
| 384 |
), |
| 385 |
set_item_op=set_item, |
| 386 |
) |
| 387 |
if val is not None: |
| 388 |
return val |
| 389 |
|
| 390 |
vec = Register(vec_type) |
| 391 |
builder.assign( |
| 392 |
vec, vec_create(builder.builder, vec_type, 0, gen.line, capacity=capacity), gen.line |
| 393 |
) |
| 394 |
loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async)) |
| 395 |
|
| 396 |
def gen_inner_stmts() -> None: |
| 397 |
e = builder.accept(gen.left_expr) |
| 398 |
builder.assign(vec, vec_append(builder.builder, vec, e, gen.line), gen.line) |
| 399 |
|
| 400 |
comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line) |
| 401 |
return vec |
| 402 |
|
| 403 |
|
| 404 |
def comprehension_helper( |
| 405 |
builder: IRBuilder, |
| 406 |
loop_params: list[tuple[Lvalue, Expression, list[Expression], bool]], |
| 407 |
gen_inner_stmts: Callable[[], None], |
| 408 |
line: int, |
| 409 |
) -> None: |
| 410 |
"""Helper function for list comprehensions. |
| 411 |
|
| 412 |
Args: |
| 413 |
loop_params: a list of (index, expr, [conditions]) tuples defining nested loops: |
| 414 |
- "index" is the Lvalue indexing that loop; |
| 415 |
- "expr" is the expression for the object to be iterated over; |
| 416 |
- "conditions" is a list of conditions, evaluated in order with short-circuiting, |
| 417 |
that must all be true for the loop body to be executed |
| 418 |
gen_inner_stmts: function to generate the IR for the body of the innermost loop |
| 419 |
""" |
| 420 |
|
| 421 |
def handle_loop(loop_params: list[tuple[Lvalue, Expression, list[Expression], bool]]) -> None: |
| 422 |
"""Generate IR for a loop. |
| 423 |
|
| 424 |
Given a list of (index, expression, [conditions]) tuples, generate IR |
| 425 |
for the nested loops the list defines. |
| 426 |
""" |
| 427 |
index, expr, conds, is_async = loop_params[0] |
| 428 |
for_loop_helper( |
| 429 |
builder, |
| 430 |
index, |
| 431 |
expr, |
| 432 |
lambda: loop_contents(conds, loop_params[1:]), |
| 433 |
None, |
| 434 |
is_async=is_async, |
| 435 |
line=line, |
| 436 |
) |
| 437 |
|
| 438 |
def loop_contents( |
| 439 |
conds: list[Expression], |
| 440 |
remaining_loop_params: list[tuple[Lvalue, Expression, list[Expression], bool]], |
| 441 |
) -> None: |
| 442 |
"""Generate the body of the loop. |
| 443 |
|
| 444 |
Args: |
| 445 |
conds: a list of conditions to be evaluated (in order, with short circuiting) |
| 446 |
to gate the body of the loop |
| 447 |
remaining_loop_params: the parameters for any further nested loops; if it's empty |
| 448 |
we'll instead evaluate the "gen_inner_stmts" function |
| 449 |
""" |
| 450 |
# Check conditions, in order, short-circuiting them. |
| 451 |
for cond in conds: |
| 452 |
with builder.enter_borrow_scope(line): |
| 453 |
cond_val = builder.accept(cond) |
| 454 |
cont_block, rest_block = BasicBlock(), BasicBlock() |
| 455 |
# If the condition is true we'll skip the continue. |
| 456 |
builder.add_bool_branch(cond_val, rest_block, cont_block) |
| 457 |
builder.activate_block(cont_block) |
| 458 |
builder.nonlocal_control[-1].gen_continue(builder, cond.line) |
| 459 |
builder.goto_and_activate(rest_block) |
| 460 |
|
| 461 |
if remaining_loop_params: |
| 462 |
# There's another nested level, so the body of this loop is another loop. |
| 463 |
return handle_loop(remaining_loop_params) |
| 464 |
else: |
| 465 |
# We finally reached the actual body of the generator. |
| 466 |
# Generate the IR for the inner loop body. |
| 467 |
with builder.enter_borrow_scope(line): |
| 468 |
gen_inner_stmts() |
| 469 |
|
| 470 |
handle_loop(loop_params) |
| 471 |
|
| 472 |
|
| 473 |
def is_range_ref(expr: RefExpr) -> bool: |
| 474 |
return ( |
| 475 |
expr.fullname == "builtins.range" |
| 476 |
or isinstance(expr.node, TypeAlias) |
| 477 |
and expr.fullname == "six.moves.xrange" |
| 478 |
) |
| 479 |
|
| 480 |
|
| 481 |
def make_for_loop_generator( |
| 482 |
builder: IRBuilder, |
| 483 |
index: Lvalue, |
| 484 |
expr: Expression, |
| 485 |
body_block: BasicBlock, |
| 486 |
loop_exit: BasicBlock, |
| 487 |
line: int, |
| 488 |
is_async: bool = False, |
| 489 |
nested: bool = False, |
| 490 |
) -> ForGenerator: |
| 491 |
"""Return helper object for generating a for loop over an iterable. |
| 492 |
|
| 493 |
If "nested" is True, this is a nested iterator such as "e" in "enumerate(e)". |
| 494 |
""" |
| 495 |
|
| 496 |
# Do an async loop if needed. async is always generic |
| 497 |
if is_async: |
| 498 |
expr_reg = builder.accept(expr) |
| 499 |
async_obj = ForAsyncIterable(builder, index, body_block, loop_exit, line, nested) |
| 500 |
item_type = builder._analyze_iterable_item_type(expr) |
| 501 |
item_rtype = builder.type_to_rtype(item_type) |
| 502 |
async_obj.init(expr_reg, item_rtype) |
| 503 |
return async_obj |
| 504 |
|
| 505 |
rtyp = builder.node_type(expr) |
| 506 |
if is_sequence_rprimitive(rtyp) or isinstance(rtyp, RVec): |
| 507 |
# Special case "for x in <seq>" for concrete sequence types. |
| 508 |
expr_reg = builder.accept(expr) |
| 509 |
target_type = builder.get_sequence_type(expr) |
| 510 |
|
| 511 |
for_list = ForSequence(builder, index, body_block, loop_exit, line, nested) |
| 512 |
for_list.init(expr_reg, target_type, reverse=False) |
| 513 |
return for_list |
| 514 |
|
| 515 |
if is_dict_rprimitive(rtyp): |
| 516 |
# Special case "for k in <dict>". |
| 517 |
expr_reg = builder.accept(expr) |
| 518 |
target_type = builder.get_dict_key_type(expr) |
| 519 |
|
| 520 |
for_dict = ForDictionaryKeys(builder, index, body_block, loop_exit, line, nested) |
| 521 |
for_dict.init(expr_reg, target_type) |
| 522 |
return for_dict |
| 523 |
|
| 524 |
if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr): |
| 525 |
if ( |
| 526 |
is_range_ref(expr.callee) |
| 527 |
and ( |
| 528 |
len(expr.args) <= 2 |
| 529 |
or (len(expr.args) == 3 and builder.extract_int(expr.args[2]) is not None) |
| 530 |
) |
| 531 |
and set(expr.arg_kinds) == {ARG_POS} |
| 532 |
): |
| 533 |
# Special case "for x in range(...)". |
| 534 |
# We support the 3 arg form but only for int literals, since it doesn't |
| 535 |
# seem worth the hassle of supporting dynamically determining which |
| 536 |
# direction of comparison to do. |
| 537 |
if len(expr.args) == 1: |
| 538 |
start_reg: Value = Integer(0) |
| 539 |
end_reg = builder.accept(expr.args[0]) |
| 540 |
else: |
| 541 |
start_reg = builder.accept(expr.args[0]) |
| 542 |
end_reg = builder.accept(expr.args[1]) |
| 543 |
if len(expr.args) == 3: |
| 544 |
step = builder.extract_int(expr.args[2]) |
| 545 |
assert step is not None |
| 546 |
if step == 0: |
| 547 |
builder.error("range() step can't be zero", expr.args[2].line) |
| 548 |
else: |
| 549 |
step = 1 |
| 550 |
|
| 551 |
for_range = ForRange(builder, index, body_block, loop_exit, line, nested) |
| 552 |
for_range.init(start_reg, end_reg, step) |
| 553 |
return for_range |
| 554 |
|
| 555 |
elif ( |
| 556 |
expr.callee.fullname == "builtins.enumerate" |
| 557 |
and len(expr.args) == 1 |
| 558 |
and expr.arg_kinds == [ARG_POS] |
| 559 |
and isinstance(index, TupleExpr) |
| 560 |
and len(index.items) == 2 |
| 561 |
): |
| 562 |
# Special case "for i, x in enumerate(y)". |
| 563 |
lvalue1 = index.items[0] |
| 564 |
lvalue2 = index.items[1] |
| 565 |
for_enumerate = ForEnumerate(builder, index, body_block, loop_exit, line, nested) |
| 566 |
for_enumerate.init(lvalue1, lvalue2, expr.args[0]) |
| 567 |
return for_enumerate |
| 568 |
|
| 569 |
elif ( |
| 570 |
expr.callee.fullname == "builtins.zip" |
| 571 |
and len(expr.args) >= 2 |
| 572 |
and set(expr.arg_kinds) == {ARG_POS} |
| 573 |
and isinstance(index, TupleExpr) |
| 574 |
and len(index.items) == len(expr.args) |
| 575 |
): |
| 576 |
# Special case "for x, y in zip(a, b)". |
| 577 |
for_zip = ForZip(builder, index, body_block, loop_exit, line, nested) |
| 578 |
for_zip.init(index.items, expr.args) |
| 579 |
return for_zip |
| 580 |
|
| 581 |
if ( |
| 582 |
expr.callee.fullname == "builtins.reversed" |
| 583 |
and len(expr.args) == 1 |
| 584 |
and expr.arg_kinds == [ARG_POS] |
| 585 |
and is_sequence_rprimitive(builder.node_type(expr.args[0])) |
| 586 |
): |
| 587 |
# Special case "for x in reversed(<list>)". |
| 588 |
expr_reg = builder.accept(expr.args[0]) |
| 589 |
target_type = builder.get_sequence_type(expr) |
| 590 |
|
| 591 |
for_list = ForSequence(builder, index, body_block, loop_exit, line, nested) |
| 592 |
for_list.init(expr_reg, target_type, reverse=True) |
| 593 |
return for_list |
| 594 |
if isinstance(expr, CallExpr) and isinstance(expr.callee, MemberExpr) and not expr.args: |
| 595 |
# Special cases for dictionary iterator methods, like dict.items(). |
| 596 |
rtype = builder.node_type(expr.callee.expr) |
| 597 |
if is_dict_rprimitive(rtype) and expr.callee.name in ("keys", "values", "items"): |
| 598 |
expr_reg = builder.accept(expr.callee.expr) |
| 599 |
for_dict_type: type[ForGenerator] | None = None |
| 600 |
if expr.callee.name == "keys": |
| 601 |
target_type = builder.get_dict_key_type(expr.callee.expr) |
| 602 |
for_dict_type = ForDictionaryKeys |
| 603 |
elif expr.callee.name == "values": |
| 604 |
target_type = builder.get_dict_value_type(expr.callee.expr) |
| 605 |
for_dict_type = ForDictionaryValues |
| 606 |
else: |
| 607 |
target_type = builder.get_dict_item_type(expr.callee.expr) |
| 608 |
for_dict_type = ForDictionaryItems |
| 609 |
for_dict_gen = for_dict_type(builder, index, body_block, loop_exit, line, nested) |
| 610 |
for_dict_gen.init(expr_reg, target_type) |
| 611 |
return for_dict_gen |
| 612 |
|
| 613 |
iterable_expr_reg: Value | None = None |
| 614 |
if isinstance(expr, SetExpr): |
| 615 |
# Special case "for x in <set literal>". |
| 616 |
from mypyc.irbuild.expression import precompute_set_literal |
| 617 |
|
| 618 |
set_literal = precompute_set_literal(builder, expr) |
| 619 |
if set_literal is not None: |
| 620 |
iterable_expr_reg = set_literal |
| 621 |
|
| 622 |
# Default to a generic for loop. |
| 623 |
if iterable_expr_reg is None: |
| 624 |
iterable_expr_reg = builder.accept(expr) |
| 625 |
|
| 626 |
it = iterable_expr_reg.type |
| 627 |
for_obj: ForNativeGenerator | ForIterable |
| 628 |
if isinstance(it, RInstance) and it.class_ir.has_method(GENERATOR_HELPER_NAME): |
| 629 |
# Directly call generator object methods if iterating over a native generator. |
| 630 |
for_obj = ForNativeGenerator(builder, index, body_block, loop_exit, line, nested) |
| 631 |
else: |
| 632 |
# Generic implementation that works of arbitrary iterables. |
| 633 |
for_obj = ForIterable(builder, index, body_block, loop_exit, line, nested) |
| 634 |
item_type = builder._analyze_iterable_item_type(expr) |
| 635 |
item_rtype = builder.type_to_rtype(item_type) |
| 636 |
for_obj.init(iterable_expr_reg, item_rtype) |
| 637 |
return for_obj |
| 638 |
|
| 639 |
|
| 640 |
class ForGenerator: |
| 641 |
"""Abstract base class for generating for loops.""" |
| 642 |
|
| 643 |
def __init__( |
| 644 |
self, |
| 645 |
builder: IRBuilder, |
| 646 |
index: Lvalue, |
| 647 |
body_block: BasicBlock, |
| 648 |
loop_exit: BasicBlock, |
| 649 |
line: int, |
| 650 |
nested: bool, |
| 651 |
) -> None: |
| 652 |
self.builder = builder |
| 653 |
self.index = index |
| 654 |
self.body_block = body_block |
| 655 |
self.line = line |
| 656 |
# Some for loops need a cleanup block that we execute at exit. We |
| 657 |
# create a cleanup block if needed. However, if we are generating a for |
| 658 |
# loop for a nested iterator, such as "e" in "enumerate(e)", the |
| 659 |
# outermost generator should generate the cleanup block -- we don't |
| 660 |
# need to do it here. |
| 661 |
if self.need_cleanup() and not nested: |
| 662 |
# Create a new block to handle cleanup after loop exit. |
| 663 |
self.loop_exit = BasicBlock() |
| 664 |
else: |
| 665 |
# Just use the existing loop exit block. |
| 666 |
self.loop_exit = loop_exit |
| 667 |
|
| 668 |
def need_cleanup(self) -> bool: |
| 669 |
"""If this returns true, we need post-loop cleanup.""" |
| 670 |
return False |
| 671 |
|
| 672 |
def add_cleanup(self, exit_block: BasicBlock) -> None: |
| 673 |
"""Add post-loop cleanup, if needed.""" |
| 674 |
if self.need_cleanup(): |
| 675 |
self.builder.activate_block(self.loop_exit) |
| 676 |
self.gen_cleanup() |
| 677 |
self.builder.goto(exit_block) |
| 678 |
|
| 679 |
def gen_condition(self) -> None: |
| 680 |
"""Generate check for loop exit (e.g. exhaustion of iteration).""" |
| 681 |
|
| 682 |
def begin_body(self) -> None: |
| 683 |
"""Generate ops at the beginning of the body (if needed).""" |
| 684 |
|
| 685 |
def gen_step(self) -> None: |
| 686 |
"""Generate stepping to the next item (if needed).""" |
| 687 |
|
| 688 |
def gen_cleanup(self) -> None: |
| 689 |
"""Generate post-loop cleanup (if needed).""" |
| 690 |
|
| 691 |
def load_len(self, expr: Value | AssignmentTarget) -> Value: |
| 692 |
"""A helper to get collection length, used by several subclasses.""" |
| 693 |
return self.builder.builder.builtin_len( |
| 694 |
self.builder.read(expr, self.line), self.line, use_pyssize_t=True |
| 695 |
) |
| 696 |
|
| 697 |
|
| 698 |
class ForIterable(ForGenerator): |
| 699 |
"""Generate IR for a for loop over an arbitrary iterable (the general case).""" |
| 700 |
|
| 701 |
def need_cleanup(self) -> bool: |
| 702 |
# Create a new cleanup block for when the loop is finished. |
| 703 |
return True |
| 704 |
|
| 705 |
def init(self, expr_reg: Value, target_type: RType) -> None: |
| 706 |
# Define targets to contain the expression, along with the iterator that will be used |
| 707 |
# for the for-loop. If we are inside of a generator function, spill these into the |
| 708 |
# environment class. |
| 709 |
builder = self.builder |
| 710 |
iter_reg = builder.primitive_op(iter_op, [expr_reg], self.line) |
| 711 |
builder.maybe_spill(expr_reg) |
| 712 |
self.iter_target = builder.maybe_spill(iter_reg) |
| 713 |
self.target_type = target_type |
| 714 |
|
| 715 |
def gen_condition(self) -> None: |
| 716 |
# We call __next__ on the iterator and check to see if the return value |
| 717 |
# is NULL, which signals either the end of the Iterable being traversed |
| 718 |
# or an exception being raised. Note that Branch.IS_ERROR checks only |
| 719 |
# for NULL (an exception does not necessarily have to be raised). |
| 720 |
builder = self.builder |
| 721 |
line = self.line |
| 722 |
self.next_reg = builder.call_c(next_op, [builder.read(self.iter_target, line)], line) |
| 723 |
builder.add(Branch(self.next_reg, self.loop_exit, self.body_block, Branch.IS_ERROR)) |
| 724 |
|
| 725 |
def begin_body(self) -> None: |
| 726 |
# Assign the value obtained from __next__ to the |
| 727 |
# lvalue so that it can be referenced by code in the body of the loop. |
| 728 |
builder = self.builder |
| 729 |
line = self.line |
| 730 |
# We unbox here so that iterating with tuple unpacking generates a tuple based |
| 731 |
# unpack instead of an iterator based one. |
| 732 |
next_reg = builder.coerce(self.next_reg, self.target_type, line) |
| 733 |
builder.assign(builder.get_assignment_target(self.index), next_reg, line) |
| 734 |
|
| 735 |
def gen_step(self) -> None: |
| 736 |
# Nothing to do here, since we get the next item as part of gen_condition(). |
| 737 |
pass |
| 738 |
|
| 739 |
def gen_cleanup(self) -> None: |
| 740 |
# We set the branch to go here if the conditional evaluates to true. If |
| 741 |
# an exception was raised during the loop, then err_reg will be set to |
| 742 |
# True. If no_err_occurred_op returns False, then the exception will be |
| 743 |
# propagated using the ERR_FALSE flag. |
| 744 |
self.builder.call_c(no_err_occurred_op, [], self.line) |
| 745 |
|
| 746 |
|
| 747 |
class ForNativeGenerator(ForGenerator): |
| 748 |
"""Generate IR for a for loop over a native generator.""" |
| 749 |
|
| 750 |
def need_cleanup(self) -> bool: |
| 751 |
# Create a new cleanup block for when the loop is finished. |
| 752 |
return True |
| 753 |
|
| 754 |
def init(self, expr_reg: Value, target_type: RType) -> None: |
| 755 |
# Define target to contains the generator expression. It's also the iterator. |
| 756 |
# If we are inside a generator function, spill these into the environment class. |
| 757 |
builder = self.builder |
| 758 |
self.iter_target = builder.maybe_spill(expr_reg) |
| 759 |
self.target_type = target_type |
| 760 |
|
| 761 |
def gen_condition(self) -> None: |
| 762 |
builder = self.builder |
| 763 |
line = self.line |
| 764 |
self.return_value = Register(object_rprimitive) |
| 765 |
err = builder.add(LoadErrorValue(object_rprimitive, undefines=True)) |
| 766 |
builder.assign(self.return_value, err, line) |
| 767 |
|
| 768 |
# Call generated generator helper method, passing a PyObject ** as the final |
| 769 |
# argument that will be used to store the return value in the return value |
| 770 |
# register. We ignore the return value but the presence of a return value |
| 771 |
# indicates that the generator has finished. This is faster than raising |
| 772 |
# and catching StopIteration, which is the non-native way of doing this. |
| 773 |
ptr = builder.add(LoadAddress(object_pointer_rprimitive, self.return_value)) |
| 774 |
nn = builder.none_object() |
| 775 |
helper_call = MethodCall( |
| 776 |
builder.read(self.iter_target, line), |
| 777 |
GENERATOR_HELPER_NAME, |
| 778 |
[nn, nn, nn, nn, ptr], |
| 779 |
line, |
| 780 |
) |
| 781 |
# We provide custom handling for error values. |
| 782 |
helper_call.error_kind = ERR_NEVER |
| 783 |
|
| 784 |
self.next_reg = builder.add(helper_call) |
| 785 |
builder.add(Branch(self.next_reg, self.loop_exit, self.body_block, Branch.IS_ERROR)) |
| 786 |
|
| 787 |
def begin_body(self) -> None: |
| 788 |
# Assign the value obtained from the generator helper method to the |
| 789 |
# lvalue so that it can be referenced by code in the body of the loop. |
| 790 |
builder = self.builder |
| 791 |
line = self.line |
| 792 |
# We unbox here so that iterating with tuple unpacking generates a tuple based |
| 793 |
# unpack instead of an iterator based one. |
| 794 |
next_reg = builder.coerce(self.next_reg, self.target_type, line) |
| 795 |
builder.assign(builder.get_assignment_target(self.index), next_reg, line) |
| 796 |
|
| 797 |
def gen_step(self) -> None: |
| 798 |
# Nothing to do here, since we get the next item as part of gen_condition(). |
| 799 |
pass |
| 800 |
|
| 801 |
def gen_cleanup(self) -> None: |
| 802 |
# If return value is NULL (it wasn't assigned to by the generator helper method), |
| 803 |
# an exception was raised that we need to propagate. |
| 804 |
self.builder.primitive_op(propagate_if_error_op, [self.return_value], self.line) |
| 805 |
|
| 806 |
|
| 807 |
class ForAsyncIterable(ForGenerator): |
| 808 |
"""Generate IR for an async for loop.""" |
| 809 |
|
| 810 |
def init(self, expr_reg: Value, target_type: RType) -> None: |
| 811 |
# Define targets to contain the expression, along with the |
| 812 |
# iterator that will be used for the for-loop. We are inside |
| 813 |
# of a generator function, so we will spill these into |
| 814 |
# environment class. |
| 815 |
builder = self.builder |
| 816 |
iter_reg = builder.call_c(aiter_op, [expr_reg], self.line) |
| 817 |
builder.maybe_spill(expr_reg) |
| 818 |
self.iter_target = builder.maybe_spill(iter_reg) |
| 819 |
self.target_type = target_type |
| 820 |
self.stop_reg = Register(bool_rprimitive) |
| 821 |
|
| 822 |
def gen_condition(self) -> None: |
| 823 |
# This does the test and fetches the next value |
| 824 |
# try: |
| 825 |
# TARGET = await type(iter).__anext__(iter) |
| 826 |
# stop = False |
| 827 |
# except StopAsyncIteration: |
| 828 |
# stop = True |
| 829 |
# |
| 830 |
# What a pain. |
| 831 |
# There are optimizations available here if we punch through some abstractions. |
| 832 |
|
| 833 |
from mypyc.irbuild.statement import emit_await, transform_try_except |
| 834 |
|
| 835 |
builder = self.builder |
| 836 |
line = self.line |
| 837 |
|
| 838 |
def except_match() -> Value: |
| 839 |
return builder.add( |
| 840 |
LoadGlobal(stop_async_iteration_op.type, stop_async_iteration_op.src, line) |
| 841 |
) |
| 842 |
|
| 843 |
def try_body() -> None: |
| 844 |
awaitable = builder.call_c(anext_op, [builder.read(self.iter_target, line)], line) |
| 845 |
self.next_reg = emit_await(builder, awaitable, line) |
| 846 |
builder.assign(self.stop_reg, builder.false(), line) |
| 847 |
|
| 848 |
def except_body() -> None: |
| 849 |
builder.assign(self.stop_reg, builder.true(), line) |
| 850 |
|
| 851 |
transform_try_except( |
| 852 |
builder, try_body, [((except_match, line), None, except_body)], None, line |
| 853 |
) |
| 854 |
|
| 855 |
builder.add(Branch(self.stop_reg, self.loop_exit, self.body_block, Branch.BOOL)) |
| 856 |
|
| 857 |
def begin_body(self) -> None: |
| 858 |
# Assign the value obtained from await __anext__ to the |
| 859 |
# lvalue so that it can be referenced by code in the body of the loop. |
| 860 |
builder = self.builder |
| 861 |
line = self.line |
| 862 |
# We unbox here so that iterating with tuple unpacking generates a tuple based |
| 863 |
# unpack instead of an iterator based one. |
| 864 |
next_reg = builder.coerce(self.next_reg, self.target_type, line) |
| 865 |
builder.assign(builder.get_assignment_target(self.index), next_reg, line) |
| 866 |
|
| 867 |
def gen_step(self) -> None: |
| 868 |
# Nothing to do here, since we get the next item as part of gen_condition(). |
| 869 |
pass |
| 870 |
|
| 871 |
|
| 872 |
def unsafe_index(builder: IRBuilder, target: Value, index: Value, line: int) -> Value: |
| 873 |
"""Emit a potentially unsafe index into a target.""" |
| 874 |
# This doesn't really fit nicely into any of our data-driven frameworks |
| 875 |
# since we want to use __getitem__ if we don't have an unsafe version, |
| 876 |
# so we just check manually. |
| 877 |
if is_list_rprimitive(target.type): |
| 878 |
if not IS_FREE_THREADED: |
| 879 |
return builder.primitive_op(list_get_item_unsafe_op, [target, index], line) |
| 880 |
else: |
| 881 |
return builder.primitive_op(list_get_item_int64_op, [target, index], line) |
| 882 |
elif is_tuple_rprimitive(target.type): |
| 883 |
return builder.call_c(tuple_get_item_unsafe_op, [target, index], line) |
| 884 |
elif is_str_rprimitive(target.type): |
| 885 |
return builder.call_c(str_get_item_unsafe_op, [target, index], line) |
| 886 |
elif isinstance(target.type, RVec): |
| 887 |
return vec_get_item_unsafe(builder.builder, target, index, line) |
| 888 |
else: |
| 889 |
return builder.gen_method_call(target, "__getitem__", [index], None, line) |
| 890 |
|
| 891 |
|
| 892 |
class ForSequence(ForGenerator): |
| 893 |
"""Generate optimized IR for a for loop over a sequence. |
| 894 |
|
| 895 |
Supports iterating in both forward and reverse. |
| 896 |
""" |
| 897 |
|
| 898 |
length_reg: Value | AssignmentTarget | None |
| 899 |
|
| 900 |
def init( |
| 901 |
self, expr_reg: Value, target_type: RType, reverse: bool, length: Value | None = None |
| 902 |
) -> None: |
| 903 |
assert is_sequence_rprimitive(expr_reg.type) or isinstance(expr_reg.type, RVec), ( |
| 904 |
expr_reg, |
| 905 |
expr_reg.type, |
| 906 |
) |
| 907 |
builder = self.builder |
| 908 |
# Record a Value indicating the length of the sequence, if known at compile time. |
| 909 |
self.length = length |
| 910 |
self.reverse = reverse |
| 911 |
# Define target to contain the expression, along with the index that will be used |
| 912 |
# for the for-loop. If we are inside of a generator function, spill these into the |
| 913 |
# environment class. |
| 914 |
self.expr_target = builder.maybe_spill(expr_reg) |
| 915 |
if is_immutable_rprimitive(expr_reg.type): |
| 916 |
# If the expression is an immutable type, we can load the length just once. |
| 917 |
self.length_reg = builder.maybe_spill(self.length or self.load_len(self.expr_target)) |
| 918 |
else: |
| 919 |
# Otherwise, even if the length is known, we must recalculate the length |
| 920 |
# at every iteration for compatibility with python semantics. |
| 921 |
self.length_reg = None |
| 922 |
if not reverse: |
| 923 |
index_reg: Value = Integer(0, c_pyssize_t_rprimitive) |
| 924 |
else: |
| 925 |
if self.length_reg is not None: |
| 926 |
len_val = builder.read(self.length_reg, self.line) |
| 927 |
else: |
| 928 |
len_val = self.load_len(self.expr_target) |
| 929 |
index_reg = builder.builder.int_sub(len_val, 1) |
| 930 |
self.index_target = builder.maybe_spill_assignable(index_reg) |
| 931 |
self.target_type = target_type |
| 932 |
|
| 933 |
def gen_condition(self) -> None: |
| 934 |
builder = self.builder |
| 935 |
line = self.line |
| 936 |
if self.reverse: |
| 937 |
# If we are iterating in reverse order, we obviously need |
| 938 |
# to check that the index is still positive. Somewhat less |
| 939 |
# obviously we still need to check against the length, |
| 940 |
# since it could shrink out from under us. |
| 941 |
comparison = builder.binary_op( |
| 942 |
builder.read(self.index_target, line), Integer(0), ">=", line |
| 943 |
) |
| 944 |
second_check = BasicBlock() |
| 945 |
builder.add_bool_branch(comparison, second_check, self.loop_exit) |
| 946 |
builder.activate_block(second_check) |
| 947 |
if self.length_reg is None: |
| 948 |
# For compatibility with python semantics we recalculate the length |
| 949 |
# at every iteration. |
| 950 |
len_reg = self.load_len(self.expr_target) |
| 951 |
else: |
| 952 |
# (unless input is immutable type). |
| 953 |
len_reg = builder.read(self.length_reg, line) |
| 954 |
comparison = builder.binary_op(builder.read(self.index_target, line), len_reg, "<", line) |
| 955 |
builder.add_bool_branch(comparison, self.body_block, self.loop_exit) |
| 956 |
|
| 957 |
def begin_body(self) -> None: |
| 958 |
builder = self.builder |
| 959 |
line = self.line |
| 960 |
# Read the next list item. |
| 961 |
value_box = unsafe_index( |
| 962 |
builder, |
| 963 |
builder.read(self.expr_target, line), |
| 964 |
builder.read(self.index_target, line), |
| 965 |
line, |
| 966 |
) |
| 967 |
assert value_box |
| 968 |
# We coerce to the type of list elements here so that |
| 969 |
# iterating with tuple unpacking generates a tuple based |
| 970 |
# unpack instead of an iterator based one. |
| 971 |
builder.assign( |
| 972 |
builder.get_assignment_target(self.index), |
| 973 |
builder.coerce(value_box, self.target_type, line), |
| 974 |
line, |
| 975 |
) |
| 976 |
|
| 977 |
def gen_step(self) -> None: |
| 978 |
# Step to the next item. |
| 979 |
builder = self.builder |
| 980 |
line = self.line |
| 981 |
step = 1 if not self.reverse else -1 |
| 982 |
add = builder.builder.int_add(builder.read(self.index_target, line), step) |
| 983 |
builder.assign(self.index_target, add, line) |
| 984 |
|
| 985 |
|
| 986 |
class ForDictionaryCommon(ForGenerator): |
| 987 |
"""Generate optimized IR for a for loop over dictionary keys/values. |
| 988 |
|
| 989 |
The logic is pretty straightforward, we use PyDict_Next() API wrapped in |
| 990 |
a tuple, so that we can modify only a single register. The layout of the tuple: |
| 991 |
* f0: are there more items (bool) |
| 992 |
* f1: current offset (int) |
| 993 |
* f2: next key (object) |
| 994 |
* f3: next value (object) |
| 995 |
For more info see https://docs.python.org/3/c-api/dict.html#c.PyDict_Next. |
| 996 |
|
| 997 |
Note that for subclasses we fall back to generic PyObject_GetIter() logic, |
| 998 |
since they may override some iteration methods in subtly incompatible manner. |
| 999 |
The fallback logic is implemented in CPy.h via dynamic type check. |
| 1000 |
""" |
| 1001 |
|
| 1002 |
dict_next_op: ClassVar[CFunctionDescription] |
| 1003 |
dict_iter_op: ClassVar[CFunctionDescription] |
| 1004 |
|
| 1005 |
def need_cleanup(self) -> bool: |
| 1006 |
# Technically, a dict subclass can raise an unrelated exception |
| 1007 |
# in __next__(), so we need this. |
| 1008 |
return True |
| 1009 |
|
| 1010 |
def init(self, expr_reg: Value, target_type: RType) -> None: |
| 1011 |
builder = self.builder |
| 1012 |
self.target_type = target_type |
| 1013 |
|
| 1014 |
# We add some variables to environment class, so they can be read across yield. |
| 1015 |
self.expr_target = builder.maybe_spill(expr_reg) |
| 1016 |
offset = Integer(0) |
| 1017 |
self.offset_target = builder.maybe_spill_assignable(offset) |
| 1018 |
self.size = builder.maybe_spill(self.load_len(self.expr_target)) |
| 1019 |
|
| 1020 |
# For dict class (not a subclass) this is the dictionary itself. |
| 1021 |
iter_reg = builder.call_c(self.dict_iter_op, [expr_reg], self.line) |
| 1022 |
self.iter_target = builder.maybe_spill(iter_reg) |
| 1023 |
|
| 1024 |
def gen_condition(self) -> None: |
| 1025 |
"""Get next key/value pair, set new offset, and check if we should continue.""" |
| 1026 |
builder = self.builder |
| 1027 |
line = self.line |
| 1028 |
self.next_tuple = self.builder.call_c( |
| 1029 |
self.dict_next_op, |
| 1030 |
[builder.read(self.iter_target, line), builder.read(self.offset_target, line)], |
| 1031 |
line, |
| 1032 |
) |
| 1033 |
|
| 1034 |
# Do this here instead of in gen_step() to minimize variables in environment. |
| 1035 |
new_offset = builder.add(TupleGet(self.next_tuple, 1, line)) |
| 1036 |
builder.assign(self.offset_target, new_offset, line) |
| 1037 |
|
| 1038 |
should_continue = builder.add(TupleGet(self.next_tuple, 0, line)) |
| 1039 |
builder.add(Branch(should_continue, self.body_block, self.loop_exit, Branch.BOOL)) |
| 1040 |
|
| 1041 |
def gen_step(self) -> None: |
| 1042 |
"""Check that dictionary didn't change size during iteration. |
| 1043 |
|
| 1044 |
Raise RuntimeError if it is not the case to match CPython behavior. |
| 1045 |
""" |
| 1046 |
builder = self.builder |
| 1047 |
line = self.line |
| 1048 |
# Technically, we don't need a new primitive for this, but it is simpler. |
| 1049 |
builder.call_c( |
| 1050 |
dict_check_size_op, |
| 1051 |
[builder.read(self.expr_target, line), builder.read(self.size, line)], |
| 1052 |
line, |
| 1053 |
) |
| 1054 |
|
| 1055 |
def gen_cleanup(self) -> None: |
| 1056 |
# Same as for generic ForIterable. |
| 1057 |
self.builder.call_c(no_err_occurred_op, [], self.line) |
| 1058 |
|
| 1059 |
|
| 1060 |
class ForDictionaryKeys(ForDictionaryCommon): |
| 1061 |
"""Generate optimized IR for a for loop over dictionary keys.""" |
| 1062 |
|
| 1063 |
dict_next_op = dict_next_key_op |
| 1064 |
dict_iter_op = dict_key_iter_op |
| 1065 |
|
| 1066 |
def begin_body(self) -> None: |
| 1067 |
builder = self.builder |
| 1068 |
line = self.line |
| 1069 |
|
| 1070 |
# Key is stored at the third place in the tuple. |
| 1071 |
key = builder.add(TupleGet(self.next_tuple, 2, line)) |
| 1072 |
builder.assign( |
| 1073 |
builder.get_assignment_target(self.index), |
| 1074 |
builder.coerce(key, self.target_type, line), |
| 1075 |
line, |
| 1076 |
) |
| 1077 |
|
| 1078 |
|
| 1079 |
class ForDictionaryValues(ForDictionaryCommon): |
| 1080 |
"""Generate optimized IR for a for loop over dictionary values.""" |
| 1081 |
|
| 1082 |
dict_next_op = dict_next_value_op |
| 1083 |
dict_iter_op = dict_value_iter_op |
| 1084 |
|
| 1085 |
def begin_body(self) -> None: |
| 1086 |
builder = self.builder |
| 1087 |
line = self.line |
| 1088 |
|
| 1089 |
# Value is stored at the third place in the tuple. |
| 1090 |
value = builder.add(TupleGet(self.next_tuple, 2, line)) |
| 1091 |
builder.assign( |
| 1092 |
builder.get_assignment_target(self.index), |
| 1093 |
builder.coerce(value, self.target_type, line), |
| 1094 |
line, |
| 1095 |
) |
| 1096 |
|
| 1097 |
|
| 1098 |
class ForDictionaryItems(ForDictionaryCommon): |
| 1099 |
"""Generate optimized IR for a for loop over dictionary items.""" |
| 1100 |
|
| 1101 |
dict_next_op = dict_next_item_op |
| 1102 |
dict_iter_op = dict_item_iter_op |
| 1103 |
|
| 1104 |
def begin_body(self) -> None: |
| 1105 |
builder = self.builder |
| 1106 |
line = self.line |
| 1107 |
|
| 1108 |
key = builder.add(TupleGet(self.next_tuple, 2, line)) |
| 1109 |
value = builder.add(TupleGet(self.next_tuple, 3, line)) |
| 1110 |
|
| 1111 |
# Coerce just in case e.g. key is itself a tuple to be unpacked. |
| 1112 |
assert isinstance(self.target_type, RTuple), self.target_type |
| 1113 |
key = builder.coerce(key, self.target_type.types[0], line) |
| 1114 |
value = builder.coerce(value, self.target_type.types[1], line) |
| 1115 |
|
| 1116 |
target = builder.get_assignment_target(self.index) |
| 1117 |
if isinstance(target, AssignmentTargetTuple): |
| 1118 |
# Simpler code for common case: for k, v in d.items(). |
| 1119 |
if len(target.items) != 2: |
| 1120 |
builder.error("Expected a pair for dict item iteration", line) |
| 1121 |
builder.assign(target.items[0], key, line) |
| 1122 |
builder.assign(target.items[1], value, line) |
| 1123 |
else: |
| 1124 |
rvalue = builder.add(TupleSet([key, value], line)) |
| 1125 |
builder.assign(target, rvalue, line) |
| 1126 |
|
| 1127 |
|
| 1128 |
class ForRange(ForGenerator): |
| 1129 |
"""Generate optimized IR for a for loop over an integer range.""" |
| 1130 |
|
| 1131 |
def init(self, start_reg: Value, end_reg: Value, step: int) -> None: |
| 1132 |
builder = self.builder |
| 1133 |
self.start_reg = start_reg |
| 1134 |
self.end_reg = end_reg |
| 1135 |
self.step = step |
| 1136 |
self.end_target = builder.maybe_spill(end_reg) |
| 1137 |
if is_short_int_rprimitive(start_reg.type) and is_short_int_rprimitive(end_reg.type): |
| 1138 |
index_type: RType = short_int_rprimitive |
| 1139 |
elif is_fixed_width_rtype(end_reg.type): |
| 1140 |
index_type = end_reg.type |
| 1141 |
else: |
| 1142 |
index_type = int_rprimitive |
| 1143 |
index_reg = Register(index_type, line=self.line) |
| 1144 |
builder.assign(index_reg, start_reg, self.line) |
| 1145 |
self.index_reg = builder.maybe_spill_assignable(index_reg) |
| 1146 |
# Initialize loop index to 0. Assert that the index target is assignable. |
| 1147 |
self.index_target: Register | AssignmentTarget = builder.get_assignment_target(self.index) |
| 1148 |
builder.assign(self.index_target, builder.read(self.index_reg, self.line), self.line) |
| 1149 |
|
| 1150 |
def gen_condition(self) -> None: |
| 1151 |
builder = self.builder |
| 1152 |
line = self.line |
| 1153 |
# Add loop condition check. |
| 1154 |
cmp = "<" if self.step > 0 else ">" |
| 1155 |
comparison = builder.binary_op( |
| 1156 |
builder.read(self.index_reg, line), builder.read(self.end_target, line), cmp, line |
| 1157 |
) |
| 1158 |
builder.add_bool_branch(comparison, self.body_block, self.loop_exit) |
| 1159 |
|
| 1160 |
def begin_body(self) -> None: |
| 1161 |
# Update the user-visible loop variable at the start of the body, |
| 1162 |
# after the condition check passes. This ensures the variable isn't |
| 1163 |
# "overshot" when the loop exits (matching CPython semantics). |
| 1164 |
builder = self.builder |
| 1165 |
builder.assign(self.index_target, builder.read(self.index_reg, self.line), self.line) |
| 1166 |
|
| 1167 |
def gen_step(self) -> None: |
| 1168 |
builder = self.builder |
| 1169 |
line = self.line |
| 1170 |
|
| 1171 |
# Increment index register. If the range is known to fit in short ints, use |
| 1172 |
# short ints. |
| 1173 |
if is_short_int_rprimitive(self.start_reg.type) and is_short_int_rprimitive( |
| 1174 |
self.end_reg.type |
| 1175 |
): |
| 1176 |
new_val = builder.int_op( |
| 1177 |
short_int_rprimitive, |
| 1178 |
builder.read(self.index_reg, line), |
| 1179 |
Integer(self.step), |
| 1180 |
IntOp.ADD, |
| 1181 |
line, |
| 1182 |
) |
| 1183 |
|
| 1184 |
else: |
| 1185 |
new_val = builder.binary_op( |
| 1186 |
builder.read(self.index_reg, line), Integer(self.step), "+", line |
| 1187 |
) |
| 1188 |
builder.assign(self.index_reg, new_val, line) |
| 1189 |
|
| 1190 |
|
| 1191 |
class ForInfiniteCounter(ForGenerator): |
| 1192 |
"""Generate optimized IR for a for loop counting from 0 to infinity.""" |
| 1193 |
|
| 1194 |
def init(self) -> None: |
| 1195 |
builder = self.builder |
| 1196 |
# Create a register to store the state of the loop index and |
| 1197 |
# initialize this register along with the loop index to 0. |
| 1198 |
zero = Integer(0) |
| 1199 |
self.index_reg = builder.maybe_spill_assignable(zero) |
| 1200 |
self.index_target: Register | AssignmentTarget = builder.get_assignment_target(self.index) |
| 1201 |
|
| 1202 |
def gen_step(self) -> None: |
| 1203 |
builder = self.builder |
| 1204 |
line = self.line |
| 1205 |
# We can safely assume that the integer is short, since we are not going to wrap |
| 1206 |
# around a 63-bit integer. |
| 1207 |
# NOTE: This would be questionable if short ints could be 32 bits. |
| 1208 |
new_val = builder.int_op( |
| 1209 |
short_int_rprimitive, builder.read(self.index_reg, line), Integer(1), IntOp.ADD, line |
| 1210 |
) |
| 1211 |
builder.assign(self.index_reg, new_val, line) |
| 1212 |
|
| 1213 |
def begin_body(self) -> None: |
| 1214 |
self.builder.assign( |
| 1215 |
self.index_target, self.builder.read(self.index_reg, self.line), self.line |
| 1216 |
) |
| 1217 |
|
| 1218 |
|
| 1219 |
class ForEnumerate(ForGenerator): |
| 1220 |
"""Generate optimized IR for a for loop of form "for i, x in enumerate(it)".""" |
| 1221 |
|
| 1222 |
def need_cleanup(self) -> bool: |
| 1223 |
# The wrapped for loop might need cleanup. This might generate a |
| 1224 |
# redundant cleanup block, but that's okay. |
| 1225 |
return True |
| 1226 |
|
| 1227 |
def init(self, index1: Lvalue, index2: Lvalue, expr: Expression) -> None: |
| 1228 |
# Count from 0 to infinity (for the index lvalue). |
| 1229 |
self.index_gen = ForInfiniteCounter( |
| 1230 |
self.builder, index1, self.body_block, self.loop_exit, self.line, nested=True |
| 1231 |
) |
| 1232 |
self.index_gen.init() |
| 1233 |
# Iterate over the actual iterable. |
| 1234 |
self.main_gen = make_for_loop_generator( |
| 1235 |
self.builder, index2, expr, self.body_block, self.loop_exit, self.line, nested=True |
| 1236 |
) |
| 1237 |
|
| 1238 |
def gen_condition(self) -> None: |
| 1239 |
# No need for a check for the index generator, since it's unconditional. |
| 1240 |
self.main_gen.gen_condition() |
| 1241 |
|
| 1242 |
def begin_body(self) -> None: |
| 1243 |
self.index_gen.begin_body() |
| 1244 |
self.main_gen.begin_body() |
| 1245 |
|
| 1246 |
def gen_step(self) -> None: |
| 1247 |
self.index_gen.gen_step() |
| 1248 |
self.main_gen.gen_step() |
| 1249 |
|
| 1250 |
def gen_cleanup(self) -> None: |
| 1251 |
self.index_gen.gen_cleanup() |
| 1252 |
self.main_gen.gen_cleanup() |
| 1253 |
|
| 1254 |
|
| 1255 |
class ForZip(ForGenerator): |
| 1256 |
"""Generate IR for a for loop of form `for x, ... in zip(a, ...)`.""" |
| 1257 |
|
| 1258 |
def need_cleanup(self) -> bool: |
| 1259 |
# The wrapped for loops might need cleanup. We might generate a |
| 1260 |
# redundant cleanup block, but that's okay. |
| 1261 |
return True |
| 1262 |
|
| 1263 |
def init(self, indexes: list[Lvalue], exprs: list[Expression]) -> None: |
| 1264 |
assert len(indexes) == len(exprs) |
| 1265 |
# Condition check will require multiple basic blocks, since there will be |
| 1266 |
# multiple conditions to check. |
| 1267 |
self.cond_blocks = [BasicBlock() for _ in range(len(indexes) - 1)] + [self.body_block] |
| 1268 |
self.gens: list[ForGenerator] = [] |
| 1269 |
for index, expr, next_block in zip(indexes, exprs, self.cond_blocks): |
| 1270 |
gen = make_for_loop_generator( |
| 1271 |
self.builder, index, expr, next_block, self.loop_exit, self.line, nested=True |
| 1272 |
) |
| 1273 |
self.gens.append(gen) |
| 1274 |
|
| 1275 |
def gen_condition(self) -> None: |
| 1276 |
for i, gen in enumerate(self.gens): |
| 1277 |
gen.gen_condition() |
| 1278 |
if i < len(self.gens) - 1: |
| 1279 |
self.builder.activate_block(self.cond_blocks[i]) |
| 1280 |
|
| 1281 |
def begin_body(self) -> None: |
| 1282 |
for gen in self.gens: |
| 1283 |
gen.begin_body() |
| 1284 |
|
| 1285 |
def gen_step(self) -> None: |
| 1286 |
for gen in self.gens: |
| 1287 |
gen.gen_step() |
| 1288 |
|
| 1289 |
def gen_cleanup(self) -> None: |
| 1290 |
for gen in self.gens: |
| 1291 |
gen.gen_cleanup() |
| 1292 |
|
| 1293 |
|
| 1294 |
def get_expr_length(builder: IRBuilder, expr: Expression) -> int | None: |
| 1295 |
folded = constant_fold_expr(builder, expr) |
| 1296 |
if isinstance(folded, (str, bytes)): |
| 1297 |
return len(folded) |
| 1298 |
elif isinstance(expr, (ListExpr, TupleExpr)): |
| 1299 |
# if there are no star expressions, or we know the length of them, |
| 1300 |
# we know the length of the expression |
| 1301 |
stars = [get_expr_length(builder, i) for i in expr.items if isinstance(i, StarExpr)] |
| 1302 |
if None not in stars: |
| 1303 |
other = sum(not isinstance(i, StarExpr) for i in expr.items) |
| 1304 |
return other + sum(stars) # type: ignore [arg-type] |
| 1305 |
elif isinstance(expr, StarExpr): |
| 1306 |
return get_expr_length(builder, expr.expr) |
| 1307 |
elif ( |
| 1308 |
isinstance(expr, RefExpr) |
| 1309 |
and isinstance(expr.node, Var) |
| 1310 |
and expr.node.is_final |
| 1311 |
and isinstance(expr.node.final_value, str) |
| 1312 |
and expr.node.has_explicit_value |
| 1313 |
): |
| 1314 |
return len(expr.node.final_value) |
| 1315 |
elif ( |
| 1316 |
isinstance(expr, CallExpr) |
| 1317 |
and isinstance(callee := expr.callee, NameExpr) |
| 1318 |
and all(kind == ARG_POS for kind in expr.arg_kinds) |
| 1319 |
): |
| 1320 |
fullname = callee.fullname |
| 1321 |
if ( |
| 1322 |
fullname |
| 1323 |
in ( |
| 1324 |
"builtins.list", |
| 1325 |
"builtins.tuple", |
| 1326 |
"builtins.enumerate", |
| 1327 |
"builtins.sorted", |
| 1328 |
"builtins.reversed", |
| 1329 |
) |
| 1330 |
and len(expr.args) == 1 |
| 1331 |
): |
| 1332 |
return get_expr_length(builder, expr.args[0]) |
| 1333 |
elif fullname == "builtins.map" and len(expr.args) == 2: |
| 1334 |
return get_expr_length(builder, expr.args[1]) |
| 1335 |
elif fullname == "builtins.zip" and expr.args: |
| 1336 |
arg_lengths = [get_expr_length(builder, arg) for arg in expr.args] |
| 1337 |
if all(arg is not None for arg in arg_lengths): |
| 1338 |
return min(arg_lengths) # type: ignore [type-var] |
| 1339 |
elif fullname == "builtins.range" and len(expr.args) <= 3: |
| 1340 |
folded_args = [constant_fold_expr(builder, arg) for arg in expr.args] |
| 1341 |
if all(isinstance(arg, int) for arg in folded_args): |
| 1342 |
try: |
| 1343 |
return len(range(*cast(list[int], folded_args))) |
| 1344 |
except ValueError: # prevent crash if invalid args |
| 1345 |
pass |
| 1346 |
|
| 1347 |
# TODO: extend this, passing length of listcomp and genexp should have worthwhile |
| 1348 |
# performance boost and can be (sometimes) figured out pretty easily. set and dict |
| 1349 |
# comps *can* be done as well but will need special logic to consider the possibility |
| 1350 |
# of key conflicts. |
| 1351 |
|
| 1352 |
# we might still be able to get the length directly from the type |
| 1353 |
rtype = builder.node_type(expr) |
| 1354 |
if isinstance(rtype, RTuple): |
| 1355 |
return len(rtype.types) |
| 1356 |
return None |
| 1357 |
|
| 1358 |
|
| 1359 |
def get_expr_length_value( |
| 1360 |
builder: IRBuilder, expr: Expression, expr_reg: Value, line: int, use_pyssize_t: bool |
| 1361 |
) -> Value: |
| 1362 |
rtype = builder.node_type(expr) |
| 1363 |
assert is_sequence_rprimitive(rtype) or isinstance(rtype, (RTuple, RVec)), rtype |
| 1364 |
length = get_expr_length(builder, expr) |
| 1365 |
if length is None: |
| 1366 |
# We cannot compute the length at compile time, so we will fetch it. |
| 1367 |
return builder.builder.builtin_len(expr_reg, line, use_pyssize_t=use_pyssize_t) |
| 1368 |
# The expression result is known at compile time, so we can use a constant. |
| 1369 |
return Integer(length, c_pyssize_t_rprimitive if use_pyssize_t else short_int_rprimitive) |