Debian Codegraph @

mypyc/irbuild/main.py

raw
1 """Transform a mypy AST to the IR form (Intermediate Representation).
2
3 For example, consider a function like this:
4
5 def f(x: int) -> int:
6 return x * 2 + 1
7
8 It would be translated to something that conceptually looks like this:
9
10 r0 = 2
11 r1 = 1
12 r2 = x * r0 :: int
13 r3 = r2 + r1 :: int
14 return r3
15
16 This module deals with the module-level IR transformation logic and
17 putting it all together. The actual IR is implemented in mypyc.ir.
18
19 For the core of the IR transform implementation, look at build_ir()
20 below, mypyc.irbuild.builder, and mypyc.irbuild.visitor.
21 """
22
23 from __future__ import annotations
24
25 from collections.abc import Callable
26 from typing import Any, TypeVar, cast
27
28 from mypy.build import Graph
29 from mypy.nodes import ClassDef, Expression, FuncDef, MypyFile
30 from mypy.state import state
31 from mypy.types import Type
32 from mypyc.analysis.attrdefined import analyze_always_defined_attrs
33 from mypyc.common import TOP_LEVEL_NAME
34 from mypyc.errors import Errors
35 from mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature
36 from mypyc.ir.module_ir import ModuleIR, ModuleIRs
37 from mypyc.ir.rtypes import none_rprimitive
38 from mypyc.irbuild.builder import IRBuilder
39 from mypyc.irbuild.mapper import Mapper
40 from mypyc.irbuild.prebuildvisitor import PreBuildVisitor
41 from mypyc.irbuild.prepare import (
42 adjust_generator_classes_of_methods,
43 build_type_map,
44 create_generator_class_for_func,
45 find_singledispatch_register_impls,
46 )
47 from mypyc.irbuild.visitor import IRBuilderVisitor
48 from mypyc.irbuild.vtable import compute_vtable
49 from mypyc.options import CompilerOptions
50
51 # The stubs for callable contextmanagers are busted so cast it to the
52 # right type...
53 F = TypeVar("F", bound=Callable[..., Any])
54 strict_optional_dec = cast(Callable[[F], F], state.strict_optional_set(True))
55
56
57 @strict_optional_dec # Turn on strict optional for any type manipulations we do
58 def build_ir(
59 modules: list[MypyFile],
60 graph: Graph,
61 types: dict[Expression, Type],
62 mapper: Mapper,
63 options: CompilerOptions,
64 errors: Errors,
65 ) -> ModuleIRs:
66 """Build basic IR for a set of modules that have been type-checked by mypy.
67
68 The returned IR is not complete and requires additional
69 transformations, such as the insertion of refcount handling.
70 """
71
72 build_type_map(mapper, modules, graph, types, options, errors)
73 adjust_generator_classes_of_methods(mapper)
74 singledispatch_info = find_singledispatch_register_impls(modules, errors)
75
76 result: ModuleIRs = {}
77 if errors.num_errors > 0:
78 return result
79
80 # Generate IR for all modules.
81 class_irs = []
82
83 for module in modules:
84 # First pass to determine free symbols.
85 pbv = PreBuildVisitor(errors, module, singledispatch_info.decorators_to_remove, types)
86 module.accept(pbv)
87
88 # Declare generator classes for nested async functions and generators.
89 for fdef in pbv.nested_funcs:
90 if isinstance(fdef, FuncDef):
91 # Make generator class name sufficiently unique.
92 suffix = f"___{fdef.line}"
93 if fdef.is_coroutine or fdef.is_generator:
94 create_generator_class_for_func(
95 module.fullname, None, fdef, mapper, name_suffix=suffix
96 )
97
98 # Construct and configure builder objects (cyclic runtime dependency).
99 visitor = IRBuilderVisitor()
100 builder = IRBuilder(
101 module.fullname,
102 types,
103 graph,
104 errors,
105 mapper,
106 pbv,
107 visitor,
108 options,
109 singledispatch_info.singledispatch_impls,
110 )
111 visitor.builder = builder
112
113 # Second pass does the bulk of the work.
114 transform_mypy_file(builder, module)
115 module_ir = ModuleIR(
116 module.fullname,
117 list(builder.imports),
118 builder.functions,
119 builder.classes,
120 builder.final_names,
121 builder.type_var_names,
122 )
123 result[module.fullname] = module_ir
124 class_irs.extend(builder.classes)
125
126 analyze_always_defined_attrs(class_irs)
127
128 # Compute vtables.
129 for cir in class_irs:
130 if cir.is_ext_class:
131 compute_vtable(cir)
132
133 return result
134
135
136 def transform_mypy_file(builder: IRBuilder, mypyfile: MypyFile) -> None:
137 """Generate IR for a single module."""
138
139 if mypyfile.fullname in ("typing", "abc"):
140 # These module are special; their contents are currently all
141 # built-in primitives.
142 return
143
144 builder.set_module(mypyfile.fullname, mypyfile.path)
145
146 classes = [node for node in mypyfile.defs if isinstance(node, ClassDef)]
147
148 # Collect all classes.
149 for cls in classes:
150 ir = builder.mapper.type_to_ir[cls.info]
151 builder.classes.append(ir)
152
153 builder.enter("<module>")
154
155 # Make sure we have a builtins import
156 builder.gen_import("builtins", 1)
157
158 # Generate ops.
159 for node in mypyfile.defs:
160 builder.accept(node)
161
162 builder.maybe_add_implicit_return()
163
164 # Generate special function representing module top level.
165 args, _, blocks, ret_type, _ = builder.leave()
166 sig = FuncSignature([], none_rprimitive)
167 func_ir = FuncIR(
168 FuncDecl(TOP_LEVEL_NAME, None, builder.module_name, sig),
169 args,
170 blocks,
171 traceback_name="<module>",
172 )
173 builder.functions.append(func_ir)