Debian Codegraph @

mypyc/irbuild/specialize.py

raw
1 """Special case IR generation of calls to specific builtin functions.
2
3 Most special cases should be handled using the data driven "primitive
4 ops" system, but certain operations require special handling that has
5 access to the AST/IR directly and can make decisions/optimizations
6 based on it. These special cases can be implemented here.
7
8 For example, we use specializers to statically emit the length of a
9 fixed length tuple and to emit optimized code for any()/all() calls with
10 generator comprehensions as the argument.
11
12 See comment below for more documentation.
13 """
14
15 from __future__ import annotations
16
17 from collections.abc import Callable
18 from typing import Final, cast
19
20 from mypy.nodes import (
21 ARG_NAMED,
22 ARG_POS,
23 CallExpr,
24 DictExpr,
25 Expression,
26 GeneratorExpr,
27 IndexExpr,
28 IntExpr,
29 ListExpr,
30 MemberExpr,
31 NameExpr,
32 RefExpr,
33 StrExpr,
34 SuperExpr,
35 TupleExpr,
36 Var,
37 )
38 from mypy.types import AnyType, TypeOfAny
39 from mypyc.ir.ops import (
40 BasicBlock,
41 Call,
42 Extend,
43 Integer,
44 PrimitiveDescription,
45 RaiseStandardError,
46 Register,
47 SetAttr,
48 Truncate,
49 Unreachable,
50 Value,
51 )
52 from mypyc.ir.rtypes import (
53 RInstance,
54 RPrimitive,
55 RTuple,
56 RType,
57 RVec,
58 bool_rprimitive,
59 bytes_rprimitive,
60 bytes_writer_rprimitive,
61 c_int_rprimitive,
62 dict_rprimitive,
63 int16_rprimitive,
64 int32_rprimitive,
65 int64_rprimitive,
66 int_rprimitive,
67 is_bool_rprimitive,
68 is_dict_rprimitive,
69 is_fixed_width_rtype,
70 is_float_rprimitive,
71 is_int16_rprimitive,
72 is_int32_rprimitive,
73 is_int64_rprimitive,
74 is_int_rprimitive,
75 is_list_rprimitive,
76 is_sequence_rprimitive,
77 is_str_rprimitive,
78 is_tagged,
79 is_uint8_rprimitive,
80 list_rprimitive,
81 object_rprimitive,
82 set_rprimitive,
83 str_rprimitive,
84 string_writer_rprimitive,
85 uint8_rprimitive,
86 )
87 from mypyc.irbuild.builder import IRBuilder, get_call_target_fullname
88 from mypyc.irbuild.constant_fold import constant_fold_expr
89 from mypyc.irbuild.for_helpers import (
90 comprehension_helper,
91 get_expr_length_value,
92 sequence_from_generator_preallocate_helper,
93 translate_list_comprehension,
94 translate_set_comprehension,
95 )
96 from mypyc.irbuild.format_str_tokenizer import (
97 FormatOp,
98 convert_format_expr_to_str,
99 join_formatted_strings,
100 tokenizer_format_call,
101 )
102 from mypyc.irbuild.vec import (
103 supports_vec_to_sequence,
104 vec_append,
105 vec_extend,
106 vec_pop,
107 vec_remove,
108 vec_to_list,
109 vec_to_tuple,
110 )
111 from mypyc.primitives.bytearray_ops import isinstance_bytearray
112 from mypyc.primitives.bytes_ops import (
113 bytes_adjust_index_op,
114 bytes_get_item_unsafe_op,
115 bytes_range_check_op,
116 isinstance_bytes,
117 )
118 from mypyc.primitives.dict_ops import (
119 dict_items_op,
120 dict_keys_op,
121 dict_setdefault_spec_init_op,
122 dict_values_op,
123 isinstance_dict,
124 )
125 from mypyc.primitives.float_ops import isinstance_float
126 from mypyc.primitives.generic_ops import generic_setattr, setup_object
127 from mypyc.primitives.int_ops import (
128 int_to_big_endian_op,
129 int_to_bytes_op,
130 int_to_little_endian_op,
131 isinstance_int,
132 )
133 from mypyc.primitives.librt_strings_ops import (
134 bytes_writer_adjust_index_op,
135 bytes_writer_get_item_unsafe_op,
136 bytes_writer_range_check_op,
137 bytes_writer_set_item_unsafe_op,
138 string_writer_adjust_index_op,
139 string_writer_get_item_unsafe_op,
140 string_writer_range_check_op,
141 )
142 from mypyc.primitives.librt_vecs_ops import isinstance_vec
143 from mypyc.primitives.list_ops import isinstance_list, new_list_set_item_op
144 from mypyc.primitives.misc_ops import isinstance_bool
145 from mypyc.primitives.set_ops import isinstance_frozenset, isinstance_set
146 from mypyc.primitives.str_ops import (
147 bytes_decode_ascii_strict,
148 bytes_decode_latin1_strict,
149 bytes_decode_utf8_strict,
150 isinstance_str,
151 str_adjust_index_op,
152 str_encode_ascii_strict,
153 str_encode_latin1_strict,
154 str_encode_utf8_strict,
155 str_get_item_unsafe_as_int_op,
156 str_range_check_op,
157 )
158 from mypyc.primitives.tuple_ops import isinstance_tuple, new_tuple_set_item_op
159
160 # Specializers are attempted before compiling the arguments to the
161 # function. Specializers can return None to indicate that they failed
162 # and the call should be compiled normally. Otherwise they should emit
163 # code for the call and return a Value containing the result.
164 #
165 # Specializers take three arguments: the IRBuilder, the CallExpr being
166 # compiled, and the RefExpr that is the left hand side of the call.
167 Specializer = Callable[["IRBuilder", CallExpr, RefExpr], Value | None]
168
169 # Dunder specializers are for special method calls like __getitem__, __setitem__, etc.
170 # that don't naturally map to CallExpr nodes (e.g., from IndexExpr).
171 #
172 # They take four arguments: the IRBuilder, the base expression (target object),
173 # the list of argument expressions (positional arguments to the dunder), and the
174 # context expression (e.g., IndexExpr) for error reporting.
175 DunderSpecializer = Callable[["IRBuilder", Expression, list[Expression], Expression], Value | None]
176
177 # Dictionary containing all configured specializers.
178 #
179 # Specializers can operate on methods as well, and are keyed on the
180 # name and RType in that case.
181 specializers: dict[tuple[str, RType | None], list[Specializer]] = {}
182
183 # Dictionary containing all configured dunder specializers.
184 #
185 # Dunder specializers are keyed on the dunder name and RType (always a method call).
186 dunder_specializers: dict[tuple[str, RType], list[DunderSpecializer]] = {}
187
188
189 def _apply_specialization(
190 builder: IRBuilder, expr: CallExpr, callee: RefExpr, name: str | None, typ: RType | None = None
191 ) -> Value | None:
192 # TODO: Allow special cases to have default args or named args. Currently they don't since
193 # they check that everything in arg_kinds is ARG_POS.
194
195 # If there is a specializer for this function, try calling it.
196 # Return the first successful one.
197 if name and (name, typ) in specializers:
198 for specializer in specializers[name, typ]:
199 val = specializer(builder, expr, callee)
200 if val is not None:
201 return val
202 return None
203
204
205 def apply_function_specialization(
206 builder: IRBuilder, expr: CallExpr, callee: RefExpr
207 ) -> Value | None:
208 """Invoke the Specializer callback for a function if one has been registered"""
209 return _apply_specialization(builder, expr, callee, get_call_target_fullname(callee))
210
211
212 def apply_method_specialization(
213 builder: IRBuilder, expr: CallExpr, callee: MemberExpr, typ: RType | None = None
214 ) -> Value | None:
215 """Invoke the Specializer callback for a method if one has been registered"""
216 name = callee.fullname if typ is None else callee.name
217 return _apply_specialization(builder, expr, callee, name, typ)
218
219
220 def specialize_function(
221 name: str, typ: RType | None = None
222 ) -> Callable[[Specializer], Specializer]:
223 """Decorator to register a function as being a specializer.
224
225 There may exist multiple specializers for one function. When
226 translating method calls, the earlier appended specializer has
227 higher priority.
228 """
229
230 def wrapper(f: Specializer) -> Specializer:
231 specializers.setdefault((name, typ), []).append(f)
232 return f
233
234 return wrapper
235
236
237 def specialize_dunder(name: str, typ: RType) -> Callable[[DunderSpecializer], DunderSpecializer]:
238 """Decorator to register a function as being a dunder specializer.
239
240 Dunder specializers handle special method calls like __getitem__ that
241 don't naturally map to CallExpr nodes.
242
243 There may exist multiple specializers for one dunder. When translating
244 dunder calls, the earlier appended specializer has higher priority.
245 """
246
247 def wrapper(f: DunderSpecializer) -> DunderSpecializer:
248 dunder_specializers.setdefault((name, typ), []).append(f)
249 return f
250
251 return wrapper
252
253
254 def apply_dunder_specialization(
255 builder: IRBuilder,
256 base_expr: Expression,
257 args: list[Expression],
258 name: str,
259 ctx_expr: Expression,
260 ) -> Value | None:
261 """Invoke the DunderSpecializer callback if one has been registered.
262
263 Args:
264 builder: The IR builder
265 base_expr: The base expression (target object)
266 args: List of argument expressions (positional arguments to the dunder)
267 name: The dunder method name (e.g., "__getitem__")
268 ctx_expr: The context expression for error reporting (e.g., IndexExpr)
269
270 Returns:
271 The specialized value, or None if no specialization was found.
272 """
273 base_type = builder.node_type(base_expr)
274
275 # Check if there's a specializer for this dunder method and type
276 if (name, base_type) in dunder_specializers:
277 for specializer in dunder_specializers[name, base_type]:
278 val = specializer(builder, base_expr, args, ctx_expr)
279 if val is not None:
280 return val
281 return None
282
283
284 @specialize_function("builtins.globals")
285 def translate_globals(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
286 if len(expr.args) == 0:
287 return builder.load_globals_dict()
288 return None
289
290
291 @specialize_function("builtins.abs")
292 @specialize_function("builtins.int")
293 @specialize_function("builtins.float")
294 @specialize_function("builtins.complex")
295 @specialize_function("mypy_extensions.i64")
296 @specialize_function("mypy_extensions.i32")
297 @specialize_function("mypy_extensions.i16")
298 @specialize_function("mypy_extensions.u8")
299 def translate_builtins_with_unary_dunder(
300 builder: IRBuilder, expr: CallExpr, callee: RefExpr
301 ) -> Value | None:
302 """Specialize calls on native classes that implement the associated dunder.
303
304 E.g. i64(x) gets specialized to x.__int__() if x is a native instance.
305 """
306 if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS] and isinstance(callee, NameExpr):
307 arg = expr.args[0]
308 arg_typ = builder.node_type(arg)
309 shortname = callee.fullname.split(".")[1]
310 if shortname in ("i64", "i32", "i16", "u8"):
311 method = "__int__"
312 else:
313 method = f"__{shortname}__"
314 if isinstance(arg_typ, RInstance) and arg_typ.class_ir.has_method(method):
315 obj = builder.accept(arg)
316 return builder.gen_method_call(obj, method, [], None, expr.line)
317
318 return None
319
320
321 @specialize_function("builtins.len")
322 def translate_len(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
323 if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]:
324 arg = expr.args[0]
325 expr_rtype = builder.node_type(arg)
326 # NOTE (?) I'm not sure if my handling of can_borrow is correct here
327 obj = builder.accept(
328 arg, can_borrow=is_list_rprimitive(expr_rtype) or isinstance(expr_rtype, RVec)
329 )
330 if is_sequence_rprimitive(expr_rtype) or isinstance(expr_rtype, RTuple):
331 return get_expr_length_value(builder, arg, obj, expr.line, use_pyssize_t=False)
332 else:
333 # TODO: Decide type of result based on context somehow?
334 if isinstance(obj.type, RVec):
335 return builder.builtin_len(obj, expr.line, use_pyssize_t=True)
336 else:
337 return builder.builtin_len(obj, expr.line)
338 return None
339
340
341 @specialize_function("builtins.list")
342 def translate_vec_to_list(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
343 if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]:
344 arg_type = builder.node_type(expr.args[0])
345 if isinstance(arg_type, RVec) and supports_vec_to_sequence(arg_type):
346 vec = builder.accept(expr.args[0])
347 return vec_to_list(builder.builder, vec, expr.line)
348 return None
349
350
351 @specialize_function("builtins.list")
352 def dict_methods_fast_path(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
353 """Specialize a common case when list() is called on a dictionary
354 view method call.
355
356 For example:
357 foo = list(bar.keys())
358 """
359 if not (len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]):
360 return None
361 arg = expr.args[0]
362 if not (isinstance(arg, CallExpr) and not arg.args and isinstance(arg.callee, MemberExpr)):
363 return None
364 base = arg.callee.expr
365 attr = arg.callee.name
366 rtype = builder.node_type(base)
367 if not (is_dict_rprimitive(rtype) and attr in ("keys", "values", "items")):
368 return None
369
370 obj = builder.accept(base)
371 # Note that it is not safe to use fast methods on dict subclasses,
372 # so the corresponding helpers in CPy.h fallback to (inlined)
373 # generic logic.
374 if attr == "keys":
375 return builder.call_c(dict_keys_op, [obj], expr.line)
376 elif attr == "values":
377 return builder.call_c(dict_values_op, [obj], expr.line)
378 else:
379 return builder.call_c(dict_items_op, [obj], expr.line)
380
381
382 @specialize_function("builtins.list")
383 def translate_list_from_generator_call(
384 builder: IRBuilder, expr: CallExpr, callee: RefExpr
385 ) -> Value | None:
386 """Special case for simplest list comprehension.
387
388 For example:
389 list(f(x) for x in some_list/some_tuple/some_str)
390 'translate_list_comprehension()' would take care of other cases
391 if this fails.
392 """
393 if (
394 len(expr.args) == 1
395 and expr.arg_kinds[0] == ARG_POS
396 and isinstance(expr.args[0], GeneratorExpr)
397 ):
398
399 def set_item(x: Value, y: Value, z: Value, line: int) -> None:
400 builder.call_c(new_list_set_item_op, [x, y, z], line)
401
402 return sequence_from_generator_preallocate_helper(
403 builder,
404 expr.args[0],
405 empty_op_llbuilder=builder.builder.new_list_op_with_length,
406 set_item_op=set_item,
407 )
408 return None
409
410
411 @specialize_function("builtins.tuple")
412 def translate_vec_to_tuple(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
413 if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]:
414 arg_type = builder.node_type(expr.args[0])
415 if isinstance(arg_type, RVec) and supports_vec_to_sequence(arg_type):
416 vec = builder.accept(expr.args[0])
417 return vec_to_tuple(builder.builder, vec, expr.line)
418 return None
419
420
421 @specialize_function("builtins.tuple")
422 def translate_tuple_from_generator_call(
423 builder: IRBuilder, expr: CallExpr, callee: RefExpr
424 ) -> Value | None:
425 """Special case for simplest tuple creation from a generator.
426
427 For example:
428 tuple(f(x) for x in some_list/some_tuple/some_str/some_bytes)
429 'translate_safe_generator_call()' would take care of other cases
430 if this fails.
431 """
432 if (
433 len(expr.args) == 1
434 and expr.arg_kinds[0] == ARG_POS
435 and isinstance(expr.args[0], GeneratorExpr)
436 ):
437
438 def set_item(x: Value, y: Value, z: Value, line: int) -> None:
439 builder.call_c(new_tuple_set_item_op, [x, y, z], line)
440
441 return sequence_from_generator_preallocate_helper(
442 builder,
443 expr.args[0],
444 empty_op_llbuilder=builder.builder.new_tuple_with_length,
445 set_item_op=set_item,
446 )
447 return None
448
449
450 @specialize_function("builtins.set")
451 def translate_set_from_generator_call(
452 builder: IRBuilder, expr: CallExpr, callee: RefExpr
453 ) -> Value | None:
454 """Special case for set creation from a generator.
455
456 For example:
457 set(f(...) for ... in iterator/nested_generators...)
458 """
459 if (
460 len(expr.args) == 1
461 and expr.arg_kinds[0] == ARG_POS
462 and isinstance(expr.args[0], GeneratorExpr)
463 ):
464 return translate_set_comprehension(builder, expr.args[0])
465 return None
466
467
468 @specialize_function("builtins.min")
469 @specialize_function("builtins.max")
470 def faster_min_max(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
471 if expr.arg_kinds == [ARG_POS, ARG_POS]:
472 x, y = builder.accept(expr.args[0]), builder.accept(expr.args[1])
473 result = Register(builder.node_type(expr))
474 # CPython evaluates arguments reversely when calling min(...) or max(...)
475 if callee.fullname == "builtins.min":
476 comparison = builder.binary_op(y, x, "<", expr.line)
477 else:
478 comparison = builder.binary_op(y, x, ">", expr.line)
479
480 true_block, false_block, next_block = BasicBlock(), BasicBlock(), BasicBlock()
481 builder.add_bool_branch(comparison, true_block, false_block)
482
483 builder.activate_block(true_block)
484 builder.assign(result, builder.coerce(y, result.type, expr.line), expr.line)
485 builder.goto(next_block)
486
487 builder.activate_block(false_block)
488 builder.assign(result, builder.coerce(x, result.type, expr.line), expr.line)
489 builder.goto(next_block)
490
491 builder.activate_block(next_block)
492 return result
493 return None
494
495
496 @specialize_function("builtins.tuple")
497 @specialize_function("builtins.frozenset")
498 @specialize_function("builtins.dict")
499 @specialize_function("builtins.min")
500 @specialize_function("builtins.max")
501 @specialize_function("builtins.sorted")
502 @specialize_function("collections.OrderedDict")
503 @specialize_function("join", str_rprimitive)
504 @specialize_function("extend", list_rprimitive)
505 @specialize_function("update", dict_rprimitive)
506 @specialize_function("update", set_rprimitive)
507 def translate_safe_generator_call(
508 builder: IRBuilder, expr: CallExpr, callee: RefExpr
509 ) -> Value | None:
510 """Special cases for things that consume iterators where we know we
511 can safely compile a generator into a list.
512 """
513 if (
514 len(expr.args) > 0
515 and expr.arg_kinds[0] == ARG_POS
516 and isinstance(expr.args[0], GeneratorExpr)
517 ):
518 if isinstance(callee, MemberExpr):
519 return builder.gen_method_call(
520 builder.accept(callee.expr),
521 callee.name,
522 (
523 [translate_list_comprehension(builder, expr.args[0])]
524 + [builder.accept(arg) for arg in expr.args[1:]]
525 ),
526 builder.node_type(expr),
527 expr.line,
528 expr.arg_kinds,
529 expr.arg_names,
530 )
531 else:
532 return builder.call_refexpr_with_args(
533 expr,
534 callee,
535 (
536 [translate_list_comprehension(builder, expr.args[0])]
537 + [builder.accept(arg) for arg in expr.args[1:]]
538 ),
539 )
540 return None
541
542
543 @specialize_function("builtins.any")
544 def translate_any_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
545 if (
546 len(expr.args) == 1
547 and expr.arg_kinds == [ARG_POS]
548 and isinstance(expr.args[0], GeneratorExpr)
549 ):
550 return any_all_helper(builder, expr.args[0], builder.false, lambda x: x, builder.true)
551 return None
552
553
554 @specialize_function("builtins.all")
555 def translate_all_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
556 if (
557 len(expr.args) == 1
558 and expr.arg_kinds == [ARG_POS]
559 and isinstance(expr.args[0], GeneratorExpr)
560 ):
561 return any_all_helper(
562 builder,
563 expr.args[0],
564 builder.true,
565 lambda x: builder.unary_op(x, "not", expr.line),
566 builder.false,
567 )
568 return None
569
570
571 def any_all_helper(
572 builder: IRBuilder,
573 gen: GeneratorExpr,
574 initial_value: Callable[[], Value],
575 modify: Callable[[Value], Value],
576 new_value: Callable[[], Value],
577 ) -> Value:
578 init_val = initial_value()
579 retval = Register(bool_rprimitive, line=init_val.line)
580 builder.assign(retval, init_val, init_val.line)
581 loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))
582 true_block, false_block, exit_block = BasicBlock(), BasicBlock(), BasicBlock()
583
584 def gen_inner_stmts() -> None:
585 comparison = modify(builder.accept(gen.left_expr))
586 builder.add_bool_branch(comparison, true_block, false_block)
587 builder.activate_block(true_block)
588 new_val = new_value()
589 builder.assign(retval, new_val, new_val.line)
590 builder.goto(exit_block)
591 builder.activate_block(false_block)
592
593 comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)
594 builder.goto_and_activate(exit_block)
595
596 return retval
597
598
599 @specialize_function("builtins.sum")
600 def translate_sum_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
601 # specialized implementation is used if:
602 # - only one or two arguments given (if not, sum() has been given invalid arguments)
603 # - first argument is a Generator (there is no benefit to optimizing the performance of eg.
604 # sum([1, 2, 3]), so non-Generator Iterables are not handled)
605 if not (
606 len(expr.args) in (1, 2)
607 and expr.arg_kinds[0] == ARG_POS
608 and isinstance(expr.args[0], GeneratorExpr)
609 ):
610 return None
611
612 # handle 'start' argument, if given
613 if len(expr.args) == 2:
614 # ensure call to sum() was properly constructed
615 if expr.arg_kinds[1] not in (ARG_POS, ARG_NAMED):
616 return None
617 start_expr = expr.args[1]
618 else:
619 start_expr = IntExpr(0)
620
621 gen_expr = expr.args[0]
622 target_type = builder.node_type(expr)
623 retval = Register(target_type, line=expr.line)
624 builder.assign(
625 retval, builder.coerce(builder.accept(start_expr), target_type, expr.line), expr.line
626 )
627
628 def gen_inner_stmts() -> None:
629 call_expr = builder.accept(gen_expr.left_expr)
630 builder.assign(
631 retval, builder.binary_op(retval, call_expr, "+", call_expr.line), call_expr.line
632 )
633
634 loop_params = list(
635 zip(gen_expr.indices, gen_expr.sequences, gen_expr.condlists, gen_expr.is_async)
636 )
637 comprehension_helper(builder, loop_params, gen_inner_stmts, gen_expr.line)
638
639 return retval
640
641
642 @specialize_function("dataclasses.field")
643 @specialize_function("attr.ib")
644 @specialize_function("attr.attrib")
645 @specialize_function("attr.Factory")
646 def translate_dataclasses_field_call(
647 builder: IRBuilder, expr: CallExpr, callee: RefExpr
648 ) -> Value | None:
649 """Special case for 'dataclasses.field', 'attr.attrib', and 'attr.Factory'
650 function calls because the results of such calls are type-checked
651 by mypy using the types of the arguments to their respective
652 functions, resulting in attempted coercions by mypyc that throw a
653 runtime error.
654 """
655 builder.types[expr] = AnyType(TypeOfAny.from_error)
656 return None
657
658
659 @specialize_function("builtins.next")
660 def translate_next_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
661 """Special case for calling next() on a generator expression, an
662 idiom that shows up some in mypy.
663
664 For example, next(x for x in l if x.id == 12, None) will
665 generate code that searches l for an element where x.id == 12
666 and produce the first such object, or None if no such element
667 exists.
668 """
669 if not (
670 expr.arg_kinds in ([ARG_POS], [ARG_POS, ARG_POS])
671 and isinstance(expr.args[0], GeneratorExpr)
672 ):
673 return None
674
675 gen = expr.args[0]
676 retval = Register(builder.node_type(expr))
677 default_val = builder.accept(expr.args[1]) if len(expr.args) > 1 else None
678 exit_block = BasicBlock()
679
680 def gen_inner_stmts() -> None:
681 # next takes the first element of the generator, so if
682 # something gets produced, we are done.
683 builder.assign(retval, builder.accept(gen.left_expr), gen.left_expr.line)
684 builder.goto(exit_block)
685
686 loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))
687 comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)
688
689 # Now we need the case for when nothing got hit. If there was
690 # a default value, we produce it, and otherwise we raise
691 # StopIteration.
692 if default_val:
693 builder.assign(retval, default_val, gen.left_expr.line)
694 builder.goto(exit_block)
695 else:
696 builder.add(RaiseStandardError(RaiseStandardError.STOP_ITERATION, None, expr.line))
697 builder.add(Unreachable())
698
699 builder.activate_block(exit_block)
700 return retval
701
702
703 isinstance_primitives: Final = {
704 "builtins.bool": isinstance_bool,
705 "builtins.bytearray": isinstance_bytearray,
706 "builtins.bytes": isinstance_bytes,
707 "builtins.dict": isinstance_dict,
708 "builtins.float": isinstance_float,
709 "builtins.frozenset": isinstance_frozenset,
710 "builtins.int": isinstance_int,
711 "builtins.list": isinstance_list,
712 "builtins.set": isinstance_set,
713 "builtins.str": isinstance_str,
714 "builtins.tuple": isinstance_tuple,
715 "librt.vecs.vec": isinstance_vec,
716 }
717
718
719 @specialize_function("builtins.isinstance")
720 def translate_isinstance(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
721 """Special case for builtins.isinstance.
722
723 Prevent coercions on the thing we are checking the instance of -
724 there is no need to coerce something to a new type before checking
725 what type it is, and the coercion could lead to bugs.
726 """
727 if not (len(expr.args) == 2 and expr.arg_kinds == [ARG_POS, ARG_POS]):
728 return None
729
730 obj_expr = expr.args[0]
731 type_expr = expr.args[1]
732
733 if isinstance(type_expr, TupleExpr) and not type_expr.items:
734 # we can compile this case to a noop
735 return builder.false()
736
737 if isinstance(type_expr, (RefExpr, TupleExpr)):
738 builder.types[obj_expr] = AnyType(TypeOfAny.from_error)
739
740 irs = builder.flatten_classes(type_expr)
741 if irs is not None:
742 can_borrow = all(
743 ir.is_ext_class and not ir.inherits_python and not ir.allow_interpreted_subclasses
744 for ir in irs
745 )
746 obj = builder.accept(obj_expr, can_borrow=can_borrow)
747 return builder.builder.isinstance_helper(obj, irs, expr.line)
748
749 if isinstance(type_expr, RefExpr):
750 node = type_expr.node
751 if node:
752 desc = isinstance_primitives.get(node.fullname)
753 if desc:
754 obj = builder.accept(obj_expr)
755 return builder.primitive_op(desc, [obj], expr.line)
756
757 elif isinstance(type_expr, TupleExpr):
758 node_names: list[str] = []
759 for item in type_expr.items:
760 if not isinstance(item, RefExpr):
761 return None
762 if item.node is None:
763 return None
764 if item.node.fullname not in node_names:
765 node_names.append(item.node.fullname)
766
767 descs = [isinstance_primitives.get(fullname) for fullname in node_names]
768 if None in descs:
769 # not all types are primitive types, abort
770 return None
771
772 obj = builder.accept(obj_expr)
773
774 retval = Register(bool_rprimitive)
775 pass_block = BasicBlock()
776 fail_block = BasicBlock()
777 exit_block = BasicBlock()
778
779 # Chain the checks: if any succeed, jump to pass_block; else, continue
780 for i, desc in enumerate(descs):
781 is_last = i == len(descs) - 1
782 next_block = fail_block if is_last else BasicBlock()
783 builder.add_bool_branch(
784 builder.primitive_op(cast(PrimitiveDescription, desc), [obj], expr.line),
785 pass_block,
786 next_block,
787 )
788 if not is_last:
789 builder.activate_block(next_block)
790
791 # If any check passed
792 builder.activate_block(pass_block)
793 builder.assign(retval, builder.true(), expr.line)
794 builder.goto(exit_block)
795
796 # If all checks failed
797 builder.activate_block(fail_block)
798 builder.assign(retval, builder.false(), expr.line)
799 builder.goto(exit_block)
800
801 # Return the result
802 builder.activate_block(exit_block)
803 return retval
804
805 return None
806
807
808 @specialize_function("setdefault", dict_rprimitive)
809 def translate_dict_setdefault(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
810 """Special case for 'dict.setdefault' which would only construct
811 default empty collection when needed.
812
813 The dict_setdefault_spec_init_op checks whether the dict contains
814 the key and would construct the empty collection only once.
815
816 For example, this specializer works for the following cases:
817 d.setdefault(key, set()).add(value)
818 d.setdefault(key, []).append(value)
819 d.setdefault(key, {})[inner_key] = inner_val
820 """
821 if (
822 len(expr.args) == 2
823 and expr.arg_kinds == [ARG_POS, ARG_POS]
824 and isinstance(callee, MemberExpr)
825 ):
826 arg = expr.args[1]
827 if isinstance(arg, ListExpr):
828 if len(arg.items):
829 return None
830 data_type = Integer(1, c_int_rprimitive, expr.line)
831 elif isinstance(arg, DictExpr):
832 if len(arg.items):
833 return None
834 data_type = Integer(2, c_int_rprimitive, expr.line)
835 elif (
836 isinstance(arg, CallExpr)
837 and isinstance(arg.callee, NameExpr)
838 and arg.callee.fullname == "builtins.set"
839 ):
840 if len(arg.args):
841 return None
842 data_type = Integer(3, c_int_rprimitive, expr.line)
843 else:
844 return None
845
846 callee_dict = builder.accept(callee.expr)
847 key_val = builder.accept(expr.args[0])
848 return builder.call_c(
849 dict_setdefault_spec_init_op, [callee_dict, key_val, data_type], expr.line
850 )
851 return None
852
853
854 @specialize_function("format", str_rprimitive)
855 def translate_str_format(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
856 if isinstance(callee, MemberExpr):
857 folded_callee = constant_fold_expr(builder, callee.expr)
858 if isinstance(folded_callee, str) and expr.arg_kinds.count(ARG_POS) == len(expr.arg_kinds):
859 tokens = tokenizer_format_call(folded_callee)
860 if tokens is None:
861 return None
862 literals, format_ops = tokens
863 # Convert variables to strings
864 substitutions = convert_format_expr_to_str(builder, format_ops, expr.args, expr.line)
865 if substitutions is None:
866 return None
867 return join_formatted_strings(builder, literals, substitutions, expr.line)
868 return None
869
870
871 @specialize_function("join", str_rprimitive)
872 def translate_fstring(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
873 """Special case for f-string, which is translated into str.join()
874 in mypy AST.
875
876 This specializer optimizes simplest f-strings which don't contain
877 any format operation.
878 """
879 if (
880 isinstance(callee, MemberExpr)
881 and isinstance(callee.expr, StrExpr)
882 and callee.expr.value == ""
883 and expr.arg_kinds == [ARG_POS]
884 and isinstance(expr.args[0], ListExpr)
885 ):
886 for item in expr.args[0].items:
887 if isinstance(item, StrExpr):
888 continue
889 elif isinstance(item, CallExpr):
890 if not isinstance(item.callee, MemberExpr) or item.callee.name != "format":
891 return None
892 elif (
893 not isinstance(item.callee.expr, StrExpr) or item.callee.expr.value != "{:{}}"
894 ):
895 return None
896
897 if not isinstance(item.args[1], StrExpr) or item.args[1].value != "":
898 return None
899 else:
900 return None
901
902 format_ops = []
903 exprs: list[Expression] = []
904
905 for item in expr.args[0].items:
906 if isinstance(item, StrExpr) and item.value != "":
907 format_ops.append(FormatOp.STR)
908 exprs.append(item)
909 elif isinstance(item, CallExpr):
910 format_ops.append(FormatOp.STR)
911 exprs.append(item.args[0])
912
913 def get_literal_str(expr: Expression) -> str | None:
914 if isinstance(expr, StrExpr):
915 return expr.value
916 elif isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_final:
917 final_value = expr.node.final_value
918 if final_value is not None:
919 return str(final_value)
920 return None
921
922 for i in range(len(exprs) - 1):
923 while (
924 len(exprs) >= i + 2
925 and (first := get_literal_str(exprs[i])) is not None
926 and (second := get_literal_str(exprs[i + 1])) is not None
927 ):
928 exprs = [*exprs[:i], StrExpr(first + second), *exprs[i + 2 :]]
929 format_ops = [*format_ops[:i], FormatOp.STR, *format_ops[i + 2 :]]
930
931 substitutions = convert_format_expr_to_str(builder, format_ops, exprs, expr.line)
932 if substitutions is None:
933 return None
934
935 return join_formatted_strings(builder, None, substitutions, expr.line)
936 return None
937
938
939 @specialize_function("encode", str_rprimitive)
940 def str_encode_fast_path(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
941 """Specialize common cases of str.encode for most used encodings and strict errors."""
942
943 if not isinstance(callee, MemberExpr):
944 return None
945
946 # We can only specialize if we have string literals as args
947 if len(expr.arg_kinds) > 0 and not isinstance(expr.args[0], StrExpr):
948 return None
949 if len(expr.arg_kinds) > 1 and not isinstance(expr.args[1], StrExpr):
950 return None
951
952 encoding = "utf8"
953 errors = "strict"
954 if len(expr.arg_kinds) > 0 and isinstance(expr.args[0], StrExpr):
955 if expr.arg_kinds[0] == ARG_NAMED:
956 if expr.arg_names[0] == "encoding":
957 encoding = expr.args[0].value
958 elif expr.arg_names[0] == "errors":
959 errors = expr.args[0].value
960 elif expr.arg_kinds[0] == ARG_POS:
961 encoding = expr.args[0].value
962 else:
963 return None
964 if len(expr.arg_kinds) > 1 and isinstance(expr.args[1], StrExpr):
965 if expr.arg_kinds[1] == ARG_NAMED:
966 if expr.arg_names[1] == "encoding":
967 encoding = expr.args[1].value
968 elif expr.arg_names[1] == "errors":
969 errors = expr.args[1].value
970 elif expr.arg_kinds[1] == ARG_POS:
971 errors = expr.args[1].value
972 else:
973 return None
974
975 if errors != "strict":
976 # We can only specialize strict errors
977 return None
978
979 encoding = encoding.lower().replace("-", "").replace("_", "") # normalize
980 # Specialized encodings and their accepted aliases
981 if encoding in ["u8", "utf", "utf8", "cp65001"]:
982 return builder.call_c(str_encode_utf8_strict, [builder.accept(callee.expr)], expr.line)
983 elif encoding in ["646", "ascii", "usascii"]:
984 return builder.call_c(str_encode_ascii_strict, [builder.accept(callee.expr)], expr.line)
985 elif encoding in ["iso88591", "8859", "cp819", "latin", "latin1", "l1"]:
986 return builder.call_c(str_encode_latin1_strict, [builder.accept(callee.expr)], expr.line)
987
988 return None
989
990
991 @specialize_function("decode", bytes_rprimitive)
992 def bytes_decode_fast_path(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
993 """Specialize common cases of obj.decode for most used encodings and strict errors."""
994
995 if not isinstance(callee, MemberExpr):
996 return None
997
998 # We can only specialize if we have string literals as args
999 if len(expr.arg_kinds) > 0 and not isinstance(expr.args[0], StrExpr):
1000 return None
1001 if len(expr.arg_kinds) > 1 and not isinstance(expr.args[1], StrExpr):
1002 return None
1003
1004 encoding = "utf8"
1005 errors = "strict"
1006 if len(expr.arg_kinds) > 0 and isinstance(expr.args[0], StrExpr):
1007 if expr.arg_kinds[0] == ARG_NAMED:
1008 if expr.arg_names[0] == "encoding":
1009 encoding = expr.args[0].value
1010 elif expr.arg_names[0] == "errors":
1011 errors = expr.args[0].value
1012 elif expr.arg_kinds[0] == ARG_POS:
1013 encoding = expr.args[0].value
1014 else:
1015 return None
1016 if len(expr.arg_kinds) > 1 and isinstance(expr.args[1], StrExpr):
1017 if expr.arg_kinds[1] == ARG_NAMED:
1018 if expr.arg_names[1] == "encoding":
1019 encoding = expr.args[1].value
1020 elif expr.arg_names[1] == "errors":
1021 errors = expr.args[1].value
1022 elif expr.arg_kinds[1] == ARG_POS:
1023 errors = expr.args[1].value
1024 else:
1025 return None
1026
1027 if errors != "strict":
1028 # We can only specialize strict errors
1029 return None
1030
1031 encoding = encoding.lower().replace("_", "-") # normalize
1032 # Specialized encodings and their accepted aliases
1033 if encoding in ["u8", "utf", "utf8", "utf-8", "cp65001"]:
1034 return builder.call_c(bytes_decode_utf8_strict, [builder.accept(callee.expr)], expr.line)
1035 elif encoding in ["646", "ascii", "usascii", "us-ascii"]:
1036 return builder.call_c(bytes_decode_ascii_strict, [builder.accept(callee.expr)], expr.line)
1037 elif encoding in [
1038 "iso8859-1",
1039 "iso-8859-1",
1040 "8859",
1041 "cp819",
1042 "latin",
1043 "latin1",
1044 "latin-1",
1045 "l1",
1046 ]:
1047 return builder.call_c(bytes_decode_latin1_strict, [builder.accept(callee.expr)], expr.line)
1048
1049 return None
1050
1051
1052 @specialize_function("mypy_extensions.i64")
1053 def translate_i64(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1054 if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:
1055 return None
1056 arg = expr.args[0]
1057 arg_type = builder.node_type(arg)
1058 if is_int64_rprimitive(arg_type):
1059 return builder.accept(arg)
1060 elif is_int32_rprimitive(arg_type) or is_int16_rprimitive(arg_type):
1061 val = builder.accept(arg)
1062 return builder.add(Extend(val, int64_rprimitive, signed=True, line=expr.line))
1063 elif is_uint8_rprimitive(arg_type):
1064 val = builder.accept(arg)
1065 return builder.add(Extend(val, int64_rprimitive, signed=False, line=expr.line))
1066 elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type):
1067 val = builder.accept(arg)
1068 return builder.coerce(val, int64_rprimitive, expr.line)
1069 return None
1070
1071
1072 @specialize_function("mypy_extensions.i32")
1073 def translate_i32(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1074 if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:
1075 return None
1076 arg = expr.args[0]
1077 arg_type = builder.node_type(arg)
1078 if is_int32_rprimitive(arg_type):
1079 return builder.accept(arg)
1080 elif is_int64_rprimitive(arg_type):
1081 val = builder.accept(arg)
1082 return builder.add(Truncate(val, int32_rprimitive, line=expr.line))
1083 elif is_int16_rprimitive(arg_type):
1084 val = builder.accept(arg)
1085 return builder.add(Extend(val, int32_rprimitive, signed=True, line=expr.line))
1086 elif is_uint8_rprimitive(arg_type):
1087 val = builder.accept(arg)
1088 return builder.add(Extend(val, int32_rprimitive, signed=False, line=expr.line))
1089 elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type):
1090 val = builder.accept(arg)
1091 val = truncate_literal(val, int32_rprimitive)
1092 return builder.coerce(val, int32_rprimitive, expr.line)
1093 return None
1094
1095
1096 @specialize_function("mypy_extensions.i16")
1097 def translate_i16(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1098 if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:
1099 return None
1100 arg = expr.args[0]
1101 arg_type = builder.node_type(arg)
1102 if is_int16_rprimitive(arg_type):
1103 return builder.accept(arg)
1104 elif is_int32_rprimitive(arg_type) or is_int64_rprimitive(arg_type):
1105 val = builder.accept(arg)
1106 return builder.add(Truncate(val, int16_rprimitive, line=expr.line))
1107 elif is_uint8_rprimitive(arg_type):
1108 val = builder.accept(arg)
1109 return builder.add(Extend(val, int16_rprimitive, signed=False, line=expr.line))
1110 elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type):
1111 val = builder.accept(arg)
1112 val = truncate_literal(val, int16_rprimitive)
1113 return builder.coerce(val, int16_rprimitive, expr.line)
1114 return None
1115
1116
1117 @specialize_function("mypy_extensions.u8")
1118 def translate_u8(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1119 if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:
1120 return None
1121 arg = expr.args[0]
1122 arg_type = builder.node_type(arg)
1123 if is_uint8_rprimitive(arg_type):
1124 return builder.accept(arg)
1125 elif (
1126 is_int16_rprimitive(arg_type)
1127 or is_int32_rprimitive(arg_type)
1128 or is_int64_rprimitive(arg_type)
1129 ):
1130 val = builder.accept(arg)
1131 return builder.add(Truncate(val, uint8_rprimitive, line=expr.line))
1132 elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type):
1133 val = builder.accept(arg)
1134 val = truncate_literal(val, uint8_rprimitive)
1135 return builder.coerce(val, uint8_rprimitive, expr.line)
1136 return None
1137
1138
1139 def truncate_literal(value: Value, rtype: RPrimitive) -> Value:
1140 """If value is an integer literal value, truncate it to given native int rtype.
1141
1142 For example, truncate 256 into 0 if rtype is u8.
1143 """
1144 if not isinstance(value, Integer):
1145 return value # Not a literal, nothing to do
1146 x = value.numeric_value()
1147 max_unsigned = (1 << (rtype.size * 8)) - 1
1148 x = x & max_unsigned
1149 if rtype.is_signed and x >= (max_unsigned + 1) // 2:
1150 # Adjust to make it a negative value
1151 x -= max_unsigned + 1
1152 return Integer(x, rtype)
1153
1154
1155 @specialize_function("builtins.int")
1156 def translate_int(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1157 if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:
1158 return None
1159 arg = expr.args[0]
1160 arg_type = builder.node_type(arg)
1161 if (
1162 is_bool_rprimitive(arg_type)
1163 or is_int_rprimitive(arg_type)
1164 or is_fixed_width_rtype(arg_type)
1165 ):
1166 src = builder.accept(arg)
1167 return builder.coerce(src, int_rprimitive, expr.line)
1168 return None
1169
1170
1171 @specialize_function("builtins.bool")
1172 def translate_bool(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1173 if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:
1174 return None
1175 arg = expr.args[0]
1176 src = builder.accept(arg)
1177 return builder.builder.bool_value(src)
1178
1179
1180 @specialize_function("builtins.float")
1181 def translate_float(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1182 if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:
1183 return None
1184 arg = expr.args[0]
1185 arg_type = builder.node_type(arg)
1186 if is_float_rprimitive(arg_type):
1187 # No-op float conversion.
1188 return builder.accept(arg)
1189 return None
1190
1191
1192 @specialize_function("builtins.ord")
1193 def translate_ord(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1194 if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:
1195 return None
1196 arg_expr = expr.args[0]
1197 arg = constant_fold_expr(builder, arg_expr)
1198 if isinstance(arg, (str, bytes)) and len(arg) == 1:
1199 return Integer(ord(arg))
1200
1201 # Check for ord(s[i]) where s is str and i is an integer
1202 if isinstance(arg_expr, IndexExpr):
1203 # Check base type
1204 base_type = builder.node_type(arg_expr.base)
1205 if is_str_rprimitive(base_type):
1206 # Check index type
1207 index_expr = arg_expr.index
1208 index_type = builder.node_type(index_expr)
1209 if is_tagged(index_type) or is_fixed_width_rtype(index_type):
1210 # This is ord(s[i]) where s is str and i is an integer.
1211 # Generate specialized inline code using the helper.
1212 result = translate_getitem_with_bounds_check(
1213 builder,
1214 arg_expr.base,
1215 [arg_expr.index],
1216 expr,
1217 str_adjust_index_op,
1218 str_range_check_op,
1219 str_get_item_unsafe_as_int_op,
1220 )
1221 return result
1222
1223 return None
1224
1225
1226 def is_object(callee: RefExpr) -> bool:
1227 """Returns True for object.<name> calls."""
1228 return (
1229 isinstance(callee, MemberExpr)
1230 and isinstance(callee.expr, NameExpr)
1231 and callee.expr.fullname == "builtins.object"
1232 )
1233
1234
1235 def is_super_or_object(expr: CallExpr, callee: RefExpr) -> bool:
1236 """Returns True for super().<name> or object.<name> calls."""
1237 return isinstance(expr.callee, SuperExpr) or is_object(callee)
1238
1239
1240 @specialize_function("__new__", object_rprimitive)
1241 def translate_object_new(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1242 fn = builder.fn_info
1243 if fn.name != "__new__" or not is_super_or_object(expr, callee):
1244 return None
1245
1246 ir = builder.get_current_class_ir()
1247 if ir is None:
1248 return None
1249
1250 call = '"object.__new__()"'
1251 if not ir.is_ext_class:
1252 builder.error(f"{call} not supported for non-extension classes", expr.line)
1253 return None
1254 if ir.inherits_python:
1255 builder.error(
1256 f"{call} not supported for classes inheriting from non-native classes", expr.line
1257 )
1258 return None
1259 if len(expr.args) != 1:
1260 builder.error(f"{call} supported only with 1 argument, got {len(expr.args)}", expr.line)
1261 return None
1262
1263 typ_arg = expr.args[0]
1264 method_args = fn.fitem.arg_names
1265 if isinstance(typ_arg, NameExpr) and len(method_args) > 0 and method_args[0] == typ_arg.name:
1266 subtype = builder.accept(expr.args[0])
1267 subs = ir.subclasses()
1268 if subs is not None and len(subs) == 0:
1269 return builder.add(Call(ir.setup, [subtype], expr.line))
1270 # Call a function that dynamically resolves the setup function of extension classes from the type object.
1271 # This is necessary because the setup involves default attribute initialization and setting up
1272 # the vtable which are specific to a given type and will not work if a subtype is created using
1273 # the setup function of its base.
1274 return builder.call_c(setup_object, [subtype], expr.line)
1275
1276 return None
1277
1278
1279 @specialize_function("__setattr__", object_rprimitive)
1280 def translate_object_setattr(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1281 is_super = isinstance(expr.callee, SuperExpr)
1282 is_object_callee = is_object(callee)
1283 if not ((is_super and len(expr.args) >= 2) or (is_object_callee and len(expr.args) >= 3)):
1284 return None
1285
1286 self_reg = builder.accept(expr.args[0]) if is_object_callee else builder.self()
1287 ir = builder.get_current_class_ir()
1288 if ir and (not ir.is_ext_class or ir.builtin_base or ir.inherits_python):
1289 return None
1290 # Need to offset by 1 for super().__setattr__ calls because there is no self arg in this case.
1291 name_idx = 0 if is_super else 1
1292 value_idx = 1 if is_super else 2
1293 attr_name = expr.args[name_idx]
1294 attr_value = expr.args[value_idx]
1295 value = builder.accept(attr_value)
1296
1297 if isinstance(attr_name, StrExpr) and ir and ir.has_attr(attr_name.value):
1298 name = attr_name.value
1299 value = builder.coerce(value, ir.attributes[name], expr.line)
1300 return builder.add(SetAttr(self_reg, name, value, expr.line))
1301
1302 name_reg = builder.accept(attr_name)
1303 return builder.call_c(generic_setattr, [self_reg, name_reg, value], expr.line)
1304
1305
1306 @specialize_function("to_bytes", int_rprimitive)
1307 def specialize_int_to_bytes(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1308 # int.to_bytes(length, byteorder, signed=False)
1309 if any(kind not in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds):
1310 return None
1311 if not isinstance(callee, MemberExpr):
1312 return None
1313 length_expr: Expression | None = None
1314 byteorder_expr: Expression | None = None
1315 signed_expr: Expression | None = None
1316 positional_index = 0
1317 for name, arg in zip(expr.arg_names, expr.args):
1318 if name is None:
1319 if positional_index == 0:
1320 length_expr = arg
1321 elif positional_index == 1:
1322 byteorder_expr = arg
1323 elif positional_index == 2:
1324 signed_expr = arg
1325 else:
1326 return None
1327 positional_index += 1
1328 elif name == "length":
1329 if length_expr is not None:
1330 return None
1331 length_expr = arg
1332 elif name == "byteorder":
1333 if byteorder_expr is not None:
1334 return None
1335 byteorder_expr = arg
1336 elif name == "signed":
1337 if signed_expr is not None:
1338 return None
1339 signed_expr = arg
1340 else:
1341 return None
1342 if length_expr is None or byteorder_expr is None:
1343 return None
1344
1345 signed_is_bool = True
1346 if signed_expr is not None:
1347 signed_is_bool = is_bool_rprimitive(builder.node_type(signed_expr))
1348 if not (
1349 is_int_rprimitive(builder.node_type(length_expr))
1350 and is_str_rprimitive(builder.node_type(byteorder_expr))
1351 and signed_is_bool
1352 ):
1353 return None
1354
1355 self_arg = builder.accept(callee.expr)
1356 length_arg = builder.accept(length_expr)
1357 if signed_expr is None:
1358 signed_arg = builder.false()
1359 else:
1360 signed_arg = builder.accept(signed_expr)
1361 if isinstance(byteorder_expr, StrExpr):
1362 if byteorder_expr.value == "little":
1363 return builder.call_c(
1364 int_to_little_endian_op, [self_arg, length_arg, signed_arg], expr.line
1365 )
1366 elif byteorder_expr.value == "big":
1367 return builder.call_c(
1368 int_to_big_endian_op, [self_arg, length_arg, signed_arg], expr.line
1369 )
1370 # Fallback to generic primitive op
1371 byteorder_arg = builder.accept(byteorder_expr)
1372 return builder.call_c(
1373 int_to_bytes_op, [self_arg, length_arg, byteorder_arg, signed_arg], expr.line
1374 )
1375
1376
1377 def translate_getitem_with_bounds_check(
1378 builder: IRBuilder,
1379 base_expr: Expression,
1380 args: list[Expression],
1381 ctx_expr: Expression,
1382 adjust_index_op: PrimitiveDescription,
1383 range_check_op: PrimitiveDescription,
1384 get_item_unsafe_op: PrimitiveDescription,
1385 ) -> Value | None:
1386 """Shared helper for optimized __getitem__ with bounds checking.
1387
1388 This implements the common pattern of:
1389 1. Adjusting negative indices
1390 2. Checking if index is in valid range
1391 3. Raising IndexError if out of range
1392 4. Getting the item if in range
1393
1394 Args:
1395 builder: The IR builder
1396 base_expr: The base object expression
1397 args: The arguments to __getitem__ (should be length 1)
1398 ctx_expr: The context expression for line numbers
1399 adjust_index_op: Primitive op to adjust negative indices
1400 range_check_op: Primitive op to check if index is in valid range
1401 get_item_unsafe_op: Primitive op to get item (no bounds checking)
1402
1403 Returns:
1404 The result value, or None if optimization doesn't apply
1405 """
1406 # Check that we have exactly one argument
1407 if len(args) != 1:
1408 return None
1409
1410 # Get the object
1411 obj = builder.accept(base_expr)
1412
1413 # Get the index argument
1414 index = builder.accept(args[0])
1415
1416 # Adjust the index (handle negative indices)
1417 adjusted_index = builder.primitive_op(adjust_index_op, [obj, index], ctx_expr.line)
1418
1419 # Check if the adjusted index is in valid range
1420 range_check = builder.primitive_op(range_check_op, [obj, adjusted_index], ctx_expr.line)
1421
1422 # Create blocks for branching
1423 valid_block = BasicBlock()
1424 invalid_block = BasicBlock()
1425
1426 builder.add_bool_branch(range_check, valid_block, invalid_block)
1427
1428 # Handle invalid index - raise IndexError
1429 builder.activate_block(invalid_block)
1430 builder.add(
1431 RaiseStandardError(RaiseStandardError.INDEX_ERROR, "index out of range", ctx_expr.line)
1432 )
1433 builder.add(Unreachable())
1434
1435 # Handle valid index - get the item
1436 builder.activate_block(valid_block)
1437 result = builder.primitive_op(get_item_unsafe_op, [obj, adjusted_index], ctx_expr.line)
1438
1439 return result
1440
1441
1442 @specialize_dunder("__getitem__", bytes_writer_rprimitive)
1443 def translate_bytes_writer_get_item(
1444 builder: IRBuilder, base_expr: Expression, args: list[Expression], ctx_expr: Expression
1445 ) -> Value | None:
1446 """Optimized BytesWriter.__getitem__ implementation with bounds checking."""
1447 return translate_getitem_with_bounds_check(
1448 builder,
1449 base_expr,
1450 args,
1451 ctx_expr,
1452 bytes_writer_adjust_index_op,
1453 bytes_writer_range_check_op,
1454 bytes_writer_get_item_unsafe_op,
1455 )
1456
1457
1458 @specialize_dunder("__setitem__", bytes_writer_rprimitive)
1459 def translate_bytes_writer_set_item(
1460 builder: IRBuilder, base_expr: Expression, args: list[Expression], ctx_expr: Expression
1461 ) -> Value | None:
1462 """Optimized BytesWriter.__setitem__ implementation with bounds checking."""
1463 # Check that we have exactly two arguments (index and value)
1464 if len(args) != 2:
1465 return None
1466
1467 # Get the BytesWriter object
1468 obj = builder.accept(base_expr)
1469
1470 # Get the index and value arguments
1471 index = builder.accept(args[0])
1472 value = builder.accept(args[1])
1473
1474 # Adjust the index (handle negative indices)
1475 adjusted_index = builder.primitive_op(
1476 bytes_writer_adjust_index_op, [obj, index], ctx_expr.line
1477 )
1478
1479 # Check if the adjusted index is in valid range
1480 range_check = builder.primitive_op(
1481 bytes_writer_range_check_op, [obj, adjusted_index], ctx_expr.line
1482 )
1483
1484 # Create blocks for branching
1485 valid_block = BasicBlock()
1486 invalid_block = BasicBlock()
1487
1488 builder.add_bool_branch(range_check, valid_block, invalid_block)
1489
1490 # Handle invalid index - raise IndexError
1491 builder.activate_block(invalid_block)
1492 builder.add(
1493 RaiseStandardError(RaiseStandardError.INDEX_ERROR, "index out of range", ctx_expr.line)
1494 )
1495 builder.add(Unreachable())
1496
1497 # Handle valid index - set the item
1498 builder.activate_block(valid_block)
1499 builder.primitive_op(
1500 bytes_writer_set_item_unsafe_op, [obj, adjusted_index, value], ctx_expr.line
1501 )
1502
1503 return builder.none()
1504
1505
1506 @specialize_dunder("__getitem__", string_writer_rprimitive)
1507 def translate_string_writer_get_item(
1508 builder: IRBuilder, base_expr: Expression, args: list[Expression], ctx_expr: Expression
1509 ) -> Value | None:
1510 """Optimized StringWriter.__getitem__ implementation with bounds checking."""
1511 return translate_getitem_with_bounds_check(
1512 builder,
1513 base_expr,
1514 args,
1515 ctx_expr,
1516 string_writer_adjust_index_op,
1517 string_writer_range_check_op,
1518 string_writer_get_item_unsafe_op,
1519 )
1520
1521
1522 @specialize_dunder("__getitem__", bytes_rprimitive)
1523 def translate_bytes_get_item(
1524 builder: IRBuilder, base_expr: Expression, args: list[Expression], ctx_expr: Expression
1525 ) -> Value | None:
1526 """Optimized bytes.__getitem__ implementation with bounds checking."""
1527 return translate_getitem_with_bounds_check(
1528 builder,
1529 base_expr,
1530 args,
1531 ctx_expr,
1532 bytes_adjust_index_op,
1533 bytes_range_check_op,
1534 bytes_get_item_unsafe_op,
1535 )
1536
1537
1538 @specialize_function("librt.vecs.append")
1539 def translate_vec_append(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1540 if len(expr.args) == 2 and expr.arg_kinds == [ARG_POS, ARG_POS]:
1541 vec_arg = expr.args[0]
1542 item_arg = expr.args[1]
1543 vec_type = builder.node_type(vec_arg)
1544 if isinstance(vec_type, RVec):
1545 vec_value = builder.accept(vec_arg)
1546 arg_value = builder.accept(item_arg)
1547 return vec_append(builder.builder, vec_value, arg_value, item_arg.line)
1548 return None
1549
1550
1551 @specialize_function("librt.vecs.extend")
1552 def translate_vec_extend(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1553 if len(expr.args) == 2 and expr.arg_kinds == [ARG_POS, ARG_POS]:
1554 vec_arg = expr.args[0]
1555 iter_arg = expr.args[1]
1556 vec_type = builder.node_type(vec_arg)
1557 if isinstance(vec_type, RVec):
1558 vec_value = builder.accept(vec_arg)
1559 iter_value = builder.accept(iter_arg)
1560 return vec_extend(builder.builder, vec_value, iter_value, iter_arg.line)
1561 return None
1562
1563
1564 @specialize_function("librt.vecs.remove")
1565 def translate_vec_remove(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1566 if len(expr.args) == 2 and expr.arg_kinds == [ARG_POS, ARG_POS]:
1567 vec_arg = expr.args[0]
1568 item_arg = expr.args[1]
1569 vec_type = builder.node_type(vec_arg)
1570 if isinstance(vec_type, RVec):
1571 vec_value = builder.accept(vec_arg)
1572 arg_value = builder.accept(item_arg)
1573 return vec_remove(builder.builder, vec_value, arg_value, item_arg.line)
1574 return None
1575
1576
1577 @specialize_function("librt.vecs.pop")
1578 def translate_vec_pop(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:
1579 if 1 <= len(expr.args) <= 2 and all(kind == ARG_POS for kind in expr.arg_kinds):
1580 vec_arg = expr.args[0]
1581 vec_type = builder.node_type(vec_arg)
1582 if isinstance(vec_type, RVec):
1583 vec_value = builder.accept(vec_arg)
1584 if len(expr.args) == 2:
1585 index_value = builder.accept(expr.args[1])
1586 else:
1587 index_value = Integer(-1, int64_rprimitive)
1588 return vec_pop(builder.builder, vec_value, index_value, vec_arg.line)
1589 return None