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