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