Debian Codegraph @

mypyc/codegen/emitmodule.py

raw
1 """Generate C code for a Python C extension module from Python source code."""
2
3 # FIXME: Basically nothing in this file operates on the level of a
4 # single module and it should be renamed.
5
6 from __future__ import annotations
7
8 import json
9 import os
10 import sys
11 from collections.abc import Iterable
12 from typing import TypeVar
13
14 from mypy.build import (
15 BuildResult,
16 BuildSource,
17 State,
18 build,
19 compute_hash,
20 create_metastore,
21 get_cache_names,
22 sorted_components,
23 )
24 from mypy.errors import CompileError
25 from mypy.fscache import FileSystemCache
26 from mypy.nodes import MypyFile
27 from mypy.options import Options
28 from mypy.plugin import Plugin, ReportConfigContext
29 from mypy.util import hash_digest, json_dumps
30 from mypyc.analysis.capsule_deps import find_class_dependencies, find_implicit_op_dependencies
31 from mypyc.codegen.cstring import c_string_initializer
32 from mypyc.codegen.emit import (
33 Emitter,
34 EmitterContext,
35 HeaderDeclaration,
36 c_array_initializer,
37 native_function_doc_initializer,
38 )
39 from mypyc.codegen.emitclass import generate_class, generate_class_reuse, generate_class_type_decl
40 from mypyc.codegen.emitfunc import generate_native_function, native_function_header
41 from mypyc.codegen.emitwrapper import (
42 generate_legacy_wrapper_function,
43 generate_wrapper_function,
44 legacy_wrapper_function_header,
45 wrapper_function_header,
46 )
47 from mypyc.codegen.literals import Literals
48 from mypyc.common import (
49 EXT_SUFFIX,
50 IS_FREE_THREADED,
51 MODULE_PREFIX,
52 PREFIX,
53 RUNTIME_C_FILES,
54 TOP_LEVEL_NAME,
55 TYPE_VAR_PREFIX,
56 shared_lib_name,
57 short_id_from_name,
58 )
59 from mypyc.crash import catch_errors
60 from mypyc.errors import Errors
61 from mypyc.ir.deps import (
62 LIBRT_BASE64,
63 LIBRT_RANDOM,
64 LIBRT_STRINGS,
65 LIBRT_TIME,
66 LIBRT_VECS,
67 Capsule,
68 HeaderDep,
69 SourceDep,
70 )
71 from mypyc.ir.func_ir import FuncIR
72 from mypyc.ir.module_ir import ModuleIR, ModuleIRs, deserialize_modules
73 from mypyc.ir.ops import DeserMaps, LoadLiteral
74 from mypyc.ir.rtypes import RType
75 from mypyc.irbuild.main import build_ir
76 from mypyc.irbuild.mapper import Mapper
77 from mypyc.irbuild.prepare import load_type_map
78 from mypyc.namegen import NameGenerator, exported_name
79 from mypyc.options import CompilerOptions
80 from mypyc.transform.copy_propagation import do_copy_propagation
81 from mypyc.transform.exceptions import insert_exception_handling
82 from mypyc.transform.flag_elimination import do_flag_elimination
83 from mypyc.transform.log_trace import insert_event_trace_logging
84 from mypyc.transform.lower import lower_ir
85 from mypyc.transform.refcount import insert_ref_count_opcodes
86 from mypyc.transform.spill import insert_spills
87 from mypyc.transform.uninit import insert_uninit_checks
88
89 # All the modules being compiled are divided into "groups". A group
90 # is a set of modules that are placed into the same shared library.
91 # Two common configurations are that every module is placed in a group
92 # by itself (fully separate compilation) and that every module is
93 # placed in the same group (fully whole-program compilation), but we
94 # support finer-grained control of the group as well.
95 #
96 # In fully whole-program compilation, we will generate N+1 extension
97 # modules: one shim per module and one shared library containing all
98 # the actual code.
99 # In fully separate compilation, we (unfortunately) will generate 2*N
100 # extension modules: one shim per module and also one library containing
101 # each module's actual code. (This might be fixable in the future,
102 # but allows a clean separation between setup of the export tables
103 # (see generate_export_table) and running module top levels.)
104 #
105 # A group is represented as a list of BuildSources containing all of
106 # its modules along with the name of the group. (Which can be None
107 # only if we are compiling only a single group with a single file in it
108 # and not using shared libraries).
109 Group = tuple[list[BuildSource], str | None]
110 Groups = list[Group]
111
112 # A list of (file name, file contents) pairs.
113 FileContents = list[tuple[str, str]]
114
115
116 class MarkedDeclaration:
117 """Add a mark, useful for topological sort."""
118
119 def __init__(self, declaration: HeaderDeclaration, mark: bool) -> None:
120 self.declaration = declaration
121 self.mark = False
122
123
124 class MypycPlugin(Plugin):
125 """Plugin for making mypyc interoperate properly with mypy incremental mode.
126
127 Basically the point of this plugin is to force mypy to recheck things
128 based on the demands of mypyc in a couple situations:
129 * Any modules in the same group must be compiled together, so we
130 tell mypy that modules depend on all their groupmates.
131 * If the IR metadata is missing or stale or any of the generated
132 C source files associated missing or stale, then we need to
133 recompile the module so we mark it as stale.
134 """
135
136 def __init__(
137 self, options: Options, compiler_options: CompilerOptions, groups: Groups
138 ) -> None:
139 super().__init__(options)
140 self.group_map: dict[str, tuple[str | None, list[str]]] = {}
141 for sources, name in groups:
142 modules = sorted(source.module for source in sources)
143 for id in modules:
144 self.group_map[id] = (name, modules)
145
146 self.compiler_options = compiler_options
147 self.metastore = create_metastore(options, parallel_worker=False)
148
149 def report_config_data(self, ctx: ReportConfigContext) -> tuple[str | None, list[str]] | None:
150 # The config data we report is the group map entry for the module.
151 # If the data is being used to check validity, we do additional checks
152 # that the IR cache exists and matches the metadata cache and all
153 # output source files exist and are up to date.
154
155 id, path, is_check = ctx.id, ctx.path, ctx.is_check
156
157 if id not in self.group_map:
158 return None
159
160 # If we aren't doing validity checks, just return the cache data
161 if not is_check:
162 return self.group_map[id]
163
164 # Load the metadata and IR cache
165 meta_path, _, _ = get_cache_names(id, path, self.options)
166 ir_path = get_ir_cache_name(id, path, self.options)
167 try:
168 meta_json = self.metastore.read(meta_path)
169 ir_json = self.metastore.read(ir_path)
170 except FileNotFoundError:
171 # This could happen if mypyc failed after mypy succeeded
172 # in the previous run or if some cache files got
173 # deleted. No big deal, just fail to load the cache.
174 return None
175
176 ir_data = json.loads(ir_json)
177
178 # Check that the IR cache matches the metadata cache
179 if hash_digest(meta_json) != ir_data["meta_hash"]:
180 return None
181
182 # Check that all the source files are present and as
183 # expected. The main situation where this would come up is the
184 # user deleting the build directory without deleting
185 # .mypy_cache, which we should handle gracefully.
186 for path, hash in ir_data["src_hashes"].items():
187 try:
188 with open(os.path.join(self.compiler_options.target_dir, path), "rb") as f:
189 contents = f.read()
190 except FileNotFoundError:
191 return None
192 real_hash = hash_digest(contents)
193 if hash != real_hash:
194 return None
195
196 return self.group_map[id]
197
198 def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]:
199 # Report dependency on modules in the module's group
200 return [(10, id, -1) for id in self.group_map.get(file.fullname, (None, []))[1]]
201
202
203 def parse_and_typecheck(
204 sources: list[BuildSource],
205 options: Options,
206 compiler_options: CompilerOptions,
207 groups: Groups,
208 fscache: FileSystemCache | None = None,
209 alt_lib_path: str | None = None,
210 ) -> BuildResult:
211 assert options.strict_optional, "strict_optional must be turned on"
212 mypyc_plugin = MypycPlugin(options, compiler_options, groups)
213 result = build(
214 sources=sources,
215 options=options,
216 alt_lib_path=alt_lib_path,
217 fscache=fscache,
218 extra_plugins=[mypyc_plugin],
219 )
220 mypyc_plugin.metastore.close()
221 if result.errors:
222 raise CompileError(result.errors)
223 return result
224
225
226 def compile_scc_to_ir(
227 scc: list[MypyFile],
228 result: BuildResult,
229 mapper: Mapper,
230 compiler_options: CompilerOptions,
231 errors: Errors,
232 ) -> ModuleIRs:
233 """Compile an SCC into ModuleIRs.
234
235 Any modules that this SCC depends on must have either been compiled,
236 type checked, or loaded from a cache into mapper.
237
238 Arguments:
239 scc: The list of MypyFiles to compile
240 result: The BuildResult from the mypy front-end
241 mapper: The Mapper object mapping mypy ASTs to class and func IRs
242 compiler_options: The compilation options
243 errors: Where to report any errors encountered
244
245 Returns the IR of the modules.
246 """
247
248 if compiler_options.verbose:
249 print("Compiling {}".format(", ".join(x.name for x in scc)))
250
251 # Generate basic IR, with missing exception and refcount handling.
252 modules = build_ir(scc, result.graph, result.types, mapper, compiler_options, errors)
253 if errors.num_errors > 0:
254 return modules
255
256 env_user_functions = {}
257 for module in modules.values():
258 for cls in module.classes:
259 if cls.env_user_function:
260 env_user_functions[cls.env_user_function] = cls
261
262 for module in modules.values():
263 module_path = result.graph[module.fullname].xpath
264 for fn in module.functions:
265 with catch_errors(module_path, fn.line):
266 # Insert checks for uninitialized values.
267 insert_uninit_checks(fn, compiler_options.strict_traceback_checks)
268 # Insert exception handling.
269 insert_exception_handling(fn, compiler_options.strict_traceback_checks)
270 # Insert reference count handling.
271 insert_ref_count_opcodes(fn)
272
273 if fn in env_user_functions:
274 insert_spills(fn, env_user_functions[fn])
275
276 if compiler_options.log_trace:
277 insert_event_trace_logging(fn, compiler_options)
278
279 # Switch to lower abstraction level IR.
280 lower_ir(fn, compiler_options)
281 # Calculate implicit module dependencies (needed for librt)
282 deps = find_implicit_op_dependencies(fn)
283 if deps is not None:
284 module.dependencies.update(deps)
285 # Perform optimizations.
286 do_copy_propagation(fn, compiler_options)
287 do_flag_elimination(fn, compiler_options)
288
289 # Calculate implicit dependencies from class attribute types
290 for cl in module.classes:
291 deps = find_class_dependencies(cl)
292 if deps is not None:
293 module.dependencies.update(deps)
294
295 return modules
296
297
298 def compile_modules_to_ir(
299 result: BuildResult, mapper: Mapper, compiler_options: CompilerOptions, errors: Errors
300 ) -> ModuleIRs:
301 """Compile a collection of modules into ModuleIRs.
302
303 The modules to compile are specified as part of mapper's group_map.
304
305 Returns the IR of the modules.
306 """
307 deser_ctx = DeserMaps({}, {})
308 modules = {}
309
310 # Process the graph by SCC in topological order, like we do in mypy.build
311 for scc in sorted_components(result.graph):
312 scc_states = [result.graph[id] for id in sorted(scc.mod_ids)]
313 trees = [st.tree for st in scc_states if st.id in mapper.group_map and st.tree]
314
315 if not trees:
316 continue
317
318 fresh = all(id not in result.manager.rechecked_modules for id in scc.mod_ids)
319 if fresh:
320 load_scc_from_cache(trees, result, mapper, deser_ctx)
321 else:
322 scc_ir = compile_scc_to_ir(trees, result, mapper, compiler_options, errors)
323 modules.update(scc_ir)
324 # A later SCC loaded from cache may reference classes/functions
325 # defined in this freshly-built SCC; populate deser_ctx so the
326 # cached IR deserializer can resolve those cross-SCC references.
327 for module_ir in scc_ir.values():
328 for cl in module_ir.classes:
329 deser_ctx.classes.setdefault(cl.fullname, cl)
330 for fn in module_ir.functions:
331 deser_ctx.functions.setdefault(fn.decl.id, fn)
332
333 return modules
334
335
336 def compile_ir_to_c(
337 groups: Groups,
338 modules: ModuleIRs,
339 result: BuildResult,
340 mapper: Mapper,
341 compiler_options: CompilerOptions,
342 ) -> dict[str | None, list[tuple[str, str]]]:
343 """Compile a collection of ModuleIRs to C source text.
344
345 Returns a dictionary mapping group names to a list of (file name,
346 file text) pairs.
347 """
348 source_paths = {
349 source.module: result.graph[source.module].xpath
350 for sources, _ in groups
351 for source in sources
352 }
353
354 names = NameGenerator(
355 [[source.module for source in sources] for sources, _ in groups],
356 separate=compiler_options.separate,
357 )
358
359 # Generate C code for each compilation group. Each group will be
360 # compiled into a separate extension module.
361 ctext: dict[str | None, list[tuple[str, str]]] = {}
362 for group_sources, group_name in groups:
363 group_modules = {
364 source.module: modules[source.module]
365 for source in group_sources
366 if source.module in modules
367 }
368 if not group_modules:
369 # Fully-cached group (e.g. pip's second setup.py invoke for
370 # the wheel phase): no fresh IR was produced. Reuse the file
371 # list recorded in any module's IR cache so the linker still
372 # sees the previous run's outputs; empty content is a "do
373 # not rewrite" sentinel for mypyc_build.
374 ctext[group_name] = _load_cached_group_files(group_sources, result)
375 continue
376 generator = GroupGenerator(
377 group_modules, source_paths, group_name, mapper.group_map, names, compiler_options
378 )
379 ctext[group_name] = generator.generate_c_for_modules()
380
381 return ctext
382
383
384 def _load_cached_group_files(
385 group_sources: list[BuildSource], result: BuildResult
386 ) -> list[tuple[str, str]]:
387 """Read the .c/.h paths recorded for this group on the previous run.
388
389 All modules in a group share the same src_hashes map, so the first
390 readable IR cache is sufficient. Returns paths paired with empty
391 content so callers can distinguish "reuse on disk" from "newly
392 generated".
393 """
394 for source in group_sources:
395 state = result.graph.get(source.module)
396 if state is None:
397 continue
398 try:
399 ir_json = result.manager.metastore.read(get_state_ir_cache_name(state))
400 except (FileNotFoundError, OSError):
401 continue
402 try:
403 ir_data = json.loads(ir_json)
404 except json.JSONDecodeError:
405 continue
406 return [(path, "") for path in ir_data.get("src_hashes", {})]
407 return []
408
409
410 def get_ir_cache_name(id: str, path: str, options: Options) -> str:
411 meta_path, _, _ = get_cache_names(id, path, options)
412 # Mypyc uses JSON cache even with --fixed-format-cache (for now).
413 return meta_path.replace(".meta.json", ".ir.json").replace(".meta.ff", ".ir.json")
414
415
416 def get_state_ir_cache_name(state: State) -> str:
417 return get_ir_cache_name(state.id, state.xpath, state.options)
418
419
420 def write_cache(
421 modules: ModuleIRs,
422 result: BuildResult,
423 group_map: dict[str, str | None],
424 ctext: dict[str | None, list[tuple[str, str]]],
425 ) -> None:
426 """Write out the cache information for modules.
427
428 Each module has the following cache information written (which is
429 in addition to the cache information written by mypy itself):
430 * A serialized version of its mypyc IR, minus the bodies of
431 functions. This allows code that depends on it to use
432 these serialized data structures when compiling against it
433 instead of needing to recompile it. (Compiling against a
434 module requires access to both its mypy and mypyc data
435 structures.)
436 * The hash of the mypy metadata cache file for the module.
437 This is used to ensure that the mypyc cache and the mypy
438 cache are in sync and refer to the same version of the code.
439 This is particularly important if mypyc crashes/errors/is
440 stopped after mypy has written its cache but before mypyc has.
441 * The hashes of all the source file outputs for the group
442 the module is in. This is so that the module will be
443 recompiled if the source outputs are missing.
444 """
445
446 hashes = {}
447 for name, files in ctext.items():
448 hashes[name] = {file: compute_hash(data) for file, data in files}
449
450 # Write out cache data
451 for id, module in modules.items():
452 st = result.graph[id]
453
454 meta_path, _, _ = get_cache_names(id, st.xpath, result.manager.options)
455 # If the metadata isn't there, skip writing the cache.
456 try:
457 meta_data = result.manager.metastore.read(meta_path)
458 except OSError:
459 continue
460
461 newpath = get_state_ir_cache_name(st)
462 ir_data = {
463 "ir": module.serialize(),
464 "meta_hash": hash_digest(meta_data),
465 "src_hashes": hashes[group_map[id]],
466 }
467
468 result.manager.metastore.write(newpath, json_dumps(ir_data))
469
470 result.manager.metastore.commit()
471
472
473 def load_scc_from_cache(
474 scc: list[MypyFile], result: BuildResult, mapper: Mapper, ctx: DeserMaps
475 ) -> ModuleIRs:
476 """Load IR for an SCC of modules from the cache.
477
478 Arguments and return are as compile_scc_to_ir.
479 """
480 cache_data = {
481 k.fullname: json.loads(
482 result.manager.metastore.read(get_state_ir_cache_name(result.graph[k.fullname]))
483 )["ir"]
484 for k in scc
485 }
486 modules = deserialize_modules(cache_data, ctx)
487 load_type_map(mapper, scc, ctx)
488 return modules
489
490
491 def collect_source_dependencies(modules: dict[str, ModuleIR]) -> set[SourceDep]:
492 """Collect all SourceDep dependencies from all modules."""
493 source_deps: set[SourceDep] = set()
494 for module in modules.values():
495 for dep in module.dependencies:
496 if isinstance(dep, SourceDep):
497 if dep.internal:
498 source_deps.add(dep)
499 elif isinstance(dep, Capsule):
500 source_deps.add(dep.internal_dep())
501 return source_deps
502
503
504 def collect_header_dependencies(modules: dict[str, ModuleIR], *, internal: bool) -> set[str]:
505 """Collect all header dependencies from all modules."""
506 header_deps: set[str] = set()
507 for module in modules.values():
508 for dep in module.dependencies:
509 if isinstance(dep, (SourceDep, HeaderDep)):
510 if dep.internal == internal:
511 header_deps.add(dep.get_header())
512 else:
513 capsule_dep = dep.internal_dep() if internal else dep.external_dep()
514 header_deps.add(capsule_dep.get_header())
515 return header_deps
516
517
518 def compile_modules_to_c(
519 result: BuildResult, compiler_options: CompilerOptions, errors: Errors, groups: Groups
520 ) -> tuple[ModuleIRs, list[FileContents], Mapper]:
521 """Compile Python module(s) to the source of Python C extension modules.
522
523 This generates the source code for the "shared library" module
524 for each group. The shim modules are generated in mypyc.build.
525 Each shared library module provides, for each module in its group,
526 a PyCapsule containing an initialization function.
527 Additionally, it provides a capsule containing an export table of
528 pointers to all the group's functions and static variables.
529
530 Arguments:
531 result: The BuildResult from the mypy front-end
532 compiler_options: The compilation options
533 errors: Where to report any errors encountered
534 groups: The groups that we are compiling. See documentation of Groups type above.
535
536 Returns the IR of the modules and a list containing the generated files for each group.
537 """
538 # Construct a map from modules to what group they belong to
539 group_map = {source.module: lib_name for group, lib_name in groups for source in group}
540 mapper = Mapper(group_map)
541
542 # Sometimes when we call back into mypy, there might be errors.
543 # We don't want to crash when that happens.
544 result.manager.errors.set_file(
545 "<mypyc>", module=None, scope=None, options=result.manager.options
546 )
547
548 modules = compile_modules_to_ir(result, mapper, compiler_options, errors)
549 if errors.num_errors > 0:
550 return {}, [], Mapper({})
551
552 ctext = compile_ir_to_c(groups, modules, result, mapper, compiler_options)
553 write_cache(modules, result, group_map, ctext)
554
555 return modules, [ctext[name] for _, name in groups], mapper
556
557
558 def generate_function_declaration(fn: FuncIR, emitter: Emitter) -> None:
559 emitter.context.declarations[emitter.native_function_name(fn.decl)] = HeaderDeclaration(
560 f"{native_function_header(fn.decl, emitter)};", needs_export=True
561 )
562 if fn.name != TOP_LEVEL_NAME and not fn.internal:
563 # needs_export=True so Python-wrapper (CPyPy_) symbols are reachable from
564 # other groups via the export table — needed for cross-group inherited
565 # __init__ / __new__ slot dispatch under `separate=True`.
566 if is_fastcall_supported(fn, emitter.capi_version):
567 emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration(
568 f"{wrapper_function_header(fn, emitter.names)};", needs_export=True
569 )
570 else:
571 emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration(
572 f"{legacy_wrapper_function_header(fn, emitter.names)};", needs_export=True
573 )
574
575
576 def pointerize(decl: str, name: str) -> str:
577 """Given a C decl and its name, modify it to be a declaration to a pointer."""
578 # This doesn't work in general but does work for all our types...
579 if "(" in decl:
580 # Function pointer. Stick an * in front of the name and wrap it in parens.
581 return decl.replace(name, f"(*{name})")
582 else:
583 # Non-function pointer. Just stick an * in front of the name.
584 return decl.replace(name, f"*{name}")
585
586
587 def group_dir(group_name: str) -> str:
588 """Given a group name, return the relative directory path for it."""
589 return os.sep.join(group_name.split(".")[:-1])
590
591
592 class GroupGenerator:
593 def __init__(
594 self,
595 modules: dict[str, ModuleIR],
596 source_paths: dict[str, str],
597 group_name: str | None,
598 group_map: dict[str, str | None],
599 names: NameGenerator,
600 compiler_options: CompilerOptions,
601 ) -> None:
602 """Generator for C source for a compilation group.
603
604 The code for a compilation group contains an internal and an
605 external .h file, and then one .c if not in multi_file mode or
606 one .c file per module if in multi_file mode.
607
608 Arguments:
609 modules: (name, ir) pairs for each module in the group
610 source_paths: Map from module names to source file paths
611 group_name: The name of the group (or None if this is single-module compilation)
612 group_map: A map of modules to their group names
613 names: The name generator for the compilation
614 compiler_options: Mypyc specific options, including multi_file mode
615 """
616 self.modules = modules
617 self.source_paths = source_paths
618 self.context = EmitterContext(
619 names, compiler_options.strict_traceback_checks, group_name, group_map
620 )
621 self.names = names
622 # Initializations of globals to simple values that we can't
623 # do statically because the windows loader is bad.
624 self.simple_inits: list[tuple[str, str]] = []
625 self.group_name = group_name
626 self.use_shared_lib = group_name is not None
627 self.compiler_options = compiler_options
628 self.multi_file = compiler_options.multi_file
629 # Multi-phase init is needed to enable free-threading. In the future we'll
630 # probably want to enable it always, but we'll wait until it's stable.
631 self.multi_phase_init = IS_FREE_THREADED
632
633 @property
634 def group_suffix(self) -> str:
635 return "_" + exported_name(self.group_name) if self.group_name else ""
636
637 @property
638 def short_group_suffix(self) -> str:
639 return "_" + exported_name(self.group_name.split(".")[-1]) if self.group_name else ""
640
641 def generate_c_for_modules(self) -> list[tuple[str, str]]:
642 file_contents = []
643 multi_file = self.use_shared_lib and self.multi_file
644
645 # Collect all literal refs in IR.
646 for module in self.modules.values():
647 for fn in module.functions:
648 collect_literals(fn, self.context.literals)
649
650 base_emitter = Emitter(self.context)
651 # Optionally just include the runtime library c files to
652 # reduce the number of compiler invocations needed.
653 # Use <> form (only -I paths) so a shim file with the same
654 # basename as a runtime file can't shadow it. Triggered by
655 # mypyc/lower/int_ops.py vs lib-rt/int_ops.c on mypy self-compile.
656 if self.compiler_options.include_runtime_files:
657 for name in RUNTIME_C_FILES:
658 base_emitter.emit_line(f"#include <{name}>")
659 # Include conditional source files
660 source_deps = collect_source_dependencies(self.modules)
661 for source_dep in sorted(source_deps, key=lambda d: d.path):
662 base_emitter.emit_line(f"#include <{source_dep.path}>")
663 if self.compiler_options.depends_on_librt_internal:
664 base_emitter.emit_line("#include <internal/librt_internal_api.c>")
665 base_emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"')
666 base_emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"')
667 emitter = base_emitter
668
669 self.generate_literal_tables()
670
671 for module_name, module in self.modules.items():
672 if multi_file:
673 emitter = Emitter(self.context, filepath=self.source_paths[module_name])
674 emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"')
675 emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"')
676
677 self.declare_module(module_name, emitter)
678 self.declare_internal_globals(module_name, emitter)
679 self.declare_imports(module.imports, emitter)
680
681 for cl in module.classes:
682 if cl.is_ext_class:
683 generate_class(cl, module_name, emitter)
684
685 # Generate Python extension module definitions and module initialization functions.
686 self.generate_module_def(emitter, module_name, module)
687
688 for fn in module.functions:
689 emitter.emit_line()
690 generate_native_function(fn, emitter, self.source_paths[module_name], module_name)
691 if fn.name != TOP_LEVEL_NAME and not fn.internal:
692 emitter.emit_line()
693 if is_fastcall_supported(fn, emitter.capi_version):
694 generate_wrapper_function(
695 fn, emitter, self.source_paths[module_name], module_name
696 )
697 else:
698 generate_legacy_wrapper_function(
699 fn, emitter, self.source_paths[module_name], module_name
700 )
701 if multi_file:
702 name = f"__native_{exported_name(module_name)}.c"
703 file_contents.append((name, "".join(emitter.fragments)))
704
705 # The external header file contains type declarations while
706 # the internal contains declarations of functions and objects
707 # (which are shared between shared libraries via dynamic
708 # exports tables and not accessed directly.)
709 ext_declarations = Emitter(self.context)
710 ext_declarations.emit_line(f"#ifndef MYPYC_NATIVE{self.group_suffix}_H")
711 ext_declarations.emit_line(f"#define MYPYC_NATIVE{self.group_suffix}_H")
712 ext_declarations.emit_line("#include <Python.h>")
713 ext_declarations.emit_line("#include <CPy.h>")
714
715 def emit_dep_headers(decls: Emitter, internal: bool) -> None:
716 suffix = "_api" if internal else ""
717 if self.compiler_options.depends_on_librt_internal:
718 decls.emit_line(f'#include "internal/librt_internal{suffix}.h"')
719 # Include headers for conditional source files
720 header_deps = collect_header_dependencies(self.modules, internal=internal)
721 for header_dep in sorted(header_deps):
722 decls.emit_line(f'#include "{header_dep}"')
723
724 emit_dep_headers(ext_declarations, False)
725
726 declarations = Emitter(self.context)
727 declarations.emit_line(f"#ifndef MYPYC_LIBRT_INTERNAL{self.group_suffix}_H")
728 declarations.emit_line(f"#define MYPYC_LIBRT_INTERNAL{self.group_suffix}_H")
729 declarations.emit_line("#include <Python.h>")
730 declarations.emit_line("#include <CPy.h>")
731
732 if not self.compiler_options.include_runtime_files:
733 emit_dep_headers(declarations, True)
734
735 declarations.emit_line(f'#include "__native{self.short_group_suffix}.h"')
736 declarations.emit_line()
737 declarations.emit_line("int CPyGlobalsInit(void);")
738 declarations.emit_line()
739
740 for module_name, module in self.modules.items():
741 self.declare_finals(module_name, module.final_names, declarations)
742 for cl in module.classes:
743 generate_class_type_decl(cl, emitter, ext_declarations, declarations)
744 if cl.reuse_freed_instance:
745 generate_class_reuse(cl, emitter, ext_declarations, declarations)
746 self.declare_type_vars(module_name, module.type_var_names, declarations)
747 for fn in module.functions:
748 generate_function_declaration(fn, declarations)
749
750 for lib in sorted(self.context.group_deps):
751 elib = exported_name(lib)
752 short_lib = exported_name(lib.split(".")[-1])
753 declarations.emit_lines(
754 "#include <{}>".format(os.path.join(group_dir(lib), f"__native_{short_lib}.h")),
755 f"struct export_table_{elib} exports_{elib};",
756 )
757
758 sorted_decls = self.toposort_declarations()
759
760 emitter = base_emitter
761 self.generate_globals_init(emitter)
762
763 emitter.emit_line()
764
765 for declaration in sorted_decls:
766 decls = ext_declarations if declaration.is_type else declarations
767 if not declaration.is_type:
768 decls.emit_lines(f"extern {declaration.decl[0]}", *declaration.decl[1:])
769 # If there is a definition, emit it. Otherwise, repeat the declaration
770 # (without an extern).
771 if declaration.defn:
772 emitter.emit_lines(*declaration.defn)
773 else:
774 emitter.emit_lines(*declaration.decl)
775 else:
776 decls.emit_lines(*declaration.decl)
777
778 if self.group_name:
779 if self.compiler_options.separate:
780 self.generate_export_table(ext_declarations, emitter)
781
782 self.generate_shared_lib_init(emitter)
783
784 ext_declarations.emit_line("#endif")
785 declarations.emit_line("#endif")
786
787 output_dir = group_dir(self.group_name) if self.group_name else ""
788 return file_contents + [
789 (
790 os.path.join(output_dir, f"__native{self.short_group_suffix}.c"),
791 "".join(emitter.fragments),
792 ),
793 (
794 os.path.join(output_dir, f"__native_internal{self.short_group_suffix}.h"),
795 "".join(declarations.fragments),
796 ),
797 (
798 os.path.join(output_dir, f"__native{self.short_group_suffix}.h"),
799 "".join(ext_declarations.fragments),
800 ),
801 ]
802
803 def generate_literal_tables(self) -> None:
804 """Generate tables containing descriptions of Python literals to construct.
805
806 We will store the constructed literals in a single array that contains
807 literals of all types. This way we can refer to an arbitrary literal by
808 its index.
809 """
810 literals = self.context.literals
811 # During module initialization we store all the constructed objects here
812 self.declare_global("PyObject *[%d]" % literals.num_literals(), "CPyStatics")
813 # Descriptions of str literals
814 init_str = c_string_array_initializer(literals.encoded_str_values())
815 self.declare_global("const char * const []", "CPyLit_Str", initializer=init_str)
816 # Descriptions of bytes literals
817 init_bytes = c_string_array_initializer(literals.encoded_bytes_values())
818 self.declare_global("const char * const []", "CPyLit_Bytes", initializer=init_bytes)
819 # Descriptions of int literals
820 init_int = c_string_array_initializer(literals.encoded_int_values())
821 self.declare_global("const char * const []", "CPyLit_Int", initializer=init_int)
822 # Descriptions of float literals
823 init_floats = c_array_initializer(literals.encoded_float_values())
824 self.declare_global("const double []", "CPyLit_Float", initializer=init_floats)
825 # Descriptions of complex literals
826 init_complex = c_array_initializer(literals.encoded_complex_values())
827 self.declare_global("const double []", "CPyLit_Complex", initializer=init_complex)
828 # Descriptions of tuple literals
829 init_tuple = c_array_initializer(literals.encoded_tuple_values())
830 self.declare_global("const int []", "CPyLit_Tuple", initializer=init_tuple)
831 # Descriptions of frozenset literals
832 init_frozenset = c_array_initializer(literals.encoded_frozenset_values())
833 self.declare_global("const int []", "CPyLit_FrozenSet", initializer=init_frozenset)
834
835 def generate_export_table(self, decl_emitter: Emitter, code_emitter: Emitter) -> None:
836 """Generate the declaration and definition of the group's export struct.
837
838 To avoid needing to deal with deeply platform specific issues
839 involving dynamic library linking (and some possibly
840 insurmountable issues involving cyclic dependencies), compiled
841 code accesses functions and data in other compilation groups
842 via an explicit "export struct".
843
844 Each group declares a struct type that contains a pointer to
845 every function and static variable it exports. It then
846 populates this struct and stores a pointer to it in a capsule
847 stored as an attribute named 'exports' on the group's shared
848 library's python module.
849
850 On load, a group's init function will import all of its
851 dependencies' exports tables using the capsule mechanism and
852 copy the contents into a local copy of the table (to eliminate
853 the need for a pointer indirection when accessing it).
854
855 Then, all calls to functions in another group and accesses to statics
856 from another group are done indirectly via the export table.
857
858 For example, a group containing a module b, where b contains a class B
859 and a function bar, would declare an export table like:
860 struct export_table_b {
861 PyTypeObject **CPyType_B;
862 PyObject *(*CPyDef_B)(CPyTagged cpy_r_x);
863 CPyTagged (*CPyDef_B___foo)(PyObject *cpy_r_self, CPyTagged cpy_r_y);
864 tuple_T2OI (*CPyDef_bar)(PyObject *cpy_r_x);
865 char (*CPyDef___top_level__)(void);
866 };
867 that would be initialized with:
868 static struct export_table_b exports = {
869 &CPyType_B,
870 &CPyDef_B,
871 &CPyDef_B___foo,
872 &CPyDef_bar,
873 &CPyDef___top_level__,
874 };
875 To call `b.foo`, then, a function in another group would do
876 `exports_b.CPyDef_bar(...)`.
877 """
878
879 decls = decl_emitter.context.declarations
880
881 decl_emitter.emit_lines("", f"struct export_table{self.group_suffix} {{")
882 for name, decl in decls.items():
883 if decl.needs_export:
884 decl_emitter.emit_line(pointerize("\n".join(decl.decl), name))
885
886 decl_emitter.emit_line("};")
887
888 code_emitter.emit_lines("", f"static struct export_table{self.group_suffix} exports = {{")
889 for name, decl in decls.items():
890 if decl.needs_export:
891 code_emitter.emit_line(f"&{name},")
892
893 code_emitter.emit_line("};")
894
895 def generate_shared_lib_init(self, emitter: Emitter) -> None:
896 """Generate the init function for a shared library.
897
898 A shared library contains all the actual code for a
899 compilation group.
900
901 The init function is responsible for creating Capsules that
902 wrap pointers to the initialization function of all the real
903 init functions for modules in this shared library as well as
904 the export table containing all the exported functions and
905 values from all the modules.
906
907 These capsules are stored in attributes of the shared library.
908 """
909 assert self.group_name is not None
910
911 emitter.emit_line()
912
913 short_name = shared_lib_name(self.group_name).split(".")[-1]
914
915 emitter.emit_lines(
916 f"static int exec_{short_name}(PyObject *module)",
917 "{",
918 "int res;",
919 "PyObject *capsule;",
920 "PyObject *tmp;",
921 "",
922 )
923
924 if self.compiler_options.separate:
925 emitter.emit_lines(
926 'capsule = PyCapsule_New(&exports, "{}.exports", NULL);'.format(
927 shared_lib_name(self.group_name)
928 ),
929 "if (!capsule) {",
930 "goto fail;",
931 "}",
932 'res = PyObject_SetAttrString(module, "exports", capsule);',
933 "Py_DECREF(capsule);",
934 "if (res < 0) {",
935 "goto fail;",
936 "}",
937 "",
938 # Expose ensure_deps_<short> as a capsule so the shim can call
939 # it before invoking the per-module init.
940 f"extern int ensure_deps_{short_name}(void);",
941 'capsule = PyCapsule_New((void *)ensure_deps_{sh}, "{lib}.ensure_deps", NULL);'.format(
942 sh=short_name, lib=shared_lib_name(self.group_name)
943 ),
944 "if (!capsule) {",
945 "goto fail;",
946 "}",
947 'res = PyObject_SetAttrString(module, "ensure_deps", capsule);',
948 "Py_DECREF(capsule);",
949 "if (res < 0) {",
950 "goto fail;",
951 "}",
952 "",
953 )
954
955 for mod in self.modules:
956 name = exported_name(mod)
957 if self.multi_phase_init:
958 capsule_func_prefix = "CPyExec_"
959 capsule_name_prefix = "exec_"
960 emitter.emit_line(f"extern int CPyExec_{name}(PyObject *);")
961 else:
962 capsule_func_prefix = "CPyInit_"
963 capsule_name_prefix = "init_"
964 emitter.emit_line(f"extern PyObject *CPyInit_{name}(void);")
965 emitter.emit_lines(
966 'capsule = PyCapsule_New((void *){}{}, "{}.{}{}", NULL);'.format(
967 capsule_func_prefix,
968 name,
969 shared_lib_name(self.group_name),
970 capsule_name_prefix,
971 name,
972 ),
973 "if (!capsule) {",
974 "goto fail;",
975 "}",
976 f'res = PyObject_SetAttrString(module, "{capsule_name_prefix}{name}", capsule);',
977 "Py_DECREF(capsule);",
978 "if (res < 0) {",
979 "goto fail;",
980 "}",
981 "",
982 )
983
984 # End of exec_<short_name>: only sets up capsules/module attributes.
985 # Cross-group imports (populating `exports_<dep>` tables) are split
986 # out into ensure_deps_<short_name>() below and run later, from the
987 # shim's PyInit. See generate_shared_lib_init for details.
988 emitter.emit_lines("return 0;", "fail:", "return -1;", "}")
989
990 if self.compiler_options.separate:
991 # ensure_deps_<short>(): populates cross-group exports tables. Run
992 # once, lazily, from the shim's PyInit just before invoking the
993 # per-module init capsule. This defers cross-group imports out of
994 # the shared-lib PyInit so they can't transitively trigger a
995 # sibling package's __init__.py while another package __init__.py
996 # is still mid-flight.
997 emitter.emit_lines(
998 "",
999 f"int ensure_deps_{short_name}(void)",
1000 "{",
1001 "static int done = 0;",
1002 "if (done) return 0;",
1003 )
1004 if self.context.group_deps:
1005 emitter.emit_lines(
1006 "static PyObject *_mypyc_fromlist = NULL;",
1007 "if (!_mypyc_fromlist) {",
1008 '_mypyc_fromlist = Py_BuildValue("(s)", "*");',
1009 "if (!_mypyc_fromlist) return -1;",
1010 "}",
1011 "PyObject *tmp;",
1012 "PyObject *caps;",
1013 )
1014 for group in sorted(self.context.group_deps):
1015 egroup = exported_name(group)
1016 # ImportModuleLevel with fromlist returns the leaf via
1017 # sys.modules (no dotted getattr walk), and fetching the
1018 # `exports` capsule directly off that module bypasses
1019 # PyCapsule_Import (which would redo the attribute walk).
1020 emitter.emit_lines(
1021 'tmp = PyImport_ImportModuleLevel("{}", NULL, NULL, _mypyc_fromlist, 0);'.format(
1022 shared_lib_name(group)
1023 ),
1024 "if (!tmp) return -1;",
1025 'caps = PyObject_GetAttrString(tmp, "exports");',
1026 "Py_DECREF(tmp);",
1027 "if (!caps) return -1;",
1028 "struct export_table_{g} *pexports_{g} = "
1029 '(struct export_table_{g} *)PyCapsule_GetPointer(caps, "{lib}.exports");'.format(
1030 g=egroup, lib=shared_lib_name(group)
1031 ),
1032 "Py_DECREF(caps);",
1033 f"if (!pexports_{egroup}) return -1;",
1034 "memcpy(&exports_{g}, pexports_{g}, sizeof(exports_{g}));".format(g=egroup),
1035 )
1036 emitter.emit_lines("done = 1;", "return 0;", "}")
1037
1038 if self.multi_phase_init:
1039 emitter.emit_lines(
1040 f"static PyModuleDef_Slot slots_{short_name}[] = {{",
1041 f"{{Py_mod_exec, exec_{short_name}}},",
1042 "{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},",
1043 "{Py_mod_gil, Py_MOD_GIL_NOT_USED},",
1044 "{0, NULL},",
1045 "};",
1046 )
1047
1048 size = 0 if self.multi_phase_init else -1
1049 emitter.emit_lines(
1050 f"static PyModuleDef module_def_{short_name} = {{",
1051 "PyModuleDef_HEAD_INIT,",
1052 f'.m_name = "{shared_lib_name(self.group_name)}",',
1053 ".m_doc = NULL,",
1054 f".m_size = {size},",
1055 ".m_methods = NULL,",
1056 )
1057 if self.multi_phase_init:
1058 emitter.emit_line(f".m_slots = slots_{short_name},")
1059 emitter.emit_line("};")
1060
1061 if self.multi_phase_init:
1062 emitter.emit_lines(
1063 f"PyMODINIT_FUNC PyInit_{short_name}(void) {{",
1064 f"return PyModuleDef_Init(&module_def_{short_name});",
1065 "}",
1066 )
1067 else:
1068 emitter.emit_lines(
1069 f"PyMODINIT_FUNC PyInit_{short_name}(void) {{",
1070 "static PyObject *module = NULL;",
1071 "if (module) {",
1072 "Py_INCREF(module);",
1073 "return module;",
1074 "}",
1075 f"module = PyModule_Create(&module_def_{short_name});",
1076 "if (!module) {",
1077 "return NULL;",
1078 "}",
1079 f"if (exec_{short_name}(module) < 0) {{",
1080 "Py_DECREF(module);",
1081 "module = NULL;",
1082 "return NULL;",
1083 "}",
1084 "return module;",
1085 "}",
1086 )
1087
1088 def generate_globals_init(self, emitter: Emitter) -> None:
1089 emitter.emit_lines(
1090 "",
1091 "int CPyGlobalsInit(void)",
1092 "{",
1093 "static int is_initialized = 0;",
1094 "if (is_initialized) return 0;",
1095 "",
1096 )
1097
1098 emitter.emit_line("CPy_Init();")
1099 for symbol, fixup in self.simple_inits:
1100 emitter.emit_line(f"{symbol} = {fixup};")
1101
1102 values = "CPyLit_Str, CPyLit_Bytes, CPyLit_Int, CPyLit_Float, CPyLit_Complex, CPyLit_Tuple, CPyLit_FrozenSet"
1103 emitter.emit_lines(
1104 f"if (CPyStatics_Initialize(CPyStatics, {values}) < 0) {{", "return -1;", "}"
1105 )
1106
1107 emitter.emit_lines("is_initialized = 1;", "return 0;", "}")
1108
1109 def generate_module_def(self, emitter: Emitter, module_name: str, module: ModuleIR) -> None:
1110 """Emit the PyModuleDef struct for a module and the module init function."""
1111 module_prefix = emitter.names.private_name(module_name)
1112 self.emit_module_methods(emitter, module_name, module_prefix, module)
1113 self.emit_module_exec_func(emitter, module_name, module_prefix, module)
1114
1115 # If using multi-phase init and a shared lib, parts of module definition
1116 # will happen in the shim modules, so we skip some steps here.
1117 if not (self.multi_phase_init and self.use_shared_lib):
1118 if self.multi_phase_init:
1119 self.emit_module_def_slots(emitter, module_prefix, module_name)
1120 self.emit_module_def_struct(emitter, module_name, module_prefix)
1121 self.emit_module_init_func(emitter, module_name, module_prefix)
1122 elif self.use_shared_lib:
1123 # Multi-phase init with shared lib: shims handle PyInit_*, but we
1124 # still need CPyInitOnly_* for same-group native imports, and the
1125 # PyModuleDef struct it depends on.
1126 self.emit_module_def_struct(emitter, module_name, module_prefix)
1127 self.emit_init_only_func(emitter, module_name, module_prefix)
1128
1129 def emit_module_def_slots(
1130 self, emitter: Emitter, module_prefix: str, module_name: str
1131 ) -> None:
1132 name = f"{module_prefix}_slots"
1133 exec_name = f"CPyExec_{exported_name(module_name)}"
1134
1135 emitter.emit_line(f"static PyModuleDef_Slot {name}[] = {{")
1136 emitter.emit_line(f"{{Py_mod_exec, {exec_name}}},")
1137 if sys.version_info >= (3, 12):
1138 # Multiple interpreter support requires not using any C global state,
1139 # which we don't support yet.
1140 emitter.emit_line(
1141 "{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},"
1142 )
1143 if sys.version_info >= (3, 13):
1144 # Declare support for free-threading to enable experimentation,
1145 # even if we don't properly support it.
1146 emitter.emit_line("{Py_mod_gil, Py_MOD_GIL_NOT_USED},")
1147 emitter.emit_line("{0, NULL},")
1148 emitter.emit_line("};")
1149
1150 def emit_module_methods(
1151 self, emitter: Emitter, module_name: str, module_prefix: str, module: ModuleIR
1152 ) -> None:
1153 """Emit module methods (the static PyMethodDef table)."""
1154 emitter.emit_line(f"static PyMethodDef {module_prefix}module_methods[] = {{")
1155 for fn in module.functions:
1156 if fn.class_name is not None or fn.name == TOP_LEVEL_NAME:
1157 continue
1158 # Coroutines are added to the module dict when the module is initialized.
1159 if fn.decl.is_coroutine:
1160 continue
1161 name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)
1162 if is_fastcall_supported(fn, emitter.capi_version):
1163 flag = "METH_FASTCALL"
1164 else:
1165 flag = "METH_VARARGS"
1166 doc = native_function_doc_initializer(fn)
1167 emitter.emit_line(
1168 (
1169 '{{"{name}", (PyCFunction){prefix}{cname}, {flag} | METH_KEYWORDS, '
1170 "PyDoc_STR({doc}) /* docstring */}},"
1171 ).format(
1172 name=name, cname=fn.cname(emitter.names), prefix=PREFIX, flag=flag, doc=doc
1173 )
1174 )
1175 emitter.emit_line("{NULL, NULL, 0, NULL}")
1176 emitter.emit_line("};")
1177 emitter.emit_line()
1178
1179 def emit_module_def_struct(
1180 self, emitter: Emitter, module_name: str, module_prefix: str
1181 ) -> None:
1182 """Emit the static module definition struct (PyModuleDef)."""
1183 emitter.emit_lines(
1184 f"static struct PyModuleDef {module_prefix}module = {{",
1185 "PyModuleDef_HEAD_INIT,",
1186 f'"{module_name}",',
1187 "NULL, /* docstring */",
1188 "0, /* size of per-interpreter state of the module */",
1189 )
1190 if self.multi_phase_init:
1191 # Methods are added later via PyModule_AddFunctions in CPyExec_*.
1192 emitter.emit_line("NULL, /* m_methods */")
1193 else:
1194 emitter.emit_line(f"{module_prefix}module_methods,")
1195 if self.multi_phase_init and not self.use_shared_lib:
1196 slots_name = f"{module_prefix}_slots"
1197 emitter.emit_line(f"{slots_name}, /* m_slots */")
1198 else:
1199 emitter.emit_line("NULL,")
1200 emitter.emit_line("};")
1201 emitter.emit_line()
1202
1203 def emit_coroutine_wrappers(self, emitter: Emitter, module: ModuleIR, globals: str) -> None:
1204 """Emit insertion of coroutines into the module dict when the module is initialized.
1205 Coroutines are wrapped in CPyFunction objects to enable introspection by functions like
1206 inspect.iscoroutinefunction(fn).
1207 """
1208 for fn in module.functions:
1209 if fn.class_name is not None or fn.name == TOP_LEVEL_NAME:
1210 continue
1211 if not fn.decl.is_coroutine:
1212 continue
1213
1214 filepath = self.source_paths[module.fullname]
1215 error_stmt = " goto fail;"
1216 name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)
1217 wrapper_name = emitter.emit_cpyfunction_instance(fn, name, filepath, error_stmt)
1218 name_obj = f"{wrapper_name}_name"
1219 emitter.emit_line(f'PyObject *{name_obj} = PyUnicode_FromString("{fn.name}");')
1220 emitter.emit_line(f"if (unlikely(!{name_obj}))")
1221 emitter.emit_line(error_stmt)
1222 emitter.emit_line(
1223 f"if (PyDict_SetItem({globals}, {name_obj}, (PyObject *){wrapper_name}) < 0)"
1224 )
1225 emitter.emit_line(error_stmt)
1226
1227 def emit_module_exec_func(
1228 self, emitter: Emitter, module_name: str, module_prefix: str, module: ModuleIR
1229 ) -> None:
1230 """Emit the module exec function.
1231
1232 If we are compiling just one module, this will be the normal C API
1233 exec function. If we are compiling 2+ modules, we generate a shared
1234 library for the modules and shims that call into the shared
1235 library, and in this case the shared module defines an internal
1236 exec function for each module and these will be called by the shims
1237 via Capsules.
1238 """
1239 exec_name = f"CPyExec_{exported_name(module_name)}"
1240 declaration = f"int {exec_name}(PyObject *module)"
1241 emitter.context.declarations[exec_name] = HeaderDeclaration(declaration + ";")
1242 module_static = self.module_internal_static_name(module_name, emitter)
1243 emitter.emit_lines(declaration, "{")
1244 emitter.emit_line("intern_strings();")
1245 if self.compiler_options.depends_on_librt_internal:
1246 emitter.emit_line("if (import_librt_internal() < 0) {")
1247 emitter.emit_line("return -1;")
1248 emitter.emit_line("}")
1249 if LIBRT_BASE64 in module.dependencies:
1250 emitter.emit_line("if (import_librt_base64() < 0) {")
1251 emitter.emit_line("return -1;")
1252 emitter.emit_line("}")
1253 if LIBRT_STRINGS in module.dependencies:
1254 emitter.emit_line("if (import_librt_strings() < 0) {")
1255 emitter.emit_line("return -1;")
1256 emitter.emit_line("}")
1257 if LIBRT_TIME in module.dependencies:
1258 emitter.emit_line("if (import_librt_time() < 0) {")
1259 emitter.emit_line("return -1;")
1260 emitter.emit_line("}")
1261 if LIBRT_VECS in module.dependencies:
1262 emitter.emit_line("if (import_librt_vecs() < 0) {")
1263 emitter.emit_line("return -1;")
1264 emitter.emit_line("}")
1265 if LIBRT_RANDOM in module.dependencies:
1266 emitter.emit_line("if (import_librt_random() < 0) {")
1267 emitter.emit_line("return -1;")
1268 emitter.emit_line("}")
1269 emitter.emit_line("PyObject* modname = NULL;")
1270 if self.multi_phase_init:
1271 emitter.emit_line(f"{module_static} = module;")
1272 emitter.emit_line(
1273 f'modname = PyObject_GetAttrString((PyObject *){module_static}, "__name__");'
1274 )
1275
1276 module_globals = emitter.static_name("globals", module_name)
1277 emitter.emit_lines(
1278 f"{module_globals} = PyModule_GetDict({module_static});",
1279 f"if (unlikely({module_globals} == NULL))",
1280 " goto fail;",
1281 )
1282
1283 if self.multi_phase_init:
1284 emitter.emit_lines(
1285 f"if (PyModule_AddFunctions(module, {module_prefix}module_methods) < 0)",
1286 " goto fail;",
1287 )
1288
1289 self.emit_coroutine_wrappers(emitter, module, module_globals)
1290
1291 # HACK: Manually instantiate generated classes here
1292 type_structs: list[str] = []
1293 for cl in module.classes:
1294 type_struct = emitter.type_struct_name(cl)
1295 type_structs.append(type_struct)
1296 if cl.is_generated:
1297 error_stmt = " goto fail;"
1298 emitter.emit_lines(
1299 "{t} = (PyTypeObject *)CPyType_FromTemplate("
1300 "(PyObject *){t}_template, NULL, modname);".format(t=type_struct)
1301 )
1302 emitter.emit_lines(f"if (unlikely(!{type_struct}))", error_stmt)
1303 name_prefix = cl.name_prefix(emitter.names)
1304 emitter.emit_line(f"CPyDef_{name_prefix}_trait_vtable_setup();")
1305
1306 emitter.emit_lines("if (CPyGlobalsInit() < 0)", " goto fail;")
1307
1308 self.generate_top_level_call(module, emitter)
1309
1310 emitter.emit_lines("Py_DECREF(modname);")
1311
1312 emitter.emit_line("return 0;")
1313 emitter.emit_lines("fail:")
1314 if self.multi_phase_init:
1315 emitter.emit_lines(f"{module_static} = NULL;", "Py_CLEAR(modname);")
1316 else:
1317 emitter.emit_lines(f"Py_CLEAR({module_static});", "Py_CLEAR(modname);")
1318 for name, typ in module.final_names:
1319 static_name = emitter.static_name(name, module_name)
1320 emitter.emit_dec_ref(static_name, typ, is_xdec=True)
1321 undef = emitter.c_undefined_value(typ)
1322 emitter.emit_line(f"{static_name} = {undef};")
1323 # the type objects returned from CPyType_FromTemplate are all new references
1324 # so we have to decref them
1325 for t in type_structs:
1326 emitter.emit_line(f"Py_CLEAR({t});")
1327 emitter.emit_line("return -1;")
1328 emitter.emit_line("}")
1329
1330 def emit_init_only_func(self, emitter: Emitter, module_name: str, module_prefix: str) -> None:
1331 """Emit CPyInitOnly_* which creates the module object without executing the body.
1332
1333 This allows the caller to set up attributes like __file__ and __package__
1334 before the module body runs. Used for same-group native imports.
1335 """
1336 init_only_name = f"CPyInitOnly_{exported_name(module_name)}"
1337 init_only_decl = f"PyObject *{init_only_name}(void)"
1338 emitter.context.declarations[init_only_name] = HeaderDeclaration(init_only_decl + ";")
1339 module_static = self.module_internal_static_name(module_name, emitter)
1340 emitter.emit_lines(init_only_decl, "{")
1341 emitter.emit_lines(
1342 f"if ({module_static}) {{",
1343 f"Py_INCREF({module_static});",
1344 f"return {module_static};",
1345 "}",
1346 )
1347 emitter.emit_lines(
1348 f"{module_static} = PyModule_Create(&{module_prefix}module);",
1349 f"return {module_static};",
1350 )
1351 emitter.emit_lines("}")
1352 emitter.emit_line("")
1353
1354 def emit_module_init_func(
1355 self, emitter: Emitter, module_name: str, module_prefix: str
1356 ) -> None:
1357 if not self.use_shared_lib:
1358 declaration = f"PyMODINIT_FUNC PyInit_{module_name}(void)"
1359 else:
1360 n = f"CPyInit_{exported_name(module_name)}"
1361 declaration = f"PyObject *{n}(void)"
1362 emitter.context.declarations[n] = HeaderDeclaration(declaration + ";")
1363
1364 if self.multi_phase_init:
1365 emitter.emit_lines(declaration, "{")
1366 def_name = f"{module_prefix}module"
1367 emitter.emit_line(f"return PyModuleDef_Init(&{def_name});")
1368 emitter.emit_line("}")
1369 return
1370
1371 exec_func = f"CPyExec_{exported_name(module_name)}"
1372
1373 if self.use_shared_lib:
1374 self.emit_init_only_func(emitter, module_name, module_prefix)
1375
1376 # Emit CPyInit_* / PyInit_* which creates the module and executes the body.
1377 emitter.emit_lines(declaration, "{")
1378 module_static = self.module_internal_static_name(module_name, emitter)
1379
1380 emitter.emit_line("PyObject* modname = NULL;")
1381 emitter.emit_lines(
1382 f"if ({module_static}) {{",
1383 f"Py_INCREF({module_static});",
1384 f"return {module_static};",
1385 "}",
1386 )
1387
1388 emitter.emit_lines(
1389 f"{module_static} = PyModule_Create(&{module_prefix}module);",
1390 f"if (unlikely({module_static} == NULL))",
1391 " goto fail;",
1392 )
1393
1394 emitter.emit_line(f'modname = PyUnicode_FromString("{module_name}");')
1395 emitter.emit_line("if (modname == NULL) CPyError_OutOfMemory();")
1396 emitter.emit_line("int rv = 0;")
1397 if self.group_name:
1398 shared_lib_mod_name = shared_lib_name(self.group_name)
1399 emitter.emit_line("PyObject *mod_dict = PyImport_GetModuleDict();")
1400 emitter.emit_line("PyObject *shared_lib = NULL;")
1401 emitter.emit_line(
1402 f'rv = PyDict_GetItemStringRef(mod_dict, "{shared_lib_mod_name}", &shared_lib);'
1403 )
1404 emitter.emit_line("if (rv < 0) goto fail;")
1405 emitter.emit_line(
1406 'PyObject *shared_lib_file = PyObject_GetAttrString(shared_lib, "__file__");'
1407 )
1408 emitter.emit_line("if (shared_lib_file == NULL) goto fail;")
1409 else:
1410 emitter.emit_line(
1411 f'PyObject *shared_lib_file = PyUnicode_FromString("{module_name + EXT_SUFFIX}");'
1412 )
1413 emitter.emit_line("if (shared_lib_file == NULL) CPyError_OutOfMemory();")
1414 emitter.emit_line(f'PyObject *ext_suffix = PyUnicode_FromString("{EXT_SUFFIX}");')
1415 emitter.emit_line("if (ext_suffix == NULL) CPyError_OutOfMemory();")
1416 is_pkg = int(self.source_paths[module_name].endswith("__init__.py"))
1417 emitter.emit_line(f"Py_ssize_t is_pkg = {is_pkg};")
1418
1419 emitter.emit_line(
1420 f"rv = CPyImport_SetDunderAttrs({module_static}, modname, shared_lib_file, ext_suffix, is_pkg);"
1421 )
1422 emitter.emit_line("Py_DECREF(ext_suffix);")
1423 emitter.emit_line("Py_DECREF(shared_lib_file);")
1424 emitter.emit_line("if (rv < 0) goto fail;")
1425
1426 # Register in sys.modules early so that circular imports via
1427 # CPyImport_ImportNative can detect that this module is already
1428 # being initialized and avoid re-executing the module body.
1429 emitter.emit_line(
1430 f"if (PyObject_SetItem(PyImport_GetModuleDict(), modname, {module_static}) < 0)"
1431 )
1432 emitter.emit_line(" goto fail;")
1433 emitter.emit_line("Py_CLEAR(modname);")
1434 emitter.emit_lines(f"if ({exec_func}({module_static}) != 0)", " goto fail;")
1435 emitter.emit_line(f"return {module_static};")
1436 emitter.emit_lines("fail:")
1437 # Clean up on failure: remove from sys.modules and clear the static
1438 # so that a subsequent import attempt will retry initialization.
1439 emitter.emit_line("{")
1440 emitter.emit_line(" PyObject *exc_type, *exc_val, *exc_tb;")
1441 emitter.emit_line(" PyErr_Fetch(&exc_type, &exc_val, &exc_tb);")
1442 emitter.emit_line(" if (modname == NULL) {")
1443 emitter.emit_line(f' modname = PyUnicode_FromString("{module_name}");')
1444 emitter.emit_line(" if (modname == NULL) CPyError_OutOfMemory();")
1445 emitter.emit_line(" }")
1446 emitter.emit_line(" PyObject_DelItem(PyImport_GetModuleDict(), modname);")
1447 emitter.emit_line(" PyErr_Clear();")
1448 emitter.emit_line(" Py_DECREF(modname);")
1449 emitter.emit_line(f" Py_CLEAR({module_static});")
1450 emitter.emit_line(" PyErr_Restore(exc_type, exc_val, exc_tb);")
1451 emitter.emit_line("}")
1452 emitter.emit_line("return NULL;")
1453 emitter.emit_lines("}")
1454
1455 def generate_top_level_call(self, module: ModuleIR, emitter: Emitter) -> None:
1456 """Generate call to function representing module top level."""
1457 # Optimization: we tend to put the top level last, so reverse iterate
1458 for fn in reversed(module.functions):
1459 if fn.name == TOP_LEVEL_NAME:
1460 emitter.emit_lines(
1461 f"char result = {emitter.native_function_name(fn.decl)}();",
1462 "if (result == 2)",
1463 " goto fail;",
1464 )
1465 break
1466
1467 def toposort_declarations(self) -> list[HeaderDeclaration]:
1468 """Topologically sort the declaration dict by dependencies.
1469
1470 Declarations can require other declarations to come prior in C (such as declaring structs).
1471 In order to guarantee that the C output will compile the declarations will thus need to
1472 be properly ordered. This simple DFS guarantees that we have a proper ordering.
1473
1474 This runs in O(V + E).
1475 """
1476 result = []
1477 marked_declarations: dict[str, MarkedDeclaration] = {}
1478 for k, v in self.context.declarations.items():
1479 marked_declarations[k] = MarkedDeclaration(v, False)
1480
1481 def _toposort_visit(name: str) -> None:
1482 decl = marked_declarations[name]
1483 if decl.mark:
1484 return
1485
1486 for child in sorted(decl.declaration.dependencies):
1487 _toposort_visit(child)
1488
1489 result.append(decl.declaration)
1490 decl.mark = True
1491
1492 for name in marked_declarations:
1493 _toposort_visit(name)
1494
1495 return result
1496
1497 def declare_global(
1498 self, type_spaced: str, name: str, *, initializer: str | None = None
1499 ) -> None:
1500 if "[" not in type_spaced:
1501 base = f"{type_spaced}{name}"
1502 else:
1503 a, b = type_spaced.split("[", 1)
1504 base = f"{a}{name}[{b}"
1505
1506 if not initializer:
1507 defn = None
1508 else:
1509 defn = [f"{base} = {initializer};"]
1510 if name not in self.context.declarations:
1511 self.context.declarations[name] = HeaderDeclaration(f"{base};", defn=defn)
1512
1513 def declare_internal_globals(self, module_name: str, emitter: Emitter) -> None:
1514 static_name = emitter.static_name("globals", module_name)
1515 if static_name not in self.context.declarations:
1516 self.context.declarations[static_name] = HeaderDeclaration(
1517 f"PyObject *{static_name};", needs_export=True
1518 )
1519
1520 def module_internal_static_name(self, module_name: str, emitter: Emitter) -> str:
1521 return emitter.static_name(module_name + "__internal", None, prefix=MODULE_PREFIX)
1522
1523 def declare_module(self, module_name: str, emitter: Emitter) -> None:
1524 # We declare two globals for each compiled module:
1525 # one used internally in the implementation of module init to cache results
1526 # and prevent infinite recursion in import cycles, and one used
1527 # by other modules to refer to it.
1528 if module_name in self.modules:
1529 internal_static_name = self.module_internal_static_name(module_name, emitter)
1530 self.declare_global("CPyModule *", internal_static_name, initializer="NULL")
1531 static_name = emitter.static_name(module_name, None, prefix=MODULE_PREFIX)
1532 self.declare_global("CPyModule *", static_name)
1533 self.simple_inits.append((static_name, "Py_None"))
1534
1535 def declare_imports(self, imps: Iterable[str], emitter: Emitter) -> None:
1536 for imp in imps:
1537 self.declare_module(imp, emitter)
1538
1539 def declare_finals(
1540 self, module: str, final_names: Iterable[tuple[str, RType]], emitter: Emitter
1541 ) -> None:
1542 for name, typ in final_names:
1543 static_name = emitter.static_name(name, module)
1544 emitter.context.declarations[static_name] = HeaderDeclaration(
1545 f"{emitter.ctype_spaced(typ)}{static_name};",
1546 [self.final_definition(module, name, typ, emitter)],
1547 needs_export=True,
1548 )
1549
1550 def final_definition(self, module: str, name: str, typ: RType, emitter: Emitter) -> str:
1551 static_name = emitter.static_name(name, module)
1552 # Here we rely on the fact that undefined value and error value are always the same
1553 undefined = emitter.c_initializer_undefined_value(typ)
1554 return f"{emitter.ctype_spaced(typ)}{static_name} = {undefined};"
1555
1556 def declare_static_pyobject(self, identifier: str, emitter: Emitter) -> None:
1557 symbol = emitter.static_name(identifier, None)
1558 self.declare_global("PyObject *", symbol)
1559
1560 def declare_type_vars(self, module: str, type_var_names: list[str], emitter: Emitter) -> None:
1561 for name in type_var_names:
1562 static_name = emitter.static_name(name, module, prefix=TYPE_VAR_PREFIX)
1563 emitter.context.declarations[static_name] = HeaderDeclaration(
1564 f"PyObject *{static_name};",
1565 [f"PyObject *{static_name} = NULL;"],
1566 needs_export=False,
1567 )
1568
1569
1570 T = TypeVar("T")
1571
1572
1573 def toposort(deps: dict[T, set[T]]) -> list[T]:
1574 """Topologically sort a dict from item to dependencies.
1575
1576 This runs in O(V + E).
1577 """
1578 result = []
1579 visited: set[T] = set()
1580
1581 def visit(item: T) -> None:
1582 if item in visited:
1583 return
1584
1585 for child in deps[item]:
1586 visit(child)
1587
1588 result.append(item)
1589 visited.add(item)
1590
1591 for item in deps:
1592 visit(item)
1593
1594 return result
1595
1596
1597 def is_fastcall_supported(fn: FuncIR, capi_version: tuple[int, int]) -> bool:
1598 if fn.class_name is not None:
1599 if fn.name == "__call__":
1600 # We can use vectorcalls (PEP 590) when supported
1601 return True
1602 # TODO: Support fastcall for __init__ and __new__.
1603 return fn.name != "__init__" and fn.name != "__new__"
1604 return True
1605
1606
1607 def collect_literals(fn: FuncIR, literals: Literals) -> None:
1608 """Store all Python literal object refs in fn.
1609
1610 Collecting literals must happen only after we have the final IR.
1611 This way we won't include literals that have been optimized away.
1612 """
1613 for block in fn.blocks:
1614 for op in block.ops:
1615 if isinstance(op, LoadLiteral):
1616 literals.record_literal(op.value)
1617
1618
1619 def c_string_array_initializer(components: list[bytes]) -> str:
1620 result = []
1621 result.append("{\n")
1622 for s in components:
1623 result.append(" " + c_string_initializer(s) + ",\n")
1624 result.append("}")
1625 return "".join(result)