diff --git a/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/licenses/LICENSE b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bdb7786b2322c9d2ab970bbfba8771d6e8774723 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/licenses/LICENSE @@ -0,0 +1,27 @@ +Mypy extensions are licensed under the terms of the MIT license, reproduced below. + += = = = = + +The MIT License + +Copyright (c) 2016-2017 Jukka Lehtosalo and contributors + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + += = = = = diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/__init__.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/analysis/__init__.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ce68f532776ca350aa358e7adeb2e3e6d03c14c6 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/analysis/__init__.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/__init__.py b/micromamba_root/Lib/site-packages/mypyc/analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..654e15a3b3f06a6bbe47d368457652244a749a8c Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.py b/micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.py new file mode 100644 index 0000000000000000000000000000000000000000..1dfd33630f1c03e3b2f796c8d7ea4acc339fd2ae --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/analysis/attrdefined.py @@ -0,0 +1,437 @@ +"""Always defined attribute analysis. + +An always defined attribute has some statements in __init__ or the +class body that cause the attribute to be always initialized when an +instance is constructed. It must also not be possible to read the +attribute before initialization, and it can't be deletable. + +We can assume that the value is always defined when reading an always +defined attribute. Otherwise we'll need to raise AttributeError if the +value is undefined (i.e. has the error value). + +We use data flow analysis to figure out attributes that are always +defined. Example: + + class C: + def __init__(self) -> None: + self.x = 0 + if func(): + self.y = 1 + else: + self.y = 2 + self.z = 3 + +In this example, the attributes 'x' and 'y' are always defined, but 'z' +is not. The analysis assumes that we know that there won't be any subclasses. + +The analysis also works if there is a known, closed set of subclasses. +An attribute defined in a base class can only be always defined if it's +also always defined in all subclasses. + +As soon as __init__ contains an op that can 'leak' self to another +function, we will stop inferring always defined attributes, since the +analysis is mostly intra-procedural and only looks at __init__ methods. +The called code could read an uninitialized attribute. Example: + + class C: + def __init__(self) -> None: + self.x = self.foo() + + def foo(self) -> int: + ... + +Now we won't infer 'x' as always defined, since 'foo' might read 'x' +before initialization. + +As an exception to the above limitation, we perform inter-procedural +analysis of super().__init__ calls, since these are very common. + +Our analysis is somewhat optimistic. We assume that nobody calls a +method of a partially uninitialized object through gc.get_objects(), in +particular. Code like this could potentially cause a segfault with a null +pointer dereference. This seems very unlikely to be an issue in practice, +however. + +Accessing an attribute via getattr always checks for undefined attributes +and thus works if the object is partially uninitialized. This can be used +as a workaround if somebody ever needs to inspect partially uninitialized +objects via gc.get_objects(). + +The analysis runs after IR building as a separate pass. Since we only +run this on __init__ methods, this analysis pass will be fairly quick. +""" + +from __future__ import annotations + +from typing import Final + +from mypyc.analysis.dataflow import ( + CFG, + MAYBE_ANALYSIS, + AnalysisResult, + BaseAnalysisVisitor, + get_cfg, + run_analysis, +) +from mypyc.analysis.selfleaks import analyze_self_leaks +from mypyc.ir.class_ir import ClassIR +from mypyc.ir.ops import ( + Assign, + AssignMulti, + BasicBlock, + Branch, + Call, + ControlOp, + GetAttr, + Register, + RegisterOp, + Return, + SetAttr, + SetMem, + Unreachable, +) +from mypyc.ir.rtypes import RInstance + +# If True, print out all always-defined attributes of native classes (to aid +# debugging and testing) +dump_always_defined: Final = False + + +def analyze_always_defined_attrs(class_irs: list[ClassIR]) -> None: + """Find always defined attributes all classes of a compilation unit. + + Also tag attribute initialization ops to not decref the previous + value (as this would read a NULL pointer and segfault). + + Update the _always_initialized_attrs, _sometimes_initialized_attrs + and init_self_leak attributes in ClassIR instances. + + This is the main entry point. + """ + seen: set[ClassIR] = set() + + # First pass: only look at target class and classes in MRO + for cl in class_irs: + analyze_always_defined_attrs_in_class(cl, seen) + + # Second pass: look at all derived class + seen = set() + for cl in class_irs: + update_always_defined_attrs_using_subclasses(cl, seen) + + # Final pass: detect attributes that need to use a bitmap to track definedness + seen = set() + for cl in class_irs: + detect_undefined_bitmap(cl, seen) + + +def analyze_always_defined_attrs_in_class(cl: ClassIR, seen: set[ClassIR]) -> None: + if cl in seen: + return + + seen.add(cl) + + if ( + cl.is_trait + or cl.inherits_python + or cl.allow_interpreted_subclasses + or cl.builtin_base is not None + or cl.children is None + or cl.is_serializable() + or cl.has_method("__new__") + ): + # Give up -- we can't enforce that attributes are always defined. + return + + # First analyze all base classes. Track seen classes to avoid duplicate work. + for base in cl.mro[1:]: + analyze_always_defined_attrs_in_class(base, seen) + + m = cl.get_method("__init__") + if m is None: + cl._always_initialized_attrs = cl.attrs_with_defaults.copy() + cl._sometimes_initialized_attrs = cl.attrs_with_defaults.copy() + return + self_reg = m.arg_regs[0] + cfg = get_cfg(m.blocks) + dirty = analyze_self_leaks(m.blocks, self_reg, cfg) + maybe_defined = analyze_maybe_defined_attrs_in_init( + m.blocks, self_reg, cl.attrs_with_defaults, cfg + ) + all_attrs: set[str] = set() + for base in cl.mro: + all_attrs.update(base.attributes) + maybe_undefined = analyze_maybe_undefined_attrs_in_init( + m.blocks, self_reg, initial_undefined=all_attrs - cl.attrs_with_defaults, cfg=cfg + ) + + always_defined = find_always_defined_attributes( + m.blocks, self_reg, all_attrs, maybe_defined, maybe_undefined, dirty + ) + always_defined = {a for a in always_defined if not cl.is_deletable(a)} + + cl._always_initialized_attrs = always_defined + if dump_always_defined: + print(cl.name, sorted(always_defined)) + cl._sometimes_initialized_attrs = find_sometimes_defined_attributes( + m.blocks, self_reg, maybe_defined, dirty + ) + + mark_attr_initialization_ops(m.blocks, self_reg, maybe_defined, dirty) + + # Check if __init__ can run unpredictable code (leak 'self'). + any_dirty = False + for b in m.blocks: + for i, op in enumerate(b.ops): + if dirty.after[b, i] and not isinstance(op, Return): + any_dirty = True + break + cl.init_self_leak = any_dirty + + +def find_always_defined_attributes( + blocks: list[BasicBlock], + self_reg: Register, + all_attrs: set[str], + maybe_defined: AnalysisResult[str], + maybe_undefined: AnalysisResult[str], + dirty: AnalysisResult[None], +) -> set[str]: + """Find attributes that are always initialized in some basic blocks. + + The analysis results are expected to be up-to-date for the blocks. + + Return a set of always defined attributes. + """ + attrs = all_attrs.copy() + for block in blocks: + for i, op in enumerate(block.ops): + # If an attribute we *read* may be undefined, it isn't always defined. + if isinstance(op, GetAttr) and op.obj is self_reg: + if op.attr in maybe_undefined.before[block, i]: + attrs.discard(op.attr) + # If an attribute we *set* may be sometimes undefined and + # sometimes defined, don't consider it always defined. Unlike + # the get case, it's fine for the attribute to be undefined. + # The set operation will then be treated as initialization. + if isinstance(op, SetAttr) and op.obj is self_reg: + if ( + op.attr in maybe_undefined.before[block, i] + and op.attr in maybe_defined.before[block, i] + ): + attrs.discard(op.attr) + # Treat an op that might run arbitrary code as an "exit" + # in terms of the analysis -- we can't do any inference + # afterwards reliably. + if dirty.after[block, i]: + if not dirty.before[block, i]: + attrs = attrs & ( + maybe_defined.after[block, i] - maybe_undefined.after[block, i] + ) + break + if isinstance(op, ControlOp): + for target in op.targets(): + # Gotos/branches can also be "exits". + if not dirty.after[block, i] and dirty.before[target, 0]: + attrs = attrs & ( + maybe_defined.after[target, 0] - maybe_undefined.after[target, 0] + ) + return attrs + + +def find_sometimes_defined_attributes( + blocks: list[BasicBlock], + self_reg: Register, + maybe_defined: AnalysisResult[str], + dirty: AnalysisResult[None], +) -> set[str]: + """Find attributes that are sometimes initialized in some basic blocks.""" + attrs: set[str] = set() + for block in blocks: + for i, op in enumerate(block.ops): + # Only look at possibly defined attributes at exits. + if dirty.after[block, i]: + if not dirty.before[block, i]: + attrs = attrs | maybe_defined.after[block, i] + break + if isinstance(op, ControlOp): + for target in op.targets(): + if not dirty.after[block, i] and dirty.before[target, 0]: + attrs = attrs | maybe_defined.after[target, 0] + return attrs + + +def mark_attr_initialization_ops( + blocks: list[BasicBlock], + self_reg: Register, + maybe_defined: AnalysisResult[str], + dirty: AnalysisResult[None], +) -> None: + """Tag all SetAttr ops in the basic blocks that initialize attributes. + + Initialization ops assume that the previous attribute value is the error value, + so there's no need to decref or check for definedness. + """ + for block in blocks: + for i, op in enumerate(block.ops): + if isinstance(op, SetAttr) and op.obj is self_reg: + attr = op.attr + if attr not in maybe_defined.before[block, i] and not dirty.after[block, i]: + op.mark_as_initializer() + + +GenAndKill = tuple[set[str], set[str]] + + +def attributes_initialized_by_init_call(op: Call) -> set[str]: + """Calculate attributes that are always initialized by a super().__init__ call.""" + self_type = op.fn.sig.args[0].type + assert isinstance(self_type, RInstance), self_type + cl = self_type.class_ir + return {a for base in cl.mro for a in base.attributes if base.is_always_defined(a)} + + +def attributes_maybe_initialized_by_init_call(op: Call) -> set[str]: + """Calculate attributes that may be initialized by a super().__init__ call.""" + self_type = op.fn.sig.args[0].type + assert isinstance(self_type, RInstance), self_type + cl = self_type.class_ir + return attributes_initialized_by_init_call(op) | cl._sometimes_initialized_attrs + + +class AttributeMaybeDefinedVisitor(BaseAnalysisVisitor[str]): + """Find attributes that may have been defined via some code path. + + Consider initializations in class body and assignments to 'self.x' + and calls to base class '__init__'. + """ + + def __init__(self, self_reg: Register) -> None: + self.self_reg = self_reg + + def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_return(self, op: Return) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]: + if isinstance(op, SetAttr) and op.obj is self.self_reg: + return {op.attr}, set() + if isinstance(op, Call) and op.fn.class_name and op.fn.name == "__init__": + return attributes_maybe_initialized_by_init_call(op), set() + return set(), set() + + def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]: + return set(), set() + + +def analyze_maybe_defined_attrs_in_init( + blocks: list[BasicBlock], self_reg: Register, attrs_with_defaults: set[str], cfg: CFG +) -> AnalysisResult[str]: + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=AttributeMaybeDefinedVisitor(self_reg), + initial=attrs_with_defaults, + backward=False, + kind=MAYBE_ANALYSIS, + ) + + +class AttributeMaybeUndefinedVisitor(BaseAnalysisVisitor[str]): + """Find attributes that may be undefined via some code path. + + Consider initializations in class body, assignments to 'self.x' + and calls to base class '__init__'. + """ + + def __init__(self, self_reg: Register) -> None: + self.self_reg = self_reg + + def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_return(self, op: Return) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]: + if isinstance(op, SetAttr) and op.obj is self.self_reg: + return set(), {op.attr} + if isinstance(op, Call) and op.fn.class_name and op.fn.name == "__init__": + return set(), attributes_initialized_by_init_call(op) + return set(), set() + + def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]: + return set(), set() + + def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]: + return set(), set() + + +def analyze_maybe_undefined_attrs_in_init( + blocks: list[BasicBlock], self_reg: Register, initial_undefined: set[str], cfg: CFG +) -> AnalysisResult[str]: + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=AttributeMaybeUndefinedVisitor(self_reg), + initial=initial_undefined, + backward=False, + kind=MAYBE_ANALYSIS, + ) + + +def update_always_defined_attrs_using_subclasses(cl: ClassIR, seen: set[ClassIR]) -> None: + """Remove attributes not defined in all subclasses from always defined attrs.""" + if cl in seen: + return + if cl.children is None: + # Subclasses are unknown + return + removed = set() + for attr in cl._always_initialized_attrs: + for child in cl.children: + update_always_defined_attrs_using_subclasses(child, seen) + if attr not in child._always_initialized_attrs: + removed.add(attr) + cl._always_initialized_attrs -= removed + seen.add(cl) + + +def detect_undefined_bitmap(cl: ClassIR, seen: set[ClassIR]) -> None: + if cl.is_trait: + return + + if cl in seen: + return + seen.add(cl) + for base in cl.base_mro[1:]: + detect_undefined_bitmap(base, seen) + + if len(cl.base_mro) > 1: + cl.bitmap_attrs.extend(cl.base_mro[1].bitmap_attrs) + for n, t in cl.attributes.items(): + if t.error_overlap and not cl.is_always_defined(n): + cl.bitmap_attrs.append(n) + + for base in cl.mro[1:]: + if base.is_trait: + for n, t in base.attributes.items(): + if t.error_overlap and not cl.is_always_defined(n) and n not in cl.bitmap_attrs: + cl.bitmap_attrs.append(n) diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c4bf1abf69117818b6fd71730c14e692ce77ef81 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.py b/micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.py new file mode 100644 index 0000000000000000000000000000000000000000..74a1bc0579c61c166ed69f575b3848e30f21a74c --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/analysis/blockfreq.py @@ -0,0 +1,32 @@ +"""Find basic blocks that are likely to be executed frequently. + +For example, this would not include blocks that have exception handlers. + +We can use different optimization heuristics for common and rare code. For +example, we can make IR fast to compile instead of fast to execute for rare +code. +""" + +from __future__ import annotations + +from mypyc.ir.ops import BasicBlock, Branch, Goto + + +def frequently_executed_blocks(entry_point: BasicBlock) -> set[BasicBlock]: + result: set[BasicBlock] = set() + worklist = [entry_point] + while worklist: + block = worklist.pop() + if block in result: + continue + result.add(block) + t = block.terminator + if isinstance(t, Goto): + worklist.append(t.label) + elif isinstance(t, Branch): + if t.rare or t.traceback_entry is not None: + worklist.append(t.false) + else: + worklist.append(t.true) + worklist.append(t.false) + return result diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3c2e6b7704c19c03ef99c39f921c4b16a1941cd3 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.py b/micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.py new file mode 100644 index 0000000000000000000000000000000000000000..5b39b8bd2e101f967ea51fbbc8e565b8a2af9b03 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/analysis/capsule_deps.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from mypyc.ir.class_ir import ClassIR +from mypyc.ir.deps import Dependency +from mypyc.ir.func_ir import FuncIR +from mypyc.ir.ops import Assign, CallC, PrimitiveOp +from mypyc.ir.rtypes import RStruct, RTuple, RType, RUnion, RVec + + +def find_implicit_op_dependencies(fn: FuncIR) -> set[Dependency] | None: + """Find implicit dependencies that need to be imported. + + Using primitives or types defined in librt submodules such as "librt.base64" + requires dependency imports (e.g., capsule imports). + + Note that a module can depend on a librt module even if it doesn't explicitly + import it, for example via re-exported names or via return types of functions + defined in other modules. + """ + deps: set[Dependency] | None = None + # Check function signature types for dependencies + deps = find_type_dependencies(fn, deps) + # Check ops for dependencies + for block in fn.blocks: + for op in block.ops: + assert not isinstance(op, PrimitiveOp), "Lowered IR is expected" + if isinstance(op, CallC) and op.dependencies is not None: + for dep in op.dependencies: + if deps is None: + deps = set() + deps.add(dep) + deps = collect_type_deps(op.type, deps) + if isinstance(op, Assign): + deps = collect_type_deps(op.dest.type, deps) + return deps + + +def find_type_dependencies(fn: FuncIR, deps: set[Dependency] | None) -> set[Dependency] | None: + """Find dependencies from RTypes in function signatures. + + Some RTypes (e.g., those for librt types) have associated dependencies + that need to be imported when the type is used. + """ + # Check parameter types + for arg in fn.decl.sig.args: + deps = collect_type_deps(arg.type, deps) + # Check return type + deps = collect_type_deps(fn.decl.sig.ret_type, deps) + return deps + + +def find_class_dependencies(cl: ClassIR) -> set[Dependency] | None: + """Find dependencies from class attribute types.""" + deps: set[Dependency] | None = None + for base in cl.mro: + for attr_type in base.attributes.values(): + deps = collect_type_deps(attr_type, deps) + return deps + + +def collect_type_deps(typ: RType, deps: set[Dependency] | None) -> set[Dependency] | None: + """Collect dependencies from an RType, recursively checking compound types.""" + if typ.dependencies is not None: + for dep in typ.dependencies: + if deps is None: + deps = set() + deps.add(dep) + if isinstance(typ, RUnion): + for item in typ.items: + deps = collect_type_deps(item, deps) + elif isinstance(typ, RTuple): + for item in typ.types: + deps = collect_type_deps(item, deps) + elif isinstance(typ, RStruct): + for item in typ.types: + deps = collect_type_deps(item, deps) + elif isinstance(typ, RVec): + deps = collect_type_deps(typ.item_type, deps) + return deps diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ef2ffcdcf55c9d715c5064229a3371a6a46f102e Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.py b/micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.py new file mode 100644 index 0000000000000000000000000000000000000000..480a725a0aecc8341be16aa655aecbfe61e0a90d --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/analysis/dataflow.py @@ -0,0 +1,645 @@ +"""Data-flow analyses.""" + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Iterable, Iterator, Set as AbstractSet +from typing import Any, Generic, TypeVar + +from mypyc.ir.ops import ( + Assign, + AssignMulti, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + ControlOp, + DecRef, + Extend, + Float, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElement, + GetElementPtr, + Goto, + IncRef, + InitStatic, + Integer, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + Op, + OpVisitor, + PrimitiveOp, + RaiseStandardError, + RegisterOp, + Return, + SetAttr, + SetElement, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Undef, + Unreachable, + Value, +) + + +class CFG: + """Control-flow graph. + + Node 0 is always assumed to be the entry point. There must be a + non-empty set of exits. + """ + + def __init__( + self, + succ: dict[BasicBlock, list[BasicBlock]], + pred: dict[BasicBlock, list[BasicBlock]], + exits: set[BasicBlock], + ) -> None: + assert exits + self.succ = succ + self.pred = pred + self.exits = exits + + def __str__(self) -> str: + exits = sorted(self.exits, key=lambda e: int(e.label)) + return f"exits: {exits}\nsucc: {self.succ}\npred: {self.pred}" + + +def get_cfg(blocks: list[BasicBlock], *, use_yields: bool = False) -> CFG: + """Calculate basic block control-flow graph. + + If use_yields is set, then we treat returns inserted by yields as gotos + instead of exits. + """ + succ_map = {} + pred_map: dict[BasicBlock, list[BasicBlock]] = {} + exits = set() + for block in blocks: + assert not any( + isinstance(op, ControlOp) for op in block.ops[:-1] + ), "Control-flow ops must be at the end of blocks" + + if use_yields and isinstance(block.terminator, Return) and block.terminator.yield_target: + succ = [block.terminator.yield_target] + else: + succ = list(block.terminator.targets()) + if not succ: + exits.add(block) + + # Errors can occur anywhere inside a block, which means that + # we can't assume that the entire block has executed before + # jumping to the error handler. In our CFG construction, we + # model this as saying that a block can jump to its error + # handler or the error handlers of any of its normal + # successors (to represent an error before that next block + # completes). This works well for analyses like "must + # defined", where it implies that registers assigned in a + # block may be undefined in its error handler, but is in + # general not a precise representation of reality; any + # analyses that require more fidelity must wait until after + # exception insertion. + for error_point in [block] + succ: + if error_point.error_handler: + succ.append(error_point.error_handler) + + succ_map[block] = succ + pred_map[block] = [] + for prev, nxt in succ_map.items(): + for label in nxt: + pred_map[label].append(prev) + return CFG(succ_map, pred_map, exits) + + +def get_real_target(label: BasicBlock) -> BasicBlock: + if len(label.ops) == 1 and isinstance(label.ops[-1], Goto): + label = label.ops[-1].label + return label + + +def cleanup_cfg(blocks: list[BasicBlock]) -> None: + """Cleanup the control flow graph. + + This eliminates obviously dead basic blocks and eliminates blocks that contain + nothing but a single jump. + + There is a lot more that could be done. + """ + changed = True + while changed: + # First collapse any jumps to basic block that only contain a goto + for block in blocks: + for i, tgt in enumerate(block.terminator.targets()): + block.terminator.set_target(i, get_real_target(tgt)) + + # Then delete any blocks that have no predecessors + changed = False + cfg = get_cfg(blocks) + orig_blocks = blocks.copy() + blocks.clear() + for i, block in enumerate(orig_blocks): + if i == 0 or cfg.pred[block]: + blocks.append(block) + else: + changed = True + + +T = TypeVar("T") + +AnalysisDict = dict[tuple[BasicBlock, int], set[T]] + + +class AnalysisResult(Generic[T]): + def __init__(self, before: AnalysisDict[T], after: AnalysisDict[T]) -> None: + self.before = before + self.after = after + + def __str__(self) -> str: + return f"before: {self.before}\nafter: {self.after}\n" + + +GenAndKill = tuple[AbstractSet[T], AbstractSet[T]] + +_EMPTY: tuple[frozenset[Any], frozenset[Any]] = (frozenset(), frozenset()) + + +class BaseAnalysisVisitor(OpVisitor[GenAndKill[T]]): + def visit_goto(self, op: Goto) -> GenAndKill[T]: + return _EMPTY + + @abstractmethod + def visit_register_op(self, op: RegisterOp) -> GenAndKill[T]: + raise NotImplementedError + + @abstractmethod + def visit_assign(self, op: Assign) -> GenAndKill[T]: + raise NotImplementedError + + @abstractmethod + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[T]: + raise NotImplementedError + + @abstractmethod + def visit_set_mem(self, op: SetMem) -> GenAndKill[T]: + raise NotImplementedError + + def visit_inc_ref(self, op: IncRef) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_dec_ref(self, op: DecRef) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_call(self, op: Call) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_method_call(self, op: MethodCall) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_error_value(self, op: LoadErrorValue) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_literal(self, op: LoadLiteral) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_get_attr(self, op: GetAttr) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_set_attr(self, op: SetAttr) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_static(self, op: LoadStatic) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_init_static(self, op: InitStatic) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_tuple_get(self, op: TupleGet) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_tuple_set(self, op: TupleSet) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_box(self, op: Box) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_unbox(self, op: Unbox) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_cast(self, op: Cast) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_call_c(self, op: CallC) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_truncate(self, op: Truncate) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_extend(self, op: Extend) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_global(self, op: LoadGlobal) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_int_op(self, op: IntOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_float_op(self, op: FloatOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_float_neg(self, op: FloatNeg) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_comparison_op(self, op: ComparisonOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_mem(self, op: LoadMem) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_get_element(self, op: GetElement) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_get_element_ptr(self, op: GetElementPtr) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_set_element(self, op: SetElement) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_load_address(self, op: LoadAddress) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_keep_alive(self, op: KeepAlive) -> GenAndKill[T]: + return self.visit_register_op(op) + + def visit_unborrow(self, op: Unborrow) -> GenAndKill[T]: + return self.visit_register_op(op) + + +class DefinedVisitor(BaseAnalysisVisitor[Value]): + """Visitor for finding defined registers. + + Note that this only deals with registers and not temporaries, on + the assumption that we never access temporaries when they might be + undefined. + + If strict_errors is True, then we regard any use of LoadErrorValue + as making a register undefined. Otherwise we only do if + `undefines` is set on the error value. + + This lets us only consider the things we care about during + uninitialized variable checking while capturing all possibly + undefined things for refcounting. + """ + + def __init__(self, strict_errors: bool = False) -> None: + self.strict_errors = strict_errors + + def visit_branch(self, op: Branch) -> GenAndKill[Value]: + return _EMPTY + + def visit_return(self, op: Return) -> GenAndKill[Value]: + return _EMPTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]: + return _EMPTY + + def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]: + return _EMPTY + + def visit_assign(self, op: Assign) -> GenAndKill[Value]: + # Loading an error value may undefine the register. + if isinstance(op.src, LoadErrorValue) and (op.src.undefines or self.strict_errors): + return set(), {op.dest} + else: + return {op.dest}, set() + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]: + # Array registers are special and we don't track the definedness of them. + return _EMPTY + + def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]: + return _EMPTY + + +def analyze_maybe_defined_regs( + blocks: list[BasicBlock], cfg: CFG, initial_defined: set[Value] +) -> AnalysisResult[Value]: + """Calculate potentially defined registers at each CFG location. + + A register is defined if it has a value along some path from the initial location. + """ + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=DefinedVisitor(), + initial=initial_defined, + backward=False, + kind=MAYBE_ANALYSIS, + ) + + +def analyze_must_defined_regs( + blocks: list[BasicBlock], + cfg: CFG, + initial_defined: set[Value], + regs: Iterable[Value], + strict_errors: bool = False, +) -> AnalysisResult[Value]: + """Calculate always defined registers at each CFG location. + + This analysis can work before exception insertion, since it is a + sound assumption that registers defined in a block might not be + initialized in its error handler. + + A register is defined if it has a value along all paths from the + initial location. + """ + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=DefinedVisitor(strict_errors=strict_errors), + initial=initial_defined, + backward=False, + kind=MUST_ANALYSIS, + universe=set(regs), + ) + + +class BorrowedArgumentsVisitor(BaseAnalysisVisitor[Value]): + def __init__(self, args: set[Value]) -> None: + self.args = args + + def visit_branch(self, op: Branch) -> GenAndKill[Value]: + return _EMPTY + + def visit_return(self, op: Return) -> GenAndKill[Value]: + return _EMPTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]: + return _EMPTY + + def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]: + return _EMPTY + + def visit_assign(self, op: Assign) -> GenAndKill[Value]: + if op.dest in self.args: + return set(), {op.dest} + return _EMPTY + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]: + return _EMPTY + + def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]: + return _EMPTY + + +def analyze_borrowed_arguments( + blocks: list[BasicBlock], cfg: CFG, borrowed: set[Value] +) -> AnalysisResult[Value]: + """Calculate arguments that can use references borrowed from the caller. + + When assigning to an argument, it no longer is borrowed. + """ + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=BorrowedArgumentsVisitor(borrowed), + initial=borrowed, + backward=False, + kind=MUST_ANALYSIS, + universe=borrowed, + ) + + +class UndefinedVisitor(BaseAnalysisVisitor[Value]): + def visit_branch(self, op: Branch) -> GenAndKill[Value]: + return _EMPTY + + def visit_return(self, op: Return) -> GenAndKill[Value]: + return _EMPTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]: + return _EMPTY + + def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]: + return set(), {op} if not op.is_void else set() + + def visit_assign(self, op: Assign) -> GenAndKill[Value]: + return set(), {op.dest} + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]: + return set(), {op.dest} + + def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]: + return _EMPTY + + +def non_trivial_sources(op: Op) -> set[Value]: + result = set() + for source in op.sources(): + if not isinstance(source, (Integer, Float, Undef)): + result.add(source) + return result + + +class LivenessVisitor(BaseAnalysisVisitor[Value]): + def visit_branch(self, op: Branch) -> GenAndKill[Value]: + return non_trivial_sources(op), set() + + def visit_return(self, op: Return) -> GenAndKill[Value]: + if not isinstance(op.value, (Integer, Float)): + return {op.value}, set() + else: + return _EMPTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]: + return _EMPTY + + def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]: + gen = non_trivial_sources(op) + if not op.is_void: + return gen, {op} + else: + return gen, set() + + def visit_assign(self, op: Assign) -> GenAndKill[Value]: + return non_trivial_sources(op), {op.dest} + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]: + return non_trivial_sources(op), {op.dest} + + def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]: + return non_trivial_sources(op), set() + + def visit_inc_ref(self, op: IncRef) -> GenAndKill[Value]: + return _EMPTY + + def visit_dec_ref(self, op: DecRef) -> GenAndKill[Value]: + return _EMPTY + + +def analyze_live_regs(blocks: list[BasicBlock], cfg: CFG) -> AnalysisResult[Value]: + """Calculate live registers at each CFG location. + + A register is live at a location if it can be read along some CFG path starting + from the location. + """ + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=LivenessVisitor(), + initial=set(), + backward=True, + kind=MAYBE_ANALYSIS, + ) + + +# Analysis kinds +MUST_ANALYSIS = 0 +MAYBE_ANALYSIS = 1 + + +def run_analysis( + blocks: list[BasicBlock], + cfg: CFG, + gen_and_kill: OpVisitor[GenAndKill[T]], + initial: set[T], + kind: int, + backward: bool, + universe: set[T] | None = None, +) -> AnalysisResult[T]: + """Run a general set-based data flow analysis. + + Args: + blocks: All basic blocks + cfg: Control-flow graph for the code + gen_and_kill: Implementation of gen and kill functions for each op + initial: Value of analysis for the entry points (for a forward analysis) or the + exit points (for a backward analysis) + kind: MUST_ANALYSIS or MAYBE_ANALYSIS + backward: If False, the analysis is a forward analysis; it's backward otherwise + universe: For a must analysis, the set of all possible values. This is the starting + value for the work list algorithm, which will narrow this down until reaching a + fixed point. For a maybe analysis the iteration always starts from an empty set + and this argument is ignored. + + Return analysis results: (before, after) + """ + block_gen = {} + block_kill = {} + + # Calculate kill and gen sets for entire basic blocks. + for block in blocks: + gen: set[T] = set() + kill: set[T] = set() + ops = block.ops + if backward: + ops = list(reversed(ops)) + for op in ops: + opgen, opkill = op.accept(gen_and_kill) + if opkill: + gen -= opkill + + if opgen: + gen |= opgen + kill -= opgen + + if opkill: + kill |= opkill + + block_gen[block] = gen + block_kill[block] = kill + + # Set up initial state for worklist algorithm. + worklist = list(blocks) + if not backward: + worklist.reverse() # Reverse for a small performance improvement + workset = set(worklist) + before: dict[BasicBlock, set[T]] = {} + after: dict[BasicBlock, set[T]] = {} + for block in blocks: + if kind == MAYBE_ANALYSIS: + before[block] = set() + after[block] = set() + else: + assert universe is not None, "Universe must be defined for a must analysis" + before[block] = set(universe) + after[block] = set(universe) + + if backward: + pred_map = cfg.succ + succ_map = cfg.pred + else: + pred_map = cfg.pred + succ_map = cfg.succ + + # Run work list algorithm to generate in and out sets for each basic block. + while worklist: + label = worklist.pop() + workset.remove(label) + if pred_map[label]: + new_before: set[T] | None = None + for pred in pred_map[label]: + if new_before is None: + new_before = set(after[pred]) + elif kind == MAYBE_ANALYSIS: + new_before |= after[pred] + else: + new_before &= after[pred] + assert new_before is not None + else: + new_before = set(initial) + before[label] = new_before + new_after = (new_before - block_kill[label]) | block_gen[label] + if new_after != after[label]: + for succ in succ_map[label]: + if succ not in workset: + worklist.append(succ) + workset.add(succ) + after[label] = new_after + + # Run algorithm for each basic block to generate opcode-level sets. + op_before: dict[tuple[BasicBlock, int], set[T]] = {} + op_after: dict[tuple[BasicBlock, int], set[T]] = {} + for block in blocks: + label = block + cur = before[label] + ops_enum: Iterator[tuple[int, Op]] = enumerate(block.ops) + if backward: + ops_enum = reversed(list(ops_enum)) + for idx, op in ops_enum: + op_before[label, idx] = cur + opgen, opkill = op.accept(gen_and_kill) + if opkill: + cur = cur - opkill + if opgen: + cur = cur | opgen + op_after[label, idx] = cur + if backward: + op_after, op_before = op_before, op_after + + return AnalysisResult(op_before, op_after) diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/ircheck.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/analysis/ircheck.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..67883b7b09d7498de35a1b905a234570f7ea3a1e Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/analysis/ircheck.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/ircheck.py b/micromamba_root/Lib/site-packages/mypyc/analysis/ircheck.py new file mode 100644 index 0000000000000000000000000000000000000000..384bcdbe5cd801ccdf9b1a3d22351245bfd7db90 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/analysis/ircheck.py @@ -0,0 +1,498 @@ +"""Utilities for checking that internal ir is valid and consistent.""" + +from __future__ import annotations + +from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncIR +from mypyc.ir.ops import ( + Assign, + AssignMulti, + BaseAssign, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + ControlOp, + DecRef, + Extend, + Float, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElement, + GetElementPtr, + Goto, + IncRef, + InitStatic, + Integer, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + Op, + OpVisitor, + PrimitiveOp, + RaiseStandardError, + Register, + Return, + SetAttr, + SetElement, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Undef, + Unreachable, + Value, +) +from mypyc.ir.pprint import format_func +from mypyc.ir.rtypes import ( + KNOWN_NATIVE_TYPES, + RArray, + RInstance, + RPrimitive, + RType, + RUnion, + RVec, + bytes_rprimitive, + dict_rprimitive, + int_rprimitive, + is_c_py_ssize_t_rprimitive, + is_fixed_width_rtype, + is_float_rprimitive, + is_object_rprimitive, + is_pointer_rprimitive, + list_rprimitive, + pointer_rprimitive, + range_rprimitive, + set_rprimitive, + str_rprimitive, + tuple_rprimitive, +) + + +class FnError: + def __init__(self, source: Op | BasicBlock, desc: str) -> None: + self.source = source + self.desc = desc + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, FnError) and self.source == other.source and self.desc == other.desc + ) + + def __repr__(self) -> str: + return f"FnError(source={self.source}, desc={self.desc})" + + +def check_func_ir(fn: FuncIR) -> list[FnError]: + """Applies validations to a given function ir and returns a list of errors found.""" + errors = [] + + op_set = set() + + for block in fn.blocks: + if not block.terminated: + errors.append( + FnError(source=block.ops[-1] if block.ops else block, desc="Block not terminated") + ) + for op in block.ops[:-1]: + if isinstance(op, ControlOp): + errors.append(FnError(source=op, desc="Block has operations after control op")) + + if op in op_set: + errors.append(FnError(source=op, desc="Func has a duplicate op")) + op_set.add(op) + + errors.extend(check_op_sources_valid(fn)) + if errors: + return errors + + op_checker = OpChecker(fn) + for block in fn.blocks: + for op in block.ops: + op.accept(op_checker) + + return op_checker.errors + + +class IrCheckException(Exception): + pass + + +def assert_func_ir_valid(fn: FuncIR) -> None: + errors = check_func_ir(fn) + if errors: + raise IrCheckException( + "Internal error: Generated invalid IR: \n" + + "\n".join(format_func(fn, [(e.source, e.desc) for e in errors])) + ) + + +def check_op_sources_valid(fn: FuncIR) -> list[FnError]: + errors = [] + valid_ops: set[Op] = set() + valid_registers: set[Register] = set() + + for block in fn.blocks: + valid_ops.update(block.ops) + + for op in block.ops: + if isinstance(op, BaseAssign): + valid_registers.add(op.dest) + elif isinstance(op, LoadAddress) and isinstance(op.src, Register): + valid_registers.add(op.src) + + valid_registers.update(fn.arg_regs) + + for block in fn.blocks: + for op in block.ops: + for source in op.sources(): + if isinstance(source, (Integer, Float, Undef)): + pass + elif isinstance(source, Op): + if source not in valid_ops: + errors.append( + FnError( + source=op, + desc=f"Invalid op reference to op of type {type(source).__name__}", + ) + ) + elif isinstance(source, Register): + if source not in valid_registers: + errors.append( + FnError( + source=op, desc=f"Invalid op reference to register {source.name!r}" + ) + ) + + return errors + + +disjoint_types = { + int_rprimitive.name, + bytes_rprimitive.name, + str_rprimitive.name, + dict_rprimitive.name, + list_rprimitive.name, + set_rprimitive.name, + tuple_rprimitive.name, + range_rprimitive.name, +} | set(KNOWN_NATIVE_TYPES) + + +def can_coerce_to(src: RType, dest: RType) -> bool: + """Check if src can be assigned to dest_rtype. + + Currently okay to have false positives. + """ + if isinstance(dest, RUnion): + return any(can_coerce_to(src, d) for d in dest.items) + + if isinstance(dest, RPrimitive): + if isinstance(src, RPrimitive): + # If either src or dest is a disjoint type, then they must both be. + if src.name in disjoint_types and dest.name in disjoint_types: + return src.name == dest.name + return src.size == dest.size + if isinstance(src, (RInstance, RVec)): + return is_object_rprimitive(dest) + if isinstance(src, RUnion): + # IR doesn't have the ability to narrow unions based on + # control flow, so cannot be a strict all() here. + return any(can_coerce_to(s, dest) for s in src.items) + return False + + return True + + +def is_valid_ptr_displacement_type(rtype: RType) -> bool: + """Check if rtype is a valid displacement type for pointer arithmetic.""" + if not (is_fixed_width_rtype(rtype) or is_c_py_ssize_t_rprimitive(rtype)): + return False + assert isinstance(rtype, RPrimitive) + return rtype.size == pointer_rprimitive.size + + +def is_pointer_arithmetic(op: IntOp) -> bool: + """Check if op is add/subtract targeting pointer_rprimitive and integer of the same size.""" + if op.op not in (IntOp.ADD, IntOp.SUB): + return False + if not is_pointer_rprimitive(op.type): + return False + left = op.lhs.type + right = op.rhs.type + if is_pointer_rprimitive(left): + return is_valid_ptr_displacement_type(right) + if is_pointer_rprimitive(right): + return is_valid_ptr_displacement_type(left) + return False + + +class OpChecker(OpVisitor[None]): + def __init__(self, parent_fn: FuncIR) -> None: + self.parent_fn = parent_fn + self.errors: list[FnError] = [] + + def fail(self, source: Op, desc: str) -> None: + self.errors.append(FnError(source=source, desc=desc)) + + def check_control_op_targets(self, op: ControlOp) -> None: + for target in op.targets(): + if target not in self.parent_fn.blocks: + self.fail(source=op, desc=f"Invalid control operation target: {target.label}") + + def check_type_coercion(self, op: Op, src: RType, dest: RType) -> None: + if not can_coerce_to(src, dest): + self.fail( + source=op, desc=f"Cannot coerce source type {src.name} to dest type {dest.name}" + ) + + def check_compatibility(self, op: Op, t: RType, s: RType) -> None: + if not can_coerce_to(t, s) or not can_coerce_to(s, t): + self.fail(source=op, desc=f"{t.name} and {s.name} are not compatible") + + def expect_float(self, op: Op, v: Value) -> None: + if not is_float_rprimitive(v.type): + self.fail(op, f"Float expected (actual type is {v.type})") + + def expect_non_float(self, op: Op, v: Value) -> None: + if is_float_rprimitive(v.type): + self.fail(op, "Float not expected") + + def expect_primitive_type(self, op: Op, v: Value) -> None: + if not isinstance(v.type, RPrimitive): + self.fail(op, f"RPrimitive expected, got {type(v.type).__name__}") + + def visit_goto(self, op: Goto) -> None: + self.check_control_op_targets(op) + + def visit_branch(self, op: Branch) -> None: + self.check_control_op_targets(op) + + def visit_return(self, op: Return) -> None: + self.check_type_coercion(op, op.value.type, self.parent_fn.decl.sig.ret_type) + + def visit_unreachable(self, op: Unreachable) -> None: + # Unreachables are checked at a higher level since validation + # requires access to the entire basic block. + pass + + def visit_assign(self, op: Assign) -> None: + self.check_type_coercion(op, op.src.type, op.dest.type) + + def visit_assign_multi(self, op: AssignMulti) -> None: + for src in op.src: + assert isinstance(op.dest.type, RArray) + self.check_type_coercion(op, src.type, op.dest.type.item_type) + + def visit_load_error_value(self, op: LoadErrorValue) -> None: + # Currently it is assumed that all types have an error value. + # Once this is fixed we can validate that the rtype here actually + # has an error value. + pass + + def check_tuple_items_valid_literals(self, op: LoadLiteral, t: tuple[object, ...]) -> None: + for x in t: + if x is not None and not isinstance(x, (str, bytes, bool, int, float, complex, tuple)): + self.fail(op, f"Invalid type for item of tuple literal: {type(x)})") + if isinstance(x, tuple): + self.check_tuple_items_valid_literals(op, x) + + def check_frozenset_items_valid_literals(self, op: LoadLiteral, s: frozenset[object]) -> None: + for x in s: + if x is None or isinstance(x, (str, bytes, bool, int, float, complex)): + pass + elif isinstance(x, tuple): + self.check_tuple_items_valid_literals(op, x) + else: + self.fail(op, f"Invalid type for item of frozenset literal: {type(x)})") + + def visit_load_literal(self, op: LoadLiteral) -> None: + expected_type = None + if op.value is None: + expected_type = "builtins.object" + elif isinstance(op.value, int): + expected_type = "builtins.int" + elif isinstance(op.value, str): + expected_type = "builtins.str" + elif isinstance(op.value, bytes): + expected_type = "builtins.bytes" + elif isinstance(op.value, float): + expected_type = "builtins.float" + elif isinstance(op.value, complex): + expected_type = "builtins.object" + elif isinstance(op.value, tuple): + expected_type = "builtins.tuple" + self.check_tuple_items_valid_literals(op, op.value) + elif isinstance(op.value, frozenset): + # There's no frozenset_rprimitive type since it'd be pretty useless so we just pretend + # it's a set (when it's really a frozenset). + expected_type = "builtins.set" + self.check_frozenset_items_valid_literals(op, op.value) + + assert expected_type is not None, "Missed a case for LoadLiteral check" + + if op.type.name not in [expected_type, "builtins.object"]: + self.fail( + op, + f"Invalid literal value for type: value has " + f"type {expected_type}, but op has type {op.type.name}", + ) + + def visit_get_attr(self, op: GetAttr) -> None: + # Nothing to do. + pass + + def visit_set_attr(self, op: SetAttr) -> None: + # Nothing to do. + pass + + # Static operations cannot be checked at the function level. + def visit_load_static(self, op: LoadStatic) -> None: + pass + + def visit_init_static(self, op: InitStatic) -> None: + pass + + def visit_tuple_get(self, op: TupleGet) -> None: + # Nothing to do. + pass + + def visit_tuple_set(self, op: TupleSet) -> None: + # Nothing to do. + pass + + def visit_inc_ref(self, op: IncRef) -> None: + # Nothing to do. + pass + + def visit_dec_ref(self, op: DecRef) -> None: + # Nothing to do. + pass + + def visit_call(self, op: Call) -> None: + # Length is checked in constructor, and return type is set + # in a way that can't be incorrect + for arg_value, arg_runtime in zip(op.args, op.fn.sig.args): + self.check_type_coercion(op, arg_value.type, arg_runtime.type) + + def visit_method_call(self, op: MethodCall) -> None: + # Similar to above, but we must look up method first. + method_decl = op.receiver_type.class_ir.method_decl(op.method) + if method_decl.kind == FUNC_STATICMETHOD: + decl_index = 0 + else: + decl_index = 1 + + if len(op.args) + decl_index != len(method_decl.sig.args): + self.fail(op, "Incorrect number of args for method call.") + + # Skip the receiver argument (self) + for arg_value, arg_runtime in zip(op.args, method_decl.sig.args[decl_index:]): + self.check_type_coercion(op, arg_value.type, arg_runtime.type) + + def visit_cast(self, op: Cast) -> None: + pass + + def visit_box(self, op: Box) -> None: + pass + + def visit_unbox(self, op: Unbox) -> None: + pass + + def visit_raise_standard_error(self, op: RaiseStandardError) -> None: + pass + + def visit_call_c(self, op: CallC) -> None: + pass + + def visit_primitive_op(self, op: PrimitiveOp) -> None: + pass + + def visit_truncate(self, op: Truncate) -> None: + pass + + def visit_extend(self, op: Extend) -> None: + pass + + def visit_load_global(self, op: LoadGlobal) -> None: + pass + + def visit_int_op(self, op: IntOp) -> None: + self.expect_primitive_type(op, op.lhs) + self.expect_primitive_type(op, op.rhs) + self.expect_non_float(op, op.lhs) + self.expect_non_float(op, op.rhs) + left = op.lhs.type + right = op.rhs.type + op_str = op.op_str[op.op] + if ( + isinstance(left, RPrimitive) + and isinstance(right, RPrimitive) + and left.is_signed != right.is_signed + and ( + op_str in ("+", "-", "*", "/", "%") + or (op_str not in ("<<", ">>") and left.size != right.size) + ) + and not is_pointer_arithmetic(op) + ): + self.fail(op, f"Operand types have incompatible signs: {left}, {right}") + + def visit_comparison_op(self, op: ComparisonOp) -> None: + self.check_compatibility(op, op.lhs.type, op.rhs.type) + self.expect_non_float(op, op.lhs) + self.expect_non_float(op, op.rhs) + left = op.lhs.type + right = op.rhs.type + if ( + isinstance(left, RPrimitive) + and isinstance(right, RPrimitive) + and left.is_signed != right.is_signed + ): + self.fail(op, f"Operand types have incompatible signs: {left}, {right}") + + def visit_float_op(self, op: FloatOp) -> None: + self.expect_float(op, op.lhs) + self.expect_float(op, op.rhs) + + def visit_float_neg(self, op: FloatNeg) -> None: + self.expect_float(op, op.src) + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> None: + self.expect_float(op, op.lhs) + self.expect_float(op, op.rhs) + + def visit_load_mem(self, op: LoadMem) -> None: + pass + + def visit_set_mem(self, op: SetMem) -> None: + pass + + def visit_get_element(self, op: GetElement) -> None: + pass + + def visit_get_element_ptr(self, op: GetElementPtr) -> None: + pass + + def visit_set_element(self, op: SetElement) -> None: + pass + + def visit_load_address(self, op: LoadAddress) -> None: + pass + + def visit_keep_alive(self, op: KeepAlive) -> None: + pass + + def visit_unborrow(self, op: Unborrow) -> None: + pass diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..85af78d1ca58b1e663908d208e0d32d02b8cab81 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.py b/micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc7ef3fb4c685603ca0bda47f5b26af8fa7c610 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/analysis/selfleaks.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +from mypyc.analysis.dataflow import ( + CFG, + MAYBE_ANALYSIS, + AnalysisResult, + GenAndKill as _DataflowGenAndKill, + run_analysis, +) +from mypyc.ir.ops import ( + Assign, + AssignMulti, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + DecRef, + Extend, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElement, + GetElementPtr, + Goto, + IncRef, + InitStatic, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + OpVisitor, + PrimitiveOp, + RaiseStandardError, + Register, + RegisterOp, + Return, + SetAttr, + SetElement, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Unreachable, +) +from mypyc.ir.rtypes import RInstance + +GenAndKill = _DataflowGenAndKill[None] + +CLEAN: GenAndKill = (set(), set()) +DIRTY: GenAndKill = ({None}, {None}) + + +class SelfLeakedVisitor(OpVisitor[GenAndKill]): + """Analyze whether 'self' may be seen by arbitrary code in '__init__'. + + More formally, the set is not empty if along some path from IR entry point + arbitrary code could have been executed that has access to 'self'. + + (We don't consider access via 'gc.get_objects()'.) + """ + + def __init__(self, self_reg: Register) -> None: + self.self_reg = self_reg + + def visit_goto(self, op: Goto) -> GenAndKill: + return CLEAN + + def visit_branch(self, op: Branch) -> GenAndKill: + return CLEAN + + def visit_return(self, op: Return) -> GenAndKill: + # Consider all exits from the function 'dirty' since they implicitly + # cause 'self' to be returned. + return DIRTY + + def visit_unreachable(self, op: Unreachable) -> GenAndKill: + return CLEAN + + def visit_assign(self, op: Assign) -> GenAndKill: + if op.src is self.self_reg or op.dest is self.self_reg: + return DIRTY + return CLEAN + + def visit_assign_multi(self, op: AssignMulti) -> GenAndKill: + return CLEAN + + def visit_set_mem(self, op: SetMem) -> GenAndKill: + return CLEAN + + def visit_inc_ref(self, op: IncRef) -> GenAndKill: + return CLEAN + + def visit_dec_ref(self, op: DecRef) -> GenAndKill: + return CLEAN + + def visit_call(self, op: Call) -> GenAndKill: + fn = op.fn + if fn.class_name and fn.name == "__init__": + self_type = op.fn.sig.args[0].type + assert isinstance(self_type, RInstance), self_type + cl = self_type.class_ir + if not cl.init_self_leak: + return CLEAN + return self.check_register_op(op) + + def visit_method_call(self, op: MethodCall) -> GenAndKill: + return self.check_register_op(op) + + def visit_load_error_value(self, op: LoadErrorValue) -> GenAndKill: + return CLEAN + + def visit_load_literal(self, op: LoadLiteral) -> GenAndKill: + return CLEAN + + def visit_get_attr(self, op: GetAttr) -> GenAndKill: + cl = op.class_type.class_ir + if cl.get_method(op.attr): + # Property -- calls a function + return self.check_register_op(op) + return CLEAN + + def visit_set_attr(self, op: SetAttr) -> GenAndKill: + cl = op.class_type.class_ir + if cl.get_method(op.attr): + # Property - calls a function + return self.check_register_op(op) + return CLEAN + + def visit_load_static(self, op: LoadStatic) -> GenAndKill: + return CLEAN + + def visit_init_static(self, op: InitStatic) -> GenAndKill: + return self.check_register_op(op) + + def visit_tuple_get(self, op: TupleGet) -> GenAndKill: + return CLEAN + + def visit_tuple_set(self, op: TupleSet) -> GenAndKill: + return self.check_register_op(op) + + def visit_box(self, op: Box) -> GenAndKill: + return self.check_register_op(op) + + def visit_unbox(self, op: Unbox) -> GenAndKill: + return self.check_register_op(op) + + def visit_cast(self, op: Cast) -> GenAndKill: + return self.check_register_op(op) + + def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill: + return CLEAN + + def visit_call_c(self, op: CallC) -> GenAndKill: + return self.check_register_op(op) + + def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill: + return self.check_register_op(op) + + def visit_truncate(self, op: Truncate) -> GenAndKill: + return CLEAN + + def visit_extend(self, op: Extend) -> GenAndKill: + return CLEAN + + def visit_load_global(self, op: LoadGlobal) -> GenAndKill: + return CLEAN + + def visit_int_op(self, op: IntOp) -> GenAndKill: + return CLEAN + + def visit_comparison_op(self, op: ComparisonOp) -> GenAndKill: + return CLEAN + + def visit_float_op(self, op: FloatOp) -> GenAndKill: + return CLEAN + + def visit_float_neg(self, op: FloatNeg) -> GenAndKill: + return CLEAN + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> GenAndKill: + return CLEAN + + def visit_load_mem(self, op: LoadMem) -> GenAndKill: + return CLEAN + + def visit_get_element(self, op: GetElement) -> GenAndKill: + return CLEAN + + def visit_get_element_ptr(self, op: GetElementPtr) -> GenAndKill: + return CLEAN + + def visit_set_element(self, op: SetElement) -> GenAndKill: + return CLEAN + + def visit_load_address(self, op: LoadAddress) -> GenAndKill: + return CLEAN + + def visit_keep_alive(self, op: KeepAlive) -> GenAndKill: + return CLEAN + + def visit_unborrow(self, op: Unborrow) -> GenAndKill: + return CLEAN + + def check_register_op(self, op: RegisterOp) -> GenAndKill: + if any(src is self.self_reg for src in op.sources()): + return DIRTY + return CLEAN + + +def analyze_self_leaks( + blocks: list[BasicBlock], self_reg: Register, cfg: CFG +) -> AnalysisResult[None]: + return run_analysis( + blocks=blocks, + cfg=cfg, + gen_and_kill=SelfLeakedVisitor(self_reg), + initial=set(), + backward=False, + kind=MAYBE_ANALYSIS, + ) diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/__init__.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/codegen/__init__.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..b2293519e1a0c0b0988724999d44a58ee82e56f6 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/codegen/__init__.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/__init__.py b/micromamba_root/Lib/site-packages/mypyc/codegen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/cstring.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/codegen/cstring.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5e21c364a48dc59a872fb8536ef6e4bbf2bcebd0 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/codegen/cstring.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/cstring.py b/micromamba_root/Lib/site-packages/mypyc/codegen/cstring.py new file mode 100644 index 0000000000000000000000000000000000000000..853787f8161d4e9277eaac3312e914816b5e2e60 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/codegen/cstring.py @@ -0,0 +1,54 @@ +"""Encode valid C string literals from Python strings. + +If a character is not allowed in C string literals, it is either emitted +as a simple escape sequence (e.g. '\\n'), or an octal escape sequence +with exactly three digits ('\\oXXX'). Question marks are escaped to +prevent trigraphs in the string literal from being interpreted. Note +that '\\?' is an invalid escape sequence in Python. + +Consider the string literal "AB\\xCDEF". As one would expect, Python +parses it as ['A', 'B', 0xCD, 'E', 'F']. However, the C standard +specifies that all hexadecimal digits immediately following '\\x' will +be interpreted as part of the escape sequence. Therefore, it is +unexpectedly parsed as ['A', 'B', 0xCDEF]. + +Emitting ("AB\\xCD" "EF") would avoid this behaviour. However, we opt +for simplicity and use octal escape sequences instead. They do not +suffer from the same issue as they are defined to parse at most three +octal digits. +""" + +from __future__ import annotations + +import string +from typing import Final + +CHAR_MAP: Final = [f"\\{i:03o}" for i in range(256)] + +# It is safe to use string.printable as it always uses the C locale. +for c in string.printable: + CHAR_MAP[ord(c)] = c + +# These assignments must come last because we prioritize simple escape +# sequences over any other representation. +for c in ("'", '"', "\\", "a", "b", "f", "n", "r", "t", "v"): + escaped = f"\\{c}" + decoded = escaped.encode("ascii").decode("unicode_escape") + CHAR_MAP[ord(decoded)] = escaped + +# This escape sequence is invalid in Python. +CHAR_MAP[ord("?")] = r"\?" + + +def encode_bytes_as_c_string(b: bytes) -> str: + """Produce contents of a C string literal for a byte string, without quotes.""" + escaped = "".join([CHAR_MAP[i] for i in b]) + return escaped + + +def c_string_initializer(value: bytes) -> str: + """Create initializer for a C char[]/ char * variable from a string. + + For example, if value if b'foo', the result would be '"foo"'. + """ + return '"' + encode_bytes_as_c_string(value) + '"' diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/emit.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/codegen/emit.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..da607b25235874ea923b2d554908be6ae30392f8 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/codegen/emit.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/emit.py b/micromamba_root/Lib/site-packages/mypyc/codegen/emit.py new file mode 100644 index 0000000000000000000000000000000000000000..e313c9231564d746a4a914aaef97a4a71b547899 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/codegen/emit.py @@ -0,0 +1,1439 @@ +"""Utilities for emitting C code.""" + +from __future__ import annotations + +import pprint +import sys +import textwrap +from collections.abc import Callable +from typing import Final + +from mypyc.codegen.cstring import c_string_initializer +from mypyc.codegen.literals import Literals +from mypyc.common import ( + ATTR_PREFIX, + BITMAP_BITS, + FAST_ISINSTANCE_MAX_SUBCLASSES, + HAVE_IMMORTAL, + MODULE_PREFIX, + NATIVE_PREFIX, + PREFIX, + REG_PREFIX, + STATIC_PREFIX, + TYPE_PREFIX, + TYPE_VAR_PREFIX, +) +from mypyc.ir.class_ir import ClassIR, all_concrete_classes +from mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncDecl, FuncIR, get_text_signature +from mypyc.ir.ops import ( + NAMESPACE_MODULE, + NAMESPACE_STATIC, + NAMESPACE_TYPE, + NAMESPACE_TYPE_VAR, + BasicBlock, + Value, +) +from mypyc.ir.rtypes import ( + RInstance, + RPrimitive, + RTuple, + RType, + RUnion, + RVec, + int_rprimitive, + is_bool_or_bit_rprimitive, + is_bytearray_rprimitive, + is_bytes_rprimitive, + is_dict_rprimitive, + is_fixed_width_rtype, + is_float_rprimitive, + is_frozenset_rprimitive, + is_int16_rprimitive, + is_int32_rprimitive, + is_int64_rprimitive, + is_int_rprimitive, + is_list_rprimitive, + is_native_rprimitive, + is_none_rprimitive, + is_object_rprimitive, + is_optional_type, + is_range_rprimitive, + is_set_rprimitive, + is_short_int_rprimitive, + is_str_rprimitive, + is_tuple_rprimitive, + is_uint8_rprimitive, + object_rprimitive, + optional_value_type, + vec_api_by_item_type, + vec_item_type_tags, +) +from mypyc.namegen import NameGenerator, exported_name +from mypyc.primitives.registry import builtin_names +from mypyc.sametype import is_same_type + +# Whether to insert debug asserts for all error handling, to quickly +# catch errors propagating without exceptions set. +DEBUG_ERRORS: Final = False + +PREFIX_MAP: Final = { + NAMESPACE_STATIC: STATIC_PREFIX, + NAMESPACE_TYPE: TYPE_PREFIX, + NAMESPACE_MODULE: MODULE_PREFIX, + NAMESPACE_TYPE_VAR: TYPE_VAR_PREFIX, +} + + +class HeaderDeclaration: + """A representation of a declaration in C. + + This is used to generate declarations in header files and + (optionally) definitions in source files. + + Attributes: + decl: C source code for the declaration. + defn: Optionally, C source code for a definition. + dependencies: The names of any objects that must be declared prior. + is_type: Whether the declaration is of a C type. (C types will be declared in + external header files and not marked 'extern'.) + needs_export: Whether the declared object needs to be exported to + other modules in the linking table. + """ + + def __init__( + self, + decl: str | list[str], + defn: list[str] | None = None, + *, + dependencies: set[str] | None = None, + is_type: bool = False, + needs_export: bool = False, + ) -> None: + self.decl = [decl] if isinstance(decl, str) else decl + self.defn = defn + self.dependencies = dependencies or set() + self.is_type = is_type + self.needs_export = needs_export + + +class EmitterContext: + """Shared emitter state for a compilation group.""" + + def __init__( + self, + names: NameGenerator, + strict_traceback_checks: bool, + group_name: str | None = None, + group_map: dict[str, str | None] | None = None, + ) -> None: + """Setup shared emitter state. + + Args: + names: The name generator to use + group_map: Map from module names to group name + group_name: Current group name + """ + self.temp_counter = 0 + self.names = names + self.group_name = group_name + self.group_map = group_map or {} + # Groups that this group depends on + self.group_deps: set[str] = set() + + # The map below is used for generating declarations and + # definitions at the top of the C file. The main idea is that they can + # be generated at any time during the emit phase. + + # A map of a C identifier to whatever the C identifier declares. Currently this is + # used for declaring structs and the key corresponds to the name of the struct. + # The declaration contains the body of the struct. + self.declarations: dict[str, HeaderDeclaration] = {} + + self.literals = Literals() + # See mypyc/options.py for context. + self.strict_traceback_checks = strict_traceback_checks + + +class ErrorHandler: + """Describes handling errors in unbox/cast operations.""" + + +class AssignHandler(ErrorHandler): + """Assign an error value on error.""" + + +class GotoHandler(ErrorHandler): + """Goto label on error.""" + + def __init__(self, label: str) -> None: + self.label = label + + +class TracebackAndGotoHandler(ErrorHandler): + """Add traceback item and goto label on error.""" + + def __init__( + self, label: str, source_path: str, module_name: str, traceback_entry: tuple[str, int] + ) -> None: + self.label = label + self.source_path = source_path + self.module_name = module_name + self.traceback_entry = traceback_entry + + +class ReturnHandler(ErrorHandler): + """Return a constant value on error.""" + + def __init__(self, value: str) -> None: + self.value = value + + +class Emitter: + """Helper for C code generation.""" + + def __init__( + self, + context: EmitterContext, + value_names: dict[Value, str] | None = None, + capi_version: tuple[int, int] | None = None, + filepath: str | None = None, + ) -> None: + self.context = context + self.capi_version = capi_version or sys.version_info[:2] + self.names = context.names + self.value_names = value_names or {} + self.fragments: list[str] = [] + self._indent = 0 + self.filepath = filepath + + # Low-level operations + + def indent(self) -> None: + self._indent += 4 + + def dedent(self) -> None: + self._indent -= 4 + assert self._indent >= 0 + + def label(self, label: BasicBlock) -> str: + return "CPyL%s" % label.label + + def reg(self, reg: Value) -> str: + return REG_PREFIX + self.value_names[reg] + + def attr(self, name: str) -> str: + return ATTR_PREFIX + name + + def object_annotation(self, obj: object, line: str) -> str: + """Build a C comment with an object's string representation. + + If the comment exceeds the line length limit, it's wrapped into a + multiline string (with the extra lines indented to be aligned with + the first line's comment). + + If it contains illegal characters, an empty string is returned.""" + line_width = self._indent + len(line) + formatted = pprint.pformat(obj, compact=True, width=max(90 - line_width, 20)) + if any(x in formatted for x in ("/*", "*/", "\0")): + return "" + + if "\n" in formatted: + first_line, rest = formatted.split("\n", maxsplit=1) + comment_continued = textwrap.indent(rest, (line_width + 3) * " ") + return f" /* {first_line}\n{comment_continued} */" + else: + return f" /* {formatted} */" + + def emit_line(self, line: str = "", *, ann: object = None) -> None: + if line.startswith("}"): + self.dedent() + comment = self.object_annotation(ann, line) if ann is not None else "" + self.fragments.append(self._indent * " " + line + comment + "\n") + if line.endswith("{"): + self.indent() + + def emit_lines(self, *lines: str) -> None: + for line in lines: + self.emit_line(line) + + def emit_label(self, label: BasicBlock | str) -> None: + if isinstance(label, str): + text = label + else: + if label.label == 0 or not label.referenced: + return + + text = self.label(label) + # Extra semicolon prevents an error when the next line declares a tempvar + self.fragments.append(f"{text}: ;\n") + + def emit_from_emitter(self, emitter: Emitter) -> None: + self.fragments.extend(emitter.fragments) + + def emit_printf(self, fmt: str, *args: str) -> None: + fmt = fmt.replace("\n", "\\n") + self.emit_line("printf(%s);" % ", ".join(['"%s"' % fmt] + list(args))) + self.emit_line("fflush(stdout);") + + def temp_name(self) -> str: + self.context.temp_counter += 1 + return "__tmp%d" % self.context.temp_counter + + def new_label(self) -> str: + self.context.temp_counter += 1 + return "__LL%d" % self.context.temp_counter + + def get_module_group_prefix(self, module_name: str) -> str: + """Get the group prefix for a module (relative to the current group). + + The prefix should be prepended to the object name whenever + accessing an object from this module. + + If the module lives is in the current compilation group, there is + no prefix. But if it lives in a different group (and hence a separate + extension module), we need to access objects from it indirectly via an + export table. + + For example, for code in group `a` to call a function `bar` in group `b`, + it would need to do `exports_b.CPyDef_bar(...)`, while code that is + also in group `b` can simply do `CPyDef_bar(...)`. + + Thus the prefix for a module in group `b` is 'exports_b.' if the current + group is *not* b and just '' if it is. + """ + groups = self.context.group_map + target_group_name = groups.get(module_name) + if target_group_name and target_group_name != self.context.group_name: + self.context.group_deps.add(target_group_name) + return f"exports_{exported_name(target_group_name)}." + else: + return "" + + def get_group_prefix(self, obj: ClassIR | FuncDecl) -> str: + """Get the group prefix for an object.""" + # See docs above + return self.get_module_group_prefix(obj.module_name) + + def static_name(self, id: str, module: str | None, prefix: str = STATIC_PREFIX) -> str: + """Create name of a C static variable. + + These are used for literals and imported modules, among other + things. + + The caller should ensure that the (id, module) pair cannot + overlap with other calls to this method within a compilation + group. + """ + lib_prefix = "" if not module else self.get_module_group_prefix(module) + # If we are accessing static via the export table, we need to dereference + # the pointer also. + star_maybe = "*" if lib_prefix else "" + suffix = self.names.private_name(module or "", id) + return f"{star_maybe}{lib_prefix}{prefix}{suffix}" + + def type_struct_name(self, cl: ClassIR) -> str: + return self.static_name(cl.name, cl.module_name, prefix=TYPE_PREFIX) + + def ctype(self, rtype: RType) -> str: + return rtype._ctype + + def ctype_spaced(self, rtype: RType) -> str: + """Adds a space after ctype for non-pointers.""" + ctype = self.ctype(rtype) + if ctype[-1] == "*": + return ctype + else: + return ctype + " " + + def set_undefined_value(self, target: str, rtype: RType) -> None: + if isinstance(rtype, RVec): + self.emit_line(f"{target}.len = -1;") + self.emit_line(f"{target}.buf = NULL;") + else: + self.emit_line(f"{target} = {self.c_undefined_value(rtype)};") + + def c_undefined_value(self, rtype: RType) -> str: + if not rtype.is_unboxed: + return "NULL" + elif isinstance(rtype, RPrimitive): + return rtype.c_undefined + elif isinstance(rtype, RTuple): + return self.tuple_undefined_value(rtype) + elif isinstance(rtype, RVec): + return f"({self.ctype(rtype)}) {{ -1, NULL }}" + assert False, rtype + + def c_error_value(self, rtype: RType) -> str: + return self.c_undefined_value(rtype) + + def native_function_name(self, fn: FuncDecl) -> str: + return f"{NATIVE_PREFIX}{fn.cname(self.names)}" + + def tuple_c_declaration(self, rtuple: RTuple) -> list[str]: + result = [ + f"#ifndef MYPYC_DECLARED_{rtuple.struct_name}", + f"#define MYPYC_DECLARED_{rtuple.struct_name}", + f"typedef struct {rtuple.struct_name} {{", + ] + if len(rtuple.types) == 0: # empty tuple + # Empty tuples contain a flag so that they can still indicate + # error values. + result.append("int empty_struct_error_flag;") + else: + i = 0 + for typ in rtuple.types: + result.append(f"{self.ctype_spaced(typ)}f{i};") + i += 1 + result.append(f"}} {rtuple.struct_name};") + result.append("#endif") + result.append("") + + return result + + def bitmap_field(self, index: int) -> str: + """Return C field name used for attribute bitmap.""" + n = index // BITMAP_BITS + if n == 0: + return "bitmap" + return f"bitmap{n + 1}" + + def attr_bitmap_expr(self, obj: str, cl: ClassIR, index: int) -> str: + """Return reference to the attribute definedness bitmap.""" + cast = f"({cl.struct_name(self.names)} *)" + attr = self.bitmap_field(index) + return f"({cast}{obj})->{attr}" + + def emit_attr_bitmap_set( + self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str + ) -> None: + """Mark an attribute as defined in the attribute bitmap. + + Assumes that the attribute is tracked in the bitmap (only some attributes + use the bitmap). If 'value' is not equal to the error value, do nothing. + """ + self._emit_attr_bitmap_update(value, obj, rtype, cl, attr, clear=False) + + def emit_attr_bitmap_clear(self, obj: str, rtype: RType, cl: ClassIR, attr: str) -> None: + """Mark an attribute as undefined in the attribute bitmap. + + Unlike emit_attr_bitmap_set, clear unconditionally. + """ + self._emit_attr_bitmap_update("", obj, rtype, cl, attr, clear=True) + + def _emit_attr_bitmap_update( + self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str, clear: bool + ) -> None: + if value: + check = self.error_value_check(rtype, value, "==") + self.emit_line(f"if (unlikely({check})) {{") + index = cl.bitmap_attrs.index(attr) + mask = 1 << (index & (BITMAP_BITS - 1)) + bitmap = self.attr_bitmap_expr(obj, cl, index) + if clear: + self.emit_line(f"{bitmap} &= ~{mask};") + else: + self.emit_line(f"{bitmap} |= {mask};") + if value: + self.emit_line("}") + + def emit_undefined_attr_check( + self, + rtype: RType, + attr_expr: str, + compare: str, + obj: str, + attr: str, + cl: ClassIR, + *, + unlikely: bool = False, + ) -> None: + check = self.error_value_check(rtype, attr_expr, compare) + if unlikely: + check = f"unlikely({check})" + if rtype.error_overlap: + index = cl.bitmap_attrs.index(attr) + bit = 1 << (index & (BITMAP_BITS - 1)) + attr = self.bitmap_field(index) + obj_expr = f"({cl.struct_name(self.names)} *){obj}" + check = f"{check} && !(({obj_expr})->{attr} & {bit})" + self.emit_line(f"if ({check}) {{") + + def error_value_check(self, rtype: RType, value: str, compare: str) -> str: + if isinstance(rtype, RTuple): + return self.tuple_undefined_check_cond( + rtype, value, self.c_error_value, compare, check_exception=False + ) + elif isinstance(rtype, RVec): + if compare == "==": + return f"{value}.len < 0" + elif compare == "!=": + return f"{value}.len >= 0" + assert False, compare + else: + return f"{value} {compare} {self.c_error_value(rtype)}" + + def tuple_undefined_check_cond( + self, + rtuple: RTuple, + tuple_expr_in_c: str, + c_type_compare_val: Callable[[RType], str], + compare: str, + *, + check_exception: bool = True, + ) -> str: + if len(rtuple.types) == 0: + # empty tuple + return "{}.empty_struct_error_flag {} {}".format( + tuple_expr_in_c, compare, c_type_compare_val(int_rprimitive) + ) + if rtuple.error_overlap: + i = 0 + item_type = rtuple.types[0] + else: + for i, typ in enumerate(rtuple.types): + if not typ.error_overlap: + item_type = rtuple.types[i] + break + else: + assert False, "not expecting tuple with error overlap" + if isinstance(item_type, RTuple): + return self.tuple_undefined_check_cond( + item_type, tuple_expr_in_c + f".f{i}", c_type_compare_val, compare + ) + elif isinstance(item_type, RVec): + return f"{tuple_expr_in_c}.f{i}.len {compare} -1" + else: + check = f"{tuple_expr_in_c}.f{i} {compare} {c_type_compare_val(item_type)}" + if rtuple.error_overlap and check_exception: + check += " && PyErr_Occurred()" + return check + + def tuple_undefined_value(self, rtuple: RTuple) -> str: + """Undefined tuple value suitable in an expression.""" + return f"({rtuple.struct_name}) {self.c_initializer_undefined_value(rtuple)}" + + def c_initializer_undefined_value(self, rtype: RType) -> str: + """Undefined value represented in a form suitable for variable initialization.""" + if isinstance(rtype, RTuple): + if not rtype.types: + # Empty tuples contain a flag so that they can still indicate + # error values. + return f"{{ {int_rprimitive.c_undefined} }}" + items = ", ".join([self.c_initializer_undefined_value(t) for t in rtype.types]) + return f"{{ {items} }}" + elif isinstance(rtype, RVec): + return "{ -1, NULL }" + else: + return self.c_undefined_value(rtype) + + # Higher-level operations + + def declare_tuple_struct(self, tuple_type: RTuple) -> None: + if tuple_type.struct_name not in self.context.declarations: + dependencies = set() + for typ in tuple_type.types: + # XXX other types might eventually need similar behavior + if isinstance(typ, RTuple): + dependencies.add(typ.struct_name) + + self.context.declarations[tuple_type.struct_name] = HeaderDeclaration( + self.tuple_c_declaration(tuple_type), dependencies=dependencies, is_type=True + ) + + def emit_inc_ref(self, dest: str, rtype: RType, *, rare: bool = False) -> None: + """Increment reference count of C expression `dest`. + + For composite unboxed structures (e.g. tuples) recursively + increment reference counts for each component. + + If rare is True, optimize for code size and compilation speed. + """ + if is_int_rprimitive(rtype): + if rare: + self.emit_line("CPyTagged_IncRef(%s);" % dest) + else: + self.emit_line("CPyTagged_INCREF(%s);" % dest) + elif isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_inc_ref(f"{dest}.f{i}", item_type) + elif isinstance(rtype, RVec): + # TODO: Only use the X variant if buf can be NULL + self.emit_line(f"Py_XINCREF({dest}.buf);") + elif not rtype.is_unboxed: + # Always inline, since this is a simple but very hot op + if rtype.may_be_immortal or not HAVE_IMMORTAL: + self.emit_line("CPy_INCREF(%s);" % dest) + else: + self.emit_line("CPy_INCREF_NO_IMM(%s);" % dest) + # Otherwise assume it's an unboxed, pointerless value and do nothing. + + def emit_dec_ref( + self, dest: str, rtype: RType, *, is_xdec: bool = False, rare: bool = False + ) -> None: + """Decrement reference count of C expression `dest`. + + For composite unboxed structures (e.g. tuples) recursively + decrement reference counts for each component. + + If rare is True, optimize for code size and compilation speed. + """ + x = "X" if is_xdec else "" + if is_int_rprimitive(rtype): + if rare: + self.emit_line(f"CPyTagged_{x}DecRef({dest});") + else: + # Inlined + self.emit_line(f"CPyTagged_{x}DECREF({dest});") + elif isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_dec_ref(f"{dest}.f{i}", item_type, is_xdec=is_xdec, rare=rare) + elif isinstance(rtype, RVec): + # TODO: Only use the X variant if buf can be NULL + if rare: + self.emit_line(f"CPy_XDecRef({dest}.buf);") + else: + self.emit_line(f"CPy_XDECREF({dest}.buf);") + elif not rtype.is_unboxed: + if rare: + self.emit_line(f"CPy_{x}DecRef({dest});") + else: + # Inlined + if rtype.may_be_immortal or not HAVE_IMMORTAL: + self.emit_line(f"CPy_{x}DECREF({dest});") + else: + self.emit_line(f"CPy_{x}DECREF_NO_IMM({dest});") + elif rtype.is_refcounted: + assert False, f"dec_ref not implemented for {rtype}" + # Otherwise assume it's an unboxed, pointerless value and do nothing. + + def pretty_name(self, typ: RType) -> str: + value_type = optional_value_type(typ) + if value_type is not None: + return "%s or None" % self.pretty_name(value_type) + return str(typ) + + def emit_cast( + self, + src: str, + dest: str, + typ: RType, + *, + declare_dest: bool = False, + error: ErrorHandler | None = None, + raise_exception: bool = True, + optional: bool = False, + src_type: RType | None = None, + likely: bool = True, + ) -> None: + """Emit code for casting a value of given type. + + Somewhat strangely, this supports unboxed types but only + operates on boxed versions. This is necessary to properly + handle types such as Optional[int] in compatibility glue. + + By default, assign NULL (error value) to dest if the value has + an incompatible type and raise TypeError. These can be customized + using 'error' and 'raise_exception'. + + Always copy/steal the reference in 'src'. + + Args: + src: Name of source C variable + dest: Name of target C variable + typ: Type of value + declare_dest: If True, also declare the variable 'dest' + error: What happens on error + raise_exception: If True, also raise TypeError on failure + likely: If the cast is likely to succeed (can be False for unions) + """ + error = error or AssignHandler() + + # Special case casting *from* optional + if src_type and is_optional_type(src_type) and not is_object_rprimitive(typ): + value_type = optional_value_type(src_type) + assert value_type is not None + if is_same_type(value_type, typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + check = "({} != Py_None)" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + return + + # TODO: Verify refcount handling. + if ( + is_list_rprimitive(typ) + or is_dict_rprimitive(typ) + or is_set_rprimitive(typ) + or is_frozenset_rprimitive(typ) + or is_str_rprimitive(typ) + or is_range_rprimitive(typ) + or is_float_rprimitive(typ) + or is_int_rprimitive(typ) + or is_bool_or_bit_rprimitive(typ) + or is_fixed_width_rtype(typ) + ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + if is_list_rprimitive(typ): + prefix = "PyList" + elif is_dict_rprimitive(typ): + prefix = "PyDict" + elif is_set_rprimitive(typ): + prefix = "PySet" + elif is_frozenset_rprimitive(typ): + prefix = "PyFrozenSet" + elif is_str_rprimitive(typ): + prefix = "PyUnicode" + elif is_range_rprimitive(typ): + prefix = "PyRange" + elif is_float_rprimitive(typ): + prefix = "CPyFloat" + elif is_int_rprimitive(typ) or is_fixed_width_rtype(typ): + # TODO: Range check for fixed-width types? + prefix = "PyLong" + elif is_bool_or_bit_rprimitive(typ): + prefix = "PyBool" + else: + assert False, f"unexpected primitive type: {typ}" + check = "({}_Check({}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(prefix, src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_bytes_rprimitive(typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + check = "(PyBytes_Check({}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src, src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_bytearray_rprimitive(typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + check = "(PyByteArray_Check({}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src, src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_tuple_rprimitive(typ): + if declare_dest: + self.emit_line(f"{self.ctype(typ)} {dest};") + check = "(PyTuple_Check({}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif isinstance(typ, RInstance): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + concrete = all_concrete_classes(typ.class_ir) + # If there are too many concrete subclasses or we can't find any + # (meaning the code ought to be dead or we aren't doing global opts), + # fall back to a normal typecheck. + # Otherwise check all the subclasses. + if not concrete or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1: + check = "(PyObject_TypeCheck({}, {}))".format( + src, self.type_struct_name(typ.class_ir) + ) + else: + full_str = "(Py_TYPE({src}) == {targets[0]})" + for i in range(1, len(concrete)): + full_str += " || (Py_TYPE({src}) == {targets[%d]})" % i + if len(concrete) > 1: + full_str = "(%s)" % full_str + check = full_str.format( + src=src, targets=[self.type_struct_name(ir) for ir in concrete] + ) + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check, optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_none_rprimitive(typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + check = "({} == Py_None)" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check.format(src), optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif is_object_rprimitive(typ): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + self.emit_arg_check(src, dest, typ, "", optional) + self.emit_line(f"{dest} = {src};") + if optional: + self.emit_line("}") + elif is_native_rprimitive(typ): + # Native primitive types have type check functions of form "CPy_Check(...)". + if declare_dest: + self.emit_line(f"PyObject *{dest};") + short_name = typ.name.rsplit(".", 1)[-1] + check = f"(CPy{short_name}_Check({src}))" + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check, optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + elif isinstance(typ, RUnion): + self.emit_union_cast( + src, dest, typ, declare_dest, error, optional, src_type, raise_exception + ) + elif isinstance(typ, RTuple): + assert not optional + self.emit_tuple_cast(src, dest, typ, declare_dest, error, src_type) + elif isinstance(typ, RVec): + if declare_dest: + self.emit_line(f"PyObject *{dest};") + # Build type check expression based on vec kind + api_name = vec_api_by_item_type.get(typ.item_type) + depth = typ.depth() + if api_name: + # Specialized vec types (vec[i64], vec[i32], etc.) + check = f"(Py_TYPE({src}) == {api_name}.boxed_type)" + elif depth == 0: + # Generic vec types (vec[T], vec[T | None]) with reference type items + item_type_c = self.vec_item_type_c(typ) + check = ( + f"(Py_TYPE({src}) == VecTApi.boxed_type && " + f"((VecTObject *){src})->vec.buf->item_type == {item_type_c})" + ) + else: + # Nested vec types (vec[vec[...]]). Check boxed type, item type, and depth. + unwrapped = typ.unwrap_item_type() + if unwrapped in vec_item_type_tags: + type_value = str(vec_item_type_tags[unwrapped]) + else: + type_value = self.vec_item_type_c(typ) + check = ( + f"(Py_TYPE({src}) == VecNestedApi.boxed_type && " + f"((VecNestedObject *){src})->vec.buf->item_type == {type_value} && " + f"((VecNestedObject *){src})->vec.buf->depth == {depth})" + ) + if likely: + check = f"(likely{check})" + self.emit_arg_check(src, dest, typ, check, optional) + self.emit_lines(f" {dest} = {src};", "else {") + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_line("}") + else: + assert False, "Cast not implemented: %s" % typ + + def emit_cast_error_handler( + self, error: ErrorHandler, src: str, dest: str, typ: RType, raise_exception: bool + ) -> None: + if raise_exception: + if isinstance(error, TracebackAndGotoHandler): + # Merge raising and emitting traceback entry into a single call. + self.emit_type_error_traceback( + error.source_path, error.module_name, error.traceback_entry, typ=typ, src=src + ) + self.emit_line("goto %s;" % error.label) + return + self.emit_line(f'CPy_TypeError("{self.pretty_name(typ)}", {src}); ') + if isinstance(error, AssignHandler): + self.emit_line("%s = NULL;" % dest) + elif isinstance(error, GotoHandler): + self.emit_line("goto %s;" % error.label) + elif isinstance(error, TracebackAndGotoHandler): + self.emit_line("%s = NULL;" % dest) + self.emit_traceback(error.source_path, error.module_name, error.traceback_entry) + self.emit_line("goto %s;" % error.label) + else: + assert isinstance(error, ReturnHandler), error + self.emit_line("return %s;" % error.value) + + def emit_union_cast( + self, + src: str, + dest: str, + typ: RUnion, + declare_dest: bool, + error: ErrorHandler, + optional: bool, + src_type: RType | None, + raise_exception: bool, + ) -> None: + """Emit cast to a union type. + + The arguments are similar to emit_cast. + """ + if declare_dest: + self.emit_line(f"PyObject *{dest};") + good_label = self.new_label() + if optional: + self.emit_line(f"if ({src} == NULL) {{") + self.emit_line(f"{dest} = {self.c_error_value(typ)};") + self.emit_line(f"goto {good_label};") + self.emit_line("}") + for item in typ.items: + self.emit_cast( + src, + dest, + item, + declare_dest=False, + raise_exception=False, + optional=False, + likely=False, + ) + self.emit_line(f"if ({dest} != NULL) goto {good_label};") + # Handle cast failure. + self.emit_cast_error_handler(error, src, dest, typ, raise_exception) + self.emit_label(good_label) + + def emit_tuple_cast( + self, + src: str, + dest: str, + typ: RTuple, + declare_dest: bool, + error: ErrorHandler, + src_type: RType | None, + ) -> None: + """Emit cast to a tuple type. + + The arguments are similar to emit_cast. + """ + if declare_dest: + self.emit_line(f"PyObject *{dest};") + # This reuse of the variable is super dodgy. We don't even + # care about the values except to check whether they are + # invalid. + out_label = self.new_label() + self.emit_lines( + "if (unlikely(!(PyTuple_Check({r}) && PyTuple_GET_SIZE({r}) == {size}))) {{".format( + r=src, size=len(typ.types) + ), + f"{dest} = NULL;", + f"goto {out_label};", + "}", + ) + for i, item in enumerate(typ.types): + # Since we did the checks above this should never fail + self.emit_cast( + f"PyTuple_GET_ITEM({src}, {i})", + dest, + item, + declare_dest=False, + raise_exception=False, + optional=False, + ) + self.emit_line(f"if ({dest} == NULL) goto {out_label};") + + self.emit_line(f"{dest} = {src};") + self.emit_label(out_label) + + def emit_arg_check(self, src: str, dest: str, typ: RType, check: str, optional: bool) -> None: + if optional: + self.emit_line(f"if ({src} == NULL) {{") + self.emit_line(f"{dest} = {self.c_error_value(typ)};") + if check != "": + self.emit_line("{}if {}".format("} else " if optional else "", check)) + elif optional: + self.emit_line("else {") + + def emit_unbox( + self, + src: str, + dest: str, + typ: RType, + *, + declare_dest: bool = False, + error: ErrorHandler | None = None, + raise_exception: bool = True, + optional: bool = False, + borrow: bool = False, + ) -> None: + """Emit code for unboxing a value of given type (from PyObject *). + + By default, assign error value to dest if the value has an + incompatible type and raise TypeError. These can be customized + using 'error' and 'raise_exception'. + + Generate a new reference unless 'borrow' is True. + + Args: + src: Name of source C variable + dest: Name of target C variable + typ: Type of value + declare_dest: If True, also declare the variable 'dest' + error: What happens on error + raise_exception: If True, also raise TypeError on failure + optional: If True, NULL src value is allowed and will map to error value + borrow: If True, create a borrowed reference + + """ + error = error or AssignHandler() + # TODO: Verify refcount handling. + if isinstance(error, AssignHandler): + failure = f"{dest} = {self.c_error_value(typ)};" + elif isinstance(error, GotoHandler): + failure = "goto %s;" % error.label + else: + assert isinstance(error, ReturnHandler), error + failure = "return %s;" % error.value + if raise_exception: + raise_exc = f'CPy_TypeError("{self.pretty_name(typ)}", {src}); ' + failure = raise_exc + failure + if is_int_rprimitive(typ) or is_short_int_rprimitive(typ): + if declare_dest: + self.emit_line(f"CPyTagged {dest};") + self.emit_arg_check(src, dest, typ, f"(likely(PyLong_Check({src})))", optional) + if borrow: + self.emit_line(f" {dest} = CPyTagged_BorrowFromObject({src});") + else: + self.emit_line(f" {dest} = CPyTagged_FromObject({src});") + self.emit_line("else {") + self.emit_line(failure) + self.emit_line("}") + elif is_bool_or_bit_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + if declare_dest: + self.emit_line(f"char {dest};") + self.emit_arg_check(src, dest, typ, f"(unlikely(!PyBool_Check({src}))) {{", optional) + self.emit_line(failure) + self.emit_line("} else") + conversion = f"{src} == Py_True" + self.emit_line(f" {dest} = {conversion};") + elif is_none_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + if declare_dest: + self.emit_line(f"char {dest};") + self.emit_arg_check(src, dest, typ, f"(unlikely({src} != Py_None)) {{", optional) + self.emit_line(failure) + self.emit_line("} else") + self.emit_line(f" {dest} = 1;") + elif is_int64_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"int64_t {dest};") + self.emit_line(f"{dest} = CPyLong_AsInt64({src});") + if not isinstance(error, AssignHandler): + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) + elif is_int32_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"int32_t {dest};") + self.emit_line(f"{dest} = CPyLong_AsInt32({src});") + if not isinstance(error, AssignHandler): + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) + elif is_int16_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"int16_t {dest};") + self.emit_line(f"{dest} = CPyLong_AsInt16({src});") + if not isinstance(error, AssignHandler): + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) + elif is_uint8_rprimitive(typ): + # Whether we are borrowing or not makes no difference. + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"uint8_t {dest};") + self.emit_line(f"{dest} = CPyLong_AsUInt8({src});") + if not isinstance(error, AssignHandler): + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) + elif is_float_rprimitive(typ): + assert not optional # Not supported for overlapping error values + if declare_dest: + self.emit_line(f"double {dest};") + # TODO: Don't use __float__ and __index__ + self.emit_line(f"{dest} = PyFloat_AsDouble({src});") + self.emit_lines(f"if ({dest} == -1.0 && PyErr_Occurred()) {{", failure, "}") + elif isinstance(typ, RTuple): + self.declare_tuple_struct(typ) + if declare_dest: + self.emit_line(f"{self.ctype(typ)} {dest};") + # HACK: The error handling for unboxing tuples is busted + # and instead of fixing it I am just wrapping it in the + # cast code which I think is right. This is not good. + if optional: + self.emit_line(f"if ({src} == NULL) {{") + self.emit_line(f"{dest} = {self.c_error_value(typ)};") + self.emit_line("} else {") + + cast_temp = self.temp_name() + self.emit_tuple_cast( + src, cast_temp, typ, declare_dest=True, error=error, src_type=None + ) + self.emit_line(f"if (unlikely({cast_temp} == NULL)) {{") + + # self.emit_arg_check(src, dest, typ, + # '(!PyTuple_Check({}) || PyTuple_Size({}) != {}) {{'.format( + # src, src, len(typ.types)), optional) + self.emit_line(failure) # TODO: Decrease refcount? + self.emit_line("} else {") + if not typ.types: + self.emit_line(f"{dest}.empty_struct_error_flag = 0;") + for i, item_type in enumerate(typ.types): + temp = self.temp_name() + # emit_tuple_cast above checks the size, so this should not fail + self.emit_line(f"PyObject *{temp} = PyTuple_GET_ITEM({src}, {i});") + temp2 = self.temp_name() + # Unbox or check the item. + if item_type.is_unboxed: + self.emit_unbox( + temp, + temp2, + item_type, + raise_exception=raise_exception, + error=error, + declare_dest=True, + borrow=borrow, + ) + else: + if not borrow: + self.emit_inc_ref(temp, object_rprimitive) + self.emit_cast(temp, temp2, item_type, declare_dest=True) + self.emit_line(f"{dest}.f{i} = {temp2};") + self.emit_line("}") + if optional: + self.emit_line("}") + elif isinstance(typ, RVec): + if declare_dest: + self.emit_line(f"{self.ctype(typ)} {dest};") + + if optional: + self.emit_line(f"if ({src} == NULL) {{") + self.emit_line(f"{dest} = {self.c_error_value(typ)};") + self.emit_line("} else {") + + specialized_api_name = vec_api_by_item_type.get(typ.item_type) + if specialized_api_name is not None: + self.emit_line(f"{dest} = {specialized_api_name}.unbox({src});") + else: + depth = typ.depth() + unwrapped = typ.unwrap_item_type() + if unwrapped in vec_item_type_tags: + type_value = str(vec_item_type_tags[unwrapped]) + else: + type_value = self.vec_item_type_c(typ) + if depth == 0: + self.emit_line(f"{dest} = VecTApi.unbox({src}, {type_value});") + else: + self.emit_line(f"{dest} = VecNestedApi.unbox({src}, {type_value}, {depth});") + + self.emit_line(f"if (VEC_IS_ERROR({dest})) {{") + self.emit_line(failure) + self.emit_line("}") + + if optional: + self.emit_line("}") + else: + assert False, "Unboxing not implemented: %s" % typ + + def vec_item_type_c(self, typ: RVec) -> str: + item_type = typ.unwrap_item_type() + type_c_ptr = self.type_c_ptr(item_type) + # Can never be None, since we unwrapped the item type above + assert type_c_ptr is not None + type_value = f"(size_t){type_c_ptr}" + if typ.is_optional(): + type_value = f"({type_value} | 1)" + return type_value + + def type_c_ptr(self, typ: RPrimitive | RInstance) -> str | None: + if isinstance(typ, RPrimitive) and typ.is_refcounted: + return "&" + builtin_names[typ.name][1] + elif isinstance(typ, RInstance): + return self.type_struct_name(typ.class_ir) + return None + + def emit_box( + self, src: str, dest: str, typ: RType, declare_dest: bool = False, can_borrow: bool = False + ) -> None: + """Emit code for boxing a value of given type. + + Generate a simple assignment if no boxing is needed. + + The source reference count is stolen for the result (no need to decref afterwards). + """ + # TODO: Always generate a new reference (if a reference type) + if declare_dest: + declaration = "PyObject *" + else: + declaration = "" + if is_int_rprimitive(typ) or is_short_int_rprimitive(typ): + # Steal the existing reference if it exists. + self.emit_line(f"{declaration}{dest} = CPyTagged_StealAsObject({src});") + elif is_bool_or_bit_rprimitive(typ): + # N.B: bool is special cased to produce a borrowed value + # after boxing, so we don't need to increment the refcount + # when this comes directly from a Box op. + self.emit_lines(f"{declaration}{dest} = {src} ? Py_True : Py_False;") + if not can_borrow: + self.emit_inc_ref(dest, object_rprimitive) + elif is_none_rprimitive(typ): + # N.B: None is special cased to produce a borrowed value + # after boxing, so we don't need to increment the refcount + # when this comes directly from a Box op. + self.emit_lines(f"{declaration}{dest} = Py_None;") + if not can_borrow: + self.emit_inc_ref(dest, object_rprimitive) + elif is_int32_rprimitive(typ) or is_int16_rprimitive(typ) or is_uint8_rprimitive(typ): + self.emit_line(f"{declaration}{dest} = PyLong_FromLong({src});") + elif is_int64_rprimitive(typ): + self.emit_line(f"{declaration}{dest} = PyLong_FromLongLong({src});") + elif is_float_rprimitive(typ): + self.emit_line(f"{declaration}{dest} = PyFloat_FromDouble({src});") + elif isinstance(typ, RTuple): + self.declare_tuple_struct(typ) + if not typ.types: + self.emit_line(f"{declaration}{dest} = CPyTuple_LoadEmptyTupleConstant();") + else: + self.emit_line(f"{declaration}{dest} = PyTuple_New({len(typ.types)});") + self.emit_line(f"if (unlikely({dest} == NULL))") + self.emit_line(" CPyError_OutOfMemory();") + + # TODO: Fail if dest is None + for i in range(len(typ.types)): + if not typ.is_unboxed: + self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {src}.f{i}") + else: + inner_name = self.temp_name() + self.emit_box(f"{src}.f{i}", inner_name, typ.types[i], declare_dest=True) + self.emit_line(f"PyTuple_SET_ITEM({dest}, {i}, {inner_name});") + elif isinstance(typ, RVec): + specialized_api_name = vec_api_by_item_type.get(typ.item_type) + if specialized_api_name is not None: + api = specialized_api_name + elif typ.depth() > 0: + api = "VecNestedApi" + else: + api = "VecTApi" + # Empty vecs of this sort don't describe item type, so it needs to be + # passed explicitly. + item_type = self.vec_item_type_c(typ) + self.emit_line(f"{declaration}{dest} = {api}.box({src}, {item_type});") + return + self.emit_line(f"{declaration}{dest} = {api}.box({src});") + else: + assert not typ.is_unboxed + # Type is boxed -- trivially just assign. + self.emit_line(f"{declaration}{dest} = {src};") + + def emit_error_check(self, value: str, rtype: RType, failure: str) -> None: + """Emit code for checking a native function return value for uncaught exception.""" + if isinstance(rtype, RTuple): + if len(rtype.types) == 0: + return # empty tuples can't fail. + else: + cond = self.tuple_undefined_check_cond(rtype, value, self.c_error_value, "==") + self.emit_line(f"if ({cond}) {{") + elif isinstance(rtype, RVec): + self.emit_line(f"if ({value}.len < 0) {{") + elif rtype.error_overlap: + # The error value is also valid as a normal value, so we need to also check + # for a raised exception. + self.emit_line(f"if ({value} == {self.c_error_value(rtype)} && PyErr_Occurred()) {{") + else: + self.emit_line(f"if ({value} == {self.c_error_value(rtype)}) {{") + self.emit_lines(failure, "}") + + def emit_gc_visit(self, target: str, rtype: RType) -> None: + """Emit code for GC visiting a C variable reference. + + Assume that 'target' represents a C expression that refers to a + struct member, such as 'self->x'. + """ + if not rtype.is_refcounted: + # Not refcounted -> no pointers -> no GC interaction. + return + elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int": + self.emit_line(f"if (CPyTagged_CheckLong({target})) {{") + self.emit_line(f"Py_VISIT(CPyTagged_LongAsObject({target}));") + self.emit_line("}") + elif isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_gc_visit(f"{target}.f{i}", item_type) + elif isinstance(rtype, RVec): + self.emit_line(f"Py_VISIT({target}.buf);") + elif self.ctype(rtype) == "PyObject *": + # The simplest case. + self.emit_line(f"Py_VISIT({target});") + else: + assert False, "emit_gc_visit() not implemented for %s" % repr(rtype) + + def emit_gc_clear(self, target: str, rtype: RType) -> None: + """Emit code for clearing a C attribute reference for GC. + + Assume that 'target' represents a C expression that refers to a + struct member, such as 'self->x'. + """ + if not rtype.is_refcounted: + # Not refcounted -> no pointers -> no GC interaction. + return + elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int": + self.emit_line(f"if (CPyTagged_CheckLong({target})) {{") + self.emit_line(f"CPyTagged __tmp = {target};") + self.emit_line(f"{target} = {self.c_undefined_value(rtype)};") + self.emit_line("Py_XDECREF(CPyTagged_LongAsObject(__tmp));") + self.emit_line("}") + elif isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_gc_clear(f"{target}.f{i}", item_type) + elif isinstance(rtype, RVec): + self.emit_line(f"Py_CLEAR({target}.buf);") + elif self.ctype(rtype) == "PyObject *" and self.c_undefined_value(rtype) == "NULL": + # The simplest case. + self.emit_line(f"Py_CLEAR({target});") + else: + assert False, "emit_gc_clear() not implemented for %s" % repr(rtype) + + def emit_reuse_clear(self, target: str, rtype: RType) -> None: + """Emit attribute clear before object is added into freelist. + + Assume that 'target' represents a C expression that refers to a + struct member, such as 'self->x'. + + Unlike emit_gc_clear(), initialize attribute value to match a freshly + allocated object. + """ + if isinstance(rtype, RTuple): + for i, item_type in enumerate(rtype.types): + self.emit_reuse_clear(f"{target}.f{i}", item_type) + elif not rtype.is_refcounted: + self.emit_line(f"{target} = {rtype.c_undefined};") + elif isinstance(rtype, RPrimitive) and rtype.name == "builtins.int": + self.emit_line(f"if (CPyTagged_CheckLong({target})) {{") + self.emit_line(f"CPyTagged __tmp = {target};") + self.emit_line(f"{target} = {self.c_undefined_value(rtype)};") + self.emit_line("Py_XDECREF(CPyTagged_LongAsObject(__tmp));") + self.emit_line("} else {") + self.emit_line(f"{target} = {self.c_undefined_value(rtype)};") + self.emit_line("}") + else: + self.emit_gc_clear(target, rtype) + + def emit_traceback( + self, source_path: str, module_name: str, traceback_entry: tuple[str, int] + ) -> None: + return self._emit_traceback("CPy_AddTraceback", source_path, module_name, traceback_entry) + + def emit_type_error_traceback( + self, + source_path: str, + module_name: str, + traceback_entry: tuple[str, int], + *, + typ: RType, + src: str, + ) -> None: + func = "CPy_TypeErrorTraceback" + type_str = f'"{self.pretty_name(typ)}"' + return self._emit_traceback( + func, source_path, module_name, traceback_entry, type_str=type_str, src=src + ) + + def _emit_traceback( + self, + func: str, + source_path: str, + module_name: str, + traceback_entry: tuple[str, int], + type_str: str = "", + src: str = "", + ) -> None: + if self.context.strict_traceback_checks: + assert traceback_entry[1] >= 0, "Traceback cannot have a negative line number" + globals_static = self.static_name("globals", module_name) + line = '%s("%s", "%s", %d, %s' % ( + func, + source_path.replace("\\", "\\\\"), + traceback_entry[0], + traceback_entry[1], + globals_static, + ) + if type_str: + assert src + line += f", {type_str}, {src}" + line += ");" + self.emit_line(line) + if DEBUG_ERRORS: + self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");') + + def emit_unbox_failure_with_overlapping_error_value( + self, dest: str, typ: RType, failure: str + ) -> None: + self.emit_line(f"if ({dest} == {self.c_error_value(typ)} && PyErr_Occurred()) {{") + self.emit_line(failure) + self.emit_line("}") + + def emit_cpyfunction_instance( + self, fn: FuncIR, name: str, filepath: str, error_stmt: str + ) -> str: + module = self.static_name(fn.decl.module_name, None, prefix=MODULE_PREFIX) + cname = f"{PREFIX}{fn.cname(self.names)}" + wrapper_name = f"{cname}_wrapper" + cfunc = f"(PyCFunction){cname}" + func_flags = "METH_FASTCALL | METH_KEYWORDS" + doc = f"PyDoc_STR({native_function_doc_initializer(fn)})" + has_self_arg = "true" if fn.class_name and fn.decl.kind != FUNC_STATICMETHOD else "false" + + code_flags = "CO_COROUTINE" + self.emit_line( + f'PyObject* {wrapper_name} = CPyFunction_New({module}, "{filepath}", "{name}", {cfunc}, {func_flags}, {doc}, {fn.line}, {code_flags}, {has_self_arg});' + ) + self.emit_line(f"if (unlikely(!{wrapper_name}))") + self.emit_line(error_stmt) + return wrapper_name + + +def c_array_initializer(components: list[str], *, indented: bool = False) -> str: + """Construct an initializer for a C array variable. + + Components are C expressions valid in an initializer. + + For example, if components are ["1", "2"], the result + would be "{1, 2}", which can be used like this: + + int a[] = {1, 2}; + + If the result is long, split it into multiple lines. + """ + indent = " " * 4 if indented else "" + res = [] + current: list[str] = [] + cur_len = 0 + for c in components: + if not current or cur_len + 2 + len(indent) + len(c) < 70: + current.append(c) + cur_len += len(c) + 2 + else: + res.append(indent + ", ".join(current)) + current = [c] + cur_len = len(c) + if not res: + # Result fits on a single line + return "{%s}" % ", ".join(current) + # Multi-line result + res.append(indent + ", ".join(current)) + return "{\n " + ",\n ".join(res) + "\n" + indent + "}" + + +def native_function_doc_initializer(func: FuncIR) -> str: + text_sig = get_text_signature(func) + if text_sig is None: + return "NULL" + docstring = f"{text_sig}\n--\n\n" + return c_string_initializer(docstring.encode("ascii", errors="backslashreplace")) diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/emitclass.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/codegen/emitclass.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ab3ab46f01a2baaf308b7633040c612e8654e153 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/codegen/emitclass.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/emitclass.py b/micromamba_root/Lib/site-packages/mypyc/codegen/emitclass.py new file mode 100644 index 0000000000000000000000000000000000000000..26bf189694f97f703759e9e4e5f1659c31ce0fc1 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/codegen/emitclass.py @@ -0,0 +1,1326 @@ +"""Code generation for native classes and related wrappers.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping + +from mypy.nodes import ARG_STAR, ARG_STAR2 +from mypyc.codegen.cstring import c_string_initializer +from mypyc.codegen.emit import ( + Emitter, + HeaderDeclaration, + ReturnHandler, + native_function_doc_initializer, +) +from mypyc.codegen.emitfunc import native_function_header +from mypyc.codegen.emitwrapper import ( + generate_bin_op_wrapper, + generate_bool_wrapper, + generate_contains_wrapper, + generate_dunder_wrapper, + generate_get_wrapper, + generate_hash_wrapper, + generate_ipow_wrapper, + generate_len_wrapper, + generate_richcompare_wrapper, + generate_set_del_item_wrapper, +) +from mypyc.common import ( + BITMAP_BITS, + BITMAP_TYPE, + CPYFUNCTION_NAME, + NATIVE_PREFIX, + PREFIX, + REG_PREFIX, + short_id_from_name, +) +from mypyc.ir.class_ir import ClassIR, VTableEntries +from mypyc.ir.func_ir import ( + FUNC_CLASSMETHOD, + FUNC_STATICMETHOD, + FuncDecl, + FuncIR, + get_text_signature, +) +from mypyc.ir.rtypes import RTuple, RType, object_rprimitive +from mypyc.namegen import NameGenerator +from mypyc.sametype import is_same_type + + +def native_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: + return f"{NATIVE_PREFIX}{fn.cname(emitter.names)}" + + +def dunder_attr_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: + wrapper_fn = cl.get_method(fn.name + "__wrapper") + assert wrapper_fn + return f"{NATIVE_PREFIX}{wrapper_fn.cname(emitter.names)}" + + +# We maintain a table from dunder function names to struct slots they +# correspond to and functions that generate a wrapper (if necessary) +# and return the function name to stick in the slot. +# TODO: Add remaining dunder methods +SlotGenerator = Callable[[ClassIR, FuncIR, Emitter], str] +SlotTable = Mapping[str, tuple[str, SlotGenerator]] + +SLOT_DEFS: SlotTable = { + "__init__": ("tp_init", lambda c, t, e: generate_init_for_class(c, t, e)), + "__call__": ("tp_call", lambda c, t, e: generate_call_wrapper(c, t, e)), + "__str__": ("tp_str", native_slot), + "__repr__": ("tp_repr", native_slot), + "__next__": ("tp_iternext", native_slot), + "__iter__": ("tp_iter", native_slot), + "__hash__": ("tp_hash", generate_hash_wrapper), + "__get__": ("tp_descr_get", generate_get_wrapper), + "__getattr__": ("tp_getattro", dunder_attr_slot), + "__setattr__": ("tp_setattro", dunder_attr_slot), +} + +AS_MAPPING_SLOT_DEFS: SlotTable = { + "__getitem__": ("mp_subscript", generate_dunder_wrapper), + "__setitem__": ("mp_ass_subscript", generate_set_del_item_wrapper), + "__delitem__": ("mp_ass_subscript", generate_set_del_item_wrapper), + "__len__": ("mp_length", generate_len_wrapper), +} + +AS_SEQUENCE_SLOT_DEFS: SlotTable = {"__contains__": ("sq_contains", generate_contains_wrapper)} + +AS_NUMBER_SLOT_DEFS: SlotTable = { + # Unary operations. + "__bool__": ("nb_bool", generate_bool_wrapper), + "__int__": ("nb_int", generate_dunder_wrapper), + "__float__": ("nb_float", generate_dunder_wrapper), + "__neg__": ("nb_negative", generate_dunder_wrapper), + "__pos__": ("nb_positive", generate_dunder_wrapper), + "__abs__": ("nb_absolute", generate_dunder_wrapper), + "__invert__": ("nb_invert", generate_dunder_wrapper), + # Binary operations. + "__add__": ("nb_add", generate_bin_op_wrapper), + "__radd__": ("nb_add", generate_bin_op_wrapper), + "__sub__": ("nb_subtract", generate_bin_op_wrapper), + "__rsub__": ("nb_subtract", generate_bin_op_wrapper), + "__mul__": ("nb_multiply", generate_bin_op_wrapper), + "__rmul__": ("nb_multiply", generate_bin_op_wrapper), + "__mod__": ("nb_remainder", generate_bin_op_wrapper), + "__rmod__": ("nb_remainder", generate_bin_op_wrapper), + "__truediv__": ("nb_true_divide", generate_bin_op_wrapper), + "__rtruediv__": ("nb_true_divide", generate_bin_op_wrapper), + "__floordiv__": ("nb_floor_divide", generate_bin_op_wrapper), + "__rfloordiv__": ("nb_floor_divide", generate_bin_op_wrapper), + "__divmod__": ("nb_divmod", generate_bin_op_wrapper), + "__rdivmod__": ("nb_divmod", generate_bin_op_wrapper), + "__lshift__": ("nb_lshift", generate_bin_op_wrapper), + "__rlshift__": ("nb_lshift", generate_bin_op_wrapper), + "__rshift__": ("nb_rshift", generate_bin_op_wrapper), + "__rrshift__": ("nb_rshift", generate_bin_op_wrapper), + "__and__": ("nb_and", generate_bin_op_wrapper), + "__rand__": ("nb_and", generate_bin_op_wrapper), + "__or__": ("nb_or", generate_bin_op_wrapper), + "__ror__": ("nb_or", generate_bin_op_wrapper), + "__xor__": ("nb_xor", generate_bin_op_wrapper), + "__rxor__": ("nb_xor", generate_bin_op_wrapper), + "__matmul__": ("nb_matrix_multiply", generate_bin_op_wrapper), + "__rmatmul__": ("nb_matrix_multiply", generate_bin_op_wrapper), + # In-place binary operations. + "__iadd__": ("nb_inplace_add", generate_dunder_wrapper), + "__isub__": ("nb_inplace_subtract", generate_dunder_wrapper), + "__imul__": ("nb_inplace_multiply", generate_dunder_wrapper), + "__imod__": ("nb_inplace_remainder", generate_dunder_wrapper), + "__itruediv__": ("nb_inplace_true_divide", generate_dunder_wrapper), + "__ifloordiv__": ("nb_inplace_floor_divide", generate_dunder_wrapper), + "__ilshift__": ("nb_inplace_lshift", generate_dunder_wrapper), + "__irshift__": ("nb_inplace_rshift", generate_dunder_wrapper), + "__iand__": ("nb_inplace_and", generate_dunder_wrapper), + "__ior__": ("nb_inplace_or", generate_dunder_wrapper), + "__ixor__": ("nb_inplace_xor", generate_dunder_wrapper), + "__imatmul__": ("nb_inplace_matrix_multiply", generate_dunder_wrapper), + # Ternary operations. (yes, really) + # These are special cased in generate_bin_op_wrapper(). + "__pow__": ("nb_power", generate_bin_op_wrapper), + "__rpow__": ("nb_power", generate_bin_op_wrapper), + "__ipow__": ("nb_inplace_power", generate_ipow_wrapper), +} + +AS_ASYNC_SLOT_DEFS: SlotTable = { + "__await__": ("am_await", native_slot), + "__aiter__": ("am_aiter", native_slot), + "__anext__": ("am_anext", native_slot), +} + +SIDE_TABLES = [ + ("as_mapping", "PyMappingMethods", AS_MAPPING_SLOT_DEFS), + ("as_sequence", "PySequenceMethods", AS_SEQUENCE_SLOT_DEFS), + ("as_number", "PyNumberMethods", AS_NUMBER_SLOT_DEFS), + ("as_async", "PyAsyncMethods", AS_ASYNC_SLOT_DEFS), +] + +# Slots that need to always be filled in because they don't get +# inherited right. +ALWAYS_FILL = {"__hash__"} + + +def generate_call_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: + return "PyVectorcall_Call" + + +def slot_key(attr: str) -> str: + """Map dunder method name to sort key. + + Sort reverse operator methods and __delitem__ after others ('x' > '_'). + """ + if (attr.startswith("__r") and attr != "__rshift__") or attr == "__delitem__": + return "x" + attr + return attr + + +def generate_slots(cl: ClassIR, table: SlotTable, emitter: Emitter) -> dict[str, str]: + fields: dict[str, str] = {} + generated: dict[str, str] = {} + # Sort for determinism on Python 3.5 + for name, (slot, generator) in sorted(table.items(), key=lambda x: slot_key(x[0])): + method_cls = cl.get_method_and_class(name) + if method_cls and (method_cls[1] == cl or name in ALWAYS_FILL): + if slot in generated: + # Reuse previously generated wrapper. + fields[slot] = generated[slot] + else: + # Generate new wrapper. + name = generator(cl, method_cls[0], emitter) + fields[slot] = name + generated[slot] = name + + return fields + + +def generate_class_type_decl( + cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter +) -> None: + context = c_emitter.context + name = emitter.type_struct_name(cl) + context.declarations[name] = HeaderDeclaration( + f"PyTypeObject *{emitter.type_struct_name(cl)};", needs_export=True + ) + + # If this is a non-extension class, all we want is the type object decl. + if not cl.is_ext_class: + return + + generate_object_struct(cl, external_emitter) + generate_full = not cl.is_trait and not cl.builtin_base + if generate_full: + context.declarations[emitter.native_function_name(cl.ctor)] = HeaderDeclaration( + f"{native_function_header(cl.ctor, emitter)};", needs_export=True + ) + + +def generate_class_reuse( + cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter +) -> None: + """Generate a definition of a single-object per-class free "list". + + This speeds up object allocation and freeing when there are many short-lived + objects. + + TODO: Generalize to support a free list with up to N objects. + """ + assert cl.reuse_freed_instance + context = c_emitter.context + name = cl.name_prefix(c_emitter.names) + "_free_instance" + struct_name = cl.struct_name(c_emitter.names) + context.declarations[name] = HeaderDeclaration( + f"CPyThreadLocal {struct_name} *{name};", needs_export=True + ) + + +def generate_class(cl: ClassIR, module: str, emitter: Emitter) -> None: + """Generate C code for a class. + + This is the main entry point to the module. + """ + name = cl.name + name_prefix = cl.name_prefix(emitter.names) + + setup_name = emitter.native_function_name(cl.setup) + new_name = f"{name_prefix}_new" + finalize_name = f"{name_prefix}_finalize" + members_name = f"{name_prefix}_members" + getseters_name = f"{name_prefix}_getseters" + vtable_name = f"{name_prefix}_vtable" + traverse_name = f"{name_prefix}_traverse" + clear_name = f"{name_prefix}_clear" + dealloc_name = f"{name_prefix}_dealloc" + methods_name = f"{name_prefix}_methods" + vtable_setup_name = f"{name_prefix}_trait_vtable_setup" + coroutine_setup_name = f"{name_prefix}_coroutine_setup" + + fields: dict[str, str] = {"tp_name": f'"{name}"'} + + generate_full = not cl.is_trait and not cl.builtin_base + needs_getseters = cl.needs_getseters or not cl.is_generated or cl.has_dict + + if not cl.builtin_base: + fields["tp_new"] = new_name + + if generate_full: + fields["tp_dealloc"] = f"(destructor){name_prefix}_dealloc" + if not cl.is_acyclic: + fields["tp_traverse"] = f"(traverseproc){name_prefix}_traverse" + fields["tp_clear"] = f"(inquiry){name_prefix}_clear" + # Populate .tp_finalize and generate a finalize method only if __del__ is defined for this class. + del_method = next((e.method for e in cl.vtable_entries if e.name == "__del__"), None) + if del_method: + fields["tp_finalize"] = f"(destructor){finalize_name}" + if needs_getseters: + fields["tp_getset"] = getseters_name + fields["tp_methods"] = methods_name + + def emit_line() -> None: + emitter.emit_line() + + emit_line() + + # If the class has a method to initialize default attribute + # values, we need to call it during initialization. + defaults_fn = cl.get_method("__mypyc_defaults_setup") + + # If there is a __init__ method, we'll use it in the native constructor. + init_fn = cl.get_method("__init__") + + # Fill out slots in the type object from dunder methods. + fields.update(generate_slots(cl, SLOT_DEFS, emitter)) + + # Fill out dunder methods that live in tables hanging off the side. + for table_name, type, slot_defs in SIDE_TABLES: + slots = generate_slots(cl, slot_defs, emitter) + if slots: + table_struct_name = generate_side_table_for_class(cl, table_name, type, slots, emitter) + fields[f"tp_{table_name}"] = f"&{table_struct_name}" + + richcompare_name = generate_richcompare_wrapper(cl, emitter) + if richcompare_name: + fields["tp_richcompare"] = richcompare_name + + # If the class inherits from python, make space for a __dict__ + struct_name = cl.struct_name(emitter.names) + if cl.builtin_base: + base_size = f"sizeof({cl.builtin_base})" + elif cl.is_trait: + base_size = "sizeof(PyObject)" + else: + base_size = f"sizeof({struct_name})" + # Since our types aren't allocated using type() we need to + # populate these fields ourselves if we want them to have correct + # values. PyType_Ready will inherit the offsets from tp_base but + # that isn't what we want. + + # XXX: there is no reason for the __weakref__ stuff to be mixed up with __dict__ + if cl.has_dict and not has_managed_dict(cl, emitter): + # __dict__ lives right after the struct and __weakref__ lives right after that + # TODO: They should get members in the struct instead of doing this nonsense. + weak_offset = f"{base_size} + sizeof(PyObject *)" + emitter.emit_lines( + f"PyMemberDef {members_name}[] = {{", + f'{{"__dict__", T_OBJECT_EX, {base_size}, 0, NULL}},', + f'{{"__weakref__", T_OBJECT_EX, {weak_offset}, 0, NULL}},', + "{0}", + "};", + ) + + fields["tp_members"] = members_name + fields["tp_basicsize"] = f"{base_size} + 2*sizeof(PyObject *)" + if emitter.capi_version < (3, 12): + fields["tp_dictoffset"] = base_size + fields["tp_weaklistoffset"] = weak_offset + else: + fields["tp_basicsize"] = base_size + + if generate_full: + assert cl.setup is not None + emitter.emit_line(native_function_header(cl.setup, emitter) + ";") + assert cl.ctor is not None + emitter.emit_line(native_function_header(cl.ctor, emitter) + ";") + + emit_line() + init_fn = cl.get_method("__init__") + generate_new_for_class(cl, new_name, vtable_name, setup_name, init_fn, emitter) + emit_line() + if not cl.is_acyclic: + generate_traverse_for_class(cl, traverse_name, emitter) + emit_line() + generate_clear_for_class(cl, clear_name, emitter) + emit_line() + generate_dealloc_for_class(cl, dealloc_name, clear_name, bool(del_method), emitter) + emit_line() + + if cl.allow_interpreted_subclasses: + shadow_vtable_name: str | None = generate_vtables( + cl, vtable_setup_name + "_shadow", vtable_name + "_shadow", emitter, shadow=True + ) + emit_line() + else: + shadow_vtable_name = None + vtable_name = generate_vtables(cl, vtable_setup_name, vtable_name, emitter, shadow=False) + emit_line() + generate_coroutine_setup(cl, coroutine_setup_name, module, emitter) + emit_line() + if del_method: + generate_finalize_for_class(del_method, finalize_name, emitter) + emit_line() + if needs_getseters: + generate_getseter_declarations(cl, emitter) + emit_line() + generate_getseters_table(cl, getseters_name, emitter) + emit_line() + + if cl.is_trait: + generate_new_for_trait(cl, new_name, emitter) + + generate_methods_table(cl, methods_name, setup_name if generate_full else None, emitter) + emit_line() + + flags = ["Py_TPFLAGS_DEFAULT", "Py_TPFLAGS_HEAPTYPE", "Py_TPFLAGS_BASETYPE"] + if generate_full and not cl.is_acyclic: + flags.append("Py_TPFLAGS_HAVE_GC") + if cl.has_method("__call__"): + fields["tp_vectorcall_offset"] = "offsetof({}, vectorcall)".format( + cl.struct_name(emitter.names) + ) + flags.append("_Py_TPFLAGS_HAVE_VECTORCALL") + if not fields.get("tp_vectorcall"): + # This is just a placeholder to please CPython. It will be + # overridden during setup. + fields["tp_call"] = "PyVectorcall_Call" + if has_managed_dict(cl, emitter): + flags.append("Py_TPFLAGS_MANAGED_DICT") + fields["tp_flags"] = " | ".join(flags) + + fields["tp_doc"] = f"PyDoc_STR({native_class_doc_initializer(cl)})" + + emitter.emit_line(f"static PyTypeObject {emitter.type_struct_name(cl)}_template_ = {{") + emitter.emit_line("PyVarObject_HEAD_INIT(NULL, 0)") + for field, value in fields.items(): + emitter.emit_line(f".{field} = {value},") + emitter.emit_line("};") + emitter.emit_line( + "static PyTypeObject *{t}_template = &{t}_template_;".format( + t=emitter.type_struct_name(cl) + ) + ) + + if cl.coroutine_name: + cpyfunction = emitter.static_name(cl.name + "_cpyfunction", module) + emitter.emit_line(f"static PyObject *{cpyfunction} = NULL;") + + emitter.emit_line() + if generate_full: + generate_setup_for_class(cl, defaults_fn, vtable_name, shadow_vtable_name, emitter) + emitter.emit_line() + generate_constructor_for_class(cl, cl.ctor, init_fn, setup_name, vtable_name, emitter) + emitter.emit_line() + if needs_getseters: + generate_getseters(cl, emitter) + + +def getter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str: + return names.private_name(cl.module_name, f"{cl.name}_get_{attribute}") + + +def setter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str: + return names.private_name(cl.module_name, f"{cl.name}_set_{attribute}") + + +def generate_object_struct(cl: ClassIR, emitter: Emitter) -> None: + seen_attrs: set[str] = set() + lines: list[str] = [] + lines += ["typedef struct {", "PyObject_HEAD", "CPyVTableItem *vtable;"] + if cl.has_method("__call__"): + lines.append("vectorcallfunc vectorcall;") + bitmap_attrs = [] + for base in reversed(cl.base_mro): + if not base.is_trait: + if base.bitmap_attrs: + # Do we need another attribute bitmap field? + if emitter.bitmap_field(len(base.bitmap_attrs) - 1) not in bitmap_attrs: + for i in range(0, len(base.bitmap_attrs), BITMAP_BITS): + attr = emitter.bitmap_field(i) + if attr not in bitmap_attrs: + lines.append(f"{BITMAP_TYPE} {attr};") + bitmap_attrs.append(attr) + for attr, rtype in base.attributes.items(): + # Generated class may redefine certain attributes with different + # types in subclasses (this would be unsafe for user-defined classes). + if attr not in seen_attrs: + lines.append(f"{emitter.ctype_spaced(rtype)}{emitter.attr(attr)};") + seen_attrs.add(attr) + + if isinstance(rtype, RTuple): + emitter.declare_tuple_struct(rtype) + + lines.append(f"}} {cl.struct_name(emitter.names)};") + lines.append("") + emitter.context.declarations[cl.struct_name(emitter.names)] = HeaderDeclaration( + lines, is_type=True + ) + + +def generate_vtables( + base: ClassIR, vtable_setup_name: str, vtable_name: str, emitter: Emitter, shadow: bool +) -> str: + """Emit the vtables and vtable setup functions for a class. + + This includes both the primary vtable and any trait implementation vtables. + The trait vtables go before the main vtable, and have the following layout: + { + CPyType_T1, // pointer to type object + C_T1_trait_vtable, // pointer to array of method pointers + C_T1_offset_table, // pointer to array of attribute offsets + CPyType_T2, + C_T2_trait_vtable, + C_T2_offset_table, + ... + } + The method implementations are calculated at the end of IR pass, attribute + offsets are {offsetof(native__C, _x1), offsetof(native__C, _y1), ...}. + + To account for both dynamic loading and dynamic class creation, + vtables are populated dynamically at class creation time, so we + emit empty array definitions to store the vtables and a function to + populate them. + + If shadow is True, generate "shadow vtables" that point to the + shadow glue methods (which should dispatch via the Python C-API). + + Returns the expression to use to refer to the vtable, which might be + different than the name, if there are trait vtables. + """ + + def trait_vtable_name(trait: ClassIR) -> str: + return "{}_{}_trait_vtable{}".format( + base.name_prefix(emitter.names), + trait.name_prefix(emitter.names), + "_shadow" if shadow else "", + ) + + def trait_offset_table_name(trait: ClassIR) -> str: + return "{}_{}_offset_table".format( + base.name_prefix(emitter.names), trait.name_prefix(emitter.names) + ) + + # Emit array definitions with enough space for all the entries + emitter.emit_line( + "static CPyVTableItem {}[{}];".format( + vtable_name, max(1, len(base.vtable_entries) + 3 * len(base.trait_vtables)) + ) + ) + + for trait, vtable in base.trait_vtables.items(): + # Trait methods entry (vtable index -> method implementation). + emitter.emit_line( + f"static CPyVTableItem {trait_vtable_name(trait)}[{max(1, len(vtable))}];" + ) + # Trait attributes entry (attribute number in trait -> offset in actual struct). + emitter.emit_line( + "static size_t {}[{}];".format( + trait_offset_table_name(trait), max(1, len(trait.attributes)) + ) + ) + + # Emit vtable setup function + emitter.emit_line("static bool") + emitter.emit_line(f"{NATIVE_PREFIX}{vtable_setup_name}(void)") + emitter.emit_line("{") + + if base.allow_interpreted_subclasses and not shadow: + emitter.emit_line(f"{NATIVE_PREFIX}{vtable_setup_name}_shadow();") + + subtables = [] + for trait, vtable in base.trait_vtables.items(): + name = trait_vtable_name(trait) + offset_name = trait_offset_table_name(trait) + generate_vtable(vtable, name, emitter, [], shadow) + generate_offset_table(offset_name, emitter, trait, base) + subtables.append((trait, name, offset_name)) + + generate_vtable(base.vtable_entries, vtable_name, emitter, subtables, shadow) + + emitter.emit_line("return 1;") + emitter.emit_line("}") + + return vtable_name if not subtables else f"{vtable_name} + {len(subtables) * 3}" + + +def generate_offset_table( + trait_offset_table_name: str, emitter: Emitter, trait: ClassIR, cl: ClassIR +) -> None: + """Generate attribute offset row of a trait vtable.""" + emitter.emit_line(f"size_t {trait_offset_table_name}_scratch[] = {{") + for attr in trait.attributes: + emitter.emit_line(f"offsetof({cl.struct_name(emitter.names)}, {emitter.attr(attr)}),") + if not trait.attributes: + # This is for msvc. + emitter.emit_line("0") + emitter.emit_line("};") + emitter.emit_line( + "memcpy({name}, {name}_scratch, sizeof({name}));".format(name=trait_offset_table_name) + ) + + +def generate_vtable( + entries: VTableEntries, + vtable_name: str, + emitter: Emitter, + subtables: list[tuple[ClassIR, str, str]], + shadow: bool, +) -> None: + emitter.emit_line(f"CPyVTableItem {vtable_name}_scratch[] = {{") + if subtables: + emitter.emit_line("/* Array of trait vtables */") + for trait, table, offset_table in subtables: + emitter.emit_line( + "(CPyVTableItem){}, (CPyVTableItem){}, (CPyVTableItem){},".format( + emitter.type_struct_name(trait), table, offset_table + ) + ) + emitter.emit_line("/* Start of real vtable */") + + for entry in entries: + method = entry.shadow_method if shadow and entry.shadow_method else entry.method + emitter.emit_line( + "(CPyVTableItem){}{}{},".format( + emitter.get_group_prefix(entry.method.decl), + NATIVE_PREFIX, + method.cname(emitter.names), + ) + ) + + # msvc doesn't allow empty arrays; maybe allowing them at all is an extension? + if not entries: + emitter.emit_line("NULL") + emitter.emit_line("};") + emitter.emit_line("memcpy({name}, {name}_scratch, sizeof({name}));".format(name=vtable_name)) + + +def generate_setup_for_class( + cl: ClassIR, + defaults_fn: FuncIR | None, + vtable_name: str, + shadow_vtable_name: str | None, + emitter: Emitter, +) -> None: + """Generate a native function that allocates an instance of a class.""" + emitter.emit_line(native_function_header(cl.setup, emitter)) + emitter.emit_line("{") + type_arg_name = REG_PREFIX + cl.setup.sig.args[0].name + emitter.emit_line(f"PyTypeObject *type = (PyTypeObject*){type_arg_name};") + struct_name = cl.struct_name(emitter.names) + emitter.emit_line(f"{struct_name} *self;") + + prefix = cl.name_prefix(emitter.names) + if cl.reuse_freed_instance: + # Attempt to use a per-type free list first (a free "list" with up to one object only). + emitter.emit_line(f"if ({prefix}_free_instance != NULL) {{") + emitter.emit_line(f"self = {prefix}_free_instance;") + emitter.emit_line(f"{prefix}_free_instance = NULL;") + emitter.emit_line("Py_SET_REFCNT(self, 1);") + if not cl.is_acyclic: + emitter.emit_line("PyObject_GC_Track(self);") + if defaults_fn is not None: + emit_attr_defaults_func_call(defaults_fn, "self", emitter) + emitter.emit_line("return (PyObject *)self;") + emitter.emit_line("}") + + emitter.emit_line(f"self = ({cl.struct_name(emitter.names)} *)type->tp_alloc(type, 0);") + emitter.emit_line("if (self == NULL)") + emitter.emit_line(" return NULL;") + + if shadow_vtable_name: + emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{") + emitter.emit_line(f"self->vtable = {shadow_vtable_name};") + emitter.emit_line("} else {") + emitter.emit_line(f"self->vtable = {vtable_name};") + emitter.emit_line("}") + else: + emitter.emit_line(f"self->vtable = {vtable_name};") + + emit_clear_bitmaps(cl, emitter) + + if cl.has_method("__call__"): + name = cl.method_decl("__call__").cname(emitter.names) + emitter.emit_line(f"self->vectorcall = {PREFIX}{name};") + + for base in reversed(cl.base_mro): + for attr, rtype in base.attributes.items(): + value = emitter.c_undefined_value(rtype) + + # We don't need to set this field to NULL since tp_alloc() already + # zero-initializes `self`. + if value != "NULL": + emitter.set_undefined_value(f"self->{emitter.attr(attr)}", rtype) + + # Initialize attributes to default values, if necessary + if defaults_fn is not None: + emit_attr_defaults_func_call(defaults_fn, "self", emitter) + + emitter.emit_line("return (PyObject *)self;") + emitter.emit_line("}") + + +def emit_clear_bitmaps(cl: ClassIR, emitter: Emitter) -> None: + """Emit C code to clear bitmaps that track if attributes have an assigned value.""" + for i in range(0, len(cl.bitmap_attrs), BITMAP_BITS): + field = emitter.bitmap_field(i) + emitter.emit_line(f"self->{field} = 0;") + + +def emit_attr_defaults_func_call(defaults_fn: FuncIR, self_name: str, emitter: Emitter) -> None: + """Emit C code to initialize attribute defaults by calling defaults_fn. + + The code returns NULL on a raised exception. + """ + emitter.emit_lines( + "if ({}{}((PyObject *){}) == 0) {{".format( + NATIVE_PREFIX, defaults_fn.cname(emitter.names), self_name + ), + "Py_DECREF(self);", + "return NULL;", + "}", + ) + + +def emit_setup_or_dunder_new_call( + cl: ClassIR, + setup_name: str, + type_arg: str, + native_prefix: bool, + new_args: str, + emitter: Emitter, +) -> None: + def emit_null_check() -> None: + emitter.emit_line("if (self == NULL)") + emitter.emit_line(" return NULL;") + + new_fn = cl.get_method("__new__") + if not new_fn: + emitter.emit_line(f"PyObject *self = {setup_name}({type_arg});") + emit_null_check() + return + prefix = emitter.get_group_prefix(new_fn.decl) + NATIVE_PREFIX if native_prefix else PREFIX + all_args = type_arg + if new_args != "": + all_args += ", " + new_args + emitter.emit_line(f"PyObject *self = {prefix}{new_fn.cname(emitter.names)}({all_args});") + emit_null_check() + + # skip __init__ if __new__ returns some other type + emitter.emit_line(f"if (Py_TYPE(self) != {emitter.type_struct_name(cl)})") + emitter.emit_line(" return self;") + + +def generate_constructor_for_class( + cl: ClassIR, + fn: FuncDecl, + init_fn: FuncIR | None, + setup_name: str, + vtable_name: str, + emitter: Emitter, +) -> None: + """Generate a native function that allocates and initializes an instance of a class.""" + emitter.emit_line(f"{native_function_header(fn, emitter)}") + emitter.emit_line("{") + + fn_args = [REG_PREFIX + arg.name for arg in fn.sig.args] + type_arg = "(PyObject *)" + emitter.type_struct_name(cl) + new_args = ", ".join(fn_args) + + use_wrapper = ( + cl.has_method("__new__") + and len(fn.sig.args) == 2 + and fn.sig.args[0].kind == ARG_STAR + and fn.sig.args[1].kind == ARG_STAR2 + ) + emit_setup_or_dunder_new_call(cl, setup_name, type_arg, not use_wrapper, new_args, emitter) + + args = ", ".join(["self"] + fn_args) + if init_fn is not None: + prefix = PREFIX if use_wrapper else NATIVE_PREFIX + cast = "!= NULL ? 0 : -1" if use_wrapper else "" + emitter.emit_line( + "char res = {}{}{}({}){};".format( + emitter.get_group_prefix(init_fn.decl), + prefix, + init_fn.cname(emitter.names), + args, + cast, + ) + ) + emitter.emit_line("if (res == 2) {") + emitter.emit_line("Py_DECREF(self);") + emitter.emit_line("return NULL;") + emitter.emit_line("}") + + # If there is a nontrivial ctor that we didn't define, invoke it via tp_init + elif len(fn.sig.args) > 1: + emitter.emit_line(f"int res = {emitter.type_struct_name(cl)}->tp_init({args});") + + emitter.emit_line("if (res < 0) {") + emitter.emit_line("Py_DECREF(self);") + emitter.emit_line("return NULL;") + emitter.emit_line("}") + + emitter.emit_line("return self;") + emitter.emit_line("}") + + +def generate_init_for_class(cl: ClassIR, init_fn: FuncIR, emitter: Emitter) -> str: + """Generate an init function suitable for use as tp_init. + + tp_init needs to be a function that returns an int, and our + __init__ methods return a PyObject. Translate NULL to -1, + everything else to 0. + """ + func_name = f"{cl.name_prefix(emitter.names)}_init" + + emitter.emit_line("static int") + emitter.emit_line(f"{func_name}(PyObject *self, PyObject *args, PyObject *kwds)") + emitter.emit_line("{") + if cl.allow_interpreted_subclasses or cl.builtin_base or cl.has_method("__new__"): + emitter.emit_line( + "return {}{}(self, args, kwds) != NULL ? 0 : -1;".format( + PREFIX, init_fn.cname(emitter.names) + ) + ) + else: + emitter.emit_line("return 0;") + emitter.emit_line("}") + + return func_name + + +def generate_new_for_class( + cl: ClassIR, + func_name: str, + vtable_name: str, + setup_name: str, + init_fn: FuncIR | None, + emitter: Emitter, +) -> None: + emitter.emit_line("static PyObject *") + emitter.emit_line(f"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)") + emitter.emit_line("{") + # TODO: Check and unbox arguments + if not cl.allow_interpreted_subclasses: + emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{") + emitter.emit_line( + 'PyErr_SetString(PyExc_TypeError, "interpreted classes cannot inherit from compiled");' + ) + emitter.emit_line("return NULL;") + emitter.emit_line("}") + + type_arg = "(PyObject*)type" + new_args = "args, kwds" + emit_setup_or_dunder_new_call(cl, setup_name, type_arg, False, new_args, emitter) + if ( + not init_fn + or cl.allow_interpreted_subclasses + or cl.builtin_base + or cl.is_serializable() + or cl.has_method("__new__") + ): + # Match Python semantics -- __new__ doesn't call __init__. + emitter.emit_line("return self;") + else: + # __new__ of a native class implicitly calls __init__ so that we + # can enforce that instances are always properly initialized. This + # is needed to support always defined attributes. + emitter.emit_line( + f"PyObject *ret = {PREFIX}{init_fn.cname(emitter.names)}(self, args, kwds);" + ) + emitter.emit_lines("if (ret == NULL)", " return NULL;") + emitter.emit_line("return self;") + emitter.emit_line("}") + + +def generate_new_for_trait(cl: ClassIR, func_name: str, emitter: Emitter) -> None: + emitter.emit_line("static PyObject *") + emitter.emit_line(f"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)") + emitter.emit_line("{") + emitter.emit_line(f"if (type != {emitter.type_struct_name(cl)}) {{") + emitter.emit_line( + "PyErr_SetString(PyExc_TypeError, " + '"interpreted classes cannot inherit from compiled traits");' + ) + emitter.emit_line("} else {") + emitter.emit_line('PyErr_SetString(PyExc_TypeError, "traits may not be directly created");') + emitter.emit_line("}") + emitter.emit_line("return NULL;") + emitter.emit_line("}") + + +def generate_traverse_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None: + """Emit function that performs cycle GC traversal of an instance.""" + emitter.emit_line("static int") + emitter.emit_line( + f"{func_name}({cl.struct_name(emitter.names)} *self, visitproc visit, void *arg)" + ) + emitter.emit_line("{") + for base in reversed(cl.base_mro): + for attr, rtype in base.attributes.items(): + emitter.emit_gc_visit(f"self->{emitter.attr(attr)}", rtype) + if has_managed_dict(cl, emitter): + emitter.emit_line("PyObject_VisitManagedDict((PyObject *)self, visit, arg);") + elif cl.has_dict: + struct_name = cl.struct_name(emitter.names) + # __dict__ lives right after the struct and __weakref__ lives right after that + emitter.emit_gc_visit( + f"*((PyObject **)((char *)self + sizeof({struct_name})))", object_rprimitive + ) + emitter.emit_gc_visit( + f"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))", + object_rprimitive, + ) + emitter.emit_line("return 0;") + emitter.emit_line("}") + + +def generate_clear_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None: + emitter.emit_line("static int") + emitter.emit_line(f"{func_name}({cl.struct_name(emitter.names)} *self)") + emitter.emit_line("{") + for base in reversed(cl.base_mro): + for attr, rtype in base.attributes.items(): + emitter.emit_gc_clear(f"self->{emitter.attr(attr)}", rtype) + if has_managed_dict(cl, emitter): + emitter.emit_line("PyObject_ClearManagedDict((PyObject *)self);") + elif cl.has_dict: + struct_name = cl.struct_name(emitter.names) + # __dict__ lives right after the struct and __weakref__ lives right after that + emitter.emit_gc_clear( + f"*((PyObject **)((char *)self + sizeof({struct_name})))", object_rprimitive + ) + emitter.emit_gc_clear( + f"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))", + object_rprimitive, + ) + emitter.emit_line("return 0;") + emitter.emit_line("}") + + +def generate_dealloc_for_class( + cl: ClassIR, + dealloc_func_name: str, + clear_func_name: str, + has_tp_finalize: bool, + emitter: Emitter, +) -> None: + emitter.emit_line("static void") + emitter.emit_line(f"{dealloc_func_name}({cl.struct_name(emitter.names)} *self)") + emitter.emit_line("{") + if has_tp_finalize: + emitter.emit_line("PyObject *type, *value, *traceback;") + emitter.emit_line("PyErr_Fetch(&type, &value, &traceback);") + emitter.emit_line("int res = PyObject_CallFinalizerFromDealloc((PyObject *)self);") + # CPython interpreter uses PyErr_WriteUnraisable: https://docs.python.org/3/c-api/exceptions.html#c.PyErr_WriteUnraisable + # However, the message is slightly different due to the way mypyc compiles classes. + # CPython interpreter prints: Exception ignored in: + # mypyc prints: Exception ignored in: + emitter.emit_line("if (PyErr_Occurred() != NULL) {") + # Don't untrack instance if error occurred + emitter.emit_line("PyErr_WriteUnraisable((PyObject *)self);") + emitter.emit_line("res = -1;") + emitter.emit_line("}") + emitter.emit_line("PyErr_Restore(type, value, traceback);") + emitter.emit_line("if (res < 0) {") + emitter.emit_line("goto done;") + emitter.emit_line("}") + if not cl.is_acyclic: + emitter.emit_line("PyObject_GC_UnTrack(self);") + if cl.reuse_freed_instance: + emit_reuse_dealloc(cl, emitter) + # The trashcan is needed to handle deep recursive deallocations + emitter.emit_line(f"CPy_TRASHCAN_BEGIN(self, {dealloc_func_name})") + emitter.emit_line(f"{clear_func_name}(self);") + emitter.emit_line("Py_TYPE(self)->tp_free((PyObject *)self);") + emitter.emit_line("CPy_TRASHCAN_END(self)") + emitter.emit_line("done: ;") + emitter.emit_line("}") + + +def emit_reuse_dealloc(cl: ClassIR, emitter: Emitter) -> None: + """Emit code to deallocate object by putting it to per-type free list. + + The free "list" currently can have up to one object. + """ + prefix = cl.name_prefix(emitter.names) + emitter.emit_line(f"if ({prefix}_free_instance == NULL) {{") + emitter.emit_line(f"{prefix}_free_instance = self;") + + # Clear attributes and free referenced objects. + + emit_clear_bitmaps(cl, emitter) + + for base in reversed(cl.base_mro): + for attr, rtype in base.attributes.items(): + emitter.emit_reuse_clear(f"self->{emitter.attr(attr)}", rtype) + + emitter.emit_line("return;") + emitter.emit_line("}") + + +def generate_finalize_for_class( + del_method: FuncIR, finalize_func_name: str, emitter: Emitter +) -> None: + emitter.emit_line("static void") + emitter.emit_line(f"{finalize_func_name}(PyObject *self)") + emitter.emit_line("{") + emitter.emit_line( + "{}{}{}(self);".format( + emitter.get_group_prefix(del_method.decl), + NATIVE_PREFIX, + del_method.cname(emitter.names), + ) + ) + emitter.emit_line("}") + + +def generate_methods_table( + cl: ClassIR, name: str, setup_name: str | None, emitter: Emitter +) -> None: + emitter.emit_line(f"static PyMethodDef {name}[] = {{") + if setup_name: + # Store pointer to the setup function so it can be resolved dynamically + # in case of instance creation in __new__. + # CPy_SetupObject expects this method to be the first one in tp_methods. + emitter.emit_line( + f'{{"__internal_mypyc_setup", (PyCFunction){setup_name}, METH_O, NULL}},' + ) + for fn in cl.methods.values(): + if fn.decl.is_prop_setter or fn.decl.is_prop_getter or fn.internal: + continue + emitter.emit_line(f'{{"{fn.name}",') + emitter.emit_line(f" (PyCFunction){PREFIX}{fn.cname(emitter.names)},") + flags = ["METH_FASTCALL", "METH_KEYWORDS"] + if fn.decl.kind == FUNC_STATICMETHOD: + flags.append("METH_STATIC") + elif fn.decl.kind == FUNC_CLASSMETHOD: + flags.append("METH_CLASS") + + doc = native_function_doc_initializer(fn) + emitter.emit_line(" {}, PyDoc_STR({})}},".format(" | ".join(flags), doc)) + + # Provide a default __getstate__ and __setstate__ + if not cl.has_method("__setstate__") and not cl.has_method("__getstate__"): + emitter.emit_lines( + '{"__setstate__", (PyCFunction)CPyPickle_SetState, METH_O, NULL},', + '{"__getstate__", (PyCFunction)CPyPickle_GetState, METH_NOARGS, NULL},', + ) + + emitter.emit_line("{NULL} /* Sentinel */") + emitter.emit_line("};") + + +def generate_side_table_for_class( + cl: ClassIR, name: str, type: str, slots: dict[str, str], emitter: Emitter +) -> str | None: + name = f"{cl.name_prefix(emitter.names)}_{name}" + emitter.emit_line(f"static {type} {name} = {{") + for field, value in slots.items(): + emitter.emit_line(f".{field} = {value},") + emitter.emit_line("};") + return name + + +def generate_getseter_declarations(cl: ClassIR, emitter: Emitter) -> None: + if not cl.is_trait: + for attr in cl.attributes: + emitter.emit_line("static PyObject *") + emitter.emit_line( + "{}({} *self, void *closure);".format( + getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("static int") + emitter.emit_line( + "{}({} *self, PyObject *value, void *closure);".format( + setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + + for prop, (getter, setter) in cl.properties.items(): + if getter.decl.implicit: + continue + + # Generate getter declaration + emitter.emit_line("static PyObject *") + emitter.emit_line( + "{}({} *self, void *closure);".format( + getter_name(cl, prop, emitter.names), cl.struct_name(emitter.names) + ) + ) + + # Generate property setter declaration if a setter exists + if setter: + emitter.emit_line("static int") + emitter.emit_line( + "{}({} *self, PyObject *value, void *closure);".format( + setter_name(cl, prop, emitter.names), cl.struct_name(emitter.names) + ) + ) + + +def generate_getseters_table(cl: ClassIR, name: str, emitter: Emitter) -> None: + emitter.emit_line(f"static PyGetSetDef {name}[] = {{") + if not cl.is_trait: + for attr in cl.attributes: + emitter.emit_line(f'{{"{attr}",') + emitter.emit_line( + " (getter){}, (setter){},".format( + getter_name(cl, attr, emitter.names), setter_name(cl, attr, emitter.names) + ) + ) + emitter.emit_line(" NULL, NULL},") + for prop, (getter, setter) in cl.properties.items(): + if getter.decl.implicit: + continue + + emitter.emit_line(f'{{"{prop}",') + emitter.emit_line(f" (getter){getter_name(cl, prop, emitter.names)},") + + if setter: + emitter.emit_line(f" (setter){setter_name(cl, prop, emitter.names)},") + emitter.emit_line("NULL, NULL},") + else: + emitter.emit_line("NULL, NULL, NULL},") + + if cl.has_dict: + emitter.emit_line('{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},') + + emitter.emit_line("{NULL} /* Sentinel */") + emitter.emit_line("};") + + +def generate_getseters(cl: ClassIR, emitter: Emitter) -> None: + if not cl.is_trait: + for i, (attr, rtype) in enumerate(cl.attributes.items()): + generate_getter(cl, attr, rtype, emitter) + emitter.emit_line("") + generate_setter(cl, attr, rtype, emitter) + if i < len(cl.attributes) - 1: + emitter.emit_line("") + for prop, (getter, setter) in cl.properties.items(): + if getter.decl.implicit: + continue + + rtype = getter.sig.ret_type + emitter.emit_line("") + generate_readonly_getter(cl, prop, rtype, getter, emitter) + if setter: + arg_type = setter.sig.args[1].type + emitter.emit_line("") + generate_property_setter(cl, prop, arg_type, setter, emitter) + + +def generate_getter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None: + attr_field = emitter.attr(attr) + emitter.emit_line("static PyObject *") + emitter.emit_line( + "{}({} *self, void *closure)".format( + getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("{") + attr_expr = f"self->{attr_field}" + + # HACK: Don't consider refcounted values as always defined, since it's possible to + # access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted + # values is benign. + always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted + + if not always_defined: + emitter.emit_undefined_attr_check(rtype, attr_expr, "==", "self", attr, cl, unlikely=True) + emitter.emit_line("PyErr_SetString(PyExc_AttributeError,") + emitter.emit_line(f' "attribute {repr(attr)} of {repr(cl.name)} undefined");') + emitter.emit_line("return NULL;") + emitter.emit_line("}") + emitter.emit_inc_ref(f"self->{attr_field}", rtype) + emitter.emit_box(f"self->{attr_field}", "retval", rtype, declare_dest=True) + emitter.emit_line("return retval;") + emitter.emit_line("}") + + +def generate_setter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None: + attr_field = emitter.attr(attr) + emitter.emit_line("static int") + emitter.emit_line( + "{}({} *self, PyObject *value, void *closure)".format( + setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("{") + + deletable = cl.is_deletable(attr) + if not deletable: + emitter.emit_line("if (value == NULL) {") + emitter.emit_line("PyErr_SetString(PyExc_AttributeError,") + emitter.emit_line( + f' "{repr(cl.name)} object attribute {repr(attr)} cannot be deleted");' + ) + emitter.emit_line("return -1;") + emitter.emit_line("}") + + # HACK: Don't consider refcounted values as always defined, since it's possible to + # access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted + # values is benign. + always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted + + if rtype.is_refcounted: + attr_expr = f"self->{attr_field}" + if not always_defined: + emitter.emit_undefined_attr_check(rtype, attr_expr, "!=", "self", attr, cl) + emitter.emit_dec_ref(f"self->{attr_field}", rtype) + if not always_defined: + emitter.emit_line("}") + + if deletable: + emitter.emit_line("if (value != NULL) {") + + if rtype.is_unboxed: + emitter.emit_unbox("value", "tmp", rtype, error=ReturnHandler("-1"), declare_dest=True) + elif is_same_type(rtype, object_rprimitive): + emitter.emit_line("PyObject *tmp = value;") + else: + emitter.emit_cast("value", "tmp", rtype, declare_dest=True) + emitter.emit_lines("if (!tmp)", " return -1;") + emitter.emit_inc_ref("tmp", rtype) + emitter.emit_line(f"self->{attr_field} = tmp;") + if rtype.error_overlap and not always_defined: + emitter.emit_attr_bitmap_set("tmp", "self", rtype, cl, attr) + + if deletable: + emitter.emit_line("} else {") + emitter.set_undefined_value(f"self->{attr_field}", rtype) + if rtype.error_overlap: + emitter.emit_attr_bitmap_clear("self", rtype, cl, attr) + emitter.emit_line("}") + emitter.emit_line("return 0;") + emitter.emit_line("}") + + +def generate_readonly_getter( + cl: ClassIR, attr: str, rtype: RType, func_ir: FuncIR, emitter: Emitter +) -> None: + emitter.emit_line("static PyObject *") + emitter.emit_line( + "{}({} *self, void *closure)".format( + getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("{") + if rtype.is_unboxed: + emitter.emit_line( + "{}retval = {}{}((PyObject *) self);".format( + emitter.ctype_spaced(rtype), NATIVE_PREFIX, func_ir.cname(emitter.names) + ) + ) + emitter.emit_error_check("retval", rtype, "return NULL;") + emitter.emit_box("retval", "retbox", rtype, declare_dest=True) + emitter.emit_line("return retbox;") + else: + emitter.emit_line( + f"return {NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self);" + ) + emitter.emit_line("}") + + +def generate_property_setter( + cl: ClassIR, attr: str, arg_type: RType, func_ir: FuncIR, emitter: Emitter +) -> None: + emitter.emit_line("static int") + emitter.emit_line( + "{}({} *self, PyObject *value, void *closure)".format( + setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names) + ) + ) + emitter.emit_line("{") + if arg_type.is_unboxed: + emitter.emit_unbox("value", "tmp", arg_type, error=ReturnHandler("-1"), declare_dest=True) + emitter.emit_line( + f"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, tmp);" + ) + else: + emitter.emit_line( + f"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, value);" + ) + emitter.emit_line("return 0;") + emitter.emit_line("}") + + +def has_managed_dict(cl: ClassIR, emitter: Emitter) -> bool: + """Should the class get the Py_TPFLAGS_MANAGED_DICT flag?""" + # On 3.11 and earlier the flag doesn't exist and we use + # tp_dictoffset instead. If a class inherits from Exception, the + # flag conflicts with tp_dictoffset set in the base class. + return ( + emitter.capi_version >= (3, 12) + and cl.has_dict + and cl.builtin_base != "PyBaseExceptionObject" + ) + + +def native_class_doc_initializer(cl: ClassIR) -> str: + init_fn = cl.get_method("__init__") + if init_fn is not None: + text_sig = get_text_signature(init_fn, bound=True) + if text_sig is None: + return "NULL" + text_sig = text_sig.replace("__init__", cl.name, 1) + else: + text_sig = f"{cl.name}()" + docstring = f"{text_sig}\n--\n\n" + return c_string_initializer(docstring.encode("ascii", errors="backslashreplace")) + + +def generate_coroutine_setup( + cl: ClassIR, coroutine_setup_name: str, module_name: str, emitter: Emitter +) -> None: + emitter.emit_line("static bool") + emitter.emit_line(f"{NATIVE_PREFIX}{coroutine_setup_name}(PyObject *type)") + emitter.emit_line("{") + + error_stmt = " return 2;" + + def emit_instance(fn: FuncIR, fn_name: str) -> str: + filepath = emitter.filepath or "" + return emitter.emit_cpyfunction_instance(fn, fn_name, filepath, error_stmt) + + def success() -> None: + emitter.emit_line("return 1;") + emitter.emit_line("}") + + if cl.coroutine_name: + # Callable class generated for a coroutine. It stores its function wrapper as an attribute. + wrapper_name = emit_instance(cl.methods["__call__"], cl.coroutine_name) + struct_name = cl.struct_name(emitter.names) + attr = emitter.attr(CPYFUNCTION_NAME) + emitter.emit_line(f"(({struct_name} *)type)->{attr} = {wrapper_name};") + return success() + + if not any(fn.decl.is_coroutine for fn in cl.methods.values()): + return success() + + emitter.emit_line("PyTypeObject *tp = (PyTypeObject *)type;") + + for fn in cl.methods.values(): + if not fn.decl.is_coroutine: + continue + + name = short_id_from_name(fn.name, fn.decl.shortname, fn.line) + wrapper_name = emit_instance(fn, name) + name_obj = f"{wrapper_name}_name" + emitter.emit_line(f'PyObject *{name_obj} = PyUnicode_FromString("{fn.name}");') + emitter.emit_line(f"if (unlikely(!{name_obj}))") + emitter.emit_line(error_stmt) + emitter.emit_line(f"if (PyDict_SetItem(tp->tp_dict, {name_obj}, {wrapper_name}) < 0)") + emitter.emit_line(error_stmt) + + return success() diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..14d98af039187b245689e587d3f60c79769b1593 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.py b/micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.py new file mode 100644 index 0000000000000000000000000000000000000000..a029ff8cc11f9e7fd46fe2faba16de2babf89c6a --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/codegen/emitfunc.py @@ -0,0 +1,993 @@ +"""Code generation for native function bodies.""" + +from __future__ import annotations + +from typing import Final + +from mypyc.analysis.blockfreq import frequently_executed_blocks +from mypyc.codegen.emit import ( + DEBUG_ERRORS, + PREFIX_MAP, + Emitter, + TracebackAndGotoHandler, + c_array_initializer, +) +from mypyc.common import GENERATOR_ATTRIBUTE_PREFIX, HAVE_IMMORTAL, NATIVE_PREFIX, REG_PREFIX +from mypyc.ir.class_ir import ClassIR +from mypyc.ir.func_ir import FUNC_CLASSMETHOD, FUNC_STATICMETHOD, FuncDecl, FuncIR, all_values +from mypyc.ir.ops import ( + ERR_FALSE, + NAMESPACE_TYPE, + Assign, + AssignMulti, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + ControlOp, + CString, + DecRef, + Extend, + Float, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElement, + GetElementPtr, + Goto, + IncRef, + InitStatic, + Integer, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + Op, + OpVisitor, + PrimitiveOp, + RaiseStandardError, + Register, + Return, + SetAttr, + SetElement, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Undef, + Unreachable, + Value, +) +from mypyc.ir.pprint import generate_names_for_ir +from mypyc.ir.rtypes import ( + RArray, + RInstance, + RStruct, + RTuple, + RType, + RVec, + is_bool_or_bit_rprimitive, + is_int32_rprimitive, + is_int64_rprimitive, + is_int_rprimitive, + is_none_rprimitive, + is_pointer_rprimitive, + is_tagged, +) + + +def native_function_type(fn: FuncIR, emitter: Emitter) -> str: + args = ", ".join(emitter.ctype(arg.type) for arg in fn.args) or "void" + ret = emitter.ctype(fn.ret_type) + return f"{ret} (*)({args})" + + +def native_function_header(fn: FuncDecl, emitter: Emitter) -> str: + args = [] + for arg in fn.sig.args: + args.append(f"{emitter.ctype_spaced(arg.type)}{REG_PREFIX}{arg.name}") + + return "{ret_type}{name}({args})".format( + ret_type=emitter.ctype_spaced(fn.sig.ret_type), + name=emitter.native_function_name(fn), + args=", ".join(args) or "void", + ) + + +def generate_native_function( + fn: FuncIR, emitter: Emitter, source_path: str, module_name: str +) -> None: + declarations = Emitter(emitter.context) + names = generate_names_for_ir(fn.arg_regs, fn.blocks) + body = Emitter(emitter.context, names) + visitor = FunctionEmitterVisitor(body, declarations, source_path, module_name) + + declarations.emit_line(f"{native_function_header(fn.decl, emitter)} {{") + body.indent() + + for r in all_values(fn.arg_regs, fn.blocks): + if isinstance(r.type, RTuple): + emitter.declare_tuple_struct(r.type) + if isinstance(r.type, RArray): + continue # Special: declared on first assignment + + if r in fn.arg_regs: + continue # Skip the arguments + + ctype = emitter.ctype_spaced(r.type) + init = "" + declarations.emit_line( + "{ctype}{prefix}{name}{init};".format( + ctype=ctype, prefix=REG_PREFIX, name=names[r], init=init + ) + ) + + # Before we emit the blocks, give them all labels + blocks = fn.blocks + for i, block in enumerate(blocks): + block.label = i + + # Find blocks that are never jumped to or are only jumped to from the + # block directly above it. This allows for more labels and gotos to be + # eliminated during code generation. + for block in fn.blocks: + terminator = block.terminator + assert isinstance(terminator, ControlOp), terminator + + for target in terminator.targets(): + is_next_block = target.label == block.label + 1 + + # Always emit labels for GetAttr error checks since the emit code that + # generates them will add instructions between the branch and the + # next label, causing the label to be wrongly removed. A better + # solution would be to change the IR so that it adds a basic block + # in between the calls. + is_problematic_op = isinstance(terminator, Branch) and any( + isinstance(s, GetAttr) for s in terminator.sources() + ) + + if not is_next_block or is_problematic_op: + fn.blocks[target.label].referenced = True + + common = frequently_executed_blocks(fn.blocks[0]) + + for i in range(len(blocks)): + block = blocks[i] + visitor.rare = block not in common + next_block = None + if i + 1 < len(blocks): + next_block = blocks[i + 1] + body.emit_label(block) + visitor.next_block = next_block + + ops = block.ops + visitor.ops = ops + visitor.op_index = 0 + while visitor.op_index < len(ops): + ops[visitor.op_index].accept(visitor) + visitor.op_index += 1 + + body.emit_line("}") + + emitter.emit_from_emitter(declarations) + emitter.emit_from_emitter(body) + + +class FunctionEmitterVisitor(OpVisitor[None]): + def __init__( + self, emitter: Emitter, declarations: Emitter, source_path: str, module_name: str + ) -> None: + self.emitter = emitter + self.names = emitter.names + self.declarations = declarations + self.source_path = source_path + self.module_name = module_name + self.literals = emitter.context.literals + self.rare = False + # Next basic block to be processed after the current one (if any), set by caller + self.next_block: BasicBlock | None = None + # Ops in the basic block currently being processed, set by caller + self.ops: list[Op] = [] + # Current index within ops; visit methods can increment this to skip/merge ops + self.op_index = 0 + + def temp_name(self) -> str: + return self.emitter.temp_name() + + def visit_goto(self, op: Goto) -> None: + if op.label is not self.next_block: + self.emit_line("goto %s;" % self.label(op.label)) + + def error_value_check(self, value: Value, compare: str) -> str: + typ = value.type + if isinstance(typ, RTuple): + # TODO: What about empty tuple? + return self.emitter.tuple_undefined_check_cond( + typ, self.reg(value), self.c_error_value, compare + ) + elif isinstance(typ, RVec): + # Error values for vecs are represented by a negative length. + vec_compare = ">=" if compare == "!=" else "<" + return f"{self.reg(value)}.len {vec_compare} 0" + else: + return f"{self.reg(value)} {compare} {self.c_error_value(typ)}" + + def visit_branch(self, op: Branch) -> None: + true, false = op.true, op.false + negated = op.negated + negated_rare = False + if true is self.next_block and op.traceback_entry is None: + # Switch true/false since it avoids an else block. + true, false = false, true + negated = not negated + negated_rare = True + + neg = "!" if negated else "" + cond = "" + if op.op == Branch.BOOL: + expr_result = self.reg(op.value) + cond = f"{neg}{expr_result}" + elif op.op == Branch.IS_ERROR: + compare = "!=" if negated else "==" + cond = self.error_value_check(op.value, compare) + else: + assert False, "Invalid branch" + + # For error checks, tell the compiler the branch is unlikely + if op.traceback_entry is not None or op.rare: + if not negated_rare: + cond = f"unlikely({cond})" + else: + cond = f"likely({cond})" + + if false is self.next_block: + if op.traceback_entry is None: + if true is not self.next_block: + self.emit_line(f"if ({cond}) goto {self.label(true)};") + else: + self.emit_line(f"if ({cond}) {{") + self.emit_traceback(op) + self.emit_lines("goto %s;" % self.label(true), "}") + else: + self.emit_line(f"if ({cond}) {{") + self.emit_traceback(op) + + if true is not self.next_block: + self.emit_line("goto %s;" % self.label(true)) + + self.emit_lines("} else", " goto %s;" % self.label(false)) + + def visit_return(self, op: Return) -> None: + value_str = self.reg(op.value) + self.emit_line("return %s;" % value_str) + + def visit_tuple_set(self, op: TupleSet) -> None: + dest = self.reg(op) + tuple_type = op.tuple_type + self.emitter.declare_tuple_struct(tuple_type) + if len(op.items) == 0: # empty tuple + self.emit_line(f"{dest}.empty_struct_error_flag = 0;") + else: + for i, item in enumerate(op.items): + self.emit_line(f"{dest}.f{i} = {self.reg(item)};") + + def visit_assign(self, op: Assign) -> None: + dest = self.reg(op.dest) + src = self.reg(op.src) + # clang whines about self assignment (which we might generate + # for some casts), so don't emit it. + if dest != src: + src_type = op.src.type + dest_type = op.dest.type + if src_type.is_unboxed and not dest_type.is_unboxed: + # We sometimes assign from an integer prepresentation of a pointer + # to a real pointer, and C compilers insist on a cast. + src = f"(void *){src}" + elif not src_type.is_unboxed and dest_type.is_unboxed: + # We sometimes assign a pointer to an integer type (e.g. to create + # tagged pointers), and here we need an explicit cast. + src = f"({self.emitter.ctype(dest_type)}){src}" + self.emit_line(f"{dest} = {src};") + + def visit_assign_multi(self, op: AssignMulti) -> None: + typ = op.dest.type + assert isinstance(typ, RArray), typ + dest = self.reg(op.dest) + # RArray values can only be assigned to once, so we can always + # declare them on initialization. + self.emit_line( + "%s%s[%d] = %s;" + % ( + self.emitter.ctype_spaced(typ.item_type), + dest, + len(op.src), + c_array_initializer([self.reg(s) for s in op.src], indented=True), + ) + ) + + def visit_load_error_value(self, op: LoadErrorValue) -> None: + reg = self.reg(op) + if isinstance(op.type, RTuple): + values = [self.c_undefined_value(item) for item in op.type.types] + tmp = self.temp_name() + self.emit_line("{} {} = {{ {} }};".format(self.ctype(op.type), tmp, ", ".join(values))) + self.emit_line(f"{reg} = {tmp};") + elif isinstance(op.type, RVec): + self.emitter.set_undefined_value(reg, op.type) + else: + self.emit_line(f"{self.reg(op)} = {self.c_error_value(op.type)};") + + def visit_load_literal(self, op: LoadLiteral) -> None: + index = self.literals.literal_index(op.value) + if not is_int_rprimitive(op.type): + self.emit_line("%s = CPyStatics[%d];" % (self.reg(op), index), ann=op.value) + else: + self.emit_line( + "%s = (CPyTagged)CPyStatics[%d] | 1;" % (self.reg(op), index), ann=op.value + ) + + def get_attr_expr(self, obj: str, op: GetAttr | SetAttr, decl_cl: ClassIR) -> str: + """Generate attribute accessor for normal (non-property) access. + + This either has a form like obj->attr_name for attributes defined in non-trait + classes, and *(obj + attr_offset) for attributes defined by traits. We also + insert all necessary C casts here. + """ + cast = f"({op.class_type.struct_name(self.emitter.names)} *)" + if decl_cl.is_trait and op.class_type.class_ir.is_trait: + # For pure trait access find the offset first, offsets + # are ordered by attribute position in the cl.attributes dict. + # TODO: pre-calculate the mapping to make this faster. + trait_attr_index = list(decl_cl.attributes).index(op.attr) + # TODO: reuse these names somehow? + offset = self.emitter.temp_name() + self.declarations.emit_line(f"size_t {offset};") + self.emitter.emit_line( + "{} = {};".format( + offset, + "CPy_FindAttrOffset({}, {}, {})".format( + self.emitter.type_struct_name(decl_cl), + f"({cast}{obj})->vtable", + trait_attr_index, + ), + ) + ) + attr_cast = f"({self.ctype(op.class_type.attr_type(op.attr))} *)" + return f"*{attr_cast}((char *){obj} + {offset})" + else: + # Cast to something non-trait. Note: for this to work, all struct + # members for non-trait classes must obey monotonic linear growth. + if op.class_type.class_ir.is_trait: + assert not decl_cl.is_trait + cast = f"({decl_cl.struct_name(self.emitter.names)} *)" + return f"({cast}{obj})->{self.emitter.attr(op.attr)}" + + def visit_get_attr(self, op: GetAttr) -> None: + if op.allow_error_value: + self.get_attr_with_allow_error_value(op) + return + dest = self.reg(op) + obj = self.reg(op.obj) + rtype = op.class_type + cl = rtype.class_ir + attr_rtype, decl_cl = cl.attr_details(op.attr) + prefer_method = cl.is_trait and attr_rtype.error_overlap + if cl.get_method(op.attr, prefer_method=prefer_method): + # Properties are essentially methods, so use vtable access for them. + if cl.is_method_final(op.attr): + self.emit_method_call(f"{dest} = ", op.obj, op.attr, []) + else: + version = "_TRAIT" if cl.is_trait else "" + self.emit_line( + "%s = CPY_GET_ATTR%s(%s, %s, %d, %s, %s); /* %s */" + % ( + dest, + version, + obj, + self.emitter.type_struct_name(rtype.class_ir), + rtype.getter_index(op.attr), + rtype.struct_name(self.names), + self.ctype(rtype.attr_type(op.attr)), + op.attr, + ) + ) + else: + # Otherwise, use direct or offset struct access. + attr_expr = self.get_attr_expr(obj, op, decl_cl) + self.emitter.emit_line(f"{dest} = {attr_expr};") + always_defined = cl.is_always_defined(op.attr) + merged_branch = None + if not always_defined: + self.emitter.emit_undefined_attr_check( + attr_rtype, dest, "==", obj, op.attr, cl, unlikely=True + ) + branch = self.next_branch() + if branch is not None: + if ( + branch.value is op + and branch.op == Branch.IS_ERROR + and branch.traceback_entry is not None + and not branch.negated + ): + # Generate code for the following branch here to avoid + # redundant branches in the generated code. + self.emit_attribute_error(branch, cl.name, op.attr) + self.emit_line("goto %s;" % self.label(branch.true)) + merged_branch = branch + self.emitter.emit_line("}") + if not merged_branch: + exc_class = "PyExc_AttributeError" + self.emitter.emit_line( + 'PyErr_SetString({}, "attribute {} of {} undefined");'.format( + exc_class, + repr(op.attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX)), + repr(cl.name), + ) + ) + + if attr_rtype.is_refcounted and not op.is_borrowed: + if not merged_branch and not always_defined: + self.emitter.emit_line("} else {") + self.emitter.emit_inc_ref(dest, attr_rtype) + if merged_branch: + if merged_branch.false is not self.next_block: + self.emit_line("goto %s;" % self.label(merged_branch.false)) + self.op_index += 1 + elif not always_defined: + self.emitter.emit_line("}") + + def get_attr_with_allow_error_value(self, op: GetAttr) -> None: + """Handle GetAttr with allow_error_value=True. + + This allows NULL or other error value without raising AttributeError. + """ + dest = self.reg(op) + obj = self.reg(op.obj) + rtype = op.class_type + cl = rtype.class_ir + attr_rtype, decl_cl = cl.attr_details(op.attr) + + # Direct struct access without NULL check + attr_expr = self.get_attr_expr(obj, op, decl_cl) + self.emitter.emit_line(f"{dest} = {attr_expr};") + + # Only emit inc_ref if not NULL + if attr_rtype.is_refcounted and not op.is_borrowed: + check = self.error_value_check(op, "!=") + self.emitter.emit_line(f"if ({check}) {{") + self.emitter.emit_inc_ref(dest, attr_rtype) + self.emitter.emit_line("}") + + def next_branch(self) -> Branch | None: + if self.op_index + 1 < len(self.ops): + next_op = self.ops[self.op_index + 1] + if isinstance(next_op, Branch): + return next_op + return None + + def visit_set_attr(self, op: SetAttr) -> None: + if op.error_kind == ERR_FALSE: + dest = self.reg(op) + obj = self.reg(op.obj) + src = self.reg(op.src) + rtype = op.class_type + cl = rtype.class_ir + attr_rtype, decl_cl = cl.attr_details(op.attr) + if op.is_propset: + # Again, use vtable access for properties... + assert not op.is_init and op.error_kind == ERR_FALSE, "%s %d %d %s" % ( + op.attr, + op.is_init, + op.error_kind, + rtype, + ) + version = "_TRAIT" if cl.is_trait else "" + self.emit_line( + "%s = CPY_SET_ATTR%s(%s, %s, %d, %s, %s, %s); /* %s */" + % ( + dest, + version, + obj, + self.emitter.type_struct_name(rtype.class_ir), + rtype.setter_index(op.attr), + src, + rtype.struct_name(self.names), + self.ctype(rtype.attr_type(op.attr)), + op.attr, + ) + ) + else: + # ...and struct access for normal attributes. + attr_expr = self.get_attr_expr(obj, op, decl_cl) + if not op.is_init and attr_rtype.is_refcounted: + # This is not an initialization (where we know that the attribute was + # previously undefined), so decref the old value. + always_defined = cl.is_always_defined(op.attr) + if not always_defined: + self.emitter.emit_undefined_attr_check( + attr_rtype, attr_expr, "!=", obj, op.attr, cl + ) + self.emitter.emit_dec_ref(attr_expr, attr_rtype) + if not always_defined: + self.emitter.emit_line("}") + elif attr_rtype.error_overlap and not cl.is_always_defined(op.attr): + # If there is overlap with the error value, update bitmap to mark + # attribute as defined. + self.emitter.emit_attr_bitmap_set(src, obj, attr_rtype, cl, op.attr) + + # This steals the reference to src, so we don't need to increment the arg + self.emitter.emit_line(f"{attr_expr} = {src};") + if op.error_kind == ERR_FALSE: + self.emitter.emit_line(f"{dest} = 1;") + + def visit_load_static(self, op: LoadStatic) -> None: + dest = self.reg(op) + prefix = PREFIX_MAP[op.namespace] + name = self.emitter.static_name(op.identifier, op.module_name, prefix) + if op.namespace == NAMESPACE_TYPE: + name = "(PyObject *)%s" % name + self.emit_line(f"{dest} = {name};", ann=op.ann) + + def visit_init_static(self, op: InitStatic) -> None: + value = self.reg(op.value) + prefix = PREFIX_MAP[op.namespace] + name = self.emitter.static_name(op.identifier, op.module_name, prefix) + if op.namespace == NAMESPACE_TYPE: + value = "(PyTypeObject *)%s" % value + self.emit_line(f"{name} = {value};") + self.emit_inc_ref(name, op.value.type) + + def visit_tuple_get(self, op: TupleGet) -> None: + dest = self.reg(op) + src = self.reg(op.src) + self.emit_line(f"{dest} = {src}.f{op.index};") + if not op.is_borrowed: + self.emit_inc_ref(dest, op.type) + + def get_dest_assign(self, dest: Value) -> str: + if not dest.is_void: + return self.reg(dest) + " = " + else: + return "" + + def visit_call(self, op: Call) -> None: + """Call native function.""" + dest = self.get_dest_assign(op) + args = ", ".join(self.reg(arg) for arg in op.args) + lib = self.emitter.get_group_prefix(op.fn) + cname = op.fn.cname(self.names) + self.emit_line(f"{dest}{lib}{NATIVE_PREFIX}{cname}({args});") + + def visit_method_call(self, op: MethodCall) -> None: + """Call native method.""" + dest = self.get_dest_assign(op) + self.emit_method_call(dest, op.obj, op.method, op.args) + + def emit_method_call(self, dest: str, op_obj: Value, name: str, op_args: list[Value]) -> None: + obj = self.reg(op_obj) + rtype = op_obj.type + assert isinstance(rtype, RInstance), rtype + class_ir = rtype.class_ir + method = rtype.class_ir.get_method(name) + assert method is not None + + # Can we call the method directly, bypassing vtable? + is_direct = class_ir.is_method_final(name) + + # The first argument gets omitted for static methods and + # turned into the class for class methods + obj_args = ( + [] + if method.decl.kind == FUNC_STATICMETHOD + else [f"(PyObject *)Py_TYPE({obj})"] if method.decl.kind == FUNC_CLASSMETHOD else [obj] + ) + args = ", ".join(obj_args + [self.reg(arg) for arg in op_args]) + mtype = native_function_type(method, self.emitter) + version = "_TRAIT" if rtype.class_ir.is_trait else "" + if is_direct: + # Directly call method, without going through the vtable. + lib = self.emitter.get_group_prefix(method.decl) + self.emit_line(f"{dest}{lib}{NATIVE_PREFIX}{method.cname(self.names)}({args});") + else: + # Call using vtable. + method_idx = rtype.method_index(name) + self.emit_line( + "{}CPY_GET_METHOD{}({}, {}, {}, {}, {})({}); /* {} */".format( + dest, + version, + obj, + self.emitter.type_struct_name(rtype.class_ir), + method_idx, + rtype.struct_name(self.names), + mtype, + args, + name, + ) + ) + + def visit_inc_ref(self, op: IncRef) -> None: + if ( + isinstance(op.src, Box) + and (is_none_rprimitive(op.src.src.type) or is_bool_or_bit_rprimitive(op.src.src.type)) + and HAVE_IMMORTAL + ): + # On Python 3.12+, None/True/False are immortal, and we can skip inc ref + return + + if isinstance(op.src, LoadLiteral) and HAVE_IMMORTAL: + value = op.src.value + # We can skip inc ref for immortal literals on Python 3.12+ + if type(value) is int and -5 <= value <= 256: + # Small integers are immortal + return + + src = self.reg(op.src) + self.emit_inc_ref(src, op.src.type) + + def visit_dec_ref(self, op: DecRef) -> None: + src = self.reg(op.src) + self.emit_dec_ref(src, op.src.type, is_xdec=op.is_xdec) + + def visit_box(self, op: Box) -> None: + self.emitter.emit_box(self.reg(op.src), self.reg(op), op.src.type, can_borrow=True) + + def visit_cast(self, op: Cast) -> None: + if op.is_unchecked and op.is_borrowed: + self.emit_line(f"{self.reg(op)} = {self.reg(op.src)};") + return + branch = self.next_branch() + handler = None + if branch is not None: + if ( + branch.value is op + and branch.op == Branch.IS_ERROR + and branch.traceback_entry is not None + and not branch.negated + and branch.false is self.next_block + ): + # Generate code also for the following branch here to avoid + # redundant branches in the generated code. + handler = TracebackAndGotoHandler( + self.label(branch.true), + self.source_path, + self.module_name, + branch.traceback_entry, + ) + self.op_index += 1 + + self.emitter.emit_cast( + self.reg(op.src), self.reg(op), op.type, src_type=op.src.type, error=handler + ) + + def visit_unbox(self, op: Unbox) -> None: + self.emitter.emit_unbox(self.reg(op.src), self.reg(op), op.type) + + def visit_unreachable(self, op: Unreachable) -> None: + self.emitter.emit_line("CPy_Unreachable();") + + def visit_raise_standard_error(self, op: RaiseStandardError) -> None: + # TODO: Better escaping of backspaces and such + if op.value is not None: + if isinstance(op.value, str): + message = op.value.replace('"', '\\"') + self.emitter.emit_line(f'PyErr_SetString(PyExc_{op.class_name}, "{message}");') + elif isinstance(op.value, Value): + self.emitter.emit_line( + "PyErr_SetObject(PyExc_{}, {});".format( + op.class_name, self.emitter.reg(op.value) + ) + ) + else: + assert False, "op value type must be either str or Value" + else: + self.emitter.emit_line(f"PyErr_SetNone(PyExc_{op.class_name});") + self.emitter.emit_line(f"{self.reg(op)} = 0;") + + def visit_call_c(self, op: CallC) -> None: + if op.is_void: + dest = "" + else: + dest = self.get_dest_assign(op) + args = ", ".join(self.reg(arg) for arg in op.args) + self.emitter.emit_line(f"{dest}{op.function_name}({args});") + + def visit_primitive_op(self, op: PrimitiveOp) -> None: + raise RuntimeError( + f"unexpected PrimitiveOp {op.desc.name}: they must be lowered before codegen" + ) + + def visit_truncate(self, op: Truncate) -> None: + dest = self.reg(op) + value = self.reg(op.src) + # for C backend the generated code are straight assignments + self.emit_line(f"{dest} = {value};") + + def visit_extend(self, op: Extend) -> None: + dest = self.reg(op) + value = self.reg(op.src) + if op.signed: + src_cast = self.emit_signed_int_cast(op.src.type) + else: + src_cast = self.emit_unsigned_int_cast(op.src.type) + self.emit_line(f"{dest} = {src_cast}{value};") + + def visit_load_global(self, op: LoadGlobal) -> None: + dest = self.reg(op) + self.emit_line(f"{dest} = {op.identifier};", ann=op.ann) + + def visit_int_op(self, op: IntOp) -> None: + dest = self.reg(op) + lhs = self.reg(op.lhs) + rhs = self.reg(op.rhs) + if op.op == IntOp.RIGHT_SHIFT: + # Signed right shift + lhs = self.emit_signed_int_cast(op.lhs.type) + lhs + rhs = self.emit_signed_int_cast(op.rhs.type) + rhs + self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};") + + def visit_comparison_op(self, op: ComparisonOp) -> None: + dest = self.reg(op) + lhs = self.reg(op.lhs) + rhs = self.reg(op.rhs) + lhs_cast = "" + rhs_cast = "" + if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE): + # Always signed comparison op + lhs_cast = self.emit_signed_int_cast(op.lhs.type) + rhs_cast = self.emit_signed_int_cast(op.rhs.type) + elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE): + # Always unsigned comparison op + lhs_cast = self.emit_unsigned_int_cast(op.lhs.type) + rhs_cast = self.emit_unsigned_int_cast(op.rhs.type) + elif isinstance(op.lhs, Integer) and op.lhs.value < 0: + # Force signed ==/!= with negative operand + rhs_cast = self.emit_signed_int_cast(op.rhs.type) + elif isinstance(op.rhs, Integer) and op.rhs.value < 0: + # Force signed ==/!= with negative operand + lhs_cast = self.emit_signed_int_cast(op.lhs.type) + self.emit_line(f"{dest} = {lhs_cast}{lhs} {op.op_str[op.op]} {rhs_cast}{rhs};") + + def visit_float_op(self, op: FloatOp) -> None: + dest = self.reg(op) + lhs = self.reg(op.lhs) + rhs = self.reg(op.rhs) + if op.op != FloatOp.MOD: + self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};") + else: + # TODO: This may set errno as a side effect, that is a little sketchy. + self.emit_line(f"{dest} = fmod({lhs}, {rhs});") + + def visit_float_neg(self, op: FloatNeg) -> None: + dest = self.reg(op) + src = self.reg(op.src) + self.emit_line(f"{dest} = -{src};") + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> None: + dest = self.reg(op) + lhs = self.reg(op.lhs) + rhs = self.reg(op.rhs) + self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};") + + def visit_load_mem(self, op: LoadMem) -> None: + dest = self.reg(op) + src = self.reg(op.src) + # TODO: we shouldn't dereference to type that are pointer type so far + type = self.ctype(op.type) + self.emit_line(f"{dest} = *({type} *){src};") + if not op.is_borrowed: + self.emit_inc_ref(dest, op.type) + + def visit_set_mem(self, op: SetMem) -> None: + dest = self.reg(op.dest) + src = self.reg(op.src) + dest_type = self.ctype(op.dest_type) + # clang whines about self assignment (which we might generate + # for some casts), so don't emit it. + if dest != src: + self.emit_line(f"*({dest_type} *){dest} = {src};") + + def visit_get_element(self, op: GetElement) -> None: + dest = self.reg(op) + src = self.reg(op.src) + dest_type = self.ctype(op.type) + self.emit_line(f"{dest} = ({dest_type}){src}.{op.field};") + + def visit_get_element_ptr(self, op: GetElementPtr) -> None: + dest = self.reg(op) + src = self.reg(op.src) + # TODO: support tuple type + assert isinstance(op.src_type, RStruct), op.src_type + assert op.field in op.src_type.names, "Invalid field name." + # Use offsetof to avoid undefined behavior when src is NULL + # (e.g., vec buf pointer for empty vecs). The &((T*)p)->field + # pattern is UB when p is NULL, which GCC -O3 can exploit. + self.emit_line( + "{} = ({})((CPyPtr){} + offsetof({}, {}));".format( + dest, op.type._ctype, src, op.src_type.name, op.field + ) + ) + + def visit_set_element(self, op: SetElement) -> None: + dest = self.reg(op) + item = self.reg(op.item) + field = op.field + if isinstance(op.src, Undef): + # First assignment to an undefined struct is trivial. + self.emit_line(f"{dest}.{field} = {item};") + else: + # In the general case create a copy of the struct with a single + # item modified. + # + # TODO: Can we do better if only a subset of fields are initialized? + # TODO: Make this less verbose in the common case + # TODO: Support tuples (or use RStruct for tuples)? + src = self.reg(op.src) + src_type = op.src.type + assert isinstance(src_type, RStruct), src_type + init_items = [] + for n in src_type.names: + if n != field: + init_items.append(f"{src}.{n}") + else: + init_items.append(item) + self.emit_line(f"{dest} = ({self.ctype(src_type)}) {{ {', '.join(init_items)} }};") + + def visit_load_address(self, op: LoadAddress) -> None: + typ = op.type + dest = self.reg(op) + if isinstance(op.src, Register): + src = self.reg(op.src) + elif isinstance(op.src, LoadStatic): + prefix = PREFIX_MAP[op.src.namespace] + src = self.emitter.static_name(op.src.identifier, op.src.module_name, prefix) + else: + src = op.src + self.emit_line(f"{dest} = ({typ._ctype})&{src};") + + def visit_keep_alive(self, op: KeepAlive) -> None: + # This is a no-op. + pass + + def visit_unborrow(self, op: Unborrow) -> None: + # This is a no-op that propagates the source value. + dest = self.reg(op) + src = self.reg(op.src) + self.emit_line(f"{dest} = {src};") + + # Helpers + + def label(self, label: BasicBlock) -> str: + return self.emitter.label(label) + + def reg(self, reg: Value) -> str: + if isinstance(reg, Integer): + val = reg.value + if val == 0 and is_pointer_rprimitive(reg.type): + return "NULL" + s = str(val) + if val >= (1 << 31): + # Avoid overflowing signed 32-bit int + if val >= (1 << 63): + s += "ULL" + else: + s += "LL" + elif val == -(1 << 63): + # Avoid overflowing C integer literal + s = "(-9223372036854775807LL - 1)" + elif val <= -(1 << 31): + s += "LL" + return s + elif isinstance(reg, Float): + r = repr(reg.value) + if r == "inf": + return "INFINITY" + elif r == "-inf": + return "-INFINITY" + elif r == "nan": + return "NAN" + return r + elif isinstance(reg, CString): + return '"' + encode_c_string_literal(reg.value) + '"' + else: + return self.emitter.reg(reg) + + def ctype(self, rtype: RType) -> str: + return self.emitter.ctype(rtype) + + def c_error_value(self, rtype: RType) -> str: + return self.emitter.c_error_value(rtype) + + def c_undefined_value(self, rtype: RType) -> str: + return self.emitter.c_undefined_value(rtype) + + def emit_line(self, line: str, *, ann: object = None) -> None: + self.emitter.emit_line(line, ann=ann) + + def emit_lines(self, *lines: str) -> None: + self.emitter.emit_lines(*lines) + + def emit_inc_ref(self, dest: str, rtype: RType) -> None: + self.emitter.emit_inc_ref(dest, rtype, rare=self.rare) + + def emit_dec_ref(self, dest: str, rtype: RType, is_xdec: bool) -> None: + self.emitter.emit_dec_ref(dest, rtype, is_xdec=is_xdec, rare=self.rare) + + def emit_declaration(self, line: str) -> None: + self.declarations.emit_line(line) + + def emit_traceback(self, op: Branch) -> None: + if op.traceback_entry is not None: + self.emitter.emit_traceback(self.source_path, self.module_name, op.traceback_entry) + + def emit_attribute_error(self, op: Branch, class_name: str, attr: str) -> None: + assert op.traceback_entry is not None + if self.emitter.context.strict_traceback_checks: + assert ( + op.traceback_entry[1] >= 0 + ), "AttributeError traceback cannot have a negative line number" + globals_static = self.emitter.static_name("globals", self.module_name) + self.emit_line( + 'CPy_AttributeError("%s", "%s", "%s", "%s", %d, %s);' + % ( + self.source_path.replace("\\", "\\\\"), + op.traceback_entry[0], + class_name, + attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX), + op.traceback_entry[1], + globals_static, + ) + ) + if DEBUG_ERRORS: + self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");') + + def emit_signed_int_cast(self, type: RType) -> str: + if is_tagged(type): + return "(Py_ssize_t)" + else: + return "" + + def emit_unsigned_int_cast(self, type: RType) -> str: + if is_int32_rprimitive(type): + return "(uint32_t)" + elif is_int64_rprimitive(type): + return "(uint64_t)" + else: + return "" + + +_translation_table: Final[dict[int, str]] = {} + + +def encode_c_string_literal(b: bytes) -> str: + """Convert bytestring to the C string literal syntax (with necessary escaping). + + For example, b'foo\n' gets converted to 'foo\\n' (note that double quotes are not added). + """ + if not _translation_table: + # Initialize the translation table on the first call. + d = { + ord("\n"): "\\n", + ord("\r"): "\\r", + ord("\t"): "\\t", + ord('"'): '\\"', + ord("\\"): "\\\\", + } + for i in range(256): + if i not in d: + if i < 32 or i >= 127: + d[i] = "\\x%.2x" % i + else: + d[i] = chr(i) + _translation_table.update(str.maketrans(d)) + return b.decode("latin1").translate(_translation_table) diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..963a6f49b36aae467c866861fb45e2848c041bc7 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.py b/micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.py new file mode 100644 index 0000000000000000000000000000000000000000..05b2e64b386523028344550cd241ea2e64e799db --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/codegen/emitmodule.py @@ -0,0 +1,1494 @@ +"""Generate C code for a Python C extension module from Python source code.""" + +# FIXME: Basically nothing in this file operates on the level of a +# single module and it should be renamed. + +from __future__ import annotations + +import json +import os +import sys +from collections.abc import Iterable +from typing import TypeVar + +from mypy.build import ( + BuildResult, + BuildSource, + State, + build, + compute_hash, + create_metastore, + get_cache_names, + sorted_components, +) +from mypy.errors import CompileError +from mypy.fscache import FileSystemCache +from mypy.nodes import MypyFile +from mypy.options import Options +from mypy.plugin import Plugin, ReportConfigContext +from mypy.util import hash_digest, json_dumps +from mypyc.analysis.capsule_deps import find_class_dependencies, find_implicit_op_dependencies +from mypyc.codegen.cstring import c_string_initializer +from mypyc.codegen.emit import ( + Emitter, + EmitterContext, + HeaderDeclaration, + c_array_initializer, + native_function_doc_initializer, +) +from mypyc.codegen.emitclass import generate_class, generate_class_reuse, generate_class_type_decl +from mypyc.codegen.emitfunc import generate_native_function, native_function_header +from mypyc.codegen.emitwrapper import ( + generate_legacy_wrapper_function, + generate_wrapper_function, + legacy_wrapper_function_header, + wrapper_function_header, +) +from mypyc.codegen.literals import Literals +from mypyc.common import ( + EXT_SUFFIX, + IS_FREE_THREADED, + MODULE_PREFIX, + PREFIX, + RUNTIME_C_FILES, + TOP_LEVEL_NAME, + TYPE_VAR_PREFIX, + shared_lib_name, + short_id_from_name, +) +from mypyc.errors import Errors +from mypyc.ir.deps import LIBRT_BASE64, LIBRT_STRINGS, LIBRT_TIME, LIBRT_VECS, SourceDep +from mypyc.ir.func_ir import FuncIR +from mypyc.ir.module_ir import ModuleIR, ModuleIRs, deserialize_modules +from mypyc.ir.ops import DeserMaps, LoadLiteral +from mypyc.ir.rtypes import RType +from mypyc.irbuild.main import build_ir +from mypyc.irbuild.mapper import Mapper +from mypyc.irbuild.prepare import load_type_map +from mypyc.namegen import NameGenerator, exported_name +from mypyc.options import CompilerOptions +from mypyc.transform.copy_propagation import do_copy_propagation +from mypyc.transform.exceptions import insert_exception_handling +from mypyc.transform.flag_elimination import do_flag_elimination +from mypyc.transform.log_trace import insert_event_trace_logging +from mypyc.transform.lower import lower_ir +from mypyc.transform.refcount import insert_ref_count_opcodes +from mypyc.transform.spill import insert_spills +from mypyc.transform.uninit import insert_uninit_checks + +# All the modules being compiled are divided into "groups". A group +# is a set of modules that are placed into the same shared library. +# Two common configurations are that every module is placed in a group +# by itself (fully separate compilation) and that every module is +# placed in the same group (fully whole-program compilation), but we +# support finer-grained control of the group as well. +# +# In fully whole-program compilation, we will generate N+1 extension +# modules: one shim per module and one shared library containing all +# the actual code. +# In fully separate compilation, we (unfortunately) will generate 2*N +# extension modules: one shim per module and also one library containing +# each module's actual code. (This might be fixable in the future, +# but allows a clean separation between setup of the export tables +# (see generate_export_table) and running module top levels.) +# +# A group is represented as a list of BuildSources containing all of +# its modules along with the name of the group. (Which can be None +# only if we are compiling only a single group with a single file in it +# and not using shared libraries). +Group = tuple[list[BuildSource], str | None] +Groups = list[Group] + +# A list of (file name, file contents) pairs. +FileContents = list[tuple[str, str]] + + +class MarkedDeclaration: + """Add a mark, useful for topological sort.""" + + def __init__(self, declaration: HeaderDeclaration, mark: bool) -> None: + self.declaration = declaration + self.mark = False + + +class MypycPlugin(Plugin): + """Plugin for making mypyc interoperate properly with mypy incremental mode. + + Basically the point of this plugin is to force mypy to recheck things + based on the demands of mypyc in a couple situations: + * Any modules in the same group must be compiled together, so we + tell mypy that modules depend on all their groupmates. + * If the IR metadata is missing or stale or any of the generated + C source files associated missing or stale, then we need to + recompile the module so we mark it as stale. + """ + + def __init__( + self, options: Options, compiler_options: CompilerOptions, groups: Groups + ) -> None: + super().__init__(options) + self.group_map: dict[str, tuple[str | None, list[str]]] = {} + for sources, name in groups: + modules = sorted(source.module for source in sources) + for id in modules: + self.group_map[id] = (name, modules) + + self.compiler_options = compiler_options + self.metastore = create_metastore(options, parallel_worker=False) + + def report_config_data(self, ctx: ReportConfigContext) -> tuple[str | None, list[str]] | None: + # The config data we report is the group map entry for the module. + # If the data is being used to check validity, we do additional checks + # that the IR cache exists and matches the metadata cache and all + # output source files exist and are up to date. + + id, path, is_check = ctx.id, ctx.path, ctx.is_check + + if id not in self.group_map: + return None + + # If we aren't doing validity checks, just return the cache data + if not is_check: + return self.group_map[id] + + # Load the metadata and IR cache + meta_path, _, _ = get_cache_names(id, path, self.options) + ir_path = get_ir_cache_name(id, path, self.options) + try: + meta_json = self.metastore.read(meta_path) + ir_json = self.metastore.read(ir_path) + except FileNotFoundError: + # This could happen if mypyc failed after mypy succeeded + # in the previous run or if some cache files got + # deleted. No big deal, just fail to load the cache. + return None + + ir_data = json.loads(ir_json) + + # Check that the IR cache matches the metadata cache + if hash_digest(meta_json) != ir_data["meta_hash"]: + return None + + # Check that all the source files are present and as + # expected. The main situation where this would come up is the + # user deleting the build directory without deleting + # .mypy_cache, which we should handle gracefully. + for path, hash in ir_data["src_hashes"].items(): + try: + with open(os.path.join(self.compiler_options.target_dir, path), "rb") as f: + contents = f.read() + except FileNotFoundError: + return None + real_hash = hash_digest(contents) + if hash != real_hash: + return None + + return self.group_map[id] + + def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: + # Report dependency on modules in the module's group + return [(10, id, -1) for id in self.group_map.get(file.fullname, (None, []))[1]] + + +def parse_and_typecheck( + sources: list[BuildSource], + options: Options, + compiler_options: CompilerOptions, + groups: Groups, + fscache: FileSystemCache | None = None, + alt_lib_path: str | None = None, +) -> BuildResult: + assert options.strict_optional, "strict_optional must be turned on" + mypyc_plugin = MypycPlugin(options, compiler_options, groups) + result = build( + sources=sources, + options=options, + alt_lib_path=alt_lib_path, + fscache=fscache, + extra_plugins=[mypyc_plugin], + ) + mypyc_plugin.metastore.close() + if result.errors: + raise CompileError(result.errors) + return result + + +def compile_scc_to_ir( + scc: list[MypyFile], + result: BuildResult, + mapper: Mapper, + compiler_options: CompilerOptions, + errors: Errors, +) -> ModuleIRs: + """Compile an SCC into ModuleIRs. + + Any modules that this SCC depends on must have either been compiled, + type checked, or loaded from a cache into mapper. + + Arguments: + scc: The list of MypyFiles to compile + result: The BuildResult from the mypy front-end + mapper: The Mapper object mapping mypy ASTs to class and func IRs + compiler_options: The compilation options + errors: Where to report any errors encountered + + Returns the IR of the modules. + """ + + if compiler_options.verbose: + print("Compiling {}".format(", ".join(x.name for x in scc))) + + # Generate basic IR, with missing exception and refcount handling. + modules = build_ir(scc, result.graph, result.types, mapper, compiler_options, errors) + if errors.num_errors > 0: + return modules + + env_user_functions = {} + for module in modules.values(): + for cls in module.classes: + if cls.env_user_function: + env_user_functions[cls.env_user_function] = cls + + for module in modules.values(): + for fn in module.functions: + # Insert checks for uninitialized values. + insert_uninit_checks(fn, compiler_options.strict_traceback_checks) + # Insert exception handling. + insert_exception_handling(fn, compiler_options.strict_traceback_checks) + # Insert reference count handling. + insert_ref_count_opcodes(fn) + + if fn in env_user_functions: + insert_spills(fn, env_user_functions[fn]) + + if compiler_options.log_trace: + insert_event_trace_logging(fn, compiler_options) + + # Switch to lower abstraction level IR. + lower_ir(fn, compiler_options) + # Calculate implicit module dependencies (needed for librt) + deps = find_implicit_op_dependencies(fn) + if deps is not None: + module.dependencies.update(deps) + # Perform optimizations. + do_copy_propagation(fn, compiler_options) + do_flag_elimination(fn, compiler_options) + + # Calculate implicit dependencies from class attribute types + for cl in module.classes: + deps = find_class_dependencies(cl) + if deps is not None: + module.dependencies.update(deps) + + return modules + + +def compile_modules_to_ir( + result: BuildResult, mapper: Mapper, compiler_options: CompilerOptions, errors: Errors +) -> ModuleIRs: + """Compile a collection of modules into ModuleIRs. + + The modules to compile are specified as part of mapper's group_map. + + Returns the IR of the modules. + """ + deser_ctx = DeserMaps({}, {}) + modules = {} + + # Process the graph by SCC in topological order, like we do in mypy.build + for scc in sorted_components(result.graph): + scc_states = [result.graph[id] for id in scc.mod_ids] + trees = [st.tree for st in scc_states if st.id in mapper.group_map and st.tree] + + if not trees: + continue + + fresh = all(id not in result.manager.rechecked_modules for id in scc.mod_ids) + if fresh: + load_scc_from_cache(trees, result, mapper, deser_ctx) + else: + scc_ir = compile_scc_to_ir(trees, result, mapper, compiler_options, errors) + modules.update(scc_ir) + + return modules + + +def compile_ir_to_c( + groups: Groups, + modules: ModuleIRs, + result: BuildResult, + mapper: Mapper, + compiler_options: CompilerOptions, +) -> dict[str | None, list[tuple[str, str]]]: + """Compile a collection of ModuleIRs to C source text. + + Returns a dictionary mapping group names to a list of (file name, + file text) pairs. + """ + source_paths = { + source.module: result.graph[source.module].xpath + for sources, _ in groups + for source in sources + } + + names = NameGenerator( + [[source.module for source in sources] for sources, _ in groups], + separate=compiler_options.separate, + ) + + # Generate C code for each compilation group. Each group will be + # compiled into a separate extension module. + ctext: dict[str | None, list[tuple[str, str]]] = {} + for group_sources, group_name in groups: + group_modules = { + source.module: modules[source.module] + for source in group_sources + if source.module in modules + } + if not group_modules: + ctext[group_name] = [] + continue + generator = GroupGenerator( + group_modules, source_paths, group_name, mapper.group_map, names, compiler_options + ) + ctext[group_name] = generator.generate_c_for_modules() + + return ctext + + +def get_ir_cache_name(id: str, path: str, options: Options) -> str: + meta_path, _, _ = get_cache_names(id, path, options) + # Mypyc uses JSON cache even with --fixed-format-cache (for now). + return meta_path.replace(".meta.json", ".ir.json").replace(".meta.ff", ".ir.json") + + +def get_state_ir_cache_name(state: State) -> str: + return get_ir_cache_name(state.id, state.xpath, state.options) + + +def write_cache( + modules: ModuleIRs, + result: BuildResult, + group_map: dict[str, str | None], + ctext: dict[str | None, list[tuple[str, str]]], +) -> None: + """Write out the cache information for modules. + + Each module has the following cache information written (which is + in addition to the cache information written by mypy itself): + * A serialized version of its mypyc IR, minus the bodies of + functions. This allows code that depends on it to use + these serialized data structures when compiling against it + instead of needing to recompile it. (Compiling against a + module requires access to both its mypy and mypyc data + structures.) + * The hash of the mypy metadata cache file for the module. + This is used to ensure that the mypyc cache and the mypy + cache are in sync and refer to the same version of the code. + This is particularly important if mypyc crashes/errors/is + stopped after mypy has written its cache but before mypyc has. + * The hashes of all the source file outputs for the group + the module is in. This is so that the module will be + recompiled if the source outputs are missing. + """ + + hashes = {} + for name, files in ctext.items(): + hashes[name] = {file: compute_hash(data) for file, data in files} + + # Write out cache data + for id, module in modules.items(): + st = result.graph[id] + + meta_path, _, _ = get_cache_names(id, st.xpath, result.manager.options) + # If the metadata isn't there, skip writing the cache. + try: + meta_data = result.manager.metastore.read(meta_path) + except OSError: + continue + + newpath = get_state_ir_cache_name(st) + ir_data = { + "ir": module.serialize(), + "meta_hash": hash_digest(meta_data), + "src_hashes": hashes[group_map[id]], + } + + result.manager.metastore.write(newpath, json_dumps(ir_data)) + + result.manager.metastore.commit() + + +def load_scc_from_cache( + scc: list[MypyFile], result: BuildResult, mapper: Mapper, ctx: DeserMaps +) -> ModuleIRs: + """Load IR for an SCC of modules from the cache. + + Arguments and return are as compile_scc_to_ir. + """ + cache_data = { + k.fullname: json.loads( + result.manager.metastore.read(get_state_ir_cache_name(result.graph[k.fullname])) + )["ir"] + for k in scc + } + modules = deserialize_modules(cache_data, ctx) + load_type_map(mapper, scc, ctx) + return modules + + +def collect_source_dependencies(modules: dict[str, ModuleIR]) -> set[SourceDep]: + """Collect all SourceDep dependencies from all modules.""" + source_deps: set[SourceDep] = set() + for module in modules.values(): + for dep in module.dependencies: + if isinstance(dep, SourceDep): + source_deps.add(dep) + return source_deps + + +def compile_modules_to_c( + result: BuildResult, compiler_options: CompilerOptions, errors: Errors, groups: Groups +) -> tuple[ModuleIRs, list[FileContents], Mapper]: + """Compile Python module(s) to the source of Python C extension modules. + + This generates the source code for the "shared library" module + for each group. The shim modules are generated in mypyc.build. + Each shared library module provides, for each module in its group, + a PyCapsule containing an initialization function. + Additionally, it provides a capsule containing an export table of + pointers to all the group's functions and static variables. + + Arguments: + result: The BuildResult from the mypy front-end + compiler_options: The compilation options + errors: Where to report any errors encountered + groups: The groups that we are compiling. See documentation of Groups type above. + + Returns the IR of the modules and a list containing the generated files for each group. + """ + # Construct a map from modules to what group they belong to + group_map = {source.module: lib_name for group, lib_name in groups for source in group} + mapper = Mapper(group_map) + + # Sometimes when we call back into mypy, there might be errors. + # We don't want to crash when that happens. + result.manager.errors.set_file( + "", module=None, scope=None, options=result.manager.options + ) + + modules = compile_modules_to_ir(result, mapper, compiler_options, errors) + if errors.num_errors > 0: + return {}, [], Mapper({}) + + ctext = compile_ir_to_c(groups, modules, result, mapper, compiler_options) + write_cache(modules, result, group_map, ctext) + + return modules, [ctext[name] for _, name in groups], mapper + + +def generate_function_declaration(fn: FuncIR, emitter: Emitter) -> None: + emitter.context.declarations[emitter.native_function_name(fn.decl)] = HeaderDeclaration( + f"{native_function_header(fn.decl, emitter)};", needs_export=True + ) + if fn.name != TOP_LEVEL_NAME and not fn.internal: + if is_fastcall_supported(fn, emitter.capi_version): + emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration( + f"{wrapper_function_header(fn, emitter.names)};" + ) + else: + emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration( + f"{legacy_wrapper_function_header(fn, emitter.names)};" + ) + + +def pointerize(decl: str, name: str) -> str: + """Given a C decl and its name, modify it to be a declaration to a pointer.""" + # This doesn't work in general but does work for all our types... + if "(" in decl: + # Function pointer. Stick an * in front of the name and wrap it in parens. + return decl.replace(name, f"(*{name})") + else: + # Non-function pointer. Just stick an * in front of the name. + return decl.replace(name, f"*{name}") + + +def group_dir(group_name: str) -> str: + """Given a group name, return the relative directory path for it.""" + return os.sep.join(group_name.split(".")[:-1]) + + +class GroupGenerator: + def __init__( + self, + modules: dict[str, ModuleIR], + source_paths: dict[str, str], + group_name: str | None, + group_map: dict[str, str | None], + names: NameGenerator, + compiler_options: CompilerOptions, + ) -> None: + """Generator for C source for a compilation group. + + The code for a compilation group contains an internal and an + external .h file, and then one .c if not in multi_file mode or + one .c file per module if in multi_file mode. + + Arguments: + modules: (name, ir) pairs for each module in the group + source_paths: Map from module names to source file paths + group_name: The name of the group (or None if this is single-module compilation) + group_map: A map of modules to their group names + names: The name generator for the compilation + compiler_options: Mypyc specific options, including multi_file mode + """ + self.modules = modules + self.source_paths = source_paths + self.context = EmitterContext( + names, compiler_options.strict_traceback_checks, group_name, group_map + ) + self.names = names + # Initializations of globals to simple values that we can't + # do statically because the windows loader is bad. + self.simple_inits: list[tuple[str, str]] = [] + self.group_name = group_name + self.use_shared_lib = group_name is not None + self.compiler_options = compiler_options + self.multi_file = compiler_options.multi_file + # Multi-phase init is needed to enable free-threading. In the future we'll + # probably want to enable it always, but we'll wait until it's stable. + self.multi_phase_init = IS_FREE_THREADED + + @property + def group_suffix(self) -> str: + return "_" + exported_name(self.group_name) if self.group_name else "" + + @property + def short_group_suffix(self) -> str: + return "_" + exported_name(self.group_name.split(".")[-1]) if self.group_name else "" + + def generate_c_for_modules(self) -> list[tuple[str, str]]: + file_contents = [] + multi_file = self.use_shared_lib and self.multi_file + + # Collect all literal refs in IR. + for module in self.modules.values(): + for fn in module.functions: + collect_literals(fn, self.context.literals) + + base_emitter = Emitter(self.context) + # Optionally just include the runtime library c files to + # reduce the number of compiler invocations needed + if self.compiler_options.include_runtime_files: + for name in RUNTIME_C_FILES: + base_emitter.emit_line(f'#include "{name}"') + # Include conditional source files + source_deps = collect_source_dependencies(self.modules) + for source_dep in sorted(source_deps, key=lambda d: d.path): + base_emitter.emit_line(f'#include "{source_dep.path}"') + base_emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"') + base_emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"') + emitter = base_emitter + + self.generate_literal_tables() + + for module_name, module in self.modules.items(): + if multi_file: + emitter = Emitter(self.context, filepath=self.source_paths[module_name]) + emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"') + emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"') + + self.declare_module(module_name, emitter) + self.declare_internal_globals(module_name, emitter) + self.declare_imports(module.imports, emitter) + + for cl in module.classes: + if cl.is_ext_class: + generate_class(cl, module_name, emitter) + + # Generate Python extension module definitions and module initialization functions. + self.generate_module_def(emitter, module_name, module) + + for fn in module.functions: + emitter.emit_line() + generate_native_function(fn, emitter, self.source_paths[module_name], module_name) + if fn.name != TOP_LEVEL_NAME and not fn.internal: + emitter.emit_line() + if is_fastcall_supported(fn, emitter.capi_version): + generate_wrapper_function( + fn, emitter, self.source_paths[module_name], module_name + ) + else: + generate_legacy_wrapper_function( + fn, emitter, self.source_paths[module_name], module_name + ) + if multi_file: + name = f"__native_{exported_name(module_name)}.c" + file_contents.append((name, "".join(emitter.fragments))) + + # The external header file contains type declarations while + # the internal contains declarations of functions and objects + # (which are shared between shared libraries via dynamic + # exports tables and not accessed directly.) + ext_declarations = Emitter(self.context) + ext_declarations.emit_line(f"#ifndef MYPYC_NATIVE{self.group_suffix}_H") + ext_declarations.emit_line(f"#define MYPYC_NATIVE{self.group_suffix}_H") + ext_declarations.emit_line("#include ") + ext_declarations.emit_line("#include ") + if self.compiler_options.depends_on_librt_internal: + ext_declarations.emit_line("#include ") + if any(LIBRT_BASE64 in mod.dependencies for mod in self.modules.values()): + ext_declarations.emit_line("#include ") + if any(LIBRT_STRINGS in mod.dependencies for mod in self.modules.values()): + ext_declarations.emit_line("#include ") + if any(LIBRT_TIME in mod.dependencies for mod in self.modules.values()): + ext_declarations.emit_line("#include