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