Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/licenses/LICENSE +27 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/__init__.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/__init__.py +0 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.py +437 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.py +32 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.py +79 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.py +645 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/ircheck.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/ircheck.py +498 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.py +231 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/__init__.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/__init__.py +0 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/cstring.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/cstring.py +54 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emit.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emit.py +1439 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emitclass.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emitclass.py +1326 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.py +993 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.py +1494 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emitwrapper.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/emitwrapper.py +978 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/literals.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/codegen/literals.py +301 -0
- micromamba_root/Lib/site-packages/mypyc/ir/__init__.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/ir/__init__.py +0 -0
- micromamba_root/Lib/site-packages/mypyc/ir/class_ir.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/ir/class_ir.py +550 -0
- micromamba_root/Lib/site-packages/mypyc/ir/deps.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/ir/deps.py +59 -0
- micromamba_root/Lib/site-packages/mypyc/ir/func_ir.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/ir/func_ir.py +484 -0
- micromamba_root/Lib/site-packages/mypyc/ir/module_ir.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/ir/module_ir.py +115 -0
- micromamba_root/Lib/site-packages/mypyc/ir/ops.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/ir/ops.py +2106 -0
- micromamba_root/Lib/site-packages/mypyc/ir/pprint.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/ir/pprint.py +530 -0
- micromamba_root/Lib/site-packages/mypyc/ir/rtypes.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/ir/rtypes.py +1444 -0
- micromamba_root/Lib/site-packages/mypyc/irbuild/__init__.cp314-win_amd64.pyd +0 -0
- micromamba_root/Lib/site-packages/mypyc/irbuild/__init__.py +0 -0
- micromamba_root/Lib/site-packages/mypyc/irbuild/ast_helpers.cp314-win_amd64.pyd +0 -0
micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Mypy extensions are licensed under the terms of the MIT license, reproduced below.
|
| 2 |
+
|
| 3 |
+
= = = = =
|
| 4 |
+
|
| 5 |
+
The MIT License
|
| 6 |
+
|
| 7 |
+
Copyright (c) 2016-2017 Jukka Lehtosalo and contributors
|
| 8 |
+
|
| 9 |
+
Permission is hereby granted, free of charge, to any person obtaining a
|
| 10 |
+
copy of this software and associated documentation files (the "Software"),
|
| 11 |
+
to deal in the Software without restriction, including without limitation
|
| 12 |
+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
| 13 |
+
and/or sell copies of the Software, and to permit persons to whom the
|
| 14 |
+
Software is furnished to do so, subject to the following conditions:
|
| 15 |
+
|
| 16 |
+
The above copyright notice and this permission notice shall be included in
|
| 17 |
+
all copies or substantial portions of the Software.
|
| 18 |
+
|
| 19 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 20 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 21 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 22 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 23 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 24 |
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
| 25 |
+
DEALINGS IN THE SOFTWARE.
|
| 26 |
+
|
| 27 |
+
= = = = =
|
micromamba_root/Lib/site-packages/mypyc/analysis/__init__.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/analysis/__init__.py
ADDED
|
File without changes
|
micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Always defined attribute analysis.
|
| 2 |
+
|
| 3 |
+
An always defined attribute has some statements in __init__ or the
|
| 4 |
+
class body that cause the attribute to be always initialized when an
|
| 5 |
+
instance is constructed. It must also not be possible to read the
|
| 6 |
+
attribute before initialization, and it can't be deletable.
|
| 7 |
+
|
| 8 |
+
We can assume that the value is always defined when reading an always
|
| 9 |
+
defined attribute. Otherwise we'll need to raise AttributeError if the
|
| 10 |
+
value is undefined (i.e. has the error value).
|
| 11 |
+
|
| 12 |
+
We use data flow analysis to figure out attributes that are always
|
| 13 |
+
defined. Example:
|
| 14 |
+
|
| 15 |
+
class C:
|
| 16 |
+
def __init__(self) -> None:
|
| 17 |
+
self.x = 0
|
| 18 |
+
if func():
|
| 19 |
+
self.y = 1
|
| 20 |
+
else:
|
| 21 |
+
self.y = 2
|
| 22 |
+
self.z = 3
|
| 23 |
+
|
| 24 |
+
In this example, the attributes 'x' and 'y' are always defined, but 'z'
|
| 25 |
+
is not. The analysis assumes that we know that there won't be any subclasses.
|
| 26 |
+
|
| 27 |
+
The analysis also works if there is a known, closed set of subclasses.
|
| 28 |
+
An attribute defined in a base class can only be always defined if it's
|
| 29 |
+
also always defined in all subclasses.
|
| 30 |
+
|
| 31 |
+
As soon as __init__ contains an op that can 'leak' self to another
|
| 32 |
+
function, we will stop inferring always defined attributes, since the
|
| 33 |
+
analysis is mostly intra-procedural and only looks at __init__ methods.
|
| 34 |
+
The called code could read an uninitialized attribute. Example:
|
| 35 |
+
|
| 36 |
+
class C:
|
| 37 |
+
def __init__(self) -> None:
|
| 38 |
+
self.x = self.foo()
|
| 39 |
+
|
| 40 |
+
def foo(self) -> int:
|
| 41 |
+
...
|
| 42 |
+
|
| 43 |
+
Now we won't infer 'x' as always defined, since 'foo' might read 'x'
|
| 44 |
+
before initialization.
|
| 45 |
+
|
| 46 |
+
As an exception to the above limitation, we perform inter-procedural
|
| 47 |
+
analysis of super().__init__ calls, since these are very common.
|
| 48 |
+
|
| 49 |
+
Our analysis is somewhat optimistic. We assume that nobody calls a
|
| 50 |
+
method of a partially uninitialized object through gc.get_objects(), in
|
| 51 |
+
particular. Code like this could potentially cause a segfault with a null
|
| 52 |
+
pointer dereference. This seems very unlikely to be an issue in practice,
|
| 53 |
+
however.
|
| 54 |
+
|
| 55 |
+
Accessing an attribute via getattr always checks for undefined attributes
|
| 56 |
+
and thus works if the object is partially uninitialized. This can be used
|
| 57 |
+
as a workaround if somebody ever needs to inspect partially uninitialized
|
| 58 |
+
objects via gc.get_objects().
|
| 59 |
+
|
| 60 |
+
The analysis runs after IR building as a separate pass. Since we only
|
| 61 |
+
run this on __init__ methods, this analysis pass will be fairly quick.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
from __future__ import annotations
|
| 65 |
+
|
| 66 |
+
from typing import Final
|
| 67 |
+
|
| 68 |
+
from mypyc.analysis.dataflow import (
|
| 69 |
+
CFG,
|
| 70 |
+
MAYBE_ANALYSIS,
|
| 71 |
+
AnalysisResult,
|
| 72 |
+
BaseAnalysisVisitor,
|
| 73 |
+
get_cfg,
|
| 74 |
+
run_analysis,
|
| 75 |
+
)
|
| 76 |
+
from mypyc.analysis.selfleaks import analyze_self_leaks
|
| 77 |
+
from mypyc.ir.class_ir import ClassIR
|
| 78 |
+
from mypyc.ir.ops import (
|
| 79 |
+
Assign,
|
| 80 |
+
AssignMulti,
|
| 81 |
+
BasicBlock,
|
| 82 |
+
Branch,
|
| 83 |
+
Call,
|
| 84 |
+
ControlOp,
|
| 85 |
+
GetAttr,
|
| 86 |
+
Register,
|
| 87 |
+
RegisterOp,
|
| 88 |
+
Return,
|
| 89 |
+
SetAttr,
|
| 90 |
+
SetMem,
|
| 91 |
+
Unreachable,
|
| 92 |
+
)
|
| 93 |
+
from mypyc.ir.rtypes import RInstance
|
| 94 |
+
|
| 95 |
+
# If True, print out all always-defined attributes of native classes (to aid
|
| 96 |
+
# debugging and testing)
|
| 97 |
+
dump_always_defined: Final = False
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def analyze_always_defined_attrs(class_irs: list[ClassIR]) -> None:
|
| 101 |
+
"""Find always defined attributes all classes of a compilation unit.
|
| 102 |
+
|
| 103 |
+
Also tag attribute initialization ops to not decref the previous
|
| 104 |
+
value (as this would read a NULL pointer and segfault).
|
| 105 |
+
|
| 106 |
+
Update the _always_initialized_attrs, _sometimes_initialized_attrs
|
| 107 |
+
and init_self_leak attributes in ClassIR instances.
|
| 108 |
+
|
| 109 |
+
This is the main entry point.
|
| 110 |
+
"""
|
| 111 |
+
seen: set[ClassIR] = set()
|
| 112 |
+
|
| 113 |
+
# First pass: only look at target class and classes in MRO
|
| 114 |
+
for cl in class_irs:
|
| 115 |
+
analyze_always_defined_attrs_in_class(cl, seen)
|
| 116 |
+
|
| 117 |
+
# Second pass: look at all derived class
|
| 118 |
+
seen = set()
|
| 119 |
+
for cl in class_irs:
|
| 120 |
+
update_always_defined_attrs_using_subclasses(cl, seen)
|
| 121 |
+
|
| 122 |
+
# Final pass: detect attributes that need to use a bitmap to track definedness
|
| 123 |
+
seen = set()
|
| 124 |
+
for cl in class_irs:
|
| 125 |
+
detect_undefined_bitmap(cl, seen)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def analyze_always_defined_attrs_in_class(cl: ClassIR, seen: set[ClassIR]) -> None:
|
| 129 |
+
if cl in seen:
|
| 130 |
+
return
|
| 131 |
+
|
| 132 |
+
seen.add(cl)
|
| 133 |
+
|
| 134 |
+
if (
|
| 135 |
+
cl.is_trait
|
| 136 |
+
or cl.inherits_python
|
| 137 |
+
or cl.allow_interpreted_subclasses
|
| 138 |
+
or cl.builtin_base is not None
|
| 139 |
+
or cl.children is None
|
| 140 |
+
or cl.is_serializable()
|
| 141 |
+
or cl.has_method("__new__")
|
| 142 |
+
):
|
| 143 |
+
# Give up -- we can't enforce that attributes are always defined.
|
| 144 |
+
return
|
| 145 |
+
|
| 146 |
+
# First analyze all base classes. Track seen classes to avoid duplicate work.
|
| 147 |
+
for base in cl.mro[1:]:
|
| 148 |
+
analyze_always_defined_attrs_in_class(base, seen)
|
| 149 |
+
|
| 150 |
+
m = cl.get_method("__init__")
|
| 151 |
+
if m is None:
|
| 152 |
+
cl._always_initialized_attrs = cl.attrs_with_defaults.copy()
|
| 153 |
+
cl._sometimes_initialized_attrs = cl.attrs_with_defaults.copy()
|
| 154 |
+
return
|
| 155 |
+
self_reg = m.arg_regs[0]
|
| 156 |
+
cfg = get_cfg(m.blocks)
|
| 157 |
+
dirty = analyze_self_leaks(m.blocks, self_reg, cfg)
|
| 158 |
+
maybe_defined = analyze_maybe_defined_attrs_in_init(
|
| 159 |
+
m.blocks, self_reg, cl.attrs_with_defaults, cfg
|
| 160 |
+
)
|
| 161 |
+
all_attrs: set[str] = set()
|
| 162 |
+
for base in cl.mro:
|
| 163 |
+
all_attrs.update(base.attributes)
|
| 164 |
+
maybe_undefined = analyze_maybe_undefined_attrs_in_init(
|
| 165 |
+
m.blocks, self_reg, initial_undefined=all_attrs - cl.attrs_with_defaults, cfg=cfg
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
always_defined = find_always_defined_attributes(
|
| 169 |
+
m.blocks, self_reg, all_attrs, maybe_defined, maybe_undefined, dirty
|
| 170 |
+
)
|
| 171 |
+
always_defined = {a for a in always_defined if not cl.is_deletable(a)}
|
| 172 |
+
|
| 173 |
+
cl._always_initialized_attrs = always_defined
|
| 174 |
+
if dump_always_defined:
|
| 175 |
+
print(cl.name, sorted(always_defined))
|
| 176 |
+
cl._sometimes_initialized_attrs = find_sometimes_defined_attributes(
|
| 177 |
+
m.blocks, self_reg, maybe_defined, dirty
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
mark_attr_initialization_ops(m.blocks, self_reg, maybe_defined, dirty)
|
| 181 |
+
|
| 182 |
+
# Check if __init__ can run unpredictable code (leak 'self').
|
| 183 |
+
any_dirty = False
|
| 184 |
+
for b in m.blocks:
|
| 185 |
+
for i, op in enumerate(b.ops):
|
| 186 |
+
if dirty.after[b, i] and not isinstance(op, Return):
|
| 187 |
+
any_dirty = True
|
| 188 |
+
break
|
| 189 |
+
cl.init_self_leak = any_dirty
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def find_always_defined_attributes(
|
| 193 |
+
blocks: list[BasicBlock],
|
| 194 |
+
self_reg: Register,
|
| 195 |
+
all_attrs: set[str],
|
| 196 |
+
maybe_defined: AnalysisResult[str],
|
| 197 |
+
maybe_undefined: AnalysisResult[str],
|
| 198 |
+
dirty: AnalysisResult[None],
|
| 199 |
+
) -> set[str]:
|
| 200 |
+
"""Find attributes that are always initialized in some basic blocks.
|
| 201 |
+
|
| 202 |
+
The analysis results are expected to be up-to-date for the blocks.
|
| 203 |
+
|
| 204 |
+
Return a set of always defined attributes.
|
| 205 |
+
"""
|
| 206 |
+
attrs = all_attrs.copy()
|
| 207 |
+
for block in blocks:
|
| 208 |
+
for i, op in enumerate(block.ops):
|
| 209 |
+
# If an attribute we *read* may be undefined, it isn't always defined.
|
| 210 |
+
if isinstance(op, GetAttr) and op.obj is self_reg:
|
| 211 |
+
if op.attr in maybe_undefined.before[block, i]:
|
| 212 |
+
attrs.discard(op.attr)
|
| 213 |
+
# If an attribute we *set* may be sometimes undefined and
|
| 214 |
+
# sometimes defined, don't consider it always defined. Unlike
|
| 215 |
+
# the get case, it's fine for the attribute to be undefined.
|
| 216 |
+
# The set operation will then be treated as initialization.
|
| 217 |
+
if isinstance(op, SetAttr) and op.obj is self_reg:
|
| 218 |
+
if (
|
| 219 |
+
op.attr in maybe_undefined.before[block, i]
|
| 220 |
+
and op.attr in maybe_defined.before[block, i]
|
| 221 |
+
):
|
| 222 |
+
attrs.discard(op.attr)
|
| 223 |
+
# Treat an op that might run arbitrary code as an "exit"
|
| 224 |
+
# in terms of the analysis -- we can't do any inference
|
| 225 |
+
# afterwards reliably.
|
| 226 |
+
if dirty.after[block, i]:
|
| 227 |
+
if not dirty.before[block, i]:
|
| 228 |
+
attrs = attrs & (
|
| 229 |
+
maybe_defined.after[block, i] - maybe_undefined.after[block, i]
|
| 230 |
+
)
|
| 231 |
+
break
|
| 232 |
+
if isinstance(op, ControlOp):
|
| 233 |
+
for target in op.targets():
|
| 234 |
+
# Gotos/branches can also be "exits".
|
| 235 |
+
if not dirty.after[block, i] and dirty.before[target, 0]:
|
| 236 |
+
attrs = attrs & (
|
| 237 |
+
maybe_defined.after[target, 0] - maybe_undefined.after[target, 0]
|
| 238 |
+
)
|
| 239 |
+
return attrs
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def find_sometimes_defined_attributes(
|
| 243 |
+
blocks: list[BasicBlock],
|
| 244 |
+
self_reg: Register,
|
| 245 |
+
maybe_defined: AnalysisResult[str],
|
| 246 |
+
dirty: AnalysisResult[None],
|
| 247 |
+
) -> set[str]:
|
| 248 |
+
"""Find attributes that are sometimes initialized in some basic blocks."""
|
| 249 |
+
attrs: set[str] = set()
|
| 250 |
+
for block in blocks:
|
| 251 |
+
for i, op in enumerate(block.ops):
|
| 252 |
+
# Only look at possibly defined attributes at exits.
|
| 253 |
+
if dirty.after[block, i]:
|
| 254 |
+
if not dirty.before[block, i]:
|
| 255 |
+
attrs = attrs | maybe_defined.after[block, i]
|
| 256 |
+
break
|
| 257 |
+
if isinstance(op, ControlOp):
|
| 258 |
+
for target in op.targets():
|
| 259 |
+
if not dirty.after[block, i] and dirty.before[target, 0]:
|
| 260 |
+
attrs = attrs | maybe_defined.after[target, 0]
|
| 261 |
+
return attrs
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def mark_attr_initialization_ops(
|
| 265 |
+
blocks: list[BasicBlock],
|
| 266 |
+
self_reg: Register,
|
| 267 |
+
maybe_defined: AnalysisResult[str],
|
| 268 |
+
dirty: AnalysisResult[None],
|
| 269 |
+
) -> None:
|
| 270 |
+
"""Tag all SetAttr ops in the basic blocks that initialize attributes.
|
| 271 |
+
|
| 272 |
+
Initialization ops assume that the previous attribute value is the error value,
|
| 273 |
+
so there's no need to decref or check for definedness.
|
| 274 |
+
"""
|
| 275 |
+
for block in blocks:
|
| 276 |
+
for i, op in enumerate(block.ops):
|
| 277 |
+
if isinstance(op, SetAttr) and op.obj is self_reg:
|
| 278 |
+
attr = op.attr
|
| 279 |
+
if attr not in maybe_defined.before[block, i] and not dirty.after[block, i]:
|
| 280 |
+
op.mark_as_initializer()
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
GenAndKill = tuple[set[str], set[str]]
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def attributes_initialized_by_init_call(op: Call) -> set[str]:
|
| 287 |
+
"""Calculate attributes that are always initialized by a super().__init__ call."""
|
| 288 |
+
self_type = op.fn.sig.args[0].type
|
| 289 |
+
assert isinstance(self_type, RInstance), self_type
|
| 290 |
+
cl = self_type.class_ir
|
| 291 |
+
return {a for base in cl.mro for a in base.attributes if base.is_always_defined(a)}
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def attributes_maybe_initialized_by_init_call(op: Call) -> set[str]:
|
| 295 |
+
"""Calculate attributes that may be initialized by a super().__init__ call."""
|
| 296 |
+
self_type = op.fn.sig.args[0].type
|
| 297 |
+
assert isinstance(self_type, RInstance), self_type
|
| 298 |
+
cl = self_type.class_ir
|
| 299 |
+
return attributes_initialized_by_init_call(op) | cl._sometimes_initialized_attrs
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class AttributeMaybeDefinedVisitor(BaseAnalysisVisitor[str]):
|
| 303 |
+
"""Find attributes that may have been defined via some code path.
|
| 304 |
+
|
| 305 |
+
Consider initializations in class body and assignments to 'self.x'
|
| 306 |
+
and calls to base class '__init__'.
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
def __init__(self, self_reg: Register) -> None:
|
| 310 |
+
self.self_reg = self_reg
|
| 311 |
+
|
| 312 |
+
def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]:
|
| 313 |
+
return set(), set()
|
| 314 |
+
|
| 315 |
+
def visit_return(self, op: Return) -> tuple[set[str], set[str]]:
|
| 316 |
+
return set(), set()
|
| 317 |
+
|
| 318 |
+
def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]:
|
| 319 |
+
return set(), set()
|
| 320 |
+
|
| 321 |
+
def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]:
|
| 322 |
+
if isinstance(op, SetAttr) and op.obj is self.self_reg:
|
| 323 |
+
return {op.attr}, set()
|
| 324 |
+
if isinstance(op, Call) and op.fn.class_name and op.fn.name == "__init__":
|
| 325 |
+
return attributes_maybe_initialized_by_init_call(op), set()
|
| 326 |
+
return set(), set()
|
| 327 |
+
|
| 328 |
+
def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]:
|
| 329 |
+
return set(), set()
|
| 330 |
+
|
| 331 |
+
def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]:
|
| 332 |
+
return set(), set()
|
| 333 |
+
|
| 334 |
+
def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]:
|
| 335 |
+
return set(), set()
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def analyze_maybe_defined_attrs_in_init(
|
| 339 |
+
blocks: list[BasicBlock], self_reg: Register, attrs_with_defaults: set[str], cfg: CFG
|
| 340 |
+
) -> AnalysisResult[str]:
|
| 341 |
+
return run_analysis(
|
| 342 |
+
blocks=blocks,
|
| 343 |
+
cfg=cfg,
|
| 344 |
+
gen_and_kill=AttributeMaybeDefinedVisitor(self_reg),
|
| 345 |
+
initial=attrs_with_defaults,
|
| 346 |
+
backward=False,
|
| 347 |
+
kind=MAYBE_ANALYSIS,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class AttributeMaybeUndefinedVisitor(BaseAnalysisVisitor[str]):
|
| 352 |
+
"""Find attributes that may be undefined via some code path.
|
| 353 |
+
|
| 354 |
+
Consider initializations in class body, assignments to 'self.x'
|
| 355 |
+
and calls to base class '__init__'.
|
| 356 |
+
"""
|
| 357 |
+
|
| 358 |
+
def __init__(self, self_reg: Register) -> None:
|
| 359 |
+
self.self_reg = self_reg
|
| 360 |
+
|
| 361 |
+
def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]:
|
| 362 |
+
return set(), set()
|
| 363 |
+
|
| 364 |
+
def visit_return(self, op: Return) -> tuple[set[str], set[str]]:
|
| 365 |
+
return set(), set()
|
| 366 |
+
|
| 367 |
+
def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]:
|
| 368 |
+
return set(), set()
|
| 369 |
+
|
| 370 |
+
def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]:
|
| 371 |
+
if isinstance(op, SetAttr) and op.obj is self.self_reg:
|
| 372 |
+
return set(), {op.attr}
|
| 373 |
+
if isinstance(op, Call) and op.fn.class_name and op.fn.name == "__init__":
|
| 374 |
+
return set(), attributes_initialized_by_init_call(op)
|
| 375 |
+
return set(), set()
|
| 376 |
+
|
| 377 |
+
def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]:
|
| 378 |
+
return set(), set()
|
| 379 |
+
|
| 380 |
+
def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]:
|
| 381 |
+
return set(), set()
|
| 382 |
+
|
| 383 |
+
def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]:
|
| 384 |
+
return set(), set()
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def analyze_maybe_undefined_attrs_in_init(
|
| 388 |
+
blocks: list[BasicBlock], self_reg: Register, initial_undefined: set[str], cfg: CFG
|
| 389 |
+
) -> AnalysisResult[str]:
|
| 390 |
+
return run_analysis(
|
| 391 |
+
blocks=blocks,
|
| 392 |
+
cfg=cfg,
|
| 393 |
+
gen_and_kill=AttributeMaybeUndefinedVisitor(self_reg),
|
| 394 |
+
initial=initial_undefined,
|
| 395 |
+
backward=False,
|
| 396 |
+
kind=MAYBE_ANALYSIS,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def update_always_defined_attrs_using_subclasses(cl: ClassIR, seen: set[ClassIR]) -> None:
|
| 401 |
+
"""Remove attributes not defined in all subclasses from always defined attrs."""
|
| 402 |
+
if cl in seen:
|
| 403 |
+
return
|
| 404 |
+
if cl.children is None:
|
| 405 |
+
# Subclasses are unknown
|
| 406 |
+
return
|
| 407 |
+
removed = set()
|
| 408 |
+
for attr in cl._always_initialized_attrs:
|
| 409 |
+
for child in cl.children:
|
| 410 |
+
update_always_defined_attrs_using_subclasses(child, seen)
|
| 411 |
+
if attr not in child._always_initialized_attrs:
|
| 412 |
+
removed.add(attr)
|
| 413 |
+
cl._always_initialized_attrs -= removed
|
| 414 |
+
seen.add(cl)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def detect_undefined_bitmap(cl: ClassIR, seen: set[ClassIR]) -> None:
|
| 418 |
+
if cl.is_trait:
|
| 419 |
+
return
|
| 420 |
+
|
| 421 |
+
if cl in seen:
|
| 422 |
+
return
|
| 423 |
+
seen.add(cl)
|
| 424 |
+
for base in cl.base_mro[1:]:
|
| 425 |
+
detect_undefined_bitmap(base, seen)
|
| 426 |
+
|
| 427 |
+
if len(cl.base_mro) > 1:
|
| 428 |
+
cl.bitmap_attrs.extend(cl.base_mro[1].bitmap_attrs)
|
| 429 |
+
for n, t in cl.attributes.items():
|
| 430 |
+
if t.error_overlap and not cl.is_always_defined(n):
|
| 431 |
+
cl.bitmap_attrs.append(n)
|
| 432 |
+
|
| 433 |
+
for base in cl.mro[1:]:
|
| 434 |
+
if base.is_trait:
|
| 435 |
+
for n, t in base.attributes.items():
|
| 436 |
+
if t.error_overlap and not cl.is_always_defined(n) and n not in cl.bitmap_attrs:
|
| 437 |
+
cl.bitmap_attrs.append(n)
|
micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Find basic blocks that are likely to be executed frequently.
|
| 2 |
+
|
| 3 |
+
For example, this would not include blocks that have exception handlers.
|
| 4 |
+
|
| 5 |
+
We can use different optimization heuristics for common and rare code. For
|
| 6 |
+
example, we can make IR fast to compile instead of fast to execute for rare
|
| 7 |
+
code.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from mypyc.ir.ops import BasicBlock, Branch, Goto
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def frequently_executed_blocks(entry_point: BasicBlock) -> set[BasicBlock]:
|
| 16 |
+
result: set[BasicBlock] = set()
|
| 17 |
+
worklist = [entry_point]
|
| 18 |
+
while worklist:
|
| 19 |
+
block = worklist.pop()
|
| 20 |
+
if block in result:
|
| 21 |
+
continue
|
| 22 |
+
result.add(block)
|
| 23 |
+
t = block.terminator
|
| 24 |
+
if isinstance(t, Goto):
|
| 25 |
+
worklist.append(t.label)
|
| 26 |
+
elif isinstance(t, Branch):
|
| 27 |
+
if t.rare or t.traceback_entry is not None:
|
| 28 |
+
worklist.append(t.false)
|
| 29 |
+
else:
|
| 30 |
+
worklist.append(t.true)
|
| 31 |
+
worklist.append(t.false)
|
| 32 |
+
return result
|
micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from mypyc.ir.class_ir import ClassIR
|
| 4 |
+
from mypyc.ir.deps import Dependency
|
| 5 |
+
from mypyc.ir.func_ir import FuncIR
|
| 6 |
+
from mypyc.ir.ops import Assign, CallC, PrimitiveOp
|
| 7 |
+
from mypyc.ir.rtypes import RStruct, RTuple, RType, RUnion, RVec
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def find_implicit_op_dependencies(fn: FuncIR) -> set[Dependency] | None:
|
| 11 |
+
"""Find implicit dependencies that need to be imported.
|
| 12 |
+
|
| 13 |
+
Using primitives or types defined in librt submodules such as "librt.base64"
|
| 14 |
+
requires dependency imports (e.g., capsule imports).
|
| 15 |
+
|
| 16 |
+
Note that a module can depend on a librt module even if it doesn't explicitly
|
| 17 |
+
import it, for example via re-exported names or via return types of functions
|
| 18 |
+
defined in other modules.
|
| 19 |
+
"""
|
| 20 |
+
deps: set[Dependency] | None = None
|
| 21 |
+
# Check function signature types for dependencies
|
| 22 |
+
deps = find_type_dependencies(fn, deps)
|
| 23 |
+
# Check ops for dependencies
|
| 24 |
+
for block in fn.blocks:
|
| 25 |
+
for op in block.ops:
|
| 26 |
+
assert not isinstance(op, PrimitiveOp), "Lowered IR is expected"
|
| 27 |
+
if isinstance(op, CallC) and op.dependencies is not None:
|
| 28 |
+
for dep in op.dependencies:
|
| 29 |
+
if deps is None:
|
| 30 |
+
deps = set()
|
| 31 |
+
deps.add(dep)
|
| 32 |
+
deps = collect_type_deps(op.type, deps)
|
| 33 |
+
if isinstance(op, Assign):
|
| 34 |
+
deps = collect_type_deps(op.dest.type, deps)
|
| 35 |
+
return deps
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def find_type_dependencies(fn: FuncIR, deps: set[Dependency] | None) -> set[Dependency] | None:
|
| 39 |
+
"""Find dependencies from RTypes in function signatures.
|
| 40 |
+
|
| 41 |
+
Some RTypes (e.g., those for librt types) have associated dependencies
|
| 42 |
+
that need to be imported when the type is used.
|
| 43 |
+
"""
|
| 44 |
+
# Check parameter types
|
| 45 |
+
for arg in fn.decl.sig.args:
|
| 46 |
+
deps = collect_type_deps(arg.type, deps)
|
| 47 |
+
# Check return type
|
| 48 |
+
deps = collect_type_deps(fn.decl.sig.ret_type, deps)
|
| 49 |
+
return deps
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def find_class_dependencies(cl: ClassIR) -> set[Dependency] | None:
|
| 53 |
+
"""Find dependencies from class attribute types."""
|
| 54 |
+
deps: set[Dependency] | None = None
|
| 55 |
+
for base in cl.mro:
|
| 56 |
+
for attr_type in base.attributes.values():
|
| 57 |
+
deps = collect_type_deps(attr_type, deps)
|
| 58 |
+
return deps
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def collect_type_deps(typ: RType, deps: set[Dependency] | None) -> set[Dependency] | None:
|
| 62 |
+
"""Collect dependencies from an RType, recursively checking compound types."""
|
| 63 |
+
if typ.dependencies is not None:
|
| 64 |
+
for dep in typ.dependencies:
|
| 65 |
+
if deps is None:
|
| 66 |
+
deps = set()
|
| 67 |
+
deps.add(dep)
|
| 68 |
+
if isinstance(typ, RUnion):
|
| 69 |
+
for item in typ.items:
|
| 70 |
+
deps = collect_type_deps(item, deps)
|
| 71 |
+
elif isinstance(typ, RTuple):
|
| 72 |
+
for item in typ.types:
|
| 73 |
+
deps = collect_type_deps(item, deps)
|
| 74 |
+
elif isinstance(typ, RStruct):
|
| 75 |
+
for item in typ.types:
|
| 76 |
+
deps = collect_type_deps(item, deps)
|
| 77 |
+
elif isinstance(typ, RVec):
|
| 78 |
+
deps = collect_type_deps(typ.item_type, deps)
|
| 79 |
+
return deps
|
micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.py
ADDED
|
@@ -0,0 +1,645 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Data-flow analyses."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from abc import abstractmethod
|
| 6 |
+
from collections.abc import Iterable, Iterator, Set as AbstractSet
|
| 7 |
+
from typing import Any, Generic, TypeVar
|
| 8 |
+
|
| 9 |
+
from mypyc.ir.ops import (
|
| 10 |
+
Assign,
|
| 11 |
+
AssignMulti,
|
| 12 |
+
BasicBlock,
|
| 13 |
+
Box,
|
| 14 |
+
Branch,
|
| 15 |
+
Call,
|
| 16 |
+
CallC,
|
| 17 |
+
Cast,
|
| 18 |
+
ComparisonOp,
|
| 19 |
+
ControlOp,
|
| 20 |
+
DecRef,
|
| 21 |
+
Extend,
|
| 22 |
+
Float,
|
| 23 |
+
FloatComparisonOp,
|
| 24 |
+
FloatNeg,
|
| 25 |
+
FloatOp,
|
| 26 |
+
GetAttr,
|
| 27 |
+
GetElement,
|
| 28 |
+
GetElementPtr,
|
| 29 |
+
Goto,
|
| 30 |
+
IncRef,
|
| 31 |
+
InitStatic,
|
| 32 |
+
Integer,
|
| 33 |
+
IntOp,
|
| 34 |
+
KeepAlive,
|
| 35 |
+
LoadAddress,
|
| 36 |
+
LoadErrorValue,
|
| 37 |
+
LoadGlobal,
|
| 38 |
+
LoadLiteral,
|
| 39 |
+
LoadMem,
|
| 40 |
+
LoadStatic,
|
| 41 |
+
MethodCall,
|
| 42 |
+
Op,
|
| 43 |
+
OpVisitor,
|
| 44 |
+
PrimitiveOp,
|
| 45 |
+
RaiseStandardError,
|
| 46 |
+
RegisterOp,
|
| 47 |
+
Return,
|
| 48 |
+
SetAttr,
|
| 49 |
+
SetElement,
|
| 50 |
+
SetMem,
|
| 51 |
+
Truncate,
|
| 52 |
+
TupleGet,
|
| 53 |
+
TupleSet,
|
| 54 |
+
Unborrow,
|
| 55 |
+
Unbox,
|
| 56 |
+
Undef,
|
| 57 |
+
Unreachable,
|
| 58 |
+
Value,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class CFG:
|
| 63 |
+
"""Control-flow graph.
|
| 64 |
+
|
| 65 |
+
Node 0 is always assumed to be the entry point. There must be a
|
| 66 |
+
non-empty set of exits.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(
|
| 70 |
+
self,
|
| 71 |
+
succ: dict[BasicBlock, list[BasicBlock]],
|
| 72 |
+
pred: dict[BasicBlock, list[BasicBlock]],
|
| 73 |
+
exits: set[BasicBlock],
|
| 74 |
+
) -> None:
|
| 75 |
+
assert exits
|
| 76 |
+
self.succ = succ
|
| 77 |
+
self.pred = pred
|
| 78 |
+
self.exits = exits
|
| 79 |
+
|
| 80 |
+
def __str__(self) -> str:
|
| 81 |
+
exits = sorted(self.exits, key=lambda e: int(e.label))
|
| 82 |
+
return f"exits: {exits}\nsucc: {self.succ}\npred: {self.pred}"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_cfg(blocks: list[BasicBlock], *, use_yields: bool = False) -> CFG:
|
| 86 |
+
"""Calculate basic block control-flow graph.
|
| 87 |
+
|
| 88 |
+
If use_yields is set, then we treat returns inserted by yields as gotos
|
| 89 |
+
instead of exits.
|
| 90 |
+
"""
|
| 91 |
+
succ_map = {}
|
| 92 |
+
pred_map: dict[BasicBlock, list[BasicBlock]] = {}
|
| 93 |
+
exits = set()
|
| 94 |
+
for block in blocks:
|
| 95 |
+
assert not any(
|
| 96 |
+
isinstance(op, ControlOp) for op in block.ops[:-1]
|
| 97 |
+
), "Control-flow ops must be at the end of blocks"
|
| 98 |
+
|
| 99 |
+
if use_yields and isinstance(block.terminator, Return) and block.terminator.yield_target:
|
| 100 |
+
succ = [block.terminator.yield_target]
|
| 101 |
+
else:
|
| 102 |
+
succ = list(block.terminator.targets())
|
| 103 |
+
if not succ:
|
| 104 |
+
exits.add(block)
|
| 105 |
+
|
| 106 |
+
# Errors can occur anywhere inside a block, which means that
|
| 107 |
+
# we can't assume that the entire block has executed before
|
| 108 |
+
# jumping to the error handler. In our CFG construction, we
|
| 109 |
+
# model this as saying that a block can jump to its error
|
| 110 |
+
# handler or the error handlers of any of its normal
|
| 111 |
+
# successors (to represent an error before that next block
|
| 112 |
+
# completes). This works well for analyses like "must
|
| 113 |
+
# defined", where it implies that registers assigned in a
|
| 114 |
+
# block may be undefined in its error handler, but is in
|
| 115 |
+
# general not a precise representation of reality; any
|
| 116 |
+
# analyses that require more fidelity must wait until after
|
| 117 |
+
# exception insertion.
|
| 118 |
+
for error_point in [block] + succ:
|
| 119 |
+
if error_point.error_handler:
|
| 120 |
+
succ.append(error_point.error_handler)
|
| 121 |
+
|
| 122 |
+
succ_map[block] = succ
|
| 123 |
+
pred_map[block] = []
|
| 124 |
+
for prev, nxt in succ_map.items():
|
| 125 |
+
for label in nxt:
|
| 126 |
+
pred_map[label].append(prev)
|
| 127 |
+
return CFG(succ_map, pred_map, exits)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def get_real_target(label: BasicBlock) -> BasicBlock:
|
| 131 |
+
if len(label.ops) == 1 and isinstance(label.ops[-1], Goto):
|
| 132 |
+
label = label.ops[-1].label
|
| 133 |
+
return label
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def cleanup_cfg(blocks: list[BasicBlock]) -> None:
|
| 137 |
+
"""Cleanup the control flow graph.
|
| 138 |
+
|
| 139 |
+
This eliminates obviously dead basic blocks and eliminates blocks that contain
|
| 140 |
+
nothing but a single jump.
|
| 141 |
+
|
| 142 |
+
There is a lot more that could be done.
|
| 143 |
+
"""
|
| 144 |
+
changed = True
|
| 145 |
+
while changed:
|
| 146 |
+
# First collapse any jumps to basic block that only contain a goto
|
| 147 |
+
for block in blocks:
|
| 148 |
+
for i, tgt in enumerate(block.terminator.targets()):
|
| 149 |
+
block.terminator.set_target(i, get_real_target(tgt))
|
| 150 |
+
|
| 151 |
+
# Then delete any blocks that have no predecessors
|
| 152 |
+
changed = False
|
| 153 |
+
cfg = get_cfg(blocks)
|
| 154 |
+
orig_blocks = blocks.copy()
|
| 155 |
+
blocks.clear()
|
| 156 |
+
for i, block in enumerate(orig_blocks):
|
| 157 |
+
if i == 0 or cfg.pred[block]:
|
| 158 |
+
blocks.append(block)
|
| 159 |
+
else:
|
| 160 |
+
changed = True
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
T = TypeVar("T")
|
| 164 |
+
|
| 165 |
+
AnalysisDict = dict[tuple[BasicBlock, int], set[T]]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class AnalysisResult(Generic[T]):
|
| 169 |
+
def __init__(self, before: AnalysisDict[T], after: AnalysisDict[T]) -> None:
|
| 170 |
+
self.before = before
|
| 171 |
+
self.after = after
|
| 172 |
+
|
| 173 |
+
def __str__(self) -> str:
|
| 174 |
+
return f"before: {self.before}\nafter: {self.after}\n"
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
GenAndKill = tuple[AbstractSet[T], AbstractSet[T]]
|
| 178 |
+
|
| 179 |
+
_EMPTY: tuple[frozenset[Any], frozenset[Any]] = (frozenset(), frozenset())
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class BaseAnalysisVisitor(OpVisitor[GenAndKill[T]]):
|
| 183 |
+
def visit_goto(self, op: Goto) -> GenAndKill[T]:
|
| 184 |
+
return _EMPTY
|
| 185 |
+
|
| 186 |
+
@abstractmethod
|
| 187 |
+
def visit_register_op(self, op: RegisterOp) -> GenAndKill[T]:
|
| 188 |
+
raise NotImplementedError
|
| 189 |
+
|
| 190 |
+
@abstractmethod
|
| 191 |
+
def visit_assign(self, op: Assign) -> GenAndKill[T]:
|
| 192 |
+
raise NotImplementedError
|
| 193 |
+
|
| 194 |
+
@abstractmethod
|
| 195 |
+
def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[T]:
|
| 196 |
+
raise NotImplementedError
|
| 197 |
+
|
| 198 |
+
@abstractmethod
|
| 199 |
+
def visit_set_mem(self, op: SetMem) -> GenAndKill[T]:
|
| 200 |
+
raise NotImplementedError
|
| 201 |
+
|
| 202 |
+
def visit_inc_ref(self, op: IncRef) -> GenAndKill[T]:
|
| 203 |
+
return self.visit_register_op(op)
|
| 204 |
+
|
| 205 |
+
def visit_dec_ref(self, op: DecRef) -> GenAndKill[T]:
|
| 206 |
+
return self.visit_register_op(op)
|
| 207 |
+
|
| 208 |
+
def visit_call(self, op: Call) -> GenAndKill[T]:
|
| 209 |
+
return self.visit_register_op(op)
|
| 210 |
+
|
| 211 |
+
def visit_method_call(self, op: MethodCall) -> GenAndKill[T]:
|
| 212 |
+
return self.visit_register_op(op)
|
| 213 |
+
|
| 214 |
+
def visit_load_error_value(self, op: LoadErrorValue) -> GenAndKill[T]:
|
| 215 |
+
return self.visit_register_op(op)
|
| 216 |
+
|
| 217 |
+
def visit_load_literal(self, op: LoadLiteral) -> GenAndKill[T]:
|
| 218 |
+
return self.visit_register_op(op)
|
| 219 |
+
|
| 220 |
+
def visit_get_attr(self, op: GetAttr) -> GenAndKill[T]:
|
| 221 |
+
return self.visit_register_op(op)
|
| 222 |
+
|
| 223 |
+
def visit_set_attr(self, op: SetAttr) -> GenAndKill[T]:
|
| 224 |
+
return self.visit_register_op(op)
|
| 225 |
+
|
| 226 |
+
def visit_load_static(self, op: LoadStatic) -> GenAndKill[T]:
|
| 227 |
+
return self.visit_register_op(op)
|
| 228 |
+
|
| 229 |
+
def visit_init_static(self, op: InitStatic) -> GenAndKill[T]:
|
| 230 |
+
return self.visit_register_op(op)
|
| 231 |
+
|
| 232 |
+
def visit_tuple_get(self, op: TupleGet) -> GenAndKill[T]:
|
| 233 |
+
return self.visit_register_op(op)
|
| 234 |
+
|
| 235 |
+
def visit_tuple_set(self, op: TupleSet) -> GenAndKill[T]:
|
| 236 |
+
return self.visit_register_op(op)
|
| 237 |
+
|
| 238 |
+
def visit_box(self, op: Box) -> GenAndKill[T]:
|
| 239 |
+
return self.visit_register_op(op)
|
| 240 |
+
|
| 241 |
+
def visit_unbox(self, op: Unbox) -> GenAndKill[T]:
|
| 242 |
+
return self.visit_register_op(op)
|
| 243 |
+
|
| 244 |
+
def visit_cast(self, op: Cast) -> GenAndKill[T]:
|
| 245 |
+
return self.visit_register_op(op)
|
| 246 |
+
|
| 247 |
+
def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill[T]:
|
| 248 |
+
return self.visit_register_op(op)
|
| 249 |
+
|
| 250 |
+
def visit_call_c(self, op: CallC) -> GenAndKill[T]:
|
| 251 |
+
return self.visit_register_op(op)
|
| 252 |
+
|
| 253 |
+
def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill[T]:
|
| 254 |
+
return self.visit_register_op(op)
|
| 255 |
+
|
| 256 |
+
def visit_truncate(self, op: Truncate) -> GenAndKill[T]:
|
| 257 |
+
return self.visit_register_op(op)
|
| 258 |
+
|
| 259 |
+
def visit_extend(self, op: Extend) -> GenAndKill[T]:
|
| 260 |
+
return self.visit_register_op(op)
|
| 261 |
+
|
| 262 |
+
def visit_load_global(self, op: LoadGlobal) -> GenAndKill[T]:
|
| 263 |
+
return self.visit_register_op(op)
|
| 264 |
+
|
| 265 |
+
def visit_int_op(self, op: IntOp) -> GenAndKill[T]:
|
| 266 |
+
return self.visit_register_op(op)
|
| 267 |
+
|
| 268 |
+
def visit_float_op(self, op: FloatOp) -> GenAndKill[T]:
|
| 269 |
+
return self.visit_register_op(op)
|
| 270 |
+
|
| 271 |
+
def visit_float_neg(self, op: FloatNeg) -> GenAndKill[T]:
|
| 272 |
+
return self.visit_register_op(op)
|
| 273 |
+
|
| 274 |
+
def visit_comparison_op(self, op: ComparisonOp) -> GenAndKill[T]:
|
| 275 |
+
return self.visit_register_op(op)
|
| 276 |
+
|
| 277 |
+
def visit_float_comparison_op(self, op: FloatComparisonOp) -> GenAndKill[T]:
|
| 278 |
+
return self.visit_register_op(op)
|
| 279 |
+
|
| 280 |
+
def visit_load_mem(self, op: LoadMem) -> GenAndKill[T]:
|
| 281 |
+
return self.visit_register_op(op)
|
| 282 |
+
|
| 283 |
+
def visit_get_element(self, op: GetElement) -> GenAndKill[T]:
|
| 284 |
+
return self.visit_register_op(op)
|
| 285 |
+
|
| 286 |
+
def visit_get_element_ptr(self, op: GetElementPtr) -> GenAndKill[T]:
|
| 287 |
+
return self.visit_register_op(op)
|
| 288 |
+
|
| 289 |
+
def visit_set_element(self, op: SetElement) -> GenAndKill[T]:
|
| 290 |
+
return self.visit_register_op(op)
|
| 291 |
+
|
| 292 |
+
def visit_load_address(self, op: LoadAddress) -> GenAndKill[T]:
|
| 293 |
+
return self.visit_register_op(op)
|
| 294 |
+
|
| 295 |
+
def visit_keep_alive(self, op: KeepAlive) -> GenAndKill[T]:
|
| 296 |
+
return self.visit_register_op(op)
|
| 297 |
+
|
| 298 |
+
def visit_unborrow(self, op: Unborrow) -> GenAndKill[T]:
|
| 299 |
+
return self.visit_register_op(op)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class DefinedVisitor(BaseAnalysisVisitor[Value]):
|
| 303 |
+
"""Visitor for finding defined registers.
|
| 304 |
+
|
| 305 |
+
Note that this only deals with registers and not temporaries, on
|
| 306 |
+
the assumption that we never access temporaries when they might be
|
| 307 |
+
undefined.
|
| 308 |
+
|
| 309 |
+
If strict_errors is True, then we regard any use of LoadErrorValue
|
| 310 |
+
as making a register undefined. Otherwise we only do if
|
| 311 |
+
`undefines` is set on the error value.
|
| 312 |
+
|
| 313 |
+
This lets us only consider the things we care about during
|
| 314 |
+
uninitialized variable checking while capturing all possibly
|
| 315 |
+
undefined things for refcounting.
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
def __init__(self, strict_errors: bool = False) -> None:
|
| 319 |
+
self.strict_errors = strict_errors
|
| 320 |
+
|
| 321 |
+
def visit_branch(self, op: Branch) -> GenAndKill[Value]:
|
| 322 |
+
return _EMPTY
|
| 323 |
+
|
| 324 |
+
def visit_return(self, op: Return) -> GenAndKill[Value]:
|
| 325 |
+
return _EMPTY
|
| 326 |
+
|
| 327 |
+
def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:
|
| 328 |
+
return _EMPTY
|
| 329 |
+
|
| 330 |
+
def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:
|
| 331 |
+
return _EMPTY
|
| 332 |
+
|
| 333 |
+
def visit_assign(self, op: Assign) -> GenAndKill[Value]:
|
| 334 |
+
# Loading an error value may undefine the register.
|
| 335 |
+
if isinstance(op.src, LoadErrorValue) and (op.src.undefines or self.strict_errors):
|
| 336 |
+
return set(), {op.dest}
|
| 337 |
+
else:
|
| 338 |
+
return {op.dest}, set()
|
| 339 |
+
|
| 340 |
+
def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:
|
| 341 |
+
# Array registers are special and we don't track the definedness of them.
|
| 342 |
+
return _EMPTY
|
| 343 |
+
|
| 344 |
+
def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:
|
| 345 |
+
return _EMPTY
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def analyze_maybe_defined_regs(
|
| 349 |
+
blocks: list[BasicBlock], cfg: CFG, initial_defined: set[Value]
|
| 350 |
+
) -> AnalysisResult[Value]:
|
| 351 |
+
"""Calculate potentially defined registers at each CFG location.
|
| 352 |
+
|
| 353 |
+
A register is defined if it has a value along some path from the initial location.
|
| 354 |
+
"""
|
| 355 |
+
return run_analysis(
|
| 356 |
+
blocks=blocks,
|
| 357 |
+
cfg=cfg,
|
| 358 |
+
gen_and_kill=DefinedVisitor(),
|
| 359 |
+
initial=initial_defined,
|
| 360 |
+
backward=False,
|
| 361 |
+
kind=MAYBE_ANALYSIS,
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def analyze_must_defined_regs(
|
| 366 |
+
blocks: list[BasicBlock],
|
| 367 |
+
cfg: CFG,
|
| 368 |
+
initial_defined: set[Value],
|
| 369 |
+
regs: Iterable[Value],
|
| 370 |
+
strict_errors: bool = False,
|
| 371 |
+
) -> AnalysisResult[Value]:
|
| 372 |
+
"""Calculate always defined registers at each CFG location.
|
| 373 |
+
|
| 374 |
+
This analysis can work before exception insertion, since it is a
|
| 375 |
+
sound assumption that registers defined in a block might not be
|
| 376 |
+
initialized in its error handler.
|
| 377 |
+
|
| 378 |
+
A register is defined if it has a value along all paths from the
|
| 379 |
+
initial location.
|
| 380 |
+
"""
|
| 381 |
+
return run_analysis(
|
| 382 |
+
blocks=blocks,
|
| 383 |
+
cfg=cfg,
|
| 384 |
+
gen_and_kill=DefinedVisitor(strict_errors=strict_errors),
|
| 385 |
+
initial=initial_defined,
|
| 386 |
+
backward=False,
|
| 387 |
+
kind=MUST_ANALYSIS,
|
| 388 |
+
universe=set(regs),
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class BorrowedArgumentsVisitor(BaseAnalysisVisitor[Value]):
|
| 393 |
+
def __init__(self, args: set[Value]) -> None:
|
| 394 |
+
self.args = args
|
| 395 |
+
|
| 396 |
+
def visit_branch(self, op: Branch) -> GenAndKill[Value]:
|
| 397 |
+
return _EMPTY
|
| 398 |
+
|
| 399 |
+
def visit_return(self, op: Return) -> GenAndKill[Value]:
|
| 400 |
+
return _EMPTY
|
| 401 |
+
|
| 402 |
+
def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:
|
| 403 |
+
return _EMPTY
|
| 404 |
+
|
| 405 |
+
def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:
|
| 406 |
+
return _EMPTY
|
| 407 |
+
|
| 408 |
+
def visit_assign(self, op: Assign) -> GenAndKill[Value]:
|
| 409 |
+
if op.dest in self.args:
|
| 410 |
+
return set(), {op.dest}
|
| 411 |
+
return _EMPTY
|
| 412 |
+
|
| 413 |
+
def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:
|
| 414 |
+
return _EMPTY
|
| 415 |
+
|
| 416 |
+
def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:
|
| 417 |
+
return _EMPTY
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def analyze_borrowed_arguments(
|
| 421 |
+
blocks: list[BasicBlock], cfg: CFG, borrowed: set[Value]
|
| 422 |
+
) -> AnalysisResult[Value]:
|
| 423 |
+
"""Calculate arguments that can use references borrowed from the caller.
|
| 424 |
+
|
| 425 |
+
When assigning to an argument, it no longer is borrowed.
|
| 426 |
+
"""
|
| 427 |
+
return run_analysis(
|
| 428 |
+
blocks=blocks,
|
| 429 |
+
cfg=cfg,
|
| 430 |
+
gen_and_kill=BorrowedArgumentsVisitor(borrowed),
|
| 431 |
+
initial=borrowed,
|
| 432 |
+
backward=False,
|
| 433 |
+
kind=MUST_ANALYSIS,
|
| 434 |
+
universe=borrowed,
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
class UndefinedVisitor(BaseAnalysisVisitor[Value]):
|
| 439 |
+
def visit_branch(self, op: Branch) -> GenAndKill[Value]:
|
| 440 |
+
return _EMPTY
|
| 441 |
+
|
| 442 |
+
def visit_return(self, op: Return) -> GenAndKill[Value]:
|
| 443 |
+
return _EMPTY
|
| 444 |
+
|
| 445 |
+
def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:
|
| 446 |
+
return _EMPTY
|
| 447 |
+
|
| 448 |
+
def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:
|
| 449 |
+
return set(), {op} if not op.is_void else set()
|
| 450 |
+
|
| 451 |
+
def visit_assign(self, op: Assign) -> GenAndKill[Value]:
|
| 452 |
+
return set(), {op.dest}
|
| 453 |
+
|
| 454 |
+
def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:
|
| 455 |
+
return set(), {op.dest}
|
| 456 |
+
|
| 457 |
+
def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:
|
| 458 |
+
return _EMPTY
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def non_trivial_sources(op: Op) -> set[Value]:
|
| 462 |
+
result = set()
|
| 463 |
+
for source in op.sources():
|
| 464 |
+
if not isinstance(source, (Integer, Float, Undef)):
|
| 465 |
+
result.add(source)
|
| 466 |
+
return result
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class LivenessVisitor(BaseAnalysisVisitor[Value]):
|
| 470 |
+
def visit_branch(self, op: Branch) -> GenAndKill[Value]:
|
| 471 |
+
return non_trivial_sources(op), set()
|
| 472 |
+
|
| 473 |
+
def visit_return(self, op: Return) -> GenAndKill[Value]:
|
| 474 |
+
if not isinstance(op.value, (Integer, Float)):
|
| 475 |
+
return {op.value}, set()
|
| 476 |
+
else:
|
| 477 |
+
return _EMPTY
|
| 478 |
+
|
| 479 |
+
def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:
|
| 480 |
+
return _EMPTY
|
| 481 |
+
|
| 482 |
+
def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:
|
| 483 |
+
gen = non_trivial_sources(op)
|
| 484 |
+
if not op.is_void:
|
| 485 |
+
return gen, {op}
|
| 486 |
+
else:
|
| 487 |
+
return gen, set()
|
| 488 |
+
|
| 489 |
+
def visit_assign(self, op: Assign) -> GenAndKill[Value]:
|
| 490 |
+
return non_trivial_sources(op), {op.dest}
|
| 491 |
+
|
| 492 |
+
def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:
|
| 493 |
+
return non_trivial_sources(op), {op.dest}
|
| 494 |
+
|
| 495 |
+
def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:
|
| 496 |
+
return non_trivial_sources(op), set()
|
| 497 |
+
|
| 498 |
+
def visit_inc_ref(self, op: IncRef) -> GenAndKill[Value]:
|
| 499 |
+
return _EMPTY
|
| 500 |
+
|
| 501 |
+
def visit_dec_ref(self, op: DecRef) -> GenAndKill[Value]:
|
| 502 |
+
return _EMPTY
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def analyze_live_regs(blocks: list[BasicBlock], cfg: CFG) -> AnalysisResult[Value]:
|
| 506 |
+
"""Calculate live registers at each CFG location.
|
| 507 |
+
|
| 508 |
+
A register is live at a location if it can be read along some CFG path starting
|
| 509 |
+
from the location.
|
| 510 |
+
"""
|
| 511 |
+
return run_analysis(
|
| 512 |
+
blocks=blocks,
|
| 513 |
+
cfg=cfg,
|
| 514 |
+
gen_and_kill=LivenessVisitor(),
|
| 515 |
+
initial=set(),
|
| 516 |
+
backward=True,
|
| 517 |
+
kind=MAYBE_ANALYSIS,
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
# Analysis kinds
|
| 522 |
+
MUST_ANALYSIS = 0
|
| 523 |
+
MAYBE_ANALYSIS = 1
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def run_analysis(
|
| 527 |
+
blocks: list[BasicBlock],
|
| 528 |
+
cfg: CFG,
|
| 529 |
+
gen_and_kill: OpVisitor[GenAndKill[T]],
|
| 530 |
+
initial: set[T],
|
| 531 |
+
kind: int,
|
| 532 |
+
backward: bool,
|
| 533 |
+
universe: set[T] | None = None,
|
| 534 |
+
) -> AnalysisResult[T]:
|
| 535 |
+
"""Run a general set-based data flow analysis.
|
| 536 |
+
|
| 537 |
+
Args:
|
| 538 |
+
blocks: All basic blocks
|
| 539 |
+
cfg: Control-flow graph for the code
|
| 540 |
+
gen_and_kill: Implementation of gen and kill functions for each op
|
| 541 |
+
initial: Value of analysis for the entry points (for a forward analysis) or the
|
| 542 |
+
exit points (for a backward analysis)
|
| 543 |
+
kind: MUST_ANALYSIS or MAYBE_ANALYSIS
|
| 544 |
+
backward: If False, the analysis is a forward analysis; it's backward otherwise
|
| 545 |
+
universe: For a must analysis, the set of all possible values. This is the starting
|
| 546 |
+
value for the work list algorithm, which will narrow this down until reaching a
|
| 547 |
+
fixed point. For a maybe analysis the iteration always starts from an empty set
|
| 548 |
+
and this argument is ignored.
|
| 549 |
+
|
| 550 |
+
Return analysis results: (before, after)
|
| 551 |
+
"""
|
| 552 |
+
block_gen = {}
|
| 553 |
+
block_kill = {}
|
| 554 |
+
|
| 555 |
+
# Calculate kill and gen sets for entire basic blocks.
|
| 556 |
+
for block in blocks:
|
| 557 |
+
gen: set[T] = set()
|
| 558 |
+
kill: set[T] = set()
|
| 559 |
+
ops = block.ops
|
| 560 |
+
if backward:
|
| 561 |
+
ops = list(reversed(ops))
|
| 562 |
+
for op in ops:
|
| 563 |
+
opgen, opkill = op.accept(gen_and_kill)
|
| 564 |
+
if opkill:
|
| 565 |
+
gen -= opkill
|
| 566 |
+
|
| 567 |
+
if opgen:
|
| 568 |
+
gen |= opgen
|
| 569 |
+
kill -= opgen
|
| 570 |
+
|
| 571 |
+
if opkill:
|
| 572 |
+
kill |= opkill
|
| 573 |
+
|
| 574 |
+
block_gen[block] = gen
|
| 575 |
+
block_kill[block] = kill
|
| 576 |
+
|
| 577 |
+
# Set up initial state for worklist algorithm.
|
| 578 |
+
worklist = list(blocks)
|
| 579 |
+
if not backward:
|
| 580 |
+
worklist.reverse() # Reverse for a small performance improvement
|
| 581 |
+
workset = set(worklist)
|
| 582 |
+
before: dict[BasicBlock, set[T]] = {}
|
| 583 |
+
after: dict[BasicBlock, set[T]] = {}
|
| 584 |
+
for block in blocks:
|
| 585 |
+
if kind == MAYBE_ANALYSIS:
|
| 586 |
+
before[block] = set()
|
| 587 |
+
after[block] = set()
|
| 588 |
+
else:
|
| 589 |
+
assert universe is not None, "Universe must be defined for a must analysis"
|
| 590 |
+
before[block] = set(universe)
|
| 591 |
+
after[block] = set(universe)
|
| 592 |
+
|
| 593 |
+
if backward:
|
| 594 |
+
pred_map = cfg.succ
|
| 595 |
+
succ_map = cfg.pred
|
| 596 |
+
else:
|
| 597 |
+
pred_map = cfg.pred
|
| 598 |
+
succ_map = cfg.succ
|
| 599 |
+
|
| 600 |
+
# Run work list algorithm to generate in and out sets for each basic block.
|
| 601 |
+
while worklist:
|
| 602 |
+
label = worklist.pop()
|
| 603 |
+
workset.remove(label)
|
| 604 |
+
if pred_map[label]:
|
| 605 |
+
new_before: set[T] | None = None
|
| 606 |
+
for pred in pred_map[label]:
|
| 607 |
+
if new_before is None:
|
| 608 |
+
new_before = set(after[pred])
|
| 609 |
+
elif kind == MAYBE_ANALYSIS:
|
| 610 |
+
new_before |= after[pred]
|
| 611 |
+
else:
|
| 612 |
+
new_before &= after[pred]
|
| 613 |
+
assert new_before is not None
|
| 614 |
+
else:
|
| 615 |
+
new_before = set(initial)
|
| 616 |
+
before[label] = new_before
|
| 617 |
+
new_after = (new_before - block_kill[label]) | block_gen[label]
|
| 618 |
+
if new_after != after[label]:
|
| 619 |
+
for succ in succ_map[label]:
|
| 620 |
+
if succ not in workset:
|
| 621 |
+
worklist.append(succ)
|
| 622 |
+
workset.add(succ)
|
| 623 |
+
after[label] = new_after
|
| 624 |
+
|
| 625 |
+
# Run algorithm for each basic block to generate opcode-level sets.
|
| 626 |
+
op_before: dict[tuple[BasicBlock, int], set[T]] = {}
|
| 627 |
+
op_after: dict[tuple[BasicBlock, int], set[T]] = {}
|
| 628 |
+
for block in blocks:
|
| 629 |
+
label = block
|
| 630 |
+
cur = before[label]
|
| 631 |
+
ops_enum: Iterator[tuple[int, Op]] = enumerate(block.ops)
|
| 632 |
+
if backward:
|
| 633 |
+
ops_enum = reversed(list(ops_enum))
|
| 634 |
+
for idx, op in ops_enum:
|
| 635 |
+
op_before[label, idx] = cur
|
| 636 |
+
opgen, opkill = op.accept(gen_and_kill)
|
| 637 |
+
if opkill:
|
| 638 |
+
cur = cur - opkill
|
| 639 |
+
if opgen:
|
| 640 |
+
cur = cur | opgen
|
| 641 |
+
op_after[label, idx] = cur
|
| 642 |
+
if backward:
|
| 643 |
+
op_after, op_before = op_before, op_after
|
| 644 |
+
|
| 645 |
+
return AnalysisResult(op_before, op_after)
|
micromamba_root/Lib/site-packages/mypyc/analysis/ircheck.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 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""Utilities for checking that internal ir is valid and consistent."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncIR
|
| 6 |
+
from mypyc.ir.ops import (
|
| 7 |
+
Assign,
|
| 8 |
+
AssignMulti,
|
| 9 |
+
BaseAssign,
|
| 10 |
+
BasicBlock,
|
| 11 |
+
Box,
|
| 12 |
+
Branch,
|
| 13 |
+
Call,
|
| 14 |
+
CallC,
|
| 15 |
+
Cast,
|
| 16 |
+
ComparisonOp,
|
| 17 |
+
ControlOp,
|
| 18 |
+
DecRef,
|
| 19 |
+
Extend,
|
| 20 |
+
Float,
|
| 21 |
+
FloatComparisonOp,
|
| 22 |
+
FloatNeg,
|
| 23 |
+
FloatOp,
|
| 24 |
+
GetAttr,
|
| 25 |
+
GetElement,
|
| 26 |
+
GetElementPtr,
|
| 27 |
+
Goto,
|
| 28 |
+
IncRef,
|
| 29 |
+
InitStatic,
|
| 30 |
+
Integer,
|
| 31 |
+
IntOp,
|
| 32 |
+
KeepAlive,
|
| 33 |
+
LoadAddress,
|
| 34 |
+
LoadErrorValue,
|
| 35 |
+
LoadGlobal,
|
| 36 |
+
LoadLiteral,
|
| 37 |
+
LoadMem,
|
| 38 |
+
LoadStatic,
|
| 39 |
+
MethodCall,
|
| 40 |
+
Op,
|
| 41 |
+
OpVisitor,
|
| 42 |
+
PrimitiveOp,
|
| 43 |
+
RaiseStandardError,
|
| 44 |
+
Register,
|
| 45 |
+
Return,
|
| 46 |
+
SetAttr,
|
| 47 |
+
SetElement,
|
| 48 |
+
SetMem,
|
| 49 |
+
Truncate,
|
| 50 |
+
TupleGet,
|
| 51 |
+
TupleSet,
|
| 52 |
+
Unborrow,
|
| 53 |
+
Unbox,
|
| 54 |
+
Undef,
|
| 55 |
+
Unreachable,
|
| 56 |
+
Value,
|
| 57 |
+
)
|
| 58 |
+
from mypyc.ir.pprint import format_func
|
| 59 |
+
from mypyc.ir.rtypes import (
|
| 60 |
+
KNOWN_NATIVE_TYPES,
|
| 61 |
+
RArray,
|
| 62 |
+
RInstance,
|
| 63 |
+
RPrimitive,
|
| 64 |
+
RType,
|
| 65 |
+
RUnion,
|
| 66 |
+
RVec,
|
| 67 |
+
bytes_rprimitive,
|
| 68 |
+
dict_rprimitive,
|
| 69 |
+
int_rprimitive,
|
| 70 |
+
is_c_py_ssize_t_rprimitive,
|
| 71 |
+
is_fixed_width_rtype,
|
| 72 |
+
is_float_rprimitive,
|
| 73 |
+
is_object_rprimitive,
|
| 74 |
+
is_pointer_rprimitive,
|
| 75 |
+
list_rprimitive,
|
| 76 |
+
pointer_rprimitive,
|
| 77 |
+
range_rprimitive,
|
| 78 |
+
set_rprimitive,
|
| 79 |
+
str_rprimitive,
|
| 80 |
+
tuple_rprimitive,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class FnError:
|
| 85 |
+
def __init__(self, source: Op | BasicBlock, desc: str) -> None:
|
| 86 |
+
self.source = source
|
| 87 |
+
self.desc = desc
|
| 88 |
+
|
| 89 |
+
def __eq__(self, other: object) -> bool:
|
| 90 |
+
return (
|
| 91 |
+
isinstance(other, FnError) and self.source == other.source and self.desc == other.desc
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def __repr__(self) -> str:
|
| 95 |
+
return f"FnError(source={self.source}, desc={self.desc})"
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def check_func_ir(fn: FuncIR) -> list[FnError]:
|
| 99 |
+
"""Applies validations to a given function ir and returns a list of errors found."""
|
| 100 |
+
errors = []
|
| 101 |
+
|
| 102 |
+
op_set = set()
|
| 103 |
+
|
| 104 |
+
for block in fn.blocks:
|
| 105 |
+
if not block.terminated:
|
| 106 |
+
errors.append(
|
| 107 |
+
FnError(source=block.ops[-1] if block.ops else block, desc="Block not terminated")
|
| 108 |
+
)
|
| 109 |
+
for op in block.ops[:-1]:
|
| 110 |
+
if isinstance(op, ControlOp):
|
| 111 |
+
errors.append(FnError(source=op, desc="Block has operations after control op"))
|
| 112 |
+
|
| 113 |
+
if op in op_set:
|
| 114 |
+
errors.append(FnError(source=op, desc="Func has a duplicate op"))
|
| 115 |
+
op_set.add(op)
|
| 116 |
+
|
| 117 |
+
errors.extend(check_op_sources_valid(fn))
|
| 118 |
+
if errors:
|
| 119 |
+
return errors
|
| 120 |
+
|
| 121 |
+
op_checker = OpChecker(fn)
|
| 122 |
+
for block in fn.blocks:
|
| 123 |
+
for op in block.ops:
|
| 124 |
+
op.accept(op_checker)
|
| 125 |
+
|
| 126 |
+
return op_checker.errors
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class IrCheckException(Exception):
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def assert_func_ir_valid(fn: FuncIR) -> None:
|
| 134 |
+
errors = check_func_ir(fn)
|
| 135 |
+
if errors:
|
| 136 |
+
raise IrCheckException(
|
| 137 |
+
"Internal error: Generated invalid IR: \n"
|
| 138 |
+
+ "\n".join(format_func(fn, [(e.source, e.desc) for e in errors]))
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def check_op_sources_valid(fn: FuncIR) -> list[FnError]:
|
| 143 |
+
errors = []
|
| 144 |
+
valid_ops: set[Op] = set()
|
| 145 |
+
valid_registers: set[Register] = set()
|
| 146 |
+
|
| 147 |
+
for block in fn.blocks:
|
| 148 |
+
valid_ops.update(block.ops)
|
| 149 |
+
|
| 150 |
+
for op in block.ops:
|
| 151 |
+
if isinstance(op, BaseAssign):
|
| 152 |
+
valid_registers.add(op.dest)
|
| 153 |
+
elif isinstance(op, LoadAddress) and isinstance(op.src, Register):
|
| 154 |
+
valid_registers.add(op.src)
|
| 155 |
+
|
| 156 |
+
valid_registers.update(fn.arg_regs)
|
| 157 |
+
|
| 158 |
+
for block in fn.blocks:
|
| 159 |
+
for op in block.ops:
|
| 160 |
+
for source in op.sources():
|
| 161 |
+
if isinstance(source, (Integer, Float, Undef)):
|
| 162 |
+
pass
|
| 163 |
+
elif isinstance(source, Op):
|
| 164 |
+
if source not in valid_ops:
|
| 165 |
+
errors.append(
|
| 166 |
+
FnError(
|
| 167 |
+
source=op,
|
| 168 |
+
desc=f"Invalid op reference to op of type {type(source).__name__}",
|
| 169 |
+
)
|
| 170 |
+
)
|
| 171 |
+
elif isinstance(source, Register):
|
| 172 |
+
if source not in valid_registers:
|
| 173 |
+
errors.append(
|
| 174 |
+
FnError(
|
| 175 |
+
source=op, desc=f"Invalid op reference to register {source.name!r}"
|
| 176 |
+
)
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
return errors
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
disjoint_types = {
|
| 183 |
+
int_rprimitive.name,
|
| 184 |
+
bytes_rprimitive.name,
|
| 185 |
+
str_rprimitive.name,
|
| 186 |
+
dict_rprimitive.name,
|
| 187 |
+
list_rprimitive.name,
|
| 188 |
+
set_rprimitive.name,
|
| 189 |
+
tuple_rprimitive.name,
|
| 190 |
+
range_rprimitive.name,
|
| 191 |
+
} | set(KNOWN_NATIVE_TYPES)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def can_coerce_to(src: RType, dest: RType) -> bool:
|
| 195 |
+
"""Check if src can be assigned to dest_rtype.
|
| 196 |
+
|
| 197 |
+
Currently okay to have false positives.
|
| 198 |
+
"""
|
| 199 |
+
if isinstance(dest, RUnion):
|
| 200 |
+
return any(can_coerce_to(src, d) for d in dest.items)
|
| 201 |
+
|
| 202 |
+
if isinstance(dest, RPrimitive):
|
| 203 |
+
if isinstance(src, RPrimitive):
|
| 204 |
+
# If either src or dest is a disjoint type, then they must both be.
|
| 205 |
+
if src.name in disjoint_types and dest.name in disjoint_types:
|
| 206 |
+
return src.name == dest.name
|
| 207 |
+
return src.size == dest.size
|
| 208 |
+
if isinstance(src, (RInstance, RVec)):
|
| 209 |
+
return is_object_rprimitive(dest)
|
| 210 |
+
if isinstance(src, RUnion):
|
| 211 |
+
# IR doesn't have the ability to narrow unions based on
|
| 212 |
+
# control flow, so cannot be a strict all() here.
|
| 213 |
+
return any(can_coerce_to(s, dest) for s in src.items)
|
| 214 |
+
return False
|
| 215 |
+
|
| 216 |
+
return True
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def is_valid_ptr_displacement_type(rtype: RType) -> bool:
|
| 220 |
+
"""Check if rtype is a valid displacement type for pointer arithmetic."""
|
| 221 |
+
if not (is_fixed_width_rtype(rtype) or is_c_py_ssize_t_rprimitive(rtype)):
|
| 222 |
+
return False
|
| 223 |
+
assert isinstance(rtype, RPrimitive)
|
| 224 |
+
return rtype.size == pointer_rprimitive.size
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def is_pointer_arithmetic(op: IntOp) -> bool:
|
| 228 |
+
"""Check if op is add/subtract targeting pointer_rprimitive and integer of the same size."""
|
| 229 |
+
if op.op not in (IntOp.ADD, IntOp.SUB):
|
| 230 |
+
return False
|
| 231 |
+
if not is_pointer_rprimitive(op.type):
|
| 232 |
+
return False
|
| 233 |
+
left = op.lhs.type
|
| 234 |
+
right = op.rhs.type
|
| 235 |
+
if is_pointer_rprimitive(left):
|
| 236 |
+
return is_valid_ptr_displacement_type(right)
|
| 237 |
+
if is_pointer_rprimitive(right):
|
| 238 |
+
return is_valid_ptr_displacement_type(left)
|
| 239 |
+
return False
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class OpChecker(OpVisitor[None]):
|
| 243 |
+
def __init__(self, parent_fn: FuncIR) -> None:
|
| 244 |
+
self.parent_fn = parent_fn
|
| 245 |
+
self.errors: list[FnError] = []
|
| 246 |
+
|
| 247 |
+
def fail(self, source: Op, desc: str) -> None:
|
| 248 |
+
self.errors.append(FnError(source=source, desc=desc))
|
| 249 |
+
|
| 250 |
+
def check_control_op_targets(self, op: ControlOp) -> None:
|
| 251 |
+
for target in op.targets():
|
| 252 |
+
if target not in self.parent_fn.blocks:
|
| 253 |
+
self.fail(source=op, desc=f"Invalid control operation target: {target.label}")
|
| 254 |
+
|
| 255 |
+
def check_type_coercion(self, op: Op, src: RType, dest: RType) -> None:
|
| 256 |
+
if not can_coerce_to(src, dest):
|
| 257 |
+
self.fail(
|
| 258 |
+
source=op, desc=f"Cannot coerce source type {src.name} to dest type {dest.name}"
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
def check_compatibility(self, op: Op, t: RType, s: RType) -> None:
|
| 262 |
+
if not can_coerce_to(t, s) or not can_coerce_to(s, t):
|
| 263 |
+
self.fail(source=op, desc=f"{t.name} and {s.name} are not compatible")
|
| 264 |
+
|
| 265 |
+
def expect_float(self, op: Op, v: Value) -> None:
|
| 266 |
+
if not is_float_rprimitive(v.type):
|
| 267 |
+
self.fail(op, f"Float expected (actual type is {v.type})")
|
| 268 |
+
|
| 269 |
+
def expect_non_float(self, op: Op, v: Value) -> None:
|
| 270 |
+
if is_float_rprimitive(v.type):
|
| 271 |
+
self.fail(op, "Float not expected")
|
| 272 |
+
|
| 273 |
+
def expect_primitive_type(self, op: Op, v: Value) -> None:
|
| 274 |
+
if not isinstance(v.type, RPrimitive):
|
| 275 |
+
self.fail(op, f"RPrimitive expected, got {type(v.type).__name__}")
|
| 276 |
+
|
| 277 |
+
def visit_goto(self, op: Goto) -> None:
|
| 278 |
+
self.check_control_op_targets(op)
|
| 279 |
+
|
| 280 |
+
def visit_branch(self, op: Branch) -> None:
|
| 281 |
+
self.check_control_op_targets(op)
|
| 282 |
+
|
| 283 |
+
def visit_return(self, op: Return) -> None:
|
| 284 |
+
self.check_type_coercion(op, op.value.type, self.parent_fn.decl.sig.ret_type)
|
| 285 |
+
|
| 286 |
+
def visit_unreachable(self, op: Unreachable) -> None:
|
| 287 |
+
# Unreachables are checked at a higher level since validation
|
| 288 |
+
# requires access to the entire basic block.
|
| 289 |
+
pass
|
| 290 |
+
|
| 291 |
+
def visit_assign(self, op: Assign) -> None:
|
| 292 |
+
self.check_type_coercion(op, op.src.type, op.dest.type)
|
| 293 |
+
|
| 294 |
+
def visit_assign_multi(self, op: AssignMulti) -> None:
|
| 295 |
+
for src in op.src:
|
| 296 |
+
assert isinstance(op.dest.type, RArray)
|
| 297 |
+
self.check_type_coercion(op, src.type, op.dest.type.item_type)
|
| 298 |
+
|
| 299 |
+
def visit_load_error_value(self, op: LoadErrorValue) -> None:
|
| 300 |
+
# Currently it is assumed that all types have an error value.
|
| 301 |
+
# Once this is fixed we can validate that the rtype here actually
|
| 302 |
+
# has an error value.
|
| 303 |
+
pass
|
| 304 |
+
|
| 305 |
+
def check_tuple_items_valid_literals(self, op: LoadLiteral, t: tuple[object, ...]) -> None:
|
| 306 |
+
for x in t:
|
| 307 |
+
if x is not None and not isinstance(x, (str, bytes, bool, int, float, complex, tuple)):
|
| 308 |
+
self.fail(op, f"Invalid type for item of tuple literal: {type(x)})")
|
| 309 |
+
if isinstance(x, tuple):
|
| 310 |
+
self.check_tuple_items_valid_literals(op, x)
|
| 311 |
+
|
| 312 |
+
def check_frozenset_items_valid_literals(self, op: LoadLiteral, s: frozenset[object]) -> None:
|
| 313 |
+
for x in s:
|
| 314 |
+
if x is None or isinstance(x, (str, bytes, bool, int, float, complex)):
|
| 315 |
+
pass
|
| 316 |
+
elif isinstance(x, tuple):
|
| 317 |
+
self.check_tuple_items_valid_literals(op, x)
|
| 318 |
+
else:
|
| 319 |
+
self.fail(op, f"Invalid type for item of frozenset literal: {type(x)})")
|
| 320 |
+
|
| 321 |
+
def visit_load_literal(self, op: LoadLiteral) -> None:
|
| 322 |
+
expected_type = None
|
| 323 |
+
if op.value is None:
|
| 324 |
+
expected_type = "builtins.object"
|
| 325 |
+
elif isinstance(op.value, int):
|
| 326 |
+
expected_type = "builtins.int"
|
| 327 |
+
elif isinstance(op.value, str):
|
| 328 |
+
expected_type = "builtins.str"
|
| 329 |
+
elif isinstance(op.value, bytes):
|
| 330 |
+
expected_type = "builtins.bytes"
|
| 331 |
+
elif isinstance(op.value, float):
|
| 332 |
+
expected_type = "builtins.float"
|
| 333 |
+
elif isinstance(op.value, complex):
|
| 334 |
+
expected_type = "builtins.object"
|
| 335 |
+
elif isinstance(op.value, tuple):
|
| 336 |
+
expected_type = "builtins.tuple"
|
| 337 |
+
self.check_tuple_items_valid_literals(op, op.value)
|
| 338 |
+
elif isinstance(op.value, frozenset):
|
| 339 |
+
# There's no frozenset_rprimitive type since it'd be pretty useless so we just pretend
|
| 340 |
+
# it's a set (when it's really a frozenset).
|
| 341 |
+
expected_type = "builtins.set"
|
| 342 |
+
self.check_frozenset_items_valid_literals(op, op.value)
|
| 343 |
+
|
| 344 |
+
assert expected_type is not None, "Missed a case for LoadLiteral check"
|
| 345 |
+
|
| 346 |
+
if op.type.name not in [expected_type, "builtins.object"]:
|
| 347 |
+
self.fail(
|
| 348 |
+
op,
|
| 349 |
+
f"Invalid literal value for type: value has "
|
| 350 |
+
f"type {expected_type}, but op has type {op.type.name}",
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
def visit_get_attr(self, op: GetAttr) -> None:
|
| 354 |
+
# Nothing to do.
|
| 355 |
+
pass
|
| 356 |
+
|
| 357 |
+
def visit_set_attr(self, op: SetAttr) -> None:
|
| 358 |
+
# Nothing to do.
|
| 359 |
+
pass
|
| 360 |
+
|
| 361 |
+
# Static operations cannot be checked at the function level.
|
| 362 |
+
def visit_load_static(self, op: LoadStatic) -> None:
|
| 363 |
+
pass
|
| 364 |
+
|
| 365 |
+
def visit_init_static(self, op: InitStatic) -> None:
|
| 366 |
+
pass
|
| 367 |
+
|
| 368 |
+
def visit_tuple_get(self, op: TupleGet) -> None:
|
| 369 |
+
# Nothing to do.
|
| 370 |
+
pass
|
| 371 |
+
|
| 372 |
+
def visit_tuple_set(self, op: TupleSet) -> None:
|
| 373 |
+
# Nothing to do.
|
| 374 |
+
pass
|
| 375 |
+
|
| 376 |
+
def visit_inc_ref(self, op: IncRef) -> None:
|
| 377 |
+
# Nothing to do.
|
| 378 |
+
pass
|
| 379 |
+
|
| 380 |
+
def visit_dec_ref(self, op: DecRef) -> None:
|
| 381 |
+
# Nothing to do.
|
| 382 |
+
pass
|
| 383 |
+
|
| 384 |
+
def visit_call(self, op: Call) -> None:
|
| 385 |
+
# Length is checked in constructor, and return type is set
|
| 386 |
+
# in a way that can't be incorrect
|
| 387 |
+
for arg_value, arg_runtime in zip(op.args, op.fn.sig.args):
|
| 388 |
+
self.check_type_coercion(op, arg_value.type, arg_runtime.type)
|
| 389 |
+
|
| 390 |
+
def visit_method_call(self, op: MethodCall) -> None:
|
| 391 |
+
# Similar to above, but we must look up method first.
|
| 392 |
+
method_decl = op.receiver_type.class_ir.method_decl(op.method)
|
| 393 |
+
if method_decl.kind == FUNC_STATICMETHOD:
|
| 394 |
+
decl_index = 0
|
| 395 |
+
else:
|
| 396 |
+
decl_index = 1
|
| 397 |
+
|
| 398 |
+
if len(op.args) + decl_index != len(method_decl.sig.args):
|
| 399 |
+
self.fail(op, "Incorrect number of args for method call.")
|
| 400 |
+
|
| 401 |
+
# Skip the receiver argument (self)
|
| 402 |
+
for arg_value, arg_runtime in zip(op.args, method_decl.sig.args[decl_index:]):
|
| 403 |
+
self.check_type_coercion(op, arg_value.type, arg_runtime.type)
|
| 404 |
+
|
| 405 |
+
def visit_cast(self, op: Cast) -> None:
|
| 406 |
+
pass
|
| 407 |
+
|
| 408 |
+
def visit_box(self, op: Box) -> None:
|
| 409 |
+
pass
|
| 410 |
+
|
| 411 |
+
def visit_unbox(self, op: Unbox) -> None:
|
| 412 |
+
pass
|
| 413 |
+
|
| 414 |
+
def visit_raise_standard_error(self, op: RaiseStandardError) -> None:
|
| 415 |
+
pass
|
| 416 |
+
|
| 417 |
+
def visit_call_c(self, op: CallC) -> None:
|
| 418 |
+
pass
|
| 419 |
+
|
| 420 |
+
def visit_primitive_op(self, op: PrimitiveOp) -> None:
|
| 421 |
+
pass
|
| 422 |
+
|
| 423 |
+
def visit_truncate(self, op: Truncate) -> None:
|
| 424 |
+
pass
|
| 425 |
+
|
| 426 |
+
def visit_extend(self, op: Extend) -> None:
|
| 427 |
+
pass
|
| 428 |
+
|
| 429 |
+
def visit_load_global(self, op: LoadGlobal) -> None:
|
| 430 |
+
pass
|
| 431 |
+
|
| 432 |
+
def visit_int_op(self, op: IntOp) -> None:
|
| 433 |
+
self.expect_primitive_type(op, op.lhs)
|
| 434 |
+
self.expect_primitive_type(op, op.rhs)
|
| 435 |
+
self.expect_non_float(op, op.lhs)
|
| 436 |
+
self.expect_non_float(op, op.rhs)
|
| 437 |
+
left = op.lhs.type
|
| 438 |
+
right = op.rhs.type
|
| 439 |
+
op_str = op.op_str[op.op]
|
| 440 |
+
if (
|
| 441 |
+
isinstance(left, RPrimitive)
|
| 442 |
+
and isinstance(right, RPrimitive)
|
| 443 |
+
and left.is_signed != right.is_signed
|
| 444 |
+
and (
|
| 445 |
+
op_str in ("+", "-", "*", "/", "%")
|
| 446 |
+
or (op_str not in ("<<", ">>") and left.size != right.size)
|
| 447 |
+
)
|
| 448 |
+
and not is_pointer_arithmetic(op)
|
| 449 |
+
):
|
| 450 |
+
self.fail(op, f"Operand types have incompatible signs: {left}, {right}")
|
| 451 |
+
|
| 452 |
+
def visit_comparison_op(self, op: ComparisonOp) -> None:
|
| 453 |
+
self.check_compatibility(op, op.lhs.type, op.rhs.type)
|
| 454 |
+
self.expect_non_float(op, op.lhs)
|
| 455 |
+
self.expect_non_float(op, op.rhs)
|
| 456 |
+
left = op.lhs.type
|
| 457 |
+
right = op.rhs.type
|
| 458 |
+
if (
|
| 459 |
+
isinstance(left, RPrimitive)
|
| 460 |
+
and isinstance(right, RPrimitive)
|
| 461 |
+
and left.is_signed != right.is_signed
|
| 462 |
+
):
|
| 463 |
+
self.fail(op, f"Operand types have incompatible signs: {left}, {right}")
|
| 464 |
+
|
| 465 |
+
def visit_float_op(self, op: FloatOp) -> None:
|
| 466 |
+
self.expect_float(op, op.lhs)
|
| 467 |
+
self.expect_float(op, op.rhs)
|
| 468 |
+
|
| 469 |
+
def visit_float_neg(self, op: FloatNeg) -> None:
|
| 470 |
+
self.expect_float(op, op.src)
|
| 471 |
+
|
| 472 |
+
def visit_float_comparison_op(self, op: FloatComparisonOp) -> None:
|
| 473 |
+
self.expect_float(op, op.lhs)
|
| 474 |
+
self.expect_float(op, op.rhs)
|
| 475 |
+
|
| 476 |
+
def visit_load_mem(self, op: LoadMem) -> None:
|
| 477 |
+
pass
|
| 478 |
+
|
| 479 |
+
def visit_set_mem(self, op: SetMem) -> None:
|
| 480 |
+
pass
|
| 481 |
+
|
| 482 |
+
def visit_get_element(self, op: GetElement) -> None:
|
| 483 |
+
pass
|
| 484 |
+
|
| 485 |
+
def visit_get_element_ptr(self, op: GetElementPtr) -> None:
|
| 486 |
+
pass
|
| 487 |
+
|
| 488 |
+
def visit_set_element(self, op: SetElement) -> None:
|
| 489 |
+
pass
|
| 490 |
+
|
| 491 |
+
def visit_load_address(self, op: LoadAddress) -> None:
|
| 492 |
+
pass
|
| 493 |
+
|
| 494 |
+
def visit_keep_alive(self, op: KeepAlive) -> None:
|
| 495 |
+
pass
|
| 496 |
+
|
| 497 |
+
def visit_unborrow(self, op: Unborrow) -> None:
|
| 498 |
+
pass
|
micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from mypyc.analysis.dataflow import (
|
| 4 |
+
CFG,
|
| 5 |
+
MAYBE_ANALYSIS,
|
| 6 |
+
AnalysisResult,
|
| 7 |
+
GenAndKill as _DataflowGenAndKill,
|
| 8 |
+
run_analysis,
|
| 9 |
+
)
|
| 10 |
+
from mypyc.ir.ops import (
|
| 11 |
+
Assign,
|
| 12 |
+
AssignMulti,
|
| 13 |
+
BasicBlock,
|
| 14 |
+
Box,
|
| 15 |
+
Branch,
|
| 16 |
+
Call,
|
| 17 |
+
CallC,
|
| 18 |
+
Cast,
|
| 19 |
+
ComparisonOp,
|
| 20 |
+
DecRef,
|
| 21 |
+
Extend,
|
| 22 |
+
FloatComparisonOp,
|
| 23 |
+
FloatNeg,
|
| 24 |
+
FloatOp,
|
| 25 |
+
GetAttr,
|
| 26 |
+
GetElement,
|
| 27 |
+
GetElementPtr,
|
| 28 |
+
Goto,
|
| 29 |
+
IncRef,
|
| 30 |
+
InitStatic,
|
| 31 |
+
IntOp,
|
| 32 |
+
KeepAlive,
|
| 33 |
+
LoadAddress,
|
| 34 |
+
LoadErrorValue,
|
| 35 |
+
LoadGlobal,
|
| 36 |
+
LoadLiteral,
|
| 37 |
+
LoadMem,
|
| 38 |
+
LoadStatic,
|
| 39 |
+
MethodCall,
|
| 40 |
+
OpVisitor,
|
| 41 |
+
PrimitiveOp,
|
| 42 |
+
RaiseStandardError,
|
| 43 |
+
Register,
|
| 44 |
+
RegisterOp,
|
| 45 |
+
Return,
|
| 46 |
+
SetAttr,
|
| 47 |
+
SetElement,
|
| 48 |
+
SetMem,
|
| 49 |
+
Truncate,
|
| 50 |
+
TupleGet,
|
| 51 |
+
TupleSet,
|
| 52 |
+
Unborrow,
|
| 53 |
+
Unbox,
|
| 54 |
+
Unreachable,
|
| 55 |
+
)
|
| 56 |
+
from mypyc.ir.rtypes import RInstance
|
| 57 |
+
|
| 58 |
+
GenAndKill = _DataflowGenAndKill[None]
|
| 59 |
+
|
| 60 |
+
CLEAN: GenAndKill = (set(), set())
|
| 61 |
+
DIRTY: GenAndKill = ({None}, {None})
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class SelfLeakedVisitor(OpVisitor[GenAndKill]):
|
| 65 |
+
"""Analyze whether 'self' may be seen by arbitrary code in '__init__'.
|
| 66 |
+
|
| 67 |
+
More formally, the set is not empty if along some path from IR entry point
|
| 68 |
+
arbitrary code could have been executed that has access to 'self'.
|
| 69 |
+
|
| 70 |
+
(We don't consider access via 'gc.get_objects()'.)
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(self, self_reg: Register) -> None:
|
| 74 |
+
self.self_reg = self_reg
|
| 75 |
+
|
| 76 |
+
def visit_goto(self, op: Goto) -> GenAndKill:
|
| 77 |
+
return CLEAN
|
| 78 |
+
|
| 79 |
+
def visit_branch(self, op: Branch) -> GenAndKill:
|
| 80 |
+
return CLEAN
|
| 81 |
+
|
| 82 |
+
def visit_return(self, op: Return) -> GenAndKill:
|
| 83 |
+
# Consider all exits from the function 'dirty' since they implicitly
|
| 84 |
+
# cause 'self' to be returned.
|
| 85 |
+
return DIRTY
|
| 86 |
+
|
| 87 |
+
def visit_unreachable(self, op: Unreachable) -> GenAndKill:
|
| 88 |
+
return CLEAN
|
| 89 |
+
|
| 90 |
+
def visit_assign(self, op: Assign) -> GenAndKill:
|
| 91 |
+
if op.src is self.self_reg or op.dest is self.self_reg:
|
| 92 |
+
return DIRTY
|
| 93 |
+
return CLEAN
|
| 94 |
+
|
| 95 |
+
def visit_assign_multi(self, op: AssignMulti) -> GenAndKill:
|
| 96 |
+
return CLEAN
|
| 97 |
+
|
| 98 |
+
def visit_set_mem(self, op: SetMem) -> GenAndKill:
|
| 99 |
+
return CLEAN
|
| 100 |
+
|
| 101 |
+
def visit_inc_ref(self, op: IncRef) -> GenAndKill:
|
| 102 |
+
return CLEAN
|
| 103 |
+
|
| 104 |
+
def visit_dec_ref(self, op: DecRef) -> GenAndKill:
|
| 105 |
+
return CLEAN
|
| 106 |
+
|
| 107 |
+
def visit_call(self, op: Call) -> GenAndKill:
|
| 108 |
+
fn = op.fn
|
| 109 |
+
if fn.class_name and fn.name == "__init__":
|
| 110 |
+
self_type = op.fn.sig.args[0].type
|
| 111 |
+
assert isinstance(self_type, RInstance), self_type
|
| 112 |
+
cl = self_type.class_ir
|
| 113 |
+
if not cl.init_self_leak:
|
| 114 |
+
return CLEAN
|
| 115 |
+
return self.check_register_op(op)
|
| 116 |
+
|
| 117 |
+
def visit_method_call(self, op: MethodCall) -> GenAndKill:
|
| 118 |
+
return self.check_register_op(op)
|
| 119 |
+
|
| 120 |
+
def visit_load_error_value(self, op: LoadErrorValue) -> GenAndKill:
|
| 121 |
+
return CLEAN
|
| 122 |
+
|
| 123 |
+
def visit_load_literal(self, op: LoadLiteral) -> GenAndKill:
|
| 124 |
+
return CLEAN
|
| 125 |
+
|
| 126 |
+
def visit_get_attr(self, op: GetAttr) -> GenAndKill:
|
| 127 |
+
cl = op.class_type.class_ir
|
| 128 |
+
if cl.get_method(op.attr):
|
| 129 |
+
# Property -- calls a function
|
| 130 |
+
return self.check_register_op(op)
|
| 131 |
+
return CLEAN
|
| 132 |
+
|
| 133 |
+
def visit_set_attr(self, op: SetAttr) -> GenAndKill:
|
| 134 |
+
cl = op.class_type.class_ir
|
| 135 |
+
if cl.get_method(op.attr):
|
| 136 |
+
# Property - calls a function
|
| 137 |
+
return self.check_register_op(op)
|
| 138 |
+
return CLEAN
|
| 139 |
+
|
| 140 |
+
def visit_load_static(self, op: LoadStatic) -> GenAndKill:
|
| 141 |
+
return CLEAN
|
| 142 |
+
|
| 143 |
+
def visit_init_static(self, op: InitStatic) -> GenAndKill:
|
| 144 |
+
return self.check_register_op(op)
|
| 145 |
+
|
| 146 |
+
def visit_tuple_get(self, op: TupleGet) -> GenAndKill:
|
| 147 |
+
return CLEAN
|
| 148 |
+
|
| 149 |
+
def visit_tuple_set(self, op: TupleSet) -> GenAndKill:
|
| 150 |
+
return self.check_register_op(op)
|
| 151 |
+
|
| 152 |
+
def visit_box(self, op: Box) -> GenAndKill:
|
| 153 |
+
return self.check_register_op(op)
|
| 154 |
+
|
| 155 |
+
def visit_unbox(self, op: Unbox) -> GenAndKill:
|
| 156 |
+
return self.check_register_op(op)
|
| 157 |
+
|
| 158 |
+
def visit_cast(self, op: Cast) -> GenAndKill:
|
| 159 |
+
return self.check_register_op(op)
|
| 160 |
+
|
| 161 |
+
def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill:
|
| 162 |
+
return CLEAN
|
| 163 |
+
|
| 164 |
+
def visit_call_c(self, op: CallC) -> GenAndKill:
|
| 165 |
+
return self.check_register_op(op)
|
| 166 |
+
|
| 167 |
+
def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill:
|
| 168 |
+
return self.check_register_op(op)
|
| 169 |
+
|
| 170 |
+
def visit_truncate(self, op: Truncate) -> GenAndKill:
|
| 171 |
+
return CLEAN
|
| 172 |
+
|
| 173 |
+
def visit_extend(self, op: Extend) -> GenAndKill:
|
| 174 |
+
return CLEAN
|
| 175 |
+
|
| 176 |
+
def visit_load_global(self, op: LoadGlobal) -> GenAndKill:
|
| 177 |
+
return CLEAN
|
| 178 |
+
|
| 179 |
+
def visit_int_op(self, op: IntOp) -> GenAndKill:
|
| 180 |
+
return CLEAN
|
| 181 |
+
|
| 182 |
+
def visit_comparison_op(self, op: ComparisonOp) -> GenAndKill:
|
| 183 |
+
return CLEAN
|
| 184 |
+
|
| 185 |
+
def visit_float_op(self, op: FloatOp) -> GenAndKill:
|
| 186 |
+
return CLEAN
|
| 187 |
+
|
| 188 |
+
def visit_float_neg(self, op: FloatNeg) -> GenAndKill:
|
| 189 |
+
return CLEAN
|
| 190 |
+
|
| 191 |
+
def visit_float_comparison_op(self, op: FloatComparisonOp) -> GenAndKill:
|
| 192 |
+
return CLEAN
|
| 193 |
+
|
| 194 |
+
def visit_load_mem(self, op: LoadMem) -> GenAndKill:
|
| 195 |
+
return CLEAN
|
| 196 |
+
|
| 197 |
+
def visit_get_element(self, op: GetElement) -> GenAndKill:
|
| 198 |
+
return CLEAN
|
| 199 |
+
|
| 200 |
+
def visit_get_element_ptr(self, op: GetElementPtr) -> GenAndKill:
|
| 201 |
+
return CLEAN
|
| 202 |
+
|
| 203 |
+
def visit_set_element(self, op: SetElement) -> GenAndKill:
|
| 204 |
+
return CLEAN
|
| 205 |
+
|
| 206 |
+
def visit_load_address(self, op: LoadAddress) -> GenAndKill:
|
| 207 |
+
return CLEAN
|
| 208 |
+
|
| 209 |
+
def visit_keep_alive(self, op: KeepAlive) -> GenAndKill:
|
| 210 |
+
return CLEAN
|
| 211 |
+
|
| 212 |
+
def visit_unborrow(self, op: Unborrow) -> GenAndKill:
|
| 213 |
+
return CLEAN
|
| 214 |
+
|
| 215 |
+
def check_register_op(self, op: RegisterOp) -> GenAndKill:
|
| 216 |
+
if any(src is self.self_reg for src in op.sources()):
|
| 217 |
+
return DIRTY
|
| 218 |
+
return CLEAN
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def analyze_self_leaks(
|
| 222 |
+
blocks: list[BasicBlock], self_reg: Register, cfg: CFG
|
| 223 |
+
) -> AnalysisResult[None]:
|
| 224 |
+
return run_analysis(
|
| 225 |
+
blocks=blocks,
|
| 226 |
+
cfg=cfg,
|
| 227 |
+
gen_and_kill=SelfLeakedVisitor(self_reg),
|
| 228 |
+
initial=set(),
|
| 229 |
+
backward=False,
|
| 230 |
+
kind=MAYBE_ANALYSIS,
|
| 231 |
+
)
|
micromamba_root/Lib/site-packages/mypyc/codegen/__init__.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/codegen/__init__.py
ADDED
|
File without changes
|
micromamba_root/Lib/site-packages/mypyc/codegen/cstring.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/codegen/cstring.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Encode valid C string literals from Python strings.
|
| 2 |
+
|
| 3 |
+
If a character is not allowed in C string literals, it is either emitted
|
| 4 |
+
as a simple escape sequence (e.g. '\\n'), or an octal escape sequence
|
| 5 |
+
with exactly three digits ('\\oXXX'). Question marks are escaped to
|
| 6 |
+
prevent trigraphs in the string literal from being interpreted. Note
|
| 7 |
+
that '\\?' is an invalid escape sequence in Python.
|
| 8 |
+
|
| 9 |
+
Consider the string literal "AB\\xCDEF". As one would expect, Python
|
| 10 |
+
parses it as ['A', 'B', 0xCD, 'E', 'F']. However, the C standard
|
| 11 |
+
specifies that all hexadecimal digits immediately following '\\x' will
|
| 12 |
+
be interpreted as part of the escape sequence. Therefore, it is
|
| 13 |
+
unexpectedly parsed as ['A', 'B', 0xCDEF].
|
| 14 |
+
|
| 15 |
+
Emitting ("AB\\xCD" "EF") would avoid this behaviour. However, we opt
|
| 16 |
+
for simplicity and use octal escape sequences instead. They do not
|
| 17 |
+
suffer from the same issue as they are defined to parse at most three
|
| 18 |
+
octal digits.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import string
|
| 24 |
+
from typing import Final
|
| 25 |
+
|
| 26 |
+
CHAR_MAP: Final = [f"\\{i:03o}" for i in range(256)]
|
| 27 |
+
|
| 28 |
+
# It is safe to use string.printable as it always uses the C locale.
|
| 29 |
+
for c in string.printable:
|
| 30 |
+
CHAR_MAP[ord(c)] = c
|
| 31 |
+
|
| 32 |
+
# These assignments must come last because we prioritize simple escape
|
| 33 |
+
# sequences over any other representation.
|
| 34 |
+
for c in ("'", '"', "\\", "a", "b", "f", "n", "r", "t", "v"):
|
| 35 |
+
escaped = f"\\{c}"
|
| 36 |
+
decoded = escaped.encode("ascii").decode("unicode_escape")
|
| 37 |
+
CHAR_MAP[ord(decoded)] = escaped
|
| 38 |
+
|
| 39 |
+
# This escape sequence is invalid in Python.
|
| 40 |
+
CHAR_MAP[ord("?")] = r"\?"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def encode_bytes_as_c_string(b: bytes) -> str:
|
| 44 |
+
"""Produce contents of a C string literal for a byte string, without quotes."""
|
| 45 |
+
escaped = "".join([CHAR_MAP[i] for i in b])
|
| 46 |
+
return escaped
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def c_string_initializer(value: bytes) -> str:
|
| 50 |
+
"""Create initializer for a C char[]/ char * variable from a string.
|
| 51 |
+
|
| 52 |
+
For example, if value if b'foo', the result would be '"foo"'.
|
| 53 |
+
"""
|
| 54 |
+
return '"' + encode_bytes_as_c_string(value) + '"'
|
micromamba_root/Lib/site-packages/mypyc/codegen/emit.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/codegen/emit.py
ADDED
|
@@ -0,0 +1,1439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities for emitting C code."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import pprint
|
| 6 |
+
import sys
|
| 7 |
+
import textwrap
|
| 8 |
+
from collections.abc import Callable
|
| 9 |
+
from typing import Final
|
| 10 |
+
|
| 11 |
+
from mypyc.codegen.cstring import c_string_initializer
|
| 12 |
+
from mypyc.codegen.literals import Literals
|
| 13 |
+
from mypyc.common import (
|
| 14 |
+
ATTR_PREFIX,
|
| 15 |
+
BITMAP_BITS,
|
| 16 |
+
FAST_ISINSTANCE_MAX_SUBCLASSES,
|
| 17 |
+
HAVE_IMMORTAL,
|
| 18 |
+
MODULE_PREFIX,
|
| 19 |
+
NATIVE_PREFIX,
|
| 20 |
+
PREFIX,
|
| 21 |
+
REG_PREFIX,
|
| 22 |
+
STATIC_PREFIX,
|
| 23 |
+
TYPE_PREFIX,
|
| 24 |
+
TYPE_VAR_PREFIX,
|
| 25 |
+
)
|
| 26 |
+
from mypyc.ir.class_ir import ClassIR, all_concrete_classes
|
| 27 |
+
from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncDecl, FuncIR, get_text_signature
|
| 28 |
+
from mypyc.ir.ops import (
|
| 29 |
+
NAMESPACE_MODULE,
|
| 30 |
+
NAMESPACE_STATIC,
|
| 31 |
+
NAMESPACE_TYPE,
|
| 32 |
+
NAMESPACE_TYPE_VAR,
|
| 33 |
+
BasicBlock,
|
| 34 |
+
Value,
|
| 35 |
+
)
|
| 36 |
+
from mypyc.ir.rtypes import (
|
| 37 |
+
RInstance,
|
| 38 |
+
RPrimitive,
|
| 39 |
+
RTuple,
|
| 40 |
+
RType,
|
| 41 |
+
RUnion,
|
| 42 |
+
RVec,
|
| 43 |
+
int_rprimitive,
|
| 44 |
+
is_bool_or_bit_rprimitive,
|
| 45 |
+
is_bytearray_rprimitive,
|
| 46 |
+
is_bytes_rprimitive,
|
| 47 |
+
is_dict_rprimitive,
|
| 48 |
+
is_fixed_width_rtype,
|
| 49 |
+
is_float_rprimitive,
|
| 50 |
+
is_frozenset_rprimitive,
|
| 51 |
+
is_int16_rprimitive,
|
| 52 |
+
is_int32_rprimitive,
|
| 53 |
+
is_int64_rprimitive,
|
| 54 |
+
is_int_rprimitive,
|
| 55 |
+
is_list_rprimitive,
|
| 56 |
+
is_native_rprimitive,
|
| 57 |
+
is_none_rprimitive,
|
| 58 |
+
is_object_rprimitive,
|
| 59 |
+
is_optional_type,
|
| 60 |
+
is_range_rprimitive,
|
| 61 |
+
is_set_rprimitive,
|
| 62 |
+
is_short_int_rprimitive,
|
| 63 |
+
is_str_rprimitive,
|
| 64 |
+
is_tuple_rprimitive,
|
| 65 |
+
is_uint8_rprimitive,
|
| 66 |
+
object_rprimitive,
|
| 67 |
+
optional_value_type,
|
| 68 |
+
vec_api_by_item_type,
|
| 69 |
+
vec_item_type_tags,
|
| 70 |
+
)
|
| 71 |
+
from mypyc.namegen import NameGenerator, exported_name
|
| 72 |
+
from mypyc.primitives.registry import builtin_names
|
| 73 |
+
from mypyc.sametype import is_same_type
|
| 74 |
+
|
| 75 |
+
# Whether to insert debug asserts for all error handling, to quickly
|
| 76 |
+
# catch errors propagating without exceptions set.
|
| 77 |
+
DEBUG_ERRORS: Final = False
|
| 78 |
+
|
| 79 |
+
PREFIX_MAP: Final = {
|
| 80 |
+
NAMESPACE_STATIC: STATIC_PREFIX,
|
| 81 |
+
NAMESPACE_TYPE: TYPE_PREFIX,
|
| 82 |
+
NAMESPACE_MODULE: MODULE_PREFIX,
|
| 83 |
+
NAMESPACE_TYPE_VAR: TYPE_VAR_PREFIX,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class HeaderDeclaration:
|
| 88 |
+
"""A representation of a declaration in C.
|
| 89 |
+
|
| 90 |
+
This is used to generate declarations in header files and
|
| 91 |
+
(optionally) definitions in source files.
|
| 92 |
+
|
| 93 |
+
Attributes:
|
| 94 |
+
decl: C source code for the declaration.
|
| 95 |
+
defn: Optionally, C source code for a definition.
|
| 96 |
+
dependencies: The names of any objects that must be declared prior.
|
| 97 |
+
is_type: Whether the declaration is of a C type. (C types will be declared in
|
| 98 |
+
external header files and not marked 'extern'.)
|
| 99 |
+
needs_export: Whether the declared object needs to be exported to
|
| 100 |
+
other modules in the linking table.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
decl: str | list[str],
|
| 106 |
+
defn: list[str] | None = None,
|
| 107 |
+
*,
|
| 108 |
+
dependencies: set[str] | None = None,
|
| 109 |
+
is_type: bool = False,
|
| 110 |
+
needs_export: bool = False,
|
| 111 |
+
) -> None:
|
| 112 |
+
self.decl = [decl] if isinstance(decl, str) else decl
|
| 113 |
+
self.defn = defn
|
| 114 |
+
self.dependencies = dependencies or set()
|
| 115 |
+
self.is_type = is_type
|
| 116 |
+
self.needs_export = needs_export
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class EmitterContext:
|
| 120 |
+
"""Shared emitter state for a compilation group."""
|
| 121 |
+
|
| 122 |
+
def __init__(
|
| 123 |
+
self,
|
| 124 |
+
names: NameGenerator,
|
| 125 |
+
strict_traceback_checks: bool,
|
| 126 |
+
group_name: str | None = None,
|
| 127 |
+
group_map: dict[str, str | None] | None = None,
|
| 128 |
+
) -> None:
|
| 129 |
+
"""Setup shared emitter state.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
names: The name generator to use
|
| 133 |
+
group_map: Map from module names to group name
|
| 134 |
+
group_name: Current group name
|
| 135 |
+
"""
|
| 136 |
+
self.temp_counter = 0
|
| 137 |
+
self.names = names
|
| 138 |
+
self.group_name = group_name
|
| 139 |
+
self.group_map = group_map or {}
|
| 140 |
+
# Groups that this group depends on
|
| 141 |
+
self.group_deps: set[str] = set()
|
| 142 |
+
|
| 143 |
+
# The map below is used for generating declarations and
|
| 144 |
+
# definitions at the top of the C file. The main idea is that they can
|
| 145 |
+
# be generated at any time during the emit phase.
|
| 146 |
+
|
| 147 |
+
# A map of a C identifier to whatever the C identifier declares. Currently this is
|
| 148 |
+
# used for declaring structs and the key corresponds to the name of the struct.
|
| 149 |
+
# The declaration contains the body of the struct.
|
| 150 |
+
self.declarations: dict[str, HeaderDeclaration] = {}
|
| 151 |
+
|
| 152 |
+
self.literals = Literals()
|
| 153 |
+
# See mypyc/options.py for context.
|
| 154 |
+
self.strict_traceback_checks = strict_traceback_checks
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class ErrorHandler:
|
| 158 |
+
"""Describes handling errors in unbox/cast operations."""
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class AssignHandler(ErrorHandler):
|
| 162 |
+
"""Assign an error value on error."""
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class GotoHandler(ErrorHandler):
|
| 166 |
+
"""Goto label on error."""
|
| 167 |
+
|
| 168 |
+
def __init__(self, label: str) -> None:
|
| 169 |
+
self.label = label
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class TracebackAndGotoHandler(ErrorHandler):
|
| 173 |
+
"""Add traceback item and goto label on error."""
|
| 174 |
+
|
| 175 |
+
def __init__(
|
| 176 |
+
self, label: str, source_path: str, module_name: str, traceback_entry: tuple[str, int]
|
| 177 |
+
) -> None:
|
| 178 |
+
self.label = label
|
| 179 |
+
self.source_path = source_path
|
| 180 |
+
self.module_name = module_name
|
| 181 |
+
self.traceback_entry = traceback_entry
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class ReturnHandler(ErrorHandler):
|
| 185 |
+
"""Return a constant value on error."""
|
| 186 |
+
|
| 187 |
+
def __init__(self, value: str) -> None:
|
| 188 |
+
self.value = value
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class Emitter:
|
| 192 |
+
"""Helper for C code generation."""
|
| 193 |
+
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
context: EmitterContext,
|
| 197 |
+
value_names: dict[Value, str] | None = None,
|
| 198 |
+
capi_version: tuple[int, int] | None = None,
|
| 199 |
+
filepath: str | None = None,
|
| 200 |
+
) -> None:
|
| 201 |
+
self.context = context
|
| 202 |
+
self.capi_version = capi_version or sys.version_info[:2]
|
| 203 |
+
self.names = context.names
|
| 204 |
+
self.value_names = value_names or {}
|
| 205 |
+
self.fragments: list[str] = []
|
| 206 |
+
self._indent = 0
|
| 207 |
+
self.filepath = filepath
|
| 208 |
+
|
| 209 |
+
# Low-level operations
|
| 210 |
+
|
| 211 |
+
def indent(self) -> None:
|
| 212 |
+
self._indent += 4
|
| 213 |
+
|
| 214 |
+
def dedent(self) -> None:
|
| 215 |
+
self._indent -= 4
|
| 216 |
+
assert self._indent >= 0
|
| 217 |
+
|
| 218 |
+
def label(self, label: BasicBlock) -> str:
|
| 219 |
+
return "CPyL%s" % label.label
|
| 220 |
+
|
| 221 |
+
def reg(self, reg: Value) -> str:
|
| 222 |
+
return REG_PREFIX + self.value_names[reg]
|
| 223 |
+
|
| 224 |
+
def attr(self, name: str) -> str:
|
| 225 |
+
return ATTR_PREFIX + name
|
| 226 |
+
|
| 227 |
+
def object_annotation(self, obj: object, line: str) -> str:
|
| 228 |
+
"""Build a C comment with an object's string representation.
|
| 229 |
+
|
| 230 |
+
If the comment exceeds the line length limit, it's wrapped into a
|
| 231 |
+
multiline string (with the extra lines indented to be aligned with
|
| 232 |
+
the first line's comment).
|
| 233 |
+
|
| 234 |
+
If it contains illegal characters, an empty string is returned."""
|
| 235 |
+
line_width = self._indent + len(line)
|
| 236 |
+
formatted = pprint.pformat(obj, compact=True, width=max(90 - line_width, 20))
|
| 237 |
+
if any(x in formatted for x in ("/*", "*/", "\0")):
|
| 238 |
+
return ""
|
| 239 |
+
|
| 240 |
+
if "\n" in formatted:
|
| 241 |
+
first_line, rest = formatted.split("\n", maxsplit=1)
|
| 242 |
+
comment_continued = textwrap.indent(rest, (line_width + 3) * " ")
|
| 243 |
+
return f" /* {first_line}\n{comment_continued} */"
|
| 244 |
+
else:
|
| 245 |
+
return f" /* {formatted} */"
|
| 246 |
+
|
| 247 |
+
def emit_line(self, line: str = "", *, ann: object = None) -> None:
|
| 248 |
+
if line.startswith("}"):
|
| 249 |
+
self.dedent()
|
| 250 |
+
comment = self.object_annotation(ann, line) if ann is not None else ""
|
| 251 |
+
self.fragments.append(self._indent * " " + line + comment + "\n")
|
| 252 |
+
if line.endswith("{"):
|
| 253 |
+
self.indent()
|
| 254 |
+
|
| 255 |
+
def emit_lines(self, *lines: str) -> None:
|
| 256 |
+
for line in lines:
|
| 257 |
+
self.emit_line(line)
|
| 258 |
+
|
| 259 |
+
def emit_label(self, label: BasicBlock | str) -> None:
|
| 260 |
+
if isinstance(label, str):
|
| 261 |
+
text = label
|
| 262 |
+
else:
|
| 263 |
+
if label.label == 0 or not label.referenced:
|
| 264 |
+
return
|
| 265 |
+
|
| 266 |
+
text = self.label(label)
|
| 267 |
+
# Extra semicolon prevents an error when the next line declares a tempvar
|
| 268 |
+
self.fragments.append(f"{text}: ;\n")
|
| 269 |
+
|
| 270 |
+
def emit_from_emitter(self, emitter: Emitter) -> None:
|
| 271 |
+
self.fragments.extend(emitter.fragments)
|
| 272 |
+
|
| 273 |
+
def emit_printf(self, fmt: str, *args: str) -> None:
|
| 274 |
+
fmt = fmt.replace("\n", "\\n")
|
| 275 |
+
self.emit_line("printf(%s);" % ", ".join(['"%s"' % fmt] + list(args)))
|
| 276 |
+
self.emit_line("fflush(stdout);")
|
| 277 |
+
|
| 278 |
+
def temp_name(self) -> str:
|
| 279 |
+
self.context.temp_counter += 1
|
| 280 |
+
return "__tmp%d" % self.context.temp_counter
|
| 281 |
+
|
| 282 |
+
def new_label(self) -> str:
|
| 283 |
+
self.context.temp_counter += 1
|
| 284 |
+
return "__LL%d" % self.context.temp_counter
|
| 285 |
+
|
| 286 |
+
def get_module_group_prefix(self, module_name: str) -> str:
|
| 287 |
+
"""Get the group prefix for a module (relative to the current group).
|
| 288 |
+
|
| 289 |
+
The prefix should be prepended to the object name whenever
|
| 290 |
+
accessing an object from this module.
|
| 291 |
+
|
| 292 |
+
If the module lives is in the current compilation group, there is
|
| 293 |
+
no prefix. But if it lives in a different group (and hence a separate
|
| 294 |
+
extension module), we need to access objects from it indirectly via an
|
| 295 |
+
export table.
|
| 296 |
+
|
| 297 |
+
For example, for code in group `a` to call a function `bar` in group `b`,
|
| 298 |
+
it would need to do `exports_b.CPyDef_bar(...)`, while code that is
|
| 299 |
+
also in group `b` can simply do `CPyDef_bar(...)`.
|
| 300 |
+
|
| 301 |
+
Thus the prefix for a module in group `b` is 'exports_b.' if the current
|
| 302 |
+
group is *not* b and just '' if it is.
|
| 303 |
+
"""
|
| 304 |
+
groups = self.context.group_map
|
| 305 |
+
target_group_name = groups.get(module_name)
|
| 306 |
+
if target_group_name and target_group_name != self.context.group_name:
|
| 307 |
+
self.context.group_deps.add(target_group_name)
|
| 308 |
+
return f"exports_{exported_name(target_group_name)}."
|
| 309 |
+
else:
|
| 310 |
+
return ""
|
| 311 |
+
|
| 312 |
+
def get_group_prefix(self, obj: ClassIR | FuncDecl) -> str:
|
| 313 |
+
"""Get the group prefix for an object."""
|
| 314 |
+
# See docs above
|
| 315 |
+
return self.get_module_group_prefix(obj.module_name)
|
| 316 |
+
|
| 317 |
+
def static_name(self, id: str, module: str | None, prefix: str = STATIC_PREFIX) -> str:
|
| 318 |
+
"""Create name of a C static variable.
|
| 319 |
+
|
| 320 |
+
These are used for literals and imported modules, among other
|
| 321 |
+
things.
|
| 322 |
+
|
| 323 |
+
The caller should ensure that the (id, module) pair cannot
|
| 324 |
+
overlap with other calls to this method within a compilation
|
| 325 |
+
group.
|
| 326 |
+
"""
|
| 327 |
+
lib_prefix = "" if not module else self.get_module_group_prefix(module)
|
| 328 |
+
# If we are accessing static via the export table, we need to dereference
|
| 329 |
+
# the pointer also.
|
| 330 |
+
star_maybe = "*" if lib_prefix else ""
|
| 331 |
+
suffix = self.names.private_name(module or "", id)
|
| 332 |
+
return f"{star_maybe}{lib_prefix}{prefix}{suffix}"
|
| 333 |
+
|
| 334 |
+
def type_struct_name(self, cl: ClassIR) -> str:
|
| 335 |
+
return self.static_name(cl.name, cl.module_name, prefix=TYPE_PREFIX)
|
| 336 |
+
|
| 337 |
+
def ctype(self, rtype: RType) -> str:
|
| 338 |
+
return rtype._ctype
|
| 339 |
+
|
| 340 |
+
def ctype_spaced(self, rtype: RType) -> str:
|
| 341 |
+
"""Adds a space after ctype for non-pointers."""
|
| 342 |
+
ctype = self.ctype(rtype)
|
| 343 |
+
if ctype[-1] == "*":
|
| 344 |
+
return ctype
|
| 345 |
+
else:
|
| 346 |
+
return ctype + " "
|
| 347 |
+
|
| 348 |
+
def set_undefined_value(self, target: str, rtype: RType) -> None:
|
| 349 |
+
if isinstance(rtype, RVec):
|
| 350 |
+
self.emit_line(f"{target}.len = -1;")
|
| 351 |
+
self.emit_line(f"{target}.buf = NULL;")
|
| 352 |
+
else:
|
| 353 |
+
self.emit_line(f"{target} = {self.c_undefined_value(rtype)};")
|
| 354 |
+
|
| 355 |
+
def c_undefined_value(self, rtype: RType) -> str:
|
| 356 |
+
if not rtype.is_unboxed:
|
| 357 |
+
return "NULL"
|
| 358 |
+
elif isinstance(rtype, RPrimitive):
|
| 359 |
+
return rtype.c_undefined
|
| 360 |
+
elif isinstance(rtype, RTuple):
|
| 361 |
+
return self.tuple_undefined_value(rtype)
|
| 362 |
+
elif isinstance(rtype, RVec):
|
| 363 |
+
return f"({self.ctype(rtype)}) {{ -1, NULL }}"
|
| 364 |
+
assert False, rtype
|
| 365 |
+
|
| 366 |
+
def c_error_value(self, rtype: RType) -> str:
|
| 367 |
+
return self.c_undefined_value(rtype)
|
| 368 |
+
|
| 369 |
+
def native_function_name(self, fn: FuncDecl) -> str:
|
| 370 |
+
return f"{NATIVE_PREFIX}{fn.cname(self.names)}"
|
| 371 |
+
|
| 372 |
+
def tuple_c_declaration(self, rtuple: RTuple) -> list[str]:
|
| 373 |
+
result = [
|
| 374 |
+
f"#ifndef MYPYC_DECLARED_{rtuple.struct_name}",
|
| 375 |
+
f"#define MYPYC_DECLARED_{rtuple.struct_name}",
|
| 376 |
+
f"typedef struct {rtuple.struct_name} {{",
|
| 377 |
+
]
|
| 378 |
+
if len(rtuple.types) == 0: # empty tuple
|
| 379 |
+
# Empty tuples contain a flag so that they can still indicate
|
| 380 |
+
# error values.
|
| 381 |
+
result.append("int empty_struct_error_flag;")
|
| 382 |
+
else:
|
| 383 |
+
i = 0
|
| 384 |
+
for typ in rtuple.types:
|
| 385 |
+
result.append(f"{self.ctype_spaced(typ)}f{i};")
|
| 386 |
+
i += 1
|
| 387 |
+
result.append(f"}} {rtuple.struct_name};")
|
| 388 |
+
result.append("#endif")
|
| 389 |
+
result.append("")
|
| 390 |
+
|
| 391 |
+
return result
|
| 392 |
+
|
| 393 |
+
def bitmap_field(self, index: int) -> str:
|
| 394 |
+
"""Return C field name used for attribute bitmap."""
|
| 395 |
+
n = index // BITMAP_BITS
|
| 396 |
+
if n == 0:
|
| 397 |
+
return "bitmap"
|
| 398 |
+
return f"bitmap{n + 1}"
|
| 399 |
+
|
| 400 |
+
def attr_bitmap_expr(self, obj: str, cl: ClassIR, index: int) -> str:
|
| 401 |
+
"""Return reference to the attribute definedness bitmap."""
|
| 402 |
+
cast = f"({cl.struct_name(self.names)} *)"
|
| 403 |
+
attr = self.bitmap_field(index)
|
| 404 |
+
return f"({cast}{obj})->{attr}"
|
| 405 |
+
|
| 406 |
+
def emit_attr_bitmap_set(
|
| 407 |
+
self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str
|
| 408 |
+
) -> None:
|
| 409 |
+
"""Mark an attribute as defined in the attribute bitmap.
|
| 410 |
+
|
| 411 |
+
Assumes that the attribute is tracked in the bitmap (only some attributes
|
| 412 |
+
use the bitmap). If 'value' is not equal to the error value, do nothing.
|
| 413 |
+
"""
|
| 414 |
+
self._emit_attr_bitmap_update(value, obj, rtype, cl, attr, clear=False)
|
| 415 |
+
|
| 416 |
+
def emit_attr_bitmap_clear(self, obj: str, rtype: RType, cl: ClassIR, attr: str) -> None:
|
| 417 |
+
"""Mark an attribute as undefined in the attribute bitmap.
|
| 418 |
+
|
| 419 |
+
Unlike emit_attr_bitmap_set, clear unconditionally.
|
| 420 |
+
"""
|
| 421 |
+
self._emit_attr_bitmap_update("", obj, rtype, cl, attr, clear=True)
|
| 422 |
+
|
| 423 |
+
def _emit_attr_bitmap_update(
|
| 424 |
+
self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str, clear: bool
|
| 425 |
+
) -> None:
|
| 426 |
+
if value:
|
| 427 |
+
check = self.error_value_check(rtype, value, "==")
|
| 428 |
+
self.emit_line(f"if (unlikely({check})) {{")
|
| 429 |
+
index = cl.bitmap_attrs.index(attr)
|
| 430 |
+
mask = 1 << (index & (BITMAP_BITS - 1))
|
| 431 |
+
bitmap = self.attr_bitmap_expr(obj, cl, index)
|
| 432 |
+
if clear:
|
| 433 |
+
self.emit_line(f"{bitmap} &= ~{mask};")
|
| 434 |
+
else:
|
| 435 |
+
self.emit_line(f"{bitmap} |= {mask};")
|
| 436 |
+
if value:
|
| 437 |
+
self.emit_line("}")
|
| 438 |
+
|
| 439 |
+
def emit_undefined_attr_check(
|
| 440 |
+
self,
|
| 441 |
+
rtype: RType,
|
| 442 |
+
attr_expr: str,
|
| 443 |
+
compare: str,
|
| 444 |
+
obj: str,
|
| 445 |
+
attr: str,
|
| 446 |
+
cl: ClassIR,
|
| 447 |
+
*,
|
| 448 |
+
unlikely: bool = False,
|
| 449 |
+
) -> None:
|
| 450 |
+
check = self.error_value_check(rtype, attr_expr, compare)
|
| 451 |
+
if unlikely:
|
| 452 |
+
check = f"unlikely({check})"
|
| 453 |
+
if rtype.error_overlap:
|
| 454 |
+
index = cl.bitmap_attrs.index(attr)
|
| 455 |
+
bit = 1 << (index & (BITMAP_BITS - 1))
|
| 456 |
+
attr = self.bitmap_field(index)
|
| 457 |
+
obj_expr = f"({cl.struct_name(self.names)} *){obj}"
|
| 458 |
+
check = f"{check} && !(({obj_expr})->{attr} & {bit})"
|
| 459 |
+
self.emit_line(f"if ({check}) {{")
|
| 460 |
+
|
| 461 |
+
def error_value_check(self, rtype: RType, value: str, compare: str) -> str:
|
| 462 |
+
if isinstance(rtype, RTuple):
|
| 463 |
+
return self.tuple_undefined_check_cond(
|
| 464 |
+
rtype, value, self.c_error_value, compare, check_exception=False
|
| 465 |
+
)
|
| 466 |
+
elif isinstance(rtype, RVec):
|
| 467 |
+
if compare == "==":
|
| 468 |
+
return f"{value}.len < 0"
|
| 469 |
+
elif compare == "!=":
|
| 470 |
+
return f"{value}.len >= 0"
|
| 471 |
+
assert False, compare
|
| 472 |
+
else:
|
| 473 |
+
return f"{value} {compare} {self.c_error_value(rtype)}"
|
| 474 |
+
|
| 475 |
+
def tuple_undefined_check_cond(
|
| 476 |
+
self,
|
| 477 |
+
rtuple: RTuple,
|
| 478 |
+
tuple_expr_in_c: str,
|
| 479 |
+
c_type_compare_val: Callable[[RType], str],
|
| 480 |
+
compare: str,
|
| 481 |
+
*,
|
| 482 |
+
check_exception: bool = True,
|
| 483 |
+
) -> str:
|
| 484 |
+
if len(rtuple.types) == 0:
|
| 485 |
+
# empty tuple
|
| 486 |
+
return "{}.empty_struct_error_flag {} {}".format(
|
| 487 |
+
tuple_expr_in_c, compare, c_type_compare_val(int_rprimitive)
|
| 488 |
+
)
|
| 489 |
+
if rtuple.error_overlap:
|
| 490 |
+
i = 0
|
| 491 |
+
item_type = rtuple.types[0]
|
| 492 |
+
else:
|
| 493 |
+
for i, typ in enumerate(rtuple.types):
|
| 494 |
+
if not typ.error_overlap:
|
| 495 |
+
item_type = rtuple.types[i]
|
| 496 |
+
break
|
| 497 |
+
else:
|
| 498 |
+
assert False, "not expecting tuple with error overlap"
|
| 499 |
+
if isinstance(item_type, RTuple):
|
| 500 |
+
return self.tuple_undefined_check_cond(
|
| 501 |
+
item_type, tuple_expr_in_c + f".f{i}", c_type_compare_val, compare
|
| 502 |
+
)
|
| 503 |
+
elif isinstance(item_type, RVec):
|
| 504 |
+
return f"{tuple_expr_in_c}.f{i}.len {compare} -1"
|
| 505 |
+
else:
|
| 506 |
+
check = f"{tuple_expr_in_c}.f{i} {compare} {c_type_compare_val(item_type)}"
|
| 507 |
+
if rtuple.error_overlap and check_exception:
|
| 508 |
+
check += " && PyErr_Occurred()"
|
| 509 |
+
return check
|
| 510 |
+
|
| 511 |
+
def tuple_undefined_value(self, rtuple: RTuple) -> str:
|
| 512 |
+
"""Undefined tuple value suitable in an expression."""
|
| 513 |
+
return f"({rtuple.struct_name}) {self.c_initializer_undefined_value(rtuple)}"
|
| 514 |
+
|
| 515 |
+
def c_initializer_undefined_value(self, rtype: RType) -> str:
|
| 516 |
+
"""Undefined value represented in a form suitable for variable initialization."""
|
| 517 |
+
if isinstance(rtype, RTuple):
|
| 518 |
+
if not rtype.types:
|
| 519 |
+
# Empty tuples contain a flag so that they can still indicate
|
| 520 |
+
# error values.
|
| 521 |
+
return f"{{ {int_rprimitive.c_undefined} }}"
|
| 522 |
+
items = ", ".join([self.c_initializer_undefined_value(t) for t in rtype.types])
|
| 523 |
+
return f"{{ {items} }}"
|
| 524 |
+
elif isinstance(rtype, RVec):
|
| 525 |
+
return "{ -1, NULL }"
|
| 526 |
+
else:
|
| 527 |
+
return self.c_undefined_value(rtype)
|
| 528 |
+
|
| 529 |
+
# Higher-level operations
|
| 530 |
+
|
| 531 |
+
def declare_tuple_struct(self, tuple_type: RTuple) -> None:
|
| 532 |
+
if tuple_type.struct_name not in self.context.declarations:
|
| 533 |
+
dependencies = set()
|
| 534 |
+
for typ in tuple_type.types:
|
| 535 |
+
# XXX other types might eventually need similar behavior
|
| 536 |
+
if isinstance(typ, RTuple):
|
| 537 |
+
dependencies.add(typ.struct_name)
|
| 538 |
+
|
| 539 |
+
self.context.declarations[tuple_type.struct_name] = HeaderDeclaration(
|
| 540 |
+
self.tuple_c_declaration(tuple_type), dependencies=dependencies, is_type=True
|
| 541 |
+
)
|
| 542 |
+
|
| 543 |
+
def emit_inc_ref(self, dest: str, rtype: RType, *, rare: bool = False) -> None:
|
| 544 |
+
"""Increment reference count of C expression `dest`.
|
| 545 |
+
|
| 546 |
+
For composite unboxed structures (e.g. tuples) recursively
|
| 547 |
+
increment reference counts for each component.
|
| 548 |
+
|
| 549 |
+
If rare is True, optimize for code size and compilation speed.
|
| 550 |
+
"""
|
| 551 |
+
if is_int_rprimitive(rtype):
|
| 552 |
+
if rare:
|
| 553 |
+
self.emit_line("CPyTagged_IncRef(%s);" % dest)
|
| 554 |
+
else:
|
| 555 |
+
self.emit_line("CPyTagged_INCREF(%s);" % dest)
|
| 556 |
+
elif isinstance(rtype, RTuple):
|
| 557 |
+
for i, item_type in enumerate(rtype.types):
|
| 558 |
+
self.emit_inc_ref(f"{dest}.f{i}", item_type)
|
| 559 |
+
elif isinstance(rtype, RVec):
|
| 560 |
+
# TODO: Only use the X variant if buf can be NULL
|
| 561 |
+
self.emit_line(f"Py_XINCREF({dest}.buf);")
|
| 562 |
+
elif not rtype.is_unboxed:
|
| 563 |
+
# Always inline, since this is a simple but very hot op
|
| 564 |
+
if rtype.may_be_immortal or not HAVE_IMMORTAL:
|
| 565 |
+
self.emit_line("CPy_INCREF(%s);" % dest)
|
| 566 |
+
else:
|
| 567 |
+
self.emit_line("CPy_INCREF_NO_IMM(%s);" % dest)
|
| 568 |
+
# Otherwise assume it's an unboxed, pointerless value and do nothing.
|
| 569 |
+
|
| 570 |
+
def emit_dec_ref(
|
| 571 |
+
self, dest: str, rtype: RType, *, is_xdec: bool = False, rare: bool = False
|
| 572 |
+
) -> None:
|
| 573 |
+
"""Decrement reference count of C expression `dest`.
|
| 574 |
+
|
| 575 |
+
For composite unboxed structures (e.g. tuples) recursively
|
| 576 |
+
decrement reference counts for each component.
|
| 577 |
+
|
| 578 |
+
If rare is True, optimize for code size and compilation speed.
|
| 579 |
+
"""
|
| 580 |
+
x = "X" if is_xdec else ""
|
| 581 |
+
if is_int_rprimitive(rtype):
|
| 582 |
+
if rare:
|
| 583 |
+
self.emit_line(f"CPyTagged_{x}DecRef({dest});")
|
| 584 |
+
else:
|
| 585 |
+
# Inlined
|
| 586 |
+
self.emit_line(f"CPyTagged_{x}DECREF({dest});")
|
| 587 |
+
elif isinstance(rtype, RTuple):
|
| 588 |
+
for i, item_type in enumerate(rtype.types):
|
| 589 |
+
self.emit_dec_ref(f"{dest}.f{i}", item_type, is_xdec=is_xdec, rare=rare)
|
| 590 |
+
elif isinstance(rtype, RVec):
|
| 591 |
+
# TODO: Only use the X variant if buf can be NULL
|
| 592 |
+
if rare:
|
| 593 |
+
self.emit_line(f"CPy_XDecRef({dest}.buf);")
|
| 594 |
+
else:
|
| 595 |
+
self.emit_line(f"CPy_XDECREF({dest}.buf);")
|
| 596 |
+
elif not rtype.is_unboxed:
|
| 597 |
+
if rare:
|
| 598 |
+
self.emit_line(f"CPy_{x}DecRef({dest});")
|
| 599 |
+
else:
|
| 600 |
+
# Inlined
|
| 601 |
+
if rtype.may_be_immortal or not HAVE_IMMORTAL:
|
| 602 |
+
self.emit_line(f"CPy_{x}DECREF({dest});")
|
| 603 |
+
else:
|
| 604 |
+
self.emit_line(f"CPy_{x}DECREF_NO_IMM({dest});")
|
| 605 |
+
elif rtype.is_refcounted:
|
| 606 |
+
assert False, f"dec_ref not implemented for {rtype}"
|
| 607 |
+
# Otherwise assume it's an unboxed, pointerless value and do nothing.
|
| 608 |
+
|
| 609 |
+
def pretty_name(self, typ: RType) -> str:
|
| 610 |
+
value_type = optional_value_type(typ)
|
| 611 |
+
if value_type is not None:
|
| 612 |
+
return "%s or None" % self.pretty_name(value_type)
|
| 613 |
+
return str(typ)
|
| 614 |
+
|
| 615 |
+
def emit_cast(
|
| 616 |
+
self,
|
| 617 |
+
src: str,
|
| 618 |
+
dest: str,
|
| 619 |
+
typ: RType,
|
| 620 |
+
*,
|
| 621 |
+
declare_dest: bool = False,
|
| 622 |
+
error: ErrorHandler | None = None,
|
| 623 |
+
raise_exception: bool = True,
|
| 624 |
+
optional: bool = False,
|
| 625 |
+
src_type: RType | None = None,
|
| 626 |
+
likely: bool = True,
|
| 627 |
+
) -> None:
|
| 628 |
+
"""Emit code for casting a value of given type.
|
| 629 |
+
|
| 630 |
+
Somewhat strangely, this supports unboxed types but only
|
| 631 |
+
operates on boxed versions. This is necessary to properly
|
| 632 |
+
handle types such as Optional[int] in compatibility glue.
|
| 633 |
+
|
| 634 |
+
By default, assign NULL (error value) to dest if the value has
|
| 635 |
+
an incompatible type and raise TypeError. These can be customized
|
| 636 |
+
using 'error' and 'raise_exception'.
|
| 637 |
+
|
| 638 |
+
Always copy/steal the reference in 'src'.
|
| 639 |
+
|
| 640 |
+
Args:
|
| 641 |
+
src: Name of source C variable
|
| 642 |
+
dest: Name of target C variable
|
| 643 |
+
typ: Type of value
|
| 644 |
+
declare_dest: If True, also declare the variable 'dest'
|
| 645 |
+
error: What happens on error
|
| 646 |
+
raise_exception: If True, also raise TypeError on failure
|
| 647 |
+
likely: If the cast is likely to succeed (can be False for unions)
|
| 648 |
+
"""
|
| 649 |
+
error = error or AssignHandler()
|
| 650 |
+
|
| 651 |
+
# Special case casting *from* optional
|
| 652 |
+
if src_type and is_optional_type(src_type) and not is_object_rprimitive(typ):
|
| 653 |
+
value_type = optional_value_type(src_type)
|
| 654 |
+
assert value_type is not None
|
| 655 |
+
if is_same_type(value_type, typ):
|
| 656 |
+
if declare_dest:
|
| 657 |
+
self.emit_line(f"PyObject *{dest};")
|
| 658 |
+
check = "({} != Py_None)"
|
| 659 |
+
if likely:
|
| 660 |
+
check = f"(likely{check})"
|
| 661 |
+
self.emit_arg_check(src, dest, typ, check.format(src), optional)
|
| 662 |
+
self.emit_lines(f" {dest} = {src};", "else {")
|
| 663 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 664 |
+
self.emit_line("}")
|
| 665 |
+
return
|
| 666 |
+
|
| 667 |
+
# TODO: Verify refcount handling.
|
| 668 |
+
if (
|
| 669 |
+
is_list_rprimitive(typ)
|
| 670 |
+
or is_dict_rprimitive(typ)
|
| 671 |
+
or is_set_rprimitive(typ)
|
| 672 |
+
or is_frozenset_rprimitive(typ)
|
| 673 |
+
or is_str_rprimitive(typ)
|
| 674 |
+
or is_range_rprimitive(typ)
|
| 675 |
+
or is_float_rprimitive(typ)
|
| 676 |
+
or is_int_rprimitive(typ)
|
| 677 |
+
or is_bool_or_bit_rprimitive(typ)
|
| 678 |
+
or is_fixed_width_rtype(typ)
|
| 679 |
+
):
|
| 680 |
+
if declare_dest:
|
| 681 |
+
self.emit_line(f"PyObject *{dest};")
|
| 682 |
+
if is_list_rprimitive(typ):
|
| 683 |
+
prefix = "PyList"
|
| 684 |
+
elif is_dict_rprimitive(typ):
|
| 685 |
+
prefix = "PyDict"
|
| 686 |
+
elif is_set_rprimitive(typ):
|
| 687 |
+
prefix = "PySet"
|
| 688 |
+
elif is_frozenset_rprimitive(typ):
|
| 689 |
+
prefix = "PyFrozenSet"
|
| 690 |
+
elif is_str_rprimitive(typ):
|
| 691 |
+
prefix = "PyUnicode"
|
| 692 |
+
elif is_range_rprimitive(typ):
|
| 693 |
+
prefix = "PyRange"
|
| 694 |
+
elif is_float_rprimitive(typ):
|
| 695 |
+
prefix = "CPyFloat"
|
| 696 |
+
elif is_int_rprimitive(typ) or is_fixed_width_rtype(typ):
|
| 697 |
+
# TODO: Range check for fixed-width types?
|
| 698 |
+
prefix = "PyLong"
|
| 699 |
+
elif is_bool_or_bit_rprimitive(typ):
|
| 700 |
+
prefix = "PyBool"
|
| 701 |
+
else:
|
| 702 |
+
assert False, f"unexpected primitive type: {typ}"
|
| 703 |
+
check = "({}_Check({}))"
|
| 704 |
+
if likely:
|
| 705 |
+
check = f"(likely{check})"
|
| 706 |
+
self.emit_arg_check(src, dest, typ, check.format(prefix, src), optional)
|
| 707 |
+
self.emit_lines(f" {dest} = {src};", "else {")
|
| 708 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 709 |
+
self.emit_line("}")
|
| 710 |
+
elif is_bytes_rprimitive(typ):
|
| 711 |
+
if declare_dest:
|
| 712 |
+
self.emit_line(f"PyObject *{dest};")
|
| 713 |
+
check = "(PyBytes_Check({}))"
|
| 714 |
+
if likely:
|
| 715 |
+
check = f"(likely{check})"
|
| 716 |
+
self.emit_arg_check(src, dest, typ, check.format(src, src), optional)
|
| 717 |
+
self.emit_lines(f" {dest} = {src};", "else {")
|
| 718 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 719 |
+
self.emit_line("}")
|
| 720 |
+
elif is_bytearray_rprimitive(typ):
|
| 721 |
+
if declare_dest:
|
| 722 |
+
self.emit_line(f"PyObject *{dest};")
|
| 723 |
+
check = "(PyByteArray_Check({}))"
|
| 724 |
+
if likely:
|
| 725 |
+
check = f"(likely{check})"
|
| 726 |
+
self.emit_arg_check(src, dest, typ, check.format(src, src), optional)
|
| 727 |
+
self.emit_lines(f" {dest} = {src};", "else {")
|
| 728 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 729 |
+
self.emit_line("}")
|
| 730 |
+
elif is_tuple_rprimitive(typ):
|
| 731 |
+
if declare_dest:
|
| 732 |
+
self.emit_line(f"{self.ctype(typ)} {dest};")
|
| 733 |
+
check = "(PyTuple_Check({}))"
|
| 734 |
+
if likely:
|
| 735 |
+
check = f"(likely{check})"
|
| 736 |
+
self.emit_arg_check(src, dest, typ, check.format(src), optional)
|
| 737 |
+
self.emit_lines(f" {dest} = {src};", "else {")
|
| 738 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 739 |
+
self.emit_line("}")
|
| 740 |
+
elif isinstance(typ, RInstance):
|
| 741 |
+
if declare_dest:
|
| 742 |
+
self.emit_line(f"PyObject *{dest};")
|
| 743 |
+
concrete = all_concrete_classes(typ.class_ir)
|
| 744 |
+
# If there are too many concrete subclasses or we can't find any
|
| 745 |
+
# (meaning the code ought to be dead or we aren't doing global opts),
|
| 746 |
+
# fall back to a normal typecheck.
|
| 747 |
+
# Otherwise check all the subclasses.
|
| 748 |
+
if not concrete or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1:
|
| 749 |
+
check = "(PyObject_TypeCheck({}, {}))".format(
|
| 750 |
+
src, self.type_struct_name(typ.class_ir)
|
| 751 |
+
)
|
| 752 |
+
else:
|
| 753 |
+
full_str = "(Py_TYPE({src}) == {targets[0]})"
|
| 754 |
+
for i in range(1, len(concrete)):
|
| 755 |
+
full_str += " || (Py_TYPE({src}) == {targets[%d]})" % i
|
| 756 |
+
if len(concrete) > 1:
|
| 757 |
+
full_str = "(%s)" % full_str
|
| 758 |
+
check = full_str.format(
|
| 759 |
+
src=src, targets=[self.type_struct_name(ir) for ir in concrete]
|
| 760 |
+
)
|
| 761 |
+
if likely:
|
| 762 |
+
check = f"(likely{check})"
|
| 763 |
+
self.emit_arg_check(src, dest, typ, check, optional)
|
| 764 |
+
self.emit_lines(f" {dest} = {src};", "else {")
|
| 765 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 766 |
+
self.emit_line("}")
|
| 767 |
+
elif is_none_rprimitive(typ):
|
| 768 |
+
if declare_dest:
|
| 769 |
+
self.emit_line(f"PyObject *{dest};")
|
| 770 |
+
check = "({} == Py_None)"
|
| 771 |
+
if likely:
|
| 772 |
+
check = f"(likely{check})"
|
| 773 |
+
self.emit_arg_check(src, dest, typ, check.format(src), optional)
|
| 774 |
+
self.emit_lines(f" {dest} = {src};", "else {")
|
| 775 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 776 |
+
self.emit_line("}")
|
| 777 |
+
elif is_object_rprimitive(typ):
|
| 778 |
+
if declare_dest:
|
| 779 |
+
self.emit_line(f"PyObject *{dest};")
|
| 780 |
+
self.emit_arg_check(src, dest, typ, "", optional)
|
| 781 |
+
self.emit_line(f"{dest} = {src};")
|
| 782 |
+
if optional:
|
| 783 |
+
self.emit_line("}")
|
| 784 |
+
elif is_native_rprimitive(typ):
|
| 785 |
+
# Native primitive types have type check functions of form "CPy<Name>_Check(...)".
|
| 786 |
+
if declare_dest:
|
| 787 |
+
self.emit_line(f"PyObject *{dest};")
|
| 788 |
+
short_name = typ.name.rsplit(".", 1)[-1]
|
| 789 |
+
check = f"(CPy{short_name}_Check({src}))"
|
| 790 |
+
if likely:
|
| 791 |
+
check = f"(likely{check})"
|
| 792 |
+
self.emit_arg_check(src, dest, typ, check, optional)
|
| 793 |
+
self.emit_lines(f" {dest} = {src};", "else {")
|
| 794 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 795 |
+
self.emit_line("}")
|
| 796 |
+
elif isinstance(typ, RUnion):
|
| 797 |
+
self.emit_union_cast(
|
| 798 |
+
src, dest, typ, declare_dest, error, optional, src_type, raise_exception
|
| 799 |
+
)
|
| 800 |
+
elif isinstance(typ, RTuple):
|
| 801 |
+
assert not optional
|
| 802 |
+
self.emit_tuple_cast(src, dest, typ, declare_dest, error, src_type)
|
| 803 |
+
elif isinstance(typ, RVec):
|
| 804 |
+
if declare_dest:
|
| 805 |
+
self.emit_line(f"PyObject *{dest};")
|
| 806 |
+
# Build type check expression based on vec kind
|
| 807 |
+
api_name = vec_api_by_item_type.get(typ.item_type)
|
| 808 |
+
depth = typ.depth()
|
| 809 |
+
if api_name:
|
| 810 |
+
# Specialized vec types (vec[i64], vec[i32], etc.)
|
| 811 |
+
check = f"(Py_TYPE({src}) == {api_name}.boxed_type)"
|
| 812 |
+
elif depth == 0:
|
| 813 |
+
# Generic vec types (vec[T], vec[T | None]) with reference type items
|
| 814 |
+
item_type_c = self.vec_item_type_c(typ)
|
| 815 |
+
check = (
|
| 816 |
+
f"(Py_TYPE({src}) == VecTApi.boxed_type && "
|
| 817 |
+
f"((VecTObject *){src})->vec.buf->item_type == {item_type_c})"
|
| 818 |
+
)
|
| 819 |
+
else:
|
| 820 |
+
# Nested vec types (vec[vec[...]]). Check boxed type, item type, and depth.
|
| 821 |
+
unwrapped = typ.unwrap_item_type()
|
| 822 |
+
if unwrapped in vec_item_type_tags:
|
| 823 |
+
type_value = str(vec_item_type_tags[unwrapped])
|
| 824 |
+
else:
|
| 825 |
+
type_value = self.vec_item_type_c(typ)
|
| 826 |
+
check = (
|
| 827 |
+
f"(Py_TYPE({src}) == VecNestedApi.boxed_type && "
|
| 828 |
+
f"((VecNestedObject *){src})->vec.buf->item_type == {type_value} && "
|
| 829 |
+
f"((VecNestedObject *){src})->vec.buf->depth == {depth})"
|
| 830 |
+
)
|
| 831 |
+
if likely:
|
| 832 |
+
check = f"(likely{check})"
|
| 833 |
+
self.emit_arg_check(src, dest, typ, check, optional)
|
| 834 |
+
self.emit_lines(f" {dest} = {src};", "else {")
|
| 835 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 836 |
+
self.emit_line("}")
|
| 837 |
+
else:
|
| 838 |
+
assert False, "Cast not implemented: %s" % typ
|
| 839 |
+
|
| 840 |
+
def emit_cast_error_handler(
|
| 841 |
+
self, error: ErrorHandler, src: str, dest: str, typ: RType, raise_exception: bool
|
| 842 |
+
) -> None:
|
| 843 |
+
if raise_exception:
|
| 844 |
+
if isinstance(error, TracebackAndGotoHandler):
|
| 845 |
+
# Merge raising and emitting traceback entry into a single call.
|
| 846 |
+
self.emit_type_error_traceback(
|
| 847 |
+
error.source_path, error.module_name, error.traceback_entry, typ=typ, src=src
|
| 848 |
+
)
|
| 849 |
+
self.emit_line("goto %s;" % error.label)
|
| 850 |
+
return
|
| 851 |
+
self.emit_line(f'CPy_TypeError("{self.pretty_name(typ)}", {src}); ')
|
| 852 |
+
if isinstance(error, AssignHandler):
|
| 853 |
+
self.emit_line("%s = NULL;" % dest)
|
| 854 |
+
elif isinstance(error, GotoHandler):
|
| 855 |
+
self.emit_line("goto %s;" % error.label)
|
| 856 |
+
elif isinstance(error, TracebackAndGotoHandler):
|
| 857 |
+
self.emit_line("%s = NULL;" % dest)
|
| 858 |
+
self.emit_traceback(error.source_path, error.module_name, error.traceback_entry)
|
| 859 |
+
self.emit_line("goto %s;" % error.label)
|
| 860 |
+
else:
|
| 861 |
+
assert isinstance(error, ReturnHandler), error
|
| 862 |
+
self.emit_line("return %s;" % error.value)
|
| 863 |
+
|
| 864 |
+
def emit_union_cast(
|
| 865 |
+
self,
|
| 866 |
+
src: str,
|
| 867 |
+
dest: str,
|
| 868 |
+
typ: RUnion,
|
| 869 |
+
declare_dest: bool,
|
| 870 |
+
error: ErrorHandler,
|
| 871 |
+
optional: bool,
|
| 872 |
+
src_type: RType | None,
|
| 873 |
+
raise_exception: bool,
|
| 874 |
+
) -> None:
|
| 875 |
+
"""Emit cast to a union type.
|
| 876 |
+
|
| 877 |
+
The arguments are similar to emit_cast.
|
| 878 |
+
"""
|
| 879 |
+
if declare_dest:
|
| 880 |
+
self.emit_line(f"PyObject *{dest};")
|
| 881 |
+
good_label = self.new_label()
|
| 882 |
+
if optional:
|
| 883 |
+
self.emit_line(f"if ({src} == NULL) {{")
|
| 884 |
+
self.emit_line(f"{dest} = {self.c_error_value(typ)};")
|
| 885 |
+
self.emit_line(f"goto {good_label};")
|
| 886 |
+
self.emit_line("}")
|
| 887 |
+
for item in typ.items:
|
| 888 |
+
self.emit_cast(
|
| 889 |
+
src,
|
| 890 |
+
dest,
|
| 891 |
+
item,
|
| 892 |
+
declare_dest=False,
|
| 893 |
+
raise_exception=False,
|
| 894 |
+
optional=False,
|
| 895 |
+
likely=False,
|
| 896 |
+
)
|
| 897 |
+
self.emit_line(f"if ({dest} != NULL) goto {good_label};")
|
| 898 |
+
# Handle cast failure.
|
| 899 |
+
self.emit_cast_error_handler(error, src, dest, typ, raise_exception)
|
| 900 |
+
self.emit_label(good_label)
|
| 901 |
+
|
| 902 |
+
def emit_tuple_cast(
|
| 903 |
+
self,
|
| 904 |
+
src: str,
|
| 905 |
+
dest: str,
|
| 906 |
+
typ: RTuple,
|
| 907 |
+
declare_dest: bool,
|
| 908 |
+
error: ErrorHandler,
|
| 909 |
+
src_type: RType | None,
|
| 910 |
+
) -> None:
|
| 911 |
+
"""Emit cast to a tuple type.
|
| 912 |
+
|
| 913 |
+
The arguments are similar to emit_cast.
|
| 914 |
+
"""
|
| 915 |
+
if declare_dest:
|
| 916 |
+
self.emit_line(f"PyObject *{dest};")
|
| 917 |
+
# This reuse of the variable is super dodgy. We don't even
|
| 918 |
+
# care about the values except to check whether they are
|
| 919 |
+
# invalid.
|
| 920 |
+
out_label = self.new_label()
|
| 921 |
+
self.emit_lines(
|
| 922 |
+
"if (unlikely(!(PyTuple_Check({r}) && PyTuple_GET_SIZE({r}) == {size}))) {{".format(
|
| 923 |
+
r=src, size=len(typ.types)
|
| 924 |
+
),
|
| 925 |
+
f"{dest} = NULL;",
|
| 926 |
+
f"goto {out_label};",
|
| 927 |
+
"}",
|
| 928 |
+
)
|
| 929 |
+
for i, item in enumerate(typ.types):
|
| 930 |
+
# Since we did the checks above this should never fail
|
| 931 |
+
self.emit_cast(
|
| 932 |
+
f"PyTuple_GET_ITEM({src}, {i})",
|
| 933 |
+
dest,
|
| 934 |
+
item,
|
| 935 |
+
declare_dest=False,
|
| 936 |
+
raise_exception=False,
|
| 937 |
+
optional=False,
|
| 938 |
+
)
|
| 939 |
+
self.emit_line(f"if ({dest} == NULL) goto {out_label};")
|
| 940 |
+
|
| 941 |
+
self.emit_line(f"{dest} = {src};")
|
| 942 |
+
self.emit_label(out_label)
|
| 943 |
+
|
| 944 |
+
def emit_arg_check(self, src: str, dest: str, typ: RType, check: str, optional: bool) -> None:
|
| 945 |
+
if optional:
|
| 946 |
+
self.emit_line(f"if ({src} == NULL) {{")
|
| 947 |
+
self.emit_line(f"{dest} = {self.c_error_value(typ)};")
|
| 948 |
+
if check != "":
|
| 949 |
+
self.emit_line("{}if {}".format("} else " if optional else "", check))
|
| 950 |
+
elif optional:
|
| 951 |
+
self.emit_line("else {")
|
| 952 |
+
|
| 953 |
+
def emit_unbox(
|
| 954 |
+
self,
|
| 955 |
+
src: str,
|
| 956 |
+
dest: str,
|
| 957 |
+
typ: RType,
|
| 958 |
+
*,
|
| 959 |
+
declare_dest: bool = False,
|
| 960 |
+
error: ErrorHandler | None = None,
|
| 961 |
+
raise_exception: bool = True,
|
| 962 |
+
optional: bool = False,
|
| 963 |
+
borrow: bool = False,
|
| 964 |
+
) -> None:
|
| 965 |
+
"""Emit code for unboxing a value of given type (from PyObject *).
|
| 966 |
+
|
| 967 |
+
By default, assign error value to dest if the value has an
|
| 968 |
+
incompatible type and raise TypeError. These can be customized
|
| 969 |
+
using 'error' and 'raise_exception'.
|
| 970 |
+
|
| 971 |
+
Generate a new reference unless 'borrow' is True.
|
| 972 |
+
|
| 973 |
+
Args:
|
| 974 |
+
src: Name of source C variable
|
| 975 |
+
dest: Name of target C variable
|
| 976 |
+
typ: Type of value
|
| 977 |
+
declare_dest: If True, also declare the variable 'dest'
|
| 978 |
+
error: What happens on error
|
| 979 |
+
raise_exception: If True, also raise TypeError on failure
|
| 980 |
+
optional: If True, NULL src value is allowed and will map to error value
|
| 981 |
+
borrow: If True, create a borrowed reference
|
| 982 |
+
|
| 983 |
+
"""
|
| 984 |
+
error = error or AssignHandler()
|
| 985 |
+
# TODO: Verify refcount handling.
|
| 986 |
+
if isinstance(error, AssignHandler):
|
| 987 |
+
failure = f"{dest} = {self.c_error_value(typ)};"
|
| 988 |
+
elif isinstance(error, GotoHandler):
|
| 989 |
+
failure = "goto %s;" % error.label
|
| 990 |
+
else:
|
| 991 |
+
assert isinstance(error, ReturnHandler), error
|
| 992 |
+
failure = "return %s;" % error.value
|
| 993 |
+
if raise_exception:
|
| 994 |
+
raise_exc = f'CPy_TypeError("{self.pretty_name(typ)}", {src}); '
|
| 995 |
+
failure = raise_exc + failure
|
| 996 |
+
if is_int_rprimitive(typ) or is_short_int_rprimitive(typ):
|
| 997 |
+
if declare_dest:
|
| 998 |
+
self.emit_line(f"CPyTagged {dest};")
|
| 999 |
+
self.emit_arg_check(src, dest, typ, f"(likely(PyLong_Check({src})))", optional)
|
| 1000 |
+
if borrow:
|
| 1001 |
+
self.emit_line(f" {dest} = CPyTagged_BorrowFromObject({src});")
|
| 1002 |
+
else:
|
| 1003 |
+
self.emit_line(f" {dest} = CPyTagged_FromObject({src});")
|
| 1004 |
+
self.emit_line("else {")
|
| 1005 |
+
self.emit_line(failure)
|
| 1006 |
+
self.emit_line("}")
|
| 1007 |
+
elif is_bool_or_bit_rprimitive(typ):
|
| 1008 |
+
# Whether we are borrowing or not makes no difference.
|
| 1009 |
+
if declare_dest:
|
| 1010 |
+
self.emit_line(f"char {dest};")
|
| 1011 |
+
self.emit_arg_check(src, dest, typ, f"(unlikely(!PyBool_Check({src}))) {{", optional)
|
| 1012 |
+
self.emit_line(failure)
|
| 1013 |
+
self.emit_line("} else")
|
| 1014 |
+
conversion = f"{src} == Py_True"
|
| 1015 |
+
self.emit_line(f" {dest} = {conversion};")
|
| 1016 |
+
elif is_none_rprimitive(typ):
|
| 1017 |
+
# Whether we are borrowing or not makes no difference.
|
| 1018 |
+
if declare_dest:
|
| 1019 |
+
self.emit_line(f"char {dest};")
|
| 1020 |
+
self.emit_arg_check(src, dest, typ, f"(unlikely({src} != Py_None)) {{", optional)
|
| 1021 |
+
self.emit_line(failure)
|
| 1022 |
+
self.emit_line("} else")
|
| 1023 |
+
self.emit_line(f" {dest} = 1;")
|
| 1024 |
+
elif is_int64_rprimitive(typ):
|
| 1025 |
+
# Whether we are borrowing or not makes no difference.
|
| 1026 |
+
assert not optional # Not supported for overlapping error values
|
| 1027 |
+
if declare_dest:
|
| 1028 |
+
self.emit_line(f"int64_t {dest};")
|
| 1029 |
+
self.emit_line(f"{dest} = CPyLong_AsInt64({src});")
|
| 1030 |
+
if not isinstance(error, AssignHandler):
|
| 1031 |
+
self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
|
| 1032 |
+
elif is_int32_rprimitive(typ):
|
| 1033 |
+
# Whether we are borrowing or not makes no difference.
|
| 1034 |
+
assert not optional # Not supported for overlapping error values
|
| 1035 |
+
if declare_dest:
|
| 1036 |
+
self.emit_line(f"int32_t {dest};")
|
| 1037 |
+
self.emit_line(f"{dest} = CPyLong_AsInt32({src});")
|
| 1038 |
+
if not isinstance(error, AssignHandler):
|
| 1039 |
+
self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
|
| 1040 |
+
elif is_int16_rprimitive(typ):
|
| 1041 |
+
# Whether we are borrowing or not makes no difference.
|
| 1042 |
+
assert not optional # Not supported for overlapping error values
|
| 1043 |
+
if declare_dest:
|
| 1044 |
+
self.emit_line(f"int16_t {dest};")
|
| 1045 |
+
self.emit_line(f"{dest} = CPyLong_AsInt16({src});")
|
| 1046 |
+
if not isinstance(error, AssignHandler):
|
| 1047 |
+
self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
|
| 1048 |
+
elif is_uint8_rprimitive(typ):
|
| 1049 |
+
# Whether we are borrowing or not makes no difference.
|
| 1050 |
+
assert not optional # Not supported for overlapping error values
|
| 1051 |
+
if declare_dest:
|
| 1052 |
+
self.emit_line(f"uint8_t {dest};")
|
| 1053 |
+
self.emit_line(f"{dest} = CPyLong_AsUInt8({src});")
|
| 1054 |
+
if not isinstance(error, AssignHandler):
|
| 1055 |
+
self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)
|
| 1056 |
+
elif is_float_rprimitive(typ):
|
| 1057 |
+
assert not optional # Not supported for overlapping error values
|
| 1058 |
+
if declare_dest:
|
| 1059 |
+
self.emit_line(f"double {dest};")
|
| 1060 |
+
# TODO: Don't use __float__ and __index__
|
| 1061 |
+
self.emit_line(f"{dest} = PyFloat_AsDouble({src});")
|
| 1062 |
+
self.emit_lines(f"if ({dest} == -1.0 && PyErr_Occurred()) {{", failure, "}")
|
| 1063 |
+
elif isinstance(typ, RTuple):
|
| 1064 |
+
self.declare_tuple_struct(typ)
|
| 1065 |
+
if declare_dest:
|
| 1066 |
+
self.emit_line(f"{self.ctype(typ)} {dest};")
|
| 1067 |
+
# HACK: The error handling for unboxing tuples is busted
|
| 1068 |
+
# and instead of fixing it I am just wrapping it in the
|
| 1069 |
+
# cast code which I think is right. This is not good.
|
| 1070 |
+
if optional:
|
| 1071 |
+
self.emit_line(f"if ({src} == NULL) {{")
|
| 1072 |
+
self.emit_line(f"{dest} = {self.c_error_value(typ)};")
|
| 1073 |
+
self.emit_line("} else {")
|
| 1074 |
+
|
| 1075 |
+
cast_temp = self.temp_name()
|
| 1076 |
+
self.emit_tuple_cast(
|
| 1077 |
+
src, cast_temp, typ, declare_dest=True, error=error, src_type=None
|
| 1078 |
+
)
|
| 1079 |
+
self.emit_line(f"if (unlikely({cast_temp} == NULL)) {{")
|
| 1080 |
+
|
| 1081 |
+
# self.emit_arg_check(src, dest, typ,
|
| 1082 |
+
# '(!PyTuple_Check({}) || PyTuple_Size({}) != {}) {{'.format(
|
| 1083 |
+
# src, src, len(typ.types)), optional)
|
| 1084 |
+
self.emit_line(failure) # TODO: Decrease refcount?
|
| 1085 |
+
self.emit_line("} else {")
|
| 1086 |
+
if not typ.types:
|
| 1087 |
+
self.emit_line(f"{dest}.empty_struct_error_flag = 0;")
|
| 1088 |
+
for i, item_type in enumerate(typ.types):
|
| 1089 |
+
temp = self.temp_name()
|
| 1090 |
+
# emit_tuple_cast above checks the size, so this should not fail
|
| 1091 |
+
self.emit_line(f"PyObject *{temp} = PyTuple_GET_ITEM({src}, {i});")
|
| 1092 |
+
temp2 = self.temp_name()
|
| 1093 |
+
# Unbox or check the item.
|
| 1094 |
+
if item_type.is_unboxed:
|
| 1095 |
+
self.emit_unbox(
|
| 1096 |
+
temp,
|
| 1097 |
+
temp2,
|
| 1098 |
+
item_type,
|
| 1099 |
+
raise_exception=raise_exception,
|
| 1100 |
+
error=error,
|
| 1101 |
+
declare_dest=True,
|
| 1102 |
+
borrow=borrow,
|
| 1103 |
+
)
|
| 1104 |
+
else:
|
| 1105 |
+
if not borrow:
|
| 1106 |
+
self.emit_inc_ref(temp, object_rprimitive)
|
| 1107 |
+
self.emit_cast(temp, temp2, item_type, declare_dest=True)
|
| 1108 |
+
self.emit_line(f"{dest}.f{i} = {temp2};")
|
| 1109 |
+
self.emit_line("}")
|
| 1110 |
+
if optional:
|
| 1111 |
+
self.emit_line("}")
|
| 1112 |
+
elif isinstance(typ, RVec):
|
| 1113 |
+
if declare_dest:
|
| 1114 |
+
self.emit_line(f"{self.ctype(typ)} {dest};")
|
| 1115 |
+
|
| 1116 |
+
if optional:
|
| 1117 |
+
self.emit_line(f"if ({src} == NULL) {{")
|
| 1118 |
+
self.emit_line(f"{dest} = {self.c_error_value(typ)};")
|
| 1119 |
+
self.emit_line("} else {")
|
| 1120 |
+
|
| 1121 |
+
specialized_api_name = vec_api_by_item_type.get(typ.item_type)
|
| 1122 |
+
if specialized_api_name is not None:
|
| 1123 |
+
self.emit_line(f"{dest} = {specialized_api_name}.unbox({src});")
|
| 1124 |
+
else:
|
| 1125 |
+
depth = typ.depth()
|
| 1126 |
+
unwrapped = typ.unwrap_item_type()
|
| 1127 |
+
if unwrapped in vec_item_type_tags:
|
| 1128 |
+
type_value = str(vec_item_type_tags[unwrapped])
|
| 1129 |
+
else:
|
| 1130 |
+
type_value = self.vec_item_type_c(typ)
|
| 1131 |
+
if depth == 0:
|
| 1132 |
+
self.emit_line(f"{dest} = VecTApi.unbox({src}, {type_value});")
|
| 1133 |
+
else:
|
| 1134 |
+
self.emit_line(f"{dest} = VecNestedApi.unbox({src}, {type_value}, {depth});")
|
| 1135 |
+
|
| 1136 |
+
self.emit_line(f"if (VEC_IS_ERROR({dest})) {{")
|
| 1137 |
+
self.emit_line(failure)
|
| 1138 |
+
self.emit_line("}")
|
| 1139 |
+
|
| 1140 |
+
if optional:
|
| 1141 |
+
self.emit_line("}")
|
| 1142 |
+
else:
|
| 1143 |
+
assert False, "Unboxing not implemented: %s" % typ
|
| 1144 |
+
|
| 1145 |
+
def vec_item_type_c(self, typ: RVec) -> str:
|
| 1146 |
+
item_type = typ.unwrap_item_type()
|
| 1147 |
+
type_c_ptr = self.type_c_ptr(item_type)
|
| 1148 |
+
# Can never be None, since we unwrapped the item type above
|
| 1149 |
+
assert type_c_ptr is not None
|
| 1150 |
+
type_value = f"(size_t){type_c_ptr}"
|
| 1151 |
+
if typ.is_optional():
|
| 1152 |
+
type_value = f"({type_value} | 1)"
|
| 1153 |
+
return type_value
|
| 1154 |
+
|
| 1155 |
+
def type_c_ptr(self, typ: RPrimitive | RInstance) -> str | None:
|
| 1156 |
+
if isinstance(typ, RPrimitive) and typ.is_refcounted:
|
| 1157 |
+
return "&" + builtin_names[typ.name][1]
|
| 1158 |
+
elif isinstance(typ, RInstance):
|
| 1159 |
+
return self.type_struct_name(typ.class_ir)
|
| 1160 |
+
return None
|
| 1161 |
+
|
| 1162 |
+
def emit_box(
|
| 1163 |
+
self, src: str, dest: str, typ: RType, declare_dest: bool = False, can_borrow: bool = False
|
| 1164 |
+
) -> None:
|
| 1165 |
+
"""Emit code for boxing a value of given type.
|
| 1166 |
+
|
| 1167 |
+
Generate a simple assignment if no boxing is needed.
|
| 1168 |
+
|
| 1169 |
+
The source reference count is stolen for the result (no need to decref afterwards).
|
| 1170 |
+
"""
|
| 1171 |
+
# TODO: Always generate a new reference (if a reference type)
|
| 1172 |
+
if declare_dest:
|
| 1173 |
+
declaration = "PyObject *"
|
| 1174 |
+
else:
|
| 1175 |
+
declaration = ""
|
| 1176 |
+
if is_int_rprimitive(typ) or is_short_int_rprimitive(typ):
|
| 1177 |
+
# Steal the existing reference if it exists.
|
| 1178 |
+
self.emit_line(f"{declaration}{dest} = CPyTagged_StealAsObject({src});")
|
| 1179 |
+
elif is_bool_or_bit_rprimitive(typ):
|
| 1180 |
+
# N.B: bool is special cased to produce a borrowed value
|
| 1181 |
+
# after boxing, so we don't need to increment the refcount
|
| 1182 |
+
# when this comes directly from a Box op.
|
| 1183 |
+
self.emit_lines(f"{declaration}{dest} = {src} ? Py_True : Py_False;")
|
| 1184 |
+
if not can_borrow:
|
| 1185 |
+
self.emit_inc_ref(dest, object_rprimitive)
|
| 1186 |
+
elif is_none_rprimitive(typ):
|
| 1187 |
+
# N.B: None is special cased to produce a borrowed value
|
| 1188 |
+
# after boxing, so we don't need to increment the refcount
|
| 1189 |
+
# when this comes directly from a Box op.
|
| 1190 |
+
self.emit_lines(f"{declaration}{dest} = Py_None;")
|
| 1191 |
+
if not can_borrow:
|
| 1192 |
+
self.emit_inc_ref(dest, object_rprimitive)
|
| 1193 |
+
elif is_int32_rprimitive(typ) or is_int16_rprimitive(typ) or is_uint8_rprimitive(typ):
|
| 1194 |
+
self.emit_line(f"{declaration}{dest} = PyLong_FromLong({src});")
|
| 1195 |
+
elif is_int64_rprimitive(typ):
|
| 1196 |
+
self.emit_line(f"{declaration}{dest} = PyLong_FromLongLong({src});")
|
| 1197 |
+
elif is_float_rprimitive(typ):
|
| 1198 |
+
self.emit_line(f"{declaration}{dest} = PyFloat_FromDouble({src});")
|
| 1199 |
+
elif isinstance(typ, RTuple):
|
| 1200 |
+
self.declare_tuple_struct(typ)
|
| 1201 |
+
if not typ.types:
|
| 1202 |
+
self.emit_line(f"{declaration}{dest} = CPyTuple_LoadEmptyTupleConstant();")
|
| 1203 |
+
else:
|
| 1204 |
+
self.emit_line(f"{declaration}{dest} = PyTuple_New({len(typ.types)});")
|
| 1205 |
+
self.emit_line(f"if (unlikely({dest} == NULL))")
|
| 1206 |
+
self.emit_line(" CPyError_OutOfMemory();")
|
| 1207 |
+
|
| 1208 |
+
# TODO: Fail if dest is None
|
| 1209 |
+
for i in range(len(typ.types)):
|
| 1210 |
+
if not typ.is_unboxed:
|
| 1211 |
+
self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {src}.f{i}")
|
| 1212 |
+
else:
|
| 1213 |
+
inner_name = self.temp_name()
|
| 1214 |
+
self.emit_box(f"{src}.f{i}", inner_name, typ.types[i], declare_dest=True)
|
| 1215 |
+
self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {inner_name});")
|
| 1216 |
+
elif isinstance(typ, RVec):
|
| 1217 |
+
specialized_api_name = vec_api_by_item_type.get(typ.item_type)
|
| 1218 |
+
if specialized_api_name is not None:
|
| 1219 |
+
api = specialized_api_name
|
| 1220 |
+
elif typ.depth() > 0:
|
| 1221 |
+
api = "VecNestedApi"
|
| 1222 |
+
else:
|
| 1223 |
+
api = "VecTApi"
|
| 1224 |
+
# Empty vecs of this sort don't describe item type, so it needs to be
|
| 1225 |
+
# passed explicitly.
|
| 1226 |
+
item_type = self.vec_item_type_c(typ)
|
| 1227 |
+
self.emit_line(f"{declaration}{dest} = {api}.box({src}, {item_type});")
|
| 1228 |
+
return
|
| 1229 |
+
self.emit_line(f"{declaration}{dest} = {api}.box({src});")
|
| 1230 |
+
else:
|
| 1231 |
+
assert not typ.is_unboxed
|
| 1232 |
+
# Type is boxed -- trivially just assign.
|
| 1233 |
+
self.emit_line(f"{declaration}{dest} = {src};")
|
| 1234 |
+
|
| 1235 |
+
def emit_error_check(self, value: str, rtype: RType, failure: str) -> None:
|
| 1236 |
+
"""Emit code for checking a native function return value for uncaught exception."""
|
| 1237 |
+
if isinstance(rtype, RTuple):
|
| 1238 |
+
if len(rtype.types) == 0:
|
| 1239 |
+
return # empty tuples can't fail.
|
| 1240 |
+
else:
|
| 1241 |
+
cond = self.tuple_undefined_check_cond(rtype, value, self.c_error_value, "==")
|
| 1242 |
+
self.emit_line(f"if ({cond}) {{")
|
| 1243 |
+
elif isinstance(rtype, RVec):
|
| 1244 |
+
self.emit_line(f"if ({value}.len < 0) {{")
|
| 1245 |
+
elif rtype.error_overlap:
|
| 1246 |
+
# The error value is also valid as a normal value, so we need to also check
|
| 1247 |
+
# for a raised exception.
|
| 1248 |
+
self.emit_line(f"if ({value} == {self.c_error_value(rtype)} && PyErr_Occurred()) {{")
|
| 1249 |
+
else:
|
| 1250 |
+
self.emit_line(f"if ({value} == {self.c_error_value(rtype)}) {{")
|
| 1251 |
+
self.emit_lines(failure, "}")
|
| 1252 |
+
|
| 1253 |
+
def emit_gc_visit(self, target: str, rtype: RType) -> None:
|
| 1254 |
+
"""Emit code for GC visiting a C variable reference.
|
| 1255 |
+
|
| 1256 |
+
Assume that 'target' represents a C expression that refers to a
|
| 1257 |
+
struct member, such as 'self->x'.
|
| 1258 |
+
"""
|
| 1259 |
+
if not rtype.is_refcounted:
|
| 1260 |
+
# Not refcounted -> no pointers -> no GC interaction.
|
| 1261 |
+
return
|
| 1262 |
+
elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int":
|
| 1263 |
+
self.emit_line(f"if (CPyTagged_CheckLong({target})) {{")
|
| 1264 |
+
self.emit_line(f"Py_VISIT(CPyTagged_LongAsObject({target}));")
|
| 1265 |
+
self.emit_line("}")
|
| 1266 |
+
elif isinstance(rtype, RTuple):
|
| 1267 |
+
for i, item_type in enumerate(rtype.types):
|
| 1268 |
+
self.emit_gc_visit(f"{target}.f{i}", item_type)
|
| 1269 |
+
elif isinstance(rtype, RVec):
|
| 1270 |
+
self.emit_line(f"Py_VISIT({target}.buf);")
|
| 1271 |
+
elif self.ctype(rtype) == "PyObject *":
|
| 1272 |
+
# The simplest case.
|
| 1273 |
+
self.emit_line(f"Py_VISIT({target});")
|
| 1274 |
+
else:
|
| 1275 |
+
assert False, "emit_gc_visit() not implemented for %s" % repr(rtype)
|
| 1276 |
+
|
| 1277 |
+
def emit_gc_clear(self, target: str, rtype: RType) -> None:
|
| 1278 |
+
"""Emit code for clearing a C attribute reference for GC.
|
| 1279 |
+
|
| 1280 |
+
Assume that 'target' represents a C expression that refers to a
|
| 1281 |
+
struct member, such as 'self->x'.
|
| 1282 |
+
"""
|
| 1283 |
+
if not rtype.is_refcounted:
|
| 1284 |
+
# Not refcounted -> no pointers -> no GC interaction.
|
| 1285 |
+
return
|
| 1286 |
+
elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int":
|
| 1287 |
+
self.emit_line(f"if (CPyTagged_CheckLong({target})) {{")
|
| 1288 |
+
self.emit_line(f"CPyTagged __tmp = {target};")
|
| 1289 |
+
self.emit_line(f"{target} = {self.c_undefined_value(rtype)};")
|
| 1290 |
+
self.emit_line("Py_XDECREF(CPyTagged_LongAsObject(__tmp));")
|
| 1291 |
+
self.emit_line("}")
|
| 1292 |
+
elif isinstance(rtype, RTuple):
|
| 1293 |
+
for i, item_type in enumerate(rtype.types):
|
| 1294 |
+
self.emit_gc_clear(f"{target}.f{i}", item_type)
|
| 1295 |
+
elif isinstance(rtype, RVec):
|
| 1296 |
+
self.emit_line(f"Py_CLEAR({target}.buf);")
|
| 1297 |
+
elif self.ctype(rtype) == "PyObject *" and self.c_undefined_value(rtype) == "NULL":
|
| 1298 |
+
# The simplest case.
|
| 1299 |
+
self.emit_line(f"Py_CLEAR({target});")
|
| 1300 |
+
else:
|
| 1301 |
+
assert False, "emit_gc_clear() not implemented for %s" % repr(rtype)
|
| 1302 |
+
|
| 1303 |
+
def emit_reuse_clear(self, target: str, rtype: RType) -> None:
|
| 1304 |
+
"""Emit attribute clear before object is added into freelist.
|
| 1305 |
+
|
| 1306 |
+
Assume that 'target' represents a C expression that refers to a
|
| 1307 |
+
struct member, such as 'self->x'.
|
| 1308 |
+
|
| 1309 |
+
Unlike emit_gc_clear(), initialize attribute value to match a freshly
|
| 1310 |
+
allocated object.
|
| 1311 |
+
"""
|
| 1312 |
+
if isinstance(rtype, RTuple):
|
| 1313 |
+
for i, item_type in enumerate(rtype.types):
|
| 1314 |
+
self.emit_reuse_clear(f"{target}.f{i}", item_type)
|
| 1315 |
+
elif not rtype.is_refcounted:
|
| 1316 |
+
self.emit_line(f"{target} = {rtype.c_undefined};")
|
| 1317 |
+
elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int":
|
| 1318 |
+
self.emit_line(f"if (CPyTagged_CheckLong({target})) {{")
|
| 1319 |
+
self.emit_line(f"CPyTagged __tmp = {target};")
|
| 1320 |
+
self.emit_line(f"{target} = {self.c_undefined_value(rtype)};")
|
| 1321 |
+
self.emit_line("Py_XDECREF(CPyTagged_LongAsObject(__tmp));")
|
| 1322 |
+
self.emit_line("} else {")
|
| 1323 |
+
self.emit_line(f"{target} = {self.c_undefined_value(rtype)};")
|
| 1324 |
+
self.emit_line("}")
|
| 1325 |
+
else:
|
| 1326 |
+
self.emit_gc_clear(target, rtype)
|
| 1327 |
+
|
| 1328 |
+
def emit_traceback(
|
| 1329 |
+
self, source_path: str, module_name: str, traceback_entry: tuple[str, int]
|
| 1330 |
+
) -> None:
|
| 1331 |
+
return self._emit_traceback("CPy_AddTraceback", source_path, module_name, traceback_entry)
|
| 1332 |
+
|
| 1333 |
+
def emit_type_error_traceback(
|
| 1334 |
+
self,
|
| 1335 |
+
source_path: str,
|
| 1336 |
+
module_name: str,
|
| 1337 |
+
traceback_entry: tuple[str, int],
|
| 1338 |
+
*,
|
| 1339 |
+
typ: RType,
|
| 1340 |
+
src: str,
|
| 1341 |
+
) -> None:
|
| 1342 |
+
func = "CPy_TypeErrorTraceback"
|
| 1343 |
+
type_str = f'"{self.pretty_name(typ)}"'
|
| 1344 |
+
return self._emit_traceback(
|
| 1345 |
+
func, source_path, module_name, traceback_entry, type_str=type_str, src=src
|
| 1346 |
+
)
|
| 1347 |
+
|
| 1348 |
+
def _emit_traceback(
|
| 1349 |
+
self,
|
| 1350 |
+
func: str,
|
| 1351 |
+
source_path: str,
|
| 1352 |
+
module_name: str,
|
| 1353 |
+
traceback_entry: tuple[str, int],
|
| 1354 |
+
type_str: str = "",
|
| 1355 |
+
src: str = "",
|
| 1356 |
+
) -> None:
|
| 1357 |
+
if self.context.strict_traceback_checks:
|
| 1358 |
+
assert traceback_entry[1] >= 0, "Traceback cannot have a negative line number"
|
| 1359 |
+
globals_static = self.static_name("globals", module_name)
|
| 1360 |
+
line = '%s("%s", "%s", %d, %s' % (
|
| 1361 |
+
func,
|
| 1362 |
+
source_path.replace("\\", "\\\\"),
|
| 1363 |
+
traceback_entry[0],
|
| 1364 |
+
traceback_entry[1],
|
| 1365 |
+
globals_static,
|
| 1366 |
+
)
|
| 1367 |
+
if type_str:
|
| 1368 |
+
assert src
|
| 1369 |
+
line += f", {type_str}, {src}"
|
| 1370 |
+
line += ");"
|
| 1371 |
+
self.emit_line(line)
|
| 1372 |
+
if DEBUG_ERRORS:
|
| 1373 |
+
self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");')
|
| 1374 |
+
|
| 1375 |
+
def emit_unbox_failure_with_overlapping_error_value(
|
| 1376 |
+
self, dest: str, typ: RType, failure: str
|
| 1377 |
+
) -> None:
|
| 1378 |
+
self.emit_line(f"if ({dest} == {self.c_error_value(typ)} && PyErr_Occurred()) {{")
|
| 1379 |
+
self.emit_line(failure)
|
| 1380 |
+
self.emit_line("}")
|
| 1381 |
+
|
| 1382 |
+
def emit_cpyfunction_instance(
|
| 1383 |
+
self, fn: FuncIR, name: str, filepath: str, error_stmt: str
|
| 1384 |
+
) -> str:
|
| 1385 |
+
module = self.static_name(fn.decl.module_name, None, prefix=MODULE_PREFIX)
|
| 1386 |
+
cname = f"{PREFIX}{fn.cname(self.names)}"
|
| 1387 |
+
wrapper_name = f"{cname}_wrapper"
|
| 1388 |
+
cfunc = f"(PyCFunction){cname}"
|
| 1389 |
+
func_flags = "METH_FASTCALL | METH_KEYWORDS"
|
| 1390 |
+
doc = f"PyDoc_STR({native_function_doc_initializer(fn)})"
|
| 1391 |
+
has_self_arg = "true" if fn.class_name and fn.decl.kind != FUNC_STATICMETHOD else "false"
|
| 1392 |
+
|
| 1393 |
+
code_flags = "CO_COROUTINE"
|
| 1394 |
+
self.emit_line(
|
| 1395 |
+
f'PyObject* {wrapper_name} = CPyFunction_New({module}, "{filepath}", "{name}", {cfunc}, {func_flags}, {doc}, {fn.line}, {code_flags}, {has_self_arg});'
|
| 1396 |
+
)
|
| 1397 |
+
self.emit_line(f"if (unlikely(!{wrapper_name}))")
|
| 1398 |
+
self.emit_line(error_stmt)
|
| 1399 |
+
return wrapper_name
|
| 1400 |
+
|
| 1401 |
+
|
| 1402 |
+
def c_array_initializer(components: list[str], *, indented: bool = False) -> str:
|
| 1403 |
+
"""Construct an initializer for a C array variable.
|
| 1404 |
+
|
| 1405 |
+
Components are C expressions valid in an initializer.
|
| 1406 |
+
|
| 1407 |
+
For example, if components are ["1", "2"], the result
|
| 1408 |
+
would be "{1, 2}", which can be used like this:
|
| 1409 |
+
|
| 1410 |
+
int a[] = {1, 2};
|
| 1411 |
+
|
| 1412 |
+
If the result is long, split it into multiple lines.
|
| 1413 |
+
"""
|
| 1414 |
+
indent = " " * 4 if indented else ""
|
| 1415 |
+
res = []
|
| 1416 |
+
current: list[str] = []
|
| 1417 |
+
cur_len = 0
|
| 1418 |
+
for c in components:
|
| 1419 |
+
if not current or cur_len + 2 + len(indent) + len(c) < 70:
|
| 1420 |
+
current.append(c)
|
| 1421 |
+
cur_len += len(c) + 2
|
| 1422 |
+
else:
|
| 1423 |
+
res.append(indent + ", ".join(current))
|
| 1424 |
+
current = [c]
|
| 1425 |
+
cur_len = len(c)
|
| 1426 |
+
if not res:
|
| 1427 |
+
# Result fits on a single line
|
| 1428 |
+
return "{%s}" % ", ".join(current)
|
| 1429 |
+
# Multi-line result
|
| 1430 |
+
res.append(indent + ", ".join(current))
|
| 1431 |
+
return "{\n " + ",\n ".join(res) + "\n" + indent + "}"
|
| 1432 |
+
|
| 1433 |
+
|
| 1434 |
+
def native_function_doc_initializer(func: FuncIR) -> str:
|
| 1435 |
+
text_sig = get_text_signature(func)
|
| 1436 |
+
if text_sig is None:
|
| 1437 |
+
return "NULL"
|
| 1438 |
+
docstring = f"{text_sig}\n--\n\n"
|
| 1439 |
+
return c_string_initializer(docstring.encode("ascii", errors="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mapping
|
| 6 |
+
|
| 7 |
+
from mypy.nodes import ARG_STAR, ARG_STAR2
|
| 8 |
+
from mypyc.codegen.cstring import c_string_initializer
|
| 9 |
+
from mypyc.codegen.emit import (
|
| 10 |
+
Emitter,
|
| 11 |
+
HeaderDeclaration,
|
| 12 |
+
ReturnHandler,
|
| 13 |
+
native_function_doc_initializer,
|
| 14 |
+
)
|
| 15 |
+
from mypyc.codegen.emitfunc import native_function_header
|
| 16 |
+
from mypyc.codegen.emitwrapper import (
|
| 17 |
+
generate_bin_op_wrapper,
|
| 18 |
+
generate_bool_wrapper,
|
| 19 |
+
generate_contains_wrapper,
|
| 20 |
+
generate_dunder_wrapper,
|
| 21 |
+
generate_get_wrapper,
|
| 22 |
+
generate_hash_wrapper,
|
| 23 |
+
generate_ipow_wrapper,
|
| 24 |
+
generate_len_wrapper,
|
| 25 |
+
generate_richcompare_wrapper,
|
| 26 |
+
generate_set_del_item_wrapper,
|
| 27 |
+
)
|
| 28 |
+
from mypyc.common import (
|
| 29 |
+
BITMAP_BITS,
|
| 30 |
+
BITMAP_TYPE,
|
| 31 |
+
CPYFUNCTION_NAME,
|
| 32 |
+
NATIVE_PREFIX,
|
| 33 |
+
PREFIX,
|
| 34 |
+
REG_PREFIX,
|
| 35 |
+
short_id_from_name,
|
| 36 |
+
)
|
| 37 |
+
from mypyc.ir.class_ir import ClassIR, VTableEntries
|
| 38 |
+
from mypyc.ir.func_ir import (
|
| 39 |
+
FUNC_CLASSMETHOD,
|
| 40 |
+
FUNC_STATICMETHOD,
|
| 41 |
+
FuncDecl,
|
| 42 |
+
FuncIR,
|
| 43 |
+
get_text_signature,
|
| 44 |
+
)
|
| 45 |
+
from mypyc.ir.rtypes import RTuple, RType, object_rprimitive
|
| 46 |
+
from mypyc.namegen import NameGenerator
|
| 47 |
+
from mypyc.sametype import is_same_type
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def native_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 51 |
+
return f"{NATIVE_PREFIX}{fn.cname(emitter.names)}"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def dunder_attr_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 55 |
+
wrapper_fn = cl.get_method(fn.name + "__wrapper")
|
| 56 |
+
assert wrapper_fn
|
| 57 |
+
return f"{NATIVE_PREFIX}{wrapper_fn.cname(emitter.names)}"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# We maintain a table from dunder function names to struct slots they
|
| 61 |
+
# correspond to and functions that generate a wrapper (if necessary)
|
| 62 |
+
# and return the function name to stick in the slot.
|
| 63 |
+
# TODO: Add remaining dunder methods
|
| 64 |
+
SlotGenerator = Callable[[ClassIR, FuncIR, Emitter], str]
|
| 65 |
+
SlotTable = Mapping[str, tuple[str, SlotGenerator]]
|
| 66 |
+
|
| 67 |
+
SLOT_DEFS: SlotTable = {
|
| 68 |
+
"__init__": ("tp_init", lambda c, t, e: generate_init_for_class(c, t, e)),
|
| 69 |
+
"__call__": ("tp_call", lambda c, t, e: generate_call_wrapper(c, t, e)),
|
| 70 |
+
"__str__": ("tp_str", native_slot),
|
| 71 |
+
"__repr__": ("tp_repr", native_slot),
|
| 72 |
+
"__next__": ("tp_iternext", native_slot),
|
| 73 |
+
"__iter__": ("tp_iter", native_slot),
|
| 74 |
+
"__hash__": ("tp_hash", generate_hash_wrapper),
|
| 75 |
+
"__get__": ("tp_descr_get", generate_get_wrapper),
|
| 76 |
+
"__getattr__": ("tp_getattro", dunder_attr_slot),
|
| 77 |
+
"__setattr__": ("tp_setattro", dunder_attr_slot),
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
AS_MAPPING_SLOT_DEFS: SlotTable = {
|
| 81 |
+
"__getitem__": ("mp_subscript", generate_dunder_wrapper),
|
| 82 |
+
"__setitem__": ("mp_ass_subscript", generate_set_del_item_wrapper),
|
| 83 |
+
"__delitem__": ("mp_ass_subscript", generate_set_del_item_wrapper),
|
| 84 |
+
"__len__": ("mp_length", generate_len_wrapper),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
AS_SEQUENCE_SLOT_DEFS: SlotTable = {"__contains__": ("sq_contains", generate_contains_wrapper)}
|
| 88 |
+
|
| 89 |
+
AS_NUMBER_SLOT_DEFS: SlotTable = {
|
| 90 |
+
# Unary operations.
|
| 91 |
+
"__bool__": ("nb_bool", generate_bool_wrapper),
|
| 92 |
+
"__int__": ("nb_int", generate_dunder_wrapper),
|
| 93 |
+
"__float__": ("nb_float", generate_dunder_wrapper),
|
| 94 |
+
"__neg__": ("nb_negative", generate_dunder_wrapper),
|
| 95 |
+
"__pos__": ("nb_positive", generate_dunder_wrapper),
|
| 96 |
+
"__abs__": ("nb_absolute", generate_dunder_wrapper),
|
| 97 |
+
"__invert__": ("nb_invert", generate_dunder_wrapper),
|
| 98 |
+
# Binary operations.
|
| 99 |
+
"__add__": ("nb_add", generate_bin_op_wrapper),
|
| 100 |
+
"__radd__": ("nb_add", generate_bin_op_wrapper),
|
| 101 |
+
"__sub__": ("nb_subtract", generate_bin_op_wrapper),
|
| 102 |
+
"__rsub__": ("nb_subtract", generate_bin_op_wrapper),
|
| 103 |
+
"__mul__": ("nb_multiply", generate_bin_op_wrapper),
|
| 104 |
+
"__rmul__": ("nb_multiply", generate_bin_op_wrapper),
|
| 105 |
+
"__mod__": ("nb_remainder", generate_bin_op_wrapper),
|
| 106 |
+
"__rmod__": ("nb_remainder", generate_bin_op_wrapper),
|
| 107 |
+
"__truediv__": ("nb_true_divide", generate_bin_op_wrapper),
|
| 108 |
+
"__rtruediv__": ("nb_true_divide", generate_bin_op_wrapper),
|
| 109 |
+
"__floordiv__": ("nb_floor_divide", generate_bin_op_wrapper),
|
| 110 |
+
"__rfloordiv__": ("nb_floor_divide", generate_bin_op_wrapper),
|
| 111 |
+
"__divmod__": ("nb_divmod", generate_bin_op_wrapper),
|
| 112 |
+
"__rdivmod__": ("nb_divmod", generate_bin_op_wrapper),
|
| 113 |
+
"__lshift__": ("nb_lshift", generate_bin_op_wrapper),
|
| 114 |
+
"__rlshift__": ("nb_lshift", generate_bin_op_wrapper),
|
| 115 |
+
"__rshift__": ("nb_rshift", generate_bin_op_wrapper),
|
| 116 |
+
"__rrshift__": ("nb_rshift", generate_bin_op_wrapper),
|
| 117 |
+
"__and__": ("nb_and", generate_bin_op_wrapper),
|
| 118 |
+
"__rand__": ("nb_and", generate_bin_op_wrapper),
|
| 119 |
+
"__or__": ("nb_or", generate_bin_op_wrapper),
|
| 120 |
+
"__ror__": ("nb_or", generate_bin_op_wrapper),
|
| 121 |
+
"__xor__": ("nb_xor", generate_bin_op_wrapper),
|
| 122 |
+
"__rxor__": ("nb_xor", generate_bin_op_wrapper),
|
| 123 |
+
"__matmul__": ("nb_matrix_multiply", generate_bin_op_wrapper),
|
| 124 |
+
"__rmatmul__": ("nb_matrix_multiply", generate_bin_op_wrapper),
|
| 125 |
+
# In-place binary operations.
|
| 126 |
+
"__iadd__": ("nb_inplace_add", generate_dunder_wrapper),
|
| 127 |
+
"__isub__": ("nb_inplace_subtract", generate_dunder_wrapper),
|
| 128 |
+
"__imul__": ("nb_inplace_multiply", generate_dunder_wrapper),
|
| 129 |
+
"__imod__": ("nb_inplace_remainder", generate_dunder_wrapper),
|
| 130 |
+
"__itruediv__": ("nb_inplace_true_divide", generate_dunder_wrapper),
|
| 131 |
+
"__ifloordiv__": ("nb_inplace_floor_divide", generate_dunder_wrapper),
|
| 132 |
+
"__ilshift__": ("nb_inplace_lshift", generate_dunder_wrapper),
|
| 133 |
+
"__irshift__": ("nb_inplace_rshift", generate_dunder_wrapper),
|
| 134 |
+
"__iand__": ("nb_inplace_and", generate_dunder_wrapper),
|
| 135 |
+
"__ior__": ("nb_inplace_or", generate_dunder_wrapper),
|
| 136 |
+
"__ixor__": ("nb_inplace_xor", generate_dunder_wrapper),
|
| 137 |
+
"__imatmul__": ("nb_inplace_matrix_multiply", generate_dunder_wrapper),
|
| 138 |
+
# Ternary operations. (yes, really)
|
| 139 |
+
# These are special cased in generate_bin_op_wrapper().
|
| 140 |
+
"__pow__": ("nb_power", generate_bin_op_wrapper),
|
| 141 |
+
"__rpow__": ("nb_power", generate_bin_op_wrapper),
|
| 142 |
+
"__ipow__": ("nb_inplace_power", generate_ipow_wrapper),
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
AS_ASYNC_SLOT_DEFS: SlotTable = {
|
| 146 |
+
"__await__": ("am_await", native_slot),
|
| 147 |
+
"__aiter__": ("am_aiter", native_slot),
|
| 148 |
+
"__anext__": ("am_anext", native_slot),
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
SIDE_TABLES = [
|
| 152 |
+
("as_mapping", "PyMappingMethods", AS_MAPPING_SLOT_DEFS),
|
| 153 |
+
("as_sequence", "PySequenceMethods", AS_SEQUENCE_SLOT_DEFS),
|
| 154 |
+
("as_number", "PyNumberMethods", AS_NUMBER_SLOT_DEFS),
|
| 155 |
+
("as_async", "PyAsyncMethods", AS_ASYNC_SLOT_DEFS),
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
# Slots that need to always be filled in because they don't get
|
| 159 |
+
# inherited right.
|
| 160 |
+
ALWAYS_FILL = {"__hash__"}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def generate_call_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 164 |
+
return "PyVectorcall_Call"
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def slot_key(attr: str) -> str:
|
| 168 |
+
"""Map dunder method name to sort key.
|
| 169 |
+
|
| 170 |
+
Sort reverse operator methods and __delitem__ after others ('x' > '_').
|
| 171 |
+
"""
|
| 172 |
+
if (attr.startswith("__r") and attr != "__rshift__") or attr == "__delitem__":
|
| 173 |
+
return "x" + attr
|
| 174 |
+
return attr
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def generate_slots(cl: ClassIR, table: SlotTable, emitter: Emitter) -> dict[str, str]:
|
| 178 |
+
fields: dict[str, str] = {}
|
| 179 |
+
generated: dict[str, str] = {}
|
| 180 |
+
# Sort for determinism on Python 3.5
|
| 181 |
+
for name, (slot, generator) in sorted(table.items(), key=lambda x: slot_key(x[0])):
|
| 182 |
+
method_cls = cl.get_method_and_class(name)
|
| 183 |
+
if method_cls and (method_cls[1] == cl or name in ALWAYS_FILL):
|
| 184 |
+
if slot in generated:
|
| 185 |
+
# Reuse previously generated wrapper.
|
| 186 |
+
fields[slot] = generated[slot]
|
| 187 |
+
else:
|
| 188 |
+
# Generate new wrapper.
|
| 189 |
+
name = generator(cl, method_cls[0], emitter)
|
| 190 |
+
fields[slot] = name
|
| 191 |
+
generated[slot] = name
|
| 192 |
+
|
| 193 |
+
return fields
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def generate_class_type_decl(
|
| 197 |
+
cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter
|
| 198 |
+
) -> None:
|
| 199 |
+
context = c_emitter.context
|
| 200 |
+
name = emitter.type_struct_name(cl)
|
| 201 |
+
context.declarations[name] = HeaderDeclaration(
|
| 202 |
+
f"PyTypeObject *{emitter.type_struct_name(cl)};", needs_export=True
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# If this is a non-extension class, all we want is the type object decl.
|
| 206 |
+
if not cl.is_ext_class:
|
| 207 |
+
return
|
| 208 |
+
|
| 209 |
+
generate_object_struct(cl, external_emitter)
|
| 210 |
+
generate_full = not cl.is_trait and not cl.builtin_base
|
| 211 |
+
if generate_full:
|
| 212 |
+
context.declarations[emitter.native_function_name(cl.ctor)] = HeaderDeclaration(
|
| 213 |
+
f"{native_function_header(cl.ctor, emitter)};", needs_export=True
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def generate_class_reuse(
|
| 218 |
+
cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter
|
| 219 |
+
) -> None:
|
| 220 |
+
"""Generate a definition of a single-object per-class free "list".
|
| 221 |
+
|
| 222 |
+
This speeds up object allocation and freeing when there are many short-lived
|
| 223 |
+
objects.
|
| 224 |
+
|
| 225 |
+
TODO: Generalize to support a free list with up to N objects.
|
| 226 |
+
"""
|
| 227 |
+
assert cl.reuse_freed_instance
|
| 228 |
+
context = c_emitter.context
|
| 229 |
+
name = cl.name_prefix(c_emitter.names) + "_free_instance"
|
| 230 |
+
struct_name = cl.struct_name(c_emitter.names)
|
| 231 |
+
context.declarations[name] = HeaderDeclaration(
|
| 232 |
+
f"CPyThreadLocal {struct_name} *{name};", needs_export=True
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def generate_class(cl: ClassIR, module: str, emitter: Emitter) -> None:
|
| 237 |
+
"""Generate C code for a class.
|
| 238 |
+
|
| 239 |
+
This is the main entry point to the module.
|
| 240 |
+
"""
|
| 241 |
+
name = cl.name
|
| 242 |
+
name_prefix = cl.name_prefix(emitter.names)
|
| 243 |
+
|
| 244 |
+
setup_name = emitter.native_function_name(cl.setup)
|
| 245 |
+
new_name = f"{name_prefix}_new"
|
| 246 |
+
finalize_name = f"{name_prefix}_finalize"
|
| 247 |
+
members_name = f"{name_prefix}_members"
|
| 248 |
+
getseters_name = f"{name_prefix}_getseters"
|
| 249 |
+
vtable_name = f"{name_prefix}_vtable"
|
| 250 |
+
traverse_name = f"{name_prefix}_traverse"
|
| 251 |
+
clear_name = f"{name_prefix}_clear"
|
| 252 |
+
dealloc_name = f"{name_prefix}_dealloc"
|
| 253 |
+
methods_name = f"{name_prefix}_methods"
|
| 254 |
+
vtable_setup_name = f"{name_prefix}_trait_vtable_setup"
|
| 255 |
+
coroutine_setup_name = f"{name_prefix}_coroutine_setup"
|
| 256 |
+
|
| 257 |
+
fields: dict[str, str] = {"tp_name": f'"{name}"'}
|
| 258 |
+
|
| 259 |
+
generate_full = not cl.is_trait and not cl.builtin_base
|
| 260 |
+
needs_getseters = cl.needs_getseters or not cl.is_generated or cl.has_dict
|
| 261 |
+
|
| 262 |
+
if not cl.builtin_base:
|
| 263 |
+
fields["tp_new"] = new_name
|
| 264 |
+
|
| 265 |
+
if generate_full:
|
| 266 |
+
fields["tp_dealloc"] = f"(destructor){name_prefix}_dealloc"
|
| 267 |
+
if not cl.is_acyclic:
|
| 268 |
+
fields["tp_traverse"] = f"(traverseproc){name_prefix}_traverse"
|
| 269 |
+
fields["tp_clear"] = f"(inquiry){name_prefix}_clear"
|
| 270 |
+
# Populate .tp_finalize and generate a finalize method only if __del__ is defined for this class.
|
| 271 |
+
del_method = next((e.method for e in cl.vtable_entries if e.name == "__del__"), None)
|
| 272 |
+
if del_method:
|
| 273 |
+
fields["tp_finalize"] = f"(destructor){finalize_name}"
|
| 274 |
+
if needs_getseters:
|
| 275 |
+
fields["tp_getset"] = getseters_name
|
| 276 |
+
fields["tp_methods"] = methods_name
|
| 277 |
+
|
| 278 |
+
def emit_line() -> None:
|
| 279 |
+
emitter.emit_line()
|
| 280 |
+
|
| 281 |
+
emit_line()
|
| 282 |
+
|
| 283 |
+
# If the class has a method to initialize default attribute
|
| 284 |
+
# values, we need to call it during initialization.
|
| 285 |
+
defaults_fn = cl.get_method("__mypyc_defaults_setup")
|
| 286 |
+
|
| 287 |
+
# If there is a __init__ method, we'll use it in the native constructor.
|
| 288 |
+
init_fn = cl.get_method("__init__")
|
| 289 |
+
|
| 290 |
+
# Fill out slots in the type object from dunder methods.
|
| 291 |
+
fields.update(generate_slots(cl, SLOT_DEFS, emitter))
|
| 292 |
+
|
| 293 |
+
# Fill out dunder methods that live in tables hanging off the side.
|
| 294 |
+
for table_name, type, slot_defs in SIDE_TABLES:
|
| 295 |
+
slots = generate_slots(cl, slot_defs, emitter)
|
| 296 |
+
if slots:
|
| 297 |
+
table_struct_name = generate_side_table_for_class(cl, table_name, type, slots, emitter)
|
| 298 |
+
fields[f"tp_{table_name}"] = f"&{table_struct_name}"
|
| 299 |
+
|
| 300 |
+
richcompare_name = generate_richcompare_wrapper(cl, emitter)
|
| 301 |
+
if richcompare_name:
|
| 302 |
+
fields["tp_richcompare"] = richcompare_name
|
| 303 |
+
|
| 304 |
+
# If the class inherits from python, make space for a __dict__
|
| 305 |
+
struct_name = cl.struct_name(emitter.names)
|
| 306 |
+
if cl.builtin_base:
|
| 307 |
+
base_size = f"sizeof({cl.builtin_base})"
|
| 308 |
+
elif cl.is_trait:
|
| 309 |
+
base_size = "sizeof(PyObject)"
|
| 310 |
+
else:
|
| 311 |
+
base_size = f"sizeof({struct_name})"
|
| 312 |
+
# Since our types aren't allocated using type() we need to
|
| 313 |
+
# populate these fields ourselves if we want them to have correct
|
| 314 |
+
# values. PyType_Ready will inherit the offsets from tp_base but
|
| 315 |
+
# that isn't what we want.
|
| 316 |
+
|
| 317 |
+
# XXX: there is no reason for the __weakref__ stuff to be mixed up with __dict__
|
| 318 |
+
if cl.has_dict and not has_managed_dict(cl, emitter):
|
| 319 |
+
# __dict__ lives right after the struct and __weakref__ lives right after that
|
| 320 |
+
# TODO: They should get members in the struct instead of doing this nonsense.
|
| 321 |
+
weak_offset = f"{base_size} + sizeof(PyObject *)"
|
| 322 |
+
emitter.emit_lines(
|
| 323 |
+
f"PyMemberDef {members_name}[] = {{",
|
| 324 |
+
f'{{"__dict__", T_OBJECT_EX, {base_size}, 0, NULL}},',
|
| 325 |
+
f'{{"__weakref__", T_OBJECT_EX, {weak_offset}, 0, NULL}},',
|
| 326 |
+
"{0}",
|
| 327 |
+
"};",
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
fields["tp_members"] = members_name
|
| 331 |
+
fields["tp_basicsize"] = f"{base_size} + 2*sizeof(PyObject *)"
|
| 332 |
+
if emitter.capi_version < (3, 12):
|
| 333 |
+
fields["tp_dictoffset"] = base_size
|
| 334 |
+
fields["tp_weaklistoffset"] = weak_offset
|
| 335 |
+
else:
|
| 336 |
+
fields["tp_basicsize"] = base_size
|
| 337 |
+
|
| 338 |
+
if generate_full:
|
| 339 |
+
assert cl.setup is not None
|
| 340 |
+
emitter.emit_line(native_function_header(cl.setup, emitter) + ";")
|
| 341 |
+
assert cl.ctor is not None
|
| 342 |
+
emitter.emit_line(native_function_header(cl.ctor, emitter) + ";")
|
| 343 |
+
|
| 344 |
+
emit_line()
|
| 345 |
+
init_fn = cl.get_method("__init__")
|
| 346 |
+
generate_new_for_class(cl, new_name, vtable_name, setup_name, init_fn, emitter)
|
| 347 |
+
emit_line()
|
| 348 |
+
if not cl.is_acyclic:
|
| 349 |
+
generate_traverse_for_class(cl, traverse_name, emitter)
|
| 350 |
+
emit_line()
|
| 351 |
+
generate_clear_for_class(cl, clear_name, emitter)
|
| 352 |
+
emit_line()
|
| 353 |
+
generate_dealloc_for_class(cl, dealloc_name, clear_name, bool(del_method), emitter)
|
| 354 |
+
emit_line()
|
| 355 |
+
|
| 356 |
+
if cl.allow_interpreted_subclasses:
|
| 357 |
+
shadow_vtable_name: str | None = generate_vtables(
|
| 358 |
+
cl, vtable_setup_name + "_shadow", vtable_name + "_shadow", emitter, shadow=True
|
| 359 |
+
)
|
| 360 |
+
emit_line()
|
| 361 |
+
else:
|
| 362 |
+
shadow_vtable_name = None
|
| 363 |
+
vtable_name = generate_vtables(cl, vtable_setup_name, vtable_name, emitter, shadow=False)
|
| 364 |
+
emit_line()
|
| 365 |
+
generate_coroutine_setup(cl, coroutine_setup_name, module, emitter)
|
| 366 |
+
emit_line()
|
| 367 |
+
if del_method:
|
| 368 |
+
generate_finalize_for_class(del_method, finalize_name, emitter)
|
| 369 |
+
emit_line()
|
| 370 |
+
if needs_getseters:
|
| 371 |
+
generate_getseter_declarations(cl, emitter)
|
| 372 |
+
emit_line()
|
| 373 |
+
generate_getseters_table(cl, getseters_name, emitter)
|
| 374 |
+
emit_line()
|
| 375 |
+
|
| 376 |
+
if cl.is_trait:
|
| 377 |
+
generate_new_for_trait(cl, new_name, emitter)
|
| 378 |
+
|
| 379 |
+
generate_methods_table(cl, methods_name, setup_name if generate_full else None, emitter)
|
| 380 |
+
emit_line()
|
| 381 |
+
|
| 382 |
+
flags = ["Py_TPFLAGS_DEFAULT", "Py_TPFLAGS_HEAPTYPE", "Py_TPFLAGS_BASETYPE"]
|
| 383 |
+
if generate_full and not cl.is_acyclic:
|
| 384 |
+
flags.append("Py_TPFLAGS_HAVE_GC")
|
| 385 |
+
if cl.has_method("__call__"):
|
| 386 |
+
fields["tp_vectorcall_offset"] = "offsetof({}, vectorcall)".format(
|
| 387 |
+
cl.struct_name(emitter.names)
|
| 388 |
+
)
|
| 389 |
+
flags.append("_Py_TPFLAGS_HAVE_VECTORCALL")
|
| 390 |
+
if not fields.get("tp_vectorcall"):
|
| 391 |
+
# This is just a placeholder to please CPython. It will be
|
| 392 |
+
# overridden during setup.
|
| 393 |
+
fields["tp_call"] = "PyVectorcall_Call"
|
| 394 |
+
if has_managed_dict(cl, emitter):
|
| 395 |
+
flags.append("Py_TPFLAGS_MANAGED_DICT")
|
| 396 |
+
fields["tp_flags"] = " | ".join(flags)
|
| 397 |
+
|
| 398 |
+
fields["tp_doc"] = f"PyDoc_STR({native_class_doc_initializer(cl)})"
|
| 399 |
+
|
| 400 |
+
emitter.emit_line(f"static PyTypeObject {emitter.type_struct_name(cl)}_template_ = {{")
|
| 401 |
+
emitter.emit_line("PyVarObject_HEAD_INIT(NULL, 0)")
|
| 402 |
+
for field, value in fields.items():
|
| 403 |
+
emitter.emit_line(f".{field} = {value},")
|
| 404 |
+
emitter.emit_line("};")
|
| 405 |
+
emitter.emit_line(
|
| 406 |
+
"static PyTypeObject *{t}_template = &{t}_template_;".format(
|
| 407 |
+
t=emitter.type_struct_name(cl)
|
| 408 |
+
)
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
if cl.coroutine_name:
|
| 412 |
+
cpyfunction = emitter.static_name(cl.name + "_cpyfunction", module)
|
| 413 |
+
emitter.emit_line(f"static PyObject *{cpyfunction} = NULL;")
|
| 414 |
+
|
| 415 |
+
emitter.emit_line()
|
| 416 |
+
if generate_full:
|
| 417 |
+
generate_setup_for_class(cl, defaults_fn, vtable_name, shadow_vtable_name, emitter)
|
| 418 |
+
emitter.emit_line()
|
| 419 |
+
generate_constructor_for_class(cl, cl.ctor, init_fn, setup_name, vtable_name, emitter)
|
| 420 |
+
emitter.emit_line()
|
| 421 |
+
if needs_getseters:
|
| 422 |
+
generate_getseters(cl, emitter)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def getter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str:
|
| 426 |
+
return names.private_name(cl.module_name, f"{cl.name}_get_{attribute}")
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def setter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str:
|
| 430 |
+
return names.private_name(cl.module_name, f"{cl.name}_set_{attribute}")
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def generate_object_struct(cl: ClassIR, emitter: Emitter) -> None:
|
| 434 |
+
seen_attrs: set[str] = set()
|
| 435 |
+
lines: list[str] = []
|
| 436 |
+
lines += ["typedef struct {", "PyObject_HEAD", "CPyVTableItem *vtable;"]
|
| 437 |
+
if cl.has_method("__call__"):
|
| 438 |
+
lines.append("vectorcallfunc vectorcall;")
|
| 439 |
+
bitmap_attrs = []
|
| 440 |
+
for base in reversed(cl.base_mro):
|
| 441 |
+
if not base.is_trait:
|
| 442 |
+
if base.bitmap_attrs:
|
| 443 |
+
# Do we need another attribute bitmap field?
|
| 444 |
+
if emitter.bitmap_field(len(base.bitmap_attrs) - 1) not in bitmap_attrs:
|
| 445 |
+
for i in range(0, len(base.bitmap_attrs), BITMAP_BITS):
|
| 446 |
+
attr = emitter.bitmap_field(i)
|
| 447 |
+
if attr not in bitmap_attrs:
|
| 448 |
+
lines.append(f"{BITMAP_TYPE} {attr};")
|
| 449 |
+
bitmap_attrs.append(attr)
|
| 450 |
+
for attr, rtype in base.attributes.items():
|
| 451 |
+
# Generated class may redefine certain attributes with different
|
| 452 |
+
# types in subclasses (this would be unsafe for user-defined classes).
|
| 453 |
+
if attr not in seen_attrs:
|
| 454 |
+
lines.append(f"{emitter.ctype_spaced(rtype)}{emitter.attr(attr)};")
|
| 455 |
+
seen_attrs.add(attr)
|
| 456 |
+
|
| 457 |
+
if isinstance(rtype, RTuple):
|
| 458 |
+
emitter.declare_tuple_struct(rtype)
|
| 459 |
+
|
| 460 |
+
lines.append(f"}} {cl.struct_name(emitter.names)};")
|
| 461 |
+
lines.append("")
|
| 462 |
+
emitter.context.declarations[cl.struct_name(emitter.names)] = HeaderDeclaration(
|
| 463 |
+
lines, is_type=True
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def generate_vtables(
|
| 468 |
+
base: ClassIR, vtable_setup_name: str, vtable_name: str, emitter: Emitter, shadow: bool
|
| 469 |
+
) -> str:
|
| 470 |
+
"""Emit the vtables and vtable setup functions for a class.
|
| 471 |
+
|
| 472 |
+
This includes both the primary vtable and any trait implementation vtables.
|
| 473 |
+
The trait vtables go before the main vtable, and have the following layout:
|
| 474 |
+
{
|
| 475 |
+
CPyType_T1, // pointer to type object
|
| 476 |
+
C_T1_trait_vtable, // pointer to array of method pointers
|
| 477 |
+
C_T1_offset_table, // pointer to array of attribute offsets
|
| 478 |
+
CPyType_T2,
|
| 479 |
+
C_T2_trait_vtable,
|
| 480 |
+
C_T2_offset_table,
|
| 481 |
+
...
|
| 482 |
+
}
|
| 483 |
+
The method implementations are calculated at the end of IR pass, attribute
|
| 484 |
+
offsets are {offsetof(native__C, _x1), offsetof(native__C, _y1), ...}.
|
| 485 |
+
|
| 486 |
+
To account for both dynamic loading and dynamic class creation,
|
| 487 |
+
vtables are populated dynamically at class creation time, so we
|
| 488 |
+
emit empty array definitions to store the vtables and a function to
|
| 489 |
+
populate them.
|
| 490 |
+
|
| 491 |
+
If shadow is True, generate "shadow vtables" that point to the
|
| 492 |
+
shadow glue methods (which should dispatch via the Python C-API).
|
| 493 |
+
|
| 494 |
+
Returns the expression to use to refer to the vtable, which might be
|
| 495 |
+
different than the name, if there are trait vtables.
|
| 496 |
+
"""
|
| 497 |
+
|
| 498 |
+
def trait_vtable_name(trait: ClassIR) -> str:
|
| 499 |
+
return "{}_{}_trait_vtable{}".format(
|
| 500 |
+
base.name_prefix(emitter.names),
|
| 501 |
+
trait.name_prefix(emitter.names),
|
| 502 |
+
"_shadow" if shadow else "",
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
def trait_offset_table_name(trait: ClassIR) -> str:
|
| 506 |
+
return "{}_{}_offset_table".format(
|
| 507 |
+
base.name_prefix(emitter.names), trait.name_prefix(emitter.names)
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
# Emit array definitions with enough space for all the entries
|
| 511 |
+
emitter.emit_line(
|
| 512 |
+
"static CPyVTableItem {}[{}];".format(
|
| 513 |
+
vtable_name, max(1, len(base.vtable_entries) + 3 * len(base.trait_vtables))
|
| 514 |
+
)
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
for trait, vtable in base.trait_vtables.items():
|
| 518 |
+
# Trait methods entry (vtable index -> method implementation).
|
| 519 |
+
emitter.emit_line(
|
| 520 |
+
f"static CPyVTableItem {trait_vtable_name(trait)}[{max(1, len(vtable))}];"
|
| 521 |
+
)
|
| 522 |
+
# Trait attributes entry (attribute number in trait -> offset in actual struct).
|
| 523 |
+
emitter.emit_line(
|
| 524 |
+
"static size_t {}[{}];".format(
|
| 525 |
+
trait_offset_table_name(trait), max(1, len(trait.attributes))
|
| 526 |
+
)
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
# Emit vtable setup function
|
| 530 |
+
emitter.emit_line("static bool")
|
| 531 |
+
emitter.emit_line(f"{NATIVE_PREFIX}{vtable_setup_name}(void)")
|
| 532 |
+
emitter.emit_line("{")
|
| 533 |
+
|
| 534 |
+
if base.allow_interpreted_subclasses and not shadow:
|
| 535 |
+
emitter.emit_line(f"{NATIVE_PREFIX}{vtable_setup_name}_shadow();")
|
| 536 |
+
|
| 537 |
+
subtables = []
|
| 538 |
+
for trait, vtable in base.trait_vtables.items():
|
| 539 |
+
name = trait_vtable_name(trait)
|
| 540 |
+
offset_name = trait_offset_table_name(trait)
|
| 541 |
+
generate_vtable(vtable, name, emitter, [], shadow)
|
| 542 |
+
generate_offset_table(offset_name, emitter, trait, base)
|
| 543 |
+
subtables.append((trait, name, offset_name))
|
| 544 |
+
|
| 545 |
+
generate_vtable(base.vtable_entries, vtable_name, emitter, subtables, shadow)
|
| 546 |
+
|
| 547 |
+
emitter.emit_line("return 1;")
|
| 548 |
+
emitter.emit_line("}")
|
| 549 |
+
|
| 550 |
+
return vtable_name if not subtables else f"{vtable_name} + {len(subtables) * 3}"
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def generate_offset_table(
|
| 554 |
+
trait_offset_table_name: str, emitter: Emitter, trait: ClassIR, cl: ClassIR
|
| 555 |
+
) -> None:
|
| 556 |
+
"""Generate attribute offset row of a trait vtable."""
|
| 557 |
+
emitter.emit_line(f"size_t {trait_offset_table_name}_scratch[] = {{")
|
| 558 |
+
for attr in trait.attributes:
|
| 559 |
+
emitter.emit_line(f"offsetof({cl.struct_name(emitter.names)}, {emitter.attr(attr)}),")
|
| 560 |
+
if not trait.attributes:
|
| 561 |
+
# This is for msvc.
|
| 562 |
+
emitter.emit_line("0")
|
| 563 |
+
emitter.emit_line("};")
|
| 564 |
+
emitter.emit_line(
|
| 565 |
+
"memcpy({name}, {name}_scratch, sizeof({name}));".format(name=trait_offset_table_name)
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def generate_vtable(
|
| 570 |
+
entries: VTableEntries,
|
| 571 |
+
vtable_name: str,
|
| 572 |
+
emitter: Emitter,
|
| 573 |
+
subtables: list[tuple[ClassIR, str, str]],
|
| 574 |
+
shadow: bool,
|
| 575 |
+
) -> None:
|
| 576 |
+
emitter.emit_line(f"CPyVTableItem {vtable_name}_scratch[] = {{")
|
| 577 |
+
if subtables:
|
| 578 |
+
emitter.emit_line("/* Array of trait vtables */")
|
| 579 |
+
for trait, table, offset_table in subtables:
|
| 580 |
+
emitter.emit_line(
|
| 581 |
+
"(CPyVTableItem){}, (CPyVTableItem){}, (CPyVTableItem){},".format(
|
| 582 |
+
emitter.type_struct_name(trait), table, offset_table
|
| 583 |
+
)
|
| 584 |
+
)
|
| 585 |
+
emitter.emit_line("/* Start of real vtable */")
|
| 586 |
+
|
| 587 |
+
for entry in entries:
|
| 588 |
+
method = entry.shadow_method if shadow and entry.shadow_method else entry.method
|
| 589 |
+
emitter.emit_line(
|
| 590 |
+
"(CPyVTableItem){}{}{},".format(
|
| 591 |
+
emitter.get_group_prefix(entry.method.decl),
|
| 592 |
+
NATIVE_PREFIX,
|
| 593 |
+
method.cname(emitter.names),
|
| 594 |
+
)
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
# msvc doesn't allow empty arrays; maybe allowing them at all is an extension?
|
| 598 |
+
if not entries:
|
| 599 |
+
emitter.emit_line("NULL")
|
| 600 |
+
emitter.emit_line("};")
|
| 601 |
+
emitter.emit_line("memcpy({name}, {name}_scratch, sizeof({name}));".format(name=vtable_name))
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def generate_setup_for_class(
|
| 605 |
+
cl: ClassIR,
|
| 606 |
+
defaults_fn: FuncIR | None,
|
| 607 |
+
vtable_name: str,
|
| 608 |
+
shadow_vtable_name: str | None,
|
| 609 |
+
emitter: Emitter,
|
| 610 |
+
) -> None:
|
| 611 |
+
"""Generate a native function that allocates an instance of a class."""
|
| 612 |
+
emitter.emit_line(native_function_header(cl.setup, emitter))
|
| 613 |
+
emitter.emit_line("{")
|
| 614 |
+
type_arg_name = REG_PREFIX + cl.setup.sig.args[0].name
|
| 615 |
+
emitter.emit_line(f"PyTypeObject *type = (PyTypeObject*){type_arg_name};")
|
| 616 |
+
struct_name = cl.struct_name(emitter.names)
|
| 617 |
+
emitter.emit_line(f"{struct_name} *self;")
|
| 618 |
+
|
| 619 |
+
prefix = cl.name_prefix(emitter.names)
|
| 620 |
+
if cl.reuse_freed_instance:
|
| 621 |
+
# Attempt to use a per-type free list first (a free "list" with up to one object only).
|
| 622 |
+
emitter.emit_line(f"if ({prefix}_free_instance != NULL) {{")
|
| 623 |
+
emitter.emit_line(f"self = {prefix}_free_instance;")
|
| 624 |
+
emitter.emit_line(f"{prefix}_free_instance = NULL;")
|
| 625 |
+
emitter.emit_line("Py_SET_REFCNT(self, 1);")
|
| 626 |
+
if not cl.is_acyclic:
|
| 627 |
+
emitter.emit_line("PyObject_GC_Track(self);")
|
| 628 |
+
if defaults_fn is not None:
|
| 629 |
+
emit_attr_defaults_func_call(defaults_fn, "self", emitter)
|
| 630 |
+
emitter.emit_line("return (PyObject *)self;")
|
| 631 |
+
emitter.emit_line("}")
|
| 632 |
+
|
| 633 |
+
emitter.emit_line(f"self = ({cl.struct_name(emitter.names)} *)type->tp_alloc(type, 0);")
|
| 634 |
+
emitter.emit_line("if (self == NULL)")
|
| 635 |
+
emitter.emit_line(" return NULL;")
|
| 636 |
+
|
| 637 |
+
if shadow_vtable_name:
|
| 638 |
+
emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{")
|
| 639 |
+
emitter.emit_line(f"self->vtable = {shadow_vtable_name};")
|
| 640 |
+
emitter.emit_line("} else {")
|
| 641 |
+
emitter.emit_line(f"self->vtable = {vtable_name};")
|
| 642 |
+
emitter.emit_line("}")
|
| 643 |
+
else:
|
| 644 |
+
emitter.emit_line(f"self->vtable = {vtable_name};")
|
| 645 |
+
|
| 646 |
+
emit_clear_bitmaps(cl, emitter)
|
| 647 |
+
|
| 648 |
+
if cl.has_method("__call__"):
|
| 649 |
+
name = cl.method_decl("__call__").cname(emitter.names)
|
| 650 |
+
emitter.emit_line(f"self->vectorcall = {PREFIX}{name};")
|
| 651 |
+
|
| 652 |
+
for base in reversed(cl.base_mro):
|
| 653 |
+
for attr, rtype in base.attributes.items():
|
| 654 |
+
value = emitter.c_undefined_value(rtype)
|
| 655 |
+
|
| 656 |
+
# We don't need to set this field to NULL since tp_alloc() already
|
| 657 |
+
# zero-initializes `self`.
|
| 658 |
+
if value != "NULL":
|
| 659 |
+
emitter.set_undefined_value(f"self->{emitter.attr(attr)}", rtype)
|
| 660 |
+
|
| 661 |
+
# Initialize attributes to default values, if necessary
|
| 662 |
+
if defaults_fn is not None:
|
| 663 |
+
emit_attr_defaults_func_call(defaults_fn, "self", emitter)
|
| 664 |
+
|
| 665 |
+
emitter.emit_line("return (PyObject *)self;")
|
| 666 |
+
emitter.emit_line("}")
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def emit_clear_bitmaps(cl: ClassIR, emitter: Emitter) -> None:
|
| 670 |
+
"""Emit C code to clear bitmaps that track if attributes have an assigned value."""
|
| 671 |
+
for i in range(0, len(cl.bitmap_attrs), BITMAP_BITS):
|
| 672 |
+
field = emitter.bitmap_field(i)
|
| 673 |
+
emitter.emit_line(f"self->{field} = 0;")
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def emit_attr_defaults_func_call(defaults_fn: FuncIR, self_name: str, emitter: Emitter) -> None:
|
| 677 |
+
"""Emit C code to initialize attribute defaults by calling defaults_fn.
|
| 678 |
+
|
| 679 |
+
The code returns NULL on a raised exception.
|
| 680 |
+
"""
|
| 681 |
+
emitter.emit_lines(
|
| 682 |
+
"if ({}{}((PyObject *){}) == 0) {{".format(
|
| 683 |
+
NATIVE_PREFIX, defaults_fn.cname(emitter.names), self_name
|
| 684 |
+
),
|
| 685 |
+
"Py_DECREF(self);",
|
| 686 |
+
"return NULL;",
|
| 687 |
+
"}",
|
| 688 |
+
)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def emit_setup_or_dunder_new_call(
|
| 692 |
+
cl: ClassIR,
|
| 693 |
+
setup_name: str,
|
| 694 |
+
type_arg: str,
|
| 695 |
+
native_prefix: bool,
|
| 696 |
+
new_args: str,
|
| 697 |
+
emitter: Emitter,
|
| 698 |
+
) -> None:
|
| 699 |
+
def emit_null_check() -> None:
|
| 700 |
+
emitter.emit_line("if (self == NULL)")
|
| 701 |
+
emitter.emit_line(" return NULL;")
|
| 702 |
+
|
| 703 |
+
new_fn = cl.get_method("__new__")
|
| 704 |
+
if not new_fn:
|
| 705 |
+
emitter.emit_line(f"PyObject *self = {setup_name}({type_arg});")
|
| 706 |
+
emit_null_check()
|
| 707 |
+
return
|
| 708 |
+
prefix = emitter.get_group_prefix(new_fn.decl) + NATIVE_PREFIX if native_prefix else PREFIX
|
| 709 |
+
all_args = type_arg
|
| 710 |
+
if new_args != "":
|
| 711 |
+
all_args += ", " + new_args
|
| 712 |
+
emitter.emit_line(f"PyObject *self = {prefix}{new_fn.cname(emitter.names)}({all_args});")
|
| 713 |
+
emit_null_check()
|
| 714 |
+
|
| 715 |
+
# skip __init__ if __new__ returns some other type
|
| 716 |
+
emitter.emit_line(f"if (Py_TYPE(self) != {emitter.type_struct_name(cl)})")
|
| 717 |
+
emitter.emit_line(" return self;")
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
def generate_constructor_for_class(
|
| 721 |
+
cl: ClassIR,
|
| 722 |
+
fn: FuncDecl,
|
| 723 |
+
init_fn: FuncIR | None,
|
| 724 |
+
setup_name: str,
|
| 725 |
+
vtable_name: str,
|
| 726 |
+
emitter: Emitter,
|
| 727 |
+
) -> None:
|
| 728 |
+
"""Generate a native function that allocates and initializes an instance of a class."""
|
| 729 |
+
emitter.emit_line(f"{native_function_header(fn, emitter)}")
|
| 730 |
+
emitter.emit_line("{")
|
| 731 |
+
|
| 732 |
+
fn_args = [REG_PREFIX + arg.name for arg in fn.sig.args]
|
| 733 |
+
type_arg = "(PyObject *)" + emitter.type_struct_name(cl)
|
| 734 |
+
new_args = ", ".join(fn_args)
|
| 735 |
+
|
| 736 |
+
use_wrapper = (
|
| 737 |
+
cl.has_method("__new__")
|
| 738 |
+
and len(fn.sig.args) == 2
|
| 739 |
+
and fn.sig.args[0].kind == ARG_STAR
|
| 740 |
+
and fn.sig.args[1].kind == ARG_STAR2
|
| 741 |
+
)
|
| 742 |
+
emit_setup_or_dunder_new_call(cl, setup_name, type_arg, not use_wrapper, new_args, emitter)
|
| 743 |
+
|
| 744 |
+
args = ", ".join(["self"] + fn_args)
|
| 745 |
+
if init_fn is not None:
|
| 746 |
+
prefix = PREFIX if use_wrapper else NATIVE_PREFIX
|
| 747 |
+
cast = "!= NULL ? 0 : -1" if use_wrapper else ""
|
| 748 |
+
emitter.emit_line(
|
| 749 |
+
"char res = {}{}{}({}){};".format(
|
| 750 |
+
emitter.get_group_prefix(init_fn.decl),
|
| 751 |
+
prefix,
|
| 752 |
+
init_fn.cname(emitter.names),
|
| 753 |
+
args,
|
| 754 |
+
cast,
|
| 755 |
+
)
|
| 756 |
+
)
|
| 757 |
+
emitter.emit_line("if (res == 2) {")
|
| 758 |
+
emitter.emit_line("Py_DECREF(self);")
|
| 759 |
+
emitter.emit_line("return NULL;")
|
| 760 |
+
emitter.emit_line("}")
|
| 761 |
+
|
| 762 |
+
# If there is a nontrivial ctor that we didn't define, invoke it via tp_init
|
| 763 |
+
elif len(fn.sig.args) > 1:
|
| 764 |
+
emitter.emit_line(f"int res = {emitter.type_struct_name(cl)}->tp_init({args});")
|
| 765 |
+
|
| 766 |
+
emitter.emit_line("if (res < 0) {")
|
| 767 |
+
emitter.emit_line("Py_DECREF(self);")
|
| 768 |
+
emitter.emit_line("return NULL;")
|
| 769 |
+
emitter.emit_line("}")
|
| 770 |
+
|
| 771 |
+
emitter.emit_line("return self;")
|
| 772 |
+
emitter.emit_line("}")
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def generate_init_for_class(cl: ClassIR, init_fn: FuncIR, emitter: Emitter) -> str:
|
| 776 |
+
"""Generate an init function suitable for use as tp_init.
|
| 777 |
+
|
| 778 |
+
tp_init needs to be a function that returns an int, and our
|
| 779 |
+
__init__ methods return a PyObject. Translate NULL to -1,
|
| 780 |
+
everything else to 0.
|
| 781 |
+
"""
|
| 782 |
+
func_name = f"{cl.name_prefix(emitter.names)}_init"
|
| 783 |
+
|
| 784 |
+
emitter.emit_line("static int")
|
| 785 |
+
emitter.emit_line(f"{func_name}(PyObject *self, PyObject *args, PyObject *kwds)")
|
| 786 |
+
emitter.emit_line("{")
|
| 787 |
+
if cl.allow_interpreted_subclasses or cl.builtin_base or cl.has_method("__new__"):
|
| 788 |
+
emitter.emit_line(
|
| 789 |
+
"return {}{}(self, args, kwds) != NULL ? 0 : -1;".format(
|
| 790 |
+
PREFIX, init_fn.cname(emitter.names)
|
| 791 |
+
)
|
| 792 |
+
)
|
| 793 |
+
else:
|
| 794 |
+
emitter.emit_line("return 0;")
|
| 795 |
+
emitter.emit_line("}")
|
| 796 |
+
|
| 797 |
+
return func_name
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def generate_new_for_class(
|
| 801 |
+
cl: ClassIR,
|
| 802 |
+
func_name: str,
|
| 803 |
+
vtable_name: str,
|
| 804 |
+
setup_name: str,
|
| 805 |
+
init_fn: FuncIR | None,
|
| 806 |
+
emitter: Emitter,
|
| 807 |
+
) -> None:
|
| 808 |
+
emitter.emit_line("static PyObject *")
|
| 809 |
+
emitter.emit_line(f"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)")
|
| 810 |
+
emitter.emit_line("{")
|
| 811 |
+
# TODO: Check and unbox arguments
|
| 812 |
+
if not cl.allow_interpreted_subclasses:
|
| 813 |
+
emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{")
|
| 814 |
+
emitter.emit_line(
|
| 815 |
+
'PyErr_SetString(PyExc_TypeError, "interpreted classes cannot inherit from compiled");'
|
| 816 |
+
)
|
| 817 |
+
emitter.emit_line("return NULL;")
|
| 818 |
+
emitter.emit_line("}")
|
| 819 |
+
|
| 820 |
+
type_arg = "(PyObject*)type"
|
| 821 |
+
new_args = "args, kwds"
|
| 822 |
+
emit_setup_or_dunder_new_call(cl, setup_name, type_arg, False, new_args, emitter)
|
| 823 |
+
if (
|
| 824 |
+
not init_fn
|
| 825 |
+
or cl.allow_interpreted_subclasses
|
| 826 |
+
or cl.builtin_base
|
| 827 |
+
or cl.is_serializable()
|
| 828 |
+
or cl.has_method("__new__")
|
| 829 |
+
):
|
| 830 |
+
# Match Python semantics -- __new__ doesn't call __init__.
|
| 831 |
+
emitter.emit_line("return self;")
|
| 832 |
+
else:
|
| 833 |
+
# __new__ of a native class implicitly calls __init__ so that we
|
| 834 |
+
# can enforce that instances are always properly initialized. This
|
| 835 |
+
# is needed to support always defined attributes.
|
| 836 |
+
emitter.emit_line(
|
| 837 |
+
f"PyObject *ret = {PREFIX}{init_fn.cname(emitter.names)}(self, args, kwds);"
|
| 838 |
+
)
|
| 839 |
+
emitter.emit_lines("if (ret == NULL)", " return NULL;")
|
| 840 |
+
emitter.emit_line("return self;")
|
| 841 |
+
emitter.emit_line("}")
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
def generate_new_for_trait(cl: ClassIR, func_name: str, emitter: Emitter) -> None:
|
| 845 |
+
emitter.emit_line("static PyObject *")
|
| 846 |
+
emitter.emit_line(f"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)")
|
| 847 |
+
emitter.emit_line("{")
|
| 848 |
+
emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{")
|
| 849 |
+
emitter.emit_line(
|
| 850 |
+
"PyErr_SetString(PyExc_TypeError, "
|
| 851 |
+
'"interpreted classes cannot inherit from compiled traits");'
|
| 852 |
+
)
|
| 853 |
+
emitter.emit_line("} else {")
|
| 854 |
+
emitter.emit_line('PyErr_SetString(PyExc_TypeError, "traits may not be directly created");')
|
| 855 |
+
emitter.emit_line("}")
|
| 856 |
+
emitter.emit_line("return NULL;")
|
| 857 |
+
emitter.emit_line("}")
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def generate_traverse_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None:
|
| 861 |
+
"""Emit function that performs cycle GC traversal of an instance."""
|
| 862 |
+
emitter.emit_line("static int")
|
| 863 |
+
emitter.emit_line(
|
| 864 |
+
f"{func_name}({cl.struct_name(emitter.names)} *self, visitproc visit, void *arg)"
|
| 865 |
+
)
|
| 866 |
+
emitter.emit_line("{")
|
| 867 |
+
for base in reversed(cl.base_mro):
|
| 868 |
+
for attr, rtype in base.attributes.items():
|
| 869 |
+
emitter.emit_gc_visit(f"self->{emitter.attr(attr)}", rtype)
|
| 870 |
+
if has_managed_dict(cl, emitter):
|
| 871 |
+
emitter.emit_line("PyObject_VisitManagedDict((PyObject *)self, visit, arg);")
|
| 872 |
+
elif cl.has_dict:
|
| 873 |
+
struct_name = cl.struct_name(emitter.names)
|
| 874 |
+
# __dict__ lives right after the struct and __weakref__ lives right after that
|
| 875 |
+
emitter.emit_gc_visit(
|
| 876 |
+
f"*((PyObject **)((char *)self + sizeof({struct_name})))", object_rprimitive
|
| 877 |
+
)
|
| 878 |
+
emitter.emit_gc_visit(
|
| 879 |
+
f"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))",
|
| 880 |
+
object_rprimitive,
|
| 881 |
+
)
|
| 882 |
+
emitter.emit_line("return 0;")
|
| 883 |
+
emitter.emit_line("}")
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
def generate_clear_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None:
|
| 887 |
+
emitter.emit_line("static int")
|
| 888 |
+
emitter.emit_line(f"{func_name}({cl.struct_name(emitter.names)} *self)")
|
| 889 |
+
emitter.emit_line("{")
|
| 890 |
+
for base in reversed(cl.base_mro):
|
| 891 |
+
for attr, rtype in base.attributes.items():
|
| 892 |
+
emitter.emit_gc_clear(f"self->{emitter.attr(attr)}", rtype)
|
| 893 |
+
if has_managed_dict(cl, emitter):
|
| 894 |
+
emitter.emit_line("PyObject_ClearManagedDict((PyObject *)self);")
|
| 895 |
+
elif cl.has_dict:
|
| 896 |
+
struct_name = cl.struct_name(emitter.names)
|
| 897 |
+
# __dict__ lives right after the struct and __weakref__ lives right after that
|
| 898 |
+
emitter.emit_gc_clear(
|
| 899 |
+
f"*((PyObject **)((char *)self + sizeof({struct_name})))", object_rprimitive
|
| 900 |
+
)
|
| 901 |
+
emitter.emit_gc_clear(
|
| 902 |
+
f"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))",
|
| 903 |
+
object_rprimitive,
|
| 904 |
+
)
|
| 905 |
+
emitter.emit_line("return 0;")
|
| 906 |
+
emitter.emit_line("}")
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def generate_dealloc_for_class(
|
| 910 |
+
cl: ClassIR,
|
| 911 |
+
dealloc_func_name: str,
|
| 912 |
+
clear_func_name: str,
|
| 913 |
+
has_tp_finalize: bool,
|
| 914 |
+
emitter: Emitter,
|
| 915 |
+
) -> None:
|
| 916 |
+
emitter.emit_line("static void")
|
| 917 |
+
emitter.emit_line(f"{dealloc_func_name}({cl.struct_name(emitter.names)} *self)")
|
| 918 |
+
emitter.emit_line("{")
|
| 919 |
+
if has_tp_finalize:
|
| 920 |
+
emitter.emit_line("PyObject *type, *value, *traceback;")
|
| 921 |
+
emitter.emit_line("PyErr_Fetch(&type, &value, &traceback);")
|
| 922 |
+
emitter.emit_line("int res = PyObject_CallFinalizerFromDealloc((PyObject *)self);")
|
| 923 |
+
# CPython interpreter uses PyErr_WriteUnraisable: https://docs.python.org/3/c-api/exceptions.html#c.PyErr_WriteUnraisable
|
| 924 |
+
# However, the message is slightly different due to the way mypyc compiles classes.
|
| 925 |
+
# CPython interpreter prints: Exception ignored in: <function F.__del__ at 0x100aed940>
|
| 926 |
+
# mypyc prints: Exception ignored in: <slot wrapper '__del__' of 'F' objects>
|
| 927 |
+
emitter.emit_line("if (PyErr_Occurred() != NULL) {")
|
| 928 |
+
# Don't untrack instance if error occurred
|
| 929 |
+
emitter.emit_line("PyErr_WriteUnraisable((PyObject *)self);")
|
| 930 |
+
emitter.emit_line("res = -1;")
|
| 931 |
+
emitter.emit_line("}")
|
| 932 |
+
emitter.emit_line("PyErr_Restore(type, value, traceback);")
|
| 933 |
+
emitter.emit_line("if (res < 0) {")
|
| 934 |
+
emitter.emit_line("goto done;")
|
| 935 |
+
emitter.emit_line("}")
|
| 936 |
+
if not cl.is_acyclic:
|
| 937 |
+
emitter.emit_line("PyObject_GC_UnTrack(self);")
|
| 938 |
+
if cl.reuse_freed_instance:
|
| 939 |
+
emit_reuse_dealloc(cl, emitter)
|
| 940 |
+
# The trashcan is needed to handle deep recursive deallocations
|
| 941 |
+
emitter.emit_line(f"CPy_TRASHCAN_BEGIN(self, {dealloc_func_name})")
|
| 942 |
+
emitter.emit_line(f"{clear_func_name}(self);")
|
| 943 |
+
emitter.emit_line("Py_TYPE(self)->tp_free((PyObject *)self);")
|
| 944 |
+
emitter.emit_line("CPy_TRASHCAN_END(self)")
|
| 945 |
+
emitter.emit_line("done: ;")
|
| 946 |
+
emitter.emit_line("}")
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
def emit_reuse_dealloc(cl: ClassIR, emitter: Emitter) -> None:
|
| 950 |
+
"""Emit code to deallocate object by putting it to per-type free list.
|
| 951 |
+
|
| 952 |
+
The free "list" currently can have up to one object.
|
| 953 |
+
"""
|
| 954 |
+
prefix = cl.name_prefix(emitter.names)
|
| 955 |
+
emitter.emit_line(f"if ({prefix}_free_instance == NULL) {{")
|
| 956 |
+
emitter.emit_line(f"{prefix}_free_instance = self;")
|
| 957 |
+
|
| 958 |
+
# Clear attributes and free referenced objects.
|
| 959 |
+
|
| 960 |
+
emit_clear_bitmaps(cl, emitter)
|
| 961 |
+
|
| 962 |
+
for base in reversed(cl.base_mro):
|
| 963 |
+
for attr, rtype in base.attributes.items():
|
| 964 |
+
emitter.emit_reuse_clear(f"self->{emitter.attr(attr)}", rtype)
|
| 965 |
+
|
| 966 |
+
emitter.emit_line("return;")
|
| 967 |
+
emitter.emit_line("}")
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
def generate_finalize_for_class(
|
| 971 |
+
del_method: FuncIR, finalize_func_name: str, emitter: Emitter
|
| 972 |
+
) -> None:
|
| 973 |
+
emitter.emit_line("static void")
|
| 974 |
+
emitter.emit_line(f"{finalize_func_name}(PyObject *self)")
|
| 975 |
+
emitter.emit_line("{")
|
| 976 |
+
emitter.emit_line(
|
| 977 |
+
"{}{}{}(self);".format(
|
| 978 |
+
emitter.get_group_prefix(del_method.decl),
|
| 979 |
+
NATIVE_PREFIX,
|
| 980 |
+
del_method.cname(emitter.names),
|
| 981 |
+
)
|
| 982 |
+
)
|
| 983 |
+
emitter.emit_line("}")
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def generate_methods_table(
|
| 987 |
+
cl: ClassIR, name: str, setup_name: str | None, emitter: Emitter
|
| 988 |
+
) -> None:
|
| 989 |
+
emitter.emit_line(f"static PyMethodDef {name}[] = {{")
|
| 990 |
+
if setup_name:
|
| 991 |
+
# Store pointer to the setup function so it can be resolved dynamically
|
| 992 |
+
# in case of instance creation in __new__.
|
| 993 |
+
# CPy_SetupObject expects this method to be the first one in tp_methods.
|
| 994 |
+
emitter.emit_line(
|
| 995 |
+
f'{{"__internal_mypyc_setup", (PyCFunction){setup_name}, METH_O, NULL}},'
|
| 996 |
+
)
|
| 997 |
+
for fn in cl.methods.values():
|
| 998 |
+
if fn.decl.is_prop_setter or fn.decl.is_prop_getter or fn.internal:
|
| 999 |
+
continue
|
| 1000 |
+
emitter.emit_line(f'{{"{fn.name}",')
|
| 1001 |
+
emitter.emit_line(f" (PyCFunction){PREFIX}{fn.cname(emitter.names)},")
|
| 1002 |
+
flags = ["METH_FASTCALL", "METH_KEYWORDS"]
|
| 1003 |
+
if fn.decl.kind == FUNC_STATICMETHOD:
|
| 1004 |
+
flags.append("METH_STATIC")
|
| 1005 |
+
elif fn.decl.kind == FUNC_CLASSMETHOD:
|
| 1006 |
+
flags.append("METH_CLASS")
|
| 1007 |
+
|
| 1008 |
+
doc = native_function_doc_initializer(fn)
|
| 1009 |
+
emitter.emit_line(" {}, PyDoc_STR({})}},".format(" | ".join(flags), doc))
|
| 1010 |
+
|
| 1011 |
+
# Provide a default __getstate__ and __setstate__
|
| 1012 |
+
if not cl.has_method("__setstate__") and not cl.has_method("__getstate__"):
|
| 1013 |
+
emitter.emit_lines(
|
| 1014 |
+
'{"__setstate__", (PyCFunction)CPyPickle_SetState, METH_O, NULL},',
|
| 1015 |
+
'{"__getstate__", (PyCFunction)CPyPickle_GetState, METH_NOARGS, NULL},',
|
| 1016 |
+
)
|
| 1017 |
+
|
| 1018 |
+
emitter.emit_line("{NULL} /* Sentinel */")
|
| 1019 |
+
emitter.emit_line("};")
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
def generate_side_table_for_class(
|
| 1023 |
+
cl: ClassIR, name: str, type: str, slots: dict[str, str], emitter: Emitter
|
| 1024 |
+
) -> str | None:
|
| 1025 |
+
name = f"{cl.name_prefix(emitter.names)}_{name}"
|
| 1026 |
+
emitter.emit_line(f"static {type} {name} = {{")
|
| 1027 |
+
for field, value in slots.items():
|
| 1028 |
+
emitter.emit_line(f".{field} = {value},")
|
| 1029 |
+
emitter.emit_line("};")
|
| 1030 |
+
return name
|
| 1031 |
+
|
| 1032 |
+
|
| 1033 |
+
def generate_getseter_declarations(cl: ClassIR, emitter: Emitter) -> None:
|
| 1034 |
+
if not cl.is_trait:
|
| 1035 |
+
for attr in cl.attributes:
|
| 1036 |
+
emitter.emit_line("static PyObject *")
|
| 1037 |
+
emitter.emit_line(
|
| 1038 |
+
"{}({} *self, void *closure);".format(
|
| 1039 |
+
getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
|
| 1040 |
+
)
|
| 1041 |
+
)
|
| 1042 |
+
emitter.emit_line("static int")
|
| 1043 |
+
emitter.emit_line(
|
| 1044 |
+
"{}({} *self, PyObject *value, void *closure);".format(
|
| 1045 |
+
setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
|
| 1046 |
+
)
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
for prop, (getter, setter) in cl.properties.items():
|
| 1050 |
+
if getter.decl.implicit:
|
| 1051 |
+
continue
|
| 1052 |
+
|
| 1053 |
+
# Generate getter declaration
|
| 1054 |
+
emitter.emit_line("static PyObject *")
|
| 1055 |
+
emitter.emit_line(
|
| 1056 |
+
"{}({} *self, void *closure);".format(
|
| 1057 |
+
getter_name(cl, prop, emitter.names), cl.struct_name(emitter.names)
|
| 1058 |
+
)
|
| 1059 |
+
)
|
| 1060 |
+
|
| 1061 |
+
# Generate property setter declaration if a setter exists
|
| 1062 |
+
if setter:
|
| 1063 |
+
emitter.emit_line("static int")
|
| 1064 |
+
emitter.emit_line(
|
| 1065 |
+
"{}({} *self, PyObject *value, void *closure);".format(
|
| 1066 |
+
setter_name(cl, prop, emitter.names), cl.struct_name(emitter.names)
|
| 1067 |
+
)
|
| 1068 |
+
)
|
| 1069 |
+
|
| 1070 |
+
|
| 1071 |
+
def generate_getseters_table(cl: ClassIR, name: str, emitter: Emitter) -> None:
|
| 1072 |
+
emitter.emit_line(f"static PyGetSetDef {name}[] = {{")
|
| 1073 |
+
if not cl.is_trait:
|
| 1074 |
+
for attr in cl.attributes:
|
| 1075 |
+
emitter.emit_line(f'{{"{attr}",')
|
| 1076 |
+
emitter.emit_line(
|
| 1077 |
+
" (getter){}, (setter){},".format(
|
| 1078 |
+
getter_name(cl, attr, emitter.names), setter_name(cl, attr, emitter.names)
|
| 1079 |
+
)
|
| 1080 |
+
)
|
| 1081 |
+
emitter.emit_line(" NULL, NULL},")
|
| 1082 |
+
for prop, (getter, setter) in cl.properties.items():
|
| 1083 |
+
if getter.decl.implicit:
|
| 1084 |
+
continue
|
| 1085 |
+
|
| 1086 |
+
emitter.emit_line(f'{{"{prop}",')
|
| 1087 |
+
emitter.emit_line(f" (getter){getter_name(cl, prop, emitter.names)},")
|
| 1088 |
+
|
| 1089 |
+
if setter:
|
| 1090 |
+
emitter.emit_line(f" (setter){setter_name(cl, prop, emitter.names)},")
|
| 1091 |
+
emitter.emit_line("NULL, NULL},")
|
| 1092 |
+
else:
|
| 1093 |
+
emitter.emit_line("NULL, NULL, NULL},")
|
| 1094 |
+
|
| 1095 |
+
if cl.has_dict:
|
| 1096 |
+
emitter.emit_line('{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},')
|
| 1097 |
+
|
| 1098 |
+
emitter.emit_line("{NULL} /* Sentinel */")
|
| 1099 |
+
emitter.emit_line("};")
|
| 1100 |
+
|
| 1101 |
+
|
| 1102 |
+
def generate_getseters(cl: ClassIR, emitter: Emitter) -> None:
|
| 1103 |
+
if not cl.is_trait:
|
| 1104 |
+
for i, (attr, rtype) in enumerate(cl.attributes.items()):
|
| 1105 |
+
generate_getter(cl, attr, rtype, emitter)
|
| 1106 |
+
emitter.emit_line("")
|
| 1107 |
+
generate_setter(cl, attr, rtype, emitter)
|
| 1108 |
+
if i < len(cl.attributes) - 1:
|
| 1109 |
+
emitter.emit_line("")
|
| 1110 |
+
for prop, (getter, setter) in cl.properties.items():
|
| 1111 |
+
if getter.decl.implicit:
|
| 1112 |
+
continue
|
| 1113 |
+
|
| 1114 |
+
rtype = getter.sig.ret_type
|
| 1115 |
+
emitter.emit_line("")
|
| 1116 |
+
generate_readonly_getter(cl, prop, rtype, getter, emitter)
|
| 1117 |
+
if setter:
|
| 1118 |
+
arg_type = setter.sig.args[1].type
|
| 1119 |
+
emitter.emit_line("")
|
| 1120 |
+
generate_property_setter(cl, prop, arg_type, setter, emitter)
|
| 1121 |
+
|
| 1122 |
+
|
| 1123 |
+
def generate_getter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None:
|
| 1124 |
+
attr_field = emitter.attr(attr)
|
| 1125 |
+
emitter.emit_line("static PyObject *")
|
| 1126 |
+
emitter.emit_line(
|
| 1127 |
+
"{}({} *self, void *closure)".format(
|
| 1128 |
+
getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
|
| 1129 |
+
)
|
| 1130 |
+
)
|
| 1131 |
+
emitter.emit_line("{")
|
| 1132 |
+
attr_expr = f"self->{attr_field}"
|
| 1133 |
+
|
| 1134 |
+
# HACK: Don't consider refcounted values as always defined, since it's possible to
|
| 1135 |
+
# access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted
|
| 1136 |
+
# values is benign.
|
| 1137 |
+
always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted
|
| 1138 |
+
|
| 1139 |
+
if not always_defined:
|
| 1140 |
+
emitter.emit_undefined_attr_check(rtype, attr_expr, "==", "self", attr, cl, unlikely=True)
|
| 1141 |
+
emitter.emit_line("PyErr_SetString(PyExc_AttributeError,")
|
| 1142 |
+
emitter.emit_line(f' "attribute {repr(attr)} of {repr(cl.name)} undefined");')
|
| 1143 |
+
emitter.emit_line("return NULL;")
|
| 1144 |
+
emitter.emit_line("}")
|
| 1145 |
+
emitter.emit_inc_ref(f"self->{attr_field}", rtype)
|
| 1146 |
+
emitter.emit_box(f"self->{attr_field}", "retval", rtype, declare_dest=True)
|
| 1147 |
+
emitter.emit_line("return retval;")
|
| 1148 |
+
emitter.emit_line("}")
|
| 1149 |
+
|
| 1150 |
+
|
| 1151 |
+
def generate_setter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None:
|
| 1152 |
+
attr_field = emitter.attr(attr)
|
| 1153 |
+
emitter.emit_line("static int")
|
| 1154 |
+
emitter.emit_line(
|
| 1155 |
+
"{}({} *self, PyObject *value, void *closure)".format(
|
| 1156 |
+
setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
|
| 1157 |
+
)
|
| 1158 |
+
)
|
| 1159 |
+
emitter.emit_line("{")
|
| 1160 |
+
|
| 1161 |
+
deletable = cl.is_deletable(attr)
|
| 1162 |
+
if not deletable:
|
| 1163 |
+
emitter.emit_line("if (value == NULL) {")
|
| 1164 |
+
emitter.emit_line("PyErr_SetString(PyExc_AttributeError,")
|
| 1165 |
+
emitter.emit_line(
|
| 1166 |
+
f' "{repr(cl.name)} object attribute {repr(attr)} cannot be deleted");'
|
| 1167 |
+
)
|
| 1168 |
+
emitter.emit_line("return -1;")
|
| 1169 |
+
emitter.emit_line("}")
|
| 1170 |
+
|
| 1171 |
+
# HACK: Don't consider refcounted values as always defined, since it's possible to
|
| 1172 |
+
# access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted
|
| 1173 |
+
# values is benign.
|
| 1174 |
+
always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted
|
| 1175 |
+
|
| 1176 |
+
if rtype.is_refcounted:
|
| 1177 |
+
attr_expr = f"self->{attr_field}"
|
| 1178 |
+
if not always_defined:
|
| 1179 |
+
emitter.emit_undefined_attr_check(rtype, attr_expr, "!=", "self", attr, cl)
|
| 1180 |
+
emitter.emit_dec_ref(f"self->{attr_field}", rtype)
|
| 1181 |
+
if not always_defined:
|
| 1182 |
+
emitter.emit_line("}")
|
| 1183 |
+
|
| 1184 |
+
if deletable:
|
| 1185 |
+
emitter.emit_line("if (value != NULL) {")
|
| 1186 |
+
|
| 1187 |
+
if rtype.is_unboxed:
|
| 1188 |
+
emitter.emit_unbox("value", "tmp", rtype, error=ReturnHandler("-1"), declare_dest=True)
|
| 1189 |
+
elif is_same_type(rtype, object_rprimitive):
|
| 1190 |
+
emitter.emit_line("PyObject *tmp = value;")
|
| 1191 |
+
else:
|
| 1192 |
+
emitter.emit_cast("value", "tmp", rtype, declare_dest=True)
|
| 1193 |
+
emitter.emit_lines("if (!tmp)", " return -1;")
|
| 1194 |
+
emitter.emit_inc_ref("tmp", rtype)
|
| 1195 |
+
emitter.emit_line(f"self->{attr_field} = tmp;")
|
| 1196 |
+
if rtype.error_overlap and not always_defined:
|
| 1197 |
+
emitter.emit_attr_bitmap_set("tmp", "self", rtype, cl, attr)
|
| 1198 |
+
|
| 1199 |
+
if deletable:
|
| 1200 |
+
emitter.emit_line("} else {")
|
| 1201 |
+
emitter.set_undefined_value(f"self->{attr_field}", rtype)
|
| 1202 |
+
if rtype.error_overlap:
|
| 1203 |
+
emitter.emit_attr_bitmap_clear("self", rtype, cl, attr)
|
| 1204 |
+
emitter.emit_line("}")
|
| 1205 |
+
emitter.emit_line("return 0;")
|
| 1206 |
+
emitter.emit_line("}")
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
def generate_readonly_getter(
|
| 1210 |
+
cl: ClassIR, attr: str, rtype: RType, func_ir: FuncIR, emitter: Emitter
|
| 1211 |
+
) -> None:
|
| 1212 |
+
emitter.emit_line("static PyObject *")
|
| 1213 |
+
emitter.emit_line(
|
| 1214 |
+
"{}({} *self, void *closure)".format(
|
| 1215 |
+
getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
|
| 1216 |
+
)
|
| 1217 |
+
)
|
| 1218 |
+
emitter.emit_line("{")
|
| 1219 |
+
if rtype.is_unboxed:
|
| 1220 |
+
emitter.emit_line(
|
| 1221 |
+
"{}retval = {}{}((PyObject *) self);".format(
|
| 1222 |
+
emitter.ctype_spaced(rtype), NATIVE_PREFIX, func_ir.cname(emitter.names)
|
| 1223 |
+
)
|
| 1224 |
+
)
|
| 1225 |
+
emitter.emit_error_check("retval", rtype, "return NULL;")
|
| 1226 |
+
emitter.emit_box("retval", "retbox", rtype, declare_dest=True)
|
| 1227 |
+
emitter.emit_line("return retbox;")
|
| 1228 |
+
else:
|
| 1229 |
+
emitter.emit_line(
|
| 1230 |
+
f"return {NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self);"
|
| 1231 |
+
)
|
| 1232 |
+
emitter.emit_line("}")
|
| 1233 |
+
|
| 1234 |
+
|
| 1235 |
+
def generate_property_setter(
|
| 1236 |
+
cl: ClassIR, attr: str, arg_type: RType, func_ir: FuncIR, emitter: Emitter
|
| 1237 |
+
) -> None:
|
| 1238 |
+
emitter.emit_line("static int")
|
| 1239 |
+
emitter.emit_line(
|
| 1240 |
+
"{}({} *self, PyObject *value, void *closure)".format(
|
| 1241 |
+
setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)
|
| 1242 |
+
)
|
| 1243 |
+
)
|
| 1244 |
+
emitter.emit_line("{")
|
| 1245 |
+
if arg_type.is_unboxed:
|
| 1246 |
+
emitter.emit_unbox("value", "tmp", arg_type, error=ReturnHandler("-1"), declare_dest=True)
|
| 1247 |
+
emitter.emit_line(
|
| 1248 |
+
f"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, tmp);"
|
| 1249 |
+
)
|
| 1250 |
+
else:
|
| 1251 |
+
emitter.emit_line(
|
| 1252 |
+
f"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, value);"
|
| 1253 |
+
)
|
| 1254 |
+
emitter.emit_line("return 0;")
|
| 1255 |
+
emitter.emit_line("}")
|
| 1256 |
+
|
| 1257 |
+
|
| 1258 |
+
def has_managed_dict(cl: ClassIR, emitter: Emitter) -> bool:
|
| 1259 |
+
"""Should the class get the Py_TPFLAGS_MANAGED_DICT flag?"""
|
| 1260 |
+
# On 3.11 and earlier the flag doesn't exist and we use
|
| 1261 |
+
# tp_dictoffset instead. If a class inherits from Exception, the
|
| 1262 |
+
# flag conflicts with tp_dictoffset set in the base class.
|
| 1263 |
+
return (
|
| 1264 |
+
emitter.capi_version >= (3, 12)
|
| 1265 |
+
and cl.has_dict
|
| 1266 |
+
and cl.builtin_base != "PyBaseExceptionObject"
|
| 1267 |
+
)
|
| 1268 |
+
|
| 1269 |
+
|
| 1270 |
+
def native_class_doc_initializer(cl: ClassIR) -> str:
|
| 1271 |
+
init_fn = cl.get_method("__init__")
|
| 1272 |
+
if init_fn is not None:
|
| 1273 |
+
text_sig = get_text_signature(init_fn, bound=True)
|
| 1274 |
+
if text_sig is None:
|
| 1275 |
+
return "NULL"
|
| 1276 |
+
text_sig = text_sig.replace("__init__", cl.name, 1)
|
| 1277 |
+
else:
|
| 1278 |
+
text_sig = f"{cl.name}()"
|
| 1279 |
+
docstring = f"{text_sig}\n--\n\n"
|
| 1280 |
+
return c_string_initializer(docstring.encode("ascii", errors="backslashreplace"))
|
| 1281 |
+
|
| 1282 |
+
|
| 1283 |
+
def generate_coroutine_setup(
|
| 1284 |
+
cl: ClassIR, coroutine_setup_name: str, module_name: str, emitter: Emitter
|
| 1285 |
+
) -> None:
|
| 1286 |
+
emitter.emit_line("static bool")
|
| 1287 |
+
emitter.emit_line(f"{NATIVE_PREFIX}{coroutine_setup_name}(PyObject *type)")
|
| 1288 |
+
emitter.emit_line("{")
|
| 1289 |
+
|
| 1290 |
+
error_stmt = " return 2;"
|
| 1291 |
+
|
| 1292 |
+
def emit_instance(fn: FuncIR, fn_name: str) -> str:
|
| 1293 |
+
filepath = emitter.filepath or ""
|
| 1294 |
+
return emitter.emit_cpyfunction_instance(fn, fn_name, filepath, error_stmt)
|
| 1295 |
+
|
| 1296 |
+
def success() -> None:
|
| 1297 |
+
emitter.emit_line("return 1;")
|
| 1298 |
+
emitter.emit_line("}")
|
| 1299 |
+
|
| 1300 |
+
if cl.coroutine_name:
|
| 1301 |
+
# Callable class generated for a coroutine. It stores its function wrapper as an attribute.
|
| 1302 |
+
wrapper_name = emit_instance(cl.methods["__call__"], cl.coroutine_name)
|
| 1303 |
+
struct_name = cl.struct_name(emitter.names)
|
| 1304 |
+
attr = emitter.attr(CPYFUNCTION_NAME)
|
| 1305 |
+
emitter.emit_line(f"(({struct_name} *)type)->{attr} = {wrapper_name};")
|
| 1306 |
+
return success()
|
| 1307 |
+
|
| 1308 |
+
if not any(fn.decl.is_coroutine for fn in cl.methods.values()):
|
| 1309 |
+
return success()
|
| 1310 |
+
|
| 1311 |
+
emitter.emit_line("PyTypeObject *tp = (PyTypeObject *)type;")
|
| 1312 |
+
|
| 1313 |
+
for fn in cl.methods.values():
|
| 1314 |
+
if not fn.decl.is_coroutine:
|
| 1315 |
+
continue
|
| 1316 |
+
|
| 1317 |
+
name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)
|
| 1318 |
+
wrapper_name = emit_instance(fn, name)
|
| 1319 |
+
name_obj = f"{wrapper_name}_name"
|
| 1320 |
+
emitter.emit_line(f'PyObject *{name_obj} = PyUnicode_FromString("{fn.name}");')
|
| 1321 |
+
emitter.emit_line(f"if (unlikely(!{name_obj}))")
|
| 1322 |
+
emitter.emit_line(error_stmt)
|
| 1323 |
+
emitter.emit_line(f"if (PyDict_SetItem(tp->tp_dict, {name_obj}, {wrapper_name}) < 0)")
|
| 1324 |
+
emitter.emit_line(error_stmt)
|
| 1325 |
+
|
| 1326 |
+
return success()
|
micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.py
ADDED
|
@@ -0,0 +1,993 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Code generation for native function bodies."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Final
|
| 6 |
+
|
| 7 |
+
from mypyc.analysis.blockfreq import frequently_executed_blocks
|
| 8 |
+
from mypyc.codegen.emit import (
|
| 9 |
+
DEBUG_ERRORS,
|
| 10 |
+
PREFIX_MAP,
|
| 11 |
+
Emitter,
|
| 12 |
+
TracebackAndGotoHandler,
|
| 13 |
+
c_array_initializer,
|
| 14 |
+
)
|
| 15 |
+
from mypyc.common import GENERATOR_ATTRIBUTE_PREFIX, HAVE_IMMORTAL, NATIVE_PREFIX, REG_PREFIX
|
| 16 |
+
from mypyc.ir.class_ir import ClassIR
|
| 17 |
+
from mypyc.ir.func_ir import FUNC_CLASSMETHOD, FUNC_STATICMETHOD, FuncDecl, FuncIR, all_values
|
| 18 |
+
from mypyc.ir.ops import (
|
| 19 |
+
ERR_FALSE,
|
| 20 |
+
NAMESPACE_TYPE,
|
| 21 |
+
Assign,
|
| 22 |
+
AssignMulti,
|
| 23 |
+
BasicBlock,
|
| 24 |
+
Box,
|
| 25 |
+
Branch,
|
| 26 |
+
Call,
|
| 27 |
+
CallC,
|
| 28 |
+
Cast,
|
| 29 |
+
ComparisonOp,
|
| 30 |
+
ControlOp,
|
| 31 |
+
CString,
|
| 32 |
+
DecRef,
|
| 33 |
+
Extend,
|
| 34 |
+
Float,
|
| 35 |
+
FloatComparisonOp,
|
| 36 |
+
FloatNeg,
|
| 37 |
+
FloatOp,
|
| 38 |
+
GetAttr,
|
| 39 |
+
GetElement,
|
| 40 |
+
GetElementPtr,
|
| 41 |
+
Goto,
|
| 42 |
+
IncRef,
|
| 43 |
+
InitStatic,
|
| 44 |
+
Integer,
|
| 45 |
+
IntOp,
|
| 46 |
+
KeepAlive,
|
| 47 |
+
LoadAddress,
|
| 48 |
+
LoadErrorValue,
|
| 49 |
+
LoadGlobal,
|
| 50 |
+
LoadLiteral,
|
| 51 |
+
LoadMem,
|
| 52 |
+
LoadStatic,
|
| 53 |
+
MethodCall,
|
| 54 |
+
Op,
|
| 55 |
+
OpVisitor,
|
| 56 |
+
PrimitiveOp,
|
| 57 |
+
RaiseStandardError,
|
| 58 |
+
Register,
|
| 59 |
+
Return,
|
| 60 |
+
SetAttr,
|
| 61 |
+
SetElement,
|
| 62 |
+
SetMem,
|
| 63 |
+
Truncate,
|
| 64 |
+
TupleGet,
|
| 65 |
+
TupleSet,
|
| 66 |
+
Unborrow,
|
| 67 |
+
Unbox,
|
| 68 |
+
Undef,
|
| 69 |
+
Unreachable,
|
| 70 |
+
Value,
|
| 71 |
+
)
|
| 72 |
+
from mypyc.ir.pprint import generate_names_for_ir
|
| 73 |
+
from mypyc.ir.rtypes import (
|
| 74 |
+
RArray,
|
| 75 |
+
RInstance,
|
| 76 |
+
RStruct,
|
| 77 |
+
RTuple,
|
| 78 |
+
RType,
|
| 79 |
+
RVec,
|
| 80 |
+
is_bool_or_bit_rprimitive,
|
| 81 |
+
is_int32_rprimitive,
|
| 82 |
+
is_int64_rprimitive,
|
| 83 |
+
is_int_rprimitive,
|
| 84 |
+
is_none_rprimitive,
|
| 85 |
+
is_pointer_rprimitive,
|
| 86 |
+
is_tagged,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def native_function_type(fn: FuncIR, emitter: Emitter) -> str:
|
| 91 |
+
args = ", ".join(emitter.ctype(arg.type) for arg in fn.args) or "void"
|
| 92 |
+
ret = emitter.ctype(fn.ret_type)
|
| 93 |
+
return f"{ret} (*)({args})"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def native_function_header(fn: FuncDecl, emitter: Emitter) -> str:
|
| 97 |
+
args = []
|
| 98 |
+
for arg in fn.sig.args:
|
| 99 |
+
args.append(f"{emitter.ctype_spaced(arg.type)}{REG_PREFIX}{arg.name}")
|
| 100 |
+
|
| 101 |
+
return "{ret_type}{name}({args})".format(
|
| 102 |
+
ret_type=emitter.ctype_spaced(fn.sig.ret_type),
|
| 103 |
+
name=emitter.native_function_name(fn),
|
| 104 |
+
args=", ".join(args) or "void",
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def generate_native_function(
|
| 109 |
+
fn: FuncIR, emitter: Emitter, source_path: str, module_name: str
|
| 110 |
+
) -> None:
|
| 111 |
+
declarations = Emitter(emitter.context)
|
| 112 |
+
names = generate_names_for_ir(fn.arg_regs, fn.blocks)
|
| 113 |
+
body = Emitter(emitter.context, names)
|
| 114 |
+
visitor = FunctionEmitterVisitor(body, declarations, source_path, module_name)
|
| 115 |
+
|
| 116 |
+
declarations.emit_line(f"{native_function_header(fn.decl, emitter)} {{")
|
| 117 |
+
body.indent()
|
| 118 |
+
|
| 119 |
+
for r in all_values(fn.arg_regs, fn.blocks):
|
| 120 |
+
if isinstance(r.type, RTuple):
|
| 121 |
+
emitter.declare_tuple_struct(r.type)
|
| 122 |
+
if isinstance(r.type, RArray):
|
| 123 |
+
continue # Special: declared on first assignment
|
| 124 |
+
|
| 125 |
+
if r in fn.arg_regs:
|
| 126 |
+
continue # Skip the arguments
|
| 127 |
+
|
| 128 |
+
ctype = emitter.ctype_spaced(r.type)
|
| 129 |
+
init = ""
|
| 130 |
+
declarations.emit_line(
|
| 131 |
+
"{ctype}{prefix}{name}{init};".format(
|
| 132 |
+
ctype=ctype, prefix=REG_PREFIX, name=names[r], init=init
|
| 133 |
+
)
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
# Before we emit the blocks, give them all labels
|
| 137 |
+
blocks = fn.blocks
|
| 138 |
+
for i, block in enumerate(blocks):
|
| 139 |
+
block.label = i
|
| 140 |
+
|
| 141 |
+
# Find blocks that are never jumped to or are only jumped to from the
|
| 142 |
+
# block directly above it. This allows for more labels and gotos to be
|
| 143 |
+
# eliminated during code generation.
|
| 144 |
+
for block in fn.blocks:
|
| 145 |
+
terminator = block.terminator
|
| 146 |
+
assert isinstance(terminator, ControlOp), terminator
|
| 147 |
+
|
| 148 |
+
for target in terminator.targets():
|
| 149 |
+
is_next_block = target.label == block.label + 1
|
| 150 |
+
|
| 151 |
+
# Always emit labels for GetAttr error checks since the emit code that
|
| 152 |
+
# generates them will add instructions between the branch and the
|
| 153 |
+
# next label, causing the label to be wrongly removed. A better
|
| 154 |
+
# solution would be to change the IR so that it adds a basic block
|
| 155 |
+
# in between the calls.
|
| 156 |
+
is_problematic_op = isinstance(terminator, Branch) and any(
|
| 157 |
+
isinstance(s, GetAttr) for s in terminator.sources()
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
if not is_next_block or is_problematic_op:
|
| 161 |
+
fn.blocks[target.label].referenced = True
|
| 162 |
+
|
| 163 |
+
common = frequently_executed_blocks(fn.blocks[0])
|
| 164 |
+
|
| 165 |
+
for i in range(len(blocks)):
|
| 166 |
+
block = blocks[i]
|
| 167 |
+
visitor.rare = block not in common
|
| 168 |
+
next_block = None
|
| 169 |
+
if i + 1 < len(blocks):
|
| 170 |
+
next_block = blocks[i + 1]
|
| 171 |
+
body.emit_label(block)
|
| 172 |
+
visitor.next_block = next_block
|
| 173 |
+
|
| 174 |
+
ops = block.ops
|
| 175 |
+
visitor.ops = ops
|
| 176 |
+
visitor.op_index = 0
|
| 177 |
+
while visitor.op_index < len(ops):
|
| 178 |
+
ops[visitor.op_index].accept(visitor)
|
| 179 |
+
visitor.op_index += 1
|
| 180 |
+
|
| 181 |
+
body.emit_line("}")
|
| 182 |
+
|
| 183 |
+
emitter.emit_from_emitter(declarations)
|
| 184 |
+
emitter.emit_from_emitter(body)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class FunctionEmitterVisitor(OpVisitor[None]):
|
| 188 |
+
def __init__(
|
| 189 |
+
self, emitter: Emitter, declarations: Emitter, source_path: str, module_name: str
|
| 190 |
+
) -> None:
|
| 191 |
+
self.emitter = emitter
|
| 192 |
+
self.names = emitter.names
|
| 193 |
+
self.declarations = declarations
|
| 194 |
+
self.source_path = source_path
|
| 195 |
+
self.module_name = module_name
|
| 196 |
+
self.literals = emitter.context.literals
|
| 197 |
+
self.rare = False
|
| 198 |
+
# Next basic block to be processed after the current one (if any), set by caller
|
| 199 |
+
self.next_block: BasicBlock | None = None
|
| 200 |
+
# Ops in the basic block currently being processed, set by caller
|
| 201 |
+
self.ops: list[Op] = []
|
| 202 |
+
# Current index within ops; visit methods can increment this to skip/merge ops
|
| 203 |
+
self.op_index = 0
|
| 204 |
+
|
| 205 |
+
def temp_name(self) -> str:
|
| 206 |
+
return self.emitter.temp_name()
|
| 207 |
+
|
| 208 |
+
def visit_goto(self, op: Goto) -> None:
|
| 209 |
+
if op.label is not self.next_block:
|
| 210 |
+
self.emit_line("goto %s;" % self.label(op.label))
|
| 211 |
+
|
| 212 |
+
def error_value_check(self, value: Value, compare: str) -> str:
|
| 213 |
+
typ = value.type
|
| 214 |
+
if isinstance(typ, RTuple):
|
| 215 |
+
# TODO: What about empty tuple?
|
| 216 |
+
return self.emitter.tuple_undefined_check_cond(
|
| 217 |
+
typ, self.reg(value), self.c_error_value, compare
|
| 218 |
+
)
|
| 219 |
+
elif isinstance(typ, RVec):
|
| 220 |
+
# Error values for vecs are represented by a negative length.
|
| 221 |
+
vec_compare = ">=" if compare == "!=" else "<"
|
| 222 |
+
return f"{self.reg(value)}.len {vec_compare} 0"
|
| 223 |
+
else:
|
| 224 |
+
return f"{self.reg(value)} {compare} {self.c_error_value(typ)}"
|
| 225 |
+
|
| 226 |
+
def visit_branch(self, op: Branch) -> None:
|
| 227 |
+
true, false = op.true, op.false
|
| 228 |
+
negated = op.negated
|
| 229 |
+
negated_rare = False
|
| 230 |
+
if true is self.next_block and op.traceback_entry is None:
|
| 231 |
+
# Switch true/false since it avoids an else block.
|
| 232 |
+
true, false = false, true
|
| 233 |
+
negated = not negated
|
| 234 |
+
negated_rare = True
|
| 235 |
+
|
| 236 |
+
neg = "!" if negated else ""
|
| 237 |
+
cond = ""
|
| 238 |
+
if op.op == Branch.BOOL:
|
| 239 |
+
expr_result = self.reg(op.value)
|
| 240 |
+
cond = f"{neg}{expr_result}"
|
| 241 |
+
elif op.op == Branch.IS_ERROR:
|
| 242 |
+
compare = "!=" if negated else "=="
|
| 243 |
+
cond = self.error_value_check(op.value, compare)
|
| 244 |
+
else:
|
| 245 |
+
assert False, "Invalid branch"
|
| 246 |
+
|
| 247 |
+
# For error checks, tell the compiler the branch is unlikely
|
| 248 |
+
if op.traceback_entry is not None or op.rare:
|
| 249 |
+
if not negated_rare:
|
| 250 |
+
cond = f"unlikely({cond})"
|
| 251 |
+
else:
|
| 252 |
+
cond = f"likely({cond})"
|
| 253 |
+
|
| 254 |
+
if false is self.next_block:
|
| 255 |
+
if op.traceback_entry is None:
|
| 256 |
+
if true is not self.next_block:
|
| 257 |
+
self.emit_line(f"if ({cond}) goto {self.label(true)};")
|
| 258 |
+
else:
|
| 259 |
+
self.emit_line(f"if ({cond}) {{")
|
| 260 |
+
self.emit_traceback(op)
|
| 261 |
+
self.emit_lines("goto %s;" % self.label(true), "}")
|
| 262 |
+
else:
|
| 263 |
+
self.emit_line(f"if ({cond}) {{")
|
| 264 |
+
self.emit_traceback(op)
|
| 265 |
+
|
| 266 |
+
if true is not self.next_block:
|
| 267 |
+
self.emit_line("goto %s;" % self.label(true))
|
| 268 |
+
|
| 269 |
+
self.emit_lines("} else", " goto %s;" % self.label(false))
|
| 270 |
+
|
| 271 |
+
def visit_return(self, op: Return) -> None:
|
| 272 |
+
value_str = self.reg(op.value)
|
| 273 |
+
self.emit_line("return %s;" % value_str)
|
| 274 |
+
|
| 275 |
+
def visit_tuple_set(self, op: TupleSet) -> None:
|
| 276 |
+
dest = self.reg(op)
|
| 277 |
+
tuple_type = op.tuple_type
|
| 278 |
+
self.emitter.declare_tuple_struct(tuple_type)
|
| 279 |
+
if len(op.items) == 0: # empty tuple
|
| 280 |
+
self.emit_line(f"{dest}.empty_struct_error_flag = 0;")
|
| 281 |
+
else:
|
| 282 |
+
for i, item in enumerate(op.items):
|
| 283 |
+
self.emit_line(f"{dest}.f{i} = {self.reg(item)};")
|
| 284 |
+
|
| 285 |
+
def visit_assign(self, op: Assign) -> None:
|
| 286 |
+
dest = self.reg(op.dest)
|
| 287 |
+
src = self.reg(op.src)
|
| 288 |
+
# clang whines about self assignment (which we might generate
|
| 289 |
+
# for some casts), so don't emit it.
|
| 290 |
+
if dest != src:
|
| 291 |
+
src_type = op.src.type
|
| 292 |
+
dest_type = op.dest.type
|
| 293 |
+
if src_type.is_unboxed and not dest_type.is_unboxed:
|
| 294 |
+
# We sometimes assign from an integer prepresentation of a pointer
|
| 295 |
+
# to a real pointer, and C compilers insist on a cast.
|
| 296 |
+
src = f"(void *){src}"
|
| 297 |
+
elif not src_type.is_unboxed and dest_type.is_unboxed:
|
| 298 |
+
# We sometimes assign a pointer to an integer type (e.g. to create
|
| 299 |
+
# tagged pointers), and here we need an explicit cast.
|
| 300 |
+
src = f"({self.emitter.ctype(dest_type)}){src}"
|
| 301 |
+
self.emit_line(f"{dest} = {src};")
|
| 302 |
+
|
| 303 |
+
def visit_assign_multi(self, op: AssignMulti) -> None:
|
| 304 |
+
typ = op.dest.type
|
| 305 |
+
assert isinstance(typ, RArray), typ
|
| 306 |
+
dest = self.reg(op.dest)
|
| 307 |
+
# RArray values can only be assigned to once, so we can always
|
| 308 |
+
# declare them on initialization.
|
| 309 |
+
self.emit_line(
|
| 310 |
+
"%s%s[%d] = %s;"
|
| 311 |
+
% (
|
| 312 |
+
self.emitter.ctype_spaced(typ.item_type),
|
| 313 |
+
dest,
|
| 314 |
+
len(op.src),
|
| 315 |
+
c_array_initializer([self.reg(s) for s in op.src], indented=True),
|
| 316 |
+
)
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
def visit_load_error_value(self, op: LoadErrorValue) -> None:
|
| 320 |
+
reg = self.reg(op)
|
| 321 |
+
if isinstance(op.type, RTuple):
|
| 322 |
+
values = [self.c_undefined_value(item) for item in op.type.types]
|
| 323 |
+
tmp = self.temp_name()
|
| 324 |
+
self.emit_line("{} {} = {{ {} }};".format(self.ctype(op.type), tmp, ", ".join(values)))
|
| 325 |
+
self.emit_line(f"{reg} = {tmp};")
|
| 326 |
+
elif isinstance(op.type, RVec):
|
| 327 |
+
self.emitter.set_undefined_value(reg, op.type)
|
| 328 |
+
else:
|
| 329 |
+
self.emit_line(f"{self.reg(op)} = {self.c_error_value(op.type)};")
|
| 330 |
+
|
| 331 |
+
def visit_load_literal(self, op: LoadLiteral) -> None:
|
| 332 |
+
index = self.literals.literal_index(op.value)
|
| 333 |
+
if not is_int_rprimitive(op.type):
|
| 334 |
+
self.emit_line("%s = CPyStatics[%d];" % (self.reg(op), index), ann=op.value)
|
| 335 |
+
else:
|
| 336 |
+
self.emit_line(
|
| 337 |
+
"%s = (CPyTagged)CPyStatics[%d] | 1;" % (self.reg(op), index), ann=op.value
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
def get_attr_expr(self, obj: str, op: GetAttr | SetAttr, decl_cl: ClassIR) -> str:
|
| 341 |
+
"""Generate attribute accessor for normal (non-property) access.
|
| 342 |
+
|
| 343 |
+
This either has a form like obj->attr_name for attributes defined in non-trait
|
| 344 |
+
classes, and *(obj + attr_offset) for attributes defined by traits. We also
|
| 345 |
+
insert all necessary C casts here.
|
| 346 |
+
"""
|
| 347 |
+
cast = f"({op.class_type.struct_name(self.emitter.names)} *)"
|
| 348 |
+
if decl_cl.is_trait and op.class_type.class_ir.is_trait:
|
| 349 |
+
# For pure trait access find the offset first, offsets
|
| 350 |
+
# are ordered by attribute position in the cl.attributes dict.
|
| 351 |
+
# TODO: pre-calculate the mapping to make this faster.
|
| 352 |
+
trait_attr_index = list(decl_cl.attributes).index(op.attr)
|
| 353 |
+
# TODO: reuse these names somehow?
|
| 354 |
+
offset = self.emitter.temp_name()
|
| 355 |
+
self.declarations.emit_line(f"size_t {offset};")
|
| 356 |
+
self.emitter.emit_line(
|
| 357 |
+
"{} = {};".format(
|
| 358 |
+
offset,
|
| 359 |
+
"CPy_FindAttrOffset({}, {}, {})".format(
|
| 360 |
+
self.emitter.type_struct_name(decl_cl),
|
| 361 |
+
f"({cast}{obj})->vtable",
|
| 362 |
+
trait_attr_index,
|
| 363 |
+
),
|
| 364 |
+
)
|
| 365 |
+
)
|
| 366 |
+
attr_cast = f"({self.ctype(op.class_type.attr_type(op.attr))} *)"
|
| 367 |
+
return f"*{attr_cast}((char *){obj} + {offset})"
|
| 368 |
+
else:
|
| 369 |
+
# Cast to something non-trait. Note: for this to work, all struct
|
| 370 |
+
# members for non-trait classes must obey monotonic linear growth.
|
| 371 |
+
if op.class_type.class_ir.is_trait:
|
| 372 |
+
assert not decl_cl.is_trait
|
| 373 |
+
cast = f"({decl_cl.struct_name(self.emitter.names)} *)"
|
| 374 |
+
return f"({cast}{obj})->{self.emitter.attr(op.attr)}"
|
| 375 |
+
|
| 376 |
+
def visit_get_attr(self, op: GetAttr) -> None:
|
| 377 |
+
if op.allow_error_value:
|
| 378 |
+
self.get_attr_with_allow_error_value(op)
|
| 379 |
+
return
|
| 380 |
+
dest = self.reg(op)
|
| 381 |
+
obj = self.reg(op.obj)
|
| 382 |
+
rtype = op.class_type
|
| 383 |
+
cl = rtype.class_ir
|
| 384 |
+
attr_rtype, decl_cl = cl.attr_details(op.attr)
|
| 385 |
+
prefer_method = cl.is_trait and attr_rtype.error_overlap
|
| 386 |
+
if cl.get_method(op.attr, prefer_method=prefer_method):
|
| 387 |
+
# Properties are essentially methods, so use vtable access for them.
|
| 388 |
+
if cl.is_method_final(op.attr):
|
| 389 |
+
self.emit_method_call(f"{dest} = ", op.obj, op.attr, [])
|
| 390 |
+
else:
|
| 391 |
+
version = "_TRAIT" if cl.is_trait else ""
|
| 392 |
+
self.emit_line(
|
| 393 |
+
"%s = CPY_GET_ATTR%s(%s, %s, %d, %s, %s); /* %s */"
|
| 394 |
+
% (
|
| 395 |
+
dest,
|
| 396 |
+
version,
|
| 397 |
+
obj,
|
| 398 |
+
self.emitter.type_struct_name(rtype.class_ir),
|
| 399 |
+
rtype.getter_index(op.attr),
|
| 400 |
+
rtype.struct_name(self.names),
|
| 401 |
+
self.ctype(rtype.attr_type(op.attr)),
|
| 402 |
+
op.attr,
|
| 403 |
+
)
|
| 404 |
+
)
|
| 405 |
+
else:
|
| 406 |
+
# Otherwise, use direct or offset struct access.
|
| 407 |
+
attr_expr = self.get_attr_expr(obj, op, decl_cl)
|
| 408 |
+
self.emitter.emit_line(f"{dest} = {attr_expr};")
|
| 409 |
+
always_defined = cl.is_always_defined(op.attr)
|
| 410 |
+
merged_branch = None
|
| 411 |
+
if not always_defined:
|
| 412 |
+
self.emitter.emit_undefined_attr_check(
|
| 413 |
+
attr_rtype, dest, "==", obj, op.attr, cl, unlikely=True
|
| 414 |
+
)
|
| 415 |
+
branch = self.next_branch()
|
| 416 |
+
if branch is not None:
|
| 417 |
+
if (
|
| 418 |
+
branch.value is op
|
| 419 |
+
and branch.op == Branch.IS_ERROR
|
| 420 |
+
and branch.traceback_entry is not None
|
| 421 |
+
and not branch.negated
|
| 422 |
+
):
|
| 423 |
+
# Generate code for the following branch here to avoid
|
| 424 |
+
# redundant branches in the generated code.
|
| 425 |
+
self.emit_attribute_error(branch, cl.name, op.attr)
|
| 426 |
+
self.emit_line("goto %s;" % self.label(branch.true))
|
| 427 |
+
merged_branch = branch
|
| 428 |
+
self.emitter.emit_line("}")
|
| 429 |
+
if not merged_branch:
|
| 430 |
+
exc_class = "PyExc_AttributeError"
|
| 431 |
+
self.emitter.emit_line(
|
| 432 |
+
'PyErr_SetString({}, "attribute {} of {} undefined");'.format(
|
| 433 |
+
exc_class,
|
| 434 |
+
repr(op.attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX)),
|
| 435 |
+
repr(cl.name),
|
| 436 |
+
)
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
if attr_rtype.is_refcounted and not op.is_borrowed:
|
| 440 |
+
if not merged_branch and not always_defined:
|
| 441 |
+
self.emitter.emit_line("} else {")
|
| 442 |
+
self.emitter.emit_inc_ref(dest, attr_rtype)
|
| 443 |
+
if merged_branch:
|
| 444 |
+
if merged_branch.false is not self.next_block:
|
| 445 |
+
self.emit_line("goto %s;" % self.label(merged_branch.false))
|
| 446 |
+
self.op_index += 1
|
| 447 |
+
elif not always_defined:
|
| 448 |
+
self.emitter.emit_line("}")
|
| 449 |
+
|
| 450 |
+
def get_attr_with_allow_error_value(self, op: GetAttr) -> None:
|
| 451 |
+
"""Handle GetAttr with allow_error_value=True.
|
| 452 |
+
|
| 453 |
+
This allows NULL or other error value without raising AttributeError.
|
| 454 |
+
"""
|
| 455 |
+
dest = self.reg(op)
|
| 456 |
+
obj = self.reg(op.obj)
|
| 457 |
+
rtype = op.class_type
|
| 458 |
+
cl = rtype.class_ir
|
| 459 |
+
attr_rtype, decl_cl = cl.attr_details(op.attr)
|
| 460 |
+
|
| 461 |
+
# Direct struct access without NULL check
|
| 462 |
+
attr_expr = self.get_attr_expr(obj, op, decl_cl)
|
| 463 |
+
self.emitter.emit_line(f"{dest} = {attr_expr};")
|
| 464 |
+
|
| 465 |
+
# Only emit inc_ref if not NULL
|
| 466 |
+
if attr_rtype.is_refcounted and not op.is_borrowed:
|
| 467 |
+
check = self.error_value_check(op, "!=")
|
| 468 |
+
self.emitter.emit_line(f"if ({check}) {{")
|
| 469 |
+
self.emitter.emit_inc_ref(dest, attr_rtype)
|
| 470 |
+
self.emitter.emit_line("}")
|
| 471 |
+
|
| 472 |
+
def next_branch(self) -> Branch | None:
|
| 473 |
+
if self.op_index + 1 < len(self.ops):
|
| 474 |
+
next_op = self.ops[self.op_index + 1]
|
| 475 |
+
if isinstance(next_op, Branch):
|
| 476 |
+
return next_op
|
| 477 |
+
return None
|
| 478 |
+
|
| 479 |
+
def visit_set_attr(self, op: SetAttr) -> None:
|
| 480 |
+
if op.error_kind == ERR_FALSE:
|
| 481 |
+
dest = self.reg(op)
|
| 482 |
+
obj = self.reg(op.obj)
|
| 483 |
+
src = self.reg(op.src)
|
| 484 |
+
rtype = op.class_type
|
| 485 |
+
cl = rtype.class_ir
|
| 486 |
+
attr_rtype, decl_cl = cl.attr_details(op.attr)
|
| 487 |
+
if op.is_propset:
|
| 488 |
+
# Again, use vtable access for properties...
|
| 489 |
+
assert not op.is_init and op.error_kind == ERR_FALSE, "%s %d %d %s" % (
|
| 490 |
+
op.attr,
|
| 491 |
+
op.is_init,
|
| 492 |
+
op.error_kind,
|
| 493 |
+
rtype,
|
| 494 |
+
)
|
| 495 |
+
version = "_TRAIT" if cl.is_trait else ""
|
| 496 |
+
self.emit_line(
|
| 497 |
+
"%s = CPY_SET_ATTR%s(%s, %s, %d, %s, %s, %s); /* %s */"
|
| 498 |
+
% (
|
| 499 |
+
dest,
|
| 500 |
+
version,
|
| 501 |
+
obj,
|
| 502 |
+
self.emitter.type_struct_name(rtype.class_ir),
|
| 503 |
+
rtype.setter_index(op.attr),
|
| 504 |
+
src,
|
| 505 |
+
rtype.struct_name(self.names),
|
| 506 |
+
self.ctype(rtype.attr_type(op.attr)),
|
| 507 |
+
op.attr,
|
| 508 |
+
)
|
| 509 |
+
)
|
| 510 |
+
else:
|
| 511 |
+
# ...and struct access for normal attributes.
|
| 512 |
+
attr_expr = self.get_attr_expr(obj, op, decl_cl)
|
| 513 |
+
if not op.is_init and attr_rtype.is_refcounted:
|
| 514 |
+
# This is not an initialization (where we know that the attribute was
|
| 515 |
+
# previously undefined), so decref the old value.
|
| 516 |
+
always_defined = cl.is_always_defined(op.attr)
|
| 517 |
+
if not always_defined:
|
| 518 |
+
self.emitter.emit_undefined_attr_check(
|
| 519 |
+
attr_rtype, attr_expr, "!=", obj, op.attr, cl
|
| 520 |
+
)
|
| 521 |
+
self.emitter.emit_dec_ref(attr_expr, attr_rtype)
|
| 522 |
+
if not always_defined:
|
| 523 |
+
self.emitter.emit_line("}")
|
| 524 |
+
elif attr_rtype.error_overlap and not cl.is_always_defined(op.attr):
|
| 525 |
+
# If there is overlap with the error value, update bitmap to mark
|
| 526 |
+
# attribute as defined.
|
| 527 |
+
self.emitter.emit_attr_bitmap_set(src, obj, attr_rtype, cl, op.attr)
|
| 528 |
+
|
| 529 |
+
# This steals the reference to src, so we don't need to increment the arg
|
| 530 |
+
self.emitter.emit_line(f"{attr_expr} = {src};")
|
| 531 |
+
if op.error_kind == ERR_FALSE:
|
| 532 |
+
self.emitter.emit_line(f"{dest} = 1;")
|
| 533 |
+
|
| 534 |
+
def visit_load_static(self, op: LoadStatic) -> None:
|
| 535 |
+
dest = self.reg(op)
|
| 536 |
+
prefix = PREFIX_MAP[op.namespace]
|
| 537 |
+
name = self.emitter.static_name(op.identifier, op.module_name, prefix)
|
| 538 |
+
if op.namespace == NAMESPACE_TYPE:
|
| 539 |
+
name = "(PyObject *)%s" % name
|
| 540 |
+
self.emit_line(f"{dest} = {name};", ann=op.ann)
|
| 541 |
+
|
| 542 |
+
def visit_init_static(self, op: InitStatic) -> None:
|
| 543 |
+
value = self.reg(op.value)
|
| 544 |
+
prefix = PREFIX_MAP[op.namespace]
|
| 545 |
+
name = self.emitter.static_name(op.identifier, op.module_name, prefix)
|
| 546 |
+
if op.namespace == NAMESPACE_TYPE:
|
| 547 |
+
value = "(PyTypeObject *)%s" % value
|
| 548 |
+
self.emit_line(f"{name} = {value};")
|
| 549 |
+
self.emit_inc_ref(name, op.value.type)
|
| 550 |
+
|
| 551 |
+
def visit_tuple_get(self, op: TupleGet) -> None:
|
| 552 |
+
dest = self.reg(op)
|
| 553 |
+
src = self.reg(op.src)
|
| 554 |
+
self.emit_line(f"{dest} = {src}.f{op.index};")
|
| 555 |
+
if not op.is_borrowed:
|
| 556 |
+
self.emit_inc_ref(dest, op.type)
|
| 557 |
+
|
| 558 |
+
def get_dest_assign(self, dest: Value) -> str:
|
| 559 |
+
if not dest.is_void:
|
| 560 |
+
return self.reg(dest) + " = "
|
| 561 |
+
else:
|
| 562 |
+
return ""
|
| 563 |
+
|
| 564 |
+
def visit_call(self, op: Call) -> None:
|
| 565 |
+
"""Call native function."""
|
| 566 |
+
dest = self.get_dest_assign(op)
|
| 567 |
+
args = ", ".join(self.reg(arg) for arg in op.args)
|
| 568 |
+
lib = self.emitter.get_group_prefix(op.fn)
|
| 569 |
+
cname = op.fn.cname(self.names)
|
| 570 |
+
self.emit_line(f"{dest}{lib}{NATIVE_PREFIX}{cname}({args});")
|
| 571 |
+
|
| 572 |
+
def visit_method_call(self, op: MethodCall) -> None:
|
| 573 |
+
"""Call native method."""
|
| 574 |
+
dest = self.get_dest_assign(op)
|
| 575 |
+
self.emit_method_call(dest, op.obj, op.method, op.args)
|
| 576 |
+
|
| 577 |
+
def emit_method_call(self, dest: str, op_obj: Value, name: str, op_args: list[Value]) -> None:
|
| 578 |
+
obj = self.reg(op_obj)
|
| 579 |
+
rtype = op_obj.type
|
| 580 |
+
assert isinstance(rtype, RInstance), rtype
|
| 581 |
+
class_ir = rtype.class_ir
|
| 582 |
+
method = rtype.class_ir.get_method(name)
|
| 583 |
+
assert method is not None
|
| 584 |
+
|
| 585 |
+
# Can we call the method directly, bypassing vtable?
|
| 586 |
+
is_direct = class_ir.is_method_final(name)
|
| 587 |
+
|
| 588 |
+
# The first argument gets omitted for static methods and
|
| 589 |
+
# turned into the class for class methods
|
| 590 |
+
obj_args = (
|
| 591 |
+
[]
|
| 592 |
+
if method.decl.kind == FUNC_STATICMETHOD
|
| 593 |
+
else [f"(PyObject *)Py_TYPE({obj})"] if method.decl.kind == FUNC_CLASSMETHOD else [obj]
|
| 594 |
+
)
|
| 595 |
+
args = ", ".join(obj_args + [self.reg(arg) for arg in op_args])
|
| 596 |
+
mtype = native_function_type(method, self.emitter)
|
| 597 |
+
version = "_TRAIT" if rtype.class_ir.is_trait else ""
|
| 598 |
+
if is_direct:
|
| 599 |
+
# Directly call method, without going through the vtable.
|
| 600 |
+
lib = self.emitter.get_group_prefix(method.decl)
|
| 601 |
+
self.emit_line(f"{dest}{lib}{NATIVE_PREFIX}{method.cname(self.names)}({args});")
|
| 602 |
+
else:
|
| 603 |
+
# Call using vtable.
|
| 604 |
+
method_idx = rtype.method_index(name)
|
| 605 |
+
self.emit_line(
|
| 606 |
+
"{}CPY_GET_METHOD{}({}, {}, {}, {}, {})({}); /* {} */".format(
|
| 607 |
+
dest,
|
| 608 |
+
version,
|
| 609 |
+
obj,
|
| 610 |
+
self.emitter.type_struct_name(rtype.class_ir),
|
| 611 |
+
method_idx,
|
| 612 |
+
rtype.struct_name(self.names),
|
| 613 |
+
mtype,
|
| 614 |
+
args,
|
| 615 |
+
name,
|
| 616 |
+
)
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
def visit_inc_ref(self, op: IncRef) -> None:
|
| 620 |
+
if (
|
| 621 |
+
isinstance(op.src, Box)
|
| 622 |
+
and (is_none_rprimitive(op.src.src.type) or is_bool_or_bit_rprimitive(op.src.src.type))
|
| 623 |
+
and HAVE_IMMORTAL
|
| 624 |
+
):
|
| 625 |
+
# On Python 3.12+, None/True/False are immortal, and we can skip inc ref
|
| 626 |
+
return
|
| 627 |
+
|
| 628 |
+
if isinstance(op.src, LoadLiteral) and HAVE_IMMORTAL:
|
| 629 |
+
value = op.src.value
|
| 630 |
+
# We can skip inc ref for immortal literals on Python 3.12+
|
| 631 |
+
if type(value) is int and -5 <= value <= 256:
|
| 632 |
+
# Small integers are immortal
|
| 633 |
+
return
|
| 634 |
+
|
| 635 |
+
src = self.reg(op.src)
|
| 636 |
+
self.emit_inc_ref(src, op.src.type)
|
| 637 |
+
|
| 638 |
+
def visit_dec_ref(self, op: DecRef) -> None:
|
| 639 |
+
src = self.reg(op.src)
|
| 640 |
+
self.emit_dec_ref(src, op.src.type, is_xdec=op.is_xdec)
|
| 641 |
+
|
| 642 |
+
def visit_box(self, op: Box) -> None:
|
| 643 |
+
self.emitter.emit_box(self.reg(op.src), self.reg(op), op.src.type, can_borrow=True)
|
| 644 |
+
|
| 645 |
+
def visit_cast(self, op: Cast) -> None:
|
| 646 |
+
if op.is_unchecked and op.is_borrowed:
|
| 647 |
+
self.emit_line(f"{self.reg(op)} = {self.reg(op.src)};")
|
| 648 |
+
return
|
| 649 |
+
branch = self.next_branch()
|
| 650 |
+
handler = None
|
| 651 |
+
if branch is not None:
|
| 652 |
+
if (
|
| 653 |
+
branch.value is op
|
| 654 |
+
and branch.op == Branch.IS_ERROR
|
| 655 |
+
and branch.traceback_entry is not None
|
| 656 |
+
and not branch.negated
|
| 657 |
+
and branch.false is self.next_block
|
| 658 |
+
):
|
| 659 |
+
# Generate code also for the following branch here to avoid
|
| 660 |
+
# redundant branches in the generated code.
|
| 661 |
+
handler = TracebackAndGotoHandler(
|
| 662 |
+
self.label(branch.true),
|
| 663 |
+
self.source_path,
|
| 664 |
+
self.module_name,
|
| 665 |
+
branch.traceback_entry,
|
| 666 |
+
)
|
| 667 |
+
self.op_index += 1
|
| 668 |
+
|
| 669 |
+
self.emitter.emit_cast(
|
| 670 |
+
self.reg(op.src), self.reg(op), op.type, src_type=op.src.type, error=handler
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
def visit_unbox(self, op: Unbox) -> None:
|
| 674 |
+
self.emitter.emit_unbox(self.reg(op.src), self.reg(op), op.type)
|
| 675 |
+
|
| 676 |
+
def visit_unreachable(self, op: Unreachable) -> None:
|
| 677 |
+
self.emitter.emit_line("CPy_Unreachable();")
|
| 678 |
+
|
| 679 |
+
def visit_raise_standard_error(self, op: RaiseStandardError) -> None:
|
| 680 |
+
# TODO: Better escaping of backspaces and such
|
| 681 |
+
if op.value is not None:
|
| 682 |
+
if isinstance(op.value, str):
|
| 683 |
+
message = op.value.replace('"', '\\"')
|
| 684 |
+
self.emitter.emit_line(f'PyErr_SetString(PyExc_{op.class_name}, "{message}");')
|
| 685 |
+
elif isinstance(op.value, Value):
|
| 686 |
+
self.emitter.emit_line(
|
| 687 |
+
"PyErr_SetObject(PyExc_{}, {});".format(
|
| 688 |
+
op.class_name, self.emitter.reg(op.value)
|
| 689 |
+
)
|
| 690 |
+
)
|
| 691 |
+
else:
|
| 692 |
+
assert False, "op value type must be either str or Value"
|
| 693 |
+
else:
|
| 694 |
+
self.emitter.emit_line(f"PyErr_SetNone(PyExc_{op.class_name});")
|
| 695 |
+
self.emitter.emit_line(f"{self.reg(op)} = 0;")
|
| 696 |
+
|
| 697 |
+
def visit_call_c(self, op: CallC) -> None:
|
| 698 |
+
if op.is_void:
|
| 699 |
+
dest = ""
|
| 700 |
+
else:
|
| 701 |
+
dest = self.get_dest_assign(op)
|
| 702 |
+
args = ", ".join(self.reg(arg) for arg in op.args)
|
| 703 |
+
self.emitter.emit_line(f"{dest}{op.function_name}({args});")
|
| 704 |
+
|
| 705 |
+
def visit_primitive_op(self, op: PrimitiveOp) -> None:
|
| 706 |
+
raise RuntimeError(
|
| 707 |
+
f"unexpected PrimitiveOp {op.desc.name}: they must be lowered before codegen"
|
| 708 |
+
)
|
| 709 |
+
|
| 710 |
+
def visit_truncate(self, op: Truncate) -> None:
|
| 711 |
+
dest = self.reg(op)
|
| 712 |
+
value = self.reg(op.src)
|
| 713 |
+
# for C backend the generated code are straight assignments
|
| 714 |
+
self.emit_line(f"{dest} = {value};")
|
| 715 |
+
|
| 716 |
+
def visit_extend(self, op: Extend) -> None:
|
| 717 |
+
dest = self.reg(op)
|
| 718 |
+
value = self.reg(op.src)
|
| 719 |
+
if op.signed:
|
| 720 |
+
src_cast = self.emit_signed_int_cast(op.src.type)
|
| 721 |
+
else:
|
| 722 |
+
src_cast = self.emit_unsigned_int_cast(op.src.type)
|
| 723 |
+
self.emit_line(f"{dest} = {src_cast}{value};")
|
| 724 |
+
|
| 725 |
+
def visit_load_global(self, op: LoadGlobal) -> None:
|
| 726 |
+
dest = self.reg(op)
|
| 727 |
+
self.emit_line(f"{dest} = {op.identifier};", ann=op.ann)
|
| 728 |
+
|
| 729 |
+
def visit_int_op(self, op: IntOp) -> None:
|
| 730 |
+
dest = self.reg(op)
|
| 731 |
+
lhs = self.reg(op.lhs)
|
| 732 |
+
rhs = self.reg(op.rhs)
|
| 733 |
+
if op.op == IntOp.RIGHT_SHIFT:
|
| 734 |
+
# Signed right shift
|
| 735 |
+
lhs = self.emit_signed_int_cast(op.lhs.type) + lhs
|
| 736 |
+
rhs = self.emit_signed_int_cast(op.rhs.type) + rhs
|
| 737 |
+
self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};")
|
| 738 |
+
|
| 739 |
+
def visit_comparison_op(self, op: ComparisonOp) -> None:
|
| 740 |
+
dest = self.reg(op)
|
| 741 |
+
lhs = self.reg(op.lhs)
|
| 742 |
+
rhs = self.reg(op.rhs)
|
| 743 |
+
lhs_cast = ""
|
| 744 |
+
rhs_cast = ""
|
| 745 |
+
if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE):
|
| 746 |
+
# Always signed comparison op
|
| 747 |
+
lhs_cast = self.emit_signed_int_cast(op.lhs.type)
|
| 748 |
+
rhs_cast = self.emit_signed_int_cast(op.rhs.type)
|
| 749 |
+
elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE):
|
| 750 |
+
# Always unsigned comparison op
|
| 751 |
+
lhs_cast = self.emit_unsigned_int_cast(op.lhs.type)
|
| 752 |
+
rhs_cast = self.emit_unsigned_int_cast(op.rhs.type)
|
| 753 |
+
elif isinstance(op.lhs, Integer) and op.lhs.value < 0:
|
| 754 |
+
# Force signed ==/!= with negative operand
|
| 755 |
+
rhs_cast = self.emit_signed_int_cast(op.rhs.type)
|
| 756 |
+
elif isinstance(op.rhs, Integer) and op.rhs.value < 0:
|
| 757 |
+
# Force signed ==/!= with negative operand
|
| 758 |
+
lhs_cast = self.emit_signed_int_cast(op.lhs.type)
|
| 759 |
+
self.emit_line(f"{dest} = {lhs_cast}{lhs} {op.op_str[op.op]} {rhs_cast}{rhs};")
|
| 760 |
+
|
| 761 |
+
def visit_float_op(self, op: FloatOp) -> None:
|
| 762 |
+
dest = self.reg(op)
|
| 763 |
+
lhs = self.reg(op.lhs)
|
| 764 |
+
rhs = self.reg(op.rhs)
|
| 765 |
+
if op.op != FloatOp.MOD:
|
| 766 |
+
self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};")
|
| 767 |
+
else:
|
| 768 |
+
# TODO: This may set errno as a side effect, that is a little sketchy.
|
| 769 |
+
self.emit_line(f"{dest} = fmod({lhs}, {rhs});")
|
| 770 |
+
|
| 771 |
+
def visit_float_neg(self, op: FloatNeg) -> None:
|
| 772 |
+
dest = self.reg(op)
|
| 773 |
+
src = self.reg(op.src)
|
| 774 |
+
self.emit_line(f"{dest} = -{src};")
|
| 775 |
+
|
| 776 |
+
def visit_float_comparison_op(self, op: FloatComparisonOp) -> None:
|
| 777 |
+
dest = self.reg(op)
|
| 778 |
+
lhs = self.reg(op.lhs)
|
| 779 |
+
rhs = self.reg(op.rhs)
|
| 780 |
+
self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};")
|
| 781 |
+
|
| 782 |
+
def visit_load_mem(self, op: LoadMem) -> None:
|
| 783 |
+
dest = self.reg(op)
|
| 784 |
+
src = self.reg(op.src)
|
| 785 |
+
# TODO: we shouldn't dereference to type that are pointer type so far
|
| 786 |
+
type = self.ctype(op.type)
|
| 787 |
+
self.emit_line(f"{dest} = *({type} *){src};")
|
| 788 |
+
if not op.is_borrowed:
|
| 789 |
+
self.emit_inc_ref(dest, op.type)
|
| 790 |
+
|
| 791 |
+
def visit_set_mem(self, op: SetMem) -> None:
|
| 792 |
+
dest = self.reg(op.dest)
|
| 793 |
+
src = self.reg(op.src)
|
| 794 |
+
dest_type = self.ctype(op.dest_type)
|
| 795 |
+
# clang whines about self assignment (which we might generate
|
| 796 |
+
# for some casts), so don't emit it.
|
| 797 |
+
if dest != src:
|
| 798 |
+
self.emit_line(f"*({dest_type} *){dest} = {src};")
|
| 799 |
+
|
| 800 |
+
def visit_get_element(self, op: GetElement) -> None:
|
| 801 |
+
dest = self.reg(op)
|
| 802 |
+
src = self.reg(op.src)
|
| 803 |
+
dest_type = self.ctype(op.type)
|
| 804 |
+
self.emit_line(f"{dest} = ({dest_type}){src}.{op.field};")
|
| 805 |
+
|
| 806 |
+
def visit_get_element_ptr(self, op: GetElementPtr) -> None:
|
| 807 |
+
dest = self.reg(op)
|
| 808 |
+
src = self.reg(op.src)
|
| 809 |
+
# TODO: support tuple type
|
| 810 |
+
assert isinstance(op.src_type, RStruct), op.src_type
|
| 811 |
+
assert op.field in op.src_type.names, "Invalid field name."
|
| 812 |
+
# Use offsetof to avoid undefined behavior when src is NULL
|
| 813 |
+
# (e.g., vec buf pointer for empty vecs). The &((T*)p)->field
|
| 814 |
+
# pattern is UB when p is NULL, which GCC -O3 can exploit.
|
| 815 |
+
self.emit_line(
|
| 816 |
+
"{} = ({})((CPyPtr){} + offsetof({}, {}));".format(
|
| 817 |
+
dest, op.type._ctype, src, op.src_type.name, op.field
|
| 818 |
+
)
|
| 819 |
+
)
|
| 820 |
+
|
| 821 |
+
def visit_set_element(self, op: SetElement) -> None:
|
| 822 |
+
dest = self.reg(op)
|
| 823 |
+
item = self.reg(op.item)
|
| 824 |
+
field = op.field
|
| 825 |
+
if isinstance(op.src, Undef):
|
| 826 |
+
# First assignment to an undefined struct is trivial.
|
| 827 |
+
self.emit_line(f"{dest}.{field} = {item};")
|
| 828 |
+
else:
|
| 829 |
+
# In the general case create a copy of the struct with a single
|
| 830 |
+
# item modified.
|
| 831 |
+
#
|
| 832 |
+
# TODO: Can we do better if only a subset of fields are initialized?
|
| 833 |
+
# TODO: Make this less verbose in the common case
|
| 834 |
+
# TODO: Support tuples (or use RStruct for tuples)?
|
| 835 |
+
src = self.reg(op.src)
|
| 836 |
+
src_type = op.src.type
|
| 837 |
+
assert isinstance(src_type, RStruct), src_type
|
| 838 |
+
init_items = []
|
| 839 |
+
for n in src_type.names:
|
| 840 |
+
if n != field:
|
| 841 |
+
init_items.append(f"{src}.{n}")
|
| 842 |
+
else:
|
| 843 |
+
init_items.append(item)
|
| 844 |
+
self.emit_line(f"{dest} = ({self.ctype(src_type)}) {{ {', '.join(init_items)} }};")
|
| 845 |
+
|
| 846 |
+
def visit_load_address(self, op: LoadAddress) -> None:
|
| 847 |
+
typ = op.type
|
| 848 |
+
dest = self.reg(op)
|
| 849 |
+
if isinstance(op.src, Register):
|
| 850 |
+
src = self.reg(op.src)
|
| 851 |
+
elif isinstance(op.src, LoadStatic):
|
| 852 |
+
prefix = PREFIX_MAP[op.src.namespace]
|
| 853 |
+
src = self.emitter.static_name(op.src.identifier, op.src.module_name, prefix)
|
| 854 |
+
else:
|
| 855 |
+
src = op.src
|
| 856 |
+
self.emit_line(f"{dest} = ({typ._ctype})&{src};")
|
| 857 |
+
|
| 858 |
+
def visit_keep_alive(self, op: KeepAlive) -> None:
|
| 859 |
+
# This is a no-op.
|
| 860 |
+
pass
|
| 861 |
+
|
| 862 |
+
def visit_unborrow(self, op: Unborrow) -> None:
|
| 863 |
+
# This is a no-op that propagates the source value.
|
| 864 |
+
dest = self.reg(op)
|
| 865 |
+
src = self.reg(op.src)
|
| 866 |
+
self.emit_line(f"{dest} = {src};")
|
| 867 |
+
|
| 868 |
+
# Helpers
|
| 869 |
+
|
| 870 |
+
def label(self, label: BasicBlock) -> str:
|
| 871 |
+
return self.emitter.label(label)
|
| 872 |
+
|
| 873 |
+
def reg(self, reg: Value) -> str:
|
| 874 |
+
if isinstance(reg, Integer):
|
| 875 |
+
val = reg.value
|
| 876 |
+
if val == 0 and is_pointer_rprimitive(reg.type):
|
| 877 |
+
return "NULL"
|
| 878 |
+
s = str(val)
|
| 879 |
+
if val >= (1 << 31):
|
| 880 |
+
# Avoid overflowing signed 32-bit int
|
| 881 |
+
if val >= (1 << 63):
|
| 882 |
+
s += "ULL"
|
| 883 |
+
else:
|
| 884 |
+
s += "LL"
|
| 885 |
+
elif val == -(1 << 63):
|
| 886 |
+
# Avoid overflowing C integer literal
|
| 887 |
+
s = "(-9223372036854775807LL - 1)"
|
| 888 |
+
elif val <= -(1 << 31):
|
| 889 |
+
s += "LL"
|
| 890 |
+
return s
|
| 891 |
+
elif isinstance(reg, Float):
|
| 892 |
+
r = repr(reg.value)
|
| 893 |
+
if r == "inf":
|
| 894 |
+
return "INFINITY"
|
| 895 |
+
elif r == "-inf":
|
| 896 |
+
return "-INFINITY"
|
| 897 |
+
elif r == "nan":
|
| 898 |
+
return "NAN"
|
| 899 |
+
return r
|
| 900 |
+
elif isinstance(reg, CString):
|
| 901 |
+
return '"' + encode_c_string_literal(reg.value) + '"'
|
| 902 |
+
else:
|
| 903 |
+
return self.emitter.reg(reg)
|
| 904 |
+
|
| 905 |
+
def ctype(self, rtype: RType) -> str:
|
| 906 |
+
return self.emitter.ctype(rtype)
|
| 907 |
+
|
| 908 |
+
def c_error_value(self, rtype: RType) -> str:
|
| 909 |
+
return self.emitter.c_error_value(rtype)
|
| 910 |
+
|
| 911 |
+
def c_undefined_value(self, rtype: RType) -> str:
|
| 912 |
+
return self.emitter.c_undefined_value(rtype)
|
| 913 |
+
|
| 914 |
+
def emit_line(self, line: str, *, ann: object = None) -> None:
|
| 915 |
+
self.emitter.emit_line(line, ann=ann)
|
| 916 |
+
|
| 917 |
+
def emit_lines(self, *lines: str) -> None:
|
| 918 |
+
self.emitter.emit_lines(*lines)
|
| 919 |
+
|
| 920 |
+
def emit_inc_ref(self, dest: str, rtype: RType) -> None:
|
| 921 |
+
self.emitter.emit_inc_ref(dest, rtype, rare=self.rare)
|
| 922 |
+
|
| 923 |
+
def emit_dec_ref(self, dest: str, rtype: RType, is_xdec: bool) -> None:
|
| 924 |
+
self.emitter.emit_dec_ref(dest, rtype, is_xdec=is_xdec, rare=self.rare)
|
| 925 |
+
|
| 926 |
+
def emit_declaration(self, line: str) -> None:
|
| 927 |
+
self.declarations.emit_line(line)
|
| 928 |
+
|
| 929 |
+
def emit_traceback(self, op: Branch) -> None:
|
| 930 |
+
if op.traceback_entry is not None:
|
| 931 |
+
self.emitter.emit_traceback(self.source_path, self.module_name, op.traceback_entry)
|
| 932 |
+
|
| 933 |
+
def emit_attribute_error(self, op: Branch, class_name: str, attr: str) -> None:
|
| 934 |
+
assert op.traceback_entry is not None
|
| 935 |
+
if self.emitter.context.strict_traceback_checks:
|
| 936 |
+
assert (
|
| 937 |
+
op.traceback_entry[1] >= 0
|
| 938 |
+
), "AttributeError traceback cannot have a negative line number"
|
| 939 |
+
globals_static = self.emitter.static_name("globals", self.module_name)
|
| 940 |
+
self.emit_line(
|
| 941 |
+
'CPy_AttributeError("%s", "%s", "%s", "%s", %d, %s);'
|
| 942 |
+
% (
|
| 943 |
+
self.source_path.replace("\\", "\\\\"),
|
| 944 |
+
op.traceback_entry[0],
|
| 945 |
+
class_name,
|
| 946 |
+
attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX),
|
| 947 |
+
op.traceback_entry[1],
|
| 948 |
+
globals_static,
|
| 949 |
+
)
|
| 950 |
+
)
|
| 951 |
+
if DEBUG_ERRORS:
|
| 952 |
+
self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");')
|
| 953 |
+
|
| 954 |
+
def emit_signed_int_cast(self, type: RType) -> str:
|
| 955 |
+
if is_tagged(type):
|
| 956 |
+
return "(Py_ssize_t)"
|
| 957 |
+
else:
|
| 958 |
+
return ""
|
| 959 |
+
|
| 960 |
+
def emit_unsigned_int_cast(self, type: RType) -> str:
|
| 961 |
+
if is_int32_rprimitive(type):
|
| 962 |
+
return "(uint32_t)"
|
| 963 |
+
elif is_int64_rprimitive(type):
|
| 964 |
+
return "(uint64_t)"
|
| 965 |
+
else:
|
| 966 |
+
return ""
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
_translation_table: Final[dict[int, str]] = {}
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
def encode_c_string_literal(b: bytes) -> str:
|
| 973 |
+
"""Convert bytestring to the C string literal syntax (with necessary escaping).
|
| 974 |
+
|
| 975 |
+
For example, b'foo\n' gets converted to 'foo\\n' (note that double quotes are not added).
|
| 976 |
+
"""
|
| 977 |
+
if not _translation_table:
|
| 978 |
+
# Initialize the translation table on the first call.
|
| 979 |
+
d = {
|
| 980 |
+
ord("\n"): "\\n",
|
| 981 |
+
ord("\r"): "\\r",
|
| 982 |
+
ord("\t"): "\\t",
|
| 983 |
+
ord('"'): '\\"',
|
| 984 |
+
ord("\\"): "\\\\",
|
| 985 |
+
}
|
| 986 |
+
for i in range(256):
|
| 987 |
+
if i not in d:
|
| 988 |
+
if i < 32 or i >= 127:
|
| 989 |
+
d[i] = "\\x%.2x" % i
|
| 990 |
+
else:
|
| 991 |
+
d[i] = chr(i)
|
| 992 |
+
_translation_table.update(str.maketrans(d))
|
| 993 |
+
return b.decode("latin1").translate(_translation_table)
|
micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.py
ADDED
|
@@ -0,0 +1,1494 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate C code for a Python C extension module from Python source code."""
|
| 2 |
+
|
| 3 |
+
# FIXME: Basically nothing in this file operates on the level of a
|
| 4 |
+
# single module and it should be renamed.
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
from collections.abc import Iterable
|
| 12 |
+
from typing import TypeVar
|
| 13 |
+
|
| 14 |
+
from mypy.build import (
|
| 15 |
+
BuildResult,
|
| 16 |
+
BuildSource,
|
| 17 |
+
State,
|
| 18 |
+
build,
|
| 19 |
+
compute_hash,
|
| 20 |
+
create_metastore,
|
| 21 |
+
get_cache_names,
|
| 22 |
+
sorted_components,
|
| 23 |
+
)
|
| 24 |
+
from mypy.errors import CompileError
|
| 25 |
+
from mypy.fscache import FileSystemCache
|
| 26 |
+
from mypy.nodes import MypyFile
|
| 27 |
+
from mypy.options import Options
|
| 28 |
+
from mypy.plugin import Plugin, ReportConfigContext
|
| 29 |
+
from mypy.util import hash_digest, json_dumps
|
| 30 |
+
from mypyc.analysis.capsule_deps import find_class_dependencies, find_implicit_op_dependencies
|
| 31 |
+
from mypyc.codegen.cstring import c_string_initializer
|
| 32 |
+
from mypyc.codegen.emit import (
|
| 33 |
+
Emitter,
|
| 34 |
+
EmitterContext,
|
| 35 |
+
HeaderDeclaration,
|
| 36 |
+
c_array_initializer,
|
| 37 |
+
native_function_doc_initializer,
|
| 38 |
+
)
|
| 39 |
+
from mypyc.codegen.emitclass import generate_class, generate_class_reuse, generate_class_type_decl
|
| 40 |
+
from mypyc.codegen.emitfunc import generate_native_function, native_function_header
|
| 41 |
+
from mypyc.codegen.emitwrapper import (
|
| 42 |
+
generate_legacy_wrapper_function,
|
| 43 |
+
generate_wrapper_function,
|
| 44 |
+
legacy_wrapper_function_header,
|
| 45 |
+
wrapper_function_header,
|
| 46 |
+
)
|
| 47 |
+
from mypyc.codegen.literals import Literals
|
| 48 |
+
from mypyc.common import (
|
| 49 |
+
EXT_SUFFIX,
|
| 50 |
+
IS_FREE_THREADED,
|
| 51 |
+
MODULE_PREFIX,
|
| 52 |
+
PREFIX,
|
| 53 |
+
RUNTIME_C_FILES,
|
| 54 |
+
TOP_LEVEL_NAME,
|
| 55 |
+
TYPE_VAR_PREFIX,
|
| 56 |
+
shared_lib_name,
|
| 57 |
+
short_id_from_name,
|
| 58 |
+
)
|
| 59 |
+
from mypyc.errors import Errors
|
| 60 |
+
from mypyc.ir.deps import LIBRT_BASE64, LIBRT_STRINGS, LIBRT_TIME, LIBRT_VECS, SourceDep
|
| 61 |
+
from mypyc.ir.func_ir import FuncIR
|
| 62 |
+
from mypyc.ir.module_ir import ModuleIR, ModuleIRs, deserialize_modules
|
| 63 |
+
from mypyc.ir.ops import DeserMaps, LoadLiteral
|
| 64 |
+
from mypyc.ir.rtypes import RType
|
| 65 |
+
from mypyc.irbuild.main import build_ir
|
| 66 |
+
from mypyc.irbuild.mapper import Mapper
|
| 67 |
+
from mypyc.irbuild.prepare import load_type_map
|
| 68 |
+
from mypyc.namegen import NameGenerator, exported_name
|
| 69 |
+
from mypyc.options import CompilerOptions
|
| 70 |
+
from mypyc.transform.copy_propagation import do_copy_propagation
|
| 71 |
+
from mypyc.transform.exceptions import insert_exception_handling
|
| 72 |
+
from mypyc.transform.flag_elimination import do_flag_elimination
|
| 73 |
+
from mypyc.transform.log_trace import insert_event_trace_logging
|
| 74 |
+
from mypyc.transform.lower import lower_ir
|
| 75 |
+
from mypyc.transform.refcount import insert_ref_count_opcodes
|
| 76 |
+
from mypyc.transform.spill import insert_spills
|
| 77 |
+
from mypyc.transform.uninit import insert_uninit_checks
|
| 78 |
+
|
| 79 |
+
# All the modules being compiled are divided into "groups". A group
|
| 80 |
+
# is a set of modules that are placed into the same shared library.
|
| 81 |
+
# Two common configurations are that every module is placed in a group
|
| 82 |
+
# by itself (fully separate compilation) and that every module is
|
| 83 |
+
# placed in the same group (fully whole-program compilation), but we
|
| 84 |
+
# support finer-grained control of the group as well.
|
| 85 |
+
#
|
| 86 |
+
# In fully whole-program compilation, we will generate N+1 extension
|
| 87 |
+
# modules: one shim per module and one shared library containing all
|
| 88 |
+
# the actual code.
|
| 89 |
+
# In fully separate compilation, we (unfortunately) will generate 2*N
|
| 90 |
+
# extension modules: one shim per module and also one library containing
|
| 91 |
+
# each module's actual code. (This might be fixable in the future,
|
| 92 |
+
# but allows a clean separation between setup of the export tables
|
| 93 |
+
# (see generate_export_table) and running module top levels.)
|
| 94 |
+
#
|
| 95 |
+
# A group is represented as a list of BuildSources containing all of
|
| 96 |
+
# its modules along with the name of the group. (Which can be None
|
| 97 |
+
# only if we are compiling only a single group with a single file in it
|
| 98 |
+
# and not using shared libraries).
|
| 99 |
+
Group = tuple[list[BuildSource], str | None]
|
| 100 |
+
Groups = list[Group]
|
| 101 |
+
|
| 102 |
+
# A list of (file name, file contents) pairs.
|
| 103 |
+
FileContents = list[tuple[str, str]]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class MarkedDeclaration:
|
| 107 |
+
"""Add a mark, useful for topological sort."""
|
| 108 |
+
|
| 109 |
+
def __init__(self, declaration: HeaderDeclaration, mark: bool) -> None:
|
| 110 |
+
self.declaration = declaration
|
| 111 |
+
self.mark = False
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class MypycPlugin(Plugin):
|
| 115 |
+
"""Plugin for making mypyc interoperate properly with mypy incremental mode.
|
| 116 |
+
|
| 117 |
+
Basically the point of this plugin is to force mypy to recheck things
|
| 118 |
+
based on the demands of mypyc in a couple situations:
|
| 119 |
+
* Any modules in the same group must be compiled together, so we
|
| 120 |
+
tell mypy that modules depend on all their groupmates.
|
| 121 |
+
* If the IR metadata is missing or stale or any of the generated
|
| 122 |
+
C source files associated missing or stale, then we need to
|
| 123 |
+
recompile the module so we mark it as stale.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def __init__(
|
| 127 |
+
self, options: Options, compiler_options: CompilerOptions, groups: Groups
|
| 128 |
+
) -> None:
|
| 129 |
+
super().__init__(options)
|
| 130 |
+
self.group_map: dict[str, tuple[str | None, list[str]]] = {}
|
| 131 |
+
for sources, name in groups:
|
| 132 |
+
modules = sorted(source.module for source in sources)
|
| 133 |
+
for id in modules:
|
| 134 |
+
self.group_map[id] = (name, modules)
|
| 135 |
+
|
| 136 |
+
self.compiler_options = compiler_options
|
| 137 |
+
self.metastore = create_metastore(options, parallel_worker=False)
|
| 138 |
+
|
| 139 |
+
def report_config_data(self, ctx: ReportConfigContext) -> tuple[str | None, list[str]] | None:
|
| 140 |
+
# The config data we report is the group map entry for the module.
|
| 141 |
+
# If the data is being used to check validity, we do additional checks
|
| 142 |
+
# that the IR cache exists and matches the metadata cache and all
|
| 143 |
+
# output source files exist and are up to date.
|
| 144 |
+
|
| 145 |
+
id, path, is_check = ctx.id, ctx.path, ctx.is_check
|
| 146 |
+
|
| 147 |
+
if id not in self.group_map:
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
# If we aren't doing validity checks, just return the cache data
|
| 151 |
+
if not is_check:
|
| 152 |
+
return self.group_map[id]
|
| 153 |
+
|
| 154 |
+
# Load the metadata and IR cache
|
| 155 |
+
meta_path, _, _ = get_cache_names(id, path, self.options)
|
| 156 |
+
ir_path = get_ir_cache_name(id, path, self.options)
|
| 157 |
+
try:
|
| 158 |
+
meta_json = self.metastore.read(meta_path)
|
| 159 |
+
ir_json = self.metastore.read(ir_path)
|
| 160 |
+
except FileNotFoundError:
|
| 161 |
+
# This could happen if mypyc failed after mypy succeeded
|
| 162 |
+
# in the previous run or if some cache files got
|
| 163 |
+
# deleted. No big deal, just fail to load the cache.
|
| 164 |
+
return None
|
| 165 |
+
|
| 166 |
+
ir_data = json.loads(ir_json)
|
| 167 |
+
|
| 168 |
+
# Check that the IR cache matches the metadata cache
|
| 169 |
+
if hash_digest(meta_json) != ir_data["meta_hash"]:
|
| 170 |
+
return None
|
| 171 |
+
|
| 172 |
+
# Check that all the source files are present and as
|
| 173 |
+
# expected. The main situation where this would come up is the
|
| 174 |
+
# user deleting the build directory without deleting
|
| 175 |
+
# .mypy_cache, which we should handle gracefully.
|
| 176 |
+
for path, hash in ir_data["src_hashes"].items():
|
| 177 |
+
try:
|
| 178 |
+
with open(os.path.join(self.compiler_options.target_dir, path), "rb") as f:
|
| 179 |
+
contents = f.read()
|
| 180 |
+
except FileNotFoundError:
|
| 181 |
+
return None
|
| 182 |
+
real_hash = hash_digest(contents)
|
| 183 |
+
if hash != real_hash:
|
| 184 |
+
return None
|
| 185 |
+
|
| 186 |
+
return self.group_map[id]
|
| 187 |
+
|
| 188 |
+
def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]:
|
| 189 |
+
# Report dependency on modules in the module's group
|
| 190 |
+
return [(10, id, -1) for id in self.group_map.get(file.fullname, (None, []))[1]]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def parse_and_typecheck(
|
| 194 |
+
sources: list[BuildSource],
|
| 195 |
+
options: Options,
|
| 196 |
+
compiler_options: CompilerOptions,
|
| 197 |
+
groups: Groups,
|
| 198 |
+
fscache: FileSystemCache | None = None,
|
| 199 |
+
alt_lib_path: str | None = None,
|
| 200 |
+
) -> BuildResult:
|
| 201 |
+
assert options.strict_optional, "strict_optional must be turned on"
|
| 202 |
+
mypyc_plugin = MypycPlugin(options, compiler_options, groups)
|
| 203 |
+
result = build(
|
| 204 |
+
sources=sources,
|
| 205 |
+
options=options,
|
| 206 |
+
alt_lib_path=alt_lib_path,
|
| 207 |
+
fscache=fscache,
|
| 208 |
+
extra_plugins=[mypyc_plugin],
|
| 209 |
+
)
|
| 210 |
+
mypyc_plugin.metastore.close()
|
| 211 |
+
if result.errors:
|
| 212 |
+
raise CompileError(result.errors)
|
| 213 |
+
return result
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def compile_scc_to_ir(
|
| 217 |
+
scc: list[MypyFile],
|
| 218 |
+
result: BuildResult,
|
| 219 |
+
mapper: Mapper,
|
| 220 |
+
compiler_options: CompilerOptions,
|
| 221 |
+
errors: Errors,
|
| 222 |
+
) -> ModuleIRs:
|
| 223 |
+
"""Compile an SCC into ModuleIRs.
|
| 224 |
+
|
| 225 |
+
Any modules that this SCC depends on must have either been compiled,
|
| 226 |
+
type checked, or loaded from a cache into mapper.
|
| 227 |
+
|
| 228 |
+
Arguments:
|
| 229 |
+
scc: The list of MypyFiles to compile
|
| 230 |
+
result: The BuildResult from the mypy front-end
|
| 231 |
+
mapper: The Mapper object mapping mypy ASTs to class and func IRs
|
| 232 |
+
compiler_options: The compilation options
|
| 233 |
+
errors: Where to report any errors encountered
|
| 234 |
+
|
| 235 |
+
Returns the IR of the modules.
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
if compiler_options.verbose:
|
| 239 |
+
print("Compiling {}".format(", ".join(x.name for x in scc)))
|
| 240 |
+
|
| 241 |
+
# Generate basic IR, with missing exception and refcount handling.
|
| 242 |
+
modules = build_ir(scc, result.graph, result.types, mapper, compiler_options, errors)
|
| 243 |
+
if errors.num_errors > 0:
|
| 244 |
+
return modules
|
| 245 |
+
|
| 246 |
+
env_user_functions = {}
|
| 247 |
+
for module in modules.values():
|
| 248 |
+
for cls in module.classes:
|
| 249 |
+
if cls.env_user_function:
|
| 250 |
+
env_user_functions[cls.env_user_function] = cls
|
| 251 |
+
|
| 252 |
+
for module in modules.values():
|
| 253 |
+
for fn in module.functions:
|
| 254 |
+
# Insert checks for uninitialized values.
|
| 255 |
+
insert_uninit_checks(fn, compiler_options.strict_traceback_checks)
|
| 256 |
+
# Insert exception handling.
|
| 257 |
+
insert_exception_handling(fn, compiler_options.strict_traceback_checks)
|
| 258 |
+
# Insert reference count handling.
|
| 259 |
+
insert_ref_count_opcodes(fn)
|
| 260 |
+
|
| 261 |
+
if fn in env_user_functions:
|
| 262 |
+
insert_spills(fn, env_user_functions[fn])
|
| 263 |
+
|
| 264 |
+
if compiler_options.log_trace:
|
| 265 |
+
insert_event_trace_logging(fn, compiler_options)
|
| 266 |
+
|
| 267 |
+
# Switch to lower abstraction level IR.
|
| 268 |
+
lower_ir(fn, compiler_options)
|
| 269 |
+
# Calculate implicit module dependencies (needed for librt)
|
| 270 |
+
deps = find_implicit_op_dependencies(fn)
|
| 271 |
+
if deps is not None:
|
| 272 |
+
module.dependencies.update(deps)
|
| 273 |
+
# Perform optimizations.
|
| 274 |
+
do_copy_propagation(fn, compiler_options)
|
| 275 |
+
do_flag_elimination(fn, compiler_options)
|
| 276 |
+
|
| 277 |
+
# Calculate implicit dependencies from class attribute types
|
| 278 |
+
for cl in module.classes:
|
| 279 |
+
deps = find_class_dependencies(cl)
|
| 280 |
+
if deps is not None:
|
| 281 |
+
module.dependencies.update(deps)
|
| 282 |
+
|
| 283 |
+
return modules
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def compile_modules_to_ir(
|
| 287 |
+
result: BuildResult, mapper: Mapper, compiler_options: CompilerOptions, errors: Errors
|
| 288 |
+
) -> ModuleIRs:
|
| 289 |
+
"""Compile a collection of modules into ModuleIRs.
|
| 290 |
+
|
| 291 |
+
The modules to compile are specified as part of mapper's group_map.
|
| 292 |
+
|
| 293 |
+
Returns the IR of the modules.
|
| 294 |
+
"""
|
| 295 |
+
deser_ctx = DeserMaps({}, {})
|
| 296 |
+
modules = {}
|
| 297 |
+
|
| 298 |
+
# Process the graph by SCC in topological order, like we do in mypy.build
|
| 299 |
+
for scc in sorted_components(result.graph):
|
| 300 |
+
scc_states = [result.graph[id] for id in scc.mod_ids]
|
| 301 |
+
trees = [st.tree for st in scc_states if st.id in mapper.group_map and st.tree]
|
| 302 |
+
|
| 303 |
+
if not trees:
|
| 304 |
+
continue
|
| 305 |
+
|
| 306 |
+
fresh = all(id not in result.manager.rechecked_modules for id in scc.mod_ids)
|
| 307 |
+
if fresh:
|
| 308 |
+
load_scc_from_cache(trees, result, mapper, deser_ctx)
|
| 309 |
+
else:
|
| 310 |
+
scc_ir = compile_scc_to_ir(trees, result, mapper, compiler_options, errors)
|
| 311 |
+
modules.update(scc_ir)
|
| 312 |
+
|
| 313 |
+
return modules
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def compile_ir_to_c(
|
| 317 |
+
groups: Groups,
|
| 318 |
+
modules: ModuleIRs,
|
| 319 |
+
result: BuildResult,
|
| 320 |
+
mapper: Mapper,
|
| 321 |
+
compiler_options: CompilerOptions,
|
| 322 |
+
) -> dict[str | None, list[tuple[str, str]]]:
|
| 323 |
+
"""Compile a collection of ModuleIRs to C source text.
|
| 324 |
+
|
| 325 |
+
Returns a dictionary mapping group names to a list of (file name,
|
| 326 |
+
file text) pairs.
|
| 327 |
+
"""
|
| 328 |
+
source_paths = {
|
| 329 |
+
source.module: result.graph[source.module].xpath
|
| 330 |
+
for sources, _ in groups
|
| 331 |
+
for source in sources
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
names = NameGenerator(
|
| 335 |
+
[[source.module for source in sources] for sources, _ in groups],
|
| 336 |
+
separate=compiler_options.separate,
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
# Generate C code for each compilation group. Each group will be
|
| 340 |
+
# compiled into a separate extension module.
|
| 341 |
+
ctext: dict[str | None, list[tuple[str, str]]] = {}
|
| 342 |
+
for group_sources, group_name in groups:
|
| 343 |
+
group_modules = {
|
| 344 |
+
source.module: modules[source.module]
|
| 345 |
+
for source in group_sources
|
| 346 |
+
if source.module in modules
|
| 347 |
+
}
|
| 348 |
+
if not group_modules:
|
| 349 |
+
ctext[group_name] = []
|
| 350 |
+
continue
|
| 351 |
+
generator = GroupGenerator(
|
| 352 |
+
group_modules, source_paths, group_name, mapper.group_map, names, compiler_options
|
| 353 |
+
)
|
| 354 |
+
ctext[group_name] = generator.generate_c_for_modules()
|
| 355 |
+
|
| 356 |
+
return ctext
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def get_ir_cache_name(id: str, path: str, options: Options) -> str:
|
| 360 |
+
meta_path, _, _ = get_cache_names(id, path, options)
|
| 361 |
+
# Mypyc uses JSON cache even with --fixed-format-cache (for now).
|
| 362 |
+
return meta_path.replace(".meta.json", ".ir.json").replace(".meta.ff", ".ir.json")
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def get_state_ir_cache_name(state: State) -> str:
|
| 366 |
+
return get_ir_cache_name(state.id, state.xpath, state.options)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def write_cache(
|
| 370 |
+
modules: ModuleIRs,
|
| 371 |
+
result: BuildResult,
|
| 372 |
+
group_map: dict[str, str | None],
|
| 373 |
+
ctext: dict[str | None, list[tuple[str, str]]],
|
| 374 |
+
) -> None:
|
| 375 |
+
"""Write out the cache information for modules.
|
| 376 |
+
|
| 377 |
+
Each module has the following cache information written (which is
|
| 378 |
+
in addition to the cache information written by mypy itself):
|
| 379 |
+
* A serialized version of its mypyc IR, minus the bodies of
|
| 380 |
+
functions. This allows code that depends on it to use
|
| 381 |
+
these serialized data structures when compiling against it
|
| 382 |
+
instead of needing to recompile it. (Compiling against a
|
| 383 |
+
module requires access to both its mypy and mypyc data
|
| 384 |
+
structures.)
|
| 385 |
+
* The hash of the mypy metadata cache file for the module.
|
| 386 |
+
This is used to ensure that the mypyc cache and the mypy
|
| 387 |
+
cache are in sync and refer to the same version of the code.
|
| 388 |
+
This is particularly important if mypyc crashes/errors/is
|
| 389 |
+
stopped after mypy has written its cache but before mypyc has.
|
| 390 |
+
* The hashes of all the source file outputs for the group
|
| 391 |
+
the module is in. This is so that the module will be
|
| 392 |
+
recompiled if the source outputs are missing.
|
| 393 |
+
"""
|
| 394 |
+
|
| 395 |
+
hashes = {}
|
| 396 |
+
for name, files in ctext.items():
|
| 397 |
+
hashes[name] = {file: compute_hash(data) for file, data in files}
|
| 398 |
+
|
| 399 |
+
# Write out cache data
|
| 400 |
+
for id, module in modules.items():
|
| 401 |
+
st = result.graph[id]
|
| 402 |
+
|
| 403 |
+
meta_path, _, _ = get_cache_names(id, st.xpath, result.manager.options)
|
| 404 |
+
# If the metadata isn't there, skip writing the cache.
|
| 405 |
+
try:
|
| 406 |
+
meta_data = result.manager.metastore.read(meta_path)
|
| 407 |
+
except OSError:
|
| 408 |
+
continue
|
| 409 |
+
|
| 410 |
+
newpath = get_state_ir_cache_name(st)
|
| 411 |
+
ir_data = {
|
| 412 |
+
"ir": module.serialize(),
|
| 413 |
+
"meta_hash": hash_digest(meta_data),
|
| 414 |
+
"src_hashes": hashes[group_map[id]],
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
result.manager.metastore.write(newpath, json_dumps(ir_data))
|
| 418 |
+
|
| 419 |
+
result.manager.metastore.commit()
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def load_scc_from_cache(
|
| 423 |
+
scc: list[MypyFile], result: BuildResult, mapper: Mapper, ctx: DeserMaps
|
| 424 |
+
) -> ModuleIRs:
|
| 425 |
+
"""Load IR for an SCC of modules from the cache.
|
| 426 |
+
|
| 427 |
+
Arguments and return are as compile_scc_to_ir.
|
| 428 |
+
"""
|
| 429 |
+
cache_data = {
|
| 430 |
+
k.fullname: json.loads(
|
| 431 |
+
result.manager.metastore.read(get_state_ir_cache_name(result.graph[k.fullname]))
|
| 432 |
+
)["ir"]
|
| 433 |
+
for k in scc
|
| 434 |
+
}
|
| 435 |
+
modules = deserialize_modules(cache_data, ctx)
|
| 436 |
+
load_type_map(mapper, scc, ctx)
|
| 437 |
+
return modules
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def collect_source_dependencies(modules: dict[str, ModuleIR]) -> set[SourceDep]:
|
| 441 |
+
"""Collect all SourceDep dependencies from all modules."""
|
| 442 |
+
source_deps: set[SourceDep] = set()
|
| 443 |
+
for module in modules.values():
|
| 444 |
+
for dep in module.dependencies:
|
| 445 |
+
if isinstance(dep, SourceDep):
|
| 446 |
+
source_deps.add(dep)
|
| 447 |
+
return source_deps
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def compile_modules_to_c(
|
| 451 |
+
result: BuildResult, compiler_options: CompilerOptions, errors: Errors, groups: Groups
|
| 452 |
+
) -> tuple[ModuleIRs, list[FileContents], Mapper]:
|
| 453 |
+
"""Compile Python module(s) to the source of Python C extension modules.
|
| 454 |
+
|
| 455 |
+
This generates the source code for the "shared library" module
|
| 456 |
+
for each group. The shim modules are generated in mypyc.build.
|
| 457 |
+
Each shared library module provides, for each module in its group,
|
| 458 |
+
a PyCapsule containing an initialization function.
|
| 459 |
+
Additionally, it provides a capsule containing an export table of
|
| 460 |
+
pointers to all the group's functions and static variables.
|
| 461 |
+
|
| 462 |
+
Arguments:
|
| 463 |
+
result: The BuildResult from the mypy front-end
|
| 464 |
+
compiler_options: The compilation options
|
| 465 |
+
errors: Where to report any errors encountered
|
| 466 |
+
groups: The groups that we are compiling. See documentation of Groups type above.
|
| 467 |
+
|
| 468 |
+
Returns the IR of the modules and a list containing the generated files for each group.
|
| 469 |
+
"""
|
| 470 |
+
# Construct a map from modules to what group they belong to
|
| 471 |
+
group_map = {source.module: lib_name for group, lib_name in groups for source in group}
|
| 472 |
+
mapper = Mapper(group_map)
|
| 473 |
+
|
| 474 |
+
# Sometimes when we call back into mypy, there might be errors.
|
| 475 |
+
# We don't want to crash when that happens.
|
| 476 |
+
result.manager.errors.set_file(
|
| 477 |
+
"<mypyc>", module=None, scope=None, options=result.manager.options
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
modules = compile_modules_to_ir(result, mapper, compiler_options, errors)
|
| 481 |
+
if errors.num_errors > 0:
|
| 482 |
+
return {}, [], Mapper({})
|
| 483 |
+
|
| 484 |
+
ctext = compile_ir_to_c(groups, modules, result, mapper, compiler_options)
|
| 485 |
+
write_cache(modules, result, group_map, ctext)
|
| 486 |
+
|
| 487 |
+
return modules, [ctext[name] for _, name in groups], mapper
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def generate_function_declaration(fn: FuncIR, emitter: Emitter) -> None:
|
| 491 |
+
emitter.context.declarations[emitter.native_function_name(fn.decl)] = HeaderDeclaration(
|
| 492 |
+
f"{native_function_header(fn.decl, emitter)};", needs_export=True
|
| 493 |
+
)
|
| 494 |
+
if fn.name != TOP_LEVEL_NAME and not fn.internal:
|
| 495 |
+
if is_fastcall_supported(fn, emitter.capi_version):
|
| 496 |
+
emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration(
|
| 497 |
+
f"{wrapper_function_header(fn, emitter.names)};"
|
| 498 |
+
)
|
| 499 |
+
else:
|
| 500 |
+
emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration(
|
| 501 |
+
f"{legacy_wrapper_function_header(fn, emitter.names)};"
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def pointerize(decl: str, name: str) -> str:
|
| 506 |
+
"""Given a C decl and its name, modify it to be a declaration to a pointer."""
|
| 507 |
+
# This doesn't work in general but does work for all our types...
|
| 508 |
+
if "(" in decl:
|
| 509 |
+
# Function pointer. Stick an * in front of the name and wrap it in parens.
|
| 510 |
+
return decl.replace(name, f"(*{name})")
|
| 511 |
+
else:
|
| 512 |
+
# Non-function pointer. Just stick an * in front of the name.
|
| 513 |
+
return decl.replace(name, f"*{name}")
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def group_dir(group_name: str) -> str:
|
| 517 |
+
"""Given a group name, return the relative directory path for it."""
|
| 518 |
+
return os.sep.join(group_name.split(".")[:-1])
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class GroupGenerator:
|
| 522 |
+
def __init__(
|
| 523 |
+
self,
|
| 524 |
+
modules: dict[str, ModuleIR],
|
| 525 |
+
source_paths: dict[str, str],
|
| 526 |
+
group_name: str | None,
|
| 527 |
+
group_map: dict[str, str | None],
|
| 528 |
+
names: NameGenerator,
|
| 529 |
+
compiler_options: CompilerOptions,
|
| 530 |
+
) -> None:
|
| 531 |
+
"""Generator for C source for a compilation group.
|
| 532 |
+
|
| 533 |
+
The code for a compilation group contains an internal and an
|
| 534 |
+
external .h file, and then one .c if not in multi_file mode or
|
| 535 |
+
one .c file per module if in multi_file mode.
|
| 536 |
+
|
| 537 |
+
Arguments:
|
| 538 |
+
modules: (name, ir) pairs for each module in the group
|
| 539 |
+
source_paths: Map from module names to source file paths
|
| 540 |
+
group_name: The name of the group (or None if this is single-module compilation)
|
| 541 |
+
group_map: A map of modules to their group names
|
| 542 |
+
names: The name generator for the compilation
|
| 543 |
+
compiler_options: Mypyc specific options, including multi_file mode
|
| 544 |
+
"""
|
| 545 |
+
self.modules = modules
|
| 546 |
+
self.source_paths = source_paths
|
| 547 |
+
self.context = EmitterContext(
|
| 548 |
+
names, compiler_options.strict_traceback_checks, group_name, group_map
|
| 549 |
+
)
|
| 550 |
+
self.names = names
|
| 551 |
+
# Initializations of globals to simple values that we can't
|
| 552 |
+
# do statically because the windows loader is bad.
|
| 553 |
+
self.simple_inits: list[tuple[str, str]] = []
|
| 554 |
+
self.group_name = group_name
|
| 555 |
+
self.use_shared_lib = group_name is not None
|
| 556 |
+
self.compiler_options = compiler_options
|
| 557 |
+
self.multi_file = compiler_options.multi_file
|
| 558 |
+
# Multi-phase init is needed to enable free-threading. In the future we'll
|
| 559 |
+
# probably want to enable it always, but we'll wait until it's stable.
|
| 560 |
+
self.multi_phase_init = IS_FREE_THREADED
|
| 561 |
+
|
| 562 |
+
@property
|
| 563 |
+
def group_suffix(self) -> str:
|
| 564 |
+
return "_" + exported_name(self.group_name) if self.group_name else ""
|
| 565 |
+
|
| 566 |
+
@property
|
| 567 |
+
def short_group_suffix(self) -> str:
|
| 568 |
+
return "_" + exported_name(self.group_name.split(".")[-1]) if self.group_name else ""
|
| 569 |
+
|
| 570 |
+
def generate_c_for_modules(self) -> list[tuple[str, str]]:
|
| 571 |
+
file_contents = []
|
| 572 |
+
multi_file = self.use_shared_lib and self.multi_file
|
| 573 |
+
|
| 574 |
+
# Collect all literal refs in IR.
|
| 575 |
+
for module in self.modules.values():
|
| 576 |
+
for fn in module.functions:
|
| 577 |
+
collect_literals(fn, self.context.literals)
|
| 578 |
+
|
| 579 |
+
base_emitter = Emitter(self.context)
|
| 580 |
+
# Optionally just include the runtime library c files to
|
| 581 |
+
# reduce the number of compiler invocations needed
|
| 582 |
+
if self.compiler_options.include_runtime_files:
|
| 583 |
+
for name in RUNTIME_C_FILES:
|
| 584 |
+
base_emitter.emit_line(f'#include "{name}"')
|
| 585 |
+
# Include conditional source files
|
| 586 |
+
source_deps = collect_source_dependencies(self.modules)
|
| 587 |
+
for source_dep in sorted(source_deps, key=lambda d: d.path):
|
| 588 |
+
base_emitter.emit_line(f'#include "{source_dep.path}"')
|
| 589 |
+
base_emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"')
|
| 590 |
+
base_emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"')
|
| 591 |
+
emitter = base_emitter
|
| 592 |
+
|
| 593 |
+
self.generate_literal_tables()
|
| 594 |
+
|
| 595 |
+
for module_name, module in self.modules.items():
|
| 596 |
+
if multi_file:
|
| 597 |
+
emitter = Emitter(self.context, filepath=self.source_paths[module_name])
|
| 598 |
+
emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"')
|
| 599 |
+
emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"')
|
| 600 |
+
|
| 601 |
+
self.declare_module(module_name, emitter)
|
| 602 |
+
self.declare_internal_globals(module_name, emitter)
|
| 603 |
+
self.declare_imports(module.imports, emitter)
|
| 604 |
+
|
| 605 |
+
for cl in module.classes:
|
| 606 |
+
if cl.is_ext_class:
|
| 607 |
+
generate_class(cl, module_name, emitter)
|
| 608 |
+
|
| 609 |
+
# Generate Python extension module definitions and module initialization functions.
|
| 610 |
+
self.generate_module_def(emitter, module_name, module)
|
| 611 |
+
|
| 612 |
+
for fn in module.functions:
|
| 613 |
+
emitter.emit_line()
|
| 614 |
+
generate_native_function(fn, emitter, self.source_paths[module_name], module_name)
|
| 615 |
+
if fn.name != TOP_LEVEL_NAME and not fn.internal:
|
| 616 |
+
emitter.emit_line()
|
| 617 |
+
if is_fastcall_supported(fn, emitter.capi_version):
|
| 618 |
+
generate_wrapper_function(
|
| 619 |
+
fn, emitter, self.source_paths[module_name], module_name
|
| 620 |
+
)
|
| 621 |
+
else:
|
| 622 |
+
generate_legacy_wrapper_function(
|
| 623 |
+
fn, emitter, self.source_paths[module_name], module_name
|
| 624 |
+
)
|
| 625 |
+
if multi_file:
|
| 626 |
+
name = f"__native_{exported_name(module_name)}.c"
|
| 627 |
+
file_contents.append((name, "".join(emitter.fragments)))
|
| 628 |
+
|
| 629 |
+
# The external header file contains type declarations while
|
| 630 |
+
# the internal contains declarations of functions and objects
|
| 631 |
+
# (which are shared between shared libraries via dynamic
|
| 632 |
+
# exports tables and not accessed directly.)
|
| 633 |
+
ext_declarations = Emitter(self.context)
|
| 634 |
+
ext_declarations.emit_line(f"#ifndef MYPYC_NATIVE{self.group_suffix}_H")
|
| 635 |
+
ext_declarations.emit_line(f"#define MYPYC_NATIVE{self.group_suffix}_H")
|
| 636 |
+
ext_declarations.emit_line("#include <Python.h>")
|
| 637 |
+
ext_declarations.emit_line("#include <CPy.h>")
|
| 638 |
+
if self.compiler_options.depends_on_librt_internal:
|
| 639 |
+
ext_declarations.emit_line("#include <internal/librt_internal.h>")
|
| 640 |
+
if any(LIBRT_BASE64 in mod.dependencies for mod in self.modules.values()):
|
| 641 |
+
ext_declarations.emit_line("#include <base64/librt_base64.h>")
|
| 642 |
+
if any(LIBRT_STRINGS in mod.dependencies for mod in self.modules.values()):
|
| 643 |
+
ext_declarations.emit_line("#include <strings/librt_strings.h>")
|
| 644 |
+
if any(LIBRT_TIME in mod.dependencies for mod in self.modules.values()):
|
| 645 |
+
ext_declarations.emit_line("#include <time/librt_time.h>")
|
| 646 |
+
if any(LIBRT_VECS in mod.dependencies for mod in self.modules.values()):
|
| 647 |
+
ext_declarations.emit_line("#include <vecs/librt_vecs.h>")
|
| 648 |
+
# Include headers for conditional source files
|
| 649 |
+
source_deps = collect_source_dependencies(self.modules)
|
| 650 |
+
for source_dep in sorted(source_deps, key=lambda d: d.path):
|
| 651 |
+
ext_declarations.emit_line(f'#include "{source_dep.get_header()}"')
|
| 652 |
+
|
| 653 |
+
declarations = Emitter(self.context)
|
| 654 |
+
declarations.emit_line(f"#ifndef MYPYC_LIBRT_INTERNAL{self.group_suffix}_H")
|
| 655 |
+
declarations.emit_line(f"#define MYPYC_LIBRT_INTERNAL{self.group_suffix}_H")
|
| 656 |
+
declarations.emit_line("#include <Python.h>")
|
| 657 |
+
declarations.emit_line("#include <CPy.h>")
|
| 658 |
+
declarations.emit_line(f'#include "__native{self.short_group_suffix}.h"')
|
| 659 |
+
declarations.emit_line()
|
| 660 |
+
declarations.emit_line("int CPyGlobalsInit(void);")
|
| 661 |
+
declarations.emit_line()
|
| 662 |
+
|
| 663 |
+
for module_name, module in self.modules.items():
|
| 664 |
+
self.declare_finals(module_name, module.final_names, declarations)
|
| 665 |
+
for cl in module.classes:
|
| 666 |
+
generate_class_type_decl(cl, emitter, ext_declarations, declarations)
|
| 667 |
+
if cl.reuse_freed_instance:
|
| 668 |
+
generate_class_reuse(cl, emitter, ext_declarations, declarations)
|
| 669 |
+
self.declare_type_vars(module_name, module.type_var_names, declarations)
|
| 670 |
+
for fn in module.functions:
|
| 671 |
+
generate_function_declaration(fn, declarations)
|
| 672 |
+
|
| 673 |
+
for lib in sorted(self.context.group_deps):
|
| 674 |
+
elib = exported_name(lib)
|
| 675 |
+
short_lib = exported_name(lib.split(".")[-1])
|
| 676 |
+
declarations.emit_lines(
|
| 677 |
+
"#include <{}>".format(os.path.join(group_dir(lib), f"__native_{short_lib}.h")),
|
| 678 |
+
f"struct export_table_{elib} exports_{elib};",
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
sorted_decls = self.toposort_declarations()
|
| 682 |
+
|
| 683 |
+
emitter = base_emitter
|
| 684 |
+
self.generate_globals_init(emitter)
|
| 685 |
+
|
| 686 |
+
emitter.emit_line()
|
| 687 |
+
|
| 688 |
+
for declaration in sorted_decls:
|
| 689 |
+
decls = ext_declarations if declaration.is_type else declarations
|
| 690 |
+
if not declaration.is_type:
|
| 691 |
+
decls.emit_lines(f"extern {declaration.decl[0]}", *declaration.decl[1:])
|
| 692 |
+
# If there is a definition, emit it. Otherwise, repeat the declaration
|
| 693 |
+
# (without an extern).
|
| 694 |
+
if declaration.defn:
|
| 695 |
+
emitter.emit_lines(*declaration.defn)
|
| 696 |
+
else:
|
| 697 |
+
emitter.emit_lines(*declaration.decl)
|
| 698 |
+
else:
|
| 699 |
+
decls.emit_lines(*declaration.decl)
|
| 700 |
+
|
| 701 |
+
if self.group_name:
|
| 702 |
+
if self.compiler_options.separate:
|
| 703 |
+
self.generate_export_table(ext_declarations, emitter)
|
| 704 |
+
|
| 705 |
+
self.generate_shared_lib_init(emitter)
|
| 706 |
+
|
| 707 |
+
ext_declarations.emit_line("#endif")
|
| 708 |
+
declarations.emit_line("#endif")
|
| 709 |
+
|
| 710 |
+
output_dir = group_dir(self.group_name) if self.group_name else ""
|
| 711 |
+
return file_contents + [
|
| 712 |
+
(
|
| 713 |
+
os.path.join(output_dir, f"__native{self.short_group_suffix}.c"),
|
| 714 |
+
"".join(emitter.fragments),
|
| 715 |
+
),
|
| 716 |
+
(
|
| 717 |
+
os.path.join(output_dir, f"__native_internal{self.short_group_suffix}.h"),
|
| 718 |
+
"".join(declarations.fragments),
|
| 719 |
+
),
|
| 720 |
+
(
|
| 721 |
+
os.path.join(output_dir, f"__native{self.short_group_suffix}.h"),
|
| 722 |
+
"".join(ext_declarations.fragments),
|
| 723 |
+
),
|
| 724 |
+
]
|
| 725 |
+
|
| 726 |
+
def generate_literal_tables(self) -> None:
|
| 727 |
+
"""Generate tables containing descriptions of Python literals to construct.
|
| 728 |
+
|
| 729 |
+
We will store the constructed literals in a single array that contains
|
| 730 |
+
literals of all types. This way we can refer to an arbitrary literal by
|
| 731 |
+
its index.
|
| 732 |
+
"""
|
| 733 |
+
literals = self.context.literals
|
| 734 |
+
# During module initialization we store all the constructed objects here
|
| 735 |
+
self.declare_global("PyObject *[%d]" % literals.num_literals(), "CPyStatics")
|
| 736 |
+
# Descriptions of str literals
|
| 737 |
+
init_str = c_string_array_initializer(literals.encoded_str_values())
|
| 738 |
+
self.declare_global("const char * const []", "CPyLit_Str", initializer=init_str)
|
| 739 |
+
# Descriptions of bytes literals
|
| 740 |
+
init_bytes = c_string_array_initializer(literals.encoded_bytes_values())
|
| 741 |
+
self.declare_global("const char * const []", "CPyLit_Bytes", initializer=init_bytes)
|
| 742 |
+
# Descriptions of int literals
|
| 743 |
+
init_int = c_string_array_initializer(literals.encoded_int_values())
|
| 744 |
+
self.declare_global("const char * const []", "CPyLit_Int", initializer=init_int)
|
| 745 |
+
# Descriptions of float literals
|
| 746 |
+
init_floats = c_array_initializer(literals.encoded_float_values())
|
| 747 |
+
self.declare_global("const double []", "CPyLit_Float", initializer=init_floats)
|
| 748 |
+
# Descriptions of complex literals
|
| 749 |
+
init_complex = c_array_initializer(literals.encoded_complex_values())
|
| 750 |
+
self.declare_global("const double []", "CPyLit_Complex", initializer=init_complex)
|
| 751 |
+
# Descriptions of tuple literals
|
| 752 |
+
init_tuple = c_array_initializer(literals.encoded_tuple_values())
|
| 753 |
+
self.declare_global("const int []", "CPyLit_Tuple", initializer=init_tuple)
|
| 754 |
+
# Descriptions of frozenset literals
|
| 755 |
+
init_frozenset = c_array_initializer(literals.encoded_frozenset_values())
|
| 756 |
+
self.declare_global("const int []", "CPyLit_FrozenSet", initializer=init_frozenset)
|
| 757 |
+
|
| 758 |
+
def generate_export_table(self, decl_emitter: Emitter, code_emitter: Emitter) -> None:
|
| 759 |
+
"""Generate the declaration and definition of the group's export struct.
|
| 760 |
+
|
| 761 |
+
To avoid needing to deal with deeply platform specific issues
|
| 762 |
+
involving dynamic library linking (and some possibly
|
| 763 |
+
insurmountable issues involving cyclic dependencies), compiled
|
| 764 |
+
code accesses functions and data in other compilation groups
|
| 765 |
+
via an explicit "export struct".
|
| 766 |
+
|
| 767 |
+
Each group declares a struct type that contains a pointer to
|
| 768 |
+
every function and static variable it exports. It then
|
| 769 |
+
populates this struct and stores a pointer to it in a capsule
|
| 770 |
+
stored as an attribute named 'exports' on the group's shared
|
| 771 |
+
library's python module.
|
| 772 |
+
|
| 773 |
+
On load, a group's init function will import all of its
|
| 774 |
+
dependencies' exports tables using the capsule mechanism and
|
| 775 |
+
copy the contents into a local copy of the table (to eliminate
|
| 776 |
+
the need for a pointer indirection when accessing it).
|
| 777 |
+
|
| 778 |
+
Then, all calls to functions in another group and accesses to statics
|
| 779 |
+
from another group are done indirectly via the export table.
|
| 780 |
+
|
| 781 |
+
For example, a group containing a module b, where b contains a class B
|
| 782 |
+
and a function bar, would declare an export table like:
|
| 783 |
+
struct export_table_b {
|
| 784 |
+
PyTypeObject **CPyType_B;
|
| 785 |
+
PyObject *(*CPyDef_B)(CPyTagged cpy_r_x);
|
| 786 |
+
CPyTagged (*CPyDef_B___foo)(PyObject *cpy_r_self, CPyTagged cpy_r_y);
|
| 787 |
+
tuple_T2OI (*CPyDef_bar)(PyObject *cpy_r_x);
|
| 788 |
+
char (*CPyDef___top_level__)(void);
|
| 789 |
+
};
|
| 790 |
+
that would be initialized with:
|
| 791 |
+
static struct export_table_b exports = {
|
| 792 |
+
&CPyType_B,
|
| 793 |
+
&CPyDef_B,
|
| 794 |
+
&CPyDef_B___foo,
|
| 795 |
+
&CPyDef_bar,
|
| 796 |
+
&CPyDef___top_level__,
|
| 797 |
+
};
|
| 798 |
+
To call `b.foo`, then, a function in another group would do
|
| 799 |
+
`exports_b.CPyDef_bar(...)`.
|
| 800 |
+
"""
|
| 801 |
+
|
| 802 |
+
decls = decl_emitter.context.declarations
|
| 803 |
+
|
| 804 |
+
decl_emitter.emit_lines("", f"struct export_table{self.group_suffix} {{")
|
| 805 |
+
for name, decl in decls.items():
|
| 806 |
+
if decl.needs_export:
|
| 807 |
+
decl_emitter.emit_line(pointerize("\n".join(decl.decl), name))
|
| 808 |
+
|
| 809 |
+
decl_emitter.emit_line("};")
|
| 810 |
+
|
| 811 |
+
code_emitter.emit_lines("", f"static struct export_table{self.group_suffix} exports = {{")
|
| 812 |
+
for name, decl in decls.items():
|
| 813 |
+
if decl.needs_export:
|
| 814 |
+
code_emitter.emit_line(f"&{name},")
|
| 815 |
+
|
| 816 |
+
code_emitter.emit_line("};")
|
| 817 |
+
|
| 818 |
+
def generate_shared_lib_init(self, emitter: Emitter) -> None:
|
| 819 |
+
"""Generate the init function for a shared library.
|
| 820 |
+
|
| 821 |
+
A shared library contains all the actual code for a
|
| 822 |
+
compilation group.
|
| 823 |
+
|
| 824 |
+
The init function is responsible for creating Capsules that
|
| 825 |
+
wrap pointers to the initialization function of all the real
|
| 826 |
+
init functions for modules in this shared library as well as
|
| 827 |
+
the export table containing all the exported functions and
|
| 828 |
+
values from all the modules.
|
| 829 |
+
|
| 830 |
+
These capsules are stored in attributes of the shared library.
|
| 831 |
+
"""
|
| 832 |
+
assert self.group_name is not None
|
| 833 |
+
|
| 834 |
+
emitter.emit_line()
|
| 835 |
+
|
| 836 |
+
short_name = shared_lib_name(self.group_name).split(".")[-1]
|
| 837 |
+
|
| 838 |
+
emitter.emit_lines(
|
| 839 |
+
f"static int exec_{short_name}(PyObject *module)",
|
| 840 |
+
"{",
|
| 841 |
+
"int res;",
|
| 842 |
+
"PyObject *capsule;",
|
| 843 |
+
"PyObject *tmp;",
|
| 844 |
+
"",
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
if self.compiler_options.separate:
|
| 848 |
+
emitter.emit_lines(
|
| 849 |
+
'capsule = PyCapsule_New(&exports, "{}.exports", NULL);'.format(
|
| 850 |
+
shared_lib_name(self.group_name)
|
| 851 |
+
),
|
| 852 |
+
"if (!capsule) {",
|
| 853 |
+
"goto fail;",
|
| 854 |
+
"}",
|
| 855 |
+
'res = PyObject_SetAttrString(module, "exports", capsule);',
|
| 856 |
+
"Py_DECREF(capsule);",
|
| 857 |
+
"if (res < 0) {",
|
| 858 |
+
"goto fail;",
|
| 859 |
+
"}",
|
| 860 |
+
"",
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
for mod in self.modules:
|
| 864 |
+
name = exported_name(mod)
|
| 865 |
+
if self.multi_phase_init:
|
| 866 |
+
capsule_func_prefix = "CPyExec_"
|
| 867 |
+
capsule_name_prefix = "exec_"
|
| 868 |
+
emitter.emit_line(f"extern int CPyExec_{name}(PyObject *);")
|
| 869 |
+
else:
|
| 870 |
+
capsule_func_prefix = "CPyInit_"
|
| 871 |
+
capsule_name_prefix = "init_"
|
| 872 |
+
emitter.emit_line(f"extern PyObject *CPyInit_{name}(void);")
|
| 873 |
+
emitter.emit_lines(
|
| 874 |
+
'capsule = PyCapsule_New((void *){}{}, "{}.{}{}", NULL);'.format(
|
| 875 |
+
capsule_func_prefix,
|
| 876 |
+
name,
|
| 877 |
+
shared_lib_name(self.group_name),
|
| 878 |
+
capsule_name_prefix,
|
| 879 |
+
name,
|
| 880 |
+
),
|
| 881 |
+
"if (!capsule) {",
|
| 882 |
+
"goto fail;",
|
| 883 |
+
"}",
|
| 884 |
+
f'res = PyObject_SetAttrString(module, "{capsule_name_prefix}{name}", capsule);',
|
| 885 |
+
"Py_DECREF(capsule);",
|
| 886 |
+
"if (res < 0) {",
|
| 887 |
+
"goto fail;",
|
| 888 |
+
"}",
|
| 889 |
+
"",
|
| 890 |
+
)
|
| 891 |
+
|
| 892 |
+
for group in sorted(self.context.group_deps):
|
| 893 |
+
egroup = exported_name(group)
|
| 894 |
+
emitter.emit_lines(
|
| 895 |
+
'tmp = PyImport_ImportModule("{}"); if (!tmp) goto fail; Py_DECREF(tmp);'.format(
|
| 896 |
+
shared_lib_name(group)
|
| 897 |
+
),
|
| 898 |
+
'struct export_table_{} *pexports_{} = PyCapsule_Import("{}.exports", 0);'.format(
|
| 899 |
+
egroup, egroup, shared_lib_name(group)
|
| 900 |
+
),
|
| 901 |
+
f"if (!pexports_{egroup}) {{",
|
| 902 |
+
"goto fail;",
|
| 903 |
+
"}",
|
| 904 |
+
"memcpy(&exports_{group}, pexports_{group}, sizeof(exports_{group}));".format(
|
| 905 |
+
group=egroup
|
| 906 |
+
),
|
| 907 |
+
"",
|
| 908 |
+
)
|
| 909 |
+
|
| 910 |
+
emitter.emit_lines("return 0;", "fail:", "return -1;", "}")
|
| 911 |
+
|
| 912 |
+
if self.multi_phase_init:
|
| 913 |
+
emitter.emit_lines(
|
| 914 |
+
f"static PyModuleDef_Slot slots_{short_name}[] = {{",
|
| 915 |
+
f"{{Py_mod_exec, exec_{short_name}}},",
|
| 916 |
+
"{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},",
|
| 917 |
+
"{Py_mod_gil, Py_MOD_GIL_NOT_USED},",
|
| 918 |
+
"{0, NULL},",
|
| 919 |
+
"};",
|
| 920 |
+
)
|
| 921 |
+
|
| 922 |
+
size = 0 if self.multi_phase_init else -1
|
| 923 |
+
emitter.emit_lines(
|
| 924 |
+
f"static PyModuleDef module_def_{short_name} = {{",
|
| 925 |
+
"PyModuleDef_HEAD_INIT,",
|
| 926 |
+
f'.m_name = "{shared_lib_name(self.group_name)}",',
|
| 927 |
+
".m_doc = NULL,",
|
| 928 |
+
f".m_size = {size},",
|
| 929 |
+
".m_methods = NULL,",
|
| 930 |
+
)
|
| 931 |
+
if self.multi_phase_init:
|
| 932 |
+
emitter.emit_line(f".m_slots = slots_{short_name},")
|
| 933 |
+
emitter.emit_line("};")
|
| 934 |
+
|
| 935 |
+
if self.multi_phase_init:
|
| 936 |
+
emitter.emit_lines(
|
| 937 |
+
f"PyMODINIT_FUNC PyInit_{short_name}(void) {{",
|
| 938 |
+
f"return PyModuleDef_Init(&module_def_{short_name});",
|
| 939 |
+
"}",
|
| 940 |
+
)
|
| 941 |
+
else:
|
| 942 |
+
emitter.emit_lines(
|
| 943 |
+
f"PyMODINIT_FUNC PyInit_{short_name}(void) {{",
|
| 944 |
+
"static PyObject *module = NULL;",
|
| 945 |
+
"if (module) {",
|
| 946 |
+
"Py_INCREF(module);",
|
| 947 |
+
"return module;",
|
| 948 |
+
"}",
|
| 949 |
+
f"module = PyModule_Create(&module_def_{short_name});",
|
| 950 |
+
"if (!module) {",
|
| 951 |
+
"return NULL;",
|
| 952 |
+
"}",
|
| 953 |
+
f"if (exec_{short_name}(module) < 0) {{",
|
| 954 |
+
"Py_DECREF(module);",
|
| 955 |
+
"return NULL;",
|
| 956 |
+
"}",
|
| 957 |
+
"return module;",
|
| 958 |
+
"}",
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
def generate_globals_init(self, emitter: Emitter) -> None:
|
| 962 |
+
emitter.emit_lines(
|
| 963 |
+
"",
|
| 964 |
+
"int CPyGlobalsInit(void)",
|
| 965 |
+
"{",
|
| 966 |
+
"static int is_initialized = 0;",
|
| 967 |
+
"if (is_initialized) return 0;",
|
| 968 |
+
"",
|
| 969 |
+
)
|
| 970 |
+
|
| 971 |
+
emitter.emit_line("CPy_Init();")
|
| 972 |
+
for symbol, fixup in self.simple_inits:
|
| 973 |
+
emitter.emit_line(f"{symbol} = {fixup};")
|
| 974 |
+
|
| 975 |
+
values = "CPyLit_Str, CPyLit_Bytes, CPyLit_Int, CPyLit_Float, CPyLit_Complex, CPyLit_Tuple, CPyLit_FrozenSet"
|
| 976 |
+
emitter.emit_lines(
|
| 977 |
+
f"if (CPyStatics_Initialize(CPyStatics, {values}) < 0) {{", "return -1;", "}"
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
emitter.emit_lines("is_initialized = 1;", "return 0;", "}")
|
| 981 |
+
|
| 982 |
+
def generate_module_def(self, emitter: Emitter, module_name: str, module: ModuleIR) -> None:
|
| 983 |
+
"""Emit the PyModuleDef struct for a module and the module init function."""
|
| 984 |
+
module_prefix = emitter.names.private_name(module_name)
|
| 985 |
+
self.emit_module_methods(emitter, module_name, module_prefix, module)
|
| 986 |
+
self.emit_module_exec_func(emitter, module_name, module_prefix, module)
|
| 987 |
+
|
| 988 |
+
# If using multi-phase init and a shared lib, parts of module definition
|
| 989 |
+
# will happen in the shim modules, so we skip some steps here.
|
| 990 |
+
if not (self.multi_phase_init and self.use_shared_lib):
|
| 991 |
+
if self.multi_phase_init:
|
| 992 |
+
self.emit_module_def_slots(emitter, module_prefix, module_name)
|
| 993 |
+
self.emit_module_def_struct(emitter, module_name, module_prefix)
|
| 994 |
+
self.emit_module_init_func(emitter, module_name, module_prefix)
|
| 995 |
+
elif self.use_shared_lib:
|
| 996 |
+
# Multi-phase init with shared lib: shims handle PyInit_*, but we
|
| 997 |
+
# still need CPyInitOnly_* for same-group native imports, and the
|
| 998 |
+
# PyModuleDef struct it depends on.
|
| 999 |
+
self.emit_module_def_struct(emitter, module_name, module_prefix)
|
| 1000 |
+
self.emit_init_only_func(emitter, module_name, module_prefix)
|
| 1001 |
+
|
| 1002 |
+
def emit_module_def_slots(
|
| 1003 |
+
self, emitter: Emitter, module_prefix: str, module_name: str
|
| 1004 |
+
) -> None:
|
| 1005 |
+
name = f"{module_prefix}_slots"
|
| 1006 |
+
exec_name = f"CPyExec_{exported_name(module_name)}"
|
| 1007 |
+
|
| 1008 |
+
emitter.emit_line(f"static PyModuleDef_Slot {name}[] = {{")
|
| 1009 |
+
emitter.emit_line(f"{{Py_mod_exec, {exec_name}}},")
|
| 1010 |
+
if sys.version_info >= (3, 12):
|
| 1011 |
+
# Multiple interpreter support requires not using any C global state,
|
| 1012 |
+
# which we don't support yet.
|
| 1013 |
+
emitter.emit_line(
|
| 1014 |
+
"{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},"
|
| 1015 |
+
)
|
| 1016 |
+
if sys.version_info >= (3, 13):
|
| 1017 |
+
# Declare support for free-threading to enable experimentation,
|
| 1018 |
+
# even if we don't properly support it.
|
| 1019 |
+
emitter.emit_line("{Py_mod_gil, Py_MOD_GIL_NOT_USED},")
|
| 1020 |
+
emitter.emit_line("{0, NULL},")
|
| 1021 |
+
emitter.emit_line("};")
|
| 1022 |
+
|
| 1023 |
+
def emit_module_methods(
|
| 1024 |
+
self, emitter: Emitter, module_name: str, module_prefix: str, module: ModuleIR
|
| 1025 |
+
) -> None:
|
| 1026 |
+
"""Emit module methods (the static PyMethodDef table)."""
|
| 1027 |
+
emitter.emit_line(f"static PyMethodDef {module_prefix}module_methods[] = {{")
|
| 1028 |
+
for fn in module.functions:
|
| 1029 |
+
if fn.class_name is not None or fn.name == TOP_LEVEL_NAME:
|
| 1030 |
+
continue
|
| 1031 |
+
# Coroutines are added to the module dict when the module is initialized.
|
| 1032 |
+
if fn.decl.is_coroutine:
|
| 1033 |
+
continue
|
| 1034 |
+
name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)
|
| 1035 |
+
if is_fastcall_supported(fn, emitter.capi_version):
|
| 1036 |
+
flag = "METH_FASTCALL"
|
| 1037 |
+
else:
|
| 1038 |
+
flag = "METH_VARARGS"
|
| 1039 |
+
doc = native_function_doc_initializer(fn)
|
| 1040 |
+
emitter.emit_line(
|
| 1041 |
+
(
|
| 1042 |
+
'{{"{name}", (PyCFunction){prefix}{cname}, {flag} | METH_KEYWORDS, '
|
| 1043 |
+
"PyDoc_STR({doc}) /* docstring */}},"
|
| 1044 |
+
).format(
|
| 1045 |
+
name=name, cname=fn.cname(emitter.names), prefix=PREFIX, flag=flag, doc=doc
|
| 1046 |
+
)
|
| 1047 |
+
)
|
| 1048 |
+
emitter.emit_line("{NULL, NULL, 0, NULL}")
|
| 1049 |
+
emitter.emit_line("};")
|
| 1050 |
+
emitter.emit_line()
|
| 1051 |
+
|
| 1052 |
+
def emit_module_def_struct(
|
| 1053 |
+
self, emitter: Emitter, module_name: str, module_prefix: str
|
| 1054 |
+
) -> None:
|
| 1055 |
+
"""Emit the static module definition struct (PyModuleDef)."""
|
| 1056 |
+
emitter.emit_lines(
|
| 1057 |
+
f"static struct PyModuleDef {module_prefix}module = {{",
|
| 1058 |
+
"PyModuleDef_HEAD_INIT,",
|
| 1059 |
+
f'"{module_name}",',
|
| 1060 |
+
"NULL, /* docstring */",
|
| 1061 |
+
"0, /* size of per-interpreter state of the module */",
|
| 1062 |
+
)
|
| 1063 |
+
if self.multi_phase_init:
|
| 1064 |
+
# Methods are added later via PyModule_AddFunctions in CPyExec_*.
|
| 1065 |
+
emitter.emit_line("NULL, /* m_methods */")
|
| 1066 |
+
else:
|
| 1067 |
+
emitter.emit_line(f"{module_prefix}module_methods,")
|
| 1068 |
+
if self.multi_phase_init and not self.use_shared_lib:
|
| 1069 |
+
slots_name = f"{module_prefix}_slots"
|
| 1070 |
+
emitter.emit_line(f"{slots_name}, /* m_slots */")
|
| 1071 |
+
else:
|
| 1072 |
+
emitter.emit_line("NULL,")
|
| 1073 |
+
emitter.emit_line("};")
|
| 1074 |
+
emitter.emit_line()
|
| 1075 |
+
|
| 1076 |
+
def emit_coroutine_wrappers(self, emitter: Emitter, module: ModuleIR, globals: str) -> None:
|
| 1077 |
+
"""Emit insertion of coroutines into the module dict when the module is initialized.
|
| 1078 |
+
Coroutines are wrapped in CPyFunction objects to enable introspection by functions like
|
| 1079 |
+
inspect.iscoroutinefunction(fn).
|
| 1080 |
+
"""
|
| 1081 |
+
for fn in module.functions:
|
| 1082 |
+
if fn.class_name is not None or fn.name == TOP_LEVEL_NAME:
|
| 1083 |
+
continue
|
| 1084 |
+
if not fn.decl.is_coroutine:
|
| 1085 |
+
continue
|
| 1086 |
+
|
| 1087 |
+
filepath = self.source_paths[module.fullname]
|
| 1088 |
+
error_stmt = " goto fail;"
|
| 1089 |
+
name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)
|
| 1090 |
+
wrapper_name = emitter.emit_cpyfunction_instance(fn, name, filepath, error_stmt)
|
| 1091 |
+
name_obj = f"{wrapper_name}_name"
|
| 1092 |
+
emitter.emit_line(f'PyObject *{name_obj} = PyUnicode_FromString("{fn.name}");')
|
| 1093 |
+
emitter.emit_line(f"if (unlikely(!{name_obj}))")
|
| 1094 |
+
emitter.emit_line(error_stmt)
|
| 1095 |
+
emitter.emit_line(
|
| 1096 |
+
f"if (PyDict_SetItem({globals}, {name_obj}, (PyObject *){wrapper_name}) < 0)"
|
| 1097 |
+
)
|
| 1098 |
+
emitter.emit_line(error_stmt)
|
| 1099 |
+
|
| 1100 |
+
def emit_module_exec_func(
|
| 1101 |
+
self, emitter: Emitter, module_name: str, module_prefix: str, module: ModuleIR
|
| 1102 |
+
) -> None:
|
| 1103 |
+
"""Emit the module exec function.
|
| 1104 |
+
|
| 1105 |
+
If we are compiling just one module, this will be the normal C API
|
| 1106 |
+
exec function. If we are compiling 2+ modules, we generate a shared
|
| 1107 |
+
library for the modules and shims that call into the shared
|
| 1108 |
+
library, and in this case the shared module defines an internal
|
| 1109 |
+
exec function for each module and these will be called by the shims
|
| 1110 |
+
via Capsules.
|
| 1111 |
+
"""
|
| 1112 |
+
exec_name = f"CPyExec_{exported_name(module_name)}"
|
| 1113 |
+
declaration = f"int {exec_name}(PyObject *module)"
|
| 1114 |
+
emitter.context.declarations[exec_name] = HeaderDeclaration(declaration + ";")
|
| 1115 |
+
module_static = self.module_internal_static_name(module_name, emitter)
|
| 1116 |
+
emitter.emit_lines(declaration, "{")
|
| 1117 |
+
emitter.emit_line("intern_strings();")
|
| 1118 |
+
if self.compiler_options.depends_on_librt_internal:
|
| 1119 |
+
emitter.emit_line("if (import_librt_internal() < 0) {")
|
| 1120 |
+
emitter.emit_line("return -1;")
|
| 1121 |
+
emitter.emit_line("}")
|
| 1122 |
+
if LIBRT_BASE64 in module.dependencies:
|
| 1123 |
+
emitter.emit_line("if (import_librt_base64() < 0) {")
|
| 1124 |
+
emitter.emit_line("return -1;")
|
| 1125 |
+
emitter.emit_line("}")
|
| 1126 |
+
if LIBRT_STRINGS in module.dependencies:
|
| 1127 |
+
emitter.emit_line("if (import_librt_strings() < 0) {")
|
| 1128 |
+
emitter.emit_line("return -1;")
|
| 1129 |
+
emitter.emit_line("}")
|
| 1130 |
+
if LIBRT_TIME in module.dependencies:
|
| 1131 |
+
emitter.emit_line("if (import_librt_time() < 0) {")
|
| 1132 |
+
emitter.emit_line("return -1;")
|
| 1133 |
+
emitter.emit_line("}")
|
| 1134 |
+
if LIBRT_VECS in module.dependencies:
|
| 1135 |
+
emitter.emit_line("if (import_librt_vecs() < 0) {")
|
| 1136 |
+
emitter.emit_line("return -1;")
|
| 1137 |
+
emitter.emit_line("}")
|
| 1138 |
+
emitter.emit_line("PyObject* modname = NULL;")
|
| 1139 |
+
if self.multi_phase_init:
|
| 1140 |
+
emitter.emit_line(f"{module_static} = module;")
|
| 1141 |
+
emitter.emit_line(
|
| 1142 |
+
f'modname = PyObject_GetAttrString((PyObject *){module_static}, "__name__");'
|
| 1143 |
+
)
|
| 1144 |
+
|
| 1145 |
+
module_globals = emitter.static_name("globals", module_name)
|
| 1146 |
+
emitter.emit_lines(
|
| 1147 |
+
f"{module_globals} = PyModule_GetDict({module_static});",
|
| 1148 |
+
f"if (unlikely({module_globals} == NULL))",
|
| 1149 |
+
" goto fail;",
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
if self.multi_phase_init:
|
| 1153 |
+
emitter.emit_lines(
|
| 1154 |
+
f"if (PyModule_AddFunctions(module, {module_prefix}module_methods) < 0)",
|
| 1155 |
+
" goto fail;",
|
| 1156 |
+
)
|
| 1157 |
+
|
| 1158 |
+
self.emit_coroutine_wrappers(emitter, module, module_globals)
|
| 1159 |
+
|
| 1160 |
+
# HACK: Manually instantiate generated classes here
|
| 1161 |
+
type_structs: list[str] = []
|
| 1162 |
+
for cl in module.classes:
|
| 1163 |
+
type_struct = emitter.type_struct_name(cl)
|
| 1164 |
+
type_structs.append(type_struct)
|
| 1165 |
+
if cl.is_generated:
|
| 1166 |
+
error_stmt = " goto fail;"
|
| 1167 |
+
emitter.emit_lines(
|
| 1168 |
+
"{t} = (PyTypeObject *)CPyType_FromTemplate("
|
| 1169 |
+
"(PyObject *){t}_template, NULL, modname);".format(t=type_struct)
|
| 1170 |
+
)
|
| 1171 |
+
emitter.emit_lines(f"if (unlikely(!{type_struct}))", error_stmt)
|
| 1172 |
+
name_prefix = cl.name_prefix(emitter.names)
|
| 1173 |
+
emitter.emit_line(f"CPyDef_{name_prefix}_trait_vtable_setup();")
|
| 1174 |
+
|
| 1175 |
+
emitter.emit_lines("if (CPyGlobalsInit() < 0)", " goto fail;")
|
| 1176 |
+
|
| 1177 |
+
self.generate_top_level_call(module, emitter)
|
| 1178 |
+
|
| 1179 |
+
emitter.emit_lines("Py_DECREF(modname);")
|
| 1180 |
+
|
| 1181 |
+
emitter.emit_line("return 0;")
|
| 1182 |
+
emitter.emit_lines("fail:")
|
| 1183 |
+
if self.multi_phase_init:
|
| 1184 |
+
emitter.emit_lines(f"{module_static} = NULL;", "Py_CLEAR(modname);")
|
| 1185 |
+
else:
|
| 1186 |
+
emitter.emit_lines(f"Py_CLEAR({module_static});", "Py_CLEAR(modname);")
|
| 1187 |
+
for name, typ in module.final_names:
|
| 1188 |
+
static_name = emitter.static_name(name, module_name)
|
| 1189 |
+
emitter.emit_dec_ref(static_name, typ, is_xdec=True)
|
| 1190 |
+
undef = emitter.c_undefined_value(typ)
|
| 1191 |
+
emitter.emit_line(f"{static_name} = {undef};")
|
| 1192 |
+
# the type objects returned from CPyType_FromTemplate are all new references
|
| 1193 |
+
# so we have to decref them
|
| 1194 |
+
for t in type_structs:
|
| 1195 |
+
emitter.emit_line(f"Py_CLEAR({t});")
|
| 1196 |
+
emitter.emit_line("return -1;")
|
| 1197 |
+
emitter.emit_line("}")
|
| 1198 |
+
|
| 1199 |
+
def emit_init_only_func(self, emitter: Emitter, module_name: str, module_prefix: str) -> None:
|
| 1200 |
+
"""Emit CPyInitOnly_* which creates the module object without executing the body.
|
| 1201 |
+
|
| 1202 |
+
This allows the caller to set up attributes like __file__ and __package__
|
| 1203 |
+
before the module body runs. Used for same-group native imports.
|
| 1204 |
+
"""
|
| 1205 |
+
init_only_name = f"CPyInitOnly_{exported_name(module_name)}"
|
| 1206 |
+
init_only_decl = f"PyObject *{init_only_name}(void)"
|
| 1207 |
+
emitter.context.declarations[init_only_name] = HeaderDeclaration(init_only_decl + ";")
|
| 1208 |
+
module_static = self.module_internal_static_name(module_name, emitter)
|
| 1209 |
+
emitter.emit_lines(init_only_decl, "{")
|
| 1210 |
+
emitter.emit_lines(
|
| 1211 |
+
f"if ({module_static}) {{",
|
| 1212 |
+
f"Py_INCREF({module_static});",
|
| 1213 |
+
f"return {module_static};",
|
| 1214 |
+
"}",
|
| 1215 |
+
)
|
| 1216 |
+
emitter.emit_lines(
|
| 1217 |
+
f"{module_static} = PyModule_Create(&{module_prefix}module);",
|
| 1218 |
+
f"return {module_static};",
|
| 1219 |
+
)
|
| 1220 |
+
emitter.emit_lines("}")
|
| 1221 |
+
emitter.emit_line("")
|
| 1222 |
+
|
| 1223 |
+
def emit_module_init_func(
|
| 1224 |
+
self, emitter: Emitter, module_name: str, module_prefix: str
|
| 1225 |
+
) -> None:
|
| 1226 |
+
if not self.use_shared_lib:
|
| 1227 |
+
declaration = f"PyMODINIT_FUNC PyInit_{module_name}(void)"
|
| 1228 |
+
else:
|
| 1229 |
+
n = f"CPyInit_{exported_name(module_name)}"
|
| 1230 |
+
declaration = f"PyObject *{n}(void)"
|
| 1231 |
+
emitter.context.declarations[n] = HeaderDeclaration(declaration + ";")
|
| 1232 |
+
|
| 1233 |
+
if self.multi_phase_init:
|
| 1234 |
+
emitter.emit_lines(declaration, "{")
|
| 1235 |
+
def_name = f"{module_prefix}module"
|
| 1236 |
+
emitter.emit_line(f"return PyModuleDef_Init(&{def_name});")
|
| 1237 |
+
emitter.emit_line("}")
|
| 1238 |
+
return
|
| 1239 |
+
|
| 1240 |
+
exec_func = f"CPyExec_{exported_name(module_name)}"
|
| 1241 |
+
|
| 1242 |
+
if self.use_shared_lib:
|
| 1243 |
+
self.emit_init_only_func(emitter, module_name, module_prefix)
|
| 1244 |
+
|
| 1245 |
+
# Emit CPyInit_* / PyInit_* which creates the module and executes the body.
|
| 1246 |
+
emitter.emit_lines(declaration, "{")
|
| 1247 |
+
module_static = self.module_internal_static_name(module_name, emitter)
|
| 1248 |
+
|
| 1249 |
+
emitter.emit_line("PyObject* modname = NULL;")
|
| 1250 |
+
emitter.emit_lines(
|
| 1251 |
+
f"if ({module_static}) {{",
|
| 1252 |
+
f"Py_INCREF({module_static});",
|
| 1253 |
+
f"return {module_static};",
|
| 1254 |
+
"}",
|
| 1255 |
+
)
|
| 1256 |
+
|
| 1257 |
+
emitter.emit_lines(
|
| 1258 |
+
f"{module_static} = PyModule_Create(&{module_prefix}module);",
|
| 1259 |
+
f"if (unlikely({module_static} == NULL))",
|
| 1260 |
+
" goto fail;",
|
| 1261 |
+
)
|
| 1262 |
+
|
| 1263 |
+
emitter.emit_line(f'modname = PyUnicode_FromString("{module_name}");')
|
| 1264 |
+
emitter.emit_line("if (modname == NULL) CPyError_OutOfMemory();")
|
| 1265 |
+
emitter.emit_line("int rv = 0;")
|
| 1266 |
+
if self.group_name:
|
| 1267 |
+
shared_lib_mod_name = shared_lib_name(self.group_name)
|
| 1268 |
+
emitter.emit_line("PyObject *mod_dict = PyImport_GetModuleDict();")
|
| 1269 |
+
emitter.emit_line("PyObject *shared_lib = NULL;")
|
| 1270 |
+
emitter.emit_line(
|
| 1271 |
+
f'rv = PyDict_GetItemStringRef(mod_dict, "{shared_lib_mod_name}", &shared_lib);'
|
| 1272 |
+
)
|
| 1273 |
+
emitter.emit_line("if (rv < 0) goto fail;")
|
| 1274 |
+
emitter.emit_line(
|
| 1275 |
+
'PyObject *shared_lib_file = PyObject_GetAttrString(shared_lib, "__file__");'
|
| 1276 |
+
)
|
| 1277 |
+
emitter.emit_line("if (shared_lib_file == NULL) goto fail;")
|
| 1278 |
+
else:
|
| 1279 |
+
emitter.emit_line(
|
| 1280 |
+
f'PyObject *shared_lib_file = PyUnicode_FromString("{module_name + EXT_SUFFIX}");'
|
| 1281 |
+
)
|
| 1282 |
+
emitter.emit_line("if (shared_lib_file == NULL) CPyError_OutOfMemory();")
|
| 1283 |
+
emitter.emit_line(f'PyObject *ext_suffix = PyUnicode_FromString("{EXT_SUFFIX}");')
|
| 1284 |
+
emitter.emit_line("if (ext_suffix == NULL) CPyError_OutOfMemory();")
|
| 1285 |
+
is_pkg = int(self.source_paths[module_name].endswith("__init__.py"))
|
| 1286 |
+
emitter.emit_line(f"Py_ssize_t is_pkg = {is_pkg};")
|
| 1287 |
+
|
| 1288 |
+
emitter.emit_line(
|
| 1289 |
+
f"rv = CPyImport_SetDunderAttrs({module_static}, modname, shared_lib_file, ext_suffix, is_pkg);"
|
| 1290 |
+
)
|
| 1291 |
+
emitter.emit_line("Py_DECREF(ext_suffix);")
|
| 1292 |
+
emitter.emit_line("Py_DECREF(shared_lib_file);")
|
| 1293 |
+
emitter.emit_line("if (rv < 0) goto fail;")
|
| 1294 |
+
|
| 1295 |
+
# Register in sys.modules early so that circular imports via
|
| 1296 |
+
# CPyImport_ImportNative can detect that this module is already
|
| 1297 |
+
# being initialized and avoid re-executing the module body.
|
| 1298 |
+
emitter.emit_line(
|
| 1299 |
+
f"if (PyObject_SetItem(PyImport_GetModuleDict(), modname, {module_static}) < 0)"
|
| 1300 |
+
)
|
| 1301 |
+
emitter.emit_line(" goto fail;")
|
| 1302 |
+
emitter.emit_line("Py_CLEAR(modname);")
|
| 1303 |
+
emitter.emit_lines(f"if ({exec_func}({module_static}) != 0)", " goto fail;")
|
| 1304 |
+
emitter.emit_line(f"return {module_static};")
|
| 1305 |
+
emitter.emit_lines("fail:")
|
| 1306 |
+
# Clean up on failure: remove from sys.modules and clear the static
|
| 1307 |
+
# so that a subsequent import attempt will retry initialization.
|
| 1308 |
+
emitter.emit_line("{")
|
| 1309 |
+
emitter.emit_line(" PyObject *exc_type, *exc_val, *exc_tb;")
|
| 1310 |
+
emitter.emit_line(" PyErr_Fetch(&exc_type, &exc_val, &exc_tb);")
|
| 1311 |
+
emitter.emit_line(" if (modname == NULL) {")
|
| 1312 |
+
emitter.emit_line(f' modname = PyUnicode_FromString("{module_name}");')
|
| 1313 |
+
emitter.emit_line(" if (modname == NULL) CPyError_OutOfMemory();")
|
| 1314 |
+
emitter.emit_line(" }")
|
| 1315 |
+
emitter.emit_line(" PyObject_DelItem(PyImport_GetModuleDict(), modname);")
|
| 1316 |
+
emitter.emit_line(" PyErr_Clear();")
|
| 1317 |
+
emitter.emit_line(" Py_DECREF(modname);")
|
| 1318 |
+
emitter.emit_line(f" Py_CLEAR({module_static});")
|
| 1319 |
+
emitter.emit_line(" PyErr_Restore(exc_type, exc_val, exc_tb);")
|
| 1320 |
+
emitter.emit_line("}")
|
| 1321 |
+
emitter.emit_line("return NULL;")
|
| 1322 |
+
emitter.emit_lines("}")
|
| 1323 |
+
|
| 1324 |
+
def generate_top_level_call(self, module: ModuleIR, emitter: Emitter) -> None:
|
| 1325 |
+
"""Generate call to function representing module top level."""
|
| 1326 |
+
# Optimization: we tend to put the top level last, so reverse iterate
|
| 1327 |
+
for fn in reversed(module.functions):
|
| 1328 |
+
if fn.name == TOP_LEVEL_NAME:
|
| 1329 |
+
emitter.emit_lines(
|
| 1330 |
+
f"char result = {emitter.native_function_name(fn.decl)}();",
|
| 1331 |
+
"if (result == 2)",
|
| 1332 |
+
" goto fail;",
|
| 1333 |
+
)
|
| 1334 |
+
break
|
| 1335 |
+
|
| 1336 |
+
def toposort_declarations(self) -> list[HeaderDeclaration]:
|
| 1337 |
+
"""Topologically sort the declaration dict by dependencies.
|
| 1338 |
+
|
| 1339 |
+
Declarations can require other declarations to come prior in C (such as declaring structs).
|
| 1340 |
+
In order to guarantee that the C output will compile the declarations will thus need to
|
| 1341 |
+
be properly ordered. This simple DFS guarantees that we have a proper ordering.
|
| 1342 |
+
|
| 1343 |
+
This runs in O(V + E).
|
| 1344 |
+
"""
|
| 1345 |
+
result = []
|
| 1346 |
+
marked_declarations: dict[str, MarkedDeclaration] = {}
|
| 1347 |
+
for k, v in self.context.declarations.items():
|
| 1348 |
+
marked_declarations[k] = MarkedDeclaration(v, False)
|
| 1349 |
+
|
| 1350 |
+
def _toposort_visit(name: str) -> None:
|
| 1351 |
+
decl = marked_declarations[name]
|
| 1352 |
+
if decl.mark:
|
| 1353 |
+
return
|
| 1354 |
+
|
| 1355 |
+
for child in decl.declaration.dependencies:
|
| 1356 |
+
_toposort_visit(child)
|
| 1357 |
+
|
| 1358 |
+
result.append(decl.declaration)
|
| 1359 |
+
decl.mark = True
|
| 1360 |
+
|
| 1361 |
+
for name in marked_declarations:
|
| 1362 |
+
_toposort_visit(name)
|
| 1363 |
+
|
| 1364 |
+
return result
|
| 1365 |
+
|
| 1366 |
+
def declare_global(
|
| 1367 |
+
self, type_spaced: str, name: str, *, initializer: str | None = None
|
| 1368 |
+
) -> None:
|
| 1369 |
+
if "[" not in type_spaced:
|
| 1370 |
+
base = f"{type_spaced}{name}"
|
| 1371 |
+
else:
|
| 1372 |
+
a, b = type_spaced.split("[", 1)
|
| 1373 |
+
base = f"{a}{name}[{b}"
|
| 1374 |
+
|
| 1375 |
+
if not initializer:
|
| 1376 |
+
defn = None
|
| 1377 |
+
else:
|
| 1378 |
+
defn = [f"{base} = {initializer};"]
|
| 1379 |
+
if name not in self.context.declarations:
|
| 1380 |
+
self.context.declarations[name] = HeaderDeclaration(f"{base};", defn=defn)
|
| 1381 |
+
|
| 1382 |
+
def declare_internal_globals(self, module_name: str, emitter: Emitter) -> None:
|
| 1383 |
+
static_name = emitter.static_name("globals", module_name)
|
| 1384 |
+
if static_name not in self.context.declarations:
|
| 1385 |
+
self.context.declarations[static_name] = HeaderDeclaration(
|
| 1386 |
+
f"PyObject *{static_name};", needs_export=True
|
| 1387 |
+
)
|
| 1388 |
+
|
| 1389 |
+
def module_internal_static_name(self, module_name: str, emitter: Emitter) -> str:
|
| 1390 |
+
return emitter.static_name(module_name + "__internal", None, prefix=MODULE_PREFIX)
|
| 1391 |
+
|
| 1392 |
+
def declare_module(self, module_name: str, emitter: Emitter) -> None:
|
| 1393 |
+
# We declare two globals for each compiled module:
|
| 1394 |
+
# one used internally in the implementation of module init to cache results
|
| 1395 |
+
# and prevent infinite recursion in import cycles, and one used
|
| 1396 |
+
# by other modules to refer to it.
|
| 1397 |
+
if module_name in self.modules:
|
| 1398 |
+
internal_static_name = self.module_internal_static_name(module_name, emitter)
|
| 1399 |
+
self.declare_global("CPyModule *", internal_static_name, initializer="NULL")
|
| 1400 |
+
static_name = emitter.static_name(module_name, None, prefix=MODULE_PREFIX)
|
| 1401 |
+
self.declare_global("CPyModule *", static_name)
|
| 1402 |
+
self.simple_inits.append((static_name, "Py_None"))
|
| 1403 |
+
|
| 1404 |
+
def declare_imports(self, imps: Iterable[str], emitter: Emitter) -> None:
|
| 1405 |
+
for imp in imps:
|
| 1406 |
+
self.declare_module(imp, emitter)
|
| 1407 |
+
|
| 1408 |
+
def declare_finals(
|
| 1409 |
+
self, module: str, final_names: Iterable[tuple[str, RType]], emitter: Emitter
|
| 1410 |
+
) -> None:
|
| 1411 |
+
for name, typ in final_names:
|
| 1412 |
+
static_name = emitter.static_name(name, module)
|
| 1413 |
+
emitter.context.declarations[static_name] = HeaderDeclaration(
|
| 1414 |
+
f"{emitter.ctype_spaced(typ)}{static_name};",
|
| 1415 |
+
[self.final_definition(module, name, typ, emitter)],
|
| 1416 |
+
needs_export=True,
|
| 1417 |
+
)
|
| 1418 |
+
|
| 1419 |
+
def final_definition(self, module: str, name: str, typ: RType, emitter: Emitter) -> str:
|
| 1420 |
+
static_name = emitter.static_name(name, module)
|
| 1421 |
+
# Here we rely on the fact that undefined value and error value are always the same
|
| 1422 |
+
undefined = emitter.c_initializer_undefined_value(typ)
|
| 1423 |
+
return f"{emitter.ctype_spaced(typ)}{static_name} = {undefined};"
|
| 1424 |
+
|
| 1425 |
+
def declare_static_pyobject(self, identifier: str, emitter: Emitter) -> None:
|
| 1426 |
+
symbol = emitter.static_name(identifier, None)
|
| 1427 |
+
self.declare_global("PyObject *", symbol)
|
| 1428 |
+
|
| 1429 |
+
def declare_type_vars(self, module: str, type_var_names: list[str], emitter: Emitter) -> None:
|
| 1430 |
+
for name in type_var_names:
|
| 1431 |
+
static_name = emitter.static_name(name, module, prefix=TYPE_VAR_PREFIX)
|
| 1432 |
+
emitter.context.declarations[static_name] = HeaderDeclaration(
|
| 1433 |
+
f"PyObject *{static_name};",
|
| 1434 |
+
[f"PyObject *{static_name} = NULL;"],
|
| 1435 |
+
needs_export=False,
|
| 1436 |
+
)
|
| 1437 |
+
|
| 1438 |
+
|
| 1439 |
+
T = TypeVar("T")
|
| 1440 |
+
|
| 1441 |
+
|
| 1442 |
+
def toposort(deps: dict[T, set[T]]) -> list[T]:
|
| 1443 |
+
"""Topologically sort a dict from item to dependencies.
|
| 1444 |
+
|
| 1445 |
+
This runs in O(V + E).
|
| 1446 |
+
"""
|
| 1447 |
+
result = []
|
| 1448 |
+
visited: set[T] = set()
|
| 1449 |
+
|
| 1450 |
+
def visit(item: T) -> None:
|
| 1451 |
+
if item in visited:
|
| 1452 |
+
return
|
| 1453 |
+
|
| 1454 |
+
for child in deps[item]:
|
| 1455 |
+
visit(child)
|
| 1456 |
+
|
| 1457 |
+
result.append(item)
|
| 1458 |
+
visited.add(item)
|
| 1459 |
+
|
| 1460 |
+
for item in deps:
|
| 1461 |
+
visit(item)
|
| 1462 |
+
|
| 1463 |
+
return result
|
| 1464 |
+
|
| 1465 |
+
|
| 1466 |
+
def is_fastcall_supported(fn: FuncIR, capi_version: tuple[int, int]) -> bool:
|
| 1467 |
+
if fn.class_name is not None:
|
| 1468 |
+
if fn.name == "__call__":
|
| 1469 |
+
# We can use vectorcalls (PEP 590) when supported
|
| 1470 |
+
return True
|
| 1471 |
+
# TODO: Support fastcall for __init__ and __new__.
|
| 1472 |
+
return fn.name != "__init__" and fn.name != "__new__"
|
| 1473 |
+
return True
|
| 1474 |
+
|
| 1475 |
+
|
| 1476 |
+
def collect_literals(fn: FuncIR, literals: Literals) -> None:
|
| 1477 |
+
"""Store all Python literal object refs in fn.
|
| 1478 |
+
|
| 1479 |
+
Collecting literals must happen only after we have the final IR.
|
| 1480 |
+
This way we won't include literals that have been optimized away.
|
| 1481 |
+
"""
|
| 1482 |
+
for block in fn.blocks:
|
| 1483 |
+
for op in block.ops:
|
| 1484 |
+
if isinstance(op, LoadLiteral):
|
| 1485 |
+
literals.record_literal(op.value)
|
| 1486 |
+
|
| 1487 |
+
|
| 1488 |
+
def c_string_array_initializer(components: list[bytes]) -> str:
|
| 1489 |
+
result = []
|
| 1490 |
+
result.append("{\n")
|
| 1491 |
+
for s in components:
|
| 1492 |
+
result.append(" " + c_string_initializer(s) + ",\n")
|
| 1493 |
+
result.append("}")
|
| 1494 |
+
return "".join(result)
|
micromamba_root/Lib/site-packages/mypyc/codegen/emitwrapper.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/codegen/emitwrapper.py
ADDED
|
@@ -0,0 +1,978 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate CPython API wrapper functions for native functions.
|
| 2 |
+
|
| 3 |
+
The wrapper functions are used by the CPython runtime when calling
|
| 4 |
+
native functions from interpreted code, and when the called function
|
| 5 |
+
can't be determined statically in compiled code. They validate, match,
|
| 6 |
+
unbox and type check function arguments, and box return values as
|
| 7 |
+
needed. All wrappers accept and return 'PyObject *' (boxed) values.
|
| 8 |
+
|
| 9 |
+
The wrappers aren't used for most calls between two native functions
|
| 10 |
+
or methods in a single compilation unit.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from collections.abc import Sequence
|
| 16 |
+
|
| 17 |
+
from mypy.nodes import ARG_NAMED, ARG_NAMED_OPT, ARG_OPT, ARG_POS, ARG_STAR, ARG_STAR2, ArgKind
|
| 18 |
+
from mypy.operators import op_methods_to_symbols, reverse_op_method_names, reverse_op_methods
|
| 19 |
+
from mypyc.codegen.emit import AssignHandler, Emitter, ErrorHandler, GotoHandler, ReturnHandler
|
| 20 |
+
from mypyc.common import (
|
| 21 |
+
BITMAP_BITS,
|
| 22 |
+
BITMAP_TYPE,
|
| 23 |
+
DUNDER_PREFIX,
|
| 24 |
+
NATIVE_PREFIX,
|
| 25 |
+
PREFIX,
|
| 26 |
+
bitmap_name,
|
| 27 |
+
)
|
| 28 |
+
from mypyc.ir.class_ir import ClassIR
|
| 29 |
+
from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncIR, RuntimeArg
|
| 30 |
+
from mypyc.ir.rtypes import (
|
| 31 |
+
RInstance,
|
| 32 |
+
RType,
|
| 33 |
+
is_bool_rprimitive,
|
| 34 |
+
is_int_rprimitive,
|
| 35 |
+
is_object_rprimitive,
|
| 36 |
+
object_rprimitive,
|
| 37 |
+
)
|
| 38 |
+
from mypyc.namegen import NameGenerator
|
| 39 |
+
|
| 40 |
+
# Generic vectorcall wrapper functions (Python 3.7+)
|
| 41 |
+
#
|
| 42 |
+
# A wrapper function has a signature like this:
|
| 43 |
+
#
|
| 44 |
+
# PyObject *fn(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
|
| 45 |
+
#
|
| 46 |
+
# The function takes a self object, pointer to an array of arguments,
|
| 47 |
+
# the number of positional arguments, and a tuple of keyword argument
|
| 48 |
+
# names (that are stored starting in args[nargs]).
|
| 49 |
+
#
|
| 50 |
+
# It returns the returned object, or NULL on an exception.
|
| 51 |
+
#
|
| 52 |
+
# These are more efficient than legacy wrapper functions, since
|
| 53 |
+
# usually no tuple or dict objects need to be created for the
|
| 54 |
+
# arguments. Vectorcalls also use pre-constructed str objects for
|
| 55 |
+
# keyword argument names and other pre-computed information, instead
|
| 56 |
+
# of processing the argument format string on each call.
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def wrapper_function_header(fn: FuncIR, names: NameGenerator) -> str:
|
| 60 |
+
"""Return header of a vectorcall wrapper function.
|
| 61 |
+
|
| 62 |
+
See comment above for a summary of the arguments.
|
| 63 |
+
"""
|
| 64 |
+
assert not fn.internal
|
| 65 |
+
return (
|
| 66 |
+
"PyObject *{prefix}{name}("
|
| 67 |
+
"PyObject *self, PyObject *const *args, size_t nargs, PyObject *kwnames)"
|
| 68 |
+
).format(prefix=PREFIX, name=fn.cname(names))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def generate_traceback_code(
|
| 72 |
+
fn: FuncIR, emitter: Emitter, source_path: str, module_name: str
|
| 73 |
+
) -> str:
|
| 74 |
+
# If we hit an error while processing arguments, then we emit a
|
| 75 |
+
# traceback frame to make it possible to debug where it happened.
|
| 76 |
+
# Unlike traceback frames added for exceptions seen in IR, we do this
|
| 77 |
+
# even if there is no `traceback_name`. This is because the error will
|
| 78 |
+
# have originated here and so we need it in the traceback.
|
| 79 |
+
globals_static = emitter.static_name("globals", module_name)
|
| 80 |
+
traceback_code = 'CPy_AddTraceback("%s", "%s", %d, %s);' % (
|
| 81 |
+
source_path.replace("\\", "\\\\"),
|
| 82 |
+
fn.traceback_name or fn.name,
|
| 83 |
+
fn.line,
|
| 84 |
+
globals_static,
|
| 85 |
+
)
|
| 86 |
+
return traceback_code
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def make_arg_groups(args: list[RuntimeArg]) -> dict[ArgKind, list[RuntimeArg]]:
|
| 90 |
+
"""Group arguments by kind."""
|
| 91 |
+
return {k: [arg for arg in args if arg.kind == k] for k in ArgKind}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def reorder_arg_groups(groups: dict[ArgKind, list[RuntimeArg]]) -> list[RuntimeArg]:
|
| 95 |
+
"""Reorder argument groups to match their order in a format string."""
|
| 96 |
+
return groups[ARG_POS] + groups[ARG_OPT] + groups[ARG_NAMED_OPT] + groups[ARG_NAMED]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def make_static_kwlist(args: list[RuntimeArg]) -> str:
|
| 100 |
+
arg_names = "".join(f'"{arg.name}", ' for arg in args)
|
| 101 |
+
return f"static const char * const kwlist[] = {{{arg_names}0}};"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def make_format_string(func_name: str | None, groups: dict[ArgKind, list[RuntimeArg]]) -> str:
|
| 105 |
+
"""Return a format string that specifies the accepted arguments.
|
| 106 |
+
|
| 107 |
+
The format string is an extended subset of what is supported by
|
| 108 |
+
PyArg_ParseTupleAndKeywords(). Only the type 'O' is used, and we
|
| 109 |
+
also support some extensions:
|
| 110 |
+
|
| 111 |
+
- Required keyword-only arguments are introduced after '@'
|
| 112 |
+
- If the function receives *args or **kwargs, we add a '%' prefix
|
| 113 |
+
|
| 114 |
+
Each group requires the previous groups' delimiters to be present
|
| 115 |
+
first.
|
| 116 |
+
|
| 117 |
+
These are used by both vectorcall and legacy wrapper functions.
|
| 118 |
+
"""
|
| 119 |
+
format = ""
|
| 120 |
+
if groups[ARG_STAR] or groups[ARG_STAR2]:
|
| 121 |
+
format += "%"
|
| 122 |
+
format += "O" * len(groups[ARG_POS])
|
| 123 |
+
if groups[ARG_OPT] or groups[ARG_NAMED_OPT] or groups[ARG_NAMED]:
|
| 124 |
+
format += "|" + "O" * len(groups[ARG_OPT])
|
| 125 |
+
if groups[ARG_NAMED_OPT] or groups[ARG_NAMED]:
|
| 126 |
+
format += "$" + "O" * len(groups[ARG_NAMED_OPT])
|
| 127 |
+
if groups[ARG_NAMED]:
|
| 128 |
+
format += "@" + "O" * len(groups[ARG_NAMED])
|
| 129 |
+
if func_name is not None:
|
| 130 |
+
format += f":{func_name}"
|
| 131 |
+
return format
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def generate_wrapper_function(
|
| 135 |
+
fn: FuncIR, emitter: Emitter, source_path: str, module_name: str
|
| 136 |
+
) -> None:
|
| 137 |
+
"""Generate a CPython-compatible vectorcall wrapper for a native function.
|
| 138 |
+
|
| 139 |
+
In particular, this handles unboxing the arguments, calling the native function, and
|
| 140 |
+
then boxing the return value.
|
| 141 |
+
"""
|
| 142 |
+
emitter.emit_line(f"{wrapper_function_header(fn, emitter.names)} {{")
|
| 143 |
+
|
| 144 |
+
# If fn is a method, then the first argument is a self param
|
| 145 |
+
real_args = list(fn.args)
|
| 146 |
+
if fn.sig.num_bitmap_args:
|
| 147 |
+
real_args = real_args[: -fn.sig.num_bitmap_args]
|
| 148 |
+
if fn.class_name and fn.decl.kind != FUNC_STATICMETHOD:
|
| 149 |
+
arg = real_args.pop(0)
|
| 150 |
+
emitter.emit_line(f"PyObject *obj_{arg.name} = self;")
|
| 151 |
+
|
| 152 |
+
# Need to order args as: required, optional, kwonly optional, kwonly required
|
| 153 |
+
# This is because CPyArg_ParseStackAndKeywords format string requires
|
| 154 |
+
# them grouped in that way.
|
| 155 |
+
groups = make_arg_groups(real_args)
|
| 156 |
+
reordered_args = reorder_arg_groups(groups)
|
| 157 |
+
|
| 158 |
+
emitter.emit_line(make_static_kwlist(reordered_args))
|
| 159 |
+
fmt = make_format_string(fn.name, groups)
|
| 160 |
+
# Define the arguments the function accepts (but no types yet)
|
| 161 |
+
emitter.emit_line(f'static CPyArg_Parser parser = {{"{fmt}", kwlist, 0}};')
|
| 162 |
+
|
| 163 |
+
for arg in real_args:
|
| 164 |
+
emitter.emit_line(
|
| 165 |
+
"PyObject *obj_{}{};".format(arg.name, " = NULL" if arg.optional else "")
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
cleanups = [f"CPy_DECREF(obj_{arg.name});" for arg in groups[ARG_STAR] + groups[ARG_STAR2]]
|
| 169 |
+
|
| 170 |
+
arg_ptrs: list[str] = []
|
| 171 |
+
if groups[ARG_STAR] or groups[ARG_STAR2]:
|
| 172 |
+
arg_ptrs += [f"&obj_{groups[ARG_STAR][0].name}" if groups[ARG_STAR] else "NULL"]
|
| 173 |
+
arg_ptrs += [f"&obj_{groups[ARG_STAR2][0].name}" if groups[ARG_STAR2] else "NULL"]
|
| 174 |
+
arg_ptrs += [f"&obj_{arg.name}" for arg in reordered_args]
|
| 175 |
+
|
| 176 |
+
if fn.name == "__call__":
|
| 177 |
+
nargs = "PyVectorcall_NARGS(nargs)"
|
| 178 |
+
else:
|
| 179 |
+
nargs = "nargs"
|
| 180 |
+
parse_fn = "CPyArg_ParseStackAndKeywords"
|
| 181 |
+
# Special case some common signatures
|
| 182 |
+
if not real_args:
|
| 183 |
+
# No args
|
| 184 |
+
parse_fn = "CPyArg_ParseStackAndKeywordsNoArgs"
|
| 185 |
+
elif len(real_args) == 1 and len(groups[ARG_POS]) == 1:
|
| 186 |
+
# Single positional arg
|
| 187 |
+
parse_fn = "CPyArg_ParseStackAndKeywordsOneArg"
|
| 188 |
+
elif len(real_args) == len(groups[ARG_POS]) + len(groups[ARG_OPT]):
|
| 189 |
+
# No keyword-only args, *args or **kwargs
|
| 190 |
+
parse_fn = "CPyArg_ParseStackAndKeywordsSimple"
|
| 191 |
+
emitter.emit_lines(
|
| 192 |
+
"if (!{}(args, {}, kwnames, &parser{})) {{".format(
|
| 193 |
+
parse_fn, nargs, "".join(", " + n for n in arg_ptrs)
|
| 194 |
+
),
|
| 195 |
+
"return NULL;",
|
| 196 |
+
"}",
|
| 197 |
+
)
|
| 198 |
+
for i in range(fn.sig.num_bitmap_args):
|
| 199 |
+
name = bitmap_name(i)
|
| 200 |
+
emitter.emit_line(f"{BITMAP_TYPE} {name} = 0;")
|
| 201 |
+
traceback_code = generate_traceback_code(fn, emitter, source_path, module_name)
|
| 202 |
+
generate_wrapper_core(
|
| 203 |
+
fn,
|
| 204 |
+
emitter,
|
| 205 |
+
groups[ARG_OPT] + groups[ARG_NAMED_OPT],
|
| 206 |
+
cleanups=cleanups,
|
| 207 |
+
traceback_code=traceback_code,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
emitter.emit_line("}")
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# Legacy generic wrapper functions
|
| 214 |
+
#
|
| 215 |
+
# These take a self object, a Python tuple of positional arguments,
|
| 216 |
+
# and a dict of keyword arguments. These are a lot slower than
|
| 217 |
+
# vectorcall wrappers, especially in calls involving keyword
|
| 218 |
+
# arguments.
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def legacy_wrapper_function_header(fn: FuncIR, names: NameGenerator) -> str:
|
| 222 |
+
return "PyObject *{prefix}{name}(PyObject *self, PyObject *args, PyObject *kw)".format(
|
| 223 |
+
prefix=PREFIX, name=fn.cname(names)
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def generate_legacy_wrapper_function(
|
| 228 |
+
fn: FuncIR, emitter: Emitter, source_path: str, module_name: str
|
| 229 |
+
) -> None:
|
| 230 |
+
"""Generates a CPython-compatible legacy wrapper for a native function.
|
| 231 |
+
|
| 232 |
+
In particular, this handles unboxing the arguments, calling the native function, and
|
| 233 |
+
then boxing the return value.
|
| 234 |
+
"""
|
| 235 |
+
emitter.emit_line(f"{legacy_wrapper_function_header(fn, emitter.names)} {{")
|
| 236 |
+
|
| 237 |
+
# If fn is a method, then the first argument is a self param
|
| 238 |
+
real_args = list(fn.args)
|
| 239 |
+
if fn.sig.num_bitmap_args:
|
| 240 |
+
real_args = real_args[: -fn.sig.num_bitmap_args]
|
| 241 |
+
if fn.class_name and (fn.decl.name == "__new__" or fn.decl.kind != FUNC_STATICMETHOD):
|
| 242 |
+
arg = real_args.pop(0)
|
| 243 |
+
emitter.emit_line(f"PyObject *obj_{arg.name} = self;")
|
| 244 |
+
|
| 245 |
+
# Need to order args as: required, optional, kwonly optional, kwonly required
|
| 246 |
+
# This is because CPyArg_ParseTupleAndKeywords format string requires
|
| 247 |
+
# them grouped in that way.
|
| 248 |
+
groups = make_arg_groups(real_args)
|
| 249 |
+
reordered_args = reorder_arg_groups(groups)
|
| 250 |
+
|
| 251 |
+
emitter.emit_line(make_static_kwlist(reordered_args))
|
| 252 |
+
for arg in real_args:
|
| 253 |
+
emitter.emit_line(
|
| 254 |
+
"PyObject *obj_{}{};".format(arg.name, " = NULL" if arg.optional else "")
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
cleanups = [f"CPy_DECREF(obj_{arg.name});" for arg in groups[ARG_STAR] + groups[ARG_STAR2]]
|
| 258 |
+
|
| 259 |
+
arg_ptrs: list[str] = []
|
| 260 |
+
if groups[ARG_STAR] or groups[ARG_STAR2]:
|
| 261 |
+
arg_ptrs += [f"&obj_{groups[ARG_STAR][0].name}" if groups[ARG_STAR] else "NULL"]
|
| 262 |
+
arg_ptrs += [f"&obj_{groups[ARG_STAR2][0].name}" if groups[ARG_STAR2] else "NULL"]
|
| 263 |
+
arg_ptrs += [f"&obj_{arg.name}" for arg in reordered_args]
|
| 264 |
+
|
| 265 |
+
emitter.emit_lines(
|
| 266 |
+
'if (!CPyArg_ParseTupleAndKeywords(args, kw, "{}", "{}", kwlist{})) {{'.format(
|
| 267 |
+
make_format_string(None, groups), fn.name, "".join(", " + n for n in arg_ptrs)
|
| 268 |
+
),
|
| 269 |
+
"return NULL;",
|
| 270 |
+
"}",
|
| 271 |
+
)
|
| 272 |
+
for i in range(fn.sig.num_bitmap_args):
|
| 273 |
+
name = bitmap_name(i)
|
| 274 |
+
emitter.emit_line(f"{BITMAP_TYPE} {name} = 0;")
|
| 275 |
+
traceback_code = generate_traceback_code(fn, emitter, source_path, module_name)
|
| 276 |
+
generate_wrapper_core(
|
| 277 |
+
fn,
|
| 278 |
+
emitter,
|
| 279 |
+
groups[ARG_OPT] + groups[ARG_NAMED_OPT],
|
| 280 |
+
cleanups=cleanups,
|
| 281 |
+
traceback_code=traceback_code,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
emitter.emit_line("}")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# Specialized wrapper functions
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def generate_dunder_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 291 |
+
"""Generates a wrapper for native __dunder__ methods to be able to fit into the mapping
|
| 292 |
+
protocol slot. This specifically means that the arguments are taken as *PyObjects and returned
|
| 293 |
+
as *PyObjects.
|
| 294 |
+
"""
|
| 295 |
+
gen = WrapperGenerator(cl, emitter)
|
| 296 |
+
gen.set_target(fn)
|
| 297 |
+
gen.emit_header()
|
| 298 |
+
gen.emit_arg_processing()
|
| 299 |
+
gen.emit_call()
|
| 300 |
+
gen.finish()
|
| 301 |
+
return gen.wrapper_name()
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def generate_ipow_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 305 |
+
"""Generate a wrapper for native __ipow__.
|
| 306 |
+
|
| 307 |
+
Since __ipow__ fills a ternary slot, but almost no one defines __ipow__ to take three
|
| 308 |
+
arguments, the wrapper needs to tweaked to force it to accept three arguments.
|
| 309 |
+
"""
|
| 310 |
+
gen = WrapperGenerator(cl, emitter)
|
| 311 |
+
gen.set_target(fn)
|
| 312 |
+
assert len(fn.args) in (2, 3), "__ipow__ should only take 2 or 3 arguments"
|
| 313 |
+
gen.arg_names = ["self", "exp", "mod"]
|
| 314 |
+
gen.emit_header()
|
| 315 |
+
gen.emit_arg_processing()
|
| 316 |
+
handle_third_pow_argument(
|
| 317 |
+
fn,
|
| 318 |
+
emitter,
|
| 319 |
+
gen,
|
| 320 |
+
if_unsupported=[
|
| 321 |
+
'PyErr_SetString(PyExc_TypeError, "__ipow__ takes 2 positional arguments but 3 were given");',
|
| 322 |
+
"return NULL;",
|
| 323 |
+
],
|
| 324 |
+
)
|
| 325 |
+
gen.emit_call()
|
| 326 |
+
gen.finish()
|
| 327 |
+
return gen.wrapper_name()
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def generate_bin_op_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 331 |
+
"""Generates a wrapper for a native binary dunder method.
|
| 332 |
+
|
| 333 |
+
The same wrapper that handles the forward method (e.g. __add__) also handles
|
| 334 |
+
the corresponding reverse method (e.g. __radd__), if defined.
|
| 335 |
+
|
| 336 |
+
Both arguments and the return value are PyObject *.
|
| 337 |
+
"""
|
| 338 |
+
gen = WrapperGenerator(cl, emitter)
|
| 339 |
+
gen.set_target(fn)
|
| 340 |
+
if fn.name in ("__pow__", "__rpow__"):
|
| 341 |
+
gen.arg_names = ["left", "right", "mod"]
|
| 342 |
+
else:
|
| 343 |
+
gen.arg_names = ["left", "right"]
|
| 344 |
+
wrapper_name = gen.wrapper_name()
|
| 345 |
+
|
| 346 |
+
gen.emit_header()
|
| 347 |
+
if fn.name not in reverse_op_methods and fn.name in reverse_op_method_names:
|
| 348 |
+
# There's only a reverse operator method.
|
| 349 |
+
generate_bin_op_reverse_only_wrapper(fn, emitter, gen)
|
| 350 |
+
else:
|
| 351 |
+
rmethod = reverse_op_methods[fn.name]
|
| 352 |
+
fn_rev = cl.get_method(rmethod)
|
| 353 |
+
if fn_rev is None:
|
| 354 |
+
# There's only a forward operator method.
|
| 355 |
+
generate_bin_op_forward_only_wrapper(fn, emitter, gen)
|
| 356 |
+
else:
|
| 357 |
+
# There's both a forward and a reverse operator method.
|
| 358 |
+
generate_bin_op_both_wrappers(cl, fn, fn_rev, emitter, gen)
|
| 359 |
+
return wrapper_name
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def generate_bin_op_forward_only_wrapper(
|
| 363 |
+
fn: FuncIR, emitter: Emitter, gen: WrapperGenerator
|
| 364 |
+
) -> None:
|
| 365 |
+
gen.emit_arg_processing(error=GotoHandler("typefail"), raise_exception=False)
|
| 366 |
+
handle_third_pow_argument(fn, emitter, gen, if_unsupported=["goto typefail;"])
|
| 367 |
+
gen.emit_call(not_implemented_handler="goto typefail;")
|
| 368 |
+
gen.emit_error_handling()
|
| 369 |
+
emitter.emit_label("typefail")
|
| 370 |
+
# If some argument has an incompatible type, treat this the same as
|
| 371 |
+
# returning NotImplemented, and try to call the reverse operator method.
|
| 372 |
+
#
|
| 373 |
+
# Note that in normal Python you'd instead of an explicit
|
| 374 |
+
# return of NotImplemented, but it doesn't generally work here
|
| 375 |
+
# the body won't be executed at all if there is an argument
|
| 376 |
+
# type check failure.
|
| 377 |
+
#
|
| 378 |
+
# The recommended way is to still use a type check in the
|
| 379 |
+
# body. This will only be used in interpreted mode:
|
| 380 |
+
#
|
| 381 |
+
# def __add__(self, other: int) -> Foo:
|
| 382 |
+
# if not isinstance(other, int):
|
| 383 |
+
# return NotImplemented
|
| 384 |
+
# ...
|
| 385 |
+
generate_bin_op_reverse_dunder_call(fn, emitter, reverse_op_methods[fn.name])
|
| 386 |
+
gen.finish()
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def generate_bin_op_reverse_only_wrapper(
|
| 390 |
+
fn: FuncIR, emitter: Emitter, gen: WrapperGenerator
|
| 391 |
+
) -> None:
|
| 392 |
+
gen.arg_names = ["right", "left"]
|
| 393 |
+
gen.emit_arg_processing(error=GotoHandler("typefail"), raise_exception=False)
|
| 394 |
+
handle_third_pow_argument(fn, emitter, gen, if_unsupported=["goto typefail;"])
|
| 395 |
+
gen.emit_call()
|
| 396 |
+
gen.emit_error_handling()
|
| 397 |
+
emitter.emit_label("typefail")
|
| 398 |
+
emitter.emit_line("Py_INCREF(Py_NotImplemented);")
|
| 399 |
+
emitter.emit_line("return Py_NotImplemented;")
|
| 400 |
+
gen.finish()
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def generate_bin_op_both_wrappers(
|
| 404 |
+
cl: ClassIR, fn: FuncIR, fn_rev: FuncIR, emitter: Emitter, gen: WrapperGenerator
|
| 405 |
+
) -> None:
|
| 406 |
+
# There's both a forward and a reverse operator method. First
|
| 407 |
+
# check if we should try calling the forward one. If the
|
| 408 |
+
# argument type check fails, fall back to the reverse method.
|
| 409 |
+
#
|
| 410 |
+
# Similar to above, we can't perfectly match Python semantics.
|
| 411 |
+
# In regular Python code you'd return NotImplemented if the
|
| 412 |
+
# operand has the wrong type, but in compiled code we'll never
|
| 413 |
+
# get to execute the type check.
|
| 414 |
+
emitter.emit_line(
|
| 415 |
+
"if (PyObject_IsInstance(obj_left, (PyObject *){})) {{".format(
|
| 416 |
+
emitter.type_struct_name(cl)
|
| 417 |
+
)
|
| 418 |
+
)
|
| 419 |
+
gen.emit_arg_processing(error=GotoHandler("typefail"), raise_exception=False)
|
| 420 |
+
handle_third_pow_argument(fn, emitter, gen, if_unsupported=["goto typefail2;"])
|
| 421 |
+
# Ternary __rpow__ calls aren't a thing so immediately bail
|
| 422 |
+
# if ternary __pow__ returns NotImplemented.
|
| 423 |
+
if fn.name == "__pow__" and len(fn.args) == 3:
|
| 424 |
+
fwd_not_implemented_handler = "goto typefail2;"
|
| 425 |
+
else:
|
| 426 |
+
fwd_not_implemented_handler = "goto typefail;"
|
| 427 |
+
gen.emit_call(not_implemented_handler=fwd_not_implemented_handler)
|
| 428 |
+
gen.emit_error_handling()
|
| 429 |
+
emitter.emit_line("}")
|
| 430 |
+
emitter.emit_label("typefail")
|
| 431 |
+
emitter.emit_line(
|
| 432 |
+
"if (PyObject_IsInstance(obj_right, (PyObject *){})) {{".format(
|
| 433 |
+
emitter.type_struct_name(cl)
|
| 434 |
+
)
|
| 435 |
+
)
|
| 436 |
+
gen.set_target(fn_rev)
|
| 437 |
+
gen.arg_names = ["right", "left"]
|
| 438 |
+
gen.emit_arg_processing(error=GotoHandler("typefail2"), raise_exception=False)
|
| 439 |
+
handle_third_pow_argument(fn_rev, emitter, gen, if_unsupported=["goto typefail2;"])
|
| 440 |
+
gen.emit_call()
|
| 441 |
+
gen.emit_error_handling()
|
| 442 |
+
emitter.emit_line("} else {")
|
| 443 |
+
generate_bin_op_reverse_dunder_call(fn, emitter, fn_rev.name)
|
| 444 |
+
emitter.emit_line("}")
|
| 445 |
+
emitter.emit_label("typefail2")
|
| 446 |
+
emitter.emit_line("Py_INCREF(Py_NotImplemented);")
|
| 447 |
+
emitter.emit_line("return Py_NotImplemented;")
|
| 448 |
+
gen.finish()
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def generate_bin_op_reverse_dunder_call(fn: FuncIR, emitter: Emitter, rmethod: str) -> None:
|
| 452 |
+
if fn.name in ("__pow__", "__rpow__"):
|
| 453 |
+
# Ternary pow() will never call the reverse dunder.
|
| 454 |
+
emitter.emit_line("if (obj_mod == Py_None) {")
|
| 455 |
+
emitter.emit_line(
|
| 456 |
+
'return CPy_CallReverseOpMethod(obj_left, obj_right, "{}", mypyc_interned_str.{});'.format(
|
| 457 |
+
op_methods_to_symbols[fn.name], rmethod
|
| 458 |
+
)
|
| 459 |
+
)
|
| 460 |
+
if fn.name in ("__pow__", "__rpow__"):
|
| 461 |
+
emitter.emit_line("} else {")
|
| 462 |
+
emitter.emit_line("Py_INCREF(Py_NotImplemented);")
|
| 463 |
+
emitter.emit_line("return Py_NotImplemented;")
|
| 464 |
+
emitter.emit_line("}")
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def handle_third_pow_argument(
|
| 468 |
+
fn: FuncIR, emitter: Emitter, gen: WrapperGenerator, *, if_unsupported: list[str]
|
| 469 |
+
) -> None:
|
| 470 |
+
if fn.name not in ("__pow__", "__rpow__", "__ipow__"):
|
| 471 |
+
return
|
| 472 |
+
|
| 473 |
+
if (fn.name in ("__pow__", "__ipow__") and len(fn.args) == 2) or fn.name == "__rpow__":
|
| 474 |
+
# If the power dunder only supports two arguments and the third
|
| 475 |
+
# argument (AKA mod) is set to a non-default value, simply bail.
|
| 476 |
+
#
|
| 477 |
+
# Importantly, this prevents any ternary __rpow__ calls from
|
| 478 |
+
# happening (as per the language specification).
|
| 479 |
+
emitter.emit_line("if (obj_mod != Py_None) {")
|
| 480 |
+
for line in if_unsupported:
|
| 481 |
+
emitter.emit_line(line)
|
| 482 |
+
emitter.emit_line("}")
|
| 483 |
+
# The slot wrapper will receive three arguments, but the call only
|
| 484 |
+
# supports two so make sure that the third argument isn't passed
|
| 485 |
+
# along. This is needed as two-argument __(i)pow__ is allowed and
|
| 486 |
+
# rather common.
|
| 487 |
+
if len(gen.arg_names) == 3:
|
| 488 |
+
gen.arg_names.pop()
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
RICHCOMPARE_OPS = {
|
| 492 |
+
"__lt__": "Py_LT",
|
| 493 |
+
"__gt__": "Py_GT",
|
| 494 |
+
"__le__": "Py_LE",
|
| 495 |
+
"__ge__": "Py_GE",
|
| 496 |
+
"__eq__": "Py_EQ",
|
| 497 |
+
"__ne__": "Py_NE",
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> str | None:
|
| 502 |
+
"""Generates a wrapper for richcompare dunder methods."""
|
| 503 |
+
# Sort for determinism on Python 3.5
|
| 504 |
+
matches = sorted(name for name in RICHCOMPARE_OPS if cl.has_method(name))
|
| 505 |
+
if not matches:
|
| 506 |
+
return None
|
| 507 |
+
|
| 508 |
+
name = f"{DUNDER_PREFIX}_RichCompare_{cl.name_prefix(emitter.names)}"
|
| 509 |
+
emitter.emit_line(
|
| 510 |
+
"static PyObject *{name}(PyObject *obj_lhs, PyObject *obj_rhs, int op) {{".format(
|
| 511 |
+
name=name
|
| 512 |
+
)
|
| 513 |
+
)
|
| 514 |
+
emitter.emit_line("switch (op) {")
|
| 515 |
+
for func in matches:
|
| 516 |
+
emitter.emit_line(f"case {RICHCOMPARE_OPS[func]}: {{")
|
| 517 |
+
method = cl.get_method(func)
|
| 518 |
+
assert method is not None
|
| 519 |
+
generate_wrapper_core(method, emitter, arg_names=["lhs", "rhs"])
|
| 520 |
+
emitter.emit_line("}")
|
| 521 |
+
emitter.emit_line("}")
|
| 522 |
+
|
| 523 |
+
emitter.emit_line("Py_INCREF(Py_NotImplemented);")
|
| 524 |
+
emitter.emit_line("return Py_NotImplemented;")
|
| 525 |
+
|
| 526 |
+
emitter.emit_line("}")
|
| 527 |
+
|
| 528 |
+
return name
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def generate_get_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 532 |
+
"""Generates a wrapper for native __get__ methods."""
|
| 533 |
+
name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
|
| 534 |
+
emitter.emit_line(
|
| 535 |
+
"static PyObject *{name}(PyObject *self, PyObject *instance, PyObject *owner) {{".format(
|
| 536 |
+
name=name
|
| 537 |
+
)
|
| 538 |
+
)
|
| 539 |
+
emitter.emit_line("instance = instance ? instance : Py_None;")
|
| 540 |
+
emitter.emit_line(f"return {NATIVE_PREFIX}{fn.cname(emitter.names)}(self, instance, owner);")
|
| 541 |
+
emitter.emit_line("}")
|
| 542 |
+
|
| 543 |
+
return name
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def generate_hash_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 547 |
+
"""Generates a wrapper for native __hash__ methods."""
|
| 548 |
+
name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
|
| 549 |
+
emitter.emit_line(f"static Py_ssize_t {name}(PyObject *self) {{")
|
| 550 |
+
emitter.emit_line(
|
| 551 |
+
"{}retval = {}{}{}(self);".format(
|
| 552 |
+
emitter.ctype_spaced(fn.ret_type),
|
| 553 |
+
emitter.get_group_prefix(fn.decl),
|
| 554 |
+
NATIVE_PREFIX,
|
| 555 |
+
fn.cname(emitter.names),
|
| 556 |
+
)
|
| 557 |
+
)
|
| 558 |
+
emitter.emit_error_check("retval", fn.ret_type, "return -1;")
|
| 559 |
+
if is_int_rprimitive(fn.ret_type):
|
| 560 |
+
emitter.emit_line("Py_ssize_t val = CPyTagged_AsSsize_t(retval);")
|
| 561 |
+
else:
|
| 562 |
+
emitter.emit_line("Py_ssize_t val = PyLong_AsSsize_t(retval);")
|
| 563 |
+
emitter.emit_dec_ref("retval", fn.ret_type)
|
| 564 |
+
emitter.emit_line("if (PyErr_Occurred()) return -1;")
|
| 565 |
+
# We can't return -1 from a hash function..
|
| 566 |
+
emitter.emit_line("if (val == -1) return -2;")
|
| 567 |
+
emitter.emit_line("return val;")
|
| 568 |
+
emitter.emit_line("}")
|
| 569 |
+
|
| 570 |
+
return name
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def generate_len_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 574 |
+
"""Generates a wrapper for native __len__ methods."""
|
| 575 |
+
name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
|
| 576 |
+
emitter.emit_line(f"static Py_ssize_t {name}(PyObject *self) {{")
|
| 577 |
+
emitter.emit_line(
|
| 578 |
+
"{}retval = {}{}{}(self);".format(
|
| 579 |
+
emitter.ctype_spaced(fn.ret_type),
|
| 580 |
+
emitter.get_group_prefix(fn.decl),
|
| 581 |
+
NATIVE_PREFIX,
|
| 582 |
+
fn.cname(emitter.names),
|
| 583 |
+
)
|
| 584 |
+
)
|
| 585 |
+
emitter.emit_error_check("retval", fn.ret_type, "return -1;")
|
| 586 |
+
if is_int_rprimitive(fn.ret_type):
|
| 587 |
+
emitter.emit_line("Py_ssize_t val = CPyTagged_AsSsize_t(retval);")
|
| 588 |
+
else:
|
| 589 |
+
emitter.emit_line("Py_ssize_t val = PyLong_AsSsize_t(retval);")
|
| 590 |
+
emitter.emit_dec_ref("retval", fn.ret_type)
|
| 591 |
+
emitter.emit_line("if (PyErr_Occurred()) return -1;")
|
| 592 |
+
emitter.emit_line("return val;")
|
| 593 |
+
emitter.emit_line("}")
|
| 594 |
+
|
| 595 |
+
return name
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def generate_bool_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 599 |
+
"""Generates a wrapper for native __bool__ methods."""
|
| 600 |
+
name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
|
| 601 |
+
emitter.emit_line(f"static int {name}(PyObject *self) {{")
|
| 602 |
+
emitter.emit_line(
|
| 603 |
+
"{}val = {}{}(self);".format(
|
| 604 |
+
emitter.ctype_spaced(fn.ret_type), NATIVE_PREFIX, fn.cname(emitter.names)
|
| 605 |
+
)
|
| 606 |
+
)
|
| 607 |
+
emitter.emit_error_check("val", fn.ret_type, "return -1;")
|
| 608 |
+
# This wouldn't be that hard to fix but it seems unimportant and
|
| 609 |
+
# getting error handling and unboxing right would be fiddly. (And
|
| 610 |
+
# way easier to do in IR!)
|
| 611 |
+
assert is_bool_rprimitive(fn.ret_type), "Only bool return supported for __bool__"
|
| 612 |
+
emitter.emit_line("return val;")
|
| 613 |
+
emitter.emit_line("}")
|
| 614 |
+
|
| 615 |
+
return name
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def generate_del_item_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 619 |
+
"""Generates a wrapper for native __delitem__.
|
| 620 |
+
|
| 621 |
+
This is only called from a combined __delitem__/__setitem__ wrapper.
|
| 622 |
+
"""
|
| 623 |
+
name = "{}{}{}".format(DUNDER_PREFIX, "__delitem__", cl.name_prefix(emitter.names))
|
| 624 |
+
input_args = ", ".join(f"PyObject *obj_{arg.name}" for arg in fn.args)
|
| 625 |
+
emitter.emit_line(f"static int {name}({input_args}) {{")
|
| 626 |
+
generate_set_del_item_wrapper_inner(fn, emitter, fn.args)
|
| 627 |
+
return name
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def generate_set_del_item_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 631 |
+
"""Generates a wrapper for native __setitem__ method (also works for __delitem__).
|
| 632 |
+
|
| 633 |
+
This is used with the mapping protocol slot. Arguments are taken as *PyObjects and we
|
| 634 |
+
return a negative C int on error.
|
| 635 |
+
|
| 636 |
+
Create a separate wrapper function for __delitem__ as needed and have the
|
| 637 |
+
__setitem__ wrapper call it if the value is NULL. Return the name
|
| 638 |
+
of the outer (__setitem__) wrapper.
|
| 639 |
+
"""
|
| 640 |
+
method_cls = cl.get_method_and_class("__delitem__")
|
| 641 |
+
del_name = None
|
| 642 |
+
if method_cls and method_cls[1] == cl:
|
| 643 |
+
# Generate a separate wrapper for __delitem__
|
| 644 |
+
del_name = generate_del_item_wrapper(cl, method_cls[0], emitter)
|
| 645 |
+
|
| 646 |
+
args = fn.args
|
| 647 |
+
if fn.name == "__delitem__":
|
| 648 |
+
# Add an extra argument for value that we expect to be NULL.
|
| 649 |
+
args = list(args) + [RuntimeArg("___value", object_rprimitive, ARG_POS)]
|
| 650 |
+
|
| 651 |
+
name = "{}{}{}".format(DUNDER_PREFIX, "__setitem__", cl.name_prefix(emitter.names))
|
| 652 |
+
input_args = ", ".join(f"PyObject *obj_{arg.name}" for arg in args)
|
| 653 |
+
emitter.emit_line(f"static int {name}({input_args}) {{")
|
| 654 |
+
|
| 655 |
+
# First check if this is __delitem__
|
| 656 |
+
emitter.emit_line(f"if (obj_{args[2].name} == NULL) {{")
|
| 657 |
+
if del_name is not None:
|
| 658 |
+
# We have a native implementation, so call it
|
| 659 |
+
emitter.emit_line(f"return {del_name}(obj_{args[0].name}, obj_{args[1].name});")
|
| 660 |
+
else:
|
| 661 |
+
# Try to call superclass method instead
|
| 662 |
+
emitter.emit_line(f"PyObject *super = CPy_Super(CPyModule_builtins, obj_{args[0].name});")
|
| 663 |
+
emitter.emit_line("if (super == NULL) return -1;")
|
| 664 |
+
emitter.emit_line(
|
| 665 |
+
'PyObject *result = PyObject_CallMethod(super, "__delitem__", "O", obj_{});'.format(
|
| 666 |
+
args[1].name
|
| 667 |
+
)
|
| 668 |
+
)
|
| 669 |
+
emitter.emit_line("Py_DECREF(super);")
|
| 670 |
+
emitter.emit_line("Py_XDECREF(result);")
|
| 671 |
+
emitter.emit_line("return result == NULL ? -1 : 0;")
|
| 672 |
+
emitter.emit_line("}")
|
| 673 |
+
|
| 674 |
+
method_cls = cl.get_method_and_class("__setitem__")
|
| 675 |
+
if method_cls and method_cls[1] == cl:
|
| 676 |
+
generate_set_del_item_wrapper_inner(fn, emitter, args)
|
| 677 |
+
else:
|
| 678 |
+
emitter.emit_line(f"PyObject *super = CPy_Super(CPyModule_builtins, obj_{args[0].name});")
|
| 679 |
+
emitter.emit_line("if (super == NULL) return -1;")
|
| 680 |
+
emitter.emit_line("PyObject *result;")
|
| 681 |
+
|
| 682 |
+
if method_cls is None and cl.builtin_base is None:
|
| 683 |
+
msg = f"'{cl.name}' object does not support item assignment"
|
| 684 |
+
emitter.emit_line(f'PyErr_SetString(PyExc_TypeError, "{msg}");')
|
| 685 |
+
emitter.emit_line("result = NULL;")
|
| 686 |
+
else:
|
| 687 |
+
# A base class may have __setitem__
|
| 688 |
+
emitter.emit_line(
|
| 689 |
+
'result = PyObject_CallMethod(super, "__setitem__", "OO", obj_{}, obj_{});'.format(
|
| 690 |
+
args[1].name, args[2].name
|
| 691 |
+
)
|
| 692 |
+
)
|
| 693 |
+
emitter.emit_line("Py_DECREF(super);")
|
| 694 |
+
emitter.emit_line("Py_XDECREF(result);")
|
| 695 |
+
emitter.emit_line("return result == NULL ? -1 : 0;")
|
| 696 |
+
emitter.emit_line("}")
|
| 697 |
+
return name
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def generate_set_del_item_wrapper_inner(
|
| 701 |
+
fn: FuncIR, emitter: Emitter, args: Sequence[RuntimeArg]
|
| 702 |
+
) -> None:
|
| 703 |
+
for arg in args:
|
| 704 |
+
generate_arg_check(arg.name, arg.type, emitter, GotoHandler("fail"))
|
| 705 |
+
native_args = ", ".join(f"arg_{arg.name}" for arg in args)
|
| 706 |
+
emitter.emit_line(
|
| 707 |
+
"{}val = {}{}({});".format(
|
| 708 |
+
emitter.ctype_spaced(fn.ret_type), NATIVE_PREFIX, fn.cname(emitter.names), native_args
|
| 709 |
+
)
|
| 710 |
+
)
|
| 711 |
+
emitter.emit_error_check("val", fn.ret_type, "goto fail;")
|
| 712 |
+
emitter.emit_dec_ref("val", fn.ret_type)
|
| 713 |
+
emitter.emit_line("return 0;")
|
| 714 |
+
emitter.emit_label("fail")
|
| 715 |
+
emitter.emit_line("return -1;")
|
| 716 |
+
emitter.emit_line("}")
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
def generate_contains_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
|
| 720 |
+
"""Generates a wrapper for a native __contains__ method."""
|
| 721 |
+
name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
|
| 722 |
+
emitter.emit_line(f"static int {name}(PyObject *self, PyObject *obj_item) {{")
|
| 723 |
+
generate_arg_check("item", fn.args[1].type, emitter, ReturnHandler("-1"))
|
| 724 |
+
emitter.emit_line(
|
| 725 |
+
"{}val = {}{}(self, arg_item);".format(
|
| 726 |
+
emitter.ctype_spaced(fn.ret_type), NATIVE_PREFIX, fn.cname(emitter.names)
|
| 727 |
+
)
|
| 728 |
+
)
|
| 729 |
+
emitter.emit_error_check("val", fn.ret_type, "return -1;")
|
| 730 |
+
if is_bool_rprimitive(fn.ret_type):
|
| 731 |
+
emitter.emit_line("return val;")
|
| 732 |
+
else:
|
| 733 |
+
emitter.emit_line("int boolval = PyObject_IsTrue(val);")
|
| 734 |
+
emitter.emit_dec_ref("val", fn.ret_type)
|
| 735 |
+
emitter.emit_line("return boolval;")
|
| 736 |
+
emitter.emit_line("}")
|
| 737 |
+
|
| 738 |
+
return name
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
# Helpers
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def generate_wrapper_core(
|
| 745 |
+
fn: FuncIR,
|
| 746 |
+
emitter: Emitter,
|
| 747 |
+
optional_args: list[RuntimeArg] | None = None,
|
| 748 |
+
arg_names: list[str] | None = None,
|
| 749 |
+
cleanups: list[str] | None = None,
|
| 750 |
+
traceback_code: str | None = None,
|
| 751 |
+
) -> None:
|
| 752 |
+
"""Generates the core part of a wrapper function for a native function.
|
| 753 |
+
|
| 754 |
+
This expects each argument as a PyObject * named obj_{arg} as a precondition.
|
| 755 |
+
It converts the PyObject *s to the necessary types, checking and unboxing if necessary,
|
| 756 |
+
makes the call, then boxes the result if necessary and returns it.
|
| 757 |
+
"""
|
| 758 |
+
gen = WrapperGenerator(None, emitter)
|
| 759 |
+
gen.set_target(fn)
|
| 760 |
+
if arg_names:
|
| 761 |
+
gen.arg_names = arg_names
|
| 762 |
+
gen.cleanups = cleanups or []
|
| 763 |
+
gen.optional_args = optional_args or []
|
| 764 |
+
gen.traceback_code = traceback_code or ""
|
| 765 |
+
|
| 766 |
+
error = ReturnHandler("NULL") if not gen.use_goto() else GotoHandler("fail")
|
| 767 |
+
gen.emit_arg_processing(error=error)
|
| 768 |
+
gen.emit_call()
|
| 769 |
+
gen.emit_error_handling()
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
def generate_arg_check(
|
| 773 |
+
name: str,
|
| 774 |
+
typ: RType,
|
| 775 |
+
emitter: Emitter,
|
| 776 |
+
error: ErrorHandler | None = None,
|
| 777 |
+
*,
|
| 778 |
+
optional: bool = False,
|
| 779 |
+
raise_exception: bool = True,
|
| 780 |
+
bitmap_arg_index: int = 0,
|
| 781 |
+
) -> None:
|
| 782 |
+
"""Insert a runtime check for argument and unbox if necessary.
|
| 783 |
+
|
| 784 |
+
The object is named PyObject *obj_{}. This is expected to generate
|
| 785 |
+
a value of name arg_{} (unboxed if necessary). For each primitive a runtime
|
| 786 |
+
check ensures the correct type.
|
| 787 |
+
"""
|
| 788 |
+
error = error or AssignHandler()
|
| 789 |
+
if typ.is_unboxed:
|
| 790 |
+
if typ.error_overlap and optional:
|
| 791 |
+
# Update bitmap is value is provided.
|
| 792 |
+
init = emitter.c_undefined_value(typ)
|
| 793 |
+
emitter.emit_line(f"{emitter.ctype(typ)} arg_{name} = {init};")
|
| 794 |
+
emitter.emit_line(f"if (obj_{name} != NULL) {{")
|
| 795 |
+
bitmap = bitmap_name(bitmap_arg_index // BITMAP_BITS)
|
| 796 |
+
emitter.emit_line(f"{bitmap} |= 1 << {bitmap_arg_index & (BITMAP_BITS - 1)};")
|
| 797 |
+
emitter.emit_unbox(
|
| 798 |
+
f"obj_{name}",
|
| 799 |
+
f"arg_{name}",
|
| 800 |
+
typ,
|
| 801 |
+
declare_dest=False,
|
| 802 |
+
raise_exception=raise_exception,
|
| 803 |
+
error=error,
|
| 804 |
+
borrow=True,
|
| 805 |
+
)
|
| 806 |
+
emitter.emit_line("}")
|
| 807 |
+
else:
|
| 808 |
+
# Borrow when unboxing to avoid reference count manipulation.
|
| 809 |
+
emitter.emit_unbox(
|
| 810 |
+
f"obj_{name}",
|
| 811 |
+
f"arg_{name}",
|
| 812 |
+
typ,
|
| 813 |
+
declare_dest=True,
|
| 814 |
+
raise_exception=raise_exception,
|
| 815 |
+
error=error,
|
| 816 |
+
borrow=True,
|
| 817 |
+
optional=optional,
|
| 818 |
+
)
|
| 819 |
+
elif is_object_rprimitive(typ):
|
| 820 |
+
# Object is trivial since any object is valid
|
| 821 |
+
if optional:
|
| 822 |
+
emitter.emit_line(f"PyObject *arg_{name};")
|
| 823 |
+
emitter.emit_line(f"if (obj_{name} == NULL) {{")
|
| 824 |
+
emitter.emit_line(f"arg_{name} = {emitter.c_error_value(typ)};")
|
| 825 |
+
emitter.emit_lines("} else {", f"arg_{name} = obj_{name}; ", "}")
|
| 826 |
+
else:
|
| 827 |
+
emitter.emit_line(f"PyObject *arg_{name} = obj_{name};")
|
| 828 |
+
else:
|
| 829 |
+
emitter.emit_cast(
|
| 830 |
+
f"obj_{name}",
|
| 831 |
+
f"arg_{name}",
|
| 832 |
+
typ,
|
| 833 |
+
declare_dest=True,
|
| 834 |
+
raise_exception=raise_exception,
|
| 835 |
+
error=error,
|
| 836 |
+
optional=optional,
|
| 837 |
+
)
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
class WrapperGenerator:
|
| 841 |
+
"""Helper that simplifies the generation of wrapper functions."""
|
| 842 |
+
|
| 843 |
+
# TODO: Use this for more wrappers
|
| 844 |
+
|
| 845 |
+
def __init__(self, cl: ClassIR | None, emitter: Emitter) -> None:
|
| 846 |
+
self.cl = cl
|
| 847 |
+
self.emitter = emitter
|
| 848 |
+
self.cleanups: list[str] = []
|
| 849 |
+
self.optional_args: list[RuntimeArg] = []
|
| 850 |
+
self.traceback_code = ""
|
| 851 |
+
|
| 852 |
+
def set_target(self, fn: FuncIR) -> None:
|
| 853 |
+
"""Set the wrapped function.
|
| 854 |
+
|
| 855 |
+
It's fine to modify the attributes initialized here later to customize
|
| 856 |
+
the wrapper function.
|
| 857 |
+
"""
|
| 858 |
+
self.target_name = fn.name
|
| 859 |
+
self.target_cname = fn.cname(self.emitter.names)
|
| 860 |
+
self.num_bitmap_args = fn.sig.num_bitmap_args
|
| 861 |
+
if self.num_bitmap_args:
|
| 862 |
+
self.args = fn.args[: -self.num_bitmap_args]
|
| 863 |
+
else:
|
| 864 |
+
self.args = fn.args
|
| 865 |
+
self.arg_names = [arg.name for arg in self.args]
|
| 866 |
+
self.ret_type = fn.ret_type
|
| 867 |
+
|
| 868 |
+
def wrapper_name(self) -> str:
|
| 869 |
+
"""Return the name of the wrapper function."""
|
| 870 |
+
return "{}{}{}".format(
|
| 871 |
+
DUNDER_PREFIX,
|
| 872 |
+
self.target_name,
|
| 873 |
+
self.cl.name_prefix(self.emitter.names) if self.cl else "",
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
def use_goto(self) -> bool:
|
| 877 |
+
"""Do we use a goto for error handling (instead of straight return)?"""
|
| 878 |
+
return bool(self.cleanups or self.traceback_code)
|
| 879 |
+
|
| 880 |
+
def emit_header(self) -> None:
|
| 881 |
+
"""Emit the function header of the wrapper implementation."""
|
| 882 |
+
input_args = ", ".join(f"PyObject *obj_{arg}" for arg in self.arg_names)
|
| 883 |
+
self.emitter.emit_line(
|
| 884 |
+
"static PyObject *{name}({input_args}) {{".format(
|
| 885 |
+
name=self.wrapper_name(), input_args=input_args
|
| 886 |
+
)
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
def emit_arg_processing(
|
| 890 |
+
self, error: ErrorHandler | None = None, raise_exception: bool = True
|
| 891 |
+
) -> None:
|
| 892 |
+
"""Emit validation and unboxing of arguments."""
|
| 893 |
+
error = error or self.error()
|
| 894 |
+
bitmap_arg_index = 0
|
| 895 |
+
for arg_name, arg in zip(self.arg_names, self.args):
|
| 896 |
+
# Suppress the argument check for *args/**kwargs, since we know it must be right.
|
| 897 |
+
typ = arg.type if arg.kind not in (ARG_STAR, ARG_STAR2) else object_rprimitive
|
| 898 |
+
optional = arg in self.optional_args
|
| 899 |
+
generate_arg_check(
|
| 900 |
+
arg_name,
|
| 901 |
+
typ,
|
| 902 |
+
self.emitter,
|
| 903 |
+
error,
|
| 904 |
+
raise_exception=raise_exception,
|
| 905 |
+
optional=optional,
|
| 906 |
+
bitmap_arg_index=bitmap_arg_index,
|
| 907 |
+
)
|
| 908 |
+
if optional and typ.error_overlap:
|
| 909 |
+
bitmap_arg_index += 1
|
| 910 |
+
|
| 911 |
+
def emit_call(self, not_implemented_handler: str = "") -> None:
|
| 912 |
+
"""Emit call to the wrapper function.
|
| 913 |
+
|
| 914 |
+
If not_implemented_handler is non-empty, use this C code to handle
|
| 915 |
+
a NotImplemented return value (if it's possible based on the return type).
|
| 916 |
+
"""
|
| 917 |
+
native_args = ", ".join(f"arg_{arg}" for arg in self.arg_names)
|
| 918 |
+
if self.num_bitmap_args:
|
| 919 |
+
bitmap_args = ", ".join(
|
| 920 |
+
[bitmap_name(i) for i in reversed(range(self.num_bitmap_args))]
|
| 921 |
+
)
|
| 922 |
+
native_args = f"{native_args}, {bitmap_args}"
|
| 923 |
+
|
| 924 |
+
ret_type = self.ret_type
|
| 925 |
+
emitter = self.emitter
|
| 926 |
+
if ret_type.is_unboxed or self.use_goto():
|
| 927 |
+
# TODO: The Py_RETURN macros return the correct PyObject * with reference count
|
| 928 |
+
# handling. Are they relevant?
|
| 929 |
+
emitter.emit_line(
|
| 930 |
+
"{}retval = {}{}({});".format(
|
| 931 |
+
emitter.ctype_spaced(ret_type), NATIVE_PREFIX, self.target_cname, native_args
|
| 932 |
+
)
|
| 933 |
+
)
|
| 934 |
+
emitter.emit_lines(*self.cleanups)
|
| 935 |
+
if ret_type.is_unboxed:
|
| 936 |
+
emitter.emit_error_check("retval", ret_type, "return NULL;")
|
| 937 |
+
emitter.emit_box("retval", "retbox", ret_type, declare_dest=True)
|
| 938 |
+
|
| 939 |
+
emitter.emit_line("return {};".format("retbox" if ret_type.is_unboxed else "retval"))
|
| 940 |
+
else:
|
| 941 |
+
if not_implemented_handler and not isinstance(ret_type, RInstance):
|
| 942 |
+
# The return value type may overlap with NotImplemented.
|
| 943 |
+
emitter.emit_line(
|
| 944 |
+
"PyObject *retbox = {}{}({});".format(
|
| 945 |
+
NATIVE_PREFIX, self.target_cname, native_args
|
| 946 |
+
)
|
| 947 |
+
)
|
| 948 |
+
emitter.emit_lines(
|
| 949 |
+
"if (retbox == Py_NotImplemented) {",
|
| 950 |
+
not_implemented_handler,
|
| 951 |
+
"}",
|
| 952 |
+
"return retbox;",
|
| 953 |
+
)
|
| 954 |
+
else:
|
| 955 |
+
emitter.emit_line(f"return {NATIVE_PREFIX}{self.target_cname}({native_args});")
|
| 956 |
+
# TODO: Tracebacks?
|
| 957 |
+
|
| 958 |
+
def error(self) -> ErrorHandler:
|
| 959 |
+
"""Figure out how to deal with errors in the wrapper."""
|
| 960 |
+
if self.cleanups or self.traceback_code:
|
| 961 |
+
# We'll have a label at the end with error handling code.
|
| 962 |
+
return GotoHandler("fail")
|
| 963 |
+
else:
|
| 964 |
+
# Nothing special needs to done to handle errors, so just return.
|
| 965 |
+
return ReturnHandler("NULL")
|
| 966 |
+
|
| 967 |
+
def emit_error_handling(self) -> None:
|
| 968 |
+
"""Emit error handling block at the end of the wrapper, if needed."""
|
| 969 |
+
emitter = self.emitter
|
| 970 |
+
if self.use_goto():
|
| 971 |
+
emitter.emit_label("fail")
|
| 972 |
+
emitter.emit_lines(*self.cleanups)
|
| 973 |
+
if self.traceback_code:
|
| 974 |
+
emitter.emit_line(self.traceback_code)
|
| 975 |
+
emitter.emit_line("return NULL;")
|
| 976 |
+
|
| 977 |
+
def finish(self) -> None:
|
| 978 |
+
self.emitter.emit_line("}")
|
micromamba_root/Lib/site-packages/mypyc/codegen/literals.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/codegen/literals.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Final, TypeGuard
|
| 4 |
+
|
| 5 |
+
# Supported Python literal types. All tuple / frozenset items must have supported
|
| 6 |
+
# literal types as well, but we can't represent the type precisely.
|
| 7 |
+
LiteralValue = (
|
| 8 |
+
str | bytes | int | bool | float | complex | tuple[object, ...] | frozenset[object] | None
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _is_literal_value(obj: object) -> TypeGuard[LiteralValue]:
|
| 13 |
+
return isinstance(obj, (str, bytes, int, float, complex, tuple, frozenset, type(None)))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Some literals are singletons and handled specially (None, False and True)
|
| 17 |
+
NUM_SINGLETONS: Final = 3
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Literals:
|
| 21 |
+
"""Collection of literal values used in a compilation group and related helpers."""
|
| 22 |
+
|
| 23 |
+
def __init__(self) -> None:
|
| 24 |
+
# Each dict maps value to literal index (0, 1, ...)
|
| 25 |
+
self.str_literals: dict[str, int] = {}
|
| 26 |
+
self.bytes_literals: dict[bytes, int] = {}
|
| 27 |
+
self.int_literals: dict[int, int] = {}
|
| 28 |
+
self.float_literals: dict[float, int] = {}
|
| 29 |
+
self.complex_literals: dict[complex, int] = {}
|
| 30 |
+
self.tuple_literals: dict[tuple[object, ...], int] = {}
|
| 31 |
+
self.frozenset_literals: dict[frozenset[object], int] = {}
|
| 32 |
+
|
| 33 |
+
def record_literal(self, value: LiteralValue) -> None:
|
| 34 |
+
"""Ensure that the literal value is available in generated code."""
|
| 35 |
+
if value is None or value is True or value is False:
|
| 36 |
+
# These are special cased and always present
|
| 37 |
+
return
|
| 38 |
+
if isinstance(value, str):
|
| 39 |
+
str_literals = self.str_literals
|
| 40 |
+
if value not in str_literals:
|
| 41 |
+
str_literals[value] = len(str_literals)
|
| 42 |
+
elif isinstance(value, bytes):
|
| 43 |
+
bytes_literals = self.bytes_literals
|
| 44 |
+
if value not in bytes_literals:
|
| 45 |
+
bytes_literals[value] = len(bytes_literals)
|
| 46 |
+
elif isinstance(value, int):
|
| 47 |
+
int_literals = self.int_literals
|
| 48 |
+
if value not in int_literals:
|
| 49 |
+
int_literals[value] = len(int_literals)
|
| 50 |
+
elif isinstance(value, float):
|
| 51 |
+
float_literals = self.float_literals
|
| 52 |
+
if value not in float_literals:
|
| 53 |
+
float_literals[value] = len(float_literals)
|
| 54 |
+
elif isinstance(value, complex):
|
| 55 |
+
complex_literals = self.complex_literals
|
| 56 |
+
if value not in complex_literals:
|
| 57 |
+
complex_literals[value] = len(complex_literals)
|
| 58 |
+
elif isinstance(value, tuple):
|
| 59 |
+
tuple_literals = self.tuple_literals
|
| 60 |
+
if value not in tuple_literals:
|
| 61 |
+
for item in value:
|
| 62 |
+
assert _is_literal_value(item)
|
| 63 |
+
self.record_literal(item)
|
| 64 |
+
tuple_literals[value] = len(tuple_literals)
|
| 65 |
+
elif isinstance(value, frozenset):
|
| 66 |
+
frozenset_literals = self.frozenset_literals
|
| 67 |
+
if value not in frozenset_literals:
|
| 68 |
+
for item in value:
|
| 69 |
+
assert _is_literal_value(item)
|
| 70 |
+
self.record_literal(item)
|
| 71 |
+
frozenset_literals[value] = len(frozenset_literals)
|
| 72 |
+
else:
|
| 73 |
+
assert False, "invalid literal: %r" % value
|
| 74 |
+
|
| 75 |
+
def literal_index(self, value: LiteralValue) -> int:
|
| 76 |
+
"""Return the index to the literals array for given value."""
|
| 77 |
+
# The array contains first None and booleans, followed by all str values,
|
| 78 |
+
# followed by bytes values, etc.
|
| 79 |
+
if value is None:
|
| 80 |
+
return 0
|
| 81 |
+
elif value is False:
|
| 82 |
+
return 1
|
| 83 |
+
elif value is True:
|
| 84 |
+
return 2
|
| 85 |
+
n = NUM_SINGLETONS
|
| 86 |
+
if isinstance(value, str):
|
| 87 |
+
return n + self.str_literals[value]
|
| 88 |
+
n += len(self.str_literals)
|
| 89 |
+
if isinstance(value, bytes):
|
| 90 |
+
return n + self.bytes_literals[value]
|
| 91 |
+
n += len(self.bytes_literals)
|
| 92 |
+
if isinstance(value, int):
|
| 93 |
+
return n + self.int_literals[value]
|
| 94 |
+
n += len(self.int_literals)
|
| 95 |
+
if isinstance(value, float):
|
| 96 |
+
return n + self.float_literals[value]
|
| 97 |
+
n += len(self.float_literals)
|
| 98 |
+
if isinstance(value, complex):
|
| 99 |
+
return n + self.complex_literals[value]
|
| 100 |
+
n += len(self.complex_literals)
|
| 101 |
+
if isinstance(value, tuple):
|
| 102 |
+
return n + self.tuple_literals[value]
|
| 103 |
+
n += len(self.tuple_literals)
|
| 104 |
+
if isinstance(value, frozenset):
|
| 105 |
+
return n + self.frozenset_literals[value]
|
| 106 |
+
assert False, "invalid literal: %r" % value
|
| 107 |
+
|
| 108 |
+
def num_literals(self) -> int:
|
| 109 |
+
# The first three are for None, True and False
|
| 110 |
+
return (
|
| 111 |
+
NUM_SINGLETONS
|
| 112 |
+
+ len(self.str_literals)
|
| 113 |
+
+ len(self.bytes_literals)
|
| 114 |
+
+ len(self.int_literals)
|
| 115 |
+
+ len(self.float_literals)
|
| 116 |
+
+ len(self.complex_literals)
|
| 117 |
+
+ len(self.tuple_literals)
|
| 118 |
+
+ len(self.frozenset_literals)
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# The following methods return the C encodings of literal values
|
| 122 |
+
# of different types
|
| 123 |
+
|
| 124 |
+
def encoded_str_values(self) -> list[bytes]:
|
| 125 |
+
return _encode_str_values(self.str_literals)
|
| 126 |
+
|
| 127 |
+
def encoded_int_values(self) -> list[bytes]:
|
| 128 |
+
return _encode_int_values(self.int_literals)
|
| 129 |
+
|
| 130 |
+
def encoded_bytes_values(self) -> list[bytes]:
|
| 131 |
+
return _encode_bytes_values(self.bytes_literals)
|
| 132 |
+
|
| 133 |
+
def encoded_float_values(self) -> list[str]:
|
| 134 |
+
return _encode_float_values(self.float_literals)
|
| 135 |
+
|
| 136 |
+
def encoded_complex_values(self) -> list[str]:
|
| 137 |
+
return _encode_complex_values(self.complex_literals)
|
| 138 |
+
|
| 139 |
+
def encoded_tuple_values(self) -> list[str]:
|
| 140 |
+
return self._encode_collection_values(self.tuple_literals)
|
| 141 |
+
|
| 142 |
+
def encoded_frozenset_values(self) -> list[str]:
|
| 143 |
+
return self._encode_collection_values(self.frozenset_literals)
|
| 144 |
+
|
| 145 |
+
def _encode_collection_values(
|
| 146 |
+
self, values: dict[tuple[object, ...], int] | dict[frozenset[object], int]
|
| 147 |
+
) -> list[str]:
|
| 148 |
+
"""Encode tuple/frozenset values into a C array.
|
| 149 |
+
|
| 150 |
+
The format of the result is like this:
|
| 151 |
+
|
| 152 |
+
<number of collections>
|
| 153 |
+
<length of the first collection>
|
| 154 |
+
<literal index of first item>
|
| 155 |
+
...
|
| 156 |
+
<literal index of last item>
|
| 157 |
+
<length of the second collection>
|
| 158 |
+
...
|
| 159 |
+
"""
|
| 160 |
+
value_by_index = {index: value for value, index in values.items()}
|
| 161 |
+
result = []
|
| 162 |
+
count = len(values)
|
| 163 |
+
result.append(str(count))
|
| 164 |
+
for i in range(count):
|
| 165 |
+
value = value_by_index[i]
|
| 166 |
+
result.append(str(len(value)))
|
| 167 |
+
for item in value:
|
| 168 |
+
assert _is_literal_value(item)
|
| 169 |
+
index = self.literal_index(item)
|
| 170 |
+
result.append(str(index))
|
| 171 |
+
return result
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _encode_str_values(values: dict[str, int]) -> list[bytes]:
|
| 175 |
+
value_by_index = {index: value for value, index in values.items()}
|
| 176 |
+
result = []
|
| 177 |
+
line: list[bytes] = []
|
| 178 |
+
line_len = 0
|
| 179 |
+
for i in range(len(values)):
|
| 180 |
+
value = value_by_index[i]
|
| 181 |
+
c_literal = format_str_literal(value)
|
| 182 |
+
c_len = len(c_literal)
|
| 183 |
+
if line_len > 0 and line_len + c_len > 70:
|
| 184 |
+
result.append(format_int(len(line)) + b"".join(line))
|
| 185 |
+
line = []
|
| 186 |
+
line_len = 0
|
| 187 |
+
line.append(c_literal)
|
| 188 |
+
line_len += c_len
|
| 189 |
+
if line:
|
| 190 |
+
result.append(format_int(len(line)) + b"".join(line))
|
| 191 |
+
result.append(b"")
|
| 192 |
+
return result
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _encode_bytes_values(values: dict[bytes, int]) -> list[bytes]:
|
| 196 |
+
value_by_index = {index: value for value, index in values.items()}
|
| 197 |
+
result = []
|
| 198 |
+
line: list[bytes] = []
|
| 199 |
+
line_len = 0
|
| 200 |
+
for i in range(len(values)):
|
| 201 |
+
value = value_by_index[i]
|
| 202 |
+
c_init = format_int(len(value))
|
| 203 |
+
c_len = len(c_init) + len(value)
|
| 204 |
+
if line_len > 0 and line_len + c_len > 70:
|
| 205 |
+
result.append(format_int(len(line)) + b"".join(line))
|
| 206 |
+
line = []
|
| 207 |
+
line_len = 0
|
| 208 |
+
line.append(c_init + value)
|
| 209 |
+
line_len += c_len
|
| 210 |
+
if line:
|
| 211 |
+
result.append(format_int(len(line)) + b"".join(line))
|
| 212 |
+
result.append(b"")
|
| 213 |
+
return result
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def format_int(n: int) -> bytes:
|
| 217 |
+
"""Format an integer using a variable-length binary encoding."""
|
| 218 |
+
if n < 128:
|
| 219 |
+
a = [n]
|
| 220 |
+
else:
|
| 221 |
+
a = []
|
| 222 |
+
while n > 0:
|
| 223 |
+
a.insert(0, n & 0x7F)
|
| 224 |
+
n >>= 7
|
| 225 |
+
for i in range(len(a) - 1):
|
| 226 |
+
# If the highest bit is set, more 7-bit digits follow
|
| 227 |
+
a[i] |= 0x80
|
| 228 |
+
return bytes(a)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def format_str_literal(s: str) -> bytes:
|
| 232 |
+
utf8 = s.encode("utf-8", errors="surrogatepass")
|
| 233 |
+
return format_int(len(utf8)) + utf8
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _encode_int_values(values: dict[int, int]) -> list[bytes]:
|
| 237 |
+
"""Encode int values into C strings.
|
| 238 |
+
|
| 239 |
+
Values are stored in base 10 and separated by 0 bytes.
|
| 240 |
+
"""
|
| 241 |
+
value_by_index = {index: value for value, index in values.items()}
|
| 242 |
+
result = []
|
| 243 |
+
line: list[bytes] = []
|
| 244 |
+
line_len = 0
|
| 245 |
+
for i in range(len(values)):
|
| 246 |
+
value = value_by_index[i]
|
| 247 |
+
encoded = b"%d" % value
|
| 248 |
+
if line_len > 0 and line_len + len(encoded) > 70:
|
| 249 |
+
result.append(format_int(len(line)) + b"\0".join(line))
|
| 250 |
+
line = []
|
| 251 |
+
line_len = 0
|
| 252 |
+
line.append(encoded)
|
| 253 |
+
line_len += len(encoded)
|
| 254 |
+
if line:
|
| 255 |
+
result.append(format_int(len(line)) + b"\0".join(line))
|
| 256 |
+
result.append(b"")
|
| 257 |
+
return result
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def float_to_c(x: float) -> str:
|
| 261 |
+
"""Return C literal representation of a float value."""
|
| 262 |
+
s = str(x)
|
| 263 |
+
if s == "inf":
|
| 264 |
+
return "INFINITY"
|
| 265 |
+
elif s == "-inf":
|
| 266 |
+
return "-INFINITY"
|
| 267 |
+
elif s == "nan":
|
| 268 |
+
return "NAN"
|
| 269 |
+
return s
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _encode_float_values(values: dict[float, int]) -> list[str]:
|
| 273 |
+
"""Encode float values into a C array values.
|
| 274 |
+
|
| 275 |
+
The result contains the number of values followed by individual values.
|
| 276 |
+
"""
|
| 277 |
+
value_by_index = {index: value for value, index in values.items()}
|
| 278 |
+
result = []
|
| 279 |
+
num = len(values)
|
| 280 |
+
result.append(str(num))
|
| 281 |
+
for i in range(num):
|
| 282 |
+
value = value_by_index[i]
|
| 283 |
+
result.append(float_to_c(value))
|
| 284 |
+
return result
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _encode_complex_values(values: dict[complex, int]) -> list[str]:
|
| 288 |
+
"""Encode float values into a C array values.
|
| 289 |
+
|
| 290 |
+
The result contains the number of values followed by pairs of doubles
|
| 291 |
+
representing complex numbers.
|
| 292 |
+
"""
|
| 293 |
+
value_by_index = {index: value for value, index in values.items()}
|
| 294 |
+
result = []
|
| 295 |
+
num = len(values)
|
| 296 |
+
result.append(str(num))
|
| 297 |
+
for i in range(num):
|
| 298 |
+
value = value_by_index[i]
|
| 299 |
+
result.append(float_to_c(value.real))
|
| 300 |
+
result.append(float_to_c(value.imag))
|
| 301 |
+
return result
|
micromamba_root/Lib/site-packages/mypyc/ir/__init__.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/ir/__init__.py
ADDED
|
File without changes
|
micromamba_root/Lib/site-packages/mypyc/ir/class_ir.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/ir/class_ir.py
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Intermediate representation of classes."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import NamedTuple
|
| 6 |
+
|
| 7 |
+
from mypyc.common import PROPSET_PREFIX, JsonDict
|
| 8 |
+
from mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature, RuntimeArg
|
| 9 |
+
from mypyc.ir.ops import DeserMaps, Value
|
| 10 |
+
from mypyc.ir.rtypes import RInstance, RType, deserialize_type, object_rprimitive
|
| 11 |
+
from mypyc.namegen import NameGenerator, exported_name
|
| 12 |
+
|
| 13 |
+
# Some notes on the vtable layout: Each concrete class has a vtable
|
| 14 |
+
# that contains function pointers for its methods. So that subclasses
|
| 15 |
+
# may be efficiently used when their parent class is expected, the
|
| 16 |
+
# layout of child vtables must be an extension of their base class's
|
| 17 |
+
# vtable.
|
| 18 |
+
#
|
| 19 |
+
# This makes multiple inheritance tricky, since obviously we cannot be
|
| 20 |
+
# an extension of multiple parent classes. We solve this by requiring
|
| 21 |
+
# all but one parent to be "traits", which we can operate on in a
|
| 22 |
+
# somewhat less efficient way. For each trait implemented by a class,
|
| 23 |
+
# we generate a separate vtable for the methods in that trait.
|
| 24 |
+
# We then store an array of (trait type, trait vtable) pointers alongside
|
| 25 |
+
# a class's main vtable. When we want to call a trait method, we
|
| 26 |
+
# (at runtime!) search the array of trait vtables to find the correct one,
|
| 27 |
+
# then call through it.
|
| 28 |
+
# Trait vtables additionally need entries for attribute getters and setters,
|
| 29 |
+
# since they can't always be in the same location.
|
| 30 |
+
#
|
| 31 |
+
# To keep down the number of indirections necessary, we store the
|
| 32 |
+
# array of trait vtables in the memory *before* the class vtable, and
|
| 33 |
+
# search it backwards. (This is a trick we can only do once---there
|
| 34 |
+
# are only two directions to store data in---but I don't think we'll
|
| 35 |
+
# need it again.)
|
| 36 |
+
# There are some tricks we could try in the future to store the trait
|
| 37 |
+
# vtables inline in the trait table (which would cut down one indirection),
|
| 38 |
+
# but this seems good enough for now.
|
| 39 |
+
#
|
| 40 |
+
# As an example:
|
| 41 |
+
# Imagine that we have a class B that inherits from a concrete class A
|
| 42 |
+
# and traits T1 and T2, and that A has methods foo() and
|
| 43 |
+
# bar() and B overrides bar() with a more specific type.
|
| 44 |
+
# Then B's vtable will look something like:
|
| 45 |
+
#
|
| 46 |
+
# T1 type object
|
| 47 |
+
# ptr to B's T1 trait vtable
|
| 48 |
+
# T2 type object
|
| 49 |
+
# ptr to B's T2 trait vtable
|
| 50 |
+
# -> | A.foo
|
| 51 |
+
# | Glue function that converts between A.bar's type and B.bar
|
| 52 |
+
# B.bar
|
| 53 |
+
# B.baz
|
| 54 |
+
#
|
| 55 |
+
# The arrow points to the "start" of the vtable (what vtable pointers
|
| 56 |
+
# point to) and the bars indicate which parts correspond to the parent
|
| 57 |
+
# class A's vtable layout.
|
| 58 |
+
#
|
| 59 |
+
# Classes that allow interpreted code to subclass them also have a
|
| 60 |
+
# "shadow vtable" that contains implementations that delegate to
|
| 61 |
+
# making a pycall, so that overridden methods in interpreted children
|
| 62 |
+
# will be called. (A better strategy could dynamically generate these
|
| 63 |
+
# vtables based on which methods are overridden in the children.)
|
| 64 |
+
|
| 65 |
+
# Descriptions of method and attribute entries in class vtables.
|
| 66 |
+
# The 'cls' field is the class that the method/attr was defined in,
|
| 67 |
+
# which might be a parent class.
|
| 68 |
+
# The 'shadow_method', if present, contains the method that should be
|
| 69 |
+
# placed in the class's shadow vtable (if it has one).
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class VTableMethod(NamedTuple):
|
| 73 |
+
cls: "ClassIR" # noqa: UP037
|
| 74 |
+
name: str
|
| 75 |
+
method: FuncIR
|
| 76 |
+
shadow_method: FuncIR | None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
VTableEntries = list[VTableMethod]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class ClassIR:
|
| 83 |
+
"""Intermediate representation of a class.
|
| 84 |
+
|
| 85 |
+
This also describes the runtime structure of native instances.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
def __init__(
|
| 89 |
+
self,
|
| 90 |
+
name: str,
|
| 91 |
+
module_name: str,
|
| 92 |
+
is_trait: bool = False,
|
| 93 |
+
is_generated: bool = False,
|
| 94 |
+
is_abstract: bool = False,
|
| 95 |
+
is_ext_class: bool = True,
|
| 96 |
+
is_final_class: bool = False,
|
| 97 |
+
) -> None:
|
| 98 |
+
self.name = name
|
| 99 |
+
self.module_name = module_name
|
| 100 |
+
self.is_trait = is_trait
|
| 101 |
+
self.is_generated = is_generated
|
| 102 |
+
self.is_abstract = is_abstract
|
| 103 |
+
self.is_ext_class = is_ext_class
|
| 104 |
+
self.is_final_class = is_final_class
|
| 105 |
+
# An augmented class has additional methods separate from what mypyc generates.
|
| 106 |
+
# Right now the only one is dataclasses.
|
| 107 |
+
self.is_augmented = False
|
| 108 |
+
# Does this inherit from a Python class?
|
| 109 |
+
self.inherits_python = False
|
| 110 |
+
# Do instances of this class have __dict__?
|
| 111 |
+
self.has_dict = False
|
| 112 |
+
# Do we allow interpreted subclasses? Derived from a mypyc_attr.
|
| 113 |
+
self.allow_interpreted_subclasses = False
|
| 114 |
+
# Does this class need getseters to be generated for its attributes? (getseters are also
|
| 115 |
+
# added if is_generated is False)
|
| 116 |
+
self.needs_getseters = False
|
| 117 |
+
# Is this class declared as serializable (supports copy.copy
|
| 118 |
+
# and pickle) using @mypyc_attr(serializable=True)?
|
| 119 |
+
#
|
| 120 |
+
# Additionally, any class with this attribute False but with
|
| 121 |
+
# an __init__ that can be called without any arguments is
|
| 122 |
+
# *implicitly serializable*. In this case __init__ will be
|
| 123 |
+
# called during deserialization without arguments. If this is
|
| 124 |
+
# True, we match Python semantics and __init__ won't be called
|
| 125 |
+
# during deserialization.
|
| 126 |
+
#
|
| 127 |
+
# This impacts also all subclasses. Use is_serializable() to
|
| 128 |
+
# also consider base classes.
|
| 129 |
+
self._serializable = False
|
| 130 |
+
# If this a subclass of some built-in python class, the name
|
| 131 |
+
# of the object for that class. We currently only support this
|
| 132 |
+
# in a few ad-hoc cases.
|
| 133 |
+
self.builtin_base: str | None = None
|
| 134 |
+
# Default empty constructor
|
| 135 |
+
self.ctor = FuncDecl(name, None, module_name, FuncSignature([], RInstance(self)))
|
| 136 |
+
# Declare setup method that allocates and initializes an object. type is the
|
| 137 |
+
# type of the class being initialized, which could be another class if there
|
| 138 |
+
# is an interpreted subclass.
|
| 139 |
+
# TODO: Make it a regular method and generate its body in IR
|
| 140 |
+
self.setup = FuncDecl(
|
| 141 |
+
"__mypyc__" + name + "_setup",
|
| 142 |
+
None,
|
| 143 |
+
module_name,
|
| 144 |
+
FuncSignature([RuntimeArg("type", object_rprimitive)], RInstance(self)),
|
| 145 |
+
)
|
| 146 |
+
# Attributes defined in the class (not inherited)
|
| 147 |
+
self.attributes: dict[str, RType] = {}
|
| 148 |
+
# Deletable attributes
|
| 149 |
+
self.deletable: list[str] = []
|
| 150 |
+
# We populate method_types with the signatures of every method before
|
| 151 |
+
# we generate methods, and we rely on this information being present.
|
| 152 |
+
self.method_decls: dict[str, FuncDecl] = {}
|
| 153 |
+
# Map of methods that are actually present in an extension class
|
| 154 |
+
self.methods: dict[str, FuncIR] = {}
|
| 155 |
+
# Glue methods for boxing/unboxing when a class changes the type
|
| 156 |
+
# while overriding a method. Maps from (parent class overridden, method)
|
| 157 |
+
# to IR of glue method.
|
| 158 |
+
self.glue_methods: dict[tuple[ClassIR, str], FuncIR] = {}
|
| 159 |
+
|
| 160 |
+
# Properties are accessed like attributes, but have behavior like method calls.
|
| 161 |
+
# They don't belong in the methods dictionary, since we don't want to expose them to
|
| 162 |
+
# Python's method API. But we want to put them into our own vtable as methods, so that
|
| 163 |
+
# they are properly handled and overridden. The property dictionary values are a tuple
|
| 164 |
+
# containing a property getter and an optional property setter.
|
| 165 |
+
self.properties: dict[str, tuple[FuncIR, FuncIR | None]] = {}
|
| 166 |
+
# We generate these in prepare_class_def so that we have access to them when generating
|
| 167 |
+
# other methods and properties that rely on these types.
|
| 168 |
+
self.property_types: dict[str, RType] = {}
|
| 169 |
+
|
| 170 |
+
self.vtable: dict[str, int] | None = None
|
| 171 |
+
self.vtable_entries: VTableEntries = []
|
| 172 |
+
self.trait_vtables: dict[ClassIR, VTableEntries] = {}
|
| 173 |
+
# N.B: base might not actually quite be the direct base.
|
| 174 |
+
# It is the nearest concrete base, but we allow a trait in between.
|
| 175 |
+
self.base: ClassIR | None = None
|
| 176 |
+
self.traits: list[ClassIR] = []
|
| 177 |
+
# Supply a working mro for most generated classes. Real classes will need to
|
| 178 |
+
# fix it up.
|
| 179 |
+
self.mro: list[ClassIR] = [self]
|
| 180 |
+
# base_mro is the chain of concrete (non-trait) ancestors
|
| 181 |
+
self.base_mro: list[ClassIR] = [self]
|
| 182 |
+
|
| 183 |
+
# Direct subclasses of this class (use subclasses() to also include non-direct ones)
|
| 184 |
+
# None if separate compilation prevents this from working.
|
| 185 |
+
#
|
| 186 |
+
# Often it's better to use has_no_subclasses() or subclasses() instead.
|
| 187 |
+
self.children: list[ClassIR] | None = []
|
| 188 |
+
|
| 189 |
+
# Instance attributes that are initialized in the class body.
|
| 190 |
+
self.attrs_with_defaults: set[str] = set()
|
| 191 |
+
|
| 192 |
+
# Attributes that are always initialized in __init__ or class body
|
| 193 |
+
# (inferred in mypyc.analysis.attrdefined using interprocedural analysis).
|
| 194 |
+
# These can never raise AttributeError when accessed. If an attribute
|
| 195 |
+
# is *not* always initialized, we normally use the error value for
|
| 196 |
+
# an undefined value. If the attribute byte has an overlapping error value
|
| 197 |
+
# (the error_overlap attribute is true for the RType), we use a bitmap
|
| 198 |
+
# to track if the attribute is defined instead (see bitmap_attrs).
|
| 199 |
+
self._always_initialized_attrs: set[str] = set()
|
| 200 |
+
|
| 201 |
+
# Attributes that are sometimes initialized in __init__
|
| 202 |
+
self._sometimes_initialized_attrs: set[str] = set()
|
| 203 |
+
|
| 204 |
+
# If True, __init__ can make 'self' visible to unanalyzed/arbitrary code
|
| 205 |
+
self.init_self_leak = False
|
| 206 |
+
|
| 207 |
+
# Definedness of these attributes is backed by a bitmap. Index in the list
|
| 208 |
+
# indicates the bit number. Includes inherited attributes. We need the
|
| 209 |
+
# bitmap for types such as native ints (i64 etc.) that can't have a dedicated
|
| 210 |
+
# error value that doesn't overlap a valid value. The bitmap is used if the
|
| 211 |
+
# value of an attribute is the same as the error value.
|
| 212 |
+
self.bitmap_attrs: list[str] = []
|
| 213 |
+
|
| 214 |
+
# If this is a generator environment class, what is the actual method for it
|
| 215 |
+
self.env_user_function: FuncIR | None = None
|
| 216 |
+
|
| 217 |
+
# If True, keep one freed, cleared instance available for immediate reuse to
|
| 218 |
+
# speed up allocations. This helps if many objects are freed quickly, before
|
| 219 |
+
# other instances of the same class are allocated. This is effectively a
|
| 220 |
+
# per-type free "list" of up to length 1.
|
| 221 |
+
self.reuse_freed_instance = False
|
| 222 |
+
|
| 223 |
+
# If True, the class does not participate in cyclic garbage collection.
|
| 224 |
+
# This can improve performance but is only safe if instances can never
|
| 225 |
+
# be part of reference cycles. Derived from @mypyc_attr(acyclic=True).
|
| 226 |
+
self.is_acyclic = False
|
| 227 |
+
|
| 228 |
+
# Is this a class inheriting from enum.Enum? Such classes can be special-cased.
|
| 229 |
+
self.is_enum = False
|
| 230 |
+
|
| 231 |
+
# Name of the function if this a callable class representing a coroutine.
|
| 232 |
+
self.coroutine_name: str | None = None
|
| 233 |
+
|
| 234 |
+
def __repr__(self) -> str:
|
| 235 |
+
return (
|
| 236 |
+
"ClassIR("
|
| 237 |
+
"name={self.name}, module_name={self.module_name}, "
|
| 238 |
+
"is_trait={self.is_trait}, is_generated={self.is_generated}, "
|
| 239 |
+
"is_abstract={self.is_abstract}, is_ext_class={self.is_ext_class}, "
|
| 240 |
+
"is_final_class={self.is_final_class}"
|
| 241 |
+
")".format(self=self)
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
@property
|
| 245 |
+
def fullname(self) -> str:
|
| 246 |
+
return f"{self.module_name}.{self.name}"
|
| 247 |
+
|
| 248 |
+
def real_base(self) -> ClassIR | None:
|
| 249 |
+
"""Return the actual concrete base class, if there is one."""
|
| 250 |
+
if len(self.mro) > 1 and not self.mro[1].is_trait:
|
| 251 |
+
return self.mro[1]
|
| 252 |
+
return None
|
| 253 |
+
|
| 254 |
+
def vtable_entry(self, name: str) -> int:
|
| 255 |
+
assert self.vtable is not None, "vtable not computed yet"
|
| 256 |
+
assert name in self.vtable, f"{self.name!r} has no attribute {name!r}"
|
| 257 |
+
return self.vtable[name]
|
| 258 |
+
|
| 259 |
+
def attr_details(self, name: str) -> tuple[RType, ClassIR]:
|
| 260 |
+
for ir in self.mro:
|
| 261 |
+
if name in ir.attributes:
|
| 262 |
+
return ir.attributes[name], ir
|
| 263 |
+
if name in ir.property_types:
|
| 264 |
+
return ir.property_types[name], ir
|
| 265 |
+
raise KeyError(f"{self.name!r} has no attribute {name!r}")
|
| 266 |
+
|
| 267 |
+
def attr_type(self, name: str) -> RType:
|
| 268 |
+
return self.attr_details(name)[0]
|
| 269 |
+
|
| 270 |
+
def method_decl(self, name: str) -> FuncDecl:
|
| 271 |
+
for ir in self.mro:
|
| 272 |
+
if name in ir.method_decls:
|
| 273 |
+
return ir.method_decls[name]
|
| 274 |
+
raise KeyError(f"{self.name!r} has no attribute {name!r}")
|
| 275 |
+
|
| 276 |
+
def method_sig(self, name: str) -> FuncSignature:
|
| 277 |
+
return self.method_decl(name).sig
|
| 278 |
+
|
| 279 |
+
def has_method(self, name: str) -> bool:
|
| 280 |
+
try:
|
| 281 |
+
self.method_decl(name)
|
| 282 |
+
except KeyError:
|
| 283 |
+
return False
|
| 284 |
+
return True
|
| 285 |
+
|
| 286 |
+
def is_method_final(self, name: str) -> bool:
|
| 287 |
+
subs = self.subclasses()
|
| 288 |
+
if subs is None:
|
| 289 |
+
return self.is_final_class
|
| 290 |
+
|
| 291 |
+
if self.has_method(name):
|
| 292 |
+
method_decl = self.method_decl(name)
|
| 293 |
+
for subc in subs:
|
| 294 |
+
if subc.method_decl(name) != method_decl:
|
| 295 |
+
return False
|
| 296 |
+
return True
|
| 297 |
+
else:
|
| 298 |
+
return not any(subc.has_method(name) for subc in subs)
|
| 299 |
+
|
| 300 |
+
def has_attr(self, name: str) -> bool:
|
| 301 |
+
try:
|
| 302 |
+
self.attr_type(name)
|
| 303 |
+
except KeyError:
|
| 304 |
+
return False
|
| 305 |
+
return True
|
| 306 |
+
|
| 307 |
+
def is_deletable(self, name: str) -> bool:
|
| 308 |
+
return any(name in ir.deletable for ir in self.mro)
|
| 309 |
+
|
| 310 |
+
def is_always_defined(self, name: str) -> bool:
|
| 311 |
+
if self.is_deletable(name):
|
| 312 |
+
return False
|
| 313 |
+
return name in self._always_initialized_attrs
|
| 314 |
+
|
| 315 |
+
def name_prefix(self, names: NameGenerator) -> str:
|
| 316 |
+
return names.private_name(self.module_name, self.name)
|
| 317 |
+
|
| 318 |
+
def struct_name(self, names: NameGenerator) -> str:
|
| 319 |
+
return f"{exported_name(self.fullname)}Object"
|
| 320 |
+
|
| 321 |
+
def get_method_and_class(
|
| 322 |
+
self, name: str, *, prefer_method: bool = False
|
| 323 |
+
) -> tuple[FuncIR, ClassIR] | None:
|
| 324 |
+
for ir in self.mro:
|
| 325 |
+
if name in ir.methods:
|
| 326 |
+
func_ir = ir.methods[name]
|
| 327 |
+
if not prefer_method and func_ir.decl.implicit:
|
| 328 |
+
# This is an implicit accessor, so there is also an attribute definition
|
| 329 |
+
# which the caller prefers. This happens if an attribute overrides a
|
| 330 |
+
# property.
|
| 331 |
+
return None
|
| 332 |
+
return func_ir, ir
|
| 333 |
+
|
| 334 |
+
return None
|
| 335 |
+
|
| 336 |
+
def get_method(self, name: str, *, prefer_method: bool = False) -> FuncIR | None:
|
| 337 |
+
res = self.get_method_and_class(name, prefer_method=prefer_method)
|
| 338 |
+
return res[0] if res else None
|
| 339 |
+
|
| 340 |
+
def has_method_decl(self, name: str) -> bool:
|
| 341 |
+
return any(name in ir.method_decls for ir in self.mro)
|
| 342 |
+
|
| 343 |
+
def has_no_subclasses(self) -> bool:
|
| 344 |
+
return self.children == [] and not self.allow_interpreted_subclasses
|
| 345 |
+
|
| 346 |
+
def subclasses(self) -> set[ClassIR] | None:
|
| 347 |
+
"""Return all subclasses of this class, both direct and indirect.
|
| 348 |
+
|
| 349 |
+
Return None if it is impossible to identify all subclasses, for example
|
| 350 |
+
because we are performing separate compilation.
|
| 351 |
+
"""
|
| 352 |
+
if self.children is None or self.allow_interpreted_subclasses:
|
| 353 |
+
return None
|
| 354 |
+
result = set(self.children)
|
| 355 |
+
for child in self.children:
|
| 356 |
+
if child.children:
|
| 357 |
+
child_subs = child.subclasses()
|
| 358 |
+
if child_subs is None:
|
| 359 |
+
return None
|
| 360 |
+
result.update(child_subs)
|
| 361 |
+
return result
|
| 362 |
+
|
| 363 |
+
def concrete_subclasses(self) -> list[ClassIR] | None:
|
| 364 |
+
"""Return all concrete (i.e. non-trait and non-abstract) subclasses.
|
| 365 |
+
|
| 366 |
+
Include both direct and indirect subclasses. Place classes with no children first.
|
| 367 |
+
"""
|
| 368 |
+
subs = self.subclasses()
|
| 369 |
+
if subs is None:
|
| 370 |
+
return None
|
| 371 |
+
concrete = {c for c in subs if not (c.is_trait or c.is_abstract)}
|
| 372 |
+
# We place classes with no children first because they are more likely
|
| 373 |
+
# to appear in various isinstance() checks. We then sort leaves by name
|
| 374 |
+
# to get stable order.
|
| 375 |
+
return sorted(concrete, key=lambda c: (len(c.children or []), c.name))
|
| 376 |
+
|
| 377 |
+
def is_serializable(self) -> bool:
|
| 378 |
+
return any(ci._serializable for ci in self.mro)
|
| 379 |
+
|
| 380 |
+
def serialize(self) -> JsonDict:
|
| 381 |
+
return {
|
| 382 |
+
"name": self.name,
|
| 383 |
+
"module_name": self.module_name,
|
| 384 |
+
"is_trait": self.is_trait,
|
| 385 |
+
"is_ext_class": self.is_ext_class,
|
| 386 |
+
"is_abstract": self.is_abstract,
|
| 387 |
+
"is_generated": self.is_generated,
|
| 388 |
+
"is_augmented": self.is_augmented,
|
| 389 |
+
"is_final_class": self.is_final_class,
|
| 390 |
+
"inherits_python": self.inherits_python,
|
| 391 |
+
"has_dict": self.has_dict,
|
| 392 |
+
"allow_interpreted_subclasses": self.allow_interpreted_subclasses,
|
| 393 |
+
"needs_getseters": self.needs_getseters,
|
| 394 |
+
"_serializable": self._serializable,
|
| 395 |
+
"builtin_base": self.builtin_base,
|
| 396 |
+
"ctor": self.ctor.serialize(),
|
| 397 |
+
# We serialize dicts as lists to ensure order is preserved
|
| 398 |
+
"attributes": [(k, t.serialize()) for k, t in self.attributes.items()],
|
| 399 |
+
# We try to serialize a name reference, but if the decl isn't in methods
|
| 400 |
+
# then we can't be sure that will work so we serialize the whole decl.
|
| 401 |
+
"method_decls": [
|
| 402 |
+
(k, d.id if k in self.methods else d.serialize())
|
| 403 |
+
for k, d in self.method_decls.items()
|
| 404 |
+
],
|
| 405 |
+
# We serialize method fullnames out and put methods in a separate dict
|
| 406 |
+
"methods": [(k, m.id) for k, m in self.methods.items()],
|
| 407 |
+
"glue_methods": [
|
| 408 |
+
((cir.fullname, k), m.id) for (cir, k), m in self.glue_methods.items()
|
| 409 |
+
],
|
| 410 |
+
# We serialize properties and property_types separately out of an
|
| 411 |
+
# abundance of caution about preserving dict ordering...
|
| 412 |
+
"property_types": [(k, t.serialize()) for k, t in self.property_types.items()],
|
| 413 |
+
"properties": list(self.properties),
|
| 414 |
+
"vtable": self.vtable,
|
| 415 |
+
"vtable_entries": serialize_vtable(self.vtable_entries),
|
| 416 |
+
"trait_vtables": [
|
| 417 |
+
(cir.fullname, serialize_vtable(v)) for cir, v in self.trait_vtables.items()
|
| 418 |
+
],
|
| 419 |
+
# References to class IRs are all just names
|
| 420 |
+
"base": self.base.fullname if self.base else None,
|
| 421 |
+
"traits": [cir.fullname for cir in self.traits],
|
| 422 |
+
"mro": [cir.fullname for cir in self.mro],
|
| 423 |
+
"base_mro": [cir.fullname for cir in self.base_mro],
|
| 424 |
+
"children": (
|
| 425 |
+
[cir.fullname for cir in self.children] if self.children is not None else None
|
| 426 |
+
),
|
| 427 |
+
"deletable": self.deletable,
|
| 428 |
+
"attrs_with_defaults": sorted(self.attrs_with_defaults),
|
| 429 |
+
"_always_initialized_attrs": sorted(self._always_initialized_attrs),
|
| 430 |
+
"_sometimes_initialized_attrs": sorted(self._sometimes_initialized_attrs),
|
| 431 |
+
"init_self_leak": self.init_self_leak,
|
| 432 |
+
"env_user_function": self.env_user_function.id if self.env_user_function else None,
|
| 433 |
+
"reuse_freed_instance": self.reuse_freed_instance,
|
| 434 |
+
"is_acyclic": self.is_acyclic,
|
| 435 |
+
"is_enum": self.is_enum,
|
| 436 |
+
"is_coroutine": self.coroutine_name,
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
@classmethod
|
| 440 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ClassIR:
|
| 441 |
+
fullname = data["module_name"] + "." + data["name"]
|
| 442 |
+
assert fullname in ctx.classes, "Class %s not in deser class map" % fullname
|
| 443 |
+
ir = ctx.classes[fullname]
|
| 444 |
+
|
| 445 |
+
ir.is_trait = data["is_trait"]
|
| 446 |
+
ir.is_generated = data["is_generated"]
|
| 447 |
+
ir.is_abstract = data["is_abstract"]
|
| 448 |
+
ir.is_ext_class = data["is_ext_class"]
|
| 449 |
+
ir.is_augmented = data["is_augmented"]
|
| 450 |
+
ir.is_final_class = data["is_final_class"]
|
| 451 |
+
ir.inherits_python = data["inherits_python"]
|
| 452 |
+
ir.has_dict = data["has_dict"]
|
| 453 |
+
ir.allow_interpreted_subclasses = data["allow_interpreted_subclasses"]
|
| 454 |
+
ir.needs_getseters = data["needs_getseters"]
|
| 455 |
+
ir._serializable = data["_serializable"]
|
| 456 |
+
ir.builtin_base = data["builtin_base"]
|
| 457 |
+
ir.ctor = FuncDecl.deserialize(data["ctor"], ctx)
|
| 458 |
+
ir.attributes = {k: deserialize_type(t, ctx) for k, t in data["attributes"]}
|
| 459 |
+
ir.method_decls = {
|
| 460 |
+
k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx)
|
| 461 |
+
for k, v in data["method_decls"]
|
| 462 |
+
}
|
| 463 |
+
ir.methods = {k: ctx.functions[v] for k, v in data["methods"]}
|
| 464 |
+
ir.glue_methods = {
|
| 465 |
+
(ctx.classes[c], k): ctx.functions[v] for (c, k), v in data["glue_methods"]
|
| 466 |
+
}
|
| 467 |
+
ir.property_types = {k: deserialize_type(t, ctx) for k, t in data["property_types"]}
|
| 468 |
+
ir.properties = {
|
| 469 |
+
k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data["properties"]
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
ir.vtable = data["vtable"]
|
| 473 |
+
ir.vtable_entries = deserialize_vtable(data["vtable_entries"], ctx)
|
| 474 |
+
ir.trait_vtables = {
|
| 475 |
+
ctx.classes[k]: deserialize_vtable(v, ctx) for k, v in data["trait_vtables"]
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
base = data["base"]
|
| 479 |
+
ir.base = ctx.classes[base] if base else None
|
| 480 |
+
ir.traits = [ctx.classes[s] for s in data["traits"]]
|
| 481 |
+
ir.mro = [ctx.classes[s] for s in data["mro"]]
|
| 482 |
+
ir.base_mro = [ctx.classes[s] for s in data["base_mro"]]
|
| 483 |
+
ir.children = data["children"] and [ctx.classes[s] for s in data["children"]]
|
| 484 |
+
ir.deletable = data["deletable"]
|
| 485 |
+
ir.attrs_with_defaults = set(data["attrs_with_defaults"])
|
| 486 |
+
ir._always_initialized_attrs = set(data["_always_initialized_attrs"])
|
| 487 |
+
ir._sometimes_initialized_attrs = set(data["_sometimes_initialized_attrs"])
|
| 488 |
+
ir.init_self_leak = data["init_self_leak"]
|
| 489 |
+
ir.env_user_function = (
|
| 490 |
+
ctx.functions[data["env_user_function"]] if data["env_user_function"] else None
|
| 491 |
+
)
|
| 492 |
+
ir.reuse_freed_instance = data["reuse_freed_instance"]
|
| 493 |
+
ir.is_acyclic = data.get("is_acyclic", False)
|
| 494 |
+
ir.is_enum = data["is_enum"]
|
| 495 |
+
ir.coroutine_name = data["is_coroutine"]
|
| 496 |
+
|
| 497 |
+
return ir
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
class NonExtClassInfo:
|
| 501 |
+
"""Information needed to construct a non-extension class (Python class).
|
| 502 |
+
|
| 503 |
+
Includes the class dictionary, a tuple of base classes,
|
| 504 |
+
the class annotations dictionary, and the metaclass.
|
| 505 |
+
"""
|
| 506 |
+
|
| 507 |
+
def __init__(self, dict: Value, bases: Value, anns: Value, metaclass: Value) -> None:
|
| 508 |
+
self.dict = dict
|
| 509 |
+
self.bases = bases
|
| 510 |
+
self.anns = anns
|
| 511 |
+
self.metaclass = metaclass
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def serialize_vtable_entry(entry: VTableMethod) -> JsonDict:
|
| 515 |
+
return {
|
| 516 |
+
".class": "VTableMethod",
|
| 517 |
+
"cls": entry.cls.fullname,
|
| 518 |
+
"name": entry.name,
|
| 519 |
+
"method": entry.method.decl.id,
|
| 520 |
+
"shadow_method": entry.shadow_method.decl.id if entry.shadow_method else None,
|
| 521 |
+
}
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def serialize_vtable(vtable: VTableEntries) -> list[JsonDict]:
|
| 525 |
+
return [serialize_vtable_entry(v) for v in vtable]
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def deserialize_vtable_entry(data: JsonDict, ctx: DeserMaps) -> VTableMethod:
|
| 529 |
+
if data[".class"] == "VTableMethod":
|
| 530 |
+
return VTableMethod(
|
| 531 |
+
ctx.classes[data["cls"]],
|
| 532 |
+
data["name"],
|
| 533 |
+
ctx.functions[data["method"]],
|
| 534 |
+
ctx.functions[data["shadow_method"]] if data["shadow_method"] else None,
|
| 535 |
+
)
|
| 536 |
+
assert False, "Bogus vtable .class: %s" % data[".class"]
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def deserialize_vtable(data: list[JsonDict], ctx: DeserMaps) -> VTableEntries:
|
| 540 |
+
return [deserialize_vtable_entry(x, ctx) for x in data]
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def all_concrete_classes(class_ir: ClassIR) -> list[ClassIR] | None:
|
| 544 |
+
"""Return all concrete classes among the class itself and its subclasses."""
|
| 545 |
+
concrete = class_ir.concrete_subclasses()
|
| 546 |
+
if concrete is None:
|
| 547 |
+
return None
|
| 548 |
+
if not (class_ir.is_abstract or class_ir.is_trait):
|
| 549 |
+
concrete.append(class_ir)
|
| 550 |
+
return concrete
|
micromamba_root/Lib/site-packages/mypyc/ir/deps.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/ir/deps.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Final
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Capsule:
|
| 5 |
+
"""Defines a C extension capsule that a primitive may require."""
|
| 6 |
+
|
| 7 |
+
def __init__(self, name: str) -> None:
|
| 8 |
+
# Module fullname, e.g. 'librt.base64'
|
| 9 |
+
self.name: Final = name
|
| 10 |
+
|
| 11 |
+
def __repr__(self) -> str:
|
| 12 |
+
return f"Capsule(name={self.name!r})"
|
| 13 |
+
|
| 14 |
+
def __eq__(self, other: object) -> bool:
|
| 15 |
+
return isinstance(other, Capsule) and self.name == other.name
|
| 16 |
+
|
| 17 |
+
def __hash__(self) -> int:
|
| 18 |
+
return hash(("Capsule", self.name))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SourceDep:
|
| 22 |
+
"""Defines a C source file that a primitive may require.
|
| 23 |
+
|
| 24 |
+
Each source file must also have a corresponding .h file (replace .c with .h)
|
| 25 |
+
that gets implicitly #included if the source is used.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(self, path: str) -> None:
|
| 29 |
+
# Relative path from mypyc/lib-rt, e.g. 'bytes_extra_ops.c'
|
| 30 |
+
self.path: Final = path
|
| 31 |
+
|
| 32 |
+
def __repr__(self) -> str:
|
| 33 |
+
return f"SourceDep(path={self.path!r})"
|
| 34 |
+
|
| 35 |
+
def __eq__(self, other: object) -> bool:
|
| 36 |
+
return isinstance(other, SourceDep) and self.path == other.path
|
| 37 |
+
|
| 38 |
+
def __hash__(self) -> int:
|
| 39 |
+
return hash(("SourceDep", self.path))
|
| 40 |
+
|
| 41 |
+
def get_header(self) -> str:
|
| 42 |
+
"""Get the header file path by replacing .c with .h"""
|
| 43 |
+
return self.path.replace(".c", ".h")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
Dependency = Capsule | SourceDep
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
LIBRT_STRINGS: Final = Capsule("librt.strings")
|
| 50 |
+
LIBRT_BASE64: Final = Capsule("librt.base64")
|
| 51 |
+
LIBRT_VECS: Final = Capsule("librt.vecs")
|
| 52 |
+
LIBRT_TIME: Final = Capsule("librt.time")
|
| 53 |
+
|
| 54 |
+
BYTES_EXTRA_OPS: Final = SourceDep("bytes_extra_ops.c")
|
| 55 |
+
BYTES_WRITER_EXTRA_OPS: Final = SourceDep("byteswriter_extra_ops.c")
|
| 56 |
+
STRING_WRITER_EXTRA_OPS: Final = SourceDep("stringwriter_extra_ops.c")
|
| 57 |
+
BYTEARRAY_EXTRA_OPS: Final = SourceDep("bytearray_extra_ops.c")
|
| 58 |
+
STR_EXTRA_OPS: Final = SourceDep("str_extra_ops.c")
|
| 59 |
+
VECS_EXTRA_OPS: Final = SourceDep("vecs_extra_ops.c")
|
micromamba_root/Lib/site-packages/mypyc/ir/func_ir.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/ir/func_ir.py
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Intermediate representation of functions."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import inspect
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
from typing import Final
|
| 8 |
+
|
| 9 |
+
from mypy.nodes import ARG_POS, ArgKind, Block, FuncDef
|
| 10 |
+
from mypyc.common import BITMAP_BITS, JsonDict, bitmap_name, get_id_from_name, short_id_from_name
|
| 11 |
+
from mypyc.ir.ops import (
|
| 12 |
+
Assign,
|
| 13 |
+
AssignMulti,
|
| 14 |
+
BasicBlock,
|
| 15 |
+
Box,
|
| 16 |
+
ControlOp,
|
| 17 |
+
DeserMaps,
|
| 18 |
+
Float,
|
| 19 |
+
Integer,
|
| 20 |
+
LoadAddress,
|
| 21 |
+
LoadLiteral,
|
| 22 |
+
Register,
|
| 23 |
+
TupleSet,
|
| 24 |
+
Value,
|
| 25 |
+
)
|
| 26 |
+
from mypyc.ir.rtypes import (
|
| 27 |
+
RType,
|
| 28 |
+
bitmap_rprimitive,
|
| 29 |
+
deserialize_type,
|
| 30 |
+
is_bool_rprimitive,
|
| 31 |
+
is_none_rprimitive,
|
| 32 |
+
)
|
| 33 |
+
from mypyc.namegen import NameGenerator
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class RuntimeArg:
|
| 37 |
+
"""Description of a function argument in IR.
|
| 38 |
+
|
| 39 |
+
Argument kind is one of ARG_* constants defined in mypy.nodes.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(
|
| 43 |
+
self, name: str, typ: RType, kind: ArgKind = ARG_POS, pos_only: bool = False
|
| 44 |
+
) -> None:
|
| 45 |
+
self.name = name
|
| 46 |
+
self.type = typ
|
| 47 |
+
self.kind = kind
|
| 48 |
+
self.pos_only = pos_only
|
| 49 |
+
|
| 50 |
+
@property
|
| 51 |
+
def optional(self) -> bool:
|
| 52 |
+
return self.kind.is_optional()
|
| 53 |
+
|
| 54 |
+
def __repr__(self) -> str:
|
| 55 |
+
return "RuntimeArg(name={}, type={}, optional={!r}, pos_only={!r})".format(
|
| 56 |
+
self.name, self.type, self.optional, self.pos_only
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def serialize(self) -> JsonDict:
|
| 60 |
+
return {
|
| 61 |
+
"name": self.name,
|
| 62 |
+
"type": self.type.serialize(),
|
| 63 |
+
"kind": int(self.kind.value),
|
| 64 |
+
"pos_only": self.pos_only,
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
@classmethod
|
| 68 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RuntimeArg:
|
| 69 |
+
return RuntimeArg(
|
| 70 |
+
data["name"],
|
| 71 |
+
deserialize_type(data["type"], ctx),
|
| 72 |
+
ArgKind(data["kind"]),
|
| 73 |
+
data["pos_only"],
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class FuncSignature:
|
| 78 |
+
"""Signature of a function in IR."""
|
| 79 |
+
|
| 80 |
+
# TODO: Track if method?
|
| 81 |
+
|
| 82 |
+
def __init__(self, args: Sequence[RuntimeArg], ret_type: RType) -> None:
|
| 83 |
+
self.args = tuple(args)
|
| 84 |
+
self.ret_type = ret_type
|
| 85 |
+
# Bitmap arguments are use to mark default values for arguments that
|
| 86 |
+
# have types with overlapping error values.
|
| 87 |
+
self.num_bitmap_args = num_bitmap_args(self.args)
|
| 88 |
+
if self.num_bitmap_args:
|
| 89 |
+
extra = [
|
| 90 |
+
RuntimeArg(bitmap_name(i), bitmap_rprimitive, pos_only=True)
|
| 91 |
+
for i in range(self.num_bitmap_args)
|
| 92 |
+
]
|
| 93 |
+
self.args = self.args + tuple(reversed(extra))
|
| 94 |
+
|
| 95 |
+
def real_args(self) -> tuple[RuntimeArg, ...]:
|
| 96 |
+
"""Return arguments without any synthetic bitmap arguments."""
|
| 97 |
+
if self.num_bitmap_args:
|
| 98 |
+
return self.args[: -self.num_bitmap_args]
|
| 99 |
+
return self.args
|
| 100 |
+
|
| 101 |
+
def bound_sig(self) -> FuncSignature:
|
| 102 |
+
if self.num_bitmap_args:
|
| 103 |
+
return FuncSignature(self.args[1 : -self.num_bitmap_args], self.ret_type)
|
| 104 |
+
else:
|
| 105 |
+
return FuncSignature(self.args[1:], self.ret_type)
|
| 106 |
+
|
| 107 |
+
def __repr__(self) -> str:
|
| 108 |
+
return f"FuncSignature(args={self.args!r}, ret={self.ret_type!r})"
|
| 109 |
+
|
| 110 |
+
def serialize(self) -> JsonDict:
|
| 111 |
+
if self.num_bitmap_args:
|
| 112 |
+
args = self.args[: -self.num_bitmap_args]
|
| 113 |
+
else:
|
| 114 |
+
args = self.args
|
| 115 |
+
return {"args": [t.serialize() for t in args], "ret_type": self.ret_type.serialize()}
|
| 116 |
+
|
| 117 |
+
@classmethod
|
| 118 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> FuncSignature:
|
| 119 |
+
return FuncSignature(
|
| 120 |
+
[RuntimeArg.deserialize(arg, ctx) for arg in data["args"]],
|
| 121 |
+
deserialize_type(data["ret_type"], ctx),
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def num_bitmap_args(args: tuple[RuntimeArg, ...]) -> int:
|
| 126 |
+
n = 0
|
| 127 |
+
for arg in args:
|
| 128 |
+
if arg.type.error_overlap and arg.kind.is_optional():
|
| 129 |
+
n += 1
|
| 130 |
+
return (n + (BITMAP_BITS - 1)) // BITMAP_BITS
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
FUNC_NORMAL: Final = 0
|
| 134 |
+
FUNC_STATICMETHOD: Final = 1
|
| 135 |
+
FUNC_CLASSMETHOD: Final = 2
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class FuncDecl:
|
| 139 |
+
"""Declaration of a function in IR (without body or implementation).
|
| 140 |
+
|
| 141 |
+
A function can be a regular module-level function, a method, a
|
| 142 |
+
static method, a class method, or a property getter/setter.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
def __init__(
|
| 146 |
+
self,
|
| 147 |
+
name: str,
|
| 148 |
+
class_name: str | None,
|
| 149 |
+
module_name: str,
|
| 150 |
+
sig: FuncSignature,
|
| 151 |
+
kind: int = FUNC_NORMAL,
|
| 152 |
+
*,
|
| 153 |
+
is_prop_setter: bool = False,
|
| 154 |
+
is_prop_getter: bool = False,
|
| 155 |
+
is_generator: bool = False,
|
| 156 |
+
is_coroutine: bool = False,
|
| 157 |
+
implicit: bool = False,
|
| 158 |
+
internal: bool = False,
|
| 159 |
+
) -> None:
|
| 160 |
+
self.name = name
|
| 161 |
+
self.class_name = class_name
|
| 162 |
+
self.module_name = module_name
|
| 163 |
+
self.sig = sig
|
| 164 |
+
self.kind = kind
|
| 165 |
+
self.is_prop_setter = is_prop_setter
|
| 166 |
+
self.is_prop_getter = is_prop_getter
|
| 167 |
+
self.is_generator = is_generator
|
| 168 |
+
self.is_coroutine = is_coroutine
|
| 169 |
+
if class_name is None:
|
| 170 |
+
self.bound_sig: FuncSignature | None = None
|
| 171 |
+
else:
|
| 172 |
+
if kind == FUNC_STATICMETHOD:
|
| 173 |
+
self.bound_sig = sig
|
| 174 |
+
else:
|
| 175 |
+
self.bound_sig = sig.bound_sig()
|
| 176 |
+
|
| 177 |
+
# If True, not present in the mypy AST and must be synthesized during irbuild
|
| 178 |
+
# Currently only supported for property getters/setters
|
| 179 |
+
self.implicit = implicit
|
| 180 |
+
|
| 181 |
+
# If True, only direct C level calls are supported (no wrapper function)
|
| 182 |
+
self.internal = internal
|
| 183 |
+
|
| 184 |
+
# This is optional because this will be set to the line number when the corresponding
|
| 185 |
+
# FuncIR is created
|
| 186 |
+
self._line: int | None = None
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def line(self) -> int:
|
| 190 |
+
assert self._line is not None
|
| 191 |
+
return self._line
|
| 192 |
+
|
| 193 |
+
@line.setter
|
| 194 |
+
def line(self, line: int) -> None:
|
| 195 |
+
self._line = line
|
| 196 |
+
|
| 197 |
+
@property
|
| 198 |
+
def id(self) -> str:
|
| 199 |
+
assert self.line is not None
|
| 200 |
+
return get_id_from_name(self.name, self.fullname, self.line)
|
| 201 |
+
|
| 202 |
+
@staticmethod
|
| 203 |
+
def compute_shortname(class_name: str | None, name: str) -> str:
|
| 204 |
+
return class_name + "." + name if class_name else name
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def shortname(self) -> str:
|
| 208 |
+
return FuncDecl.compute_shortname(self.class_name, self.name)
|
| 209 |
+
|
| 210 |
+
@property
|
| 211 |
+
def fullname(self) -> str:
|
| 212 |
+
return self.module_name + "." + self.shortname
|
| 213 |
+
|
| 214 |
+
def cname(self, names: NameGenerator) -> str:
|
| 215 |
+
partial_name = short_id_from_name(self.name, self.shortname, self._line)
|
| 216 |
+
return names.private_name(self.module_name, partial_name)
|
| 217 |
+
|
| 218 |
+
def serialize(self) -> JsonDict:
|
| 219 |
+
return {
|
| 220 |
+
"name": self.name,
|
| 221 |
+
"class_name": self.class_name,
|
| 222 |
+
"module_name": self.module_name,
|
| 223 |
+
"sig": self.sig.serialize(),
|
| 224 |
+
"kind": self.kind,
|
| 225 |
+
"is_prop_setter": self.is_prop_setter,
|
| 226 |
+
"is_prop_getter": self.is_prop_getter,
|
| 227 |
+
"is_generator": self.is_generator,
|
| 228 |
+
"is_coroutine": self.is_coroutine,
|
| 229 |
+
"implicit": self.implicit,
|
| 230 |
+
"internal": self.internal,
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
# TODO: move this to FuncIR?
|
| 234 |
+
@staticmethod
|
| 235 |
+
def get_id_from_json(func_ir: JsonDict) -> str:
|
| 236 |
+
"""Get the id from the serialized FuncIR associated with this FuncDecl"""
|
| 237 |
+
decl = func_ir["decl"]
|
| 238 |
+
shortname = FuncDecl.compute_shortname(decl["class_name"], decl["name"])
|
| 239 |
+
fullname = decl["module_name"] + "." + shortname
|
| 240 |
+
return get_id_from_name(decl["name"], fullname, func_ir["line"])
|
| 241 |
+
|
| 242 |
+
@classmethod
|
| 243 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> FuncDecl:
|
| 244 |
+
return FuncDecl(
|
| 245 |
+
data["name"],
|
| 246 |
+
data["class_name"],
|
| 247 |
+
data["module_name"],
|
| 248 |
+
FuncSignature.deserialize(data["sig"], ctx),
|
| 249 |
+
data["kind"],
|
| 250 |
+
is_prop_setter=data["is_prop_setter"],
|
| 251 |
+
is_prop_getter=data["is_prop_getter"],
|
| 252 |
+
is_generator=data["is_generator"],
|
| 253 |
+
is_coroutine=data["is_coroutine"],
|
| 254 |
+
implicit=data["implicit"],
|
| 255 |
+
internal=data["internal"],
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class FuncIR:
|
| 260 |
+
"""Intermediate representation of a function with contextual information.
|
| 261 |
+
|
| 262 |
+
Unlike FuncDecl, this includes the IR of the body (basic blocks).
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
def __init__(
|
| 266 |
+
self,
|
| 267 |
+
decl: FuncDecl,
|
| 268 |
+
arg_regs: list[Register],
|
| 269 |
+
blocks: list[BasicBlock],
|
| 270 |
+
line: int = -1,
|
| 271 |
+
traceback_name: str | None = None,
|
| 272 |
+
) -> None:
|
| 273 |
+
# Declaration of the function, including the signature
|
| 274 |
+
self.decl = decl
|
| 275 |
+
# Registers for all the arguments to the function
|
| 276 |
+
self.arg_regs = arg_regs
|
| 277 |
+
# Body of the function
|
| 278 |
+
self.blocks = blocks
|
| 279 |
+
self.decl.line = line
|
| 280 |
+
# The name that should be displayed for tracebacks that
|
| 281 |
+
# include this function. Function will be omitted from
|
| 282 |
+
# tracebacks if None.
|
| 283 |
+
self.traceback_name = traceback_name
|
| 284 |
+
|
| 285 |
+
@property
|
| 286 |
+
def line(self) -> int:
|
| 287 |
+
return self.decl.line
|
| 288 |
+
|
| 289 |
+
@property
|
| 290 |
+
def args(self) -> Sequence[RuntimeArg]:
|
| 291 |
+
return self.decl.sig.args
|
| 292 |
+
|
| 293 |
+
@property
|
| 294 |
+
def ret_type(self) -> RType:
|
| 295 |
+
return self.decl.sig.ret_type
|
| 296 |
+
|
| 297 |
+
@property
|
| 298 |
+
def class_name(self) -> str | None:
|
| 299 |
+
return self.decl.class_name
|
| 300 |
+
|
| 301 |
+
@property
|
| 302 |
+
def sig(self) -> FuncSignature:
|
| 303 |
+
return self.decl.sig
|
| 304 |
+
|
| 305 |
+
@property
|
| 306 |
+
def name(self) -> str:
|
| 307 |
+
return self.decl.name
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def fullname(self) -> str:
|
| 311 |
+
return self.decl.fullname
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def id(self) -> str:
|
| 315 |
+
return self.decl.id
|
| 316 |
+
|
| 317 |
+
@property
|
| 318 |
+
def internal(self) -> bool:
|
| 319 |
+
return self.decl.internal
|
| 320 |
+
|
| 321 |
+
def cname(self, names: NameGenerator) -> str:
|
| 322 |
+
return self.decl.cname(names)
|
| 323 |
+
|
| 324 |
+
def __repr__(self) -> str:
|
| 325 |
+
if self.class_name:
|
| 326 |
+
return f"<FuncIR {self.class_name}.{self.name}>"
|
| 327 |
+
else:
|
| 328 |
+
return f"<FuncIR {self.name}>"
|
| 329 |
+
|
| 330 |
+
def serialize(self) -> JsonDict:
|
| 331 |
+
# We don't include blocks in the serialized version
|
| 332 |
+
return {
|
| 333 |
+
"decl": self.decl.serialize(),
|
| 334 |
+
"line": self.line,
|
| 335 |
+
"traceback_name": self.traceback_name,
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
@classmethod
|
| 339 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> FuncIR:
|
| 340 |
+
return FuncIR(
|
| 341 |
+
FuncDecl.deserialize(data["decl"], ctx), [], [], data["line"], data["traceback_name"]
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
INVALID_FUNC_DEF: Final = FuncDef("<INVALID_FUNC_DEF>", [], Block([]))
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def all_values(args: list[Register], blocks: list[BasicBlock]) -> list[Value]:
|
| 349 |
+
"""Return the set of all values that may be initialized in the blocks.
|
| 350 |
+
|
| 351 |
+
This omits registers that are only read.
|
| 352 |
+
"""
|
| 353 |
+
values: list[Value] = list(args)
|
| 354 |
+
seen_registers = set(args)
|
| 355 |
+
|
| 356 |
+
for block in blocks:
|
| 357 |
+
for op in block.ops:
|
| 358 |
+
if not isinstance(op, ControlOp):
|
| 359 |
+
if isinstance(op, (Assign, AssignMulti)):
|
| 360 |
+
if op.dest not in seen_registers:
|
| 361 |
+
values.append(op.dest)
|
| 362 |
+
seen_registers.add(op.dest)
|
| 363 |
+
elif op.is_void:
|
| 364 |
+
continue
|
| 365 |
+
else:
|
| 366 |
+
# If we take the address of a register, it might get initialized.
|
| 367 |
+
if (
|
| 368 |
+
isinstance(op, LoadAddress)
|
| 369 |
+
and isinstance(op.src, Register)
|
| 370 |
+
and op.src not in seen_registers
|
| 371 |
+
):
|
| 372 |
+
values.append(op.src)
|
| 373 |
+
seen_registers.add(op.src)
|
| 374 |
+
values.append(op)
|
| 375 |
+
|
| 376 |
+
return values
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def all_values_full(args: list[Register], blocks: list[BasicBlock]) -> list[Value]:
|
| 380 |
+
"""Return set of all values that are initialized or accessed."""
|
| 381 |
+
values: list[Value] = list(args)
|
| 382 |
+
seen_registers = set(args)
|
| 383 |
+
|
| 384 |
+
for block in blocks:
|
| 385 |
+
for op in block.ops:
|
| 386 |
+
for source in op.sources():
|
| 387 |
+
# Look for uninitialized registers that are accessed. Ignore
|
| 388 |
+
# non-registers since we don't allow ops outside basic blocks.
|
| 389 |
+
if isinstance(source, Register) and source not in seen_registers:
|
| 390 |
+
values.append(source)
|
| 391 |
+
seen_registers.add(source)
|
| 392 |
+
if not isinstance(op, ControlOp):
|
| 393 |
+
if isinstance(op, (Assign, AssignMulti)):
|
| 394 |
+
if op.dest not in seen_registers:
|
| 395 |
+
values.append(op.dest)
|
| 396 |
+
seen_registers.add(op.dest)
|
| 397 |
+
elif op.is_void:
|
| 398 |
+
continue
|
| 399 |
+
else:
|
| 400 |
+
values.append(op)
|
| 401 |
+
|
| 402 |
+
return values
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
_ARG_KIND_TO_INSPECT: Final = {
|
| 406 |
+
ArgKind.ARG_POS: inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
| 407 |
+
ArgKind.ARG_OPT: inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
| 408 |
+
ArgKind.ARG_STAR: inspect.Parameter.VAR_POSITIONAL,
|
| 409 |
+
ArgKind.ARG_NAMED: inspect.Parameter.KEYWORD_ONLY,
|
| 410 |
+
ArgKind.ARG_STAR2: inspect.Parameter.VAR_KEYWORD,
|
| 411 |
+
ArgKind.ARG_NAMED_OPT: inspect.Parameter.KEYWORD_ONLY,
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
# Sentinel indicating a value that cannot be represented in a text signature.
|
| 415 |
+
_NOT_REPRESENTABLE = object()
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def get_text_signature(fn: FuncIR, *, bound: bool = False) -> str | None:
|
| 419 |
+
"""Return a text signature in CPython's internal doc format, or None
|
| 420 |
+
if the function's signature cannot be represented.
|
| 421 |
+
"""
|
| 422 |
+
parameters = []
|
| 423 |
+
mark_self = (fn.class_name is not None) and (fn.decl.kind != FUNC_STATICMETHOD) and not bound
|
| 424 |
+
sig = fn.decl.bound_sig if bound and fn.decl.bound_sig is not None else fn.decl.sig
|
| 425 |
+
# Pre-scan for end of positional-only parameters.
|
| 426 |
+
# This is needed to handle signatures like 'def foo(self, __x)', where mypy
|
| 427 |
+
# currently sees 'self' as being positional-or-keyword and '__x' as positional-only.
|
| 428 |
+
pos_only_idx = -1
|
| 429 |
+
for idx, arg in enumerate(sig.args):
|
| 430 |
+
if arg.pos_only and arg.kind in (ArgKind.ARG_POS, ArgKind.ARG_OPT):
|
| 431 |
+
pos_only_idx = idx
|
| 432 |
+
for idx, arg in enumerate(sig.args):
|
| 433 |
+
if arg.name.startswith(("__bitmap", "__mypyc")):
|
| 434 |
+
continue
|
| 435 |
+
kind = (
|
| 436 |
+
inspect.Parameter.POSITIONAL_ONLY
|
| 437 |
+
if idx <= pos_only_idx
|
| 438 |
+
else _ARG_KIND_TO_INSPECT[arg.kind]
|
| 439 |
+
)
|
| 440 |
+
default: object = inspect.Parameter.empty
|
| 441 |
+
if arg.optional:
|
| 442 |
+
default = _find_default_argument(arg.name, fn.blocks)
|
| 443 |
+
if default is _NOT_REPRESENTABLE:
|
| 444 |
+
# This default argument cannot be represented in a __text_signature__
|
| 445 |
+
return None
|
| 446 |
+
|
| 447 |
+
curr_param = inspect.Parameter(arg.name, kind, default=default)
|
| 448 |
+
parameters.append(curr_param)
|
| 449 |
+
if mark_self:
|
| 450 |
+
# Parameter.__init__/Parameter.replace do not accept $
|
| 451 |
+
curr_param._name = f"${arg.name}" # type: ignore[attr-defined]
|
| 452 |
+
mark_self = False
|
| 453 |
+
return f"{fn.name}{inspect.Signature(parameters)}"
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def _find_default_argument(name: str, blocks: list[BasicBlock]) -> object:
|
| 457 |
+
# Find assignment inserted by gen_arg_defaults. Assumed to be the first assignment.
|
| 458 |
+
for block in blocks:
|
| 459 |
+
for op in block.ops:
|
| 460 |
+
if isinstance(op, Assign) and op.dest.name == name:
|
| 461 |
+
return _extract_python_literal(op.src)
|
| 462 |
+
return _NOT_REPRESENTABLE
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def _extract_python_literal(value: Value) -> object:
|
| 466 |
+
if isinstance(value, Integer):
|
| 467 |
+
if is_none_rprimitive(value.type):
|
| 468 |
+
return None
|
| 469 |
+
val = value.numeric_value()
|
| 470 |
+
if is_bool_rprimitive(value.type):
|
| 471 |
+
return bool(val)
|
| 472 |
+
return val
|
| 473 |
+
elif isinstance(value, Float):
|
| 474 |
+
return value.value
|
| 475 |
+
elif isinstance(value, LoadLiteral):
|
| 476 |
+
return value.value
|
| 477 |
+
elif isinstance(value, Box):
|
| 478 |
+
return _extract_python_literal(value.src)
|
| 479 |
+
elif isinstance(value, TupleSet):
|
| 480 |
+
items = tuple(_extract_python_literal(item) for item in value.items)
|
| 481 |
+
if any(itm is _NOT_REPRESENTABLE for itm in items):
|
| 482 |
+
return _NOT_REPRESENTABLE
|
| 483 |
+
return items
|
| 484 |
+
return _NOT_REPRESENTABLE
|
micromamba_root/Lib/site-packages/mypyc/ir/module_ir.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/ir/module_ir.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Intermediate representation of modules."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from mypyc.common import JsonDict
|
| 6 |
+
from mypyc.ir.class_ir import ClassIR
|
| 7 |
+
from mypyc.ir.deps import Capsule, Dependency, SourceDep
|
| 8 |
+
from mypyc.ir.func_ir import FuncDecl, FuncIR
|
| 9 |
+
from mypyc.ir.ops import DeserMaps
|
| 10 |
+
from mypyc.ir.rtypes import RType, deserialize_type
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ModuleIR:
|
| 14 |
+
"""Intermediate representation of a module."""
|
| 15 |
+
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
fullname: str,
|
| 19 |
+
imports: list[str],
|
| 20 |
+
functions: list[FuncIR],
|
| 21 |
+
classes: list[ClassIR],
|
| 22 |
+
final_names: list[tuple[str, RType]],
|
| 23 |
+
type_var_names: list[str],
|
| 24 |
+
) -> None:
|
| 25 |
+
self.fullname = fullname
|
| 26 |
+
self.imports = imports.copy()
|
| 27 |
+
self.functions = functions
|
| 28 |
+
self.classes = classes
|
| 29 |
+
self.final_names = final_names
|
| 30 |
+
# Names of C statics used for Python 3.12 type variable objects.
|
| 31 |
+
# These are only visible in the module that defined them, so no need
|
| 32 |
+
# to serialize.
|
| 33 |
+
self.type_var_names = type_var_names
|
| 34 |
+
# Dependencies needed by the module (such as capsules or source files)
|
| 35 |
+
self.dependencies: set[Dependency] = set()
|
| 36 |
+
|
| 37 |
+
def serialize(self) -> JsonDict:
|
| 38 |
+
# Serialize dependencies as a list of dicts with type information
|
| 39 |
+
serialized_deps = []
|
| 40 |
+
for dep in sorted(self.dependencies, key=lambda d: (type(d).__name__, str(d))):
|
| 41 |
+
if isinstance(dep, Capsule):
|
| 42 |
+
serialized_deps.append({"type": "Capsule", "name": dep.name})
|
| 43 |
+
elif isinstance(dep, SourceDep):
|
| 44 |
+
serialized_deps.append({"type": "SourceDep", "path": dep.path})
|
| 45 |
+
|
| 46 |
+
return {
|
| 47 |
+
"fullname": self.fullname,
|
| 48 |
+
"imports": self.imports,
|
| 49 |
+
"functions": [f.serialize() for f in self.functions],
|
| 50 |
+
"classes": [c.serialize() for c in self.classes],
|
| 51 |
+
"final_names": [(k, t.serialize()) for k, t in self.final_names],
|
| 52 |
+
"dependencies": serialized_deps,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
@classmethod
|
| 56 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ModuleIR:
|
| 57 |
+
module = ModuleIR(
|
| 58 |
+
data["fullname"],
|
| 59 |
+
data["imports"],
|
| 60 |
+
[ctx.functions[FuncDecl.get_id_from_json(f)] for f in data["functions"]],
|
| 61 |
+
[ClassIR.deserialize(c, ctx) for c in data["classes"]],
|
| 62 |
+
[(k, deserialize_type(t, ctx)) for k, t in data["final_names"]],
|
| 63 |
+
[],
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Deserialize dependencies
|
| 67 |
+
deps: set[Dependency] = set()
|
| 68 |
+
for dep_dict in data["dependencies"]:
|
| 69 |
+
if dep_dict["type"] == "Capsule":
|
| 70 |
+
deps.add(Capsule(dep_dict["name"]))
|
| 71 |
+
elif dep_dict["type"] == "SourceDep":
|
| 72 |
+
deps.add(SourceDep(dep_dict["path"]))
|
| 73 |
+
module.dependencies = deps
|
| 74 |
+
|
| 75 |
+
return module
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def deserialize_modules(data: dict[str, JsonDict], ctx: DeserMaps) -> dict[str, ModuleIR]:
|
| 79 |
+
"""Deserialize a collection of modules.
|
| 80 |
+
|
| 81 |
+
The modules can contain dependencies on each other.
|
| 82 |
+
|
| 83 |
+
Arguments:
|
| 84 |
+
data: A dict containing the modules to deserialize.
|
| 85 |
+
ctx: The deserialization maps to use and to populate.
|
| 86 |
+
They are populated with information from the deserialized
|
| 87 |
+
modules and as a precondition must have been populated by
|
| 88 |
+
deserializing any dependencies of the modules being deserialized
|
| 89 |
+
(outside of dependencies between the modules themselves).
|
| 90 |
+
|
| 91 |
+
Returns a map containing the deserialized modules.
|
| 92 |
+
"""
|
| 93 |
+
for mod in data.values():
|
| 94 |
+
# First create ClassIRs for every class so that we can construct types and whatnot
|
| 95 |
+
for cls in mod["classes"]:
|
| 96 |
+
ir = ClassIR(cls["name"], cls["module_name"])
|
| 97 |
+
assert ir.fullname not in ctx.classes, "Class %s already in map" % ir.fullname
|
| 98 |
+
ctx.classes[ir.fullname] = ir
|
| 99 |
+
|
| 100 |
+
for mod in data.values():
|
| 101 |
+
# Then deserialize all of the functions so that methods are available
|
| 102 |
+
# to the class deserialization.
|
| 103 |
+
for method in mod["functions"]:
|
| 104 |
+
func = FuncIR.deserialize(method, ctx)
|
| 105 |
+
assert func.decl.id not in ctx.functions, (
|
| 106 |
+
"Method %s already in map" % func.decl.fullname
|
| 107 |
+
)
|
| 108 |
+
ctx.functions[func.decl.id] = func
|
| 109 |
+
|
| 110 |
+
return {k: ModuleIR.deserialize(v, ctx) for k, v in data.items()}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ModulesIRs should also always be an *OrderedDict*, but if we
|
| 114 |
+
# declared it that way we would need to put it in quotes everywhere...
|
| 115 |
+
ModuleIRs = dict[str, ModuleIR]
|
micromamba_root/Lib/site-packages/mypyc/ir/ops.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/ir/ops.py
ADDED
|
@@ -0,0 +1,2106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Low-level opcodes for compiler intermediate representation (IR).
|
| 2 |
+
|
| 3 |
+
Opcodes operate on abstract values (Value) in a register machine. Each
|
| 4 |
+
value has a type (RType). A value can hold various things, such as:
|
| 5 |
+
|
| 6 |
+
- local variables or temporaries (Register)
|
| 7 |
+
- intermediate values of expressions (RegisterOp subclasses)
|
| 8 |
+
- condition flags (true/false)
|
| 9 |
+
- literals (integer literals, True, False, etc.)
|
| 10 |
+
|
| 11 |
+
NOTE: As a convention, we don't create subclasses of concrete Value/Op
|
| 12 |
+
subclasses (e.g. you shouldn't define a subclass of Integer, which
|
| 13 |
+
is a concrete class).
|
| 14 |
+
|
| 15 |
+
If you want to introduce a variant of an existing class, you'd
|
| 16 |
+
typically add an attribute (e.g. a flag) to an existing concrete
|
| 17 |
+
class to enable the new behavior. Sometimes adding a new abstract
|
| 18 |
+
base class is also an option, or just creating a new subclass
|
| 19 |
+
without any inheritance relationship (some duplication of code
|
| 20 |
+
is preferred over introducing complex implementation inheritance).
|
| 21 |
+
|
| 22 |
+
This makes it possible to use isinstance(x, <concrete Value
|
| 23 |
+
subclass>) checks without worrying about potential subclasses.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
from abc import abstractmethod
|
| 29 |
+
from collections.abc import Sequence
|
| 30 |
+
from typing import TYPE_CHECKING, Final, Generic, NamedTuple, TypeVar, final
|
| 31 |
+
|
| 32 |
+
from mypy_extensions import trait
|
| 33 |
+
|
| 34 |
+
from mypyc.common import PROPSET_PREFIX
|
| 35 |
+
from mypyc.ir.deps import Dependency
|
| 36 |
+
from mypyc.ir.rtypes import (
|
| 37 |
+
RArray,
|
| 38 |
+
RInstance,
|
| 39 |
+
RStruct,
|
| 40 |
+
RTuple,
|
| 41 |
+
RType,
|
| 42 |
+
RUnion,
|
| 43 |
+
RVec,
|
| 44 |
+
RVoid,
|
| 45 |
+
bit_rprimitive,
|
| 46 |
+
bool_rprimitive,
|
| 47 |
+
cstring_rprimitive,
|
| 48 |
+
float_rprimitive,
|
| 49 |
+
int_rprimitive,
|
| 50 |
+
is_bool_or_bit_rprimitive,
|
| 51 |
+
is_fixed_width_rtype,
|
| 52 |
+
is_int_rprimitive,
|
| 53 |
+
is_none_rprimitive,
|
| 54 |
+
is_pointer_rprimitive,
|
| 55 |
+
is_short_int_rprimitive,
|
| 56 |
+
object_rprimitive,
|
| 57 |
+
pointer_rprimitive,
|
| 58 |
+
short_int_rprimitive,
|
| 59 |
+
void_rtype,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if TYPE_CHECKING:
|
| 63 |
+
from mypyc.codegen.literals import LiteralValue
|
| 64 |
+
from mypyc.ir.class_ir import ClassIR
|
| 65 |
+
from mypyc.ir.func_ir import FuncDecl, FuncIR
|
| 66 |
+
|
| 67 |
+
T = TypeVar("T")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@final
|
| 71 |
+
class BasicBlock:
|
| 72 |
+
"""IR basic block.
|
| 73 |
+
|
| 74 |
+
Contains a sequence of Ops and ends with a ControlOp (Goto,
|
| 75 |
+
Branch, Return or Unreachable). Only the last op can be a
|
| 76 |
+
ControlOp.
|
| 77 |
+
|
| 78 |
+
All generated Ops live in basic blocks. Basic blocks determine the
|
| 79 |
+
order of evaluation and control flow within a function. A basic
|
| 80 |
+
block is always associated with a single function/method (FuncIR).
|
| 81 |
+
|
| 82 |
+
When building the IR, ops that raise exceptions can be included in
|
| 83 |
+
the middle of a basic block, but the exceptions aren't checked.
|
| 84 |
+
Afterwards we perform a transform that inserts explicit checks for
|
| 85 |
+
all error conditions and splits basic blocks accordingly to preserve
|
| 86 |
+
the invariant that a jump, branch or return can only ever appear
|
| 87 |
+
as the final op in a block. Manually inserting error checking ops
|
| 88 |
+
would be boring and error-prone.
|
| 89 |
+
|
| 90 |
+
BasicBlocks have an error_handler attribute that determines where
|
| 91 |
+
to jump if an error occurs. If none is specified, an error will
|
| 92 |
+
propagate up out of the function. This is compiled away by the
|
| 93 |
+
`exceptions` module.
|
| 94 |
+
|
| 95 |
+
Block labels are used for pretty printing and emitting C code, and
|
| 96 |
+
get filled in by those passes.
|
| 97 |
+
|
| 98 |
+
Ops that may terminate the program aren't treated as exits.
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
def __init__(self, label: int = -1) -> None:
|
| 102 |
+
self.label = label
|
| 103 |
+
self.ops: list[Op] = []
|
| 104 |
+
self.error_handler: BasicBlock | None = None
|
| 105 |
+
self.referenced = False
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def terminated(self) -> bool:
|
| 109 |
+
"""Does the block end with a jump, branch or return?
|
| 110 |
+
|
| 111 |
+
This should always be true after the basic block has been fully built, but
|
| 112 |
+
this is false during construction.
|
| 113 |
+
"""
|
| 114 |
+
return bool(self.ops) and isinstance(self.ops[-1], ControlOp)
|
| 115 |
+
|
| 116 |
+
@property
|
| 117 |
+
def terminator(self) -> ControlOp:
|
| 118 |
+
"""The terminator operation of the block."""
|
| 119 |
+
assert bool(self.ops) and isinstance(self.ops[-1], ControlOp)
|
| 120 |
+
return self.ops[-1]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# Never generates an exception
|
| 124 |
+
ERR_NEVER: Final = 0
|
| 125 |
+
# Generates magic value (c_error_value) based on target RType on exception
|
| 126 |
+
ERR_MAGIC: Final = 1
|
| 127 |
+
# Generates false (bool) on exception
|
| 128 |
+
ERR_FALSE: Final = 2
|
| 129 |
+
# Always fails
|
| 130 |
+
ERR_ALWAYS: Final = 3
|
| 131 |
+
# Like ERR_MAGIC, but the magic return overlaps with a possible return value, and
|
| 132 |
+
# an extra PyErr_Occurred() check is also required
|
| 133 |
+
ERR_MAGIC_OVERLAPPING: Final = 4
|
| 134 |
+
|
| 135 |
+
# Hack: using this line number for an op will suppress it in tracebacks
|
| 136 |
+
NO_TRACEBACK_LINE_NO = -10000
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class Value:
|
| 140 |
+
"""Abstract base class for all IR values.
|
| 141 |
+
|
| 142 |
+
These include references to registers, literals, and all
|
| 143 |
+
operations (Ops), such as assignments, calls and branches.
|
| 144 |
+
|
| 145 |
+
Values are often used as inputs of Ops. Register can be used as an
|
| 146 |
+
assignment target.
|
| 147 |
+
|
| 148 |
+
A Value is part of the IR being compiled if it's included in a BasicBlock
|
| 149 |
+
that is reachable from a FuncIR (i.e., is part of a function).
|
| 150 |
+
|
| 151 |
+
See also: Op is a subclass of Value that is the base class of all
|
| 152 |
+
operations.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
# Source line number (-1 for no/unknown line)
|
| 156 |
+
line = -1
|
| 157 |
+
# Type of the value or the result of the operation
|
| 158 |
+
type: RType = void_rtype
|
| 159 |
+
is_borrowed = False
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def is_void(self) -> bool:
|
| 163 |
+
return isinstance(self.type, RVoid)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@final
|
| 167 |
+
class Register(Value):
|
| 168 |
+
"""A Register holds a value of a specific type, and it can be read and mutated.
|
| 169 |
+
|
| 170 |
+
A Register is always local to a function. Each local variable maps
|
| 171 |
+
to a Register, and they are also used for some (but not all)
|
| 172 |
+
temporary values.
|
| 173 |
+
|
| 174 |
+
Note that the term 'register' is overloaded and is sometimes used
|
| 175 |
+
to refer to arbitrary Values (for example, in RegisterOp).
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
def __init__(self, type: RType, name: str = "", is_arg: bool = False, line: int = -1) -> None:
|
| 179 |
+
self.type = type
|
| 180 |
+
self.name = name
|
| 181 |
+
self.is_arg = is_arg
|
| 182 |
+
self.is_borrowed = is_arg
|
| 183 |
+
self.line = line
|
| 184 |
+
|
| 185 |
+
@property
|
| 186 |
+
def is_void(self) -> bool:
|
| 187 |
+
return False
|
| 188 |
+
|
| 189 |
+
def __repr__(self) -> str:
|
| 190 |
+
return f"<Register {self.name!r} at {hex(id(self))}>"
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@final
|
| 194 |
+
class Integer(Value):
|
| 195 |
+
"""Short integer literal.
|
| 196 |
+
|
| 197 |
+
Integer literals are treated as constant values and are generally
|
| 198 |
+
not included in data flow analyses and such, unlike Register and
|
| 199 |
+
Op subclasses.
|
| 200 |
+
|
| 201 |
+
Integer can represent multiple types:
|
| 202 |
+
|
| 203 |
+
* Short tagged integers (short_int_primitive type; the tag bit is clear)
|
| 204 |
+
* Ordinary fixed-width integers (e.g., int32_rprimitive)
|
| 205 |
+
* Values of other unboxed primitive types that are represented as integers
|
| 206 |
+
(none_rprimitive, bool_rprimitive)
|
| 207 |
+
* Null pointers (value 0) of various types, including object_rprimitive
|
| 208 |
+
"""
|
| 209 |
+
|
| 210 |
+
def __init__(self, value: int, rtype: RType = short_int_rprimitive, line: int = -1) -> None:
|
| 211 |
+
if is_short_int_rprimitive(rtype) or is_int_rprimitive(rtype):
|
| 212 |
+
self.value = value * 2
|
| 213 |
+
else:
|
| 214 |
+
self.value = value
|
| 215 |
+
self.type = rtype
|
| 216 |
+
self.line = line
|
| 217 |
+
|
| 218 |
+
def numeric_value(self) -> int:
|
| 219 |
+
if is_short_int_rprimitive(self.type) or is_int_rprimitive(self.type):
|
| 220 |
+
return self.value // 2
|
| 221 |
+
return self.value
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
@final
|
| 225 |
+
class Float(Value):
|
| 226 |
+
"""Float literal.
|
| 227 |
+
|
| 228 |
+
Floating point literals are treated as constant values and are generally
|
| 229 |
+
not included in data flow analyses and such, unlike Register and
|
| 230 |
+
Op subclasses.
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
def __init__(self, value: float, line: int = -1) -> None:
|
| 234 |
+
self.value = value
|
| 235 |
+
self.type = float_rprimitive
|
| 236 |
+
self.line = line
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@final
|
| 240 |
+
class CString(Value):
|
| 241 |
+
"""C string literal (zero-terminated).
|
| 242 |
+
|
| 243 |
+
You can also include zero values in the value, but then you'll need to track
|
| 244 |
+
the length of the string separately.
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
def __init__(self, value: bytes, line: int = -1) -> None:
|
| 248 |
+
self.value = value
|
| 249 |
+
self.type = cstring_rprimitive
|
| 250 |
+
self.line = line
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@final
|
| 254 |
+
class Undef(Value):
|
| 255 |
+
"""An undefined value.
|
| 256 |
+
|
| 257 |
+
Use Undef() as the initial value followed by one or more SetElement
|
| 258 |
+
ops to initialize a struct. Pseudocode example:
|
| 259 |
+
|
| 260 |
+
r0 = set_element undef MyStruct, "field1", f1
|
| 261 |
+
r1 = set_element r0, "field2", f2
|
| 262 |
+
# r1 now has new struct value with two fields set
|
| 263 |
+
|
| 264 |
+
Warning: Always initialize undefined values before using them,
|
| 265 |
+
as otherwise the values are garbage. You shouldn't expect that
|
| 266 |
+
undefined values are zeroed, in particular.
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
def __init__(self, rtype: RType) -> None:
|
| 270 |
+
self.type = rtype
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class Op(Value):
|
| 274 |
+
"""Abstract base class for all IR operations.
|
| 275 |
+
|
| 276 |
+
Each operation must be stored in a BasicBlock (in 'ops') to be
|
| 277 |
+
active in the IR. This is different from non-Op values, including
|
| 278 |
+
Register and Integer, where a reference from an active Op is
|
| 279 |
+
sufficient to be considered active.
|
| 280 |
+
|
| 281 |
+
In well-formed IR an active Op has no references to inactive ops
|
| 282 |
+
or ops used in another function.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
def __init__(self, line: int) -> None:
|
| 286 |
+
self.line = line
|
| 287 |
+
|
| 288 |
+
def can_raise(self) -> bool:
|
| 289 |
+
# Override this is if Op may raise an exception. Note that currently the fact that
|
| 290 |
+
# only RegisterOps may raise an exception in hard coded in some places.
|
| 291 |
+
return False
|
| 292 |
+
|
| 293 |
+
@abstractmethod
|
| 294 |
+
def sources(self) -> list[Value]:
|
| 295 |
+
"""All the values the op may read."""
|
| 296 |
+
|
| 297 |
+
@abstractmethod
|
| 298 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 299 |
+
"""Rewrite the sources of an op"""
|
| 300 |
+
|
| 301 |
+
def stolen(self) -> list[Value]:
|
| 302 |
+
"""Return arguments that have a reference count stolen by this op"""
|
| 303 |
+
return []
|
| 304 |
+
|
| 305 |
+
def unique_sources(self) -> list[Value]:
|
| 306 |
+
result: list[Value] = []
|
| 307 |
+
for reg in self.sources():
|
| 308 |
+
if reg not in result:
|
| 309 |
+
result.append(reg)
|
| 310 |
+
return result
|
| 311 |
+
|
| 312 |
+
@abstractmethod
|
| 313 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 314 |
+
pass
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class BaseAssign(Op):
|
| 318 |
+
"""Abstract base class for ops that assign to a register."""
|
| 319 |
+
|
| 320 |
+
def __init__(self, dest: Register, line: int = -1) -> None:
|
| 321 |
+
super().__init__(line)
|
| 322 |
+
self.dest = dest
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
@final
|
| 326 |
+
class Assign(BaseAssign):
|
| 327 |
+
"""Assign a value to a Register (dest = src)."""
|
| 328 |
+
|
| 329 |
+
error_kind = ERR_NEVER
|
| 330 |
+
|
| 331 |
+
def __init__(self, dest: Register, src: Value, line: int = -1) -> None:
|
| 332 |
+
super().__init__(dest, line)
|
| 333 |
+
self.src = src
|
| 334 |
+
|
| 335 |
+
def sources(self) -> list[Value]:
|
| 336 |
+
return [self.src]
|
| 337 |
+
|
| 338 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 339 |
+
(self.src,) = new
|
| 340 |
+
|
| 341 |
+
def stolen(self) -> list[Value]:
|
| 342 |
+
if not self.dest.type.is_refcounted:
|
| 343 |
+
return []
|
| 344 |
+
return [self.src]
|
| 345 |
+
|
| 346 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 347 |
+
return visitor.visit_assign(self)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
@final
|
| 351 |
+
class AssignMulti(BaseAssign):
|
| 352 |
+
"""Assign multiple values to a Register (dest = src1, src2, ...).
|
| 353 |
+
|
| 354 |
+
This is used to initialize RArray values. It's provided to avoid
|
| 355 |
+
very verbose IR for common vectorcall operations.
|
| 356 |
+
|
| 357 |
+
Note that this interacts atypically with reference counting. We
|
| 358 |
+
assume that each RArray register is initialized exactly once
|
| 359 |
+
with this op.
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
error_kind = ERR_NEVER
|
| 363 |
+
|
| 364 |
+
def __init__(self, dest: Register, src: list[Value], line: int = -1) -> None:
|
| 365 |
+
super().__init__(dest, line)
|
| 366 |
+
assert src
|
| 367 |
+
assert isinstance(dest.type, RArray)
|
| 368 |
+
assert dest.type.length == len(src)
|
| 369 |
+
self.src = src
|
| 370 |
+
|
| 371 |
+
def sources(self) -> list[Value]:
|
| 372 |
+
return self.src.copy()
|
| 373 |
+
|
| 374 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 375 |
+
self.src = new[:]
|
| 376 |
+
|
| 377 |
+
def stolen(self) -> list[Value]:
|
| 378 |
+
return []
|
| 379 |
+
|
| 380 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 381 |
+
return visitor.visit_assign_multi(self)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class ControlOp(Op):
|
| 385 |
+
"""Abstract base class for control flow operations."""
|
| 386 |
+
|
| 387 |
+
def targets(self) -> Sequence[BasicBlock]:
|
| 388 |
+
"""Get all basic block targets of the control operation."""
|
| 389 |
+
return ()
|
| 390 |
+
|
| 391 |
+
def set_target(self, i: int, new: BasicBlock) -> None:
|
| 392 |
+
"""Update a basic block target."""
|
| 393 |
+
raise AssertionError(f"Invalid set_target({self}, {i})")
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
@final
|
| 397 |
+
class Goto(ControlOp):
|
| 398 |
+
"""Unconditional jump."""
|
| 399 |
+
|
| 400 |
+
error_kind = ERR_NEVER
|
| 401 |
+
|
| 402 |
+
def __init__(self, label: BasicBlock, line: int = -1) -> None:
|
| 403 |
+
super().__init__(line)
|
| 404 |
+
self.label = label
|
| 405 |
+
|
| 406 |
+
def targets(self) -> Sequence[BasicBlock]:
|
| 407 |
+
return (self.label,)
|
| 408 |
+
|
| 409 |
+
def set_target(self, i: int, new: BasicBlock) -> None:
|
| 410 |
+
assert i == 0
|
| 411 |
+
self.label = new
|
| 412 |
+
|
| 413 |
+
def __repr__(self) -> str:
|
| 414 |
+
return "<Goto %s>" % self.label.label
|
| 415 |
+
|
| 416 |
+
def sources(self) -> list[Value]:
|
| 417 |
+
return []
|
| 418 |
+
|
| 419 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 420 |
+
assert not new
|
| 421 |
+
|
| 422 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 423 |
+
return visitor.visit_goto(self)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
@final
|
| 427 |
+
class Branch(ControlOp):
|
| 428 |
+
"""Branch based on a value.
|
| 429 |
+
|
| 430 |
+
If op is BOOL, branch based on a bit/bool value:
|
| 431 |
+
if [not] r1 goto L1 else goto L2
|
| 432 |
+
|
| 433 |
+
If op is IS_ERROR, branch based on whether there is an error value:
|
| 434 |
+
if [not] is_error(r1) goto L1 else goto L2
|
| 435 |
+
"""
|
| 436 |
+
|
| 437 |
+
# Branch ops never raise an exception.
|
| 438 |
+
error_kind = ERR_NEVER
|
| 439 |
+
|
| 440 |
+
BOOL: Final = 100
|
| 441 |
+
IS_ERROR: Final = 101
|
| 442 |
+
|
| 443 |
+
def __init__(
|
| 444 |
+
self,
|
| 445 |
+
value: Value,
|
| 446 |
+
true_label: BasicBlock,
|
| 447 |
+
false_label: BasicBlock,
|
| 448 |
+
op: int,
|
| 449 |
+
line: int = -1,
|
| 450 |
+
*,
|
| 451 |
+
rare: bool = False,
|
| 452 |
+
) -> None:
|
| 453 |
+
super().__init__(line)
|
| 454 |
+
# Target value being checked
|
| 455 |
+
self.value = value
|
| 456 |
+
# Branch here if the condition is true
|
| 457 |
+
self.true = true_label
|
| 458 |
+
# Branch here if the condition is false
|
| 459 |
+
self.false = false_label
|
| 460 |
+
# Branch.BOOL (boolean check) or Branch.IS_ERROR (error value check)
|
| 461 |
+
self.op = op
|
| 462 |
+
# If True, the condition is negated
|
| 463 |
+
self.negated = False
|
| 464 |
+
# If not None, the true label should generate a traceback entry (func name, line number)
|
| 465 |
+
self.traceback_entry: tuple[str, int] | None = None
|
| 466 |
+
# If True, we expect to usually take the false branch (for optimization purposes);
|
| 467 |
+
# this is implicitly treated as true if there is a traceback entry
|
| 468 |
+
self.rare = rare
|
| 469 |
+
|
| 470 |
+
def targets(self) -> Sequence[BasicBlock]:
|
| 471 |
+
return (self.true, self.false)
|
| 472 |
+
|
| 473 |
+
def set_target(self, i: int, new: BasicBlock) -> None:
|
| 474 |
+
assert i == 0 or i == 1
|
| 475 |
+
if i == 0:
|
| 476 |
+
self.true = new
|
| 477 |
+
else:
|
| 478 |
+
self.false = new
|
| 479 |
+
|
| 480 |
+
def sources(self) -> list[Value]:
|
| 481 |
+
return [self.value]
|
| 482 |
+
|
| 483 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 484 |
+
(self.value,) = new
|
| 485 |
+
|
| 486 |
+
def invert(self) -> None:
|
| 487 |
+
self.negated = not self.negated
|
| 488 |
+
|
| 489 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 490 |
+
return visitor.visit_branch(self)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
@final
|
| 494 |
+
class Return(ControlOp):
|
| 495 |
+
"""Return a value from a function."""
|
| 496 |
+
|
| 497 |
+
error_kind = ERR_NEVER
|
| 498 |
+
|
| 499 |
+
def __init__(
|
| 500 |
+
self, value: Value, line: int = -1, *, yield_target: BasicBlock | None = None
|
| 501 |
+
) -> None:
|
| 502 |
+
super().__init__(line)
|
| 503 |
+
self.value = value
|
| 504 |
+
# If this return is created by a yield, keep track of the next
|
| 505 |
+
# basic block. This doesn't affect the code we generate but
|
| 506 |
+
# can feed into analysis that need to understand the
|
| 507 |
+
# *original* CFG.
|
| 508 |
+
self.yield_target = yield_target
|
| 509 |
+
|
| 510 |
+
def sources(self) -> list[Value]:
|
| 511 |
+
return [self.value]
|
| 512 |
+
|
| 513 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 514 |
+
(self.value,) = new
|
| 515 |
+
|
| 516 |
+
def stolen(self) -> list[Value]:
|
| 517 |
+
return [self.value]
|
| 518 |
+
|
| 519 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 520 |
+
return visitor.visit_return(self)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@final
|
| 524 |
+
class Unreachable(ControlOp):
|
| 525 |
+
"""Mark the end of basic block as unreachable.
|
| 526 |
+
|
| 527 |
+
This is sometimes necessary when the end of a basic block is never
|
| 528 |
+
reached. This can also be explicitly added to the end of non-None
|
| 529 |
+
returning functions (in None-returning function we can just return
|
| 530 |
+
None).
|
| 531 |
+
|
| 532 |
+
Mypy statically guarantees that the end of the function is not
|
| 533 |
+
unreachable if there is not a return statement.
|
| 534 |
+
|
| 535 |
+
This prevents the block formatter from being confused due to lack
|
| 536 |
+
of a leave and also leaves a nifty note in the IR. It is not
|
| 537 |
+
generally processed by visitors.
|
| 538 |
+
"""
|
| 539 |
+
|
| 540 |
+
error_kind = ERR_NEVER
|
| 541 |
+
|
| 542 |
+
def __init__(self, line: int = -1) -> None:
|
| 543 |
+
super().__init__(line)
|
| 544 |
+
|
| 545 |
+
def sources(self) -> list[Value]:
|
| 546 |
+
return []
|
| 547 |
+
|
| 548 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 549 |
+
assert not new
|
| 550 |
+
|
| 551 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 552 |
+
return visitor.visit_unreachable(self)
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
class RegisterOp(Op):
|
| 556 |
+
"""Abstract base class for operations that can be written as r1 = f(r2, ..., rn).
|
| 557 |
+
|
| 558 |
+
Takes some values, performs an operation, and generates an output
|
| 559 |
+
(unless the 'type' attribute is void_rtype, which is the default).
|
| 560 |
+
Other ops can refer to the result of the Op by referring to the Op
|
| 561 |
+
instance. This doesn't do any explicit control flow, but can raise an
|
| 562 |
+
error.
|
| 563 |
+
|
| 564 |
+
Note that the operands can be arbitrary Values, not just Register
|
| 565 |
+
instances, even though the naming may suggest otherwise.
|
| 566 |
+
"""
|
| 567 |
+
|
| 568 |
+
error_kind = -1 # Can this raise exception and how is it signalled; one of ERR_*
|
| 569 |
+
|
| 570 |
+
_type: RType | None = None
|
| 571 |
+
|
| 572 |
+
def __init__(self, line: int) -> None:
|
| 573 |
+
super().__init__(line)
|
| 574 |
+
assert self.error_kind != -1, "error_kind not defined"
|
| 575 |
+
|
| 576 |
+
def can_raise(self) -> bool:
|
| 577 |
+
return self.error_kind != ERR_NEVER
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
@final
|
| 581 |
+
class IncRef(RegisterOp):
|
| 582 |
+
"""Increase reference count (inc_ref src)."""
|
| 583 |
+
|
| 584 |
+
error_kind = ERR_NEVER
|
| 585 |
+
|
| 586 |
+
def __init__(self, src: Value, line: int = -1) -> None:
|
| 587 |
+
assert src.type.is_refcounted
|
| 588 |
+
super().__init__(line)
|
| 589 |
+
self.src = src
|
| 590 |
+
|
| 591 |
+
def sources(self) -> list[Value]:
|
| 592 |
+
return [self.src]
|
| 593 |
+
|
| 594 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 595 |
+
(self.src,) = new
|
| 596 |
+
|
| 597 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 598 |
+
return visitor.visit_inc_ref(self)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
@final
|
| 602 |
+
class DecRef(RegisterOp):
|
| 603 |
+
"""Decrease reference count and free object if zero (dec_ref src).
|
| 604 |
+
|
| 605 |
+
The is_xdec flag says to use an XDECREF, which checks if the
|
| 606 |
+
pointer is NULL first.
|
| 607 |
+
"""
|
| 608 |
+
|
| 609 |
+
error_kind = ERR_NEVER
|
| 610 |
+
|
| 611 |
+
def __init__(self, src: Value, is_xdec: bool = False, line: int = -1) -> None:
|
| 612 |
+
assert src.type.is_refcounted
|
| 613 |
+
super().__init__(line)
|
| 614 |
+
self.src = src
|
| 615 |
+
self.is_xdec = is_xdec
|
| 616 |
+
|
| 617 |
+
def __repr__(self) -> str:
|
| 618 |
+
return "<{}DecRef {!r}>".format("X" if self.is_xdec else "", self.src)
|
| 619 |
+
|
| 620 |
+
def sources(self) -> list[Value]:
|
| 621 |
+
return [self.src]
|
| 622 |
+
|
| 623 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 624 |
+
(self.src,) = new
|
| 625 |
+
|
| 626 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 627 |
+
return visitor.visit_dec_ref(self)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
@final
|
| 631 |
+
class Call(RegisterOp):
|
| 632 |
+
"""Native call f(arg, ...).
|
| 633 |
+
|
| 634 |
+
The call target can be a module-level function or a class.
|
| 635 |
+
"""
|
| 636 |
+
|
| 637 |
+
def __init__(self, fn: FuncDecl, args: Sequence[Value], line: int) -> None:
|
| 638 |
+
self.fn = fn
|
| 639 |
+
self.args = list(args)
|
| 640 |
+
assert len(self.args) == len(fn.sig.args)
|
| 641 |
+
self.type = fn.sig.ret_type
|
| 642 |
+
ret_type = fn.sig.ret_type
|
| 643 |
+
if not ret_type.error_overlap:
|
| 644 |
+
self.error_kind = ERR_MAGIC
|
| 645 |
+
else:
|
| 646 |
+
self.error_kind = ERR_MAGIC_OVERLAPPING
|
| 647 |
+
super().__init__(line)
|
| 648 |
+
|
| 649 |
+
def sources(self) -> list[Value]:
|
| 650 |
+
return list(self.args.copy())
|
| 651 |
+
|
| 652 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 653 |
+
self.args = new[:]
|
| 654 |
+
|
| 655 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 656 |
+
return visitor.visit_call(self)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
@final
|
| 660 |
+
class MethodCall(RegisterOp):
|
| 661 |
+
"""Native method call obj.method(arg, ...)"""
|
| 662 |
+
|
| 663 |
+
def __init__(self, obj: Value, method: str, args: list[Value], line: int = -1) -> None:
|
| 664 |
+
self.obj = obj
|
| 665 |
+
self.method = method
|
| 666 |
+
self.args = args
|
| 667 |
+
assert isinstance(obj.type, RInstance), "Methods can only be called on instances"
|
| 668 |
+
self.receiver_type = obj.type
|
| 669 |
+
method_ir = self.receiver_type.class_ir.method_sig(method)
|
| 670 |
+
assert method_ir is not None, "{} doesn't have method {}".format(
|
| 671 |
+
self.receiver_type.name, method
|
| 672 |
+
)
|
| 673 |
+
ret_type = method_ir.ret_type
|
| 674 |
+
self.type = ret_type
|
| 675 |
+
if not ret_type.error_overlap:
|
| 676 |
+
self.error_kind = ERR_MAGIC
|
| 677 |
+
else:
|
| 678 |
+
self.error_kind = ERR_MAGIC_OVERLAPPING
|
| 679 |
+
super().__init__(line)
|
| 680 |
+
|
| 681 |
+
def sources(self) -> list[Value]:
|
| 682 |
+
return self.args.copy() + [self.obj]
|
| 683 |
+
|
| 684 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 685 |
+
*self.args, self.obj = new
|
| 686 |
+
|
| 687 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 688 |
+
return visitor.visit_method_call(self)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
@final
|
| 692 |
+
class PrimitiveDescription:
|
| 693 |
+
"""Description of a primitive op.
|
| 694 |
+
|
| 695 |
+
Primitives get lowered into lower-level ops before code generation.
|
| 696 |
+
|
| 697 |
+
If c_function_name is provided, a primitive will be lowered into a CallC op.
|
| 698 |
+
Otherwise, custom logic will need to be implemented to transform the
|
| 699 |
+
primitive into lower-level ops.
|
| 700 |
+
"""
|
| 701 |
+
|
| 702 |
+
def __init__(
|
| 703 |
+
self,
|
| 704 |
+
name: str,
|
| 705 |
+
arg_types: list[RType],
|
| 706 |
+
return_type: RType, # TODO: What about generic?
|
| 707 |
+
var_arg_type: RType | None,
|
| 708 |
+
truncated_type: RType | None,
|
| 709 |
+
c_function_name: str | None,
|
| 710 |
+
error_kind: int,
|
| 711 |
+
steals: StealsDescription,
|
| 712 |
+
is_borrowed: bool,
|
| 713 |
+
ordering: list[int] | None,
|
| 714 |
+
extra_int_constants: list[tuple[int, RType]],
|
| 715 |
+
priority: int,
|
| 716 |
+
is_pure: bool,
|
| 717 |
+
experimental: bool,
|
| 718 |
+
dependencies: list[Dependency] | None,
|
| 719 |
+
) -> None:
|
| 720 |
+
# Each primitive much have a distinct name, but otherwise they are arbitrary.
|
| 721 |
+
self.name: Final = name
|
| 722 |
+
self.arg_types: Final = arg_types
|
| 723 |
+
self.return_type: Final = return_type
|
| 724 |
+
self.var_arg_type: Final = var_arg_type
|
| 725 |
+
self.truncated_type: Final = truncated_type
|
| 726 |
+
# If non-None, this will map to a call of a C helper function; if None,
|
| 727 |
+
# there must be a custom handler function that gets invoked during the lowering
|
| 728 |
+
# pass to generate low-level IR for the primitive (in the mypyc.lower package)
|
| 729 |
+
self.c_function_name: Final = c_function_name
|
| 730 |
+
self.error_kind: Final = error_kind
|
| 731 |
+
self.steals: Final = steals
|
| 732 |
+
self.is_borrowed: Final = is_borrowed
|
| 733 |
+
self.ordering: Final = ordering
|
| 734 |
+
self.extra_int_constants: Final = extra_int_constants
|
| 735 |
+
self.priority: Final = priority
|
| 736 |
+
# Pure primitives have no side effects, take immutable arguments, and
|
| 737 |
+
# never fail. They support additional optimizations.
|
| 738 |
+
self.is_pure: Final = is_pure
|
| 739 |
+
if is_pure:
|
| 740 |
+
assert error_kind == ERR_NEVER
|
| 741 |
+
# Experimental primitives are not used unless mypyc experimental features are
|
| 742 |
+
# explicitly enabled
|
| 743 |
+
self.experimental = experimental
|
| 744 |
+
# Dependencies for the primitive, such as a capsule that needs to imported
|
| 745 |
+
# and configured to call the primitive.
|
| 746 |
+
self.dependencies = dependencies
|
| 747 |
+
# Native integer types such as u8 can cause ambiguity in primitive
|
| 748 |
+
# matching, since these are assignable to plain int *and* vice versa.
|
| 749 |
+
# If this flag is set, the primitive has native integer types and must
|
| 750 |
+
# be matched using more complex rules.
|
| 751 |
+
self.is_ambiguous = any(has_fixed_width_int(t) for t in arg_types)
|
| 752 |
+
|
| 753 |
+
def __repr__(self) -> str:
|
| 754 |
+
return f"<PrimitiveDescription {self.name!r}: {self.arg_types}>"
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def has_fixed_width_int(t: RType) -> bool:
|
| 758 |
+
if isinstance(t, RTuple):
|
| 759 |
+
return any(has_fixed_width_int(t) for t in t.types)
|
| 760 |
+
elif isinstance(t, RUnion):
|
| 761 |
+
return any(has_fixed_width_int(t) for t in t.items)
|
| 762 |
+
return is_fixed_width_rtype(t)
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
@final
|
| 766 |
+
class PrimitiveOp(RegisterOp):
|
| 767 |
+
"""A higher-level primitive operation.
|
| 768 |
+
|
| 769 |
+
Some of these have special compiler support. These will be lowered
|
| 770 |
+
(transformed) into lower-level IR ops before code generation, and after
|
| 771 |
+
reference counting op insertion. Others will be transformed into CallC
|
| 772 |
+
ops.
|
| 773 |
+
|
| 774 |
+
Tagged integer equality is a typical primitive op with non-trivial
|
| 775 |
+
lowering. It gets transformed into a tag check, followed by different
|
| 776 |
+
code paths for short and long representations.
|
| 777 |
+
"""
|
| 778 |
+
|
| 779 |
+
def __init__(self, args: list[Value], desc: PrimitiveDescription, line: int = -1) -> None:
|
| 780 |
+
self.error_kind = desc.error_kind
|
| 781 |
+
super().__init__(line)
|
| 782 |
+
self.args = args
|
| 783 |
+
self.type = desc.return_type
|
| 784 |
+
self.desc = desc
|
| 785 |
+
|
| 786 |
+
def sources(self) -> list[Value]:
|
| 787 |
+
return self.args
|
| 788 |
+
|
| 789 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 790 |
+
self.args = new[:]
|
| 791 |
+
|
| 792 |
+
def stolen(self) -> list[Value]:
|
| 793 |
+
steals = self.desc.steals
|
| 794 |
+
if isinstance(steals, list):
|
| 795 |
+
assert len(steals) == len(self.args)
|
| 796 |
+
return [arg for arg, steal in zip(self.args, steals) if steal]
|
| 797 |
+
else:
|
| 798 |
+
return [] if not steals else self.sources()
|
| 799 |
+
|
| 800 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 801 |
+
return visitor.visit_primitive_op(self)
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
@final
|
| 805 |
+
class LoadErrorValue(RegisterOp):
|
| 806 |
+
"""Load an error value.
|
| 807 |
+
|
| 808 |
+
Each type has one reserved value that signals an error (exception). This
|
| 809 |
+
loads the error value for a specific type.
|
| 810 |
+
"""
|
| 811 |
+
|
| 812 |
+
error_kind = ERR_NEVER
|
| 813 |
+
|
| 814 |
+
def __init__(
|
| 815 |
+
self, rtype: RType, line: int = -1, is_borrowed: bool = False, undefines: bool = False
|
| 816 |
+
) -> None:
|
| 817 |
+
super().__init__(line)
|
| 818 |
+
self.type = rtype
|
| 819 |
+
self.is_borrowed = is_borrowed
|
| 820 |
+
# Undefines is true if this should viewed by the definedness
|
| 821 |
+
# analysis pass as making the register it is assigned to
|
| 822 |
+
# undefined (and thus checks should be added on uses).
|
| 823 |
+
self.undefines = undefines
|
| 824 |
+
|
| 825 |
+
def sources(self) -> list[Value]:
|
| 826 |
+
return []
|
| 827 |
+
|
| 828 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 829 |
+
assert not new
|
| 830 |
+
|
| 831 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 832 |
+
return visitor.visit_load_error_value(self)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
@final
|
| 836 |
+
class LoadLiteral(RegisterOp):
|
| 837 |
+
"""Load a Python literal object (dest = 'foo' / b'foo' / ...).
|
| 838 |
+
|
| 839 |
+
This is used to load a static PyObject * value corresponding to
|
| 840 |
+
a literal of one of the supported types.
|
| 841 |
+
|
| 842 |
+
Tuple / frozenset literals must contain only valid literal values as items.
|
| 843 |
+
|
| 844 |
+
NOTE: You can use this to load boxed (Python) int objects. Use
|
| 845 |
+
Integer to load unboxed, tagged integers or fixed-width,
|
| 846 |
+
low-level integers.
|
| 847 |
+
|
| 848 |
+
For int literals, both int_rprimitive (CPyTagged) and
|
| 849 |
+
object_primitive (PyObject *) are supported as rtype. However,
|
| 850 |
+
when using int_rprimitive, the value must *not* be small enough
|
| 851 |
+
to fit in an unboxed integer.
|
| 852 |
+
"""
|
| 853 |
+
|
| 854 |
+
error_kind = ERR_NEVER
|
| 855 |
+
is_borrowed = True
|
| 856 |
+
|
| 857 |
+
def __init__(self, value: LiteralValue, rtype: RType, line: int = -1) -> None:
|
| 858 |
+
super().__init__(line)
|
| 859 |
+
self.value = value
|
| 860 |
+
self.type = rtype
|
| 861 |
+
|
| 862 |
+
def sources(self) -> list[Value]:
|
| 863 |
+
return []
|
| 864 |
+
|
| 865 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 866 |
+
assert not new
|
| 867 |
+
|
| 868 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 869 |
+
return visitor.visit_load_literal(self)
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
@final
|
| 873 |
+
class GetAttr(RegisterOp):
|
| 874 |
+
"""obj.attr (for a native object)"""
|
| 875 |
+
|
| 876 |
+
error_kind = ERR_MAGIC
|
| 877 |
+
|
| 878 |
+
def __init__(
|
| 879 |
+
self,
|
| 880 |
+
obj: Value,
|
| 881 |
+
attr: str,
|
| 882 |
+
line: int,
|
| 883 |
+
*,
|
| 884 |
+
borrow: bool = False,
|
| 885 |
+
allow_error_value: bool = False,
|
| 886 |
+
) -> None:
|
| 887 |
+
super().__init__(line)
|
| 888 |
+
self.obj = obj
|
| 889 |
+
self.attr = attr
|
| 890 |
+
self.allow_error_value = allow_error_value
|
| 891 |
+
assert isinstance(obj.type, RInstance), "Attribute access not supported: %s" % obj.type
|
| 892 |
+
self.class_type = obj.type
|
| 893 |
+
attr_type = obj.type.attr_type(attr)
|
| 894 |
+
self.type = attr_type
|
| 895 |
+
if allow_error_value:
|
| 896 |
+
self.error_kind = ERR_NEVER
|
| 897 |
+
elif attr_type.error_overlap:
|
| 898 |
+
self.error_kind = ERR_MAGIC_OVERLAPPING
|
| 899 |
+
self.is_borrowed = borrow and attr_type.is_refcounted
|
| 900 |
+
|
| 901 |
+
def sources(self) -> list[Value]:
|
| 902 |
+
return [self.obj]
|
| 903 |
+
|
| 904 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 905 |
+
(self.obj,) = new
|
| 906 |
+
|
| 907 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 908 |
+
return visitor.visit_get_attr(self)
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
@final
|
| 912 |
+
class SetAttr(RegisterOp):
|
| 913 |
+
"""obj.attr = src (for a native object)"""
|
| 914 |
+
|
| 915 |
+
error_kind = ERR_FALSE
|
| 916 |
+
|
| 917 |
+
def __init__(self, obj: Value, attr: str, src: Value, line: int) -> None:
|
| 918 |
+
super().__init__(line)
|
| 919 |
+
self.obj = obj
|
| 920 |
+
self.attr = attr
|
| 921 |
+
self.src = src
|
| 922 |
+
assert isinstance(obj.type, RInstance), "Attribute access not supported: %s" % obj.type
|
| 923 |
+
self.class_type = obj.type
|
| 924 |
+
self.type = bool_rprimitive
|
| 925 |
+
# If True, we can safely assume that the attribute is previously undefined
|
| 926 |
+
# and we don't use a setter
|
| 927 |
+
self.is_init = False
|
| 928 |
+
|
| 929 |
+
cl = self.class_type.class_ir
|
| 930 |
+
is_propset = False
|
| 931 |
+
for ir in cl.mro:
|
| 932 |
+
propset = ir.method_decls.get(PROPSET_PREFIX + attr)
|
| 933 |
+
if propset is not None:
|
| 934 |
+
is_propset = not propset.implicit
|
| 935 |
+
break
|
| 936 |
+
# If True, this op represents calling a property setter.
|
| 937 |
+
self.is_propset = is_propset
|
| 938 |
+
|
| 939 |
+
def mark_as_initializer(self) -> None:
|
| 940 |
+
self.is_init = True
|
| 941 |
+
self.error_kind = ERR_NEVER
|
| 942 |
+
self.type = void_rtype
|
| 943 |
+
|
| 944 |
+
def sources(self) -> list[Value]:
|
| 945 |
+
return [self.obj, self.src]
|
| 946 |
+
|
| 947 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 948 |
+
self.obj, self.src = new
|
| 949 |
+
|
| 950 |
+
def stolen(self) -> list[Value]:
|
| 951 |
+
# The property setter method increfs the passed value so don't treat it as a steal
|
| 952 |
+
# to avoid leaking.
|
| 953 |
+
if self.is_propset:
|
| 954 |
+
return []
|
| 955 |
+
return [self.src]
|
| 956 |
+
|
| 957 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 958 |
+
return visitor.visit_set_attr(self)
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
# Default name space for statics, variables
|
| 962 |
+
NAMESPACE_STATIC: Final = "static"
|
| 963 |
+
|
| 964 |
+
# Static namespace for pointers to native type objects
|
| 965 |
+
NAMESPACE_TYPE: Final = "type"
|
| 966 |
+
|
| 967 |
+
# Namespace for modules
|
| 968 |
+
NAMESPACE_MODULE: Final = "module"
|
| 969 |
+
|
| 970 |
+
# Namespace for Python 3.12 type variable objects (implicitly created TypeVar instances, etc.)
|
| 971 |
+
NAMESPACE_TYPE_VAR: Final = "typevar"
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
@final
|
| 975 |
+
class LoadStatic(RegisterOp):
|
| 976 |
+
"""Load a static name (name :: static).
|
| 977 |
+
|
| 978 |
+
Load a C static variable/pointer. The namespace for statics is shared
|
| 979 |
+
for the entire compilation group. You can optionally provide a module
|
| 980 |
+
name and a sub-namespace identifier for additional namespacing to avoid
|
| 981 |
+
name conflicts. The static namespace does not overlap with other C names,
|
| 982 |
+
since the final C name will get a prefix, so conflicts only must be
|
| 983 |
+
avoided with other statics.
|
| 984 |
+
"""
|
| 985 |
+
|
| 986 |
+
error_kind = ERR_NEVER
|
| 987 |
+
is_borrowed = True
|
| 988 |
+
|
| 989 |
+
def __init__(
|
| 990 |
+
self,
|
| 991 |
+
type: RType,
|
| 992 |
+
identifier: str,
|
| 993 |
+
module_name: str | None = None,
|
| 994 |
+
namespace: str = NAMESPACE_STATIC,
|
| 995 |
+
line: int = -1,
|
| 996 |
+
ann: object = None,
|
| 997 |
+
) -> None:
|
| 998 |
+
super().__init__(line)
|
| 999 |
+
self.identifier = identifier
|
| 1000 |
+
self.module_name = module_name
|
| 1001 |
+
self.namespace = namespace
|
| 1002 |
+
self.type = type
|
| 1003 |
+
self.ann = ann # An object to pretty print with the load
|
| 1004 |
+
|
| 1005 |
+
def sources(self) -> list[Value]:
|
| 1006 |
+
return []
|
| 1007 |
+
|
| 1008 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1009 |
+
assert not new
|
| 1010 |
+
|
| 1011 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1012 |
+
return visitor.visit_load_static(self)
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
@final
|
| 1016 |
+
class InitStatic(RegisterOp):
|
| 1017 |
+
"""static = value :: static
|
| 1018 |
+
|
| 1019 |
+
Initialize a C static variable/pointer. See everything in LoadStatic.
|
| 1020 |
+
"""
|
| 1021 |
+
|
| 1022 |
+
error_kind = ERR_NEVER
|
| 1023 |
+
|
| 1024 |
+
def __init__(
|
| 1025 |
+
self,
|
| 1026 |
+
value: Value,
|
| 1027 |
+
identifier: str,
|
| 1028 |
+
module_name: str | None = None,
|
| 1029 |
+
namespace: str = NAMESPACE_STATIC,
|
| 1030 |
+
line: int = -1,
|
| 1031 |
+
) -> None:
|
| 1032 |
+
super().__init__(line)
|
| 1033 |
+
self.identifier = identifier
|
| 1034 |
+
self.module_name = module_name
|
| 1035 |
+
self.namespace = namespace
|
| 1036 |
+
self.value = value
|
| 1037 |
+
|
| 1038 |
+
def sources(self) -> list[Value]:
|
| 1039 |
+
return [self.value]
|
| 1040 |
+
|
| 1041 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1042 |
+
(self.value,) = new
|
| 1043 |
+
|
| 1044 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1045 |
+
return visitor.visit_init_static(self)
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
@final
|
| 1049 |
+
class TupleSet(RegisterOp):
|
| 1050 |
+
"""dest = (reg, ...) (for fixed-length tuple)"""
|
| 1051 |
+
|
| 1052 |
+
error_kind = ERR_NEVER
|
| 1053 |
+
|
| 1054 |
+
def __init__(self, items: list[Value], line: int) -> None:
|
| 1055 |
+
super().__init__(line)
|
| 1056 |
+
self.items = items
|
| 1057 |
+
# Don't keep track of the fact that an int is short after it
|
| 1058 |
+
# is put into a tuple, since we don't properly implement
|
| 1059 |
+
# runtime subtyping for tuples.
|
| 1060 |
+
self.tuple_type = RTuple(
|
| 1061 |
+
[
|
| 1062 |
+
arg.type if not is_short_int_rprimitive(arg.type) else int_rprimitive
|
| 1063 |
+
for arg in items
|
| 1064 |
+
]
|
| 1065 |
+
)
|
| 1066 |
+
self.type = self.tuple_type
|
| 1067 |
+
|
| 1068 |
+
def sources(self) -> list[Value]:
|
| 1069 |
+
return self.items.copy()
|
| 1070 |
+
|
| 1071 |
+
def stolen(self) -> list[Value]:
|
| 1072 |
+
return self.items.copy()
|
| 1073 |
+
|
| 1074 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1075 |
+
self.items = new[:]
|
| 1076 |
+
|
| 1077 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1078 |
+
return visitor.visit_tuple_set(self)
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
@final
|
| 1082 |
+
class TupleGet(RegisterOp):
|
| 1083 |
+
"""Get item of a fixed-length tuple (src[index])."""
|
| 1084 |
+
|
| 1085 |
+
error_kind = ERR_NEVER
|
| 1086 |
+
|
| 1087 |
+
def __init__(self, src: Value, index: int, line: int = -1, *, borrow: bool = False) -> None:
|
| 1088 |
+
super().__init__(line)
|
| 1089 |
+
assert isinstance(
|
| 1090 |
+
src.type, RTuple
|
| 1091 |
+
), f"TupleGet only operates on tuples, not {type(src.type).__name__}"
|
| 1092 |
+
src_len = len(src.type.types)
|
| 1093 |
+
self.src = src
|
| 1094 |
+
self.index = index
|
| 1095 |
+
if index < 0:
|
| 1096 |
+
self.index += src_len
|
| 1097 |
+
assert (
|
| 1098 |
+
self.index <= src_len - 1
|
| 1099 |
+
), f"Index out of range.\nsource type: {src.type}\nindex: {index}"
|
| 1100 |
+
self.type = src.type.types[index]
|
| 1101 |
+
self.is_borrowed = borrow
|
| 1102 |
+
|
| 1103 |
+
def sources(self) -> list[Value]:
|
| 1104 |
+
return [self.src]
|
| 1105 |
+
|
| 1106 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1107 |
+
(self.src,) = new
|
| 1108 |
+
|
| 1109 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1110 |
+
return visitor.visit_tuple_get(self)
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
@final
|
| 1114 |
+
class Cast(RegisterOp):
|
| 1115 |
+
"""cast(type, src)
|
| 1116 |
+
|
| 1117 |
+
Perform a runtime type check (no representation or value conversion).
|
| 1118 |
+
|
| 1119 |
+
DO NOT increment reference counts.
|
| 1120 |
+
"""
|
| 1121 |
+
|
| 1122 |
+
error_kind = ERR_MAGIC
|
| 1123 |
+
|
| 1124 |
+
def __init__(
|
| 1125 |
+
self, src: Value, typ: RType, line: int, *, borrow: bool = False, unchecked: bool = False
|
| 1126 |
+
) -> None:
|
| 1127 |
+
super().__init__(line)
|
| 1128 |
+
self.src = src
|
| 1129 |
+
self.type = typ
|
| 1130 |
+
# If true, don't incref the result.
|
| 1131 |
+
self.is_borrowed = borrow
|
| 1132 |
+
# If true, don't perform a runtime type check (only changes the static type of
|
| 1133 |
+
# the operand). Used when we know that the cast will always succeed.
|
| 1134 |
+
self.is_unchecked = unchecked
|
| 1135 |
+
if unchecked:
|
| 1136 |
+
self.error_kind = ERR_NEVER
|
| 1137 |
+
|
| 1138 |
+
def sources(self) -> list[Value]:
|
| 1139 |
+
return [self.src]
|
| 1140 |
+
|
| 1141 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1142 |
+
(self.src,) = new
|
| 1143 |
+
|
| 1144 |
+
def stolen(self) -> list[Value]:
|
| 1145 |
+
if self.is_borrowed:
|
| 1146 |
+
return []
|
| 1147 |
+
return [self.src]
|
| 1148 |
+
|
| 1149 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1150 |
+
return visitor.visit_cast(self)
|
| 1151 |
+
|
| 1152 |
+
|
| 1153 |
+
@final
|
| 1154 |
+
class Box(RegisterOp):
|
| 1155 |
+
"""box(type, src)
|
| 1156 |
+
|
| 1157 |
+
This converts from a potentially unboxed representation to a straight Python object.
|
| 1158 |
+
Only supported for types with an unboxed representation.
|
| 1159 |
+
"""
|
| 1160 |
+
|
| 1161 |
+
error_kind = ERR_NEVER
|
| 1162 |
+
|
| 1163 |
+
def __init__(self, src: Value, line: int = -1) -> None:
|
| 1164 |
+
super().__init__(line)
|
| 1165 |
+
self.src = src
|
| 1166 |
+
self.type = object_rprimitive
|
| 1167 |
+
# When we box None and bool values, we produce a borrowed result
|
| 1168 |
+
if is_none_rprimitive(self.src.type) or is_bool_or_bit_rprimitive(self.src.type):
|
| 1169 |
+
self.is_borrowed = True
|
| 1170 |
+
|
| 1171 |
+
def sources(self) -> list[Value]:
|
| 1172 |
+
return [self.src]
|
| 1173 |
+
|
| 1174 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1175 |
+
(self.src,) = new
|
| 1176 |
+
|
| 1177 |
+
def stolen(self) -> list[Value]:
|
| 1178 |
+
return [self.src]
|
| 1179 |
+
|
| 1180 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1181 |
+
return visitor.visit_box(self)
|
| 1182 |
+
|
| 1183 |
+
|
| 1184 |
+
@final
|
| 1185 |
+
class Unbox(RegisterOp):
|
| 1186 |
+
"""unbox(type, src)
|
| 1187 |
+
|
| 1188 |
+
This is similar to a cast, but it also changes to a (potentially) unboxed runtime
|
| 1189 |
+
representation. Only supported for types with an unboxed representation.
|
| 1190 |
+
"""
|
| 1191 |
+
|
| 1192 |
+
def __init__(self, src: Value, typ: RType, line: int) -> None:
|
| 1193 |
+
self.src = src
|
| 1194 |
+
self.type = typ
|
| 1195 |
+
if not typ.error_overlap:
|
| 1196 |
+
self.error_kind = ERR_MAGIC
|
| 1197 |
+
else:
|
| 1198 |
+
self.error_kind = ERR_MAGIC_OVERLAPPING
|
| 1199 |
+
super().__init__(line)
|
| 1200 |
+
|
| 1201 |
+
def sources(self) -> list[Value]:
|
| 1202 |
+
return [self.src]
|
| 1203 |
+
|
| 1204 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1205 |
+
(self.src,) = new
|
| 1206 |
+
|
| 1207 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1208 |
+
return visitor.visit_unbox(self)
|
| 1209 |
+
|
| 1210 |
+
|
| 1211 |
+
@final
|
| 1212 |
+
class RaiseStandardError(RegisterOp):
|
| 1213 |
+
"""Raise built-in exception with an optional error string.
|
| 1214 |
+
|
| 1215 |
+
We have a separate opcode for this for convenience and to
|
| 1216 |
+
generate smaller, more idiomatic C code.
|
| 1217 |
+
"""
|
| 1218 |
+
|
| 1219 |
+
# TODO: Make it more explicit at IR level that this always raises
|
| 1220 |
+
|
| 1221 |
+
error_kind = ERR_FALSE
|
| 1222 |
+
|
| 1223 |
+
VALUE_ERROR: Final = "ValueError"
|
| 1224 |
+
ASSERTION_ERROR: Final = "AssertionError"
|
| 1225 |
+
STOP_ITERATION: Final = "StopIteration"
|
| 1226 |
+
UNBOUND_LOCAL_ERROR: Final = "UnboundLocalError"
|
| 1227 |
+
RUNTIME_ERROR: Final = "RuntimeError"
|
| 1228 |
+
NAME_ERROR: Final = "NameError"
|
| 1229 |
+
ZERO_DIVISION_ERROR: Final = "ZeroDivisionError"
|
| 1230 |
+
INDEX_ERROR: Final = "IndexError"
|
| 1231 |
+
|
| 1232 |
+
def __init__(self, class_name: str, value: str | Value | None, line: int) -> None:
|
| 1233 |
+
super().__init__(line)
|
| 1234 |
+
self.class_name = class_name
|
| 1235 |
+
self.value = value
|
| 1236 |
+
self.type = bool_rprimitive
|
| 1237 |
+
|
| 1238 |
+
def sources(self) -> list[Value]:
|
| 1239 |
+
return []
|
| 1240 |
+
|
| 1241 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1242 |
+
assert not new
|
| 1243 |
+
|
| 1244 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1245 |
+
return visitor.visit_raise_standard_error(self)
|
| 1246 |
+
|
| 1247 |
+
|
| 1248 |
+
# True steals all arguments, False steals none, a list steals those in matching positions
|
| 1249 |
+
StealsDescription = bool | list[bool]
|
| 1250 |
+
|
| 1251 |
+
|
| 1252 |
+
@final
|
| 1253 |
+
class CallC(RegisterOp):
|
| 1254 |
+
"""result = function(arg0, arg1, ...)
|
| 1255 |
+
|
| 1256 |
+
Call a C function that is not a compiled/native function (for
|
| 1257 |
+
example, a Python C API function). Use Call to call native
|
| 1258 |
+
functions.
|
| 1259 |
+
"""
|
| 1260 |
+
|
| 1261 |
+
def __init__(
|
| 1262 |
+
self,
|
| 1263 |
+
function_name: str,
|
| 1264 |
+
args: list[Value],
|
| 1265 |
+
ret_type: RType,
|
| 1266 |
+
steals: StealsDescription,
|
| 1267 |
+
is_borrowed: bool,
|
| 1268 |
+
error_kind: int,
|
| 1269 |
+
line: int,
|
| 1270 |
+
var_arg_idx: int = -1,
|
| 1271 |
+
*,
|
| 1272 |
+
is_pure: bool = False,
|
| 1273 |
+
returns_null: bool = False,
|
| 1274 |
+
dependencies: list[Dependency] | None = None,
|
| 1275 |
+
) -> None:
|
| 1276 |
+
self.error_kind = error_kind
|
| 1277 |
+
super().__init__(line)
|
| 1278 |
+
self.function_name = function_name
|
| 1279 |
+
self.args = args
|
| 1280 |
+
self.type = ret_type
|
| 1281 |
+
self.steals = steals
|
| 1282 |
+
self.is_borrowed = is_borrowed
|
| 1283 |
+
# The position of the first variable argument in args (if >= 0)
|
| 1284 |
+
self.var_arg_idx = var_arg_idx
|
| 1285 |
+
# Is the function pure? Pure functions have no side effects
|
| 1286 |
+
# and all the arguments are immutable. Pure functions support
|
| 1287 |
+
# additional optimizations. Pure functions never fail.
|
| 1288 |
+
self.is_pure = is_pure
|
| 1289 |
+
# The function might return a null value that does not indicate
|
| 1290 |
+
# an error.
|
| 1291 |
+
self.returns_null = returns_null
|
| 1292 |
+
# Dependencies (such as capsules) that must be imported and initialized before
|
| 1293 |
+
# calling this function (used for C functions exported from librt).
|
| 1294 |
+
self.dependencies = dependencies
|
| 1295 |
+
if is_pure or returns_null:
|
| 1296 |
+
assert error_kind == ERR_NEVER
|
| 1297 |
+
|
| 1298 |
+
def sources(self) -> list[Value]:
|
| 1299 |
+
return self.args[:]
|
| 1300 |
+
|
| 1301 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1302 |
+
self.args = new[:]
|
| 1303 |
+
|
| 1304 |
+
def stolen(self) -> list[Value]:
|
| 1305 |
+
if isinstance(self.steals, list):
|
| 1306 |
+
assert len(self.steals) == len(self.args)
|
| 1307 |
+
return [arg for arg, steal in zip(self.args, self.steals) if steal]
|
| 1308 |
+
else:
|
| 1309 |
+
return [] if not self.steals else self.sources()
|
| 1310 |
+
|
| 1311 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1312 |
+
return visitor.visit_call_c(self)
|
| 1313 |
+
|
| 1314 |
+
|
| 1315 |
+
@final
|
| 1316 |
+
class Truncate(RegisterOp):
|
| 1317 |
+
"""result = truncate src from src_type to dst_type
|
| 1318 |
+
|
| 1319 |
+
Truncate a value from type with more bits to type with less bits.
|
| 1320 |
+
|
| 1321 |
+
dst_type and src_type can be native integer types, bools or tagged
|
| 1322 |
+
integers. Tagged integers should have the tag bit unset.
|
| 1323 |
+
"""
|
| 1324 |
+
|
| 1325 |
+
error_kind = ERR_NEVER
|
| 1326 |
+
|
| 1327 |
+
def __init__(self, src: Value, dst_type: RType, line: int = -1) -> None:
|
| 1328 |
+
super().__init__(line)
|
| 1329 |
+
self.src = src
|
| 1330 |
+
self.type = dst_type
|
| 1331 |
+
self.src_type = src.type
|
| 1332 |
+
|
| 1333 |
+
def sources(self) -> list[Value]:
|
| 1334 |
+
return [self.src]
|
| 1335 |
+
|
| 1336 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1337 |
+
(self.src,) = new
|
| 1338 |
+
|
| 1339 |
+
def stolen(self) -> list[Value]:
|
| 1340 |
+
return []
|
| 1341 |
+
|
| 1342 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1343 |
+
return visitor.visit_truncate(self)
|
| 1344 |
+
|
| 1345 |
+
|
| 1346 |
+
@final
|
| 1347 |
+
class Extend(RegisterOp):
|
| 1348 |
+
"""result = extend src from src_type to dst_type
|
| 1349 |
+
|
| 1350 |
+
Extend a value from a type with fewer bits to a type with more bits.
|
| 1351 |
+
|
| 1352 |
+
dst_type and src_type can be native integer types, bools or tagged
|
| 1353 |
+
integers. Tagged integers should have the tag bit unset.
|
| 1354 |
+
|
| 1355 |
+
If 'signed' is true, perform sign extension. Otherwise, the result will be
|
| 1356 |
+
zero extended.
|
| 1357 |
+
"""
|
| 1358 |
+
|
| 1359 |
+
error_kind = ERR_NEVER
|
| 1360 |
+
|
| 1361 |
+
def __init__(self, src: Value, dst_type: RType, signed: bool, line: int = -1) -> None:
|
| 1362 |
+
super().__init__(line)
|
| 1363 |
+
self.src = src
|
| 1364 |
+
self.type = dst_type
|
| 1365 |
+
self.src_type = src.type
|
| 1366 |
+
self.signed = signed
|
| 1367 |
+
|
| 1368 |
+
def sources(self) -> list[Value]:
|
| 1369 |
+
return [self.src]
|
| 1370 |
+
|
| 1371 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1372 |
+
(self.src,) = new
|
| 1373 |
+
|
| 1374 |
+
def stolen(self) -> list[Value]:
|
| 1375 |
+
return []
|
| 1376 |
+
|
| 1377 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1378 |
+
return visitor.visit_extend(self)
|
| 1379 |
+
|
| 1380 |
+
|
| 1381 |
+
@final
|
| 1382 |
+
class LoadGlobal(RegisterOp):
|
| 1383 |
+
"""Load a low-level global variable/pointer.
|
| 1384 |
+
|
| 1385 |
+
Note that can't be used to directly load Python module-level
|
| 1386 |
+
global variable, since they are stored in a globals dictionary
|
| 1387 |
+
and accessed using dictionary operations.
|
| 1388 |
+
"""
|
| 1389 |
+
|
| 1390 |
+
error_kind = ERR_NEVER
|
| 1391 |
+
is_borrowed = True
|
| 1392 |
+
|
| 1393 |
+
def __init__(self, type: RType, identifier: str, line: int = -1, ann: object = None) -> None:
|
| 1394 |
+
super().__init__(line)
|
| 1395 |
+
self.identifier = identifier
|
| 1396 |
+
self.type = type
|
| 1397 |
+
self.ann = ann # An object to pretty print with the load
|
| 1398 |
+
|
| 1399 |
+
def sources(self) -> list[Value]:
|
| 1400 |
+
return []
|
| 1401 |
+
|
| 1402 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1403 |
+
assert not new
|
| 1404 |
+
|
| 1405 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1406 |
+
return visitor.visit_load_global(self)
|
| 1407 |
+
|
| 1408 |
+
|
| 1409 |
+
@final
|
| 1410 |
+
class IntOp(RegisterOp):
|
| 1411 |
+
"""Binary arithmetic or bitwise op on integer operands (e.g., r1 = r2 + r3).
|
| 1412 |
+
|
| 1413 |
+
These ops are low-level and are similar to the corresponding C
|
| 1414 |
+
operations.
|
| 1415 |
+
|
| 1416 |
+
The left and right values must have low-level integer types with
|
| 1417 |
+
compatible representations. Fixed-width integers, short_int_rprimitive,
|
| 1418 |
+
bool_rprimitive and bit_rprimitive are supported.
|
| 1419 |
+
|
| 1420 |
+
For tagged (arbitrary-precision) integer ops look at mypyc.primitives.int_ops.
|
| 1421 |
+
"""
|
| 1422 |
+
|
| 1423 |
+
error_kind = ERR_NEVER
|
| 1424 |
+
|
| 1425 |
+
# Arithmetic ops
|
| 1426 |
+
ADD: Final = 0
|
| 1427 |
+
SUB: Final = 1
|
| 1428 |
+
MUL: Final = 2
|
| 1429 |
+
DIV: Final = 3
|
| 1430 |
+
MOD: Final = 4
|
| 1431 |
+
|
| 1432 |
+
# Bitwise ops
|
| 1433 |
+
AND: Final = 200
|
| 1434 |
+
OR: Final = 201
|
| 1435 |
+
XOR: Final = 202
|
| 1436 |
+
LEFT_SHIFT: Final = 203
|
| 1437 |
+
RIGHT_SHIFT: Final = 204
|
| 1438 |
+
|
| 1439 |
+
op_str: Final = {
|
| 1440 |
+
ADD: "+",
|
| 1441 |
+
SUB: "-",
|
| 1442 |
+
MUL: "*",
|
| 1443 |
+
DIV: "/",
|
| 1444 |
+
MOD: "%",
|
| 1445 |
+
AND: "&",
|
| 1446 |
+
OR: "|",
|
| 1447 |
+
XOR: "^",
|
| 1448 |
+
LEFT_SHIFT: "<<",
|
| 1449 |
+
RIGHT_SHIFT: ">>",
|
| 1450 |
+
}
|
| 1451 |
+
|
| 1452 |
+
def __init__(self, type: RType, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:
|
| 1453 |
+
super().__init__(line)
|
| 1454 |
+
self.type = type
|
| 1455 |
+
self.lhs = lhs
|
| 1456 |
+
self.rhs = rhs
|
| 1457 |
+
self.op = op
|
| 1458 |
+
|
| 1459 |
+
def sources(self) -> list[Value]:
|
| 1460 |
+
return [self.lhs, self.rhs]
|
| 1461 |
+
|
| 1462 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1463 |
+
self.lhs, self.rhs = new
|
| 1464 |
+
|
| 1465 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1466 |
+
return visitor.visit_int_op(self)
|
| 1467 |
+
|
| 1468 |
+
|
| 1469 |
+
# We can't have this in the IntOp class body, because of
|
| 1470 |
+
# https://github.com/mypyc/mypyc/issues/932.
|
| 1471 |
+
int_op_to_id: Final = {op: op_id for op_id, op in IntOp.op_str.items()}
|
| 1472 |
+
|
| 1473 |
+
|
| 1474 |
+
@final
|
| 1475 |
+
class ComparisonOp(RegisterOp):
|
| 1476 |
+
"""Low-level comparison op for integers and pointers.
|
| 1477 |
+
|
| 1478 |
+
Both unsigned and signed comparisons are supported. Supports
|
| 1479 |
+
comparisons between fixed-width integer types and pointer types.
|
| 1480 |
+
The operands should have matching sizes.
|
| 1481 |
+
|
| 1482 |
+
The result is always a bit (representing a boolean).
|
| 1483 |
+
|
| 1484 |
+
Python semantics, such as calling __eq__, are not supported.
|
| 1485 |
+
"""
|
| 1486 |
+
|
| 1487 |
+
# Must be ERR_NEVER or ERR_FALSE. ERR_FALSE means that a false result
|
| 1488 |
+
# indicates that an exception has been raised and should be propagated.
|
| 1489 |
+
error_kind = ERR_NEVER
|
| 1490 |
+
|
| 1491 |
+
# S for signed and U for unsigned
|
| 1492 |
+
EQ: Final = 100
|
| 1493 |
+
NEQ: Final = 101
|
| 1494 |
+
SLT: Final = 102
|
| 1495 |
+
SGT: Final = 103
|
| 1496 |
+
SLE: Final = 104
|
| 1497 |
+
SGE: Final = 105
|
| 1498 |
+
ULT: Final = 106
|
| 1499 |
+
UGT: Final = 107
|
| 1500 |
+
ULE: Final = 108
|
| 1501 |
+
UGE: Final = 109
|
| 1502 |
+
|
| 1503 |
+
op_str: Final = {
|
| 1504 |
+
EQ: "==",
|
| 1505 |
+
NEQ: "!=",
|
| 1506 |
+
SLT: "<",
|
| 1507 |
+
SGT: ">",
|
| 1508 |
+
SLE: "<=",
|
| 1509 |
+
SGE: ">=",
|
| 1510 |
+
ULT: "<",
|
| 1511 |
+
UGT: ">",
|
| 1512 |
+
ULE: "<=",
|
| 1513 |
+
UGE: ">=",
|
| 1514 |
+
}
|
| 1515 |
+
|
| 1516 |
+
signed_ops: Final = {"==": EQ, "!=": NEQ, "<": SLT, ">": SGT, "<=": SLE, ">=": SGE}
|
| 1517 |
+
unsigned_ops: Final = {"==": EQ, "!=": NEQ, "<": ULT, ">": UGT, "<=": ULE, ">=": UGE}
|
| 1518 |
+
|
| 1519 |
+
def __init__(self, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:
|
| 1520 |
+
super().__init__(line)
|
| 1521 |
+
self.type = bit_rprimitive
|
| 1522 |
+
self.lhs = lhs
|
| 1523 |
+
self.rhs = rhs
|
| 1524 |
+
self.op = op
|
| 1525 |
+
|
| 1526 |
+
def sources(self) -> list[Value]:
|
| 1527 |
+
return [self.lhs, self.rhs]
|
| 1528 |
+
|
| 1529 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1530 |
+
self.lhs, self.rhs = new
|
| 1531 |
+
|
| 1532 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1533 |
+
return visitor.visit_comparison_op(self)
|
| 1534 |
+
|
| 1535 |
+
|
| 1536 |
+
@final
|
| 1537 |
+
class FloatOp(RegisterOp):
|
| 1538 |
+
"""Binary float arithmetic op (e.g., r1 = r2 + r3).
|
| 1539 |
+
|
| 1540 |
+
These ops are low-level and are similar to the corresponding C
|
| 1541 |
+
operations (and somewhat different from Python operations).
|
| 1542 |
+
|
| 1543 |
+
The left and right values must be floats.
|
| 1544 |
+
"""
|
| 1545 |
+
|
| 1546 |
+
error_kind = ERR_NEVER
|
| 1547 |
+
|
| 1548 |
+
ADD: Final = 0
|
| 1549 |
+
SUB: Final = 1
|
| 1550 |
+
MUL: Final = 2
|
| 1551 |
+
DIV: Final = 3
|
| 1552 |
+
MOD: Final = 4
|
| 1553 |
+
|
| 1554 |
+
op_str: Final = {ADD: "+", SUB: "-", MUL: "*", DIV: "/", MOD: "%"}
|
| 1555 |
+
|
| 1556 |
+
def __init__(self, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:
|
| 1557 |
+
super().__init__(line)
|
| 1558 |
+
self.type = float_rprimitive
|
| 1559 |
+
self.lhs = lhs
|
| 1560 |
+
self.rhs = rhs
|
| 1561 |
+
self.op = op
|
| 1562 |
+
|
| 1563 |
+
def sources(self) -> list[Value]:
|
| 1564 |
+
return [self.lhs, self.rhs]
|
| 1565 |
+
|
| 1566 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1567 |
+
self.lhs, self.rhs = new
|
| 1568 |
+
|
| 1569 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1570 |
+
return visitor.visit_float_op(self)
|
| 1571 |
+
|
| 1572 |
+
|
| 1573 |
+
# We can't have this in the FloatOp class body, because of
|
| 1574 |
+
# https://github.com/mypyc/mypyc/issues/932.
|
| 1575 |
+
float_op_to_id: Final = {op: op_id for op_id, op in FloatOp.op_str.items()}
|
| 1576 |
+
|
| 1577 |
+
|
| 1578 |
+
@final
|
| 1579 |
+
class FloatNeg(RegisterOp):
|
| 1580 |
+
"""Float negation op (r1 = -r2)."""
|
| 1581 |
+
|
| 1582 |
+
error_kind = ERR_NEVER
|
| 1583 |
+
|
| 1584 |
+
def __init__(self, src: Value, line: int = -1) -> None:
|
| 1585 |
+
super().__init__(line)
|
| 1586 |
+
self.type = float_rprimitive
|
| 1587 |
+
self.src = src
|
| 1588 |
+
|
| 1589 |
+
def sources(self) -> list[Value]:
|
| 1590 |
+
return [self.src]
|
| 1591 |
+
|
| 1592 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1593 |
+
(self.src,) = new
|
| 1594 |
+
|
| 1595 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1596 |
+
return visitor.visit_float_neg(self)
|
| 1597 |
+
|
| 1598 |
+
|
| 1599 |
+
@final
|
| 1600 |
+
class FloatComparisonOp(RegisterOp):
|
| 1601 |
+
"""Low-level comparison op for floats."""
|
| 1602 |
+
|
| 1603 |
+
error_kind = ERR_NEVER
|
| 1604 |
+
|
| 1605 |
+
EQ: Final = 200
|
| 1606 |
+
NEQ: Final = 201
|
| 1607 |
+
LT: Final = 202
|
| 1608 |
+
GT: Final = 203
|
| 1609 |
+
LE: Final = 204
|
| 1610 |
+
GE: Final = 205
|
| 1611 |
+
|
| 1612 |
+
op_str: Final = {EQ: "==", NEQ: "!=", LT: "<", GT: ">", LE: "<=", GE: ">="}
|
| 1613 |
+
|
| 1614 |
+
def __init__(self, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:
|
| 1615 |
+
super().__init__(line)
|
| 1616 |
+
self.type = bit_rprimitive
|
| 1617 |
+
self.lhs = lhs
|
| 1618 |
+
self.rhs = rhs
|
| 1619 |
+
self.op = op
|
| 1620 |
+
|
| 1621 |
+
def sources(self) -> list[Value]:
|
| 1622 |
+
return [self.lhs, self.rhs]
|
| 1623 |
+
|
| 1624 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1625 |
+
self.lhs, self.rhs = new
|
| 1626 |
+
|
| 1627 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1628 |
+
return visitor.visit_float_comparison_op(self)
|
| 1629 |
+
|
| 1630 |
+
|
| 1631 |
+
# We can't have this in the FloatOp class body, because of
|
| 1632 |
+
# https://github.com/mypyc/mypyc/issues/932.
|
| 1633 |
+
float_comparison_op_to_id: Final = {op: op_id for op_id, op in FloatComparisonOp.op_str.items()}
|
| 1634 |
+
|
| 1635 |
+
|
| 1636 |
+
@final
|
| 1637 |
+
class LoadMem(RegisterOp):
|
| 1638 |
+
"""Read a memory location: result = *(type *)src.
|
| 1639 |
+
|
| 1640 |
+
Attributes:
|
| 1641 |
+
type: Type of the read value
|
| 1642 |
+
src: Pointer to memory to read
|
| 1643 |
+
"""
|
| 1644 |
+
|
| 1645 |
+
error_kind = ERR_NEVER
|
| 1646 |
+
|
| 1647 |
+
def __init__(self, type: RType, src: Value, line: int = -1, *, borrow: bool = False) -> None:
|
| 1648 |
+
super().__init__(line)
|
| 1649 |
+
self.type = type
|
| 1650 |
+
# TODO: Support other native integer types
|
| 1651 |
+
assert is_pointer_rprimitive(src.type)
|
| 1652 |
+
self.src = src
|
| 1653 |
+
self.is_borrowed = borrow and type.is_refcounted
|
| 1654 |
+
|
| 1655 |
+
def sources(self) -> list[Value]:
|
| 1656 |
+
return [self.src]
|
| 1657 |
+
|
| 1658 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1659 |
+
(self.src,) = new
|
| 1660 |
+
|
| 1661 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1662 |
+
return visitor.visit_load_mem(self)
|
| 1663 |
+
|
| 1664 |
+
|
| 1665 |
+
@final
|
| 1666 |
+
class SetMem(Op):
|
| 1667 |
+
"""Write to a memory location: *(type *)dest = src
|
| 1668 |
+
|
| 1669 |
+
Attributes:
|
| 1670 |
+
type: Type of the written value
|
| 1671 |
+
dest: Pointer to memory to write
|
| 1672 |
+
src: Source value
|
| 1673 |
+
"""
|
| 1674 |
+
|
| 1675 |
+
error_kind = ERR_NEVER
|
| 1676 |
+
|
| 1677 |
+
def __init__(self, type: RType, dest: Value, src: Value, line: int = -1) -> None:
|
| 1678 |
+
super().__init__(line)
|
| 1679 |
+
self.type = void_rtype
|
| 1680 |
+
self.dest_type = type
|
| 1681 |
+
self.src = src
|
| 1682 |
+
self.dest = dest
|
| 1683 |
+
|
| 1684 |
+
def sources(self) -> list[Value]:
|
| 1685 |
+
return [self.src, self.dest]
|
| 1686 |
+
|
| 1687 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1688 |
+
self.src, self.dest = new
|
| 1689 |
+
|
| 1690 |
+
def stolen(self) -> list[Value]:
|
| 1691 |
+
return [self.src]
|
| 1692 |
+
|
| 1693 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1694 |
+
return visitor.visit_set_mem(self)
|
| 1695 |
+
|
| 1696 |
+
|
| 1697 |
+
@final
|
| 1698 |
+
class GetElement(RegisterOp):
|
| 1699 |
+
"""Get the value of a struct element from a struct value."""
|
| 1700 |
+
|
| 1701 |
+
error_kind = ERR_NEVER
|
| 1702 |
+
is_borrowed = True
|
| 1703 |
+
|
| 1704 |
+
def __init__(self, src: Value, field: str, line: int = -1) -> None:
|
| 1705 |
+
super().__init__(line)
|
| 1706 |
+
assert isinstance(src.type, (RStruct, RVec))
|
| 1707 |
+
self.type = src.type.field_type(field)
|
| 1708 |
+
self.src = src
|
| 1709 |
+
self.src_type = src.type
|
| 1710 |
+
self.field = field
|
| 1711 |
+
|
| 1712 |
+
def sources(self) -> list[Value]:
|
| 1713 |
+
return [self.src]
|
| 1714 |
+
|
| 1715 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1716 |
+
(self.src,) = new
|
| 1717 |
+
|
| 1718 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1719 |
+
return visitor.visit_get_element(self)
|
| 1720 |
+
|
| 1721 |
+
|
| 1722 |
+
@final
|
| 1723 |
+
class GetElementPtr(RegisterOp):
|
| 1724 |
+
"""Get the address of a struct element from a pointer to a struct.
|
| 1725 |
+
|
| 1726 |
+
If you have a struct value, use GetElement instead.
|
| 1727 |
+
|
| 1728 |
+
Note that you may need to use KeepAlive to avoid the struct
|
| 1729 |
+
being freed, if it's reference counted, such as PyObject *.
|
| 1730 |
+
"""
|
| 1731 |
+
|
| 1732 |
+
error_kind = ERR_NEVER
|
| 1733 |
+
|
| 1734 |
+
def __init__(self, src: Value, src_type: RType, field: str, line: int = -1) -> None:
|
| 1735 |
+
super().__init__(line)
|
| 1736 |
+
assert not isinstance(src.type, (RStruct, RVec))
|
| 1737 |
+
self.type = pointer_rprimitive
|
| 1738 |
+
self.src = src
|
| 1739 |
+
self.src_type = src_type
|
| 1740 |
+
self.field = field
|
| 1741 |
+
|
| 1742 |
+
def sources(self) -> list[Value]:
|
| 1743 |
+
return [self.src]
|
| 1744 |
+
|
| 1745 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1746 |
+
(self.src,) = new
|
| 1747 |
+
|
| 1748 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1749 |
+
return visitor.visit_get_element_ptr(self)
|
| 1750 |
+
|
| 1751 |
+
|
| 1752 |
+
@final
|
| 1753 |
+
class SetElement(RegisterOp):
|
| 1754 |
+
"""Set the value of a struct element.
|
| 1755 |
+
|
| 1756 |
+
This evaluates to a new struct with the changed value.
|
| 1757 |
+
|
| 1758 |
+
Use together with Undef to initialize a fresh struct value
|
| 1759 |
+
(see Undef for more details).
|
| 1760 |
+
"""
|
| 1761 |
+
|
| 1762 |
+
error_kind = ERR_NEVER
|
| 1763 |
+
|
| 1764 |
+
def __init__(self, src: Value, field: str, item: Value, line: int = -1) -> None:
|
| 1765 |
+
super().__init__(line)
|
| 1766 |
+
assert isinstance(src.type, (RStruct, RVec)), src.type
|
| 1767 |
+
self.type = src.type
|
| 1768 |
+
self.src = src
|
| 1769 |
+
self.item = item
|
| 1770 |
+
self.field = field
|
| 1771 |
+
|
| 1772 |
+
def sources(self) -> list[Value]:
|
| 1773 |
+
return [self.src]
|
| 1774 |
+
|
| 1775 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1776 |
+
(self.src,) = new
|
| 1777 |
+
|
| 1778 |
+
def stolen(self) -> list[Value]:
|
| 1779 |
+
return [self.src]
|
| 1780 |
+
|
| 1781 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1782 |
+
return visitor.visit_set_element(self)
|
| 1783 |
+
|
| 1784 |
+
|
| 1785 |
+
@final
|
| 1786 |
+
class LoadAddress(RegisterOp):
|
| 1787 |
+
"""Get the address of a value: result = (type)&src
|
| 1788 |
+
|
| 1789 |
+
Attributes:
|
| 1790 |
+
type: Type of the loaded address(e.g. ptr/object_ptr)
|
| 1791 |
+
src: Source value (str for globals like 'PyList_Type',
|
| 1792 |
+
Register for temporary values or locals, LoadStatic
|
| 1793 |
+
for statics.)
|
| 1794 |
+
"""
|
| 1795 |
+
|
| 1796 |
+
error_kind = ERR_NEVER
|
| 1797 |
+
is_borrowed = True
|
| 1798 |
+
|
| 1799 |
+
def __init__(self, type: RType, src: str | Register | LoadStatic, line: int = -1) -> None:
|
| 1800 |
+
super().__init__(line)
|
| 1801 |
+
self.type = type
|
| 1802 |
+
self.src = src
|
| 1803 |
+
|
| 1804 |
+
def sources(self) -> list[Value]:
|
| 1805 |
+
if isinstance(self.src, Register):
|
| 1806 |
+
return [self.src]
|
| 1807 |
+
else:
|
| 1808 |
+
return []
|
| 1809 |
+
|
| 1810 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1811 |
+
if new:
|
| 1812 |
+
assert isinstance(new[0], Register)
|
| 1813 |
+
assert len(new) == 1
|
| 1814 |
+
self.src = new[0]
|
| 1815 |
+
|
| 1816 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1817 |
+
return visitor.visit_load_address(self)
|
| 1818 |
+
|
| 1819 |
+
|
| 1820 |
+
@final
|
| 1821 |
+
class KeepAlive(RegisterOp):
|
| 1822 |
+
"""A no-op operation that ensures source values aren't freed.
|
| 1823 |
+
|
| 1824 |
+
This is sometimes useful to avoid decref when a reference is still
|
| 1825 |
+
being held but not seen by the compiler.
|
| 1826 |
+
|
| 1827 |
+
A typical use case is like this (C-like pseudocode):
|
| 1828 |
+
|
| 1829 |
+
ptr = &x.item
|
| 1830 |
+
r = *ptr
|
| 1831 |
+
keep_alive x # x must not be freed here
|
| 1832 |
+
# x may be freed here
|
| 1833 |
+
|
| 1834 |
+
If we didn't have "keep_alive x", x could be freed immediately
|
| 1835 |
+
after taking the address of 'item', resulting in a read after free
|
| 1836 |
+
on the second line.
|
| 1837 |
+
|
| 1838 |
+
If 'steal' is true, the value is considered to be stolen at
|
| 1839 |
+
this op, i.e. it won't be decref'd. You need to ensure that
|
| 1840 |
+
the value is freed otherwise, perhaps by using borrowing
|
| 1841 |
+
followed by Unborrow.
|
| 1842 |
+
|
| 1843 |
+
Be careful with steal=True -- this can cause memory leaks.
|
| 1844 |
+
"""
|
| 1845 |
+
|
| 1846 |
+
error_kind = ERR_NEVER
|
| 1847 |
+
|
| 1848 |
+
def __init__(self, src: list[Value], line: int = -1, *, steal: bool = False) -> None:
|
| 1849 |
+
super().__init__(line)
|
| 1850 |
+
assert src
|
| 1851 |
+
self.src = src
|
| 1852 |
+
self.steal = steal
|
| 1853 |
+
|
| 1854 |
+
def sources(self) -> list[Value]:
|
| 1855 |
+
return self.src.copy()
|
| 1856 |
+
|
| 1857 |
+
def stolen(self) -> list[Value]:
|
| 1858 |
+
if self.steal:
|
| 1859 |
+
return self.src.copy()
|
| 1860 |
+
return []
|
| 1861 |
+
|
| 1862 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1863 |
+
self.src = new[:]
|
| 1864 |
+
|
| 1865 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1866 |
+
return visitor.visit_keep_alive(self)
|
| 1867 |
+
|
| 1868 |
+
|
| 1869 |
+
@final
|
| 1870 |
+
class Unborrow(RegisterOp):
|
| 1871 |
+
"""A no-op op to create a regular reference from a borrowed one.
|
| 1872 |
+
|
| 1873 |
+
Borrowed references can only be used temporarily and the reference
|
| 1874 |
+
counts won't be managed. This value will be refcounted normally.
|
| 1875 |
+
|
| 1876 |
+
This is mainly useful if you split an aggregate value, such as
|
| 1877 |
+
a tuple, into components using borrowed values (to avoid increfs),
|
| 1878 |
+
and want to treat the components as sharing the original managed
|
| 1879 |
+
reference. You'll also need to use KeepAlive with steal=True to
|
| 1880 |
+
"consume" the original tuple reference:
|
| 1881 |
+
|
| 1882 |
+
# t is a 2-tuple
|
| 1883 |
+
r0 = borrow t[0]
|
| 1884 |
+
r1 = borrow t[1]
|
| 1885 |
+
keep_alive steal t
|
| 1886 |
+
r2 = unborrow r0
|
| 1887 |
+
r3 = unborrow r1
|
| 1888 |
+
# now (r2, r3) represent the tuple as separate items, that are
|
| 1889 |
+
# managed again. (Note we need to steal before unborrow, to avoid
|
| 1890 |
+
# refcount briefly touching zero if r2 or r3 are unused.)
|
| 1891 |
+
|
| 1892 |
+
Be careful with this -- this can easily cause double freeing.
|
| 1893 |
+
"""
|
| 1894 |
+
|
| 1895 |
+
error_kind = ERR_NEVER
|
| 1896 |
+
|
| 1897 |
+
def __init__(self, src: Value, line: int = -1) -> None:
|
| 1898 |
+
super().__init__(line)
|
| 1899 |
+
assert src.is_borrowed
|
| 1900 |
+
self.src = src
|
| 1901 |
+
self.type = src.type
|
| 1902 |
+
|
| 1903 |
+
def sources(self) -> list[Value]:
|
| 1904 |
+
return [self.src]
|
| 1905 |
+
|
| 1906 |
+
def set_sources(self, new: list[Value]) -> None:
|
| 1907 |
+
(self.src,) = new
|
| 1908 |
+
|
| 1909 |
+
def stolen(self) -> list[Value]:
|
| 1910 |
+
return []
|
| 1911 |
+
|
| 1912 |
+
def accept(self, visitor: OpVisitor[T]) -> T:
|
| 1913 |
+
return visitor.visit_unborrow(self)
|
| 1914 |
+
|
| 1915 |
+
|
| 1916 |
+
@trait
|
| 1917 |
+
class OpVisitor(Generic[T]):
|
| 1918 |
+
"""Generic visitor over ops (uses the visitor design pattern)."""
|
| 1919 |
+
|
| 1920 |
+
@abstractmethod
|
| 1921 |
+
def visit_goto(self, op: Goto) -> T:
|
| 1922 |
+
raise NotImplementedError
|
| 1923 |
+
|
| 1924 |
+
@abstractmethod
|
| 1925 |
+
def visit_branch(self, op: Branch) -> T:
|
| 1926 |
+
raise NotImplementedError
|
| 1927 |
+
|
| 1928 |
+
@abstractmethod
|
| 1929 |
+
def visit_return(self, op: Return) -> T:
|
| 1930 |
+
raise NotImplementedError
|
| 1931 |
+
|
| 1932 |
+
@abstractmethod
|
| 1933 |
+
def visit_unreachable(self, op: Unreachable) -> T:
|
| 1934 |
+
raise NotImplementedError
|
| 1935 |
+
|
| 1936 |
+
@abstractmethod
|
| 1937 |
+
def visit_assign(self, op: Assign) -> T:
|
| 1938 |
+
raise NotImplementedError
|
| 1939 |
+
|
| 1940 |
+
@abstractmethod
|
| 1941 |
+
def visit_assign_multi(self, op: AssignMulti) -> T:
|
| 1942 |
+
raise NotImplementedError
|
| 1943 |
+
|
| 1944 |
+
@abstractmethod
|
| 1945 |
+
def visit_load_error_value(self, op: LoadErrorValue) -> T:
|
| 1946 |
+
raise NotImplementedError
|
| 1947 |
+
|
| 1948 |
+
@abstractmethod
|
| 1949 |
+
def visit_load_literal(self, op: LoadLiteral) -> T:
|
| 1950 |
+
raise NotImplementedError
|
| 1951 |
+
|
| 1952 |
+
@abstractmethod
|
| 1953 |
+
def visit_get_attr(self, op: GetAttr) -> T:
|
| 1954 |
+
raise NotImplementedError
|
| 1955 |
+
|
| 1956 |
+
@abstractmethod
|
| 1957 |
+
def visit_set_attr(self, op: SetAttr) -> T:
|
| 1958 |
+
raise NotImplementedError
|
| 1959 |
+
|
| 1960 |
+
@abstractmethod
|
| 1961 |
+
def visit_load_static(self, op: LoadStatic) -> T:
|
| 1962 |
+
raise NotImplementedError
|
| 1963 |
+
|
| 1964 |
+
@abstractmethod
|
| 1965 |
+
def visit_init_static(self, op: InitStatic) -> T:
|
| 1966 |
+
raise NotImplementedError
|
| 1967 |
+
|
| 1968 |
+
@abstractmethod
|
| 1969 |
+
def visit_tuple_get(self, op: TupleGet) -> T:
|
| 1970 |
+
raise NotImplementedError
|
| 1971 |
+
|
| 1972 |
+
@abstractmethod
|
| 1973 |
+
def visit_tuple_set(self, op: TupleSet) -> T:
|
| 1974 |
+
raise NotImplementedError
|
| 1975 |
+
|
| 1976 |
+
def visit_inc_ref(self, op: IncRef) -> T:
|
| 1977 |
+
raise NotImplementedError
|
| 1978 |
+
|
| 1979 |
+
def visit_dec_ref(self, op: DecRef) -> T:
|
| 1980 |
+
raise NotImplementedError
|
| 1981 |
+
|
| 1982 |
+
@abstractmethod
|
| 1983 |
+
def visit_call(self, op: Call) -> T:
|
| 1984 |
+
raise NotImplementedError
|
| 1985 |
+
|
| 1986 |
+
@abstractmethod
|
| 1987 |
+
def visit_method_call(self, op: MethodCall) -> T:
|
| 1988 |
+
raise NotImplementedError
|
| 1989 |
+
|
| 1990 |
+
@abstractmethod
|
| 1991 |
+
def visit_cast(self, op: Cast) -> T:
|
| 1992 |
+
raise NotImplementedError
|
| 1993 |
+
|
| 1994 |
+
@abstractmethod
|
| 1995 |
+
def visit_box(self, op: Box) -> T:
|
| 1996 |
+
raise NotImplementedError
|
| 1997 |
+
|
| 1998 |
+
@abstractmethod
|
| 1999 |
+
def visit_unbox(self, op: Unbox) -> T:
|
| 2000 |
+
raise NotImplementedError
|
| 2001 |
+
|
| 2002 |
+
@abstractmethod
|
| 2003 |
+
def visit_raise_standard_error(self, op: RaiseStandardError) -> T:
|
| 2004 |
+
raise NotImplementedError
|
| 2005 |
+
|
| 2006 |
+
@abstractmethod
|
| 2007 |
+
def visit_call_c(self, op: CallC) -> T:
|
| 2008 |
+
raise NotImplementedError
|
| 2009 |
+
|
| 2010 |
+
@abstractmethod
|
| 2011 |
+
def visit_primitive_op(self, op: PrimitiveOp) -> T:
|
| 2012 |
+
raise NotImplementedError
|
| 2013 |
+
|
| 2014 |
+
@abstractmethod
|
| 2015 |
+
def visit_truncate(self, op: Truncate) -> T:
|
| 2016 |
+
raise NotImplementedError
|
| 2017 |
+
|
| 2018 |
+
@abstractmethod
|
| 2019 |
+
def visit_extend(self, op: Extend) -> T:
|
| 2020 |
+
raise NotImplementedError
|
| 2021 |
+
|
| 2022 |
+
@abstractmethod
|
| 2023 |
+
def visit_load_global(self, op: LoadGlobal) -> T:
|
| 2024 |
+
raise NotImplementedError
|
| 2025 |
+
|
| 2026 |
+
@abstractmethod
|
| 2027 |
+
def visit_int_op(self, op: IntOp) -> T:
|
| 2028 |
+
raise NotImplementedError
|
| 2029 |
+
|
| 2030 |
+
@abstractmethod
|
| 2031 |
+
def visit_comparison_op(self, op: ComparisonOp) -> T:
|
| 2032 |
+
raise NotImplementedError
|
| 2033 |
+
|
| 2034 |
+
@abstractmethod
|
| 2035 |
+
def visit_float_op(self, op: FloatOp) -> T:
|
| 2036 |
+
raise NotImplementedError
|
| 2037 |
+
|
| 2038 |
+
@abstractmethod
|
| 2039 |
+
def visit_float_neg(self, op: FloatNeg) -> T:
|
| 2040 |
+
raise NotImplementedError
|
| 2041 |
+
|
| 2042 |
+
@abstractmethod
|
| 2043 |
+
def visit_float_comparison_op(self, op: FloatComparisonOp) -> T:
|
| 2044 |
+
raise NotImplementedError
|
| 2045 |
+
|
| 2046 |
+
@abstractmethod
|
| 2047 |
+
def visit_load_mem(self, op: LoadMem) -> T:
|
| 2048 |
+
raise NotImplementedError
|
| 2049 |
+
|
| 2050 |
+
@abstractmethod
|
| 2051 |
+
def visit_set_mem(self, op: SetMem) -> T:
|
| 2052 |
+
raise NotImplementedError
|
| 2053 |
+
|
| 2054 |
+
@abstractmethod
|
| 2055 |
+
def visit_get_element(self, op: GetElement) -> T:
|
| 2056 |
+
raise NotImplementedError
|
| 2057 |
+
|
| 2058 |
+
@abstractmethod
|
| 2059 |
+
def visit_get_element_ptr(self, op: GetElementPtr) -> T:
|
| 2060 |
+
raise NotImplementedError
|
| 2061 |
+
|
| 2062 |
+
@abstractmethod
|
| 2063 |
+
def visit_set_element(self, op: SetElement) -> T:
|
| 2064 |
+
raise NotImplementedError
|
| 2065 |
+
|
| 2066 |
+
@abstractmethod
|
| 2067 |
+
def visit_load_address(self, op: LoadAddress) -> T:
|
| 2068 |
+
raise NotImplementedError
|
| 2069 |
+
|
| 2070 |
+
@abstractmethod
|
| 2071 |
+
def visit_keep_alive(self, op: KeepAlive) -> T:
|
| 2072 |
+
raise NotImplementedError
|
| 2073 |
+
|
| 2074 |
+
@abstractmethod
|
| 2075 |
+
def visit_unborrow(self, op: Unborrow) -> T:
|
| 2076 |
+
raise NotImplementedError
|
| 2077 |
+
|
| 2078 |
+
|
| 2079 |
+
# TODO: Should the following definition live somewhere else?
|
| 2080 |
+
|
| 2081 |
+
|
| 2082 |
+
# We do a three-pass deserialization scheme in order to resolve name
|
| 2083 |
+
# references.
|
| 2084 |
+
# 1. Create an empty ClassIR for each class in an SCC.
|
| 2085 |
+
# 2. Deserialize all of the functions, which can contain references
|
| 2086 |
+
# to ClassIRs in their types
|
| 2087 |
+
# 3. Deserialize all of the classes, which contain lots of references
|
| 2088 |
+
# to the functions they contain. (And to other classes.)
|
| 2089 |
+
#
|
| 2090 |
+
# Note that this approach differs from how we deserialize ASTs in mypy itself,
|
| 2091 |
+
# where everything is deserialized in one pass then a second pass cleans up
|
| 2092 |
+
# 'cross_refs'. We don't follow that approach here because it seems to be more
|
| 2093 |
+
# code for not a lot of gain since it is easy in mypyc to identify all the objects
|
| 2094 |
+
# we might need to reference.
|
| 2095 |
+
#
|
| 2096 |
+
# Because of these references, we need to maintain maps from class
|
| 2097 |
+
# names to ClassIRs and func IDs to FuncIRs.
|
| 2098 |
+
#
|
| 2099 |
+
# These are tracked in a DeserMaps which is passed to every
|
| 2100 |
+
# deserialization function.
|
| 2101 |
+
#
|
| 2102 |
+
# (Serialization and deserialization *will* be used for incremental
|
| 2103 |
+
# compilation but so far it is not hooked up to anything.)
|
| 2104 |
+
class DeserMaps(NamedTuple):
|
| 2105 |
+
classes: dict[str, ClassIR]
|
| 2106 |
+
functions: dict[str, FuncIR]
|
micromamba_root/Lib/site-packages/mypyc/ir/pprint.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/ir/pprint.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities for pretty-printing IR in a human-readable form."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
from typing import Any, Final
|
| 8 |
+
|
| 9 |
+
from mypyc.common import short_name
|
| 10 |
+
from mypyc.ir.func_ir import FuncIR, all_values_full
|
| 11 |
+
from mypyc.ir.module_ir import ModuleIRs
|
| 12 |
+
from mypyc.ir.ops import (
|
| 13 |
+
ERR_NEVER,
|
| 14 |
+
Assign,
|
| 15 |
+
AssignMulti,
|
| 16 |
+
BasicBlock,
|
| 17 |
+
Box,
|
| 18 |
+
Branch,
|
| 19 |
+
Call,
|
| 20 |
+
CallC,
|
| 21 |
+
Cast,
|
| 22 |
+
ComparisonOp,
|
| 23 |
+
ControlOp,
|
| 24 |
+
CString,
|
| 25 |
+
DecRef,
|
| 26 |
+
Extend,
|
| 27 |
+
Float,
|
| 28 |
+
FloatComparisonOp,
|
| 29 |
+
FloatNeg,
|
| 30 |
+
FloatOp,
|
| 31 |
+
GetAttr,
|
| 32 |
+
GetElement,
|
| 33 |
+
GetElementPtr,
|
| 34 |
+
Goto,
|
| 35 |
+
IncRef,
|
| 36 |
+
InitStatic,
|
| 37 |
+
Integer,
|
| 38 |
+
IntOp,
|
| 39 |
+
KeepAlive,
|
| 40 |
+
LoadAddress,
|
| 41 |
+
LoadErrorValue,
|
| 42 |
+
LoadGlobal,
|
| 43 |
+
LoadLiteral,
|
| 44 |
+
LoadMem,
|
| 45 |
+
LoadStatic,
|
| 46 |
+
MethodCall,
|
| 47 |
+
Op,
|
| 48 |
+
OpVisitor,
|
| 49 |
+
PrimitiveOp,
|
| 50 |
+
RaiseStandardError,
|
| 51 |
+
Register,
|
| 52 |
+
Return,
|
| 53 |
+
SetAttr,
|
| 54 |
+
SetElement,
|
| 55 |
+
SetMem,
|
| 56 |
+
Truncate,
|
| 57 |
+
TupleGet,
|
| 58 |
+
TupleSet,
|
| 59 |
+
Unborrow,
|
| 60 |
+
Unbox,
|
| 61 |
+
Undef,
|
| 62 |
+
Unreachable,
|
| 63 |
+
Value,
|
| 64 |
+
)
|
| 65 |
+
from mypyc.ir.rtypes import RType, is_bool_rprimitive, is_int_rprimitive
|
| 66 |
+
|
| 67 |
+
ErrorSource = BasicBlock | Op
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class IRPrettyPrintVisitor(OpVisitor[str]):
|
| 71 |
+
"""Internal visitor that pretty-prints ops."""
|
| 72 |
+
|
| 73 |
+
def __init__(self, names: dict[Value, str]) -> None:
|
| 74 |
+
# This should contain a name for all values that are shown as
|
| 75 |
+
# registers in the output. This is not just for Register
|
| 76 |
+
# instances -- all Ops that produce values need (generated) names.
|
| 77 |
+
self.names = names
|
| 78 |
+
|
| 79 |
+
def visit_goto(self, op: Goto) -> str:
|
| 80 |
+
return self.format("goto %l", op.label)
|
| 81 |
+
|
| 82 |
+
branch_op_names: Final = {Branch.BOOL: ("%r", "bool"), Branch.IS_ERROR: ("is_error(%r)", "")}
|
| 83 |
+
|
| 84 |
+
def visit_branch(self, op: Branch) -> str:
|
| 85 |
+
fmt, typ = self.branch_op_names[op.op]
|
| 86 |
+
if op.negated:
|
| 87 |
+
fmt = f"not {fmt}"
|
| 88 |
+
|
| 89 |
+
cond = self.format(fmt, op.value)
|
| 90 |
+
tb = ""
|
| 91 |
+
if op.traceback_entry:
|
| 92 |
+
tb = " (error at %s:%d)" % op.traceback_entry
|
| 93 |
+
fmt = f"if {cond} goto %l{tb} else goto %l"
|
| 94 |
+
if typ:
|
| 95 |
+
fmt += f" :: {typ}"
|
| 96 |
+
return self.format(fmt, op.true, op.false)
|
| 97 |
+
|
| 98 |
+
def visit_return(self, op: Return) -> str:
|
| 99 |
+
return self.format("return %r", op.value)
|
| 100 |
+
|
| 101 |
+
def visit_unreachable(self, op: Unreachable) -> str:
|
| 102 |
+
return "unreachable"
|
| 103 |
+
|
| 104 |
+
def visit_assign(self, op: Assign) -> str:
|
| 105 |
+
return self.format("%r = %r", op.dest, op.src)
|
| 106 |
+
|
| 107 |
+
def visit_assign_multi(self, op: AssignMulti) -> str:
|
| 108 |
+
return self.format("%r = [%s]", op.dest, ", ".join(self.format("%r", v) for v in op.src))
|
| 109 |
+
|
| 110 |
+
def visit_load_error_value(self, op: LoadErrorValue) -> str:
|
| 111 |
+
return self.format("%r = <error> :: %s", op, op.type)
|
| 112 |
+
|
| 113 |
+
def visit_load_literal(self, op: LoadLiteral) -> str:
|
| 114 |
+
prefix = ""
|
| 115 |
+
# For values that have a potential unboxed representation, make
|
| 116 |
+
# it explicit that this is a Python object.
|
| 117 |
+
if isinstance(op.value, int):
|
| 118 |
+
prefix = "object "
|
| 119 |
+
|
| 120 |
+
rvalue = repr(op.value)
|
| 121 |
+
if isinstance(op.value, frozenset):
|
| 122 |
+
# We need to generate a string representation that won't vary
|
| 123 |
+
# run-to-run because sets are unordered, otherwise we may get
|
| 124 |
+
# spurious irbuild test failures.
|
| 125 |
+
#
|
| 126 |
+
# Sorting by the item's string representation is a bit of a
|
| 127 |
+
# hack, but it's stable and won't cause TypeErrors.
|
| 128 |
+
formatted_items = [repr(i) for i in sorted(op.value, key=str)]
|
| 129 |
+
rvalue = "frozenset({" + ", ".join(formatted_items) + "})"
|
| 130 |
+
return self.format("%r = %s%s", op, prefix, rvalue)
|
| 131 |
+
|
| 132 |
+
def visit_get_attr(self, op: GetAttr) -> str:
|
| 133 |
+
return self.format("%r = %s%r.%s", op, self.borrow_prefix(op), op.obj, op.attr)
|
| 134 |
+
|
| 135 |
+
def borrow_prefix(self, op: Op) -> str:
|
| 136 |
+
if op.is_borrowed:
|
| 137 |
+
return "borrow "
|
| 138 |
+
return ""
|
| 139 |
+
|
| 140 |
+
def visit_set_attr(self, op: SetAttr) -> str:
|
| 141 |
+
if op.is_init:
|
| 142 |
+
assert op.error_kind == ERR_NEVER
|
| 143 |
+
if op.error_kind == ERR_NEVER:
|
| 144 |
+
# Initialization and direct struct access can never fail
|
| 145 |
+
return self.format("%r.%s = %r", op.obj, op.attr, op.src)
|
| 146 |
+
else:
|
| 147 |
+
return self.format("%r.%s = %r; %r = is_error", op.obj, op.attr, op.src, op)
|
| 148 |
+
|
| 149 |
+
def visit_load_static(self, op: LoadStatic) -> str:
|
| 150 |
+
ann = f" ({repr(op.ann)})" if op.ann else ""
|
| 151 |
+
name = op.identifier
|
| 152 |
+
if op.module_name is not None:
|
| 153 |
+
name = f"{op.module_name}.{name}"
|
| 154 |
+
return self.format("%r = %s :: %s%s", op, name, op.namespace, ann)
|
| 155 |
+
|
| 156 |
+
def visit_init_static(self, op: InitStatic) -> str:
|
| 157 |
+
name = op.identifier
|
| 158 |
+
if op.module_name is not None:
|
| 159 |
+
name = f"{op.module_name}.{name}"
|
| 160 |
+
return self.format("%s = %r :: %s", name, op.value, op.namespace)
|
| 161 |
+
|
| 162 |
+
def visit_tuple_get(self, op: TupleGet) -> str:
|
| 163 |
+
return self.format("%r = %s%r[%d]", op, self.borrow_prefix(op), op.src, op.index)
|
| 164 |
+
|
| 165 |
+
def visit_tuple_set(self, op: TupleSet) -> str:
|
| 166 |
+
item_str = ", ".join(self.format("%r", item) for item in op.items)
|
| 167 |
+
return self.format("%r = (%s)", op, item_str)
|
| 168 |
+
|
| 169 |
+
def visit_inc_ref(self, op: IncRef) -> str:
|
| 170 |
+
s = self.format("inc_ref %r", op.src)
|
| 171 |
+
# TODO: Remove bool check (it's unboxed)
|
| 172 |
+
if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):
|
| 173 |
+
s += f" :: {short_name(op.src.type.name)}"
|
| 174 |
+
return s
|
| 175 |
+
|
| 176 |
+
def visit_dec_ref(self, op: DecRef) -> str:
|
| 177 |
+
s = self.format("%sdec_ref %r", "x" if op.is_xdec else "", op.src)
|
| 178 |
+
# TODO: Remove bool check (it's unboxed)
|
| 179 |
+
if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):
|
| 180 |
+
s += f" :: {short_name(op.src.type.name)}"
|
| 181 |
+
return s
|
| 182 |
+
|
| 183 |
+
def visit_call(self, op: Call) -> str:
|
| 184 |
+
args = ", ".join(self.format("%r", arg) for arg in op.args)
|
| 185 |
+
# TODO: Display long name?
|
| 186 |
+
short_name = op.fn.shortname
|
| 187 |
+
s = f"{short_name}({args})"
|
| 188 |
+
if not op.is_void:
|
| 189 |
+
s = self.format("%r = ", op) + s
|
| 190 |
+
return s
|
| 191 |
+
|
| 192 |
+
def visit_method_call(self, op: MethodCall) -> str:
|
| 193 |
+
args = ", ".join(self.format("%r", arg) for arg in op.args)
|
| 194 |
+
s = self.format("%r.%s(%s)", op.obj, op.method, args)
|
| 195 |
+
if not op.is_void:
|
| 196 |
+
s = self.format("%r = ", op) + s
|
| 197 |
+
return s
|
| 198 |
+
|
| 199 |
+
def visit_cast(self, op: Cast) -> str:
|
| 200 |
+
if op.is_unchecked:
|
| 201 |
+
prefix = "unchecked "
|
| 202 |
+
else:
|
| 203 |
+
prefix = ""
|
| 204 |
+
return self.format(
|
| 205 |
+
"%r = %s%scast(%s, %r)", op, prefix, self.borrow_prefix(op), op.type, op.src
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
def visit_box(self, op: Box) -> str:
|
| 209 |
+
return self.format("%r = box(%s, %r)", op, op.src.type, op.src)
|
| 210 |
+
|
| 211 |
+
def visit_unbox(self, op: Unbox) -> str:
|
| 212 |
+
return self.format("%r = unbox(%s, %r)", op, op.type, op.src)
|
| 213 |
+
|
| 214 |
+
def visit_raise_standard_error(self, op: RaiseStandardError) -> str:
|
| 215 |
+
if op.value is not None:
|
| 216 |
+
if isinstance(op.value, str):
|
| 217 |
+
return self.format("%r = raise %s(%s)", op, op.class_name, repr(op.value))
|
| 218 |
+
elif isinstance(op.value, Value):
|
| 219 |
+
return self.format("%r = raise %s(%r)", op, op.class_name, op.value)
|
| 220 |
+
else:
|
| 221 |
+
assert False, "value type must be either str or Value"
|
| 222 |
+
else:
|
| 223 |
+
return self.format("%r = raise %s", op, op.class_name)
|
| 224 |
+
|
| 225 |
+
def visit_call_c(self, op: CallC) -> str:
|
| 226 |
+
args_str = ", ".join(self.format("%r", arg) for arg in op.args)
|
| 227 |
+
if op.is_void:
|
| 228 |
+
return self.format("%s(%s)", op.function_name, args_str)
|
| 229 |
+
else:
|
| 230 |
+
return self.format("%r = %s(%s)", op, op.function_name, args_str)
|
| 231 |
+
|
| 232 |
+
def visit_primitive_op(self, op: PrimitiveOp) -> str:
|
| 233 |
+
args_str = ", ".join(self.format("%r", arg) for arg in op.args)
|
| 234 |
+
if op.is_void:
|
| 235 |
+
return self.format("%s %s", op.desc.name, args_str)
|
| 236 |
+
else:
|
| 237 |
+
return self.format("%r = %s %s", op, op.desc.name, args_str)
|
| 238 |
+
|
| 239 |
+
def visit_truncate(self, op: Truncate) -> str:
|
| 240 |
+
return self.format("%r = truncate %r: %t to %t", op, op.src, op.src_type, op.type)
|
| 241 |
+
|
| 242 |
+
def visit_extend(self, op: Extend) -> str:
|
| 243 |
+
if op.signed:
|
| 244 |
+
extra = " signed"
|
| 245 |
+
else:
|
| 246 |
+
extra = ""
|
| 247 |
+
return self.format("%r = extend%s %r: %t to %t", op, extra, op.src, op.src_type, op.type)
|
| 248 |
+
|
| 249 |
+
def visit_load_global(self, op: LoadGlobal) -> str:
|
| 250 |
+
ann = f" ({repr(op.ann)})" if op.ann else ""
|
| 251 |
+
return self.format("%r = load_global %s :: static%s", op, op.identifier, ann)
|
| 252 |
+
|
| 253 |
+
def visit_int_op(self, op: IntOp) -> str:
|
| 254 |
+
return self.format("%r = %r %s %r", op, op.lhs, IntOp.op_str[op.op], op.rhs)
|
| 255 |
+
|
| 256 |
+
def visit_comparison_op(self, op: ComparisonOp) -> str:
|
| 257 |
+
if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE):
|
| 258 |
+
sign_format = " :: signed"
|
| 259 |
+
elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE):
|
| 260 |
+
sign_format = " :: unsigned"
|
| 261 |
+
else:
|
| 262 |
+
sign_format = ""
|
| 263 |
+
return self.format(
|
| 264 |
+
"%r = %r %s %r%s", op, op.lhs, ComparisonOp.op_str[op.op], op.rhs, sign_format
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
def visit_float_op(self, op: FloatOp) -> str:
|
| 268 |
+
return self.format("%r = %r %s %r", op, op.lhs, FloatOp.op_str[op.op], op.rhs)
|
| 269 |
+
|
| 270 |
+
def visit_float_neg(self, op: FloatNeg) -> str:
|
| 271 |
+
return self.format("%r = -%r", op, op.src)
|
| 272 |
+
|
| 273 |
+
def visit_float_comparison_op(self, op: FloatComparisonOp) -> str:
|
| 274 |
+
return self.format("%r = %r %s %r", op, op.lhs, op.op_str[op.op], op.rhs)
|
| 275 |
+
|
| 276 |
+
def visit_load_mem(self, op: LoadMem) -> str:
|
| 277 |
+
return self.format(
|
| 278 |
+
"%r = %sload_mem %r :: %t*", op, self.borrow_prefix(op), op.src, op.type
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
def visit_set_mem(self, op: SetMem) -> str:
|
| 282 |
+
return self.format("set_mem %r, %r :: %t*", op.dest, op.src, op.dest_type)
|
| 283 |
+
|
| 284 |
+
def visit_get_element(self, op: GetElement) -> str:
|
| 285 |
+
return self.format("%r = %r.%s", op, op.src, op.field)
|
| 286 |
+
|
| 287 |
+
def visit_get_element_ptr(self, op: GetElementPtr) -> str:
|
| 288 |
+
return self.format("%r = get_element_ptr %r %s :: %t", op, op.src, op.field, op.src_type)
|
| 289 |
+
|
| 290 |
+
def visit_set_element(self, op: SetElement) -> str:
|
| 291 |
+
return self.format("%r = set_element %r, %s, %r", op, op.src, op.field, op.item)
|
| 292 |
+
|
| 293 |
+
def visit_load_address(self, op: LoadAddress) -> str:
|
| 294 |
+
if isinstance(op.src, Register):
|
| 295 |
+
return self.format("%r = load_address %r", op, op.src)
|
| 296 |
+
elif isinstance(op.src, LoadStatic):
|
| 297 |
+
name = op.src.identifier
|
| 298 |
+
if op.src.module_name is not None:
|
| 299 |
+
name = f"{op.src.module_name}.{name}"
|
| 300 |
+
return self.format("%r = load_address %s :: %s", op, name, op.src.namespace)
|
| 301 |
+
else:
|
| 302 |
+
return self.format("%r = load_address %s", op, op.src)
|
| 303 |
+
|
| 304 |
+
def visit_keep_alive(self, op: KeepAlive) -> str:
|
| 305 |
+
if op.steal:
|
| 306 |
+
steal = "steal "
|
| 307 |
+
else:
|
| 308 |
+
steal = ""
|
| 309 |
+
return self.format(
|
| 310 |
+
"keep_alive {}{}".format(steal, ", ".join(self.format("%r", v) for v in op.src))
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
def visit_unborrow(self, op: Unborrow) -> str:
|
| 314 |
+
return self.format("%r = unborrow %r", op, op.src)
|
| 315 |
+
|
| 316 |
+
# Helpers
|
| 317 |
+
|
| 318 |
+
def format(self, fmt: str, *args: Any) -> str:
|
| 319 |
+
"""Helper for formatting strings.
|
| 320 |
+
|
| 321 |
+
These format sequences are supported in fmt:
|
| 322 |
+
|
| 323 |
+
%s: arbitrary object converted to string using str()
|
| 324 |
+
%r: name of IR value/register
|
| 325 |
+
%d: int
|
| 326 |
+
%f: float
|
| 327 |
+
%l: BasicBlock (formatted as label 'Ln')
|
| 328 |
+
%t: RType
|
| 329 |
+
"""
|
| 330 |
+
result = []
|
| 331 |
+
i = 0
|
| 332 |
+
arglist = list(args)
|
| 333 |
+
while i < len(fmt):
|
| 334 |
+
n = fmt.find("%", i)
|
| 335 |
+
if n < 0:
|
| 336 |
+
n = len(fmt)
|
| 337 |
+
result.append(fmt[i:n])
|
| 338 |
+
if n < len(fmt):
|
| 339 |
+
typespec = fmt[n + 1]
|
| 340 |
+
arg = arglist.pop(0)
|
| 341 |
+
if typespec == "r":
|
| 342 |
+
# Register/value
|
| 343 |
+
assert isinstance(arg, Value)
|
| 344 |
+
if isinstance(arg, Integer):
|
| 345 |
+
result.append(str(arg.value))
|
| 346 |
+
elif isinstance(arg, Float):
|
| 347 |
+
result.append(repr(arg.value))
|
| 348 |
+
elif isinstance(arg, CString):
|
| 349 |
+
result.append(f"CString({arg.value!r})")
|
| 350 |
+
elif isinstance(arg, Undef):
|
| 351 |
+
result.append(f"undef {arg.type.name}")
|
| 352 |
+
else:
|
| 353 |
+
result.append(self.names[arg])
|
| 354 |
+
elif typespec == "d":
|
| 355 |
+
# Integer
|
| 356 |
+
result.append("%d" % arg)
|
| 357 |
+
elif typespec == "f":
|
| 358 |
+
# Float
|
| 359 |
+
result.append("%f" % arg)
|
| 360 |
+
elif typespec == "l":
|
| 361 |
+
# Basic block (label)
|
| 362 |
+
assert isinstance(arg, BasicBlock)
|
| 363 |
+
result.append("L%s" % arg.label)
|
| 364 |
+
elif typespec == "t":
|
| 365 |
+
# RType
|
| 366 |
+
assert isinstance(arg, RType)
|
| 367 |
+
result.append(arg.name)
|
| 368 |
+
elif typespec == "s":
|
| 369 |
+
# String
|
| 370 |
+
result.append(str(arg))
|
| 371 |
+
else:
|
| 372 |
+
raise ValueError(f"Invalid format sequence %{typespec}")
|
| 373 |
+
i = n + 2
|
| 374 |
+
else:
|
| 375 |
+
i = n
|
| 376 |
+
return "".join(result)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def format_registers(func_ir: FuncIR, names: dict[Value, str]) -> list[str]:
|
| 380 |
+
result = []
|
| 381 |
+
i = 0
|
| 382 |
+
regs = all_values_full(func_ir.arg_regs, func_ir.blocks)
|
| 383 |
+
while i < len(regs):
|
| 384 |
+
i0 = i
|
| 385 |
+
group = [names[regs[i0]]]
|
| 386 |
+
while i + 1 < len(regs) and regs[i + 1].type == regs[i0].type:
|
| 387 |
+
i += 1
|
| 388 |
+
group.append(names[regs[i]])
|
| 389 |
+
i += 1
|
| 390 |
+
result.append("{} :: {}".format(", ".join(group), regs[i0].type))
|
| 391 |
+
return result
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def format_blocks(
|
| 395 |
+
blocks: list[BasicBlock],
|
| 396 |
+
names: dict[Value, str],
|
| 397 |
+
source_to_error: dict[ErrorSource, list[str]],
|
| 398 |
+
) -> list[str]:
|
| 399 |
+
"""Format a list of IR basic blocks into a human-readable form."""
|
| 400 |
+
# First label all of the blocks
|
| 401 |
+
for i, block in enumerate(blocks):
|
| 402 |
+
block.label = i
|
| 403 |
+
|
| 404 |
+
handler_map: dict[BasicBlock, list[BasicBlock]] = {}
|
| 405 |
+
for b in blocks:
|
| 406 |
+
if b.error_handler:
|
| 407 |
+
handler_map.setdefault(b.error_handler, []).append(b)
|
| 408 |
+
|
| 409 |
+
visitor = IRPrettyPrintVisitor(names)
|
| 410 |
+
|
| 411 |
+
lines = []
|
| 412 |
+
for i, block in enumerate(blocks):
|
| 413 |
+
handler_msg = ""
|
| 414 |
+
if block in handler_map:
|
| 415 |
+
labels = sorted("L%d" % b.label for b in handler_map[block])
|
| 416 |
+
handler_msg = " (handler for {})".format(", ".join(labels))
|
| 417 |
+
|
| 418 |
+
lines.append("L%d:%s" % (block.label, handler_msg))
|
| 419 |
+
if block in source_to_error:
|
| 420 |
+
for error in source_to_error[block]:
|
| 421 |
+
lines.append(f" ERROR: {error}")
|
| 422 |
+
ops = block.ops
|
| 423 |
+
if (
|
| 424 |
+
isinstance(ops[-1], Goto)
|
| 425 |
+
and i + 1 < len(blocks)
|
| 426 |
+
and ops[-1].label == blocks[i + 1]
|
| 427 |
+
and not source_to_error.get(ops[-1], [])
|
| 428 |
+
):
|
| 429 |
+
# Hide the last goto if it just goes to the next basic block,
|
| 430 |
+
# and there are no assocatiated errors with the op.
|
| 431 |
+
ops = ops[:-1]
|
| 432 |
+
for op in ops:
|
| 433 |
+
line = " " + op.accept(visitor)
|
| 434 |
+
lines.append(line)
|
| 435 |
+
if op in source_to_error:
|
| 436 |
+
first = len(lines) - 1
|
| 437 |
+
# Use emojis to highlight the error
|
| 438 |
+
for error in source_to_error[op]:
|
| 439 |
+
lines.append(f" \U0001f446 ERROR: {error}")
|
| 440 |
+
lines[first] = " \U0000274c " + lines[first][4:]
|
| 441 |
+
|
| 442 |
+
if not isinstance(block.ops[-1], (Goto, Branch, Return, Unreachable)):
|
| 443 |
+
# Each basic block needs to exit somewhere.
|
| 444 |
+
lines.append(" [MISSING BLOCK EXIT OPCODE]")
|
| 445 |
+
return lines
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def format_func(fn: FuncIR, errors: Sequence[tuple[ErrorSource, str]] = ()) -> list[str]:
|
| 449 |
+
lines = []
|
| 450 |
+
cls_prefix = fn.class_name + "." if fn.class_name else ""
|
| 451 |
+
lines.append(
|
| 452 |
+
"def {}{}({}):".format(cls_prefix, fn.name, ", ".join(arg.name for arg in fn.args))
|
| 453 |
+
)
|
| 454 |
+
names = generate_names_for_ir(fn.arg_regs, fn.blocks)
|
| 455 |
+
for line in format_registers(fn, names):
|
| 456 |
+
lines.append(" " + line)
|
| 457 |
+
|
| 458 |
+
source_to_error = defaultdict(list)
|
| 459 |
+
for source, error in errors:
|
| 460 |
+
source_to_error[source].append(error)
|
| 461 |
+
|
| 462 |
+
code = format_blocks(fn.blocks, names, source_to_error)
|
| 463 |
+
lines.extend(code)
|
| 464 |
+
return lines
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def format_modules(modules: ModuleIRs) -> list[str]:
|
| 468 |
+
ops = []
|
| 469 |
+
for module in modules.values():
|
| 470 |
+
for fn in module.functions:
|
| 471 |
+
ops.extend(format_func(fn))
|
| 472 |
+
ops.append("")
|
| 473 |
+
return ops
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def generate_names_for_ir(args: list[Register], blocks: list[BasicBlock]) -> dict[Value, str]:
|
| 477 |
+
"""Generate unique names for IR values.
|
| 478 |
+
|
| 479 |
+
Give names such as 'r5' to temp values in IR which are useful when
|
| 480 |
+
pretty-printing or generating C. Ensure generated names are unique.
|
| 481 |
+
"""
|
| 482 |
+
names: dict[Value, str] = {}
|
| 483 |
+
used_names = set()
|
| 484 |
+
|
| 485 |
+
temp_index = 0
|
| 486 |
+
|
| 487 |
+
for arg in args:
|
| 488 |
+
names[arg] = arg.name
|
| 489 |
+
used_names.add(arg.name)
|
| 490 |
+
|
| 491 |
+
for block in blocks:
|
| 492 |
+
for op in block.ops:
|
| 493 |
+
values = []
|
| 494 |
+
|
| 495 |
+
for source in op.sources():
|
| 496 |
+
if source not in names:
|
| 497 |
+
values.append(source)
|
| 498 |
+
|
| 499 |
+
if isinstance(op, (Assign, AssignMulti)):
|
| 500 |
+
values.append(op.dest)
|
| 501 |
+
elif isinstance(op, ControlOp) or op.is_void:
|
| 502 |
+
continue
|
| 503 |
+
elif op not in names:
|
| 504 |
+
values.append(op)
|
| 505 |
+
|
| 506 |
+
for value in values:
|
| 507 |
+
if value in names:
|
| 508 |
+
continue
|
| 509 |
+
if isinstance(value, Register) and value.name:
|
| 510 |
+
name = value.name
|
| 511 |
+
elif isinstance(value, (Integer, Float, Undef)):
|
| 512 |
+
continue
|
| 513 |
+
else:
|
| 514 |
+
name = "r%d" % temp_index
|
| 515 |
+
temp_index += 1
|
| 516 |
+
|
| 517 |
+
# Append _2, _3, ... if needed to make the name unique.
|
| 518 |
+
if name in used_names:
|
| 519 |
+
n = 2
|
| 520 |
+
while True:
|
| 521 |
+
candidate = "%s_%d" % (name, n)
|
| 522 |
+
if candidate not in used_names:
|
| 523 |
+
name = candidate
|
| 524 |
+
break
|
| 525 |
+
n += 1
|
| 526 |
+
|
| 527 |
+
names[value] = name
|
| 528 |
+
used_names.add(name)
|
| 529 |
+
|
| 530 |
+
return names
|
micromamba_root/Lib/site-packages/mypyc/ir/rtypes.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/ir/rtypes.py
ADDED
|
@@ -0,0 +1,1444 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_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=(LIBRT_STRINGS,))
|
| 541 |
+
for name in [
|
| 542 |
+
"librt.internal.WriteBuffer",
|
| 543 |
+
"librt.internal.ReadBuffer",
|
| 544 |
+
"librt.strings.BytesWriter",
|
| 545 |
+
"librt.strings.StringWriter",
|
| 546 |
+
]
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
bytes_writer_rprimitive: Final = KNOWN_NATIVE_TYPES["librt.strings.BytesWriter"]
|
| 550 |
+
string_writer_rprimitive: Final = KNOWN_NATIVE_TYPES["librt.strings.StringWriter"]
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def is_native_rprimitive(rtype: RType) -> bool:
|
| 554 |
+
return isinstance(rtype, RPrimitive) and rtype.name in KNOWN_NATIVE_TYPES
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def is_tagged(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 558 |
+
return rtype is int_rprimitive or rtype is short_int_rprimitive
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def is_any_int(rtype: RType) -> bool:
|
| 562 |
+
return is_tagged(rtype) or is_int32_rprimitive(rtype) or is_int64_rprimitive(rtype)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def is_int_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 566 |
+
return rtype is int_rprimitive
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def is_short_int_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 570 |
+
return rtype is short_int_rprimitive
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def is_int16_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 574 |
+
return rtype is int16_rprimitive
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def is_int32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 578 |
+
return rtype is int32_rprimitive or (
|
| 579 |
+
rtype is c_pyssize_t_rprimitive and rtype._ctype == "int32_t"
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def is_int64_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 584 |
+
return rtype is int64_rprimitive or (
|
| 585 |
+
rtype is c_pyssize_t_rprimitive and rtype._ctype == "int64_t"
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def is_fixed_width_rtype(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 590 |
+
return (
|
| 591 |
+
is_int64_rprimitive(rtype)
|
| 592 |
+
or is_int32_rprimitive(rtype)
|
| 593 |
+
or is_int16_rprimitive(rtype)
|
| 594 |
+
or is_uint8_rprimitive(rtype)
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def is_uint8_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 599 |
+
return rtype is uint8_rprimitive
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def is_uint32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 603 |
+
return rtype is uint32_rprimitive
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def is_uint64_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 607 |
+
return rtype is uint64_rprimitive
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def is_c_py_ssize_t_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 611 |
+
return rtype is c_pyssize_t_rprimitive
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def is_pointer_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 615 |
+
return rtype is pointer_rprimitive
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def is_float_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 619 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.float"
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def is_bool_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 623 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bool"
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def is_bit_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 627 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "bit"
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def is_bool_or_bit_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 631 |
+
return is_bool_rprimitive(rtype) or is_bit_rprimitive(rtype)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def is_object_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 635 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.object"
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def is_none_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 639 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.None"
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
def is_list_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 643 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.list"
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def is_dict_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 647 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.dict"
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
def is_set_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 651 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.set"
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def is_frozenset_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 655 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.frozenset"
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def is_str_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 659 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.str"
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def is_bytes_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 663 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bytes"
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def is_bytearray_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 667 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bytearray"
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def is_tuple_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 671 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.tuple"
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def is_range_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 675 |
+
return isinstance(rtype, RPrimitive) and rtype.name == "builtins.range"
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def is_sequence_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 679 |
+
return isinstance(rtype, RPrimitive) and (
|
| 680 |
+
is_list_rprimitive(rtype)
|
| 681 |
+
or is_tuple_rprimitive(rtype)
|
| 682 |
+
or is_str_rprimitive(rtype)
|
| 683 |
+
or is_bytes_rprimitive(rtype)
|
| 684 |
+
or is_bytearray_rprimitive(rtype)
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def is_immutable_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
|
| 689 |
+
return (
|
| 690 |
+
is_str_rprimitive(rtype)
|
| 691 |
+
or is_bytes_rprimitive(rtype)
|
| 692 |
+
or is_tuple_rprimitive(rtype)
|
| 693 |
+
or is_frozenset_rprimitive(rtype)
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
class TupleNameVisitor(RTypeVisitor[str]):
|
| 698 |
+
"""Produce a tuple name based on the concrete representations of types."""
|
| 699 |
+
|
| 700 |
+
def visit_rinstance(self, t: RInstance) -> str:
|
| 701 |
+
return "O"
|
| 702 |
+
|
| 703 |
+
def visit_rvec(self, t: RVec) -> str:
|
| 704 |
+
if isinstance(t.item_type, RVec):
|
| 705 |
+
# All nested vecs share a representation
|
| 706 |
+
return "Vv"
|
| 707 |
+
return "V" + t.item_type.accept(self)
|
| 708 |
+
|
| 709 |
+
def visit_runion(self, t: RUnion) -> str:
|
| 710 |
+
return "O"
|
| 711 |
+
|
| 712 |
+
def visit_rprimitive(self, t: RPrimitive) -> str:
|
| 713 |
+
if t._ctype == "CPyTagged":
|
| 714 |
+
return "I"
|
| 715 |
+
elif t._ctype == "char":
|
| 716 |
+
return "C"
|
| 717 |
+
elif t._ctype == "int64_t":
|
| 718 |
+
return "8" # "8 byte integer"
|
| 719 |
+
elif t._ctype == "int32_t":
|
| 720 |
+
return "4" # "4 byte integer"
|
| 721 |
+
elif t._ctype == "int16_t":
|
| 722 |
+
return "2" # "2 byte integer"
|
| 723 |
+
elif t._ctype == "uint8_t":
|
| 724 |
+
return "U1" # "1 byte unsigned integer"
|
| 725 |
+
elif t._ctype == "double":
|
| 726 |
+
return "F"
|
| 727 |
+
assert not t.is_unboxed, f"{t} unexpected unboxed type"
|
| 728 |
+
return "O"
|
| 729 |
+
|
| 730 |
+
def visit_rtuple(self, t: RTuple) -> str:
|
| 731 |
+
parts = [elem.accept(self) for elem in t.types]
|
| 732 |
+
return "T{}{}".format(len(parts), "".join(parts))
|
| 733 |
+
|
| 734 |
+
def visit_rstruct(self, t: RStruct) -> str:
|
| 735 |
+
if t.name == "VecNestedBufItem":
|
| 736 |
+
return "Vi"
|
| 737 |
+
assert False, "RStruct not supported in tuple"
|
| 738 |
+
|
| 739 |
+
def visit_rarray(self, t: RArray) -> str:
|
| 740 |
+
assert False, "RArray not supported in tuple"
|
| 741 |
+
|
| 742 |
+
def visit_rvoid(self, t: RVoid) -> str:
|
| 743 |
+
assert False, "rvoid in tuple?"
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
@final
|
| 747 |
+
class RTuple(RType):
|
| 748 |
+
"""Fixed-length unboxed tuple (represented as a C struct).
|
| 749 |
+
|
| 750 |
+
These are used to represent mypy TupleType values (fixed-length
|
| 751 |
+
Python tuples). Since this is unboxed, the identity of a tuple
|
| 752 |
+
object is not preserved within compiled code. If the identity of a
|
| 753 |
+
tuple is important, or there is a need to have multiple references
|
| 754 |
+
to a single tuple object, a variable-length tuple should be used
|
| 755 |
+
(tuple_rprimitive or Tuple[T, ...] with explicit '...'), as they
|
| 756 |
+
are boxed.
|
| 757 |
+
|
| 758 |
+
These aren't immutable. However, user code won't be able to mutate
|
| 759 |
+
individual tuple items.
|
| 760 |
+
"""
|
| 761 |
+
|
| 762 |
+
is_unboxed = True
|
| 763 |
+
|
| 764 |
+
def __init__(self, types: list[RType]) -> None:
|
| 765 |
+
self.name = "tuple"
|
| 766 |
+
self.types = tuple(types)
|
| 767 |
+
self.is_refcounted = any(t.is_refcounted for t in self.types)
|
| 768 |
+
# Generate a unique id which is used in naming corresponding C identifiers.
|
| 769 |
+
# This is necessary since C does not have anonymous structural type equivalence
|
| 770 |
+
# in the same way python can just assign a Tuple[int, bool] to a Tuple[int, bool].
|
| 771 |
+
self.unique_id = self.accept(TupleNameVisitor())
|
| 772 |
+
# Nominally the max c length is 31 chars, but I'm not honestly worried about this.
|
| 773 |
+
self.struct_name = f"tuple_{self.unique_id}"
|
| 774 |
+
self._ctype = f"{self.struct_name}"
|
| 775 |
+
self.error_overlap = all(t.error_overlap for t in self.types) and bool(self.types)
|
| 776 |
+
|
| 777 |
+
def accept(self, visitor: RTypeVisitor[T]) -> T:
|
| 778 |
+
return visitor.visit_rtuple(self)
|
| 779 |
+
|
| 780 |
+
@property
|
| 781 |
+
def may_be_immortal(self) -> bool:
|
| 782 |
+
return False
|
| 783 |
+
|
| 784 |
+
def __str__(self) -> str:
|
| 785 |
+
return "tuple[%s]" % ", ".join(str(typ) for typ in self.types)
|
| 786 |
+
|
| 787 |
+
def __repr__(self) -> str:
|
| 788 |
+
return "<RTuple %s>" % ", ".join(repr(typ) for typ in self.types)
|
| 789 |
+
|
| 790 |
+
def __eq__(self, other: object) -> TypeGuard[RTuple]:
|
| 791 |
+
return isinstance(other, RTuple) and self.types == other.types
|
| 792 |
+
|
| 793 |
+
def __hash__(self) -> int:
|
| 794 |
+
return hash((self.name, self.types))
|
| 795 |
+
|
| 796 |
+
def serialize(self) -> JsonDict:
|
| 797 |
+
types = [x.serialize() for x in self.types]
|
| 798 |
+
return {".class": "RTuple", "types": types}
|
| 799 |
+
|
| 800 |
+
@classmethod
|
| 801 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RTuple:
|
| 802 |
+
types = [deserialize_type(t, ctx) for t in data["types"]]
|
| 803 |
+
return RTuple(types)
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
# Exception tuple: (exception class, exception instance, traceback object)
|
| 807 |
+
exc_rtuple = RTuple([object_rprimitive, object_rprimitive, object_rprimitive])
|
| 808 |
+
|
| 809 |
+
# Dictionary iterator tuple: (should continue, internal offset, key, value)
|
| 810 |
+
# See mypyc.irbuild.for_helpers.ForDictionaryCommon for more details.
|
| 811 |
+
dict_next_rtuple_pair = RTuple(
|
| 812 |
+
[bool_rprimitive, short_int_rprimitive, object_rprimitive, object_rprimitive]
|
| 813 |
+
)
|
| 814 |
+
# Same as above but just for key or value.
|
| 815 |
+
dict_next_rtuple_single = RTuple([bool_rprimitive, short_int_rprimitive, object_rprimitive])
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def compute_rtype_alignment(typ: RType) -> int:
|
| 819 |
+
"""Compute alignment of a given type based on platform alignment rule"""
|
| 820 |
+
platform_alignment = PLATFORM_SIZE
|
| 821 |
+
if isinstance(typ, RPrimitive):
|
| 822 |
+
return typ.size
|
| 823 |
+
elif isinstance(typ, RInstance):
|
| 824 |
+
return platform_alignment
|
| 825 |
+
elif isinstance(typ, RUnion):
|
| 826 |
+
return platform_alignment
|
| 827 |
+
elif isinstance(typ, RArray):
|
| 828 |
+
return compute_rtype_alignment(typ.item_type)
|
| 829 |
+
else:
|
| 830 |
+
if isinstance(typ, RTuple):
|
| 831 |
+
items = list(typ.types)
|
| 832 |
+
elif isinstance(typ, RStruct):
|
| 833 |
+
items = typ.types
|
| 834 |
+
else:
|
| 835 |
+
assert False, "invalid rtype for computing alignment"
|
| 836 |
+
max_alignment = max(compute_rtype_alignment(item) for item in items)
|
| 837 |
+
return max_alignment
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
def compute_rtype_size(typ: RType) -> int:
|
| 841 |
+
"""Compute unaligned size of rtype"""
|
| 842 |
+
if isinstance(typ, RPrimitive):
|
| 843 |
+
return typ.size
|
| 844 |
+
elif isinstance(typ, RTuple):
|
| 845 |
+
return compute_aligned_offsets_and_size(list(typ.types))[1]
|
| 846 |
+
elif isinstance(typ, RUnion):
|
| 847 |
+
return PLATFORM_SIZE
|
| 848 |
+
elif isinstance(typ, RStruct):
|
| 849 |
+
return compute_aligned_offsets_and_size(typ.types)[1]
|
| 850 |
+
elif isinstance(typ, RInstance):
|
| 851 |
+
return PLATFORM_SIZE
|
| 852 |
+
elif isinstance(typ, RArray):
|
| 853 |
+
alignment = compute_rtype_alignment(typ)
|
| 854 |
+
aligned_size = (compute_rtype_size(typ.item_type) + (alignment - 1)) & ~(alignment - 1)
|
| 855 |
+
return aligned_size * typ.length
|
| 856 |
+
else:
|
| 857 |
+
assert False, "invalid rtype for computing size"
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def compute_aligned_offsets_and_size(types: list[RType]) -> tuple[list[int], int]:
|
| 861 |
+
"""Compute offsets and total size of a list of types after alignment
|
| 862 |
+
|
| 863 |
+
Note that the types argument are types of values that are stored
|
| 864 |
+
sequentially with platform default alignment.
|
| 865 |
+
"""
|
| 866 |
+
unaligned_sizes = [compute_rtype_size(typ) for typ in types]
|
| 867 |
+
alignments = [compute_rtype_alignment(typ) for typ in types]
|
| 868 |
+
|
| 869 |
+
current_offset = 0
|
| 870 |
+
offsets = []
|
| 871 |
+
final_size = 0
|
| 872 |
+
for i in range(len(unaligned_sizes)):
|
| 873 |
+
offsets.append(current_offset)
|
| 874 |
+
if i + 1 < len(unaligned_sizes):
|
| 875 |
+
cur_size = unaligned_sizes[i]
|
| 876 |
+
current_offset += cur_size
|
| 877 |
+
next_alignment = alignments[i + 1]
|
| 878 |
+
# compute aligned offset,
|
| 879 |
+
# check https://en.wikipedia.org/wiki/Data_structure_alignment for more information
|
| 880 |
+
current_offset = (current_offset + (next_alignment - 1)) & -next_alignment
|
| 881 |
+
else:
|
| 882 |
+
struct_alignment = max(alignments)
|
| 883 |
+
final_size = current_offset + unaligned_sizes[i]
|
| 884 |
+
final_size = (final_size + (struct_alignment - 1)) & -struct_alignment
|
| 885 |
+
return offsets, final_size
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
@final
|
| 889 |
+
class RStruct(RType):
|
| 890 |
+
"""C struct type"""
|
| 891 |
+
|
| 892 |
+
def __init__(self, name: str, names: list[str], types: list[RType]) -> None:
|
| 893 |
+
self.name = name
|
| 894 |
+
self.names = names
|
| 895 |
+
self.types = types
|
| 896 |
+
self.is_refcounted = any(t.is_refcounted for t in self.types)
|
| 897 |
+
|
| 898 |
+
# generate dummy names
|
| 899 |
+
if len(self.names) < len(self.types):
|
| 900 |
+
for i in range(len(self.types) - len(self.names)):
|
| 901 |
+
self.names.append("_item" + str(i))
|
| 902 |
+
self.offsets, self.size = compute_aligned_offsets_and_size(types)
|
| 903 |
+
self._ctype = name
|
| 904 |
+
|
| 905 |
+
def field_type(self, name: str) -> RType:
|
| 906 |
+
for n, t in zip(self.names, self.types):
|
| 907 |
+
if n == name:
|
| 908 |
+
return t
|
| 909 |
+
assert False, f"{self.name} has no field '{name}'"
|
| 910 |
+
|
| 911 |
+
def accept(self, visitor: RTypeVisitor[T]) -> T:
|
| 912 |
+
return visitor.visit_rstruct(self)
|
| 913 |
+
|
| 914 |
+
@property
|
| 915 |
+
def may_be_immortal(self) -> bool:
|
| 916 |
+
return False
|
| 917 |
+
|
| 918 |
+
def __str__(self) -> str:
|
| 919 |
+
# if not tuple(unnamed structs)
|
| 920 |
+
return "{}{{{}}}".format(
|
| 921 |
+
self.name,
|
| 922 |
+
", ".join(name + ":" + str(typ) for name, typ in zip(self.names, self.types)),
|
| 923 |
+
)
|
| 924 |
+
|
| 925 |
+
def __repr__(self) -> str:
|
| 926 |
+
return "<RStruct {}{{{}}}>".format(
|
| 927 |
+
self.name,
|
| 928 |
+
", ".join(name + ":" + repr(typ) for name, typ in zip(self.names, self.types)),
|
| 929 |
+
)
|
| 930 |
+
|
| 931 |
+
def __eq__(self, other: object) -> TypeGuard[RStruct]:
|
| 932 |
+
return (
|
| 933 |
+
isinstance(other, RStruct)
|
| 934 |
+
and self.name == other.name
|
| 935 |
+
and self.names == other.names
|
| 936 |
+
and self.types == other.types
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
def __hash__(self) -> int:
|
| 940 |
+
return hash((self.name, tuple(self.names), tuple(self.types)))
|
| 941 |
+
|
| 942 |
+
def serialize(self) -> JsonDict:
|
| 943 |
+
assert False
|
| 944 |
+
|
| 945 |
+
@classmethod
|
| 946 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RStruct:
|
| 947 |
+
assert False
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
@final
|
| 951 |
+
class RInstance(RType):
|
| 952 |
+
"""Instance of user-defined class (compiled to C extension class).
|
| 953 |
+
|
| 954 |
+
The runtime representation is 'PyObject *', and these are always
|
| 955 |
+
boxed and thus reference-counted.
|
| 956 |
+
|
| 957 |
+
These support fast method calls and fast attribute access using
|
| 958 |
+
vtables, and they usually use a dict-free, struct-based
|
| 959 |
+
representation of attributes. Method calls and attribute access
|
| 960 |
+
can skip the vtable if we know that there is no overriding.
|
| 961 |
+
|
| 962 |
+
These are also sometimes called 'native' types, since these have
|
| 963 |
+
the most efficient representation and ops (along with certain
|
| 964 |
+
RPrimitive types and RTuple).
|
| 965 |
+
"""
|
| 966 |
+
|
| 967 |
+
is_unboxed = False
|
| 968 |
+
|
| 969 |
+
def __init__(self, class_ir: ClassIR) -> None:
|
| 970 |
+
# name is used for formatting the name in messages and debug output
|
| 971 |
+
# so we want the fullname for precision.
|
| 972 |
+
self.name = class_ir.fullname
|
| 973 |
+
self.class_ir = class_ir
|
| 974 |
+
self._ctype = "PyObject *"
|
| 975 |
+
|
| 976 |
+
def accept(self, visitor: RTypeVisitor[T]) -> T:
|
| 977 |
+
return visitor.visit_rinstance(self)
|
| 978 |
+
|
| 979 |
+
@property
|
| 980 |
+
def may_be_immortal(self) -> bool:
|
| 981 |
+
return False
|
| 982 |
+
|
| 983 |
+
def struct_name(self, names: NameGenerator) -> str:
|
| 984 |
+
return self.class_ir.struct_name(names)
|
| 985 |
+
|
| 986 |
+
def getter_index(self, name: str) -> int:
|
| 987 |
+
return self.class_ir.vtable_entry(name)
|
| 988 |
+
|
| 989 |
+
def setter_index(self, name: str) -> int:
|
| 990 |
+
return self.getter_index(name) + 1
|
| 991 |
+
|
| 992 |
+
def method_index(self, name: str) -> int:
|
| 993 |
+
return self.class_ir.vtable_entry(name)
|
| 994 |
+
|
| 995 |
+
def attr_type(self, name: str) -> RType:
|
| 996 |
+
return self.class_ir.attr_type(name)
|
| 997 |
+
|
| 998 |
+
def __repr__(self) -> str:
|
| 999 |
+
return "<RInstance %s>" % self.name
|
| 1000 |
+
|
| 1001 |
+
def __eq__(self, other: object) -> TypeGuard[RInstance]:
|
| 1002 |
+
return isinstance(other, RInstance) and other.name == self.name
|
| 1003 |
+
|
| 1004 |
+
def __hash__(self) -> int:
|
| 1005 |
+
return hash(self.name)
|
| 1006 |
+
|
| 1007 |
+
def serialize(self) -> str:
|
| 1008 |
+
return self.name
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
@final
|
| 1012 |
+
class RVec(RType):
|
| 1013 |
+
"""librt.vecs.vec[T]"""
|
| 1014 |
+
|
| 1015 |
+
is_unboxed = True
|
| 1016 |
+
|
| 1017 |
+
def __init__(self, item_type: RType) -> None:
|
| 1018 |
+
self.name = "vec[%s]" % item_type
|
| 1019 |
+
self.item_type = item_type
|
| 1020 |
+
self.names = ["len", "buf"]
|
| 1021 |
+
self.dependencies = (LIBRT_VECS,)
|
| 1022 |
+
if isinstance(item_type, RUnion):
|
| 1023 |
+
non_opt = optional_value_type(item_type)
|
| 1024 |
+
else:
|
| 1025 |
+
non_opt = item_type
|
| 1026 |
+
if item_type in vec_buf_types:
|
| 1027 |
+
self._ctype = vec_c_types[item_type]
|
| 1028 |
+
self.buf_type = vec_buf_types[item_type]
|
| 1029 |
+
self.types = [c_pyssize_t_rprimitive, self.buf_type]
|
| 1030 |
+
elif isinstance(non_opt, RVec):
|
| 1031 |
+
self._ctype = "VecNested"
|
| 1032 |
+
self.types = [c_pyssize_t_rprimitive, VecTBufObject]
|
| 1033 |
+
self.buf_type = VecNestedBufObject
|
| 1034 |
+
else:
|
| 1035 |
+
self._ctype = "VecT"
|
| 1036 |
+
self.types = [c_pyssize_t_rprimitive, VecTBufObject]
|
| 1037 |
+
self.buf_type = VecTBufObject
|
| 1038 |
+
|
| 1039 |
+
@property
|
| 1040 |
+
def may_be_immortal(self) -> bool:
|
| 1041 |
+
return False
|
| 1042 |
+
|
| 1043 |
+
def unwrap_item_type(self) -> RPrimitive | RInstance:
|
| 1044 |
+
"""Return the non-optional value (non-vec) item type in a potentially nested vec."""
|
| 1045 |
+
item_type = self.item_type
|
| 1046 |
+
while True:
|
| 1047 |
+
if isinstance(item_type, RUnion):
|
| 1048 |
+
value_type = optional_value_type(item_type)
|
| 1049 |
+
assert value_type is not None
|
| 1050 |
+
item_type = value_type
|
| 1051 |
+
elif isinstance(item_type, RVec):
|
| 1052 |
+
item_type = item_type.item_type
|
| 1053 |
+
elif isinstance(item_type, (RPrimitive, RInstance)):
|
| 1054 |
+
return item_type
|
| 1055 |
+
else:
|
| 1056 |
+
assert False, f"unexpected item type: {self.item_type}"
|
| 1057 |
+
|
| 1058 |
+
def is_optional(self) -> bool:
|
| 1059 |
+
item_type = self.item_type
|
| 1060 |
+
if isinstance(item_type, RUnion):
|
| 1061 |
+
return True
|
| 1062 |
+
elif isinstance(item_type, RVec):
|
| 1063 |
+
return item_type.is_optional()
|
| 1064 |
+
return False
|
| 1065 |
+
|
| 1066 |
+
def depth(self) -> int:
|
| 1067 |
+
item_type = self.item_type
|
| 1068 |
+
if isinstance(item_type, RUnion):
|
| 1069 |
+
value_type = optional_value_type(item_type)
|
| 1070 |
+
assert value_type is not None
|
| 1071 |
+
item_type = value_type
|
| 1072 |
+
if isinstance(item_type, RVec):
|
| 1073 |
+
return 1 + item_type.depth()
|
| 1074 |
+
return 0
|
| 1075 |
+
|
| 1076 |
+
def field_type(self, name: str) -> RType:
|
| 1077 |
+
if name == "len":
|
| 1078 |
+
return c_pyssize_t_rprimitive
|
| 1079 |
+
elif name == "buf":
|
| 1080 |
+
return object_rprimitive
|
| 1081 |
+
assert False, f"RVec has no field '{name}'"
|
| 1082 |
+
|
| 1083 |
+
def accept(self, visitor: RTypeVisitor[T]) -> T:
|
| 1084 |
+
return visitor.visit_rvec(self)
|
| 1085 |
+
|
| 1086 |
+
def __str__(self) -> str:
|
| 1087 |
+
if self.is_optional() and self.depth() == 0:
|
| 1088 |
+
type_str = f"{self.unwrap_item_type()} | None"
|
| 1089 |
+
else:
|
| 1090 |
+
type_str = str(self.item_type)
|
| 1091 |
+
return f"vec[{type_str}]"
|
| 1092 |
+
|
| 1093 |
+
def __repr__(self) -> str:
|
| 1094 |
+
return "<RVec[%s]>" % self.item_type
|
| 1095 |
+
|
| 1096 |
+
def __eq__(self, other: object) -> bool:
|
| 1097 |
+
return isinstance(other, RVec) and other.item_type == self.item_type
|
| 1098 |
+
|
| 1099 |
+
def __hash__(self) -> int:
|
| 1100 |
+
return hash(self.item_type) ^ 1
|
| 1101 |
+
|
| 1102 |
+
def serialize(self) -> JsonDict:
|
| 1103 |
+
return {".class": "RVec", "item_type": self.item_type.serialize()}
|
| 1104 |
+
|
| 1105 |
+
@classmethod
|
| 1106 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RVec:
|
| 1107 |
+
return RVec(deserialize_type(data["item_type"], ctx))
|
| 1108 |
+
|
| 1109 |
+
|
| 1110 |
+
@final
|
| 1111 |
+
class RUnion(RType):
|
| 1112 |
+
"""union[x, ..., y]"""
|
| 1113 |
+
|
| 1114 |
+
is_unboxed = False
|
| 1115 |
+
|
| 1116 |
+
def __init__(self, items: list[RType]) -> None:
|
| 1117 |
+
self.name = "union"
|
| 1118 |
+
self.items = items
|
| 1119 |
+
self.items_set = frozenset(items)
|
| 1120 |
+
self._ctype = "PyObject *"
|
| 1121 |
+
|
| 1122 |
+
@staticmethod
|
| 1123 |
+
def make_simplified_union(items: list[RType]) -> RType:
|
| 1124 |
+
"""Return a normalized union that covers the given items.
|
| 1125 |
+
|
| 1126 |
+
Flatten nested unions and remove duplicate items.
|
| 1127 |
+
|
| 1128 |
+
Overlapping items are *not* simplified. For example,
|
| 1129 |
+
[object, str] will not be simplified.
|
| 1130 |
+
"""
|
| 1131 |
+
items = flatten_nested_unions(items)
|
| 1132 |
+
assert items
|
| 1133 |
+
|
| 1134 |
+
unique_items = dict.fromkeys(items)
|
| 1135 |
+
if len(unique_items) > 1:
|
| 1136 |
+
return RUnion(list(unique_items))
|
| 1137 |
+
else:
|
| 1138 |
+
return next(iter(unique_items))
|
| 1139 |
+
|
| 1140 |
+
def accept(self, visitor: RTypeVisitor[T]) -> T:
|
| 1141 |
+
return visitor.visit_runion(self)
|
| 1142 |
+
|
| 1143 |
+
@property
|
| 1144 |
+
def may_be_immortal(self) -> bool:
|
| 1145 |
+
return any(item.may_be_immortal for item in self.items)
|
| 1146 |
+
|
| 1147 |
+
def __repr__(self) -> str:
|
| 1148 |
+
return "<RUnion %s>" % ", ".join(str(item) for item in self.items)
|
| 1149 |
+
|
| 1150 |
+
def __str__(self) -> str:
|
| 1151 |
+
return "union[%s]" % ", ".join(str(item) for item in self.items)
|
| 1152 |
+
|
| 1153 |
+
# We compare based on the set because order in a union doesn't matter
|
| 1154 |
+
def __eq__(self, other: object) -> TypeGuard[RUnion]:
|
| 1155 |
+
return isinstance(other, RUnion) and self.items_set == other.items_set
|
| 1156 |
+
|
| 1157 |
+
def __hash__(self) -> int:
|
| 1158 |
+
return hash(("union", self.items_set))
|
| 1159 |
+
|
| 1160 |
+
def serialize(self) -> JsonDict:
|
| 1161 |
+
types = [x.serialize() for x in self.items]
|
| 1162 |
+
return {".class": "RUnion", "types": types}
|
| 1163 |
+
|
| 1164 |
+
@classmethod
|
| 1165 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RUnion:
|
| 1166 |
+
types = [deserialize_type(t, ctx) for t in data["types"]]
|
| 1167 |
+
return RUnion(types)
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
def flatten_nested_unions(types: list[RType]) -> list[RType]:
|
| 1171 |
+
if not any(isinstance(t, RUnion) for t in types):
|
| 1172 |
+
return types # Fast path
|
| 1173 |
+
|
| 1174 |
+
flat_items: list[RType] = []
|
| 1175 |
+
for t in types:
|
| 1176 |
+
if isinstance(t, RUnion):
|
| 1177 |
+
flat_items.extend(flatten_nested_unions(t.items))
|
| 1178 |
+
else:
|
| 1179 |
+
flat_items.append(t)
|
| 1180 |
+
return flat_items
|
| 1181 |
+
|
| 1182 |
+
|
| 1183 |
+
def optional_value_type(rtype: RType) -> RType | None:
|
| 1184 |
+
"""If rtype is the union of none_rprimitive and another type X, return X.
|
| 1185 |
+
|
| 1186 |
+
Otherwise, return None.
|
| 1187 |
+
"""
|
| 1188 |
+
if isinstance(rtype, RUnion) and len(rtype.items) == 2:
|
| 1189 |
+
if rtype.items[0] == none_rprimitive:
|
| 1190 |
+
return rtype.items[1]
|
| 1191 |
+
elif rtype.items[1] == none_rprimitive:
|
| 1192 |
+
return rtype.items[0]
|
| 1193 |
+
return None
|
| 1194 |
+
|
| 1195 |
+
|
| 1196 |
+
def is_optional_type(rtype: RType) -> TypeGuard[RUnion]:
|
| 1197 |
+
"""Is rtype an optional type with exactly two union items?"""
|
| 1198 |
+
return optional_value_type(rtype) is not None
|
| 1199 |
+
|
| 1200 |
+
|
| 1201 |
+
@final
|
| 1202 |
+
class RArray(RType):
|
| 1203 |
+
"""Fixed-length C array type (for example, int[5]).
|
| 1204 |
+
|
| 1205 |
+
Note that the implementation is a bit limited, and these can basically
|
| 1206 |
+
be only used for local variables that are initialized in one location.
|
| 1207 |
+
"""
|
| 1208 |
+
|
| 1209 |
+
def __init__(self, item_type: RType, length: int) -> None:
|
| 1210 |
+
self.item_type = item_type
|
| 1211 |
+
# Number of items
|
| 1212 |
+
self.length = length
|
| 1213 |
+
self.is_refcounted = False
|
| 1214 |
+
|
| 1215 |
+
def accept(self, visitor: RTypeVisitor[T]) -> T:
|
| 1216 |
+
return visitor.visit_rarray(self)
|
| 1217 |
+
|
| 1218 |
+
@property
|
| 1219 |
+
def may_be_immortal(self) -> bool:
|
| 1220 |
+
return False
|
| 1221 |
+
|
| 1222 |
+
def __str__(self) -> str:
|
| 1223 |
+
return f"{self.item_type}[{self.length}]"
|
| 1224 |
+
|
| 1225 |
+
def __repr__(self) -> str:
|
| 1226 |
+
return f"<RArray {self.item_type!r}[{self.length}]>"
|
| 1227 |
+
|
| 1228 |
+
def __eq__(self, other: object) -> TypeGuard[RArray]:
|
| 1229 |
+
return (
|
| 1230 |
+
isinstance(other, RArray)
|
| 1231 |
+
and self.item_type == other.item_type
|
| 1232 |
+
and self.length == other.length
|
| 1233 |
+
)
|
| 1234 |
+
|
| 1235 |
+
def __hash__(self) -> int:
|
| 1236 |
+
return hash((self.item_type, self.length))
|
| 1237 |
+
|
| 1238 |
+
def serialize(self) -> JsonDict:
|
| 1239 |
+
assert False
|
| 1240 |
+
|
| 1241 |
+
@classmethod
|
| 1242 |
+
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RArray:
|
| 1243 |
+
assert False
|
| 1244 |
+
|
| 1245 |
+
|
| 1246 |
+
PyObject = RStruct(
|
| 1247 |
+
name="PyObject",
|
| 1248 |
+
names=["ob_refcnt", "ob_type"],
|
| 1249 |
+
types=[c_pyssize_t_rprimitive, pointer_rprimitive],
|
| 1250 |
+
)
|
| 1251 |
+
|
| 1252 |
+
PyVarObject = RStruct(
|
| 1253 |
+
name="PyVarObject", names=["ob_base", "ob_size"], types=[PyObject, c_pyssize_t_rprimitive]
|
| 1254 |
+
)
|
| 1255 |
+
|
| 1256 |
+
setentry = RStruct(
|
| 1257 |
+
name="setentry", names=["key", "hash"], types=[pointer_rprimitive, c_pyssize_t_rprimitive]
|
| 1258 |
+
)
|
| 1259 |
+
|
| 1260 |
+
smalltable = RStruct(name="smalltable", names=[], types=[setentry] * 8)
|
| 1261 |
+
|
| 1262 |
+
PySetObject = RStruct(
|
| 1263 |
+
name="PySetObject",
|
| 1264 |
+
names=[
|
| 1265 |
+
"ob_base",
|
| 1266 |
+
"fill",
|
| 1267 |
+
"used",
|
| 1268 |
+
"mask",
|
| 1269 |
+
"table",
|
| 1270 |
+
"hash",
|
| 1271 |
+
"finger",
|
| 1272 |
+
"smalltable",
|
| 1273 |
+
"weakreflist",
|
| 1274 |
+
],
|
| 1275 |
+
types=[
|
| 1276 |
+
PyObject,
|
| 1277 |
+
c_pyssize_t_rprimitive,
|
| 1278 |
+
c_pyssize_t_rprimitive,
|
| 1279 |
+
c_pyssize_t_rprimitive,
|
| 1280 |
+
pointer_rprimitive,
|
| 1281 |
+
c_pyssize_t_rprimitive,
|
| 1282 |
+
c_pyssize_t_rprimitive,
|
| 1283 |
+
smalltable,
|
| 1284 |
+
pointer_rprimitive,
|
| 1285 |
+
],
|
| 1286 |
+
)
|
| 1287 |
+
|
| 1288 |
+
PyListObject = RStruct(
|
| 1289 |
+
name="PyListObject",
|
| 1290 |
+
names=["ob_base", "ob_item", "allocated"],
|
| 1291 |
+
types=[PyVarObject, pointer_rprimitive, c_pyssize_t_rprimitive],
|
| 1292 |
+
)
|
| 1293 |
+
|
| 1294 |
+
|
| 1295 |
+
def check_native_int_range(rtype: RPrimitive, n: int) -> bool:
|
| 1296 |
+
"""Is n within the range of a native, fixed-width int type?
|
| 1297 |
+
|
| 1298 |
+
Assume the type is a fixed-width int type.
|
| 1299 |
+
"""
|
| 1300 |
+
if not rtype.is_signed:
|
| 1301 |
+
return 0 <= n < (1 << (8 * rtype.size))
|
| 1302 |
+
else:
|
| 1303 |
+
limit = 1 << (rtype.size * 8 - 1)
|
| 1304 |
+
return -limit <= n < limit
|
| 1305 |
+
|
| 1306 |
+
|
| 1307 |
+
# Buffers for vec item types that have a packed representation
|
| 1308 |
+
#
|
| 1309 |
+
# Note that the 'items' fields are variable-length arrays, and mypyc IR isn't
|
| 1310 |
+
# able to represent these, so the field type is omitted for now.
|
| 1311 |
+
|
| 1312 |
+
VecI64BufObject = RStruct(
|
| 1313 |
+
name="VecI64BufObject",
|
| 1314 |
+
names=["ob_base", "len", "items"],
|
| 1315 |
+
types=[PyVarObject, int64_rprimitive],
|
| 1316 |
+
)
|
| 1317 |
+
|
| 1318 |
+
VecI32BufObject = RStruct(
|
| 1319 |
+
name="VecI32BufObject",
|
| 1320 |
+
names=["ob_base", "len", "items"],
|
| 1321 |
+
types=[PyVarObject, int64_rprimitive],
|
| 1322 |
+
)
|
| 1323 |
+
|
| 1324 |
+
VecI16BufObject = RStruct(
|
| 1325 |
+
name="VecI16BufObject",
|
| 1326 |
+
names=["ob_base", "len", "items"],
|
| 1327 |
+
types=[PyVarObject, int64_rprimitive],
|
| 1328 |
+
)
|
| 1329 |
+
|
| 1330 |
+
VecU8BufObject = RStruct(
|
| 1331 |
+
name="VecU8BufObject", names=["ob_base", "len", "items"], types=[PyVarObject, int64_rprimitive]
|
| 1332 |
+
)
|
| 1333 |
+
|
| 1334 |
+
VecFloatBufObject = RStruct(
|
| 1335 |
+
name="VecFloatBufObject",
|
| 1336 |
+
names=["ob_base", "len", "items"],
|
| 1337 |
+
types=[PyVarObject, int64_rprimitive],
|
| 1338 |
+
)
|
| 1339 |
+
|
| 1340 |
+
VecBoolBufObject = RStruct(
|
| 1341 |
+
name="VecBoolBufObject",
|
| 1342 |
+
names=["ob_base", "len", "items"],
|
| 1343 |
+
types=[PyVarObject, int64_rprimitive],
|
| 1344 |
+
)
|
| 1345 |
+
|
| 1346 |
+
|
| 1347 |
+
# Struct type for vec[i64] (in most cases use RVec instead).
|
| 1348 |
+
VecI64 = RStruct(
|
| 1349 |
+
name="VecI64", names=["len", "buf"], types=[c_pyssize_t_rprimitive, object_rprimitive]
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
|
| 1353 |
+
# Buffer for vec[t]
|
| 1354 |
+
VecTBufObject = RStruct(
|
| 1355 |
+
name="VecTBufObject",
|
| 1356 |
+
names=["ob_base", "item_type", "items"],
|
| 1357 |
+
types=[PyVarObject, c_pyssize_t_rprimitive, object_rprimitive],
|
| 1358 |
+
)
|
| 1359 |
+
|
| 1360 |
+
# Struct type for vec[t] (in most cases use RVec instead).
|
| 1361 |
+
VecT = RStruct(
|
| 1362 |
+
name="VecT", names=["len", "buf"], types=[c_pyssize_t_rprimitive, object_rprimitive]
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
VecNestedBufItem = RStruct(
|
| 1366 |
+
name="VecNestedBufItem",
|
| 1367 |
+
names=["len", "buf"],
|
| 1368 |
+
types=[c_pyssize_t_rprimitive, object_non_refcounted_rprimitive],
|
| 1369 |
+
)
|
| 1370 |
+
|
| 1371 |
+
# Buffer for vec[vec[t]]
|
| 1372 |
+
VecNestedBufObject = RStruct(
|
| 1373 |
+
name="VecNestedBufObject",
|
| 1374 |
+
names=["ob_base", "item_type", "depth", "optionals", "items"],
|
| 1375 |
+
types=[
|
| 1376 |
+
PyVarObject,
|
| 1377 |
+
c_pyssize_t_rprimitive,
|
| 1378 |
+
int32_rprimitive,
|
| 1379 |
+
int32_rprimitive,
|
| 1380 |
+
VecNestedBufItem,
|
| 1381 |
+
],
|
| 1382 |
+
)
|
| 1383 |
+
|
| 1384 |
+
# Struct type for vec[vec[...]] (in most cases use RVec instead).
|
| 1385 |
+
VecNested = RStruct(
|
| 1386 |
+
name="VecNested", names=["len", "buf"], types=[c_pyssize_t_rprimitive, object_rprimitive]
|
| 1387 |
+
)
|
| 1388 |
+
|
| 1389 |
+
VecNestedBufObject_rprimitive = RPrimitive(
|
| 1390 |
+
"VecNestedBufObject_ptr", is_unboxed=False, is_refcounted=True, ctype="VecNestedBufObject *"
|
| 1391 |
+
)
|
| 1392 |
+
|
| 1393 |
+
VecNestedPopResult = RStruct(
|
| 1394 |
+
name="VecNestedPopResult", names=["vec", "item"], types=[VecNested, VecNestedBufItem]
|
| 1395 |
+
)
|
| 1396 |
+
|
| 1397 |
+
|
| 1398 |
+
vec_buf_types: Final[dict[RType, RStruct]] = {
|
| 1399 |
+
int64_rprimitive: VecI64BufObject,
|
| 1400 |
+
int32_rprimitive: VecI32BufObject,
|
| 1401 |
+
int16_rprimitive: VecI16BufObject,
|
| 1402 |
+
uint8_rprimitive: VecU8BufObject,
|
| 1403 |
+
float_rprimitive: VecFloatBufObject,
|
| 1404 |
+
bool_rprimitive: VecBoolBufObject,
|
| 1405 |
+
}
|
| 1406 |
+
|
| 1407 |
+
vec_c_types: Final[dict[RType, str]] = {
|
| 1408 |
+
int64_rprimitive: "VecI64",
|
| 1409 |
+
int32_rprimitive: "VecI32",
|
| 1410 |
+
int16_rprimitive: "VecI16",
|
| 1411 |
+
uint8_rprimitive: "VecU8",
|
| 1412 |
+
float_rprimitive: "VecFloat",
|
| 1413 |
+
bool_rprimitive: "VecBool",
|
| 1414 |
+
}
|
| 1415 |
+
|
| 1416 |
+
vec_api_fields: Final[dict[RType, str]] = {
|
| 1417 |
+
int64_rprimitive: "i64",
|
| 1418 |
+
int32_rprimitive: "i32",
|
| 1419 |
+
int16_rprimitive: "i16",
|
| 1420 |
+
uint8_rprimitive: "u8",
|
| 1421 |
+
float_rprimitive: "float_",
|
| 1422 |
+
bool_rprimitive: "bool_",
|
| 1423 |
+
}
|
| 1424 |
+
|
| 1425 |
+
vec_api_by_item_type: Final[dict[RType, str]] = {
|
| 1426 |
+
int64_rprimitive: "VecI64Api",
|
| 1427 |
+
int32_rprimitive: "VecI32Api",
|
| 1428 |
+
int16_rprimitive: "VecI16Api",
|
| 1429 |
+
uint8_rprimitive: "VecU8Api",
|
| 1430 |
+
float_rprimitive: "VecFloatApi",
|
| 1431 |
+
bool_rprimitive: "VecBoolApi",
|
| 1432 |
+
}
|
| 1433 |
+
|
| 1434 |
+
# These are special item type constants used in nested vecs to represent
|
| 1435 |
+
# item types with specialized representations. These must match definitions
|
| 1436 |
+
# in the vecs module (see VEC_ITEM_TYPE_I64 etc.).
|
| 1437 |
+
vec_item_type_tags: Final[dict[RType, int]] = {
|
| 1438 |
+
int64_rprimitive: 2,
|
| 1439 |
+
int32_rprimitive: 6,
|
| 1440 |
+
int16_rprimitive: 10,
|
| 1441 |
+
uint8_rprimitive: 14,
|
| 1442 |
+
float_rprimitive: 18,
|
| 1443 |
+
bool_rprimitive: 22,
|
| 1444 |
+
}
|
micromamba_root/Lib/site-packages/mypyc/irbuild/__init__.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|
micromamba_root/Lib/site-packages/mypyc/irbuild/__init__.py
ADDED
|
File without changes
|
micromamba_root/Lib/site-packages/mypyc/irbuild/ast_helpers.cp314-win_amd64.pyd
ADDED
|
Binary file (10.2 kB). View file
|
|
|