Debian Codegraph @

mypyc/ir/rtypes.py

raw
1 """Types used in the intermediate representation.
2
3 These are runtime types (RTypes), as opposed to mypy Type objects.
4 The latter are only used during type checking and not directly used at
5 runtime. Runtime types are derived from mypy types, but there's no
6 simple one-to-one correspondence. (Here 'runtime' means 'runtime
7 checked'.)
8
9 The generated IR ensures some runtime type safety properties based on
10 RTypes. Compiled code can assume that the runtime value matches the
11 static RType of a value. If the RType of a register is 'builtins.str'
12 (str_rprimitive), for example, the generated IR will ensure that the
13 register will have a 'str' object.
14
15 RTypes are simpler and less expressive than mypy (or PEP 484)
16 types. For example, all mypy types of form 'list[T]' (for arbitrary T)
17 are erased to the single RType 'builtins.list' (list_rprimitive).
18
19 mypyc.irbuild.mapper.Mapper.type_to_rtype converts mypy Types to mypyc
20 RTypes.
21
22 NOTE: As a convention, we don't create subclasses of concrete RType
23 subclasses (e.g. you shouldn't define a subclass of RTuple, which
24 is a concrete class). We prefer a flat class hierarchy.
25
26 If you want to introduce a variant of an existing class, you'd
27 typically add an attribute (e.g. a flag) to an existing concrete
28 class to enable the new behavior. In rare cases, adding a new
29 abstract base class could also be an option. Adding a completely
30 separate class and sharing some functionality using module-level
31 helper functions may also be reasonable.
32
33 This makes it possible to use isinstance(x, <concrete RType
34 subclass>) checks without worrying about potential subclasses
35 and avoids most trouble caused by implementation inheritance.
36 """
37
38 from __future__ import annotations
39
40 from abc import abstractmethod
41 from typing import TYPE_CHECKING, ClassVar, Final, Generic, TypeGuard, TypeVar, Union, final
42
43 from mypyc.common import HAVE_IMMORTAL, IS_32_BIT_PLATFORM, PLATFORM_SIZE, JsonDict, short_name
44 from mypyc.ir.deps import LIBRT_RANDOM, LIBRT_STRINGS, LIBRT_THREADING, LIBRT_VECS, Dependency
45 from mypyc.namegen import NameGenerator
46
47 if TYPE_CHECKING:
48 from mypyc.ir.class_ir import ClassIR
49 from mypyc.ir.ops import DeserMaps
50
51 T = TypeVar("T")
52
53
54 class RType:
55 """Abstract base class for runtime types (erased, only concrete; no generics)."""
56
57 name: str
58 # If True, the type has a special unboxed representation. If False, the
59 # type is represented as PyObject *. Even if True, the representation
60 # may contain pointers.
61 is_unboxed = False
62 # This is the C undefined value for this type. It's used for initialization
63 # if there's no value yet, and for function return value on error/exception.
64 #
65 # TODO: This shouldn't be specific to C or a string
66 c_undefined: str
67 # If unboxed: does the unboxed version use reference counting?
68 is_refcounted = True
69 # C type; use Emitter.ctype() to access
70 _ctype: str
71 # If True, error/undefined value overlaps with a valid value. To
72 # detect an exception, PyErr_Occurred() must be used in addition
73 # to checking for error value as the return value of a function.
74 #
75 # For example, no i64 value can be reserved for error value, so we
76 # pick an arbitrary value (-113) to signal error, but this is
77 # also a valid non-error value. The chosen value is rare as a
78 # normal, non-error value, so most of the time we can avoid calling
79 # PyErr_Occurred() when checking for errors raised by called
80 # functions.
81 #
82 # This also means that if an attribute with this type might be
83 # undefined, we can't just rely on the error value to signal this.
84 # Instead, we add a bitfield to keep track whether attributes with
85 # "error overlap" have a value. If there is no value, AttributeError
86 # is raised on attribute read. Parameters with default values also
87 # use the bitfield trick to indicate whether the caller passed a
88 # value. (If we can determine that an attribute is "always defined",
89 # we never raise an AttributeError and don't need the bitfield
90 # entry.)
91 error_overlap = False
92 dependencies: tuple[Dependency, ...] | None = None
93
94 @abstractmethod
95 def accept(self, visitor: RTypeVisitor[T]) -> T:
96 raise NotImplementedError()
97
98 def short_name(self) -> str:
99 return short_name(self.name)
100
101 @property
102 @abstractmethod
103 def may_be_immortal(self) -> bool:
104 raise NotImplementedError
105
106 def __str__(self) -> str:
107 return short_name(self.name)
108
109 def __repr__(self) -> str:
110 return "<%s>" % self.__class__.__name__
111
112 def serialize(self) -> JsonDict | str:
113 raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance")
114
115
116 def deserialize_type(data: JsonDict | str, ctx: DeserMaps) -> RType:
117 """Deserialize a JSON-serialized RType.
118
119 Arguments:
120 data: The decoded JSON of the serialized type
121 ctx: The deserialization maps to use
122 """
123 # Since there are so few types, we just case on them directly. If
124 # more get added we should switch to a system like mypy.types
125 # uses.
126 if isinstance(data, str):
127 if data in ctx.classes:
128 return RInstance(ctx.classes[data])
129 elif data in RPrimitive.primitive_map:
130 return RPrimitive.primitive_map[data]
131 elif data == "void":
132 return RVoid()
133 else:
134 assert False, f"Can't find class {data}"
135 elif data[".class"] == "RTuple":
136 return RTuple.deserialize(data, ctx)
137 elif data[".class"] == "RUnion":
138 return RUnion.deserialize(data, ctx)
139 elif data[".class"] == "RVec":
140 return RVec.deserialize(data, ctx)
141 raise NotImplementedError("unexpected .class {}".format(data[".class"]))
142
143
144 class RTypeVisitor(Generic[T]):
145 """Generic visitor over RTypes (uses the visitor design pattern)."""
146
147 @abstractmethod
148 def visit_rprimitive(self, typ: RPrimitive, /) -> T:
149 raise NotImplementedError
150
151 @abstractmethod
152 def visit_rinstance(self, typ: RInstance, /) -> T:
153 raise NotImplementedError
154
155 def visit_rtypevar(self, typ: RTypeVar, /) -> T:
156 raise RuntimeError("RTypeVar should not be encountered here")
157
158 @abstractmethod
159 def visit_rvec(self, typ: RVec, /) -> T:
160 raise NotImplementedError
161
162 @abstractmethod
163 def visit_runion(self, typ: RUnion, /) -> T:
164 raise NotImplementedError
165
166 @abstractmethod
167 def visit_rtuple(self, typ: RTuple, /) -> T:
168 raise NotImplementedError
169
170 @abstractmethod
171 def visit_rstruct(self, typ: RStruct, /) -> T:
172 raise NotImplementedError
173
174 @abstractmethod
175 def visit_rarray(self, typ: RArray, /) -> T:
176 raise NotImplementedError
177
178 @abstractmethod
179 def visit_rvoid(self, typ: RVoid, /) -> T:
180 raise NotImplementedError
181
182
183 # These types are implemented as C structs.
184 RStructLike = Union["RStruct", "RVec"]
185
186
187 @final
188 class RVoid(RType):
189 """The void type (no value).
190
191 This is a singleton -- use void_rtype (below) to refer to this instead of
192 constructing a new instance.
193 """
194
195 is_unboxed = False
196 name = "void"
197 ctype = "void"
198
199 def accept(self, visitor: RTypeVisitor[T]) -> T:
200 return visitor.visit_rvoid(self)
201
202 @property
203 def may_be_immortal(self) -> bool:
204 return False
205
206 def serialize(self) -> str:
207 return "void"
208
209 def __eq__(self, other: object) -> TypeGuard[RVoid]:
210 return isinstance(other, RVoid)
211
212 def __hash__(self) -> int:
213 return hash(RVoid)
214
215
216 # Singleton instance of RVoid
217 void_rtype: Final = RVoid()
218
219
220 @final
221 class RPrimitive(RType):
222 """Primitive type such as 'object' or 'int'.
223
224 These often have custom ops associated with them. The 'object'
225 primitive type can be used to hold arbitrary Python objects.
226
227 Different primitive types have different representations, and
228 primitives may be unboxed or boxed. Primitive types don't need to
229 directly correspond to Python types, but most do.
230
231 NOTE: All supported primitive types are defined below
232 (e.g. object_rprimitive).
233 """
234
235 # Map from primitive names to primitive types and is used by deserialization
236 primitive_map: ClassVar[dict[str, RPrimitive]] = {}
237
238 def __init__(
239 self,
240 name: str,
241 *,
242 is_unboxed: bool,
243 is_refcounted: bool,
244 is_native_int: bool = False,
245 is_signed: bool = False,
246 ctype: str = "PyObject *",
247 size: int = PLATFORM_SIZE,
248 error_overlap: bool = False,
249 may_be_immortal: bool = True,
250 dependencies: tuple[Dependency, ...] | None = None,
251 ) -> None:
252 RPrimitive.primitive_map[name] = self
253
254 self.name = name
255 self.is_unboxed = is_unboxed
256 self.is_refcounted = is_refcounted
257 self.is_native_int = is_native_int
258 self.is_signed = is_signed
259 self._ctype = ctype
260 self.size = size
261 self.error_overlap = error_overlap
262 self._may_be_immortal = may_be_immortal and HAVE_IMMORTAL
263 self.dependencies = dependencies
264 if ctype == "CPyTagged":
265 self.c_undefined = "CPY_INT_TAG"
266 elif ctype in ("int16_t", "int32_t", "int64_t"):
267 # This is basically an arbitrary value that is pretty
268 # unlikely to overlap with a real value.
269 self.c_undefined = "-113"
270 elif ctype == "CPyPtr":
271 # TODO: Invent an overlapping error value?
272 self.c_undefined = "0"
273 elif ctype.endswith("*"):
274 # Boxed and pointer types use the null pointer as the error value.
275 self.c_undefined = "NULL"
276 elif ctype == "char":
277 self.c_undefined = "2"
278 elif ctype == "double":
279 self.c_undefined = "-113.0"
280 elif ctype in ("uint8_t", "uint16_t", "uint32_t", "uint64_t"):
281 self.c_undefined = "239" # An arbitrary number
282 else:
283 assert False, "Unrecognized ctype: %r" % ctype
284
285 def accept(self, visitor: RTypeVisitor[T]) -> T:
286 return visitor.visit_rprimitive(self)
287
288 @property
289 def may_be_immortal(self) -> bool:
290 return self._may_be_immortal
291
292 def serialize(self) -> str:
293 return self.name
294
295 def __repr__(self) -> str:
296 return "<RPrimitive %s>" % self.name
297
298 def __eq__(self, other: object) -> TypeGuard[RPrimitive]:
299 return isinstance(other, RPrimitive) and other.name == self.name
300
301 def __hash__(self) -> int:
302 return hash(self.name)
303
304
305 # NOTE: All the supported instances of RPrimitive are defined
306 # below. Use these instead of creating new instances.
307
308 # Used to represent arbitrary objects and dynamically typed (Any)
309 # values. There are various ops that let you perform generic, runtime
310 # checked operations on these (that match Python semantics). See the
311 # ops in mypyc.primitives.misc_ops, including py_getattr_op,
312 # py_call_op, and many others.
313 #
314 # If there is no more specific RType available for some value, we fall
315 # back to using this type.
316 #
317 # NOTE: Even though this is very flexible, this type should be used as
318 # little as possible, as generic ops are typically slow. Other types,
319 # including other primitive types and RInstance, are usually much
320 # faster.
321 object_rprimitive: Final = RPrimitive("builtins.object", is_unboxed=False, is_refcounted=True)
322
323 # represents a low level pointer of an object
324 object_pointer_rprimitive: Final = RPrimitive(
325 "object_ptr", is_unboxed=False, is_refcounted=False, ctype="PyObject **"
326 )
327
328 # Similar to object_primitive, but does not use automatic reference
329 # counting. Useful for temporaries.
330 object_non_refcounted_rprimitive: Final = RPrimitive(
331 "builtins.object_nrc", is_unboxed=False, is_refcounted=False
332 )
333
334 # Arbitrary-precision integer (corresponds to Python 'int'). Small
335 # enough values are stored unboxed, while large integers are
336 # represented as a tagged pointer to a Python 'int' PyObject. The
337 # lowest bit is used as the tag to decide whether it is a signed
338 # unboxed value (shifted left by one) or a PyObject * pointing to an
339 # 'int' object. Pointers have the least significant bit set.
340 #
341 # The undefined/error value is the null pointer (1 -- only the least
342 # significant bit is set)).
343 #
344 # This cannot represent a subclass of int. An instance of a subclass
345 # of int is coerced to the corresponding 'int' value.
346 int_rprimitive: Final = RPrimitive(
347 "builtins.int", is_unboxed=True, is_refcounted=True, ctype="CPyTagged"
348 )
349
350 # An unboxed integer. The representation is the same as for unboxed
351 # int_rprimitive (shifted left by one). These can be used when an
352 # integer is known to be small enough to fit size_t (CPyTagged).
353 short_int_rprimitive: Final = RPrimitive(
354 "short_int", is_unboxed=True, is_refcounted=False, ctype="CPyTagged"
355 )
356
357 # Low level integer types (correspond to C integer types)
358
359 int16_rprimitive: Final = RPrimitive(
360 "i16",
361 is_unboxed=True,
362 is_refcounted=False,
363 is_native_int=True,
364 is_signed=True,
365 ctype="int16_t",
366 size=2,
367 error_overlap=True,
368 )
369 int32_rprimitive: Final = RPrimitive(
370 "i32",
371 is_unboxed=True,
372 is_refcounted=False,
373 is_native_int=True,
374 is_signed=True,
375 ctype="int32_t",
376 size=4,
377 error_overlap=True,
378 )
379 int64_rprimitive: Final = RPrimitive(
380 "i64",
381 is_unboxed=True,
382 is_refcounted=False,
383 is_native_int=True,
384 is_signed=True,
385 ctype="int64_t",
386 size=8,
387 error_overlap=True,
388 )
389 uint8_rprimitive: Final = RPrimitive(
390 "u8",
391 is_unboxed=True,
392 is_refcounted=False,
393 is_native_int=True,
394 is_signed=False,
395 ctype="uint8_t",
396 size=1,
397 error_overlap=True,
398 )
399
400 # The following unsigned native int types (u16, u32, u64) are not
401 # exposed to the user. They are for internal use within mypyc only.
402
403 u16_rprimitive: Final = RPrimitive(
404 "u16",
405 is_unboxed=True,
406 is_refcounted=False,
407 is_native_int=True,
408 is_signed=False,
409 ctype="uint16_t",
410 size=2,
411 error_overlap=True,
412 )
413 uint32_rprimitive: Final = RPrimitive(
414 "u32",
415 is_unboxed=True,
416 is_refcounted=False,
417 is_native_int=True,
418 is_signed=False,
419 ctype="uint32_t",
420 size=4,
421 error_overlap=True,
422 )
423 uint64_rprimitive: Final = RPrimitive(
424 "u64",
425 is_unboxed=True,
426 is_refcounted=False,
427 is_native_int=True,
428 is_signed=False,
429 ctype="uint64_t",
430 size=8,
431 error_overlap=True,
432 )
433
434 # The C 'int' type
435 c_int_rprimitive = int32_rprimitive
436
437 if IS_32_BIT_PLATFORM:
438 c_size_t_rprimitive = uint32_rprimitive
439 c_pyssize_t_rprimitive = RPrimitive(
440 "native_int",
441 is_unboxed=True,
442 is_refcounted=False,
443 is_native_int=True,
444 is_signed=True,
445 ctype="int32_t",
446 size=4,
447 )
448 else:
449 c_size_t_rprimitive = uint64_rprimitive
450 c_pyssize_t_rprimitive = RPrimitive(
451 "native_int",
452 is_unboxed=True,
453 is_refcounted=False,
454 is_native_int=True,
455 is_signed=True,
456 ctype="int64_t",
457 size=8,
458 )
459
460 # Untyped pointer, represented as integer in the C backend
461 pointer_rprimitive: Final = RPrimitive("ptr", is_unboxed=True, is_refcounted=False, ctype="CPyPtr")
462
463 # Untyped pointer, represented as void * in the C backend
464 c_pointer_rprimitive: Final = RPrimitive(
465 "c_ptr", is_unboxed=False, is_refcounted=False, ctype="void *"
466 )
467
468 cstring_rprimitive: Final = RPrimitive(
469 "cstring", is_unboxed=True, is_refcounted=False, ctype="const char *"
470 )
471
472 # The type corresponding to mypyc.common.BITMAP_TYPE
473 bitmap_rprimitive: Final = uint32_rprimitive
474
475 # Floats are represent as 'float' PyObject * values. (In the future
476 # we'll likely switch to a more efficient, unboxed representation.)
477 float_rprimitive: Final = RPrimitive(
478 "builtins.float",
479 is_unboxed=True,
480 is_refcounted=False,
481 ctype="double",
482 size=8,
483 error_overlap=True,
484 )
485
486 # An unboxed Python bool value. This actually has three possible values
487 # (0 -> False, 1 -> True, 2 -> error). If you only need True/False, use
488 # bit_rprimitive instead.
489 bool_rprimitive: Final = RPrimitive(
490 "builtins.bool", is_unboxed=True, is_refcounted=False, ctype="char", size=1
491 )
492
493 # A low-level boolean value with two possible values: 0 and 1. Any
494 # other value results in undefined behavior. Undefined or error values
495 # are not supported.
496 bit_rprimitive: Final = RPrimitive(
497 "bit", is_unboxed=True, is_refcounted=False, ctype="char", size=1
498 )
499
500 # The 'None' value. The possible values are 0 -> None and 2 -> error.
501 none_rprimitive: Final = RPrimitive(
502 "builtins.None", is_unboxed=True, is_refcounted=False, ctype="char", size=1
503 )
504
505 # Python list object (or an instance of a subclass of list). These could be
506 # immortal, but since this is expected to be very rare, and the immortality checks
507 # can be pretty expensive for lists, we treat lists as non-immortal.
508 list_rprimitive: Final = RPrimitive(
509 "builtins.list", is_unboxed=False, is_refcounted=True, may_be_immortal=False
510 )
511
512 # Python dict object (or an instance of a subclass of dict).
513 dict_rprimitive: Final = RPrimitive("builtins.dict", is_unboxed=False, is_refcounted=True)
514
515 # Python set object (or an instance of a subclass of set).
516 set_rprimitive: Final = RPrimitive("builtins.set", is_unboxed=False, is_refcounted=True)
517
518 # Python frozenset object (or an instance of a subclass of frozenset).
519 frozenset_rprimitive: Final = RPrimitive(
520 "builtins.frozenset", is_unboxed=False, is_refcounted=True
521 )
522
523 # Python str object. At the C layer, str is referred to as unicode
524 # (PyUnicode).
525 str_rprimitive: Final = RPrimitive("builtins.str", is_unboxed=False, is_refcounted=True)
526
527 # Python bytes object.
528 bytes_rprimitive: Final = RPrimitive("builtins.bytes", is_unboxed=False, is_refcounted=True)
529
530 # Python bytearray object.
531 bytearray_rprimitive: Final = RPrimitive(
532 "builtins.bytearray", is_unboxed=False, is_refcounted=True
533 )
534
535 # Tuple of an arbitrary length (corresponds to Tuple[t, ...], with
536 # explicit '...').
537 tuple_rprimitive: Final = RPrimitive("builtins.tuple", is_unboxed=False, is_refcounted=True)
538
539 # Python range object.
540 range_rprimitive: Final = RPrimitive("builtins.range", is_unboxed=False, is_refcounted=True)
541
542 KNOWN_NATIVE_TYPES: Final = {
543 name: RPrimitive(name, is_unboxed=False, is_refcounted=True, dependencies=deps)
544 for name, deps in [
545 ("librt.internal.WriteBuffer", ()),
546 ("librt.internal.ReadBuffer", ()),
547 ("librt.strings.BytesWriter", (LIBRT_STRINGS,)),
548 ("librt.strings.StringWriter", (LIBRT_STRINGS,)),
549 ]
550 } | {
551 "librt.random.Random": RPrimitive(
552 "librt.random.Random", is_unboxed=False, is_refcounted=True, dependencies=(LIBRT_RANDOM,)
553 ),
554 "librt.threading.Lock": RPrimitive(
555 "librt.threading.Lock",
556 is_unboxed=False,
557 is_refcounted=True,
558 dependencies=(LIBRT_THREADING,),
559 ),
560 }
561
562 bytes_writer_rprimitive: Final = KNOWN_NATIVE_TYPES["librt.strings.BytesWriter"]
563 string_writer_rprimitive: Final = KNOWN_NATIVE_TYPES["librt.strings.StringWriter"]
564 random_rprimitive: Final = KNOWN_NATIVE_TYPES["librt.random.Random"]
565 lock_rprimitive: Final = KNOWN_NATIVE_TYPES["librt.threading.Lock"]
566
567
568 def is_native_rprimitive(rtype: RType) -> bool:
569 return isinstance(rtype, RPrimitive) and rtype.name in KNOWN_NATIVE_TYPES
570
571
572 def is_simple_refcounted_pointer(rtype: RType) -> bool:
573 """Is rtype represented at runtime as a single, reference-counted 'PyObject *'?
574
575 This covers 'object', 'str', containers, instances of native classes and
576 optional/union types -- everything whose C representation is exactly one
577 'PyObject *' field that owns a reference. It excludes unboxed types (tagged
578 'int', fixed-width ints, floats, bools), inline tuples ('RTuple'), vectors
579 ('RVec') and C structs ('RStruct'), which need different treatment for
580 free-threaded memory safety.
581 """
582 return rtype.is_refcounted and not rtype.is_unboxed and not isinstance(rtype, RStruct)
583
584
585 def is_tagged(rtype: RType) -> TypeGuard[RPrimitive]:
586 return rtype is int_rprimitive or rtype is short_int_rprimitive
587
588
589 def is_any_int(rtype: RType) -> bool:
590 return is_tagged(rtype) or is_int32_rprimitive(rtype) or is_int64_rprimitive(rtype)
591
592
593 def is_int_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
594 return rtype is int_rprimitive
595
596
597 def is_short_int_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
598 return rtype is short_int_rprimitive
599
600
601 def is_int16_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
602 return rtype is int16_rprimitive
603
604
605 def is_int32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
606 return rtype is int32_rprimitive or (
607 rtype is c_pyssize_t_rprimitive and rtype._ctype == "int32_t"
608 )
609
610
611 def is_int64_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
612 return rtype is int64_rprimitive or (
613 rtype is c_pyssize_t_rprimitive and rtype._ctype == "int64_t"
614 )
615
616
617 def is_fixed_width_rtype(rtype: RType) -> TypeGuard[RPrimitive]:
618 return (
619 is_int64_rprimitive(rtype)
620 or is_int32_rprimitive(rtype)
621 or is_int16_rprimitive(rtype)
622 or is_uint8_rprimitive(rtype)
623 )
624
625
626 def is_uint8_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
627 return rtype is uint8_rprimitive
628
629
630 def is_uint32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
631 return rtype is uint32_rprimitive
632
633
634 def is_uint64_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
635 return rtype is uint64_rprimitive
636
637
638 def is_c_py_ssize_t_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
639 return rtype is c_pyssize_t_rprimitive
640
641
642 def is_pointer_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
643 return rtype is pointer_rprimitive
644
645
646 def is_float_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
647 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.float"
648
649
650 def is_bool_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
651 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bool"
652
653
654 def is_bit_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
655 return isinstance(rtype, RPrimitive) and rtype.name == "bit"
656
657
658 def is_bool_or_bit_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
659 return is_bool_rprimitive(rtype) or is_bit_rprimitive(rtype)
660
661
662 def is_object_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
663 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.object"
664
665
666 def is_none_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
667 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.None"
668
669
670 def is_list_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
671 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.list"
672
673
674 def is_dict_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
675 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.dict"
676
677
678 def is_set_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
679 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.set"
680
681
682 def is_frozenset_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
683 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.frozenset"
684
685
686 def is_str_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
687 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.str"
688
689
690 def is_bytes_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
691 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bytes"
692
693
694 def is_bytearray_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
695 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bytearray"
696
697
698 def is_tuple_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
699 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.tuple"
700
701
702 def is_range_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
703 return isinstance(rtype, RPrimitive) and rtype.name == "builtins.range"
704
705
706 def is_sequence_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
707 return isinstance(rtype, RPrimitive) and (
708 is_list_rprimitive(rtype)
709 or is_tuple_rprimitive(rtype)
710 or is_str_rprimitive(rtype)
711 or is_bytes_rprimitive(rtype)
712 or is_bytearray_rprimitive(rtype)
713 )
714
715
716 def is_immutable_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
717 return (
718 is_str_rprimitive(rtype)
719 or is_bytes_rprimitive(rtype)
720 or is_tuple_rprimitive(rtype)
721 or is_frozenset_rprimitive(rtype)
722 )
723
724
725 class TupleNameVisitor(RTypeVisitor[str]):
726 """Produce a tuple name based on the concrete representations of types."""
727
728 def visit_rinstance(self, t: RInstance) -> str:
729 return "O"
730
731 def visit_rvec(self, t: RVec) -> str:
732 if isinstance(t.item_type, RVec):
733 # All nested vecs share a representation
734 return "Vv"
735 return "V" + t.item_type.accept(self)
736
737 def visit_runion(self, t: RUnion) -> str:
738 return "O"
739
740 def visit_rprimitive(self, t: RPrimitive) -> str:
741 if t._ctype == "CPyTagged":
742 return "I"
743 elif t._ctype == "char":
744 return "C"
745 elif t._ctype == "int64_t":
746 return "8" # "8 byte integer"
747 elif t._ctype == "int32_t":
748 return "4" # "4 byte integer"
749 elif t._ctype == "int16_t":
750 return "2" # "2 byte integer"
751 elif t._ctype == "uint8_t":
752 return "U1" # "1 byte unsigned integer"
753 elif t._ctype == "double":
754 return "F"
755 assert not t.is_unboxed, f"{t} unexpected unboxed type"
756 return "O"
757
758 def visit_rtuple(self, t: RTuple) -> str:
759 parts = [elem.accept(self) for elem in t.types]
760 return "T{}{}".format(len(parts), "".join(parts))
761
762 def visit_rstruct(self, t: RStruct) -> str:
763 if t.name == "VecNestedBufItem":
764 return "Vi"
765 assert False, "RStruct not supported in tuple"
766
767 def visit_rarray(self, t: RArray) -> str:
768 assert False, "RArray not supported in tuple"
769
770 def visit_rvoid(self, t: RVoid) -> str:
771 assert False, "rvoid in tuple?"
772
773 def visit_rtypevar(self, typ: RTypeVar) -> str:
774 # We need to return something to support generic RTuples, etc. Make sure
775 # the return value is invalid C so that generic RTuples must be expanded
776 # before they can be used in IR.
777 return f"!RTypeVar {typ.id} invalid!"
778
779
780 @final
781 class RTuple(RType):
782 """Fixed-length unboxed tuple (represented as a C struct).
783
784 These are used to represent mypy TupleType values (fixed-length
785 Python tuples). Since this is unboxed, the identity of a tuple
786 object is not preserved within compiled code. If the identity of a
787 tuple is important, or there is a need to have multiple references
788 to a single tuple object, a variable-length tuple should be used
789 (tuple_rprimitive or Tuple[T, ...] with explicit '...'), as they
790 are boxed.
791
792 These aren't immutable. However, user code won't be able to mutate
793 individual tuple items.
794 """
795
796 is_unboxed = True
797
798 def __init__(self, types: list[RType]) -> None:
799 self.name = "tuple"
800 self.types = tuple(types)
801 self.is_refcounted = any(t.is_refcounted for t in self.types)
802 # Generate a unique id which is used in naming corresponding C identifiers.
803 # This is necessary since C does not have anonymous structural type equivalence
804 # in the same way python can just assign a Tuple[int, bool] to a Tuple[int, bool].
805 self.unique_id = self.accept(TupleNameVisitor())
806 # Nominally the max c length is 31 chars, but I'm not honestly worried about this.
807 self.struct_name = f"tuple_{self.unique_id}"
808 self._ctype = f"{self.struct_name}"
809 self.error_overlap = all(t.error_overlap for t in self.types) and bool(self.types)
810
811 def accept(self, visitor: RTypeVisitor[T]) -> T:
812 return visitor.visit_rtuple(self)
813
814 @property
815 def may_be_immortal(self) -> bool:
816 return False
817
818 def __str__(self) -> str:
819 return "tuple[%s]" % ", ".join(str(typ) for typ in self.types)
820
821 def __repr__(self) -> str:
822 return "<RTuple %s>" % ", ".join(repr(typ) for typ in self.types)
823
824 def __eq__(self, other: object) -> TypeGuard[RTuple]:
825 return isinstance(other, RTuple) and self.types == other.types
826
827 def __hash__(self) -> int:
828 return hash((self.name, self.types))
829
830 def serialize(self) -> JsonDict:
831 types = [x.serialize() for x in self.types]
832 return {".class": "RTuple", "types": types}
833
834 @classmethod
835 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RTuple:
836 types = [deserialize_type(t, ctx) for t in data["types"]]
837 return RTuple(types)
838
839
840 # Exception tuple: (exception class, exception instance, traceback object)
841 exc_rtuple = RTuple([object_rprimitive, object_rprimitive, object_rprimitive])
842
843 # Dictionary iterator tuple: (should continue, internal offset, key, value)
844 # See mypyc.irbuild.for_helpers.ForDictionaryCommon for more details.
845 dict_next_rtuple_pair = RTuple(
846 [bool_rprimitive, short_int_rprimitive, object_rprimitive, object_rprimitive]
847 )
848 # Same as above but just for key or value.
849 dict_next_rtuple_single = RTuple([bool_rprimitive, short_int_rprimitive, object_rprimitive])
850
851
852 def compute_rtype_alignment(typ: RType) -> int:
853 """Compute alignment of a given type based on platform alignment rule"""
854 platform_alignment = PLATFORM_SIZE
855 if isinstance(typ, RPrimitive):
856 return typ.size
857 elif isinstance(typ, RInstance):
858 return platform_alignment
859 elif isinstance(typ, RUnion):
860 return platform_alignment
861 elif isinstance(typ, RArray):
862 return compute_rtype_alignment(typ.item_type)
863 else:
864 if isinstance(typ, RTuple):
865 items = list(typ.types)
866 elif isinstance(typ, RStruct):
867 items = typ.types
868 else:
869 assert False, "invalid rtype for computing alignment"
870 max_alignment = max(compute_rtype_alignment(item) for item in items)
871 return max_alignment
872
873
874 def compute_rtype_size(typ: RType) -> int:
875 """Compute unaligned size of rtype"""
876 if isinstance(typ, RPrimitive):
877 return typ.size
878 elif isinstance(typ, RTuple):
879 return compute_aligned_offsets_and_size(list(typ.types))[1]
880 elif isinstance(typ, RUnion):
881 return PLATFORM_SIZE
882 elif isinstance(typ, RStruct):
883 return compute_aligned_offsets_and_size(typ.types)[1]
884 elif isinstance(typ, RInstance):
885 return PLATFORM_SIZE
886 elif isinstance(typ, RArray):
887 alignment = compute_rtype_alignment(typ)
888 aligned_size = (compute_rtype_size(typ.item_type) + (alignment - 1)) & ~(alignment - 1)
889 return aligned_size * typ.length
890 else:
891 assert False, "invalid rtype for computing size"
892
893
894 def compute_aligned_offsets_and_size(types: list[RType]) -> tuple[list[int], int]:
895 """Compute offsets and total size of a list of types after alignment
896
897 Note that the types argument are types of values that are stored
898 sequentially with platform default alignment.
899 """
900 unaligned_sizes = [compute_rtype_size(typ) for typ in types]
901 alignments = [compute_rtype_alignment(typ) for typ in types]
902
903 current_offset = 0
904 offsets = []
905 final_size = 0
906 for i in range(len(unaligned_sizes)):
907 offsets.append(current_offset)
908 if i + 1 < len(unaligned_sizes):
909 cur_size = unaligned_sizes[i]
910 current_offset += cur_size
911 next_alignment = alignments[i + 1]
912 # compute aligned offset,
913 # check https://en.wikipedia.org/wiki/Data_structure_alignment for more information
914 current_offset = (current_offset + (next_alignment - 1)) & -next_alignment
915 else:
916 struct_alignment = max(alignments)
917 final_size = current_offset + unaligned_sizes[i]
918 final_size = (final_size + (struct_alignment - 1)) & -struct_alignment
919 return offsets, final_size
920
921
922 @final
923 class RStruct(RType):
924 """C struct type"""
925
926 def __init__(self, name: str, names: list[str], types: list[RType]) -> None:
927 self.name = name
928 self.names = names
929 self.types = types
930 self.is_refcounted = any(t.is_refcounted for t in self.types)
931
932 # generate dummy names
933 if len(self.names) < len(self.types):
934 for i in range(len(self.types) - len(self.names)):
935 self.names.append("_item" + str(i))
936 self.offsets, self.size = compute_aligned_offsets_and_size(types)
937 self._ctype = name
938
939 def field_type(self, name: str) -> RType:
940 for n, t in zip(self.names, self.types):
941 if n == name:
942 return t
943 assert False, f"{self.name} has no field '{name}'"
944
945 def accept(self, visitor: RTypeVisitor[T]) -> T:
946 return visitor.visit_rstruct(self)
947
948 @property
949 def may_be_immortal(self) -> bool:
950 return False
951
952 def __str__(self) -> str:
953 # if not tuple(unnamed structs)
954 return "{}{{{}}}".format(
955 self.name,
956 ", ".join(name + ":" + str(typ) for name, typ in zip(self.names, self.types)),
957 )
958
959 def __repr__(self) -> str:
960 return "<RStruct {}{{{}}}>".format(
961 self.name,
962 ", ".join(name + ":" + repr(typ) for name, typ in zip(self.names, self.types)),
963 )
964
965 def __eq__(self, other: object) -> TypeGuard[RStruct]:
966 return (
967 isinstance(other, RStruct)
968 and self.name == other.name
969 and self.names == other.names
970 and self.types == other.types
971 )
972
973 def __hash__(self) -> int:
974 return hash((self.name, tuple(self.names), tuple(self.types)))
975
976 def serialize(self) -> JsonDict:
977 assert False
978
979 @classmethod
980 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RStruct:
981 assert False
982
983
984 @final
985 class RInstance(RType):
986 """Instance of user-defined class (compiled to C extension class).
987
988 The runtime representation is 'PyObject *', and these are always
989 boxed and thus reference-counted.
990
991 These support fast method calls and fast attribute access using
992 vtables, and they usually use a dict-free, struct-based
993 representation of attributes. Method calls and attribute access
994 can skip the vtable if we know that there is no overriding.
995
996 These are also sometimes called 'native' types, since these have
997 the most efficient representation and ops (along with certain
998 RPrimitive types and RTuple).
999 """
1000
1001 is_unboxed = False
1002
1003 def __init__(self, class_ir: ClassIR) -> None:
1004 # name is used for formatting the name in messages and debug output
1005 # so we want the fullname for precision.
1006 self.name = class_ir.fullname
1007 self.class_ir = class_ir
1008 self._ctype = "PyObject *"
1009
1010 def accept(self, visitor: RTypeVisitor[T]) -> T:
1011 return visitor.visit_rinstance(self)
1012
1013 @property
1014 def may_be_immortal(self) -> bool:
1015 return False
1016
1017 def struct_name(self, names: NameGenerator) -> str:
1018 return self.class_ir.struct_name(names)
1019
1020 def getter_index(self, name: str) -> int:
1021 return self.class_ir.vtable_entry(name)
1022
1023 def setter_index(self, name: str) -> int:
1024 return self.getter_index(name) + 1
1025
1026 def method_index(self, name: str) -> int:
1027 return self.class_ir.vtable_entry(name)
1028
1029 def attr_type(self, name: str) -> RType:
1030 return self.class_ir.attr_type(name)
1031
1032 def __repr__(self) -> str:
1033 return "<RInstance %s>" % self.name
1034
1035 def __eq__(self, other: object) -> TypeGuard[RInstance]:
1036 return isinstance(other, RInstance) and other.name == self.name
1037
1038 def __hash__(self) -> int:
1039 return hash(self.name)
1040
1041 def serialize(self) -> str:
1042 return self.name
1043
1044
1045 @final
1046 class RTypeVar(RType):
1047 """Type variable type used for generic primitive ops.
1048
1049 This allows having generic primitive operations like vec get item, which is
1050 parametrized by the vec item type.
1051
1052 These types are not valid in any other context outside PrimitiveDescription,
1053 and they will always be substituted during the construction of a PrimitiveOp.
1054
1055 NOTE: This is not related to mypy's TypeVarType!
1056 """
1057
1058 def __init__(self, id: int) -> None:
1059 self.id = id
1060
1061 @property
1062 def may_be_immortal(self) -> bool:
1063 # RTypeVar must always be substituted before use, so this should never matter.
1064 return False
1065
1066 def accept(self, visitor: RTypeVisitor[T]) -> T:
1067 return visitor.visit_rtypevar(self)
1068
1069 def __str__(self) -> str:
1070 return f"<RTypeVar {self.id}>"
1071
1072 def __repr__(self) -> str:
1073 return f"<RTypeVar {self.id}>"
1074
1075 def __eq__(self, other: object) -> TypeGuard[RTypeVar]:
1076 return isinstance(other, RTypeVar) and other.id == self.id
1077
1078 def __hash__(self) -> int:
1079 return self.id ^ 12345
1080
1081 def serialize(self) -> JsonDict:
1082 return {".class": "RTypeVar", "id": self.id}
1083
1084 @classmethod
1085 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RTypeVar:
1086 return RTypeVar(data["id"])
1087
1088
1089 @final
1090 class RVec(RType):
1091 """librt.vecs.vec[T]"""
1092
1093 is_unboxed = True
1094
1095 def __init__(self, item_type: RType) -> None:
1096 self.name = "vec[%s]" % item_type
1097 self.item_type = item_type
1098 self.names = ["len", "items"]
1099 self.dependencies = (LIBRT_VECS,)
1100 if isinstance(item_type, RUnion):
1101 non_opt = optional_value_type(item_type)
1102 else:
1103 non_opt = item_type
1104 if item_type in vec_buf_types:
1105 self._ctype = vec_c_types[item_type]
1106 self.buf_type = vec_buf_types[item_type]
1107 self.types = [c_pyssize_t_rprimitive, pointer_rprimitive]
1108 elif isinstance(non_opt, RVec):
1109 self._ctype = "VecNested"
1110 self.types = [c_pyssize_t_rprimitive, pointer_rprimitive]
1111 self.buf_type = VecNestedBufObject
1112 else:
1113 self._ctype = "VecT"
1114 self.types = [c_pyssize_t_rprimitive, pointer_rprimitive]
1115 self.buf_type = VecTBufObject
1116
1117 @property
1118 def may_be_immortal(self) -> bool:
1119 return False
1120
1121 def unwrap_item_type(self) -> RPrimitive | RInstance:
1122 """Return the non-optional value (non-vec) item type in a potentially nested vec."""
1123 item_type = self.item_type
1124 while True:
1125 if isinstance(item_type, RUnion):
1126 value_type = optional_value_type(item_type)
1127 assert value_type is not None
1128 item_type = value_type
1129 elif isinstance(item_type, RVec):
1130 item_type = item_type.item_type
1131 elif isinstance(item_type, (RPrimitive, RInstance)):
1132 return item_type
1133 else:
1134 assert False, f"unexpected item type: {self.item_type}"
1135
1136 def is_optional(self) -> bool:
1137 item_type = self.item_type
1138 if isinstance(item_type, RUnion):
1139 return True
1140 elif isinstance(item_type, RVec):
1141 return item_type.is_optional()
1142 return False
1143
1144 def depth(self) -> int:
1145 item_type = self.item_type
1146 if isinstance(item_type, RUnion):
1147 value_type = optional_value_type(item_type)
1148 assert value_type is not None
1149 item_type = value_type
1150 if isinstance(item_type, RVec):
1151 return 1 + item_type.depth()
1152 return 0
1153
1154 def field_type(self, name: str) -> RType:
1155 if name == "len":
1156 return c_pyssize_t_rprimitive
1157 elif name == "items":
1158 return pointer_rprimitive
1159 assert False, f"RVec has no field '{name}'"
1160
1161 def accept(self, visitor: RTypeVisitor[T]) -> T:
1162 return visitor.visit_rvec(self)
1163
1164 def __str__(self) -> str:
1165 if self.is_optional() and self.depth() == 0:
1166 type_str = f"{self.unwrap_item_type()} | None"
1167 else:
1168 type_str = str(self.item_type)
1169 return f"vec[{type_str}]"
1170
1171 def __repr__(self) -> str:
1172 return "<RVec[%s]>" % self.item_type
1173
1174 def __eq__(self, other: object) -> bool:
1175 return isinstance(other, RVec) and other.item_type == self.item_type
1176
1177 def __hash__(self) -> int:
1178 return hash(self.item_type) ^ 1
1179
1180 def serialize(self) -> JsonDict:
1181 return {".class": "RVec", "item_type": self.item_type.serialize()}
1182
1183 @classmethod
1184 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RVec:
1185 return RVec(deserialize_type(data["item_type"], ctx))
1186
1187
1188 @final
1189 class RUnion(RType):
1190 """union[x, ..., y]"""
1191
1192 is_unboxed = False
1193
1194 def __init__(self, items: list[RType]) -> None:
1195 self.name = "union"
1196 self.items = items
1197 self.items_set = frozenset(items)
1198 self._ctype = "PyObject *"
1199
1200 @staticmethod
1201 def make_simplified_union(items: list[RType]) -> RType:
1202 """Return a normalized union that covers the given items.
1203
1204 Flatten nested unions and remove duplicate items.
1205
1206 Overlapping items are *not* simplified. For example,
1207 [object, str] will not be simplified.
1208 """
1209 items = flatten_nested_unions(items)
1210 assert items
1211
1212 unique_items = dict.fromkeys(items)
1213 if len(unique_items) > 1:
1214 return RUnion(list(unique_items))
1215 else:
1216 return next(iter(unique_items))
1217
1218 def accept(self, visitor: RTypeVisitor[T]) -> T:
1219 return visitor.visit_runion(self)
1220
1221 @property
1222 def may_be_immortal(self) -> bool:
1223 return any(item.may_be_immortal for item in self.items)
1224
1225 def __repr__(self) -> str:
1226 return "<RUnion %s>" % ", ".join(str(item) for item in self.items)
1227
1228 def __str__(self) -> str:
1229 return "union[%s]" % ", ".join(str(item) for item in self.items)
1230
1231 # We compare based on the set because order in a union doesn't matter
1232 def __eq__(self, other: object) -> TypeGuard[RUnion]:
1233 return isinstance(other, RUnion) and self.items_set == other.items_set
1234
1235 def __hash__(self) -> int:
1236 return hash(("union", self.items_set))
1237
1238 def serialize(self) -> JsonDict:
1239 types = [x.serialize() for x in self.items]
1240 return {".class": "RUnion", "types": types}
1241
1242 @classmethod
1243 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RUnion:
1244 types = [deserialize_type(t, ctx) for t in data["types"]]
1245 return RUnion(types)
1246
1247
1248 def flatten_nested_unions(types: list[RType]) -> list[RType]:
1249 if not any(isinstance(t, RUnion) for t in types):
1250 return types # Fast path
1251
1252 flat_items: list[RType] = []
1253 for t in types:
1254 if isinstance(t, RUnion):
1255 flat_items.extend(flatten_nested_unions(t.items))
1256 else:
1257 flat_items.append(t)
1258 return flat_items
1259
1260
1261 def optional_value_type(rtype: RType) -> RType | None:
1262 """If rtype is the union of none_rprimitive and another type X, return X.
1263
1264 Otherwise, return None.
1265 """
1266 if isinstance(rtype, RUnion) and len(rtype.items) == 2:
1267 if rtype.items[0] == none_rprimitive:
1268 return rtype.items[1]
1269 elif rtype.items[1] == none_rprimitive:
1270 return rtype.items[0]
1271 return None
1272
1273
1274 def is_optional_type(rtype: RType) -> TypeGuard[RUnion]:
1275 """Is rtype an optional type with exactly two union items?"""
1276 return optional_value_type(rtype) is not None
1277
1278
1279 @final
1280 class RArray(RType):
1281 """Fixed-length C array type (for example, int[5]).
1282
1283 Note that the implementation is a bit limited, and these can basically
1284 be only used for local variables that are initialized in one location.
1285 """
1286
1287 def __init__(self, item_type: RType, length: int) -> None:
1288 self.item_type = item_type
1289 # Number of items
1290 self.length = length
1291 self.is_refcounted = False
1292
1293 def accept(self, visitor: RTypeVisitor[T]) -> T:
1294 return visitor.visit_rarray(self)
1295
1296 @property
1297 def may_be_immortal(self) -> bool:
1298 return False
1299
1300 def __str__(self) -> str:
1301 return f"{self.item_type}[{self.length}]"
1302
1303 def __repr__(self) -> str:
1304 return f"<RArray {self.item_type!r}[{self.length}]>"
1305
1306 def __eq__(self, other: object) -> TypeGuard[RArray]:
1307 return (
1308 isinstance(other, RArray)
1309 and self.item_type == other.item_type
1310 and self.length == other.length
1311 )
1312
1313 def __hash__(self) -> int:
1314 return hash((self.item_type, self.length))
1315
1316 def serialize(self) -> JsonDict:
1317 assert False
1318
1319 @classmethod
1320 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RArray:
1321 assert False
1322
1323
1324 PyObject = RStruct(
1325 name="PyObject",
1326 names=["ob_refcnt", "ob_type"],
1327 types=[c_pyssize_t_rprimitive, pointer_rprimitive],
1328 )
1329
1330 PyVarObject = RStruct(
1331 name="PyVarObject", names=["ob_base", "ob_size"], types=[PyObject, c_pyssize_t_rprimitive]
1332 )
1333
1334 setentry = RStruct(
1335 name="setentry", names=["key", "hash"], types=[pointer_rprimitive, c_pyssize_t_rprimitive]
1336 )
1337
1338 smalltable = RStruct(name="smalltable", names=[], types=[setentry] * 8)
1339
1340 PySetObject = RStruct(
1341 name="PySetObject",
1342 names=[
1343 "ob_base",
1344 "fill",
1345 "used",
1346 "mask",
1347 "table",
1348 "hash",
1349 "finger",
1350 "smalltable",
1351 "weakreflist",
1352 ],
1353 types=[
1354 PyObject,
1355 c_pyssize_t_rprimitive,
1356 c_pyssize_t_rprimitive,
1357 c_pyssize_t_rprimitive,
1358 pointer_rprimitive,
1359 c_pyssize_t_rprimitive,
1360 c_pyssize_t_rprimitive,
1361 smalltable,
1362 pointer_rprimitive,
1363 ],
1364 )
1365
1366 PyListObject = RStruct(
1367 name="PyListObject",
1368 names=["ob_base", "ob_item", "allocated"],
1369 types=[PyVarObject, pointer_rprimitive, c_pyssize_t_rprimitive],
1370 )
1371
1372
1373 def check_native_int_range(rtype: RPrimitive, n: int) -> bool:
1374 """Is n within the range of a native, fixed-width int type?
1375
1376 Assume the type is a fixed-width int type.
1377 """
1378 if not rtype.is_signed:
1379 return 0 <= n < (1 << (8 * rtype.size))
1380 else:
1381 limit = 1 << (rtype.size * 8 - 1)
1382 return -limit <= n < limit
1383
1384
1385 # Buffers for vec item types that have a packed representation
1386 #
1387 # Note that the 'items' fields are variable-length arrays, and mypyc IR isn't
1388 # able to represent these, so the field type is omitted for now.
1389
1390 VecI64BufObject = RStruct(
1391 name="VecI64BufObject",
1392 names=["ob_base", "len", "items"],
1393 types=[PyVarObject, int64_rprimitive],
1394 )
1395
1396 VecI32BufObject = RStruct(
1397 name="VecI32BufObject",
1398 names=["ob_base", "len", "items"],
1399 types=[PyVarObject, int64_rprimitive],
1400 )
1401
1402 VecI16BufObject = RStruct(
1403 name="VecI16BufObject",
1404 names=["ob_base", "len", "items"],
1405 types=[PyVarObject, int64_rprimitive],
1406 )
1407
1408 VecU8BufObject = RStruct(
1409 name="VecU8BufObject", names=["ob_base", "len", "items"], types=[PyVarObject, int64_rprimitive]
1410 )
1411
1412 VecFloatBufObject = RStruct(
1413 name="VecFloatBufObject",
1414 names=["ob_base", "len", "items"],
1415 types=[PyVarObject, int64_rprimitive],
1416 )
1417
1418 VecBoolBufObject = RStruct(
1419 name="VecBoolBufObject",
1420 names=["ob_base", "len", "items"],
1421 types=[PyVarObject, int64_rprimitive],
1422 )
1423
1424
1425 # Struct type for vec[i64] (in most cases use RVec instead).
1426 VecI64 = RStruct(
1427 name="VecI64", names=["len", "items"], types=[c_pyssize_t_rprimitive, pointer_rprimitive]
1428 )
1429
1430
1431 # Buffer for vec[t]
1432 VecTBufObject = RStruct(
1433 name="VecTBufObject",
1434 names=["ob_base", "item_type", "items"],
1435 types=[PyVarObject, c_pyssize_t_rprimitive, object_rprimitive],
1436 )
1437
1438 # Struct type for vec[t] (in most cases use RVec instead).
1439 VecT = RStruct(
1440 name="VecT", names=["len", "items"], types=[c_pyssize_t_rprimitive, pointer_rprimitive]
1441 )
1442
1443 VecNestedBufItem = RStruct(
1444 name="VecNestedBufItem",
1445 names=["len", "items"],
1446 types=[c_pyssize_t_rprimitive, pointer_rprimitive],
1447 )
1448
1449 # Buffer for vec[vec[t]]
1450 VecNestedBufObject = RStruct(
1451 name="VecNestedBufObject",
1452 names=["ob_base", "item_type", "depth", "optionals", "items"],
1453 types=[
1454 PyVarObject,
1455 c_pyssize_t_rprimitive,
1456 int32_rprimitive,
1457 int32_rprimitive,
1458 VecNestedBufItem,
1459 ],
1460 )
1461
1462 # Struct type for vec[vec[...]] (in most cases use RVec instead).
1463 VecNested = RStruct(
1464 name="VecNested", names=["len", "items"], types=[c_pyssize_t_rprimitive, pointer_rprimitive]
1465 )
1466
1467 VecNestedBufObject_rprimitive = RPrimitive(
1468 "VecNestedBufObject_ptr", is_unboxed=False, is_refcounted=True, ctype="VecNestedBufObject *"
1469 )
1470
1471 VecNestedPopResult = RStruct(
1472 name="VecNestedPopResult", names=["vec", "item"], types=[VecNested, VecNestedBufItem]
1473 )
1474
1475
1476 vec_buf_types: Final[dict[RType, RStruct]] = {
1477 int64_rprimitive: VecI64BufObject,
1478 int32_rprimitive: VecI32BufObject,
1479 int16_rprimitive: VecI16BufObject,
1480 uint8_rprimitive: VecU8BufObject,
1481 float_rprimitive: VecFloatBufObject,
1482 bool_rprimitive: VecBoolBufObject,
1483 }
1484
1485 vec_c_types: Final[dict[RType, str]] = {
1486 int64_rprimitive: "VecI64",
1487 int32_rprimitive: "VecI32",
1488 int16_rprimitive: "VecI16",
1489 uint8_rprimitive: "VecU8",
1490 float_rprimitive: "VecFloat",
1491 bool_rprimitive: "VecBool",
1492 }
1493
1494 vec_api_fields: Final[dict[RType, str]] = {
1495 int64_rprimitive: "i64",
1496 int32_rprimitive: "i32",
1497 int16_rprimitive: "i16",
1498 uint8_rprimitive: "u8",
1499 float_rprimitive: "float_",
1500 bool_rprimitive: "bool_",
1501 }
1502
1503 vec_api_by_item_type: Final[dict[RType, str]] = {
1504 int64_rprimitive: "VecI64Api",
1505 int32_rprimitive: "VecI32Api",
1506 int16_rprimitive: "VecI16Api",
1507 uint8_rprimitive: "VecU8Api",
1508 float_rprimitive: "VecFloatApi",
1509 bool_rprimitive: "VecBoolApi",
1510 }
1511
1512 # These are special item type constants used in nested vecs to represent
1513 # item types with specialized representations. These must match definitions
1514 # in the vecs module (see VEC_ITEM_TYPE_I64 etc.).
1515 vec_item_type_tags: Final[dict[RType, int]] = {
1516 int64_rprimitive: 2,
1517 int32_rprimitive: 6,
1518 int16_rprimitive: 10,
1519 uint8_rprimitive: 14,
1520 float_rprimitive: 18,
1521 bool_rprimitive: 22,
1522 }