MLIR 23.0.0git
stubgen_runner.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Generates .pyi stubs for nanobind extensions using nanobind's stubgen."""
3
4import argparse
5import ctypes
6import importlib.util
7import sys
8from pathlib import Path
9
10from python.runfiles import Runfiles
11
12
13def load_extension(path: Path):
14 """Load an extension module from a .so file with RTLD_GLOBAL."""
15 module_name = path.stem.removesuffix(".abi3")
16
17 # Load with RTLD_GLOBAL so symbols are available to dependent extensions.
18 ctypes.CDLL(str(path), mode=ctypes.RTLD_GLOBAL)
19
20 spec = importlib.util.spec_from_file_location(module_name, path)
21 if spec is None or spec.loader is None:
22 sys.exit(f"Failed to load extension from {path}")
23
24 module = importlib.util.module_from_spec(spec)
25 sys.modules[module_name] = module
26 spec.loader.exec_module(module)
27 return module_name
28
29
30def main():
31 parser = argparse.ArgumentParser()
32 parser.add_argument(
33 "--module", required=True, help="Module name to generate stubs for"
34 )
35 parser.add_argument(
36 "--deps", required=True, help="Comma-separated .so files to load"
37 )
38 parser.add_argument("-o", "--output", required=True, help="Output directory")
39 args = parser.parse_args()
40
41 for dep_path in args.deps.split(","):
42 load_extension(Path(dep_path).resolve())
43
44 runfiles = Runfiles.Create()
45 stubgen_path = runfiles.Rlocation("+llvm_repos_extension+nanobind/src/stubgen.py")
46 spec = importlib.util.spec_from_file_location("stubgen", stubgen_path)
47 stubgen = importlib.util.module_from_spec(spec)
48 sys.modules["stubgen"] = stubgen
49 spec.loader.exec_module(stubgen)
50 stubgen.main(["-m", args.module, "-r", "-O", args.output])
51
52
53if __name__ == "__main__":
54 main()
load_extension(Path path)