build.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. """Support for building extensions using mypyc with distutils or setuptools
  2. The main entry point is mypycify, which produces a list of extension
  3. modules to be passed to setup. A trivial setup.py for a mypyc built
  4. project, then, looks like:
  5. from setuptools import setup
  6. from mypyc.build import mypycify
  7. setup(name='test_module',
  8. ext_modules=mypycify(['foo.py']),
  9. )
  10. See the mypycify docs for additional arguments.
  11. mypycify can integrate with either distutils or setuptools, but needs
  12. to know at import-time whether it is using distutils or setuputils. We
  13. hackily decide based on whether setuptools has been imported already.
  14. """
  15. from __future__ import annotations
  16. import hashlib
  17. import os.path
  18. import re
  19. import sys
  20. import time
  21. from typing import TYPE_CHECKING, Any, Dict, Iterable, NoReturn, Union, cast
  22. from mypy.build import BuildSource
  23. from mypy.errors import CompileError
  24. from mypy.fscache import FileSystemCache
  25. from mypy.main import process_options
  26. from mypy.options import Options
  27. from mypy.util import write_junit_xml
  28. from mypyc.codegen import emitmodule
  29. from mypyc.common import RUNTIME_C_FILES, shared_lib_name
  30. from mypyc.errors import Errors
  31. from mypyc.ir.pprint import format_modules
  32. from mypyc.namegen import exported_name
  33. from mypyc.options import CompilerOptions
  34. if TYPE_CHECKING:
  35. from distutils.core import Extension as _distutils_Extension
  36. from typing_extensions import TypeAlias
  37. from setuptools import Extension as _setuptools_Extension
  38. Extension: TypeAlias = Union[_setuptools_Extension, _distutils_Extension]
  39. try:
  40. # Import setuptools so that it monkey-patch overrides distutils
  41. import setuptools
  42. except ImportError:
  43. if sys.version_info >= (3, 12):
  44. # Raise on Python 3.12, since distutils will go away forever
  45. raise
  46. from distutils import ccompiler, sysconfig
  47. def get_extension() -> type[Extension]:
  48. # We can work with either setuptools or distutils, and pick setuptools
  49. # if it has been imported.
  50. use_setuptools = "setuptools" in sys.modules
  51. extension_class: type[Extension]
  52. if not use_setuptools:
  53. import distutils.core
  54. extension_class = distutils.core.Extension
  55. else:
  56. extension_class = setuptools.Extension
  57. return extension_class
  58. def setup_mypycify_vars() -> None:
  59. """Rewrite a bunch of config vars in pretty dubious ways."""
  60. # There has to be a better approach to this.
  61. # The vars can contain ints but we only work with str ones
  62. vars = cast(Dict[str, str], sysconfig.get_config_vars())
  63. if sys.platform == "darwin":
  64. # Disable building 32-bit binaries, since we generate too much code
  65. # for a 32-bit Mach-O object. There has to be a better way to do this.
  66. vars["LDSHARED"] = vars["LDSHARED"].replace("-arch i386", "")
  67. vars["LDFLAGS"] = vars["LDFLAGS"].replace("-arch i386", "")
  68. vars["CFLAGS"] = vars["CFLAGS"].replace("-arch i386", "")
  69. def fail(message: str) -> NoReturn:
  70. # TODO: Is there something else we should do to fail?
  71. sys.exit(message)
  72. def emit_messages(options: Options, messages: list[str], dt: float, serious: bool = False) -> None:
  73. # ... you know, just in case.
  74. if options.junit_xml:
  75. py_version = f"{options.python_version[0]}_{options.python_version[1]}"
  76. write_junit_xml(dt, serious, messages, options.junit_xml, py_version, options.platform)
  77. if messages:
  78. print("\n".join(messages))
  79. def get_mypy_config(
  80. mypy_options: list[str],
  81. only_compile_paths: Iterable[str] | None,
  82. compiler_options: CompilerOptions,
  83. fscache: FileSystemCache | None,
  84. ) -> tuple[list[BuildSource], list[BuildSource], Options]:
  85. """Construct mypy BuildSources and Options from file and options lists"""
  86. all_sources, options = process_options(mypy_options, fscache=fscache)
  87. if only_compile_paths is not None:
  88. paths_set = set(only_compile_paths)
  89. mypyc_sources = [s for s in all_sources if s.path in paths_set]
  90. else:
  91. mypyc_sources = all_sources
  92. if compiler_options.separate:
  93. mypyc_sources = [
  94. src for src in mypyc_sources if src.path and not src.path.endswith("__init__.py")
  95. ]
  96. if not mypyc_sources:
  97. return mypyc_sources, all_sources, options
  98. # Override whatever python_version is inferred from the .ini file,
  99. # and set the python_version to be the currently used version.
  100. options.python_version = sys.version_info[:2]
  101. if options.python_version[0] == 2:
  102. fail("Python 2 not supported")
  103. if not options.strict_optional:
  104. fail("Disabling strict optional checking not supported")
  105. options.show_traceback = True
  106. # Needed to get types for all AST nodes
  107. options.export_types = True
  108. # We use mypy incremental mode when doing separate/incremental mypyc compilation
  109. options.incremental = compiler_options.separate
  110. options.preserve_asts = True
  111. for source in mypyc_sources:
  112. options.per_module_options.setdefault(source.module, {})["mypyc"] = True
  113. return mypyc_sources, all_sources, options
  114. def generate_c_extension_shim(
  115. full_module_name: str, module_name: str, dir_name: str, group_name: str
  116. ) -> str:
  117. """Create a C extension shim with a passthrough PyInit function.
  118. Arguments:
  119. full_module_name: the dotted full module name
  120. module_name: the final component of the module name
  121. dir_name: the directory to place source code
  122. group_name: the name of the group
  123. """
  124. cname = "%s.c" % full_module_name.replace(".", os.sep)
  125. cpath = os.path.join(dir_name, cname)
  126. # We load the C extension shim template from a file.
  127. # (So that the file could be reused as a bazel template also.)
  128. with open(os.path.join(include_dir(), "module_shim.tmpl")) as f:
  129. shim_template = f.read()
  130. write_file(
  131. cpath,
  132. shim_template.format(
  133. modname=module_name,
  134. libname=shared_lib_name(group_name),
  135. full_modname=exported_name(full_module_name),
  136. ),
  137. )
  138. return cpath
  139. def group_name(modules: list[str]) -> str:
  140. """Produce a probably unique name for a group from a list of module names."""
  141. if len(modules) == 1:
  142. return modules[0]
  143. h = hashlib.sha1()
  144. h.update(",".join(modules).encode())
  145. return h.hexdigest()[:20]
  146. def include_dir() -> str:
  147. """Find the path of the lib-rt dir that needs to be included"""
  148. return os.path.join(os.path.abspath(os.path.dirname(__file__)), "lib-rt")
  149. def generate_c(
  150. sources: list[BuildSource],
  151. options: Options,
  152. groups: emitmodule.Groups,
  153. fscache: FileSystemCache,
  154. compiler_options: CompilerOptions,
  155. ) -> tuple[list[list[tuple[str, str]]], str]:
  156. """Drive the actual core compilation step.
  157. The groups argument describes how modules are assigned to C
  158. extension modules. See the comments on the Groups type in
  159. mypyc.emitmodule for details.
  160. Returns the C source code and (for debugging) the pretty printed IR.
  161. """
  162. t0 = time.time()
  163. try:
  164. result = emitmodule.parse_and_typecheck(
  165. sources, options, compiler_options, groups, fscache
  166. )
  167. except CompileError as e:
  168. emit_messages(options, e.messages, time.time() - t0, serious=(not e.use_stdout))
  169. sys.exit(1)
  170. t1 = time.time()
  171. if result.errors:
  172. emit_messages(options, result.errors, t1 - t0)
  173. sys.exit(1)
  174. if compiler_options.verbose:
  175. print(f"Parsed and typechecked in {t1 - t0:.3f}s")
  176. errors = Errors(options)
  177. modules, ctext = emitmodule.compile_modules_to_c(
  178. result, compiler_options=compiler_options, errors=errors, groups=groups
  179. )
  180. t2 = time.time()
  181. emit_messages(options, errors.new_messages(), t2 - t1)
  182. if errors.num_errors:
  183. # No need to stop the build if only warnings were emitted.
  184. sys.exit(1)
  185. if compiler_options.verbose:
  186. print(f"Compiled to C in {t2 - t1:.3f}s")
  187. return ctext, "\n".join(format_modules(modules))
  188. def build_using_shared_lib(
  189. sources: list[BuildSource],
  190. group_name: str,
  191. cfiles: list[str],
  192. deps: list[str],
  193. build_dir: str,
  194. extra_compile_args: list[str],
  195. ) -> list[Extension]:
  196. """Produce the list of extension modules when a shared library is needed.
  197. This creates one shared library extension module that all of the
  198. others import and then one shim extension module for each
  199. module in the build, that simply calls an initialization function
  200. in the shared library.
  201. The shared library (which lib_name is the name of) is a python
  202. extension module that exports the real initialization functions in
  203. Capsules stored in module attributes.
  204. """
  205. extensions = [
  206. get_extension()(
  207. shared_lib_name(group_name),
  208. sources=cfiles,
  209. include_dirs=[include_dir(), build_dir],
  210. depends=deps,
  211. extra_compile_args=extra_compile_args,
  212. )
  213. ]
  214. for source in sources:
  215. module_name = source.module.split(".")[-1]
  216. shim_file = generate_c_extension_shim(source.module, module_name, build_dir, group_name)
  217. # We include the __init__ in the "module name" we stick in the Extension,
  218. # since this seems to be needed for it to end up in the right place.
  219. full_module_name = source.module
  220. assert source.path
  221. if os.path.split(source.path)[1] == "__init__.py":
  222. full_module_name += ".__init__"
  223. extensions.append(
  224. get_extension()(
  225. full_module_name, sources=[shim_file], extra_compile_args=extra_compile_args
  226. )
  227. )
  228. return extensions
  229. def build_single_module(
  230. sources: list[BuildSource], cfiles: list[str], extra_compile_args: list[str]
  231. ) -> list[Extension]:
  232. """Produce the list of extension modules for a standalone extension.
  233. This contains just one module, since there is no need for a shared module.
  234. """
  235. return [
  236. get_extension()(
  237. sources[0].module,
  238. sources=cfiles,
  239. include_dirs=[include_dir()],
  240. extra_compile_args=extra_compile_args,
  241. )
  242. ]
  243. def write_file(path: str, contents: str) -> None:
  244. """Write data into a file.
  245. If the file already exists and has the same contents we
  246. want to write, skip writing so as to preserve the mtime
  247. and avoid triggering recompilation.
  248. """
  249. # We encode it ourselves and open the files as binary to avoid windows
  250. # newline translation
  251. encoded_contents = contents.encode("utf-8")
  252. try:
  253. with open(path, "rb") as f:
  254. old_contents: bytes | None = f.read()
  255. except OSError:
  256. old_contents = None
  257. if old_contents != encoded_contents:
  258. os.makedirs(os.path.dirname(path), exist_ok=True)
  259. with open(path, "wb") as g:
  260. g.write(encoded_contents)
  261. # Fudge the mtime forward because otherwise when two builds happen close
  262. # together (like in a test) setuptools might not realize the source is newer
  263. # than the new artifact.
  264. # XXX: This is bad though.
  265. new_mtime = os.stat(path).st_mtime + 1
  266. os.utime(path, times=(new_mtime, new_mtime))
  267. def construct_groups(
  268. sources: list[BuildSource],
  269. separate: bool | list[tuple[list[str], str | None]],
  270. use_shared_lib: bool,
  271. ) -> emitmodule.Groups:
  272. """Compute Groups given the input source list and separate configs.
  273. separate is the user-specified configuration for how to assign
  274. modules to compilation groups (see mypycify docstring for details).
  275. This takes that and expands it into our internal representation of
  276. group configuration, documented in mypyc.emitmodule's definition
  277. of Group.
  278. """
  279. if separate is True:
  280. groups: emitmodule.Groups = [([source], None) for source in sources]
  281. elif isinstance(separate, list):
  282. groups = []
  283. used_sources = set()
  284. for files, name in separate:
  285. group_sources = [src for src in sources if src.path in files]
  286. groups.append((group_sources, name))
  287. used_sources.update(group_sources)
  288. unused_sources = [src for src in sources if src not in used_sources]
  289. if unused_sources:
  290. groups.extend([([source], None) for source in unused_sources])
  291. else:
  292. groups = [(sources, None)]
  293. # Generate missing names
  294. for i, (group, name) in enumerate(groups):
  295. if use_shared_lib and not name:
  296. name = group_name([source.module for source in group])
  297. groups[i] = (group, name)
  298. return groups
  299. def get_header_deps(cfiles: list[tuple[str, str]]) -> list[str]:
  300. """Find all the headers used by a group of cfiles.
  301. We do this by just regexping the source, which is a bit simpler than
  302. properly plumbing the data through.
  303. Arguments:
  304. cfiles: A list of (file name, file contents) pairs.
  305. """
  306. headers: set[str] = set()
  307. for _, contents in cfiles:
  308. headers.update(re.findall(r'#include "(.*)"', contents))
  309. return sorted(headers)
  310. def mypyc_build(
  311. paths: list[str],
  312. compiler_options: CompilerOptions,
  313. *,
  314. separate: bool | list[tuple[list[str], str | None]] = False,
  315. only_compile_paths: Iterable[str] | None = None,
  316. skip_cgen_input: Any | None = None,
  317. always_use_shared_lib: bool = False,
  318. ) -> tuple[emitmodule.Groups, list[tuple[list[str], list[str]]]]:
  319. """Do the front and middle end of mypyc building, producing and writing out C source."""
  320. fscache = FileSystemCache()
  321. mypyc_sources, all_sources, options = get_mypy_config(
  322. paths, only_compile_paths, compiler_options, fscache
  323. )
  324. # We generate a shared lib if there are multiple modules or if any
  325. # of the modules are in package. (Because I didn't want to fuss
  326. # around with making the single module code handle packages.)
  327. use_shared_lib = (
  328. len(mypyc_sources) > 1
  329. or any("." in x.module for x in mypyc_sources)
  330. or always_use_shared_lib
  331. )
  332. groups = construct_groups(mypyc_sources, separate, use_shared_lib)
  333. # We let the test harness just pass in the c file contents instead
  334. # so that it can do a corner-cutting version without full stubs.
  335. if not skip_cgen_input:
  336. group_cfiles, ops_text = generate_c(
  337. all_sources, options, groups, fscache, compiler_options=compiler_options
  338. )
  339. # TODO: unique names?
  340. write_file(os.path.join(compiler_options.target_dir, "ops.txt"), ops_text)
  341. else:
  342. group_cfiles = skip_cgen_input
  343. # Write out the generated C and collect the files for each group
  344. # Should this be here??
  345. group_cfilenames: list[tuple[list[str], list[str]]] = []
  346. for cfiles in group_cfiles:
  347. cfilenames = []
  348. for cfile, ctext in cfiles:
  349. cfile = os.path.join(compiler_options.target_dir, cfile)
  350. write_file(cfile, ctext)
  351. if os.path.splitext(cfile)[1] == ".c":
  352. cfilenames.append(cfile)
  353. deps = [os.path.join(compiler_options.target_dir, dep) for dep in get_header_deps(cfiles)]
  354. group_cfilenames.append((cfilenames, deps))
  355. return groups, group_cfilenames
  356. def mypycify(
  357. paths: list[str],
  358. *,
  359. only_compile_paths: Iterable[str] | None = None,
  360. verbose: bool = False,
  361. opt_level: str = "3",
  362. debug_level: str = "1",
  363. strip_asserts: bool = False,
  364. multi_file: bool = False,
  365. separate: bool | list[tuple[list[str], str | None]] = False,
  366. skip_cgen_input: Any | None = None,
  367. target_dir: str | None = None,
  368. include_runtime_files: bool | None = None,
  369. ) -> list[Extension]:
  370. """Main entry point to building using mypyc.
  371. This produces a list of Extension objects that should be passed as the
  372. ext_modules parameter to setup.
  373. Arguments:
  374. paths: A list of file paths to build. It may also contain mypy options.
  375. only_compile_paths: If not None, an iterable of paths that are to be
  376. the only modules compiled, even if other modules
  377. appear in the mypy command line given to paths.
  378. (These modules must still be passed to paths.)
  379. verbose: Should mypyc be more verbose. Defaults to false.
  380. opt_level: The optimization level, as a string. Defaults to '3' (meaning '-O3').
  381. debug_level: The debug level, as a string. Defaults to '1' (meaning '-g1').
  382. strip_asserts: Should asserts be stripped from the generated code.
  383. multi_file: Should each Python module be compiled into its own C source file.
  384. This can reduce compile time and memory requirements at the likely
  385. cost of runtime performance of compiled code. Defaults to false.
  386. separate: Should compiled modules be placed in separate extension modules.
  387. If False, all modules are placed in a single shared library.
  388. If True, every module is placed in its own library.
  389. Otherwise separate should be a list of
  390. (file name list, optional shared library name) pairs specifying
  391. groups of files that should be placed in the same shared library
  392. (while all other modules will be placed in its own library).
  393. Each group can be compiled independently, which can
  394. speed up compilation, but calls between groups can
  395. be slower than calls within a group and can't be
  396. inlined.
  397. target_dir: The directory to write C output files. Defaults to 'build'.
  398. include_runtime_files: If not None, whether the mypyc runtime library
  399. should be directly #include'd instead of linked
  400. separately in order to reduce compiler invocations.
  401. Defaults to False in multi_file mode, True otherwise.
  402. """
  403. # Figure out our configuration
  404. compiler_options = CompilerOptions(
  405. strip_asserts=strip_asserts,
  406. multi_file=multi_file,
  407. verbose=verbose,
  408. separate=separate is not False,
  409. target_dir=target_dir,
  410. include_runtime_files=include_runtime_files,
  411. )
  412. # Generate all the actual important C code
  413. groups, group_cfilenames = mypyc_build(
  414. paths,
  415. only_compile_paths=only_compile_paths,
  416. compiler_options=compiler_options,
  417. separate=separate,
  418. skip_cgen_input=skip_cgen_input,
  419. )
  420. # Mess around with setuptools and actually get the thing built
  421. setup_mypycify_vars()
  422. # Create a compiler object so we can make decisions based on what
  423. # compiler is being used. typeshed is missing some attributes on the
  424. # compiler object so we give it type Any
  425. compiler: Any = ccompiler.new_compiler()
  426. sysconfig.customize_compiler(compiler)
  427. build_dir = compiler_options.target_dir
  428. cflags: list[str] = []
  429. if compiler.compiler_type == "unix":
  430. cflags += [
  431. f"-O{opt_level}",
  432. f"-g{debug_level}",
  433. "-Werror",
  434. "-Wno-unused-function",
  435. "-Wno-unused-label",
  436. "-Wno-unreachable-code",
  437. "-Wno-unused-variable",
  438. "-Wno-unused-command-line-argument",
  439. "-Wno-unknown-warning-option",
  440. "-Wno-unused-but-set-variable",
  441. "-Wno-ignored-optimization-argument",
  442. # Disables C Preprocessor (cpp) warnings
  443. # See https://github.com/mypyc/mypyc/issues/956
  444. "-Wno-cpp",
  445. ]
  446. elif compiler.compiler_type == "msvc":
  447. # msvc doesn't have levels, '/O2' is full and '/Od' is disable
  448. if opt_level == "0":
  449. opt_level = "d"
  450. elif opt_level in ("1", "2", "3"):
  451. opt_level = "2"
  452. if debug_level == "0":
  453. debug_level = "NONE"
  454. elif debug_level == "1":
  455. debug_level = "FASTLINK"
  456. elif debug_level in ("2", "3"):
  457. debug_level = "FULL"
  458. cflags += [
  459. f"/O{opt_level}",
  460. f"/DEBUG:{debug_level}",
  461. "/wd4102", # unreferenced label
  462. "/wd4101", # unreferenced local variable
  463. "/wd4146", # negating unsigned int
  464. ]
  465. if multi_file:
  466. # Disable whole program optimization in multi-file mode so
  467. # that we actually get the compilation speed and memory
  468. # use wins that multi-file mode is intended for.
  469. cflags += ["/GL-", "/wd9025"] # warning about overriding /GL
  470. # If configured to (defaults to yes in multi-file mode), copy the
  471. # runtime library in. Otherwise it just gets #included to save on
  472. # compiler invocations.
  473. shared_cfilenames = []
  474. if not compiler_options.include_runtime_files:
  475. for name in RUNTIME_C_FILES:
  476. rt_file = os.path.join(build_dir, name)
  477. with open(os.path.join(include_dir(), name), encoding="utf-8") as f:
  478. write_file(rt_file, f.read())
  479. shared_cfilenames.append(rt_file)
  480. extensions = []
  481. for (group_sources, lib_name), (cfilenames, deps) in zip(groups, group_cfilenames):
  482. if lib_name:
  483. extensions.extend(
  484. build_using_shared_lib(
  485. group_sources,
  486. lib_name,
  487. cfilenames + shared_cfilenames,
  488. deps,
  489. build_dir,
  490. cflags,
  491. )
  492. )
  493. else:
  494. extensions.extend(
  495. build_single_module(group_sources, cfilenames + shared_cfilenames, cflags)
  496. )
  497. return extensions