GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [mypyc] Enable incremental self-compilation (#21369) · python/mypy@db297c5

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • mypyc
    • build.py
    • codegen
      • emit.py
      • emitfunc.py
      • emitmodule.py
    • irbuild
      • prepare.py
    • lib-rt
      • misc_ops.c
  • setup.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎mypyc/build.py‎

Copy file name to clipboardExpand all lines: mypyc/build.py
+84-3Lines changed: 84 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,70 @@ def write_file(path: str, contents: str) -> None:
450450
os.utime(path, times=(new_mtime, new_mtime))
451451

452452

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+
453517
def construct_groups(
454518
sources: list[BuildSource],
455519
separate: bool | list[tuple[list[str], str | None]],
@@ -513,7 +577,7 @@ def get_header_deps(cfiles: list[tuple[str, str]]) -> list[str]:
513577
"""
514578
headers: set[str] = set()
515579
for _, contents in cfiles:
516-
headers.update(re.findall(r'#include "(.*)"', contents))
580+
headers.update(re.findall(r'#include [<"]([^>"]+)[>"]', contents))
517581

518582
return sorted(headers)
519583

@@ -573,12 +637,21 @@ def mypyc_build(
573637
cfilenames = []
574638
for cfile, ctext in cfiles:
575639
cfile = os.path.join(compiler_options.target_dir, cfile)
576-
if not options.mypyc_skip_c_generation:
640+
# Empty contents marks a file the previous run already wrote
641+
# (fully-cached group): skip the rewrite and just reuse it.
642+
if ctext and not options.mypyc_skip_c_generation:
577643
write_file(cfile, ctext)
578644
if os.path.splitext(cfile)[1] == ".c":
579645
cfilenames.append(cfile)
580646

581-
deps = [os.path.join(compiler_options.target_dir, dep) for dep in get_header_deps(cfiles)]
647+
# The header regex matches both quote styles, so the result can
648+
# include system headers like `<Python.h>` that don't live under
649+
# target_dir. Joining those produces non-existent paths which
650+
# would force a full rebuild on every run via Extension.depends.
651+
candidate_deps = (
652+
os.path.join(compiler_options.target_dir, dep) for dep in get_header_deps(cfiles)
653+
)
654+
deps = [d for d in candidate_deps if os.path.exists(d)]
582655
group_cfilenames.append((cfilenames, deps))
583656

584657
return groups, group_cfilenames, source_deps
@@ -755,6 +828,9 @@ def mypycify(
755828
have no backward compatibility guarantees!
756829
"""
757830

831+
# Skip redundant inplace .so copies on every build_ext invocation.
832+
_patch_setuptools_copy_extensions_to_source()
833+
758834
# Figure out our configuration
759835
compiler_options = CompilerOptions(
760836
strip_asserts=strip_asserts,
@@ -869,4 +945,9 @@ def mypycify(
869945
)
870946
)
871947

948+
# Tag every extension we own so the build_ext patch knows it's
949+
# safe to skip the redundant inplace copy for these specifically.
950+
for ext in extensions:
951+
setattr(ext, _MYPYC_EXTENSION_MARKER, True)
952+
872953
return extensions
Collapse file

‎mypyc/codegen/emit.py‎

Copy file name to clipboardExpand all lines: mypyc/codegen/emit.py
+12Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,18 @@ def get_group_prefix(self, obj: ClassIR | FuncDecl) -> str:
326326
# See docs above
327327
return self.get_module_group_prefix(obj.module_name)
328328

329+
def register_group_dep(self, cl: ClassIR) -> None:
330+
"""Record `cl`'s defining group as a cross-group dep, if any.
331+
332+
Call this when emitting code that refers to `cl`'s struct
333+
layout: the .c file consuming that layout needs the defining
334+
group's `__native_*.h` included, and group_deps drives which
335+
headers get pulled in.
336+
"""
337+
target_group = self.context.group_map.get(cl.module_name)
338+
if target_group and target_group != self.context.group_name:
339+
self.context.group_deps.add(target_group)
340+
329341
def static_name(self, id: str, module: str | None, prefix: str = STATIC_PREFIX) -> str:
330342
"""Create name of a C static variable.
331343
Collapse file

‎mypyc/codegen/emitfunc.py‎

Copy file name to clipboardExpand all lines: mypyc/codegen/emitfunc.py
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,11 @@ def get_attr_expr(self, obj: str, op: GetAttr | SetAttr, decl_cl: ClassIR) -> st
360360
classes, and *(obj + attr_offset) for attributes defined by traits. We also
361361
insert all necessary C casts here.
362362
"""
363+
# The struct cast below needs the defining group's __native.h
364+
# included by the consuming .c file. Record both the receiver
365+
# and declaring classes as cross-group deps.
366+
self.emitter.register_group_dep(op.class_type.class_ir)
367+
self.emitter.register_group_dep(decl_cl)
363368
cast = f"({op.class_type.struct_name(self.emitter.names)} *)"
364369
if decl_cl.is_trait and op.class_type.class_ir.is_trait:
365370
# For pure trait access find the offset first, offsets
Collapse file

‎mypyc/codegen/emitmodule.py‎

Copy file name to clipboardExpand all lines: mypyc/codegen/emitmodule.py
+39-5Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,12 @@ def compile_ir_to_c(
363363
if source.module in modules
364364
}
365365
if not group_modules:
366-
ctext[group_name] = []
366+
# Fully-cached group (e.g. pip's second setup.py invoke for
367+
# the wheel phase): no fresh IR was produced. Reuse the file
368+
# list recorded in any module's IR cache so the linker still
369+
# sees the previous run's outputs; empty content is a "do
370+
# not rewrite" sentinel for mypyc_build.
371+
ctext[group_name] = _load_cached_group_files(group_sources, result)
367372
continue
368373
generator = GroupGenerator(
369374
group_modules, source_paths, group_name, mapper.group_map, names, compiler_options
@@ -373,6 +378,32 @@ def compile_ir_to_c(
373378
return ctext
374379

375380

381+
def _load_cached_group_files(
382+
group_sources: list[BuildSource], result: BuildResult
383+
) -> list[tuple[str, str]]:
384+
"""Read the .c/.h paths recorded for this group on the previous run.
385+
386+
All modules in a group share the same src_hashes map, so the first
387+
readable IR cache is sufficient. Returns paths paired with empty
388+
content so callers can distinguish "reuse on disk" from "newly
389+
generated".
390+
"""
391+
for source in group_sources:
392+
state = result.graph.get(source.module)
393+
if state is None:
394+
continue
395+
try:
396+
ir_json = result.manager.metastore.read(get_state_ir_cache_name(state))
397+
except (FileNotFoundError, OSError):
398+
continue
399+
try:
400+
ir_data = json.loads(ir_json)
401+
except json.JSONDecodeError:
402+
continue
403+
return [(path, "") for path in ir_data.get("src_hashes", {})]
404+
return []
405+
406+
376407
def get_ir_cache_name(id: str, path: str, options: Options) -> str:
377408
meta_path, _, _ = get_cache_names(id, path, options)
378409
# Mypyc uses JSON cache even with --fixed-format-cache (for now).
@@ -615,16 +646,19 @@ def generate_c_for_modules(self) -> list[tuple[str, str]]:
615646

616647
base_emitter = Emitter(self.context)
617648
# Optionally just include the runtime library c files to
618-
# reduce the number of compiler invocations needed
649+
# reduce the number of compiler invocations needed.
650+
# Use <> form (only -I paths) so a shim file with the same
651+
# basename as a runtime file can't shadow it. Triggered by
652+
# mypyc/lower/int_ops.py vs lib-rt/int_ops.c on mypy self-compile.
619653
if self.compiler_options.include_runtime_files:
620654
for name in RUNTIME_C_FILES:
621-
base_emitter.emit_line(f'#include "{name}"')
655+
base_emitter.emit_line(f"#include <{name}>")
622656
# Include conditional source files
623657
source_deps = collect_source_dependencies(self.modules)
624658
for source_dep in sorted(source_deps, key=lambda d: d.path):
625-
base_emitter.emit_line(f'#include "{source_dep.path}"')
659+
base_emitter.emit_line(f"#include <{source_dep.path}>")
626660
if self.compiler_options.depends_on_librt_internal:
627-
base_emitter.emit_line('#include "internal/librt_internal_api.c"')
661+
base_emitter.emit_line("#include <internal/librt_internal_api.c>")
628662
base_emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"')
629663
base_emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"')
630664
emitter = base_emitter
Collapse file

‎mypyc/irbuild/prepare.py‎

Copy file name to clipboardExpand all lines: mypyc/irbuild/prepare.py
+6-1Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,12 @@ def load_type_map(mapper: Mapper, modules: list[MypyFile], deser_ctx: DeserMaps)
182182
continue
183183
mapper.type_to_ir[node.node] = ir
184184
mapper.symbol_fullnames.add(node.node.fullname)
185-
mapper.func_to_decl[node.node] = ir.ctor
185+
# Trait/builtin-base classes have an ir.ctor FuncDecl
186+
# but no emitted CPyDef_<ctor>, so a cross-group direct
187+
# call would hit an undefined symbol. Mirror the skip
188+
# in prepare_init_method.
189+
if not ir.is_trait and not ir.builtin_base:
190+
mapper.func_to_decl[node.node] = ir.ctor
186191

187192
for module in modules:
188193
for func in get_module_func_defs(module):
Collapse file

‎mypyc/lib-rt/misc_ops.c‎

Copy file name to clipboardExpand all lines: mypyc/lib-rt/misc_ops.c
+50-10Lines changed: 50 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1281,12 +1281,17 @@ static int CPyImport_SetModuleFile(PyObject *modobj, PyObject *module_name,
12811281
Py_DECREF(file);
12821282
return 0;
12831283
}
1284-
// Derive __file__ from the shared library's __file__ (for its
1285-
// directory), the module name (dots -> path separators), and the
1286-
// extension suffix. E.g. for module "a.b.c", shared lib
1287-
// "/path/to/group__mypyc.cpython-312-x86_64-linux-gnu.so",
1288-
// suffix ".cpython-312-x86_64-linux-gnu.so":
1289-
// => "/path/to/a/b/c.cpython-312-x86_64-linux-gnu.so"
1284+
// Derive __file__ from the shared lib's directory, the module
1285+
// name, and the extension suffix. Two layouts:
1286+
//
1287+
// Monolithic: one shared lib above the package tree holds many
1288+
// modules, so append the full dotted module path.
1289+
// separate=True: each module has its own "<segment>__mypyc.so"
1290+
// next to the module, so dirname(shared_lib) is already inside
1291+
// the parent package. Append only the last segment.
1292+
//
1293+
// Detect the separate=True case by matching the shared lib's
1294+
// basename against "<last_segment>__mypyc<ext>".
12901295
PyObject *derived_file = NULL;
12911296
if (shared_lib_file != NULL && shared_lib_file != Py_None &&
12921297
PyUnicode_Check(shared_lib_file)) {
@@ -1314,30 +1319,65 @@ static int CPyImport_SetModuleFile(PyObject *modobj, PyObject *module_name,
13141319
if (module_path == NULL) {
13151320
return -1;
13161321
}
1322+
1323+
// Compute the module's last dotted segment for the separate=True check.
1324+
Py_ssize_t name_len = PyUnicode_GetLength(module_name);
1325+
Py_ssize_t last_dot = PyUnicode_FindChar(module_name, '.', 0, name_len, -1);
1326+
PyObject *last_segment;
1327+
if (last_dot >= 0) {
1328+
last_segment = PyUnicode_Substring(module_name, last_dot + 1, name_len);
1329+
} else {
1330+
last_segment = module_name;
1331+
Py_INCREF(last_segment);
1332+
}
1333+
if (last_segment == NULL) {
1334+
Py_DECREF(module_path);
1335+
return -1;
1336+
}
1337+
// Compare shared_lib_file basename against "<last_segment>__mypyc<ext>".
1338+
PyObject *expected_basename = PyUnicode_FromFormat(
1339+
"%U__mypyc%U", last_segment, ext_suffix);
1340+
PyObject *actual_basename;
1341+
if (sep >= 0) {
1342+
actual_basename = PyUnicode_Substring(shared_lib_file, sep + 1, sf_len);
1343+
} else {
1344+
actual_basename = shared_lib_file;
1345+
Py_INCREF(actual_basename);
1346+
}
1347+
int is_per_module_lib = 0;
1348+
if (expected_basename != NULL && actual_basename != NULL) {
1349+
is_per_module_lib =
1350+
(PyUnicode_Compare(expected_basename, actual_basename) == 0);
1351+
}
1352+
Py_XDECREF(expected_basename);
1353+
Py_XDECREF(actual_basename);
1354+
13171355
// For packages, __file__ should point to __init__<ext>,
13181356
// e.g. "a/b/__init__.cpython-312-x86_64-linux-gnu.so".
1357+
PyObject *file_path = is_per_module_lib ? last_segment : module_path;
13191358
if (sep >= 0) {
13201359
PyObject *dir = PyUnicode_Substring(shared_lib_file, 0, sep);
13211360
if (dir != NULL) {
13221361
if (is_package) {
13231362
derived_file = PyUnicode_FromFormat(
13241363
"%U%c%U%c__init__%U", dir, (int)sep_char,
1325-
module_path, (int)sep_char, ext_suffix);
1364+
file_path, (int)sep_char, ext_suffix);
13261365
} else {
13271366
derived_file = PyUnicode_FromFormat(
13281367
"%U%c%U%U", dir, (int)sep_char,
1329-
module_path, ext_suffix);
1368+
file_path, ext_suffix);
13301369
}
13311370
Py_DECREF(dir);
13321371
}
13331372
} else {
13341373
if (is_package) {
13351374
derived_file = PyUnicode_FromFormat(
1336-
"%U%c__init__%U", module_path, (int)SEP[0], ext_suffix);
1375+
"%U%c__init__%U", file_path, (int)SEP[0], ext_suffix);
13371376
} else {
1338-
derived_file = PyUnicode_FromFormat("%U%U", module_path, ext_suffix);
1377+
derived_file = PyUnicode_FromFormat("%U%U", file_path, ext_suffix);
13391378
}
13401379
}
1380+
Py_DECREF(last_segment);
13411381
Py_DECREF(module_path);
13421382
}
13431383
if (derived_file == NULL && !PyErr_Occurred()) {
Collapse file

‎setup.py‎

Copy file name to clipboardExpand all lines: setup.py
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ def run(self) -> None:
153153
debug_level = os.getenv("MYPYC_DEBUG_LEVEL", "1")
154154
force_multifile = os.getenv("MYPYC_MULTI_FILE", "") == "1"
155155
log_trace = bool(int(os.getenv("MYPYC_LOG_TRACE", "0")))
156+
separate = os.getenv("MYPYC_SEPARATE", "") == "1"
156157
ext_modules = mypycify(
157158
mypyc_targets + ["--config-file=mypy_bootstrap.ini"],
158159
opt_level=opt_level,
@@ -161,6 +162,7 @@ def run(self) -> None:
161162
# our Appveyor builds run out of memory sometimes.
162163
multi_file=sys.platform == "win32" or force_multifile,
163164
log_trace=log_trace,
165+
separate=separate,
164166
# Mypy itself is allowed to use native_internal extension.
165167
depends_on_librt_internal=True,
166168
)

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.