Debian Codegraph @

mypyc/build.py

raw
1 """Support for building extensions using mypyc with distutils or setuptools
2
3 The main entry point is mypycify, which produces a list of extension
4 modules to be passed to setup. A trivial setup.py for a mypyc built
5 project, then, looks like:
6
7 from setuptools import setup
8 from mypyc.build import mypycify
9
10 setup(name='test_module',
11 ext_modules=mypycify(['foo.py']),
12 )
13
14 See the mypycify docs for additional arguments.
15
16 mypycify can integrate with either distutils or setuptools, but needs
17 to know at import-time whether it is using distutils or setuputils. We
18 hackily decide based on whether setuptools has been imported already.
19 """
20
21 from __future__ import annotations
22
23 import hashlib
24 import os.path
25 import re
26 import sys
27 import time
28 from collections.abc import Iterable
29 from typing import TYPE_CHECKING, Any, NamedTuple, NoReturn, cast
30
31 import mypyc.build_setup # noqa: F401
32 from mypy.build import BuildSource
33 from mypy.errors import CompileError
34 from mypy.fscache import FileSystemCache
35 from mypy.main import process_options
36 from mypy.options import Options
37 from mypy.util import write_junit_xml
38 from mypyc.annotate import generate_annotated_html
39 from mypyc.codegen import emitmodule
40 from mypyc.common import IS_FREE_THREADED, RUNTIME_C_FILES, shared_lib_name
41 from mypyc.errors import Errors
42 from mypyc.ir.deps import SourceDep
43 from mypyc.ir.pprint import format_modules
44 from mypyc.namegen import exported_name
45 from mypyc.options import CompilerOptions
46
47
48 class ModDesc(NamedTuple):
49 module: str
50 c_files: list[str]
51 other_files: list[str]
52 include_dirs: list[str]
53
54
55 LIBRT_MODULES = [
56 ModDesc("librt.internal", ["internal/librt_internal.c"], [], ["internal"]),
57 ModDesc("librt.strings", ["strings/librt_strings.c"], [], ["strings"]),
58 ModDesc(
59 "librt.base64",
60 [
61 "base64/librt_base64.c",
62 "base64/lib.c",
63 "base64/codec_choose.c",
64 "base64/tables/tables.c",
65 "base64/arch/generic/codec.c",
66 "base64/arch/ssse3/codec.c",
67 "base64/arch/sse41/codec.c",
68 "base64/arch/sse42/codec.c",
69 "base64/arch/avx/codec.c",
70 "base64/arch/avx2/codec.c",
71 "base64/arch/avx512/codec.c",
72 "base64/arch/neon32/codec.c",
73 "base64/arch/neon64/codec.c",
74 ],
75 [
76 "base64/arch/avx/enc_loop_asm.c",
77 "base64/arch/avx2/enc_loop.c",
78 "base64/arch/avx2/enc_loop_asm.c",
79 "base64/arch/avx2/enc_reshuffle.c",
80 "base64/arch/avx2/enc_translate.c",
81 "base64/arch/avx2/dec_loop.c",
82 "base64/arch/avx2/dec_reshuffle.c",
83 "base64/arch/generic/32/enc_loop.c",
84 "base64/arch/generic/64/enc_loop.c",
85 "base64/arch/generic/32/dec_loop.c",
86 "base64/arch/generic/enc_head.c",
87 "base64/arch/generic/enc_tail.c",
88 "base64/arch/generic/dec_head.c",
89 "base64/arch/generic/dec_tail.c",
90 "base64/arch/ssse3/dec_reshuffle.c",
91 "base64/arch/ssse3/dec_loop.c",
92 "base64/arch/ssse3/enc_loop_asm.c",
93 "base64/arch/ssse3/enc_translate.c",
94 "base64/arch/ssse3/enc_reshuffle.c",
95 "base64/arch/ssse3/enc_loop.c",
96 "base64/arch/neon64/dec_loop.c",
97 "base64/arch/neon64/enc_loop_asm.c",
98 "base64/codecs.h",
99 "base64/env.h",
100 "base64/lib_openmp.c",
101 "base64/tables/tables.h",
102 "base64/tables/table_dec_32bit.h",
103 "base64/tables/table_enc_12bit.h",
104 ],
105 ["base64"],
106 ),
107 ModDesc(
108 "librt.vecs",
109 [
110 "vecs/librt_vecs.c",
111 "vecs/vec_i64.c",
112 "vecs/vec_i32.c",
113 "vecs/vec_i16.c",
114 "vecs/vec_u8.c",
115 "vecs/vec_float.c",
116 "vecs/vec_bool.c",
117 "vecs/vec_t.c",
118 "vecs/vec_nested.c",
119 ],
120 ["vecs/librt_vecs.h", "vecs/vec_template.c"],
121 ["vecs"],
122 ),
123 ModDesc("librt.time", ["time/librt_time.c"], ["time/librt_time.h"], []),
124 ModDesc("librt.random", ["random/librt_random.c"], ["random/librt_random.h"], ["random"]),
125 ]
126
127 try:
128 # Import setuptools so that it monkey-patch overrides distutils
129 import setuptools
130 except ImportError:
131 pass
132
133 if TYPE_CHECKING:
134 if sys.version_info >= (3, 12):
135 from setuptools import Extension
136 else:
137 from distutils.core import Extension as _distutils_Extension
138 from typing import TypeAlias
139
140 from setuptools import Extension as _setuptools_Extension
141
142 Extension: TypeAlias = _setuptools_Extension | _distutils_Extension
143
144 if sys.version_info >= (3, 12):
145 # From setuptools' monkeypatch
146 from distutils import ccompiler, sysconfig # type: ignore[import-not-found]
147 else:
148 from distutils import ccompiler, sysconfig
149
150
151 def get_extension() -> type[Extension]:
152 # We can work with either setuptools or distutils, and pick setuptools
153 # if it has been imported.
154 use_setuptools = "setuptools" in sys.modules
155 extension_class: type[Extension]
156
157 if sys.version_info < (3, 12) and not use_setuptools:
158 import distutils.core
159
160 extension_class = distutils.core.Extension
161 else:
162 if not use_setuptools:
163 sys.exit("error: setuptools not installed")
164 extension_class = setuptools.Extension
165
166 return extension_class
167
168
169 def setup_mypycify_vars() -> None:
170 """Rewrite a bunch of config vars in pretty dubious ways."""
171 # There has to be a better approach to this.
172
173 # The vars can contain ints but we only work with str ones
174 vars = cast(dict[str, str], sysconfig.get_config_vars())
175 if sys.platform == "darwin":
176 # Disable building 32-bit binaries, since we generate too much code
177 # for a 32-bit Mach-O object. There has to be a better way to do this.
178 vars["LDSHARED"] = vars["LDSHARED"].replace("-arch i386", "")
179 vars["LDFLAGS"] = vars["LDFLAGS"].replace("-arch i386", "")
180 vars["CFLAGS"] = vars["CFLAGS"].replace("-arch i386", "")
181
182
183 def fail(message: str) -> NoReturn:
184 # TODO: Is there something else we should do to fail?
185 sys.exit(message)
186
187
188 def emit_messages(options: Options, messages: list[str], dt: float, serious: bool = False) -> None:
189 # ... you know, just in case.
190 if options.junit_xml:
191 py_version = f"{options.python_version[0]}_{options.python_version[1]}"
192 write_junit_xml(
193 dt,
194 serious,
195 {None: messages} if messages else {},
196 options.junit_xml,
197 py_version,
198 options.platform,
199 )
200 if messages:
201 print("\n".join(messages))
202
203
204 def get_mypy_config(
205 mypy_options: list[str],
206 only_compile_paths: Iterable[str] | None,
207 compiler_options: CompilerOptions,
208 fscache: FileSystemCache | None,
209 ) -> tuple[list[BuildSource], list[BuildSource], Options]:
210 """Construct mypy BuildSources and Options from file and options lists"""
211 all_sources, options = process_options(mypy_options, fscache=fscache, mypyc=True)
212 if only_compile_paths is not None:
213 paths_set = set(only_compile_paths)
214 mypyc_sources = [s for s in all_sources if s.path in paths_set]
215 else:
216 mypyc_sources = all_sources
217
218 if compiler_options.separate:
219 mypyc_sources = [src for src in mypyc_sources if src.path]
220
221 if not mypyc_sources:
222 return mypyc_sources, all_sources, options
223
224 # Override whatever python_version is inferred from the .ini file,
225 # and set the python_version to be the currently used version.
226 options.python_version = sys.version_info[:2]
227
228 if options.python_version[0] == 2:
229 fail("Python 2 not supported")
230 if not options.strict_optional:
231 fail("Disabling strict optional checking not supported")
232 options.show_traceback = True
233 # Needed to get types for all AST nodes
234 options.export_types = True
235 # We use mypy incremental mode when doing separate/incremental mypyc compilation
236 options.incremental = compiler_options.separate
237 options.preserve_asts = True
238
239 for source in mypyc_sources:
240 options.per_module_options.setdefault(source.module, {})["mypyc"] = True
241
242 return mypyc_sources, all_sources, options
243
244
245 def is_package_source(source: BuildSource) -> bool:
246 return source.path is not None and os.path.split(source.path)[1] == "__init__.py"
247
248
249 def generate_c_extension_shim(
250 full_module_name: str, module_name: str, dir_name: str, group_name: str
251 ) -> str:
252 """Create a C extension shim with a passthrough PyInit function.
253
254 Arguments:
255 full_module_name: the dotted full module name
256 module_name: the final component of the module name
257 dir_name: the directory to place source code
258 group_name: the name of the group
259 """
260 cname = "%s.c" % full_module_name.replace(".", os.sep)
261 cpath = os.path.join(dir_name, cname)
262
263 if IS_FREE_THREADED:
264 # We use multi-phase init in free-threaded builds to enable free threading.
265 shim_name = "module_shim_no_gil_multiphase.tmpl"
266 else:
267 shim_name = "module_shim.tmpl"
268
269 # We load the C extension shim template from a file.
270 # (So that the file could be reused as a bazel template also.)
271 with open(os.path.join(include_dir(), shim_name)) as f:
272 shim_template = f.read()
273
274 write_file(
275 cpath,
276 shim_template.format(
277 modname=module_name,
278 libname=shared_lib_name(group_name),
279 full_modname=exported_name(full_module_name),
280 ),
281 )
282
283 return cpath
284
285
286 def group_name(modules: list[str]) -> str:
287 """Produce a probably unique name for a group from a list of module names."""
288 if len(modules) == 1:
289 return modules[0]
290
291 h = hashlib.sha1()
292 h.update(",".join(modules).encode())
293 return h.hexdigest()[:20]
294
295
296 def include_dir() -> str:
297 """Find the path of the lib-rt dir that needs to be included"""
298 return os.path.join(os.path.abspath(os.path.dirname(__file__)), "lib-rt")
299
300
301 def generate_c(
302 sources: list[BuildSource],
303 options: Options,
304 groups: emitmodule.Groups,
305 fscache: FileSystemCache,
306 compiler_options: CompilerOptions,
307 ) -> tuple[list[list[tuple[str, str]]], str, list[SourceDep]]:
308 """Drive the actual core compilation step.
309
310 The groups argument describes how modules are assigned to C
311 extension modules. See the comments on the Groups type in
312 mypyc.emitmodule for details.
313
314 Returns the C source code, (for debugging) the pretty printed IR, and list of SourceDeps.
315 """
316 t0 = time.time()
317
318 try:
319 result = emitmodule.parse_and_typecheck(
320 sources, options, compiler_options, groups, fscache
321 )
322 except CompileError as e:
323 emit_messages(options, e.messages, time.time() - t0, serious=(not e.use_stdout))
324 sys.exit(1)
325
326 t1 = time.time()
327 if result.errors:
328 emit_messages(options, result.errors, t1 - t0)
329 sys.exit(1)
330
331 if compiler_options.verbose:
332 print(f"Parsed and typechecked in {t1 - t0:.3f}s")
333
334 errors = Errors(options)
335 modules, ctext, mapper = emitmodule.compile_modules_to_c(
336 result, compiler_options=compiler_options, errors=errors, groups=groups
337 )
338 t2 = time.time()
339 emit_messages(options, errors.new_messages(), t2 - t1)
340 if errors.num_errors:
341 # No need to stop the build if only warnings were emitted.
342 sys.exit(1)
343
344 if compiler_options.verbose:
345 print(f"Compiled to C in {t2 - t1:.3f}s")
346
347 if options.mypyc_annotation_file:
348 generate_annotated_html(options.mypyc_annotation_file, result, modules, mapper)
349
350 # Collect SourceDep dependencies
351 source_deps = sorted(emitmodule.collect_source_dependencies(modules), key=lambda d: d.path)
352
353 return ctext, "\n".join(format_modules(modules)), source_deps
354
355
356 def build_using_shared_lib(
357 sources: list[BuildSource],
358 group_name: str,
359 cfiles: list[str],
360 deps: list[str],
361 build_dir: str,
362 extra_compile_args: list[str],
363 extra_include_dirs: list[str],
364 ) -> list[Extension]:
365 """Produce the list of extension modules when a shared library is needed.
366
367 This creates one shared library extension module that all the
368 others import, and one shim extension module for each
369 module in the build. Each shim simply calls an initialization function
370 in the shared library.
371
372 The shared library (which lib_name is the name of) is a Python
373 extension module that exports the real initialization functions in
374 Capsules stored in module attributes.
375 """
376 extensions = [
377 get_extension()(
378 shared_lib_name(group_name),
379 sources=cfiles,
380 include_dirs=[include_dir(), build_dir] + extra_include_dirs,
381 depends=deps,
382 extra_compile_args=extra_compile_args,
383 )
384 ]
385
386 for source in sources:
387 module_name = source.module.split(".")[-1]
388 shim_file = generate_c_extension_shim(source.module, module_name, build_dir, group_name)
389
390 # We include the __init__ in the "module name" we stick in the Extension,
391 # since this seems to be needed for it to end up in the right place.
392 full_module_name = source.module
393 assert source.path
394 if is_package_source(source):
395 full_module_name += ".__init__"
396 extensions.append(
397 get_extension()(
398 full_module_name, sources=[shim_file], extra_compile_args=extra_compile_args
399 )
400 )
401
402 return extensions
403
404
405 def build_single_module(
406 sources: list[BuildSource],
407 cfiles: list[str],
408 extra_compile_args: list[str],
409 extra_include_dirs: list[str],
410 ) -> list[Extension]:
411 """Produce the list of extension modules for a standalone extension.
412
413 This contains just one module, since there is no need for a shared module.
414 """
415 return [
416 get_extension()(
417 sources[0].module,
418 sources=cfiles,
419 include_dirs=[include_dir()] + extra_include_dirs,
420 extra_compile_args=extra_compile_args,
421 )
422 ]
423
424
425 def write_file(path: str, contents: str) -> None:
426 """Write data into a file.
427
428 If the file already exists and has the same contents we
429 want to write, skip writing so as to preserve the mtime
430 and avoid triggering recompilation.
431 """
432 # We encode it ourselves and open the files as binary to avoid windows
433 # newline translation
434 encoded_contents = contents.encode("utf-8")
435 try:
436 with open(path, "rb") as f:
437 old_contents: bytes | None = f.read()
438 except OSError:
439 old_contents = None
440 if old_contents != encoded_contents:
441 os.makedirs(os.path.dirname(path), exist_ok=True)
442 with open(path, "wb") as g:
443 g.write(encoded_contents)
444
445 # Fudge the mtime forward because otherwise when two builds happen close
446 # together (like in a test) setuptools might not realize the source is newer
447 # than the new artifact.
448 # XXX: This is bad though.
449 new_mtime = os.stat(path).st_mtime + 1
450 os.utime(path, times=(new_mtime, new_mtime))
451
452
453 _MYPYC_EXTENSION_MARKER = "_mypyc_skip_redundant_inplace_copy"
454 _setuptools_patch_applied = False
455
456
457 def _patch_setuptools_copy_extensions_to_source() -> None:
458 """Skip redundant `.so` copies for extensions we generated.
459
460 setuptools' copy_extensions_to_source rewrites every `.so` in the
461 source tree on every build_ext, even when nothing changed. On macOS
462 this invalidates AMFI's signature cache (~100 ms re-verification per
463 `.so` on the next import), eating most of the separate=True
464 incremental speedup.
465
466 The patch is global because copy_extensions_to_source runs during
467 setup()'s build_ext command, after mypycify() has already returned;
468 we can't scope a context manager around it. Instead the skip only
469 fires for extensions tagged by mypycify (via the marker attribute),
470 so other setuptools users in the same setup.py see the unmodified
471 upstream behavior, including stub writes.
472 """
473 global _setuptools_patch_applied
474 if _setuptools_patch_applied:
475 return
476 _setuptools_patch_applied = True
477
478 from setuptools.command.build_ext import build_ext as _build_ext
479
480 original = _build_ext.copy_extensions_to_source
481
482 def _files_match(a: str, b: str) -> bool:
483 try:
484 sa = os.stat(a)
485 sb = os.stat(b)
486 except OSError:
487 return False
488 # Compare size + whole-second mtime. distutils' copy_file
489 # propagates the source mtime, but macOS drops sub-second
490 # precision on write so the float values never match verbatim.
491 return sa.st_size == sb.st_size and int(sa.st_mtime) == int(sb.st_mtime)
492
493 def patched(self: Any) -> None:
494 build_py = self.get_finalized_command("build_py")
495
496 def is_redundant(ext: Any) -> bool:
497 if not getattr(ext, _MYPYC_EXTENSION_MARKER, False):
498 return False
499 inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)
500 return _files_match(regular_file, inplace_file)
501
502 # Hide our already-fresh extensions from setuptools' loop and
503 # let it handle whatever's left. Delegating instead of
504 # reimplementing the body means future setuptools changes carry
505 # over for free. self.extensions is restored before we return
506 # so anything that inspects it later sees the original list.
507 saved = self.extensions
508 self.extensions = [ext for ext in saved if not is_redundant(ext)]
509 try:
510 original(self)
511 finally:
512 self.extensions = saved
513
514 _build_ext.copy_extensions_to_source = patched # type: ignore[method-assign]
515
516
517 def construct_groups(
518 sources: list[BuildSource],
519 separate: bool | list[tuple[list[str], str | None]],
520 use_shared_lib: bool,
521 group_name_override: str | None,
522 ) -> emitmodule.Groups:
523 """Compute Groups given the input source list and separate configs.
524
525 separate is the user-specified configuration for how to assign
526 modules to compilation groups (see mypycify docstring for details).
527
528 This takes that and expands it into our internal representation of
529 group configuration, documented in mypyc.emitmodule's definition
530 of Group.
531 """
532
533 if separate is True:
534 groups: emitmodule.Groups = [([source], None) for source in sources]
535 elif isinstance(separate, list):
536 groups = []
537 used_sources = set()
538 for files, name in separate:
539 normalized_files = {os.path.normpath(f) for f in files}
540 group_sources = [
541 src
542 for src in sources
543 if src.path is not None and os.path.normpath(src.path) in normalized_files
544 ]
545 groups.append((group_sources, name))
546 used_sources.update(group_sources)
547 unused_sources = [src for src in sources if src not in used_sources]
548 if unused_sources:
549 groups.extend([([source], None) for source in unused_sources])
550 else:
551 groups = [(sources, None)]
552
553 # Generate missing names.
554 # Sort the modules to make the compilation results consistent regardless of
555 # the source file order passed to mypycify.
556 for i, (group, name) in enumerate(groups):
557 group = sorted(group, key=lambda source: source.module)
558 if use_shared_lib and not name:
559 if group_name_override is not None:
560 name = group_name_override
561 else:
562 name = group_name([source.module for source in group])
563 groups[i] = (group, name)
564
565 groups = sorted(groups, key=lambda g: (g[1] or "", [s.module for s in g[0]]))
566 return groups
567
568
569 # Single regex that captures both `#include "foo"` and `#include <foo>`. The
570 # alternation lets us tell the two forms apart: the quoted-form match populates
571 # group 1 and the angle-form match populates group 2. The C preprocessor
572 # applies different search rules to each kind (see `_extract_includes`), so we
573 # carry the kind through resolution rather than collapsing them up front.
574 _INCLUDE_RE = re.compile(r'#\s*include\s+(?:"([^"]+)"|<([^>]+)>)')
575
576
577 def _extract_includes(contents: str) -> list[tuple[bool, str]]:
578 """Return each `#include` directive's (is_angled, name) from `contents`.
579
580 is_angled=False for `#include "foo"`, True for `#include <foo>`.
581 """
582 out: list[tuple[bool, str]] = []
583 for quoted, angled in _INCLUDE_RE.findall(contents):
584 if quoted:
585 out.append((False, quoted))
586 else:
587 out.append((True, angled))
588 return out
589
590
591 def get_header_deps(cfiles: list[tuple[str, str]]) -> list[tuple[bool, str]]:
592 """Find all the headers directly included by a group of cfiles.
593
594 Returns a sorted, deduplicated list of `(is_angled, header_name)` pairs.
595 Callers that only need the names can ignore the bool, but it is needed by
596 `resolve_cfile_deps` to apply the correct preprocessor search order.
597
598 We do this by just regexping the source, which is a bit simpler than
599 properly plumbing the data through. Transitive header-to-header includes
600 are picked up by `resolve_cfile_deps` in `mypyc_build`, which can read
601 the on-disk headers after every group has written its files.
602
603 Arguments:
604 cfiles: A list of (file name, file contents) pairs. Contents must be
605 non-empty; callers handling cached groups must re-read the .c
606 from disk before calling, otherwise direct includes are missed
607 and Extension.depends ends up empty.
608 """
609 assert all(
610 contents for _, contents in cfiles
611 ), "get_header_deps requires non-empty file contents"
612 headers: set[tuple[bool, str]] = set()
613 for _, contents in cfiles:
614 headers.update(_extract_includes(contents))
615
616 return sorted(headers)
617
618
619 def resolve_cfile_deps(
620 cfile_dir: str, direct_includes: list[tuple[bool, str]], target_dir: str
621 ) -> set[str]:
622 """
623 Resolve a .c file's `#include`s to on-disk paths, walking transitively through resolved headers.
624
625 The C preprocessor resolves `#include "foo"` against the includer's directory first, then via
626 -I, while `#include <foo>` only uses -I. We mirror that exactly: quoted includes are searched
627 in (includer_dir, target_dir) order, and angled includes are searched in target_dir only.
628 `target_dir` is the only -I path that holds files we generate; anything we cannot resolve under
629 it (or, for quoted form, the includer's dir) is dropped. Other headers like `<Python.h>` and
630 `<CPy.h>` live elsewhere and do not change between builds, so they are not real dependencies
631 for incremental purposes.
632
633 The walk is transitive: each resolved header is opened and scanned for its own `#include`
634 directives. Without this, cross-group export-table headers reached via `__native_internal_<mod>.h`
635 (which includes `<other_group/__native_other.h>`) would be missed, and edits that shift struct
636 offsets in `other_group` would not trigger a recompile of the consumer's .o file. Its baked-in
637 offsets would then resolve to whatever class/function now occupies that slot => runtime corruption.
638
639 Returns a set of resolved paths suitable for use as an Extension.depends list.
640 """
641 resolved: set[str] = set()
642
643 # Worklist of (search_dir, is_angled, header_name). search_dir is the includer's directory; for the
644 # initial cfile it is the cfile's dir, for a transitively-included header it is that header's dir.
645 # It is only consulted for quoted-form includes.
646 worklist: list[tuple[str, bool, str]] = [
647 (cfile_dir, is_angled, dep) for is_angled, dep in direct_includes
648 ]
649
650 while worklist:
651 search_dir, is_angled, dep = worklist.pop()
652 # Quoted form: includer's dir first, then -I (target_dir).
653 # Angled form: -I only (skips the includer's dir).
654 search_bases = (target_dir,) if is_angled else (search_dir, target_dir)
655 for base in search_bases:
656 candidate = os.path.normpath(os.path.join(base, dep))
657 if not os.path.exists(candidate):
658 continue
659 if candidate in resolved:
660 break
661 resolved.add(candidate)
662 # Recurse only into headers. Some lib-rt sources are pulled in as `#include "init.c"` etc.;
663 # those do not resolve under target_dir so they get filtered out before we would try to scan
664 # them, but the .h guard is a cheap belt-and-braces.
665 if candidate.endswith(".h"):
666 try:
667 with open(candidate, encoding="utf-8") as f:
668 header_contents = f.read()
669 except OSError:
670 header_contents = ""
671 sub_dir = os.path.dirname(candidate)
672 for sub_angled, sub in _extract_includes(header_contents):
673 worklist.append((sub_dir, sub_angled, sub))
674 break
675 return resolved
676
677
678 def mypyc_build(
679 paths: list[str],
680 compiler_options: CompilerOptions,
681 *,
682 separate: bool | list[tuple[list[str], str | None]] = False,
683 only_compile_paths: Iterable[str] | None = None,
684 skip_cgen_input: (
685 tuple[list[list[tuple[str, str]]], list[tuple[str, list[str], bool]]] | None
686 ) = None,
687 always_use_shared_lib: bool = False,
688 ) -> tuple[emitmodule.Groups, list[tuple[list[str], list[str]]], list[SourceDep]]:
689 """Do the front and middle end of mypyc building, producing and writing out C source."""
690 fscache = FileSystemCache()
691 mypyc_sources, all_sources, options = get_mypy_config(
692 paths, only_compile_paths, compiler_options, fscache
693 )
694
695 # We generate a shared lib if there are multiple modules or if any
696 # of the modules are in package. (Because I didn't want to fuss
697 # around with making the single module code handle packages.)
698 use_shared_lib = (
699 len(mypyc_sources) > 1
700 or any("." in x.module for x in mypyc_sources)
701 or any(is_package_source(x) for x in mypyc_sources)
702 or always_use_shared_lib
703 )
704
705 groups = construct_groups(mypyc_sources, separate, use_shared_lib, compiler_options.group_name)
706
707 if compiler_options.group_name is not None:
708 assert len(groups) == 1, "If using custom group_name, only one group is expected"
709
710 # We let the test harness just pass in the c file contents instead
711 # so that it can do a corner-cutting version without full stubs.
712 source_deps: list[SourceDep] = []
713 if not skip_cgen_input:
714 group_cfiles, ops_text, source_deps = generate_c(
715 all_sources, options, groups, fscache, compiler_options=compiler_options
716 )
717 # TODO: unique names?
718 write_file(os.path.join(compiler_options.target_dir, "ops.txt"), ops_text)
719 else:
720 group_cfiles = skip_cgen_input[0]
721 source_deps = [
722 SourceDep(path, include_dirs=dirs, internal=internal)
723 for (path, dirs, internal) in skip_cgen_input[1]
724 ]
725
726 # Write out the generated C and collect the files for each group.
727 # Should this be here??
728 #
729 # Header resolution is deferred to a second pass: a header in one group may include a header
730 # generated by another group, so resolving here misses cross-group deps for groups processed first.
731 pending: list[list[tuple[str, list[tuple[bool, str]]]]] = []
732 for cfiles in group_cfiles:
733 per_cfile_deps: list[tuple[str, list[tuple[bool, str]]]] = []
734 for cfile, ctext in cfiles:
735 cfile = os.path.join(compiler_options.target_dir, cfile)
736
737 # Empty contents marks a file the previous run already wrote
738 # (fully-cached group): skip the rewrite and just reuse it.
739 if ctext and not options.mypyc_skip_c_generation:
740 write_file(cfile, ctext)
741
742 # For fully-cached groups ctext is empty; read the on-disk .c so the dep resolver
743 # can walk its transitive header chain and populate Extension.depends. Otherwise,
744 # cross-group export-table header changes (e.g. a new class shifting struct offsets)
745 # won't trigger a recompile of this cached consumer's .o.
746 if not ctext and os.path.exists(cfile):
747 try:
748 with open(cfile, encoding="utf-8") as _f:
749 ctext = _f.read()
750 except OSError:
751 pass
752 per_cfile_deps.append((cfile, get_header_deps([(cfile, ctext)])))
753 pending.append(per_cfile_deps)
754
755 # Second pass: assemble each group's .c filenames and resolve transitive deps now that every group's
756 # headers are on disk. See resolve_cfile_deps for the rules.
757 group_cfilenames: list[tuple[list[str], list[str]]] = []
758 for per_cfile in pending:
759 cfilenames = [cf for cf, _ in per_cfile if os.path.splitext(cf)[1] == ".c"]
760 deps_set: set[str] = set()
761 for cfile_full, dep_names in per_cfile:
762 deps_set.update(
763 resolve_cfile_deps(
764 os.path.dirname(cfile_full), dep_names, compiler_options.target_dir
765 )
766 )
767 group_cfilenames.append((cfilenames, sorted(deps_set)))
768
769 return groups, group_cfilenames, source_deps
770
771
772 def get_cflags(
773 *,
774 compiler_type: str | None = None,
775 opt_level: str = "3",
776 debug_level: str = "1",
777 multi_file: bool = False,
778 experimental_features: bool = False,
779 log_trace: bool = False,
780 ) -> list[str]:
781 """Get C compiler flags for the given configuration.
782
783 Args:
784 compiler_type: Compiler type, e.g. "unix" or "msvc". If None, detected automatically.
785 opt_level: Optimization level as string ("0", "1", "2", or "3").
786 debug_level: Debug level as string ("0", "1", "2", or "3").
787 multi_file: Whether multi-file compilation mode is enabled.
788 experimental_features: Whether experimental features are enabled.
789 log_trace: Whether trace logging is enabled.
790
791 Returns:
792 List of compiler flags.
793 """
794 if compiler_type is None:
795 compiler: Any = ccompiler.new_compiler()
796 sysconfig.customize_compiler(compiler)
797 compiler_type = compiler.compiler_type
798
799 cflags: list[str] = []
800 if compiler_type == "unix":
801 cflags += [
802 f"-O{opt_level}",
803 f"-g{debug_level}",
804 "-Werror",
805 "-Wno-unused-function",
806 "-Wno-unused-label",
807 "-Wno-unreachable-code",
808 "-Wno-unused-variable",
809 "-Wno-unused-command-line-argument",
810 "-Wno-unknown-warning-option",
811 "-Wno-unused-but-set-variable",
812 "-Wno-ignored-optimization-argument",
813 # GCC at -O3 false-positives on struct hack (items[1]) in vec buffers
814 "-Wno-array-bounds",
815 "-Wno-stringop-overread",
816 "-Wno-stringop-overflow",
817 # Disables C Preprocessor (cpp) warnings
818 # See https://github.com/mypyc/mypyc/issues/956
819 "-Wno-cpp",
820 "-Wno-array-bounds",
821 "-Wno-stringop-overread",
822 "-Wno-stringop-overflow",
823 ]
824 if log_trace:
825 cflags.append("-DMYPYC_LOG_TRACE")
826 if experimental_features:
827 cflags.append("-DMYPYC_EXPERIMENTAL")
828 if opt_level == "0":
829 cflags.append("-UNDEBUG")
830 elif compiler_type == "msvc":
831 # msvc doesn't have levels, '/O2' is full and '/Od' is disable
832 if opt_level == "0":
833 opt_level = "d"
834 cflags.append("/UNDEBUG")
835 elif opt_level in ("1", "2", "3"):
836 opt_level = "2"
837 if debug_level == "0":
838 debug_level = "NONE"
839 elif debug_level == "1":
840 debug_level = "FASTLINK"
841 elif debug_level in ("2", "3"):
842 debug_level = "FULL"
843 cflags += [
844 f"/O{opt_level}",
845 f"/DEBUG:{debug_level}",
846 "/wd4102", # unreferenced label
847 "/wd4101", # unreferenced local variable
848 "/wd4146", # negating unsigned int
849 ]
850 if multi_file:
851 # Disable whole program optimization in multi-file mode so
852 # that we actually get the compilation speed and memory
853 # use wins that multi-file mode is intended for.
854 cflags += ["/GL-", "/wd9025"] # warning about overriding /GL
855 if log_trace:
856 cflags.append("/DMYPYC_LOG_TRACE")
857 if experimental_features:
858 cflags.append("/DMYPYC_EXPERIMENTAL")
859 return cflags
860
861
862 def mypycify(
863 paths: list[str],
864 *,
865 only_compile_paths: Iterable[str] | None = None,
866 verbose: bool = False,
867 opt_level: str = "3",
868 debug_level: str = "1",
869 strip_asserts: bool = False,
870 multi_file: bool = False,
871 separate: bool | list[tuple[list[str], str | None]] = False,
872 skip_cgen_input: (
873 tuple[list[list[tuple[str, str]]], list[tuple[str, list[str], bool]]] | None
874 ) = None,
875 target_dir: str | None = None,
876 include_runtime_files: bool | None = None,
877 strict_dunder_typing: bool = False,
878 group_name: str | None = None,
879 log_trace: bool = False,
880 depends_on_librt_internal: bool = False,
881 install_librt: bool = False,
882 experimental_features: bool = False,
883 ) -> list[Extension]:
884 """Main entry point to building using mypyc.
885
886 This produces a list of Extension objects that should be passed as the
887 ext_modules parameter to setup.
888
889 Arguments:
890 paths: A list of file paths to build. It may also contain mypy options.
891 only_compile_paths: If not None, an iterable of paths that are to be
892 the only modules compiled, even if other modules
893 appear in the mypy command line given to paths.
894 (These modules must still be passed to paths.)
895
896 verbose: Should mypyc be more verbose. Defaults to false.
897
898 opt_level: The optimization level, as a string. Defaults to '3' (meaning '-O3').
899 debug_level: The debug level, as a string. Defaults to '1' (meaning '-g1').
900 strip_asserts: Should asserts be stripped from the generated code.
901
902 multi_file: Should each Python module be compiled into its own C source file.
903 This can reduce compile time and memory requirements at the likely
904 cost of runtime performance of compiled code. Defaults to false.
905 separate: Should compiled modules be placed in separate extension modules.
906 If False, all modules are placed in a single shared library.
907 If True, every module is placed in its own library.
908 Otherwise, separate should be a list of
909 (file name list, optional shared library name) pairs specifying
910 groups of files that should be placed in the same shared library
911 (while all other modules will be placed in its own library).
912
913 Each group can be compiled independently, which can
914 speed up compilation, but calls between groups can
915 be slower than calls within a group and can't be
916 inlined.
917 target_dir: The directory to write C output files. Defaults to 'build'.
918 include_runtime_files: If not None, whether the mypyc runtime library
919 should be directly #include'd instead of linked
920 separately in order to reduce compiler invocations.
921 Defaults to False in multi_file mode, True otherwise.
922 strict_dunder_typing: If True, force dunder methods to have the return type
923 of the method strictly, which can lead to more
924 optimization opportunities. Defaults to False.
925 group_name: If set, override the default group name derived from
926 the hash of module names. This is used for the names of the
927 output C files and the shared library. This is only supported
928 if there is a single group. [Experimental]
929 log_trace: If True, compiled code writes a trace log of events in
930 mypyc_trace.txt (derived from executed operations). This is
931 useful for performance analysis, such as analyzing which
932 primitive ops are used the most and on which lines.
933 depends_on_librt_internal: This is True only for mypy itself.
934 install_librt: If True, also build the librt extension modules. Normally,
935 those are build and published on PyPI separately, but during
936 tests, we want to use their development versions (i.e. from
937 current commit).
938 experimental_features: Enable experimental features (install_librt=True is
939 also needed if using experimental librt features). These
940 have no backward compatibility guarantees!
941 """
942
943 # Skip redundant inplace .so copies on every build_ext invocation.
944 _patch_setuptools_copy_extensions_to_source()
945
946 # Figure out our configuration
947 compiler_options = CompilerOptions(
948 strip_asserts=strip_asserts,
949 multi_file=multi_file,
950 verbose=verbose,
951 separate=separate is not False,
952 target_dir=target_dir,
953 include_runtime_files=include_runtime_files,
954 strict_dunder_typing=strict_dunder_typing,
955 group_name=group_name,
956 log_trace=log_trace,
957 depends_on_librt_internal=depends_on_librt_internal,
958 experimental_features=experimental_features,
959 )
960
961 # Generate all the actual important C code
962 groups, group_cfilenames, source_deps = mypyc_build(
963 paths,
964 only_compile_paths=only_compile_paths,
965 compiler_options=compiler_options,
966 separate=separate,
967 skip_cgen_input=skip_cgen_input,
968 )
969
970 # Mess around with setuptools and actually get the thing built
971 setup_mypycify_vars()
972
973 # Create a compiler object so we can make decisions based on what
974 # compiler is being used. typeshed is missing some attributes on the
975 # compiler object so we give it type Any
976 compiler: Any = ccompiler.new_compiler()
977 sysconfig.customize_compiler(compiler)
978
979 build_dir = compiler_options.target_dir
980
981 cflags = get_cflags(
982 compiler_type=compiler.compiler_type,
983 opt_level=opt_level,
984 debug_level=debug_level,
985 multi_file=multi_file,
986 experimental_features=experimental_features,
987 log_trace=log_trace,
988 )
989
990 # If configured to (defaults to yes in multi-file mode), copy the
991 # runtime library in. Otherwise it just gets #included to save on
992 # compiler invocations.
993 shared_cfilenames = []
994 include_dirs = set()
995 if not compiler_options.include_runtime_files:
996 # Collect all files to copy: runtime files + conditional source files
997 files_to_copy = list(RUNTIME_C_FILES)
998 for source_dep in source_deps:
999 files_to_copy.append(source_dep.path)
1000 files_to_copy.append(source_dep.get_header())
1001 include_dirs.update(source_dep.include_dirs)
1002
1003 if compiler_options.depends_on_librt_internal:
1004 files_to_copy.append("internal/librt_internal_api.h")
1005 files_to_copy.append("internal/librt_internal_api.c")
1006 include_dirs.add("internal")
1007
1008 # Copy all files
1009 for name in files_to_copy:
1010 rt_file = os.path.join(build_dir, name)
1011 with open(os.path.join(include_dir(), name), encoding="utf-8") as f:
1012 write_file(rt_file, f.read())
1013 if name.endswith(".c"):
1014 shared_cfilenames.append(rt_file)
1015
1016 extensions = []
1017 extra_include_dirs = [os.path.join(include_dir(), dir) for dir in include_dirs]
1018 for (group_sources, lib_name), (cfilenames, deps) in zip(groups, group_cfilenames):
1019 if lib_name:
1020 extensions.extend(
1021 build_using_shared_lib(
1022 group_sources,
1023 lib_name,
1024 cfilenames + shared_cfilenames,
1025 deps,
1026 build_dir,
1027 cflags,
1028 extra_include_dirs,
1029 )
1030 )
1031 else:
1032 extensions.extend(
1033 build_single_module(
1034 group_sources, cfilenames + shared_cfilenames, cflags, extra_include_dirs
1035 )
1036 )
1037
1038 if install_librt:
1039 for name in RUNTIME_C_FILES:
1040 rt_file = os.path.join(build_dir, name)
1041 with open(os.path.join(include_dir(), name), encoding="utf-8") as f:
1042 write_file(rt_file, f.read())
1043 for mod, file_names, addit_files, includes in LIBRT_MODULES:
1044 for file_name in file_names + addit_files:
1045 rt_file = os.path.join(build_dir, file_name)
1046 with open(os.path.join(include_dir(), file_name), encoding="utf-8") as f:
1047 write_file(rt_file, f.read())
1048 extensions.append(
1049 get_extension()(
1050 mod,
1051 sources=[
1052 os.path.join(build_dir, file) for file in file_names + RUNTIME_C_FILES
1053 ],
1054 include_dirs=[include_dir()]
1055 + [os.path.join(include_dir(), d) for d in includes],
1056 extra_compile_args=cflags,
1057 )
1058 )
1059
1060 # Tag every extension we own so the build_ext patch knows it's
1061 # safe to skip the redundant inplace copy for these specifically.
1062 for ext in extensions:
1063 setattr(ext, _MYPYC_EXTENSION_MARKER, True)
1064
1065 return extensions