Debian Codegraph @

mypyc/common.py

raw
1 from __future__ import annotations
2
3 import importlib.machinery
4 import sys
5 import sysconfig
6 from typing import Any, Final
7
8 from mypy.util import unnamed_function
9
10 PREFIX: Final = "CPyPy_" # Python wrappers
11 NATIVE_PREFIX: Final = "CPyDef_" # Native functions etc.
12 DUNDER_PREFIX: Final = "CPyDunder_" # Wrappers for exposing dunder methods to the API
13 REG_PREFIX: Final = "cpy_r_" # Registers
14 STATIC_PREFIX: Final = "CPyStatic_" # Static variables (for literals etc.)
15 TYPE_PREFIX: Final = "CPyType_" # Type object struct
16 MODULE_PREFIX: Final = "CPyModule_" # Cached modules
17 TYPE_VAR_PREFIX: Final = "CPyTypeVar_" # Type variables when using new-style Python 3.12 syntax
18 ATTR_PREFIX: Final = "_" # Attributes
19 FAST_PREFIX: Final = "__mypyc_fast_" # Optimized methods in non-extension classes
20
21 ENV_ATTR_NAME: Final = "__mypyc_env__"
22 NEXT_LABEL_ATTR_NAME: Final = "__mypyc_next_label__"
23 TEMP_ATTR_NAME: Final = "__mypyc_temp__"
24 LAMBDA_NAME: Final = "__mypyc_lambda__"
25 PROPSET_PREFIX: Final = "__mypyc_setter__"
26 SELF_NAME: Final = "__mypyc_self__"
27 MYPYC_DEFAULTS_SETUP: Final = "__mypyc_defaults_setup"
28 GENERATOR_ATTRIBUTE_PREFIX: Final = "__mypyc_generator_attribute__"
29 CPYFUNCTION_NAME = "__cpyfunction__"
30
31 # Max short int we accept as a literal is based on 32-bit platforms,
32 # so that we can just always emit the same code.
33
34 TOP_LEVEL_NAME: Final = "__top_level__" # Special function representing module top level
35
36 # Maximal number of subclasses for a class to trigger fast path in isinstance() checks.
37 FAST_ISINSTANCE_MAX_SUBCLASSES: Final = 2
38
39 # Size of size_t, if configured.
40 SIZEOF_SIZE_T_SYSCONFIG: Final = sysconfig.get_config_var("SIZEOF_SIZE_T")
41
42 SIZEOF_SIZE_T: Final = (
43 int(SIZEOF_SIZE_T_SYSCONFIG)
44 if SIZEOF_SIZE_T_SYSCONFIG is not None
45 else (sys.maxsize + 1).bit_length() // 8
46 )
47
48 IS_32_BIT_PLATFORM: Final = int(SIZEOF_SIZE_T) == 4
49
50 PLATFORM_SIZE = 4 if IS_32_BIT_PLATFORM else 8
51
52 # Maximum value for a short tagged integer.
53 MAX_SHORT_INT: Final = 2 ** (8 * int(SIZEOF_SIZE_T) - 2) - 1
54
55 # Minimum value for a short tagged integer.
56 MIN_SHORT_INT: Final = -(MAX_SHORT_INT) - 1
57
58 # Maximum value for a short tagged integer represented as a C integer literal.
59 #
60 # Note: Assume that the compiled code uses the same bit width as mypyc
61 MAX_LITERAL_SHORT_INT: Final = MAX_SHORT_INT
62 MIN_LITERAL_SHORT_INT: Final = -MAX_LITERAL_SHORT_INT - 1
63
64 # Description of the C type used to track the definedness of attributes and
65 # the presence of argument default values that have types with overlapping
66 # error values. Each tracked attribute/argument has a dedicated bit in the
67 # relevant bitmap.
68 BITMAP_TYPE: Final = "uint32_t"
69 BITMAP_BITS: Final = 32
70
71 # Constant for keeping a (often borrowed) op alive for a short time (a few subexpressions,
72 # no arbitrary computation or memory allocations), until flush_keep_alives() is called.
73 KEEP_ALIVE_SHORT_LIVED: Final = 0
74 # Keep value alive longer, up to until the current top-level expression has been fully
75 # evaluated. This allows keeping alive values across function calls and arbitrary
76 # computation. Note that some expressions (e.g. lambdas), restrict the scope of borrowing.
77 KEEP_ALIVE_WHOLE_EXPRESSION: Final = 1
78
79 # Runtime C library files that are always included (some ops may bring
80 # extra dependencies via mypyc.ir.deps.SourceDep or mypyc.ir.deps.HeaderDep)
81 RUNTIME_C_FILES: Final = [
82 "init.c",
83 "getargs.c",
84 "getargsfast.c",
85 "int_ops.c",
86 "float_ops.c",
87 "str_ops.c",
88 "bytes_ops.c",
89 "list_ops.c",
90 "dict_ops.c",
91 "set_ops.c",
92 "tuple_ops.c",
93 "exc_ops.c",
94 "misc_ops.c",
95 "generic_ops.c",
96 "pythonsupport.c",
97 "function_wrapper.c",
98 ]
99
100 # Python 3.12 introduced immortal objects, specified via a special reference count
101 # value. The reference counts of immortal objects are normally not modified, but it's
102 # not strictly wrong to modify them. See PEP 683 for more information, but note that
103 # some details in the PEP are out of date.
104 HAVE_IMMORTAL: Final = sys.version_info >= (3, 12)
105
106 # Are we running on a free-threaded build (GIL disabled)? This implies that
107 # we are on Python 3.13 or later.
108 IS_FREE_THREADED: Final = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
109
110 # The file extension suffix for C extension modules on the current platform
111 # (e.g. ".cpython-312-x86_64-linux-gnu.so" or ".pyd").
112 _EXT_SUFFIXES: Final = importlib.machinery.EXTENSION_SUFFIXES
113 EXT_SUFFIX: Final = _EXT_SUFFIXES[0] if _EXT_SUFFIXES else ".so"
114
115
116 JsonDict = dict[str, Any]
117
118
119 def shared_lib_name(group_name: str) -> str:
120 """Given a group name, return the actual name of its extension module.
121
122 (This just adds a suffix to the final component.)
123 """
124 return f"{group_name}__mypyc"
125
126
127 def short_name(name: str) -> str:
128 if name.startswith("builtins."):
129 return name[9:]
130 return name
131
132
133 def get_id_from_name(name: str, fullname: str, line: int) -> str:
134 """Create a unique id for a function.
135
136 This creates an id that is unique for any given function definition, so that it can be used as
137 a dictionary key. This is usually the fullname of the function, but this is different in that
138 it handles the case where the function is named '_', in which case multiple different functions
139 could have the same name."""
140 if unnamed_function(name):
141 return f"{fullname}.{line}"
142 else:
143 return fullname
144
145
146 def short_id_from_name(func_name: str, shortname: str, line: int | None) -> str:
147 if unnamed_function(func_name):
148 assert line is not None
149 partial_name = f"{shortname}.{line}"
150 else:
151 partial_name = shortname
152 return partial_name
153
154
155 def bitmap_name(index: int) -> str:
156 if index == 0:
157 return "__bitmap"
158 return f"__bitmap{index + 1}"