base.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. """distutils.ccompiler
  2. Contains Compiler, an abstract base class that defines the interface
  3. for the Distutils compiler abstraction model."""
  4. from __future__ import annotations
  5. import os
  6. import pathlib
  7. import re
  8. import sys
  9. import warnings
  10. from collections.abc import Callable, Iterable, MutableSequence, Sequence
  11. from typing import (
  12. TYPE_CHECKING,
  13. ClassVar,
  14. Literal,
  15. TypeVar,
  16. Union,
  17. overload,
  18. )
  19. from more_itertools import always_iterable
  20. from ..._log import log
  21. from ..._modified import newer_group
  22. from ...dir_util import mkpath
  23. from ...errors import (
  24. DistutilsModuleError,
  25. DistutilsPlatformError,
  26. )
  27. from ...file_util import move_file
  28. from ...spawn import spawn
  29. from ...util import execute, is_mingw, split_quoted
  30. from .errors import (
  31. CompileError,
  32. LinkError,
  33. UnknownFileType,
  34. )
  35. if TYPE_CHECKING:
  36. from typing_extensions import TypeAlias, TypeVarTuple, Unpack
  37. _Ts = TypeVarTuple("_Ts")
  38. _Macro: TypeAlias = Union[tuple[str], tuple[str, Union[str, None]]]
  39. _StrPathT = TypeVar("_StrPathT", bound="str | os.PathLike[str]")
  40. _BytesPathT = TypeVar("_BytesPathT", bound="bytes | os.PathLike[bytes]")
  41. class Compiler:
  42. """Abstract base class to define the interface that must be implemented
  43. by real compiler classes. Also has some utility methods used by
  44. several compiler classes.
  45. The basic idea behind a compiler abstraction class is that each
  46. instance can be used for all the compile/link steps in building a
  47. single project. Thus, attributes common to all of those compile and
  48. link steps -- include directories, macros to define, libraries to link
  49. against, etc. -- are attributes of the compiler instance. To allow for
  50. variability in how individual files are treated, most of those
  51. attributes may be varied on a per-compilation or per-link basis.
  52. """
  53. # 'compiler_type' is a class attribute that identifies this class. It
  54. # keeps code that wants to know what kind of compiler it's dealing with
  55. # from having to import all possible compiler classes just to do an
  56. # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type'
  57. # should really, really be one of the keys of the 'compiler_class'
  58. # dictionary (see below -- used by the 'new_compiler()' factory
  59. # function) -- authors of new compiler interface classes are
  60. # responsible for updating 'compiler_class'!
  61. compiler_type: ClassVar[str] = None # type: ignore[assignment]
  62. # XXX things not handled by this compiler abstraction model:
  63. # * client can't provide additional options for a compiler,
  64. # e.g. warning, optimization, debugging flags. Perhaps this
  65. # should be the domain of concrete compiler abstraction classes
  66. # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
  67. # class should have methods for the common ones.
  68. # * can't completely override the include or library searchg
  69. # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
  70. # I'm not sure how widely supported this is even by Unix
  71. # compilers, much less on other platforms. And I'm even less
  72. # sure how useful it is; maybe for cross-compiling, but
  73. # support for that is a ways off. (And anyways, cross
  74. # compilers probably have a dedicated binary with the
  75. # right paths compiled in. I hope.)
  76. # * can't do really freaky things with the library list/library
  77. # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
  78. # different versions of libfoo.a in different locations. I
  79. # think this is useless without the ability to null out the
  80. # library search path anyways.
  81. executables: ClassVar[dict]
  82. # Subclasses that rely on the standard filename generation methods
  83. # implemented below should override these; see the comment near
  84. # those methods ('object_filenames()' et. al.) for details:
  85. src_extensions: ClassVar[list[str] | None] = None
  86. obj_extension: ClassVar[str | None] = None
  87. static_lib_extension: ClassVar[str | None] = None
  88. shared_lib_extension: ClassVar[str | None] = None
  89. static_lib_format: ClassVar[str | None] = None # format string
  90. shared_lib_format: ClassVar[str | None] = None # prob. same as static_lib_format
  91. exe_extension: ClassVar[str | None] = None
  92. # Default language settings. language_map is used to detect a source
  93. # file or Extension target language, checking source filenames.
  94. # language_order is used to detect the language precedence, when deciding
  95. # what language to use when mixing source types. For example, if some
  96. # extension has two files with ".c" extension, and one with ".cpp", it
  97. # is still linked as c++.
  98. language_map: ClassVar[dict[str, str]] = {
  99. ".c": "c",
  100. ".cc": "c++",
  101. ".cpp": "c++",
  102. ".cxx": "c++",
  103. ".m": "objc",
  104. }
  105. language_order: ClassVar[list[str]] = ["c++", "objc", "c"]
  106. include_dirs: list[str] = []
  107. """
  108. include dirs specific to this compiler class
  109. """
  110. library_dirs: list[str] = []
  111. """
  112. library dirs specific to this compiler class
  113. """
  114. def __init__(
  115. self, verbose: bool = False, dry_run: bool = False, force: bool = False
  116. ) -> None:
  117. self.dry_run = dry_run
  118. self.force = force
  119. self.verbose = verbose
  120. # 'output_dir': a common output directory for object, library,
  121. # shared object, and shared library files
  122. self.output_dir: str | None = None
  123. # 'macros': a list of macro definitions (or undefinitions). A
  124. # macro definition is a 2-tuple (name, value), where the value is
  125. # either a string or None (no explicit value). A macro
  126. # undefinition is a 1-tuple (name,).
  127. self.macros: list[_Macro] = []
  128. # 'include_dirs': a list of directories to search for include files
  129. self.include_dirs = []
  130. # 'libraries': a list of libraries to include in any link
  131. # (library names, not filenames: eg. "foo" not "libfoo.a")
  132. self.libraries: list[str] = []
  133. # 'library_dirs': a list of directories to search for libraries
  134. self.library_dirs = []
  135. # 'runtime_library_dirs': a list of directories to search for
  136. # shared libraries/objects at runtime
  137. self.runtime_library_dirs: list[str] = []
  138. # 'objects': a list of object files (or similar, such as explicitly
  139. # named library files) to include on any link
  140. self.objects: list[str] = []
  141. for key in self.executables.keys():
  142. self.set_executable(key, self.executables[key])
  143. def set_executables(self, **kwargs: str) -> None:
  144. """Define the executables (and options for them) that will be run
  145. to perform the various stages of compilation. The exact set of
  146. executables that may be specified here depends on the compiler
  147. class (via the 'executables' class attribute), but most will have:
  148. compiler the C/C++ compiler
  149. linker_so linker used to create shared objects and libraries
  150. linker_exe linker used to create binary executables
  151. archiver static library creator
  152. On platforms with a command-line (Unix, DOS/Windows), each of these
  153. is a string that will be split into executable name and (optional)
  154. list of arguments. (Splitting the string is done similarly to how
  155. Unix shells operate: words are delimited by spaces, but quotes and
  156. backslashes can override this. See
  157. 'distutils.util.split_quoted()'.)
  158. """
  159. # Note that some CCompiler implementation classes will define class
  160. # attributes 'cpp', 'cc', etc. with hard-coded executable names;
  161. # this is appropriate when a compiler class is for exactly one
  162. # compiler/OS combination (eg. MSVCCompiler). Other compiler
  163. # classes (UnixCCompiler, in particular) are driven by information
  164. # discovered at run-time, since there are many different ways to do
  165. # basically the same things with Unix C compilers.
  166. for key in kwargs:
  167. if key not in self.executables:
  168. raise ValueError(
  169. f"unknown executable '{key}' for class {self.__class__.__name__}"
  170. )
  171. self.set_executable(key, kwargs[key])
  172. def set_executable(self, key, value):
  173. if isinstance(value, str):
  174. setattr(self, key, split_quoted(value))
  175. else:
  176. setattr(self, key, value)
  177. def _find_macro(self, name):
  178. i = 0
  179. for defn in self.macros:
  180. if defn[0] == name:
  181. return i
  182. i += 1
  183. return None
  184. def _check_macro_definitions(self, definitions):
  185. """Ensure that every element of 'definitions' is valid."""
  186. for defn in definitions:
  187. self._check_macro_definition(*defn)
  188. def _check_macro_definition(self, defn):
  189. """
  190. Raise a TypeError if defn is not valid.
  191. A valid definition is either a (name, value) 2-tuple or a (name,) tuple.
  192. """
  193. if not isinstance(defn, tuple) or not self._is_valid_macro(*defn):
  194. raise TypeError(
  195. f"invalid macro definition '{defn}': "
  196. "must be tuple (string,), (string, string), or (string, None)"
  197. )
  198. @staticmethod
  199. def _is_valid_macro(name, value=None):
  200. """
  201. A valid macro is a ``name : str`` and a ``value : str | None``.
  202. >>> Compiler._is_valid_macro('foo', None)
  203. True
  204. """
  205. return isinstance(name, str) and isinstance(value, (str, type(None)))
  206. # -- Bookkeeping methods -------------------------------------------
  207. def define_macro(self, name: str, value: str | None = None) -> None:
  208. """Define a preprocessor macro for all compilations driven by this
  209. compiler object. The optional parameter 'value' should be a
  210. string; if it is not supplied, then the macro will be defined
  211. without an explicit value and the exact outcome depends on the
  212. compiler used (XXX true? does ANSI say anything about this?)
  213. """
  214. # Delete from the list of macro definitions/undefinitions if
  215. # already there (so that this one will take precedence).
  216. i = self._find_macro(name)
  217. if i is not None:
  218. del self.macros[i]
  219. self.macros.append((name, value))
  220. def undefine_macro(self, name: str) -> None:
  221. """Undefine a preprocessor macro for all compilations driven by
  222. this compiler object. If the same macro is defined by
  223. 'define_macro()' and undefined by 'undefine_macro()' the last call
  224. takes precedence (including multiple redefinitions or
  225. undefinitions). If the macro is redefined/undefined on a
  226. per-compilation basis (ie. in the call to 'compile()'), then that
  227. takes precedence.
  228. """
  229. # Delete from the list of macro definitions/undefinitions if
  230. # already there (so that this one will take precedence).
  231. i = self._find_macro(name)
  232. if i is not None:
  233. del self.macros[i]
  234. undefn = (name,)
  235. self.macros.append(undefn)
  236. def add_include_dir(self, dir: str) -> None:
  237. """Add 'dir' to the list of directories that will be searched for
  238. header files. The compiler is instructed to search directories in
  239. the order in which they are supplied by successive calls to
  240. 'add_include_dir()'.
  241. """
  242. self.include_dirs.append(dir)
  243. def set_include_dirs(self, dirs: list[str]) -> None:
  244. """Set the list of directories that will be searched to 'dirs' (a
  245. list of strings). Overrides any preceding calls to
  246. 'add_include_dir()'; subsequence calls to 'add_include_dir()' add
  247. to the list passed to 'set_include_dirs()'. This does not affect
  248. any list of standard include directories that the compiler may
  249. search by default.
  250. """
  251. self.include_dirs = dirs[:]
  252. def add_library(self, libname: str) -> None:
  253. """Add 'libname' to the list of libraries that will be included in
  254. all links driven by this compiler object. Note that 'libname'
  255. should *not* be the name of a file containing a library, but the
  256. name of the library itself: the actual filename will be inferred by
  257. the linker, the compiler, or the compiler class (depending on the
  258. platform).
  259. The linker will be instructed to link against libraries in the
  260. order they were supplied to 'add_library()' and/or
  261. 'set_libraries()'. It is perfectly valid to duplicate library
  262. names; the linker will be instructed to link against libraries as
  263. many times as they are mentioned.
  264. """
  265. self.libraries.append(libname)
  266. def set_libraries(self, libnames: list[str]) -> None:
  267. """Set the list of libraries to be included in all links driven by
  268. this compiler object to 'libnames' (a list of strings). This does
  269. not affect any standard system libraries that the linker may
  270. include by default.
  271. """
  272. self.libraries = libnames[:]
  273. def add_library_dir(self, dir: str) -> None:
  274. """Add 'dir' to the list of directories that will be searched for
  275. libraries specified to 'add_library()' and 'set_libraries()'. The
  276. linker will be instructed to search for libraries in the order they
  277. are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
  278. """
  279. self.library_dirs.append(dir)
  280. def set_library_dirs(self, dirs: list[str]) -> None:
  281. """Set the list of library search directories to 'dirs' (a list of
  282. strings). This does not affect any standard library search path
  283. that the linker may search by default.
  284. """
  285. self.library_dirs = dirs[:]
  286. def add_runtime_library_dir(self, dir: str) -> None:
  287. """Add 'dir' to the list of directories that will be searched for
  288. shared libraries at runtime.
  289. """
  290. self.runtime_library_dirs.append(dir)
  291. def set_runtime_library_dirs(self, dirs: list[str]) -> None:
  292. """Set the list of directories to search for shared libraries at
  293. runtime to 'dirs' (a list of strings). This does not affect any
  294. standard search path that the runtime linker may search by
  295. default.
  296. """
  297. self.runtime_library_dirs = dirs[:]
  298. def add_link_object(self, object: str) -> None:
  299. """Add 'object' to the list of object files (or analogues, such as
  300. explicitly named library files or the output of "resource
  301. compilers") to be included in every link driven by this compiler
  302. object.
  303. """
  304. self.objects.append(object)
  305. def set_link_objects(self, objects: list[str]) -> None:
  306. """Set the list of object files (or analogues) to be included in
  307. every link to 'objects'. This does not affect any standard object
  308. files that the linker may include by default (such as system
  309. libraries).
  310. """
  311. self.objects = objects[:]
  312. # -- Private utility methods --------------------------------------
  313. # (here for the convenience of subclasses)
  314. # Helper method to prep compiler in subclass compile() methods
  315. def _setup_compile(
  316. self,
  317. outdir: str | None,
  318. macros: list[_Macro] | None,
  319. incdirs: list[str] | tuple[str, ...] | None,
  320. sources,
  321. depends,
  322. extra,
  323. ):
  324. """Process arguments and decide which source files to compile."""
  325. outdir, macros, incdirs = self._fix_compile_args(outdir, macros, incdirs)
  326. if extra is None:
  327. extra = []
  328. # Get the list of expected output (object) files
  329. objects = self.object_filenames(sources, strip_dir=False, output_dir=outdir)
  330. assert len(objects) == len(sources)
  331. pp_opts = gen_preprocess_options(macros, incdirs)
  332. build = {}
  333. for i in range(len(sources)):
  334. src = sources[i]
  335. obj = objects[i]
  336. ext = os.path.splitext(src)[1]
  337. self.mkpath(os.path.dirname(obj))
  338. build[obj] = (src, ext)
  339. return macros, objects, extra, pp_opts, build
  340. def _get_cc_args(self, pp_opts, debug, before):
  341. # works for unixccompiler, cygwinccompiler
  342. cc_args = pp_opts + ['-c']
  343. if debug:
  344. cc_args[:0] = ['-g']
  345. if before:
  346. cc_args[:0] = before
  347. return cc_args
  348. def _fix_compile_args(
  349. self,
  350. output_dir: str | None,
  351. macros: list[_Macro] | None,
  352. include_dirs: list[str] | tuple[str, ...] | None,
  353. ) -> tuple[str, list[_Macro], list[str]]:
  354. """Typecheck and fix-up some of the arguments to the 'compile()'
  355. method, and return fixed-up values. Specifically: if 'output_dir'
  356. is None, replaces it with 'self.output_dir'; ensures that 'macros'
  357. is a list, and augments it with 'self.macros'; ensures that
  358. 'include_dirs' is a list, and augments it with 'self.include_dirs'.
  359. Guarantees that the returned values are of the correct type,
  360. i.e. for 'output_dir' either string or None, and for 'macros' and
  361. 'include_dirs' either list or None.
  362. """
  363. if output_dir is None:
  364. output_dir = self.output_dir
  365. elif not isinstance(output_dir, str):
  366. raise TypeError("'output_dir' must be a string or None")
  367. if macros is None:
  368. macros = list(self.macros)
  369. elif isinstance(macros, list):
  370. macros = macros + (self.macros or [])
  371. else:
  372. raise TypeError("'macros' (if supplied) must be a list of tuples")
  373. if include_dirs is None:
  374. include_dirs = list(self.include_dirs)
  375. elif isinstance(include_dirs, (list, tuple)):
  376. include_dirs = list(include_dirs) + (self.include_dirs or [])
  377. else:
  378. raise TypeError("'include_dirs' (if supplied) must be a list of strings")
  379. # add include dirs for class
  380. include_dirs += self.__class__.include_dirs
  381. return output_dir, macros, include_dirs
  382. def _prep_compile(self, sources, output_dir, depends=None):
  383. """Decide which source files must be recompiled.
  384. Determine the list of object files corresponding to 'sources',
  385. and figure out which ones really need to be recompiled.
  386. Return a list of all object files and a dictionary telling
  387. which source files can be skipped.
  388. """
  389. # Get the list of expected output (object) files
  390. objects = self.object_filenames(sources, output_dir=output_dir)
  391. assert len(objects) == len(sources)
  392. # Return an empty dict for the "which source files can be skipped"
  393. # return value to preserve API compatibility.
  394. return objects, {}
  395. def _fix_object_args(
  396. self, objects: list[str] | tuple[str, ...], output_dir: str | None
  397. ) -> tuple[list[str], str]:
  398. """Typecheck and fix up some arguments supplied to various methods.
  399. Specifically: ensure that 'objects' is a list; if output_dir is
  400. None, replace with self.output_dir. Return fixed versions of
  401. 'objects' and 'output_dir'.
  402. """
  403. if not isinstance(objects, (list, tuple)):
  404. raise TypeError("'objects' must be a list or tuple of strings")
  405. objects = list(objects)
  406. if output_dir is None:
  407. output_dir = self.output_dir
  408. elif not isinstance(output_dir, str):
  409. raise TypeError("'output_dir' must be a string or None")
  410. return (objects, output_dir)
  411. def _fix_lib_args(
  412. self,
  413. libraries: list[str] | tuple[str, ...] | None,
  414. library_dirs: list[str] | tuple[str, ...] | None,
  415. runtime_library_dirs: list[str] | tuple[str, ...] | None,
  416. ) -> tuple[list[str], list[str], list[str]]:
  417. """Typecheck and fix up some of the arguments supplied to the
  418. 'link_*' methods. Specifically: ensure that all arguments are
  419. lists, and augment them with their permanent versions
  420. (eg. 'self.libraries' augments 'libraries'). Return a tuple with
  421. fixed versions of all arguments.
  422. """
  423. if libraries is None:
  424. libraries = list(self.libraries)
  425. elif isinstance(libraries, (list, tuple)):
  426. libraries = list(libraries) + (self.libraries or [])
  427. else:
  428. raise TypeError("'libraries' (if supplied) must be a list of strings")
  429. if library_dirs is None:
  430. library_dirs = list(self.library_dirs)
  431. elif isinstance(library_dirs, (list, tuple)):
  432. library_dirs = list(library_dirs) + (self.library_dirs or [])
  433. else:
  434. raise TypeError("'library_dirs' (if supplied) must be a list of strings")
  435. # add library dirs for class
  436. library_dirs += self.__class__.library_dirs
  437. if runtime_library_dirs is None:
  438. runtime_library_dirs = list(self.runtime_library_dirs)
  439. elif isinstance(runtime_library_dirs, (list, tuple)):
  440. runtime_library_dirs = list(runtime_library_dirs) + (
  441. self.runtime_library_dirs or []
  442. )
  443. else:
  444. raise TypeError(
  445. "'runtime_library_dirs' (if supplied) must be a list of strings"
  446. )
  447. return (libraries, library_dirs, runtime_library_dirs)
  448. def _need_link(self, objects, output_file):
  449. """Return true if we need to relink the files listed in 'objects'
  450. to recreate 'output_file'.
  451. """
  452. if self.force:
  453. return True
  454. else:
  455. if self.dry_run:
  456. newer = newer_group(objects, output_file, missing='newer')
  457. else:
  458. newer = newer_group(objects, output_file)
  459. return newer
  460. def detect_language(self, sources: str | list[str]) -> str | None:
  461. """Detect the language of a given file, or list of files. Uses
  462. language_map, and language_order to do the job.
  463. """
  464. if not isinstance(sources, list):
  465. sources = [sources]
  466. lang = None
  467. index = len(self.language_order)
  468. for source in sources:
  469. base, ext = os.path.splitext(source)
  470. extlang = self.language_map.get(ext)
  471. try:
  472. extindex = self.language_order.index(extlang)
  473. if extindex < index:
  474. lang = extlang
  475. index = extindex
  476. except ValueError:
  477. pass
  478. return lang
  479. # -- Worker methods ------------------------------------------------
  480. # (must be implemented by subclasses)
  481. def preprocess(
  482. self,
  483. source: str | os.PathLike[str],
  484. output_file: str | os.PathLike[str] | None = None,
  485. macros: list[_Macro] | None = None,
  486. include_dirs: list[str] | tuple[str, ...] | None = None,
  487. extra_preargs: list[str] | None = None,
  488. extra_postargs: Iterable[str] | None = None,
  489. ):
  490. """Preprocess a single C/C++ source file, named in 'source'.
  491. Output will be written to file named 'output_file', or stdout if
  492. 'output_file' not supplied. 'macros' is a list of macro
  493. definitions as for 'compile()', which will augment the macros set
  494. with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a
  495. list of directory names that will be added to the default list.
  496. Raises PreprocessError on failure.
  497. """
  498. pass
  499. def compile(
  500. self,
  501. sources: Sequence[str | os.PathLike[str]],
  502. output_dir: str | None = None,
  503. macros: list[_Macro] | None = None,
  504. include_dirs: list[str] | tuple[str, ...] | None = None,
  505. debug: bool = False,
  506. extra_preargs: list[str] | None = None,
  507. extra_postargs: list[str] | None = None,
  508. depends: list[str] | tuple[str, ...] | None = None,
  509. ) -> list[str]:
  510. """Compile one or more source files.
  511. 'sources' must be a list of filenames, most likely C/C++
  512. files, but in reality anything that can be handled by a
  513. particular compiler and compiler class (eg. MSVCCompiler can
  514. handle resource files in 'sources'). Return a list of object
  515. filenames, one per source filename in 'sources'. Depending on
  516. the implementation, not all source files will necessarily be
  517. compiled, but all corresponding object filenames will be
  518. returned.
  519. If 'output_dir' is given, object files will be put under it, while
  520. retaining their original path component. That is, "foo/bar.c"
  521. normally compiles to "foo/bar.o" (for a Unix implementation); if
  522. 'output_dir' is "build", then it would compile to
  523. "build/foo/bar.o".
  524. 'macros', if given, must be a list of macro definitions. A macro
  525. definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
  526. The former defines a macro; if the value is None, the macro is
  527. defined without an explicit value. The 1-tuple case undefines a
  528. macro. Later definitions/redefinitions/ undefinitions take
  529. precedence.
  530. 'include_dirs', if given, must be a list of strings, the
  531. directories to add to the default include file search path for this
  532. compilation only.
  533. 'debug' is a boolean; if true, the compiler will be instructed to
  534. output debug symbols in (or alongside) the object file(s).
  535. 'extra_preargs' and 'extra_postargs' are implementation- dependent.
  536. On platforms that have the notion of a command-line (e.g. Unix,
  537. DOS/Windows), they are most likely lists of strings: extra
  538. command-line arguments to prepend/append to the compiler command
  539. line. On other platforms, consult the implementation class
  540. documentation. In any event, they are intended as an escape hatch
  541. for those occasions when the abstract compiler framework doesn't
  542. cut the mustard.
  543. 'depends', if given, is a list of filenames that all targets
  544. depend on. If a source file is older than any file in
  545. depends, then the source file will be recompiled. This
  546. supports dependency tracking, but only at a coarse
  547. granularity.
  548. Raises CompileError on failure.
  549. """
  550. # A concrete compiler class can either override this method
  551. # entirely or implement _compile().
  552. macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
  553. output_dir, macros, include_dirs, sources, depends, extra_postargs
  554. )
  555. cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
  556. for obj in objects:
  557. try:
  558. src, ext = build[obj]
  559. except KeyError:
  560. continue
  561. self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
  562. # Return *all* object filenames, not just the ones we just built.
  563. return objects
  564. def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
  565. """Compile 'src' to product 'obj'."""
  566. # A concrete compiler class that does not override compile()
  567. # should implement _compile().
  568. pass
  569. def create_static_lib(
  570. self,
  571. objects: list[str] | tuple[str, ...],
  572. output_libname: str,
  573. output_dir: str | None = None,
  574. debug: bool = False,
  575. target_lang: str | None = None,
  576. ) -> None:
  577. """Link a bunch of stuff together to create a static library file.
  578. The "bunch of stuff" consists of the list of object files supplied
  579. as 'objects', the extra object files supplied to
  580. 'add_link_object()' and/or 'set_link_objects()', the libraries
  581. supplied to 'add_library()' and/or 'set_libraries()', and the
  582. libraries supplied as 'libraries' (if any).
  583. 'output_libname' should be a library name, not a filename; the
  584. filename will be inferred from the library name. 'output_dir' is
  585. the directory where the library file will be put.
  586. 'debug' is a boolean; if true, debugging information will be
  587. included in the library (note that on most platforms, it is the
  588. compile step where this matters: the 'debug' flag is included here
  589. just for consistency).
  590. 'target_lang' is the target language for which the given objects
  591. are being compiled. This allows specific linkage time treatment of
  592. certain languages.
  593. Raises LibError on failure.
  594. """
  595. pass
  596. # values for target_desc parameter in link()
  597. SHARED_OBJECT = "shared_object"
  598. SHARED_LIBRARY = "shared_library"
  599. EXECUTABLE = "executable"
  600. def link(
  601. self,
  602. target_desc: str,
  603. objects: list[str] | tuple[str, ...],
  604. output_filename: str,
  605. output_dir: str | None = None,
  606. libraries: list[str] | tuple[str, ...] | None = None,
  607. library_dirs: list[str] | tuple[str, ...] | None = None,
  608. runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
  609. export_symbols: Iterable[str] | None = None,
  610. debug: bool = False,
  611. extra_preargs: list[str] | None = None,
  612. extra_postargs: list[str] | None = None,
  613. build_temp: str | os.PathLike[str] | None = None,
  614. target_lang: str | None = None,
  615. ):
  616. """Link a bunch of stuff together to create an executable or
  617. shared library file.
  618. The "bunch of stuff" consists of the list of object files supplied
  619. as 'objects'. 'output_filename' should be a filename. If
  620. 'output_dir' is supplied, 'output_filename' is relative to it
  621. (i.e. 'output_filename' can provide directory components if
  622. needed).
  623. 'libraries' is a list of libraries to link against. These are
  624. library names, not filenames, since they're translated into
  625. filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
  626. on Unix and "foo.lib" on DOS/Windows). However, they can include a
  627. directory component, which means the linker will look in that
  628. specific directory rather than searching all the normal locations.
  629. 'library_dirs', if supplied, should be a list of directories to
  630. search for libraries that were specified as bare library names
  631. (ie. no directory component). These are on top of the system
  632. default and those supplied to 'add_library_dir()' and/or
  633. 'set_library_dirs()'. 'runtime_library_dirs' is a list of
  634. directories that will be embedded into the shared library and used
  635. to search for other shared libraries that *it* depends on at
  636. run-time. (This may only be relevant on Unix.)
  637. 'export_symbols' is a list of symbols that the shared library will
  638. export. (This appears to be relevant only on Windows.)
  639. 'debug' is as for 'compile()' and 'create_static_lib()', with the
  640. slight distinction that it actually matters on most platforms (as
  641. opposed to 'create_static_lib()', which includes a 'debug' flag
  642. mostly for form's sake).
  643. 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
  644. of course that they supply command-line arguments for the
  645. particular linker being used).
  646. 'target_lang' is the target language for which the given objects
  647. are being compiled. This allows specific linkage time treatment of
  648. certain languages.
  649. Raises LinkError on failure.
  650. """
  651. raise NotImplementedError
  652. # Old 'link_*()' methods, rewritten to use the new 'link()' method.
  653. def link_shared_lib(
  654. self,
  655. objects: list[str] | tuple[str, ...],
  656. output_libname: str,
  657. output_dir: str | None = None,
  658. libraries: list[str] | tuple[str, ...] | None = None,
  659. library_dirs: list[str] | tuple[str, ...] | None = None,
  660. runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
  661. export_symbols: Iterable[str] | None = None,
  662. debug: bool = False,
  663. extra_preargs: list[str] | None = None,
  664. extra_postargs: list[str] | None = None,
  665. build_temp: str | os.PathLike[str] | None = None,
  666. target_lang: str | None = None,
  667. ):
  668. self.link(
  669. Compiler.SHARED_LIBRARY,
  670. objects,
  671. self.library_filename(output_libname, lib_type='shared'),
  672. output_dir,
  673. libraries,
  674. library_dirs,
  675. runtime_library_dirs,
  676. export_symbols,
  677. debug,
  678. extra_preargs,
  679. extra_postargs,
  680. build_temp,
  681. target_lang,
  682. )
  683. def link_shared_object(
  684. self,
  685. objects: list[str] | tuple[str, ...],
  686. output_filename: str,
  687. output_dir: str | None = None,
  688. libraries: list[str] | tuple[str, ...] | None = None,
  689. library_dirs: list[str] | tuple[str, ...] | None = None,
  690. runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
  691. export_symbols: Iterable[str] | None = None,
  692. debug: bool = False,
  693. extra_preargs: list[str] | None = None,
  694. extra_postargs: list[str] | None = None,
  695. build_temp: str | os.PathLike[str] | None = None,
  696. target_lang: str | None = None,
  697. ):
  698. self.link(
  699. Compiler.SHARED_OBJECT,
  700. objects,
  701. output_filename,
  702. output_dir,
  703. libraries,
  704. library_dirs,
  705. runtime_library_dirs,
  706. export_symbols,
  707. debug,
  708. extra_preargs,
  709. extra_postargs,
  710. build_temp,
  711. target_lang,
  712. )
  713. def link_executable(
  714. self,
  715. objects: list[str] | tuple[str, ...],
  716. output_progname: str,
  717. output_dir: str | None = None,
  718. libraries: list[str] | tuple[str, ...] | None = None,
  719. library_dirs: list[str] | tuple[str, ...] | None = None,
  720. runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
  721. debug: bool = False,
  722. extra_preargs: list[str] | None = None,
  723. extra_postargs: list[str] | None = None,
  724. target_lang: str | None = None,
  725. ):
  726. self.link(
  727. Compiler.EXECUTABLE,
  728. objects,
  729. self.executable_filename(output_progname),
  730. output_dir,
  731. libraries,
  732. library_dirs,
  733. runtime_library_dirs,
  734. None,
  735. debug,
  736. extra_preargs,
  737. extra_postargs,
  738. None,
  739. target_lang,
  740. )
  741. # -- Miscellaneous methods -----------------------------------------
  742. # These are all used by the 'gen_lib_options() function; there is
  743. # no appropriate default implementation so subclasses should
  744. # implement all of these.
  745. def library_dir_option(self, dir: str) -> str:
  746. """Return the compiler option to add 'dir' to the list of
  747. directories searched for libraries.
  748. """
  749. raise NotImplementedError
  750. def runtime_library_dir_option(self, dir: str) -> str:
  751. """Return the compiler option to add 'dir' to the list of
  752. directories searched for runtime libraries.
  753. """
  754. raise NotImplementedError
  755. def library_option(self, lib: str) -> str:
  756. """Return the compiler option to add 'lib' to the list of libraries
  757. linked into the shared library or executable.
  758. """
  759. raise NotImplementedError
  760. def has_function( # noqa: C901
  761. self,
  762. funcname: str,
  763. includes: Iterable[str] | None = None,
  764. include_dirs: list[str] | tuple[str, ...] | None = None,
  765. libraries: list[str] | None = None,
  766. library_dirs: list[str] | tuple[str, ...] | None = None,
  767. ) -> bool:
  768. """Return a boolean indicating whether funcname is provided as
  769. a symbol on the current platform. The optional arguments can
  770. be used to augment the compilation environment.
  771. The libraries argument is a list of flags to be passed to the
  772. linker to make additional symbol definitions available for
  773. linking.
  774. The includes and include_dirs arguments are deprecated.
  775. Usually, supplying include files with function declarations
  776. will cause function detection to fail even in cases where the
  777. symbol is available for linking.
  778. """
  779. # this can't be included at module scope because it tries to
  780. # import math which might not be available at that point - maybe
  781. # the necessary logic should just be inlined?
  782. import tempfile
  783. if includes is None:
  784. includes = []
  785. else:
  786. warnings.warn("includes is deprecated", DeprecationWarning)
  787. if include_dirs is None:
  788. include_dirs = []
  789. else:
  790. warnings.warn("include_dirs is deprecated", DeprecationWarning)
  791. if libraries is None:
  792. libraries = []
  793. if library_dirs is None:
  794. library_dirs = []
  795. fd, fname = tempfile.mkstemp(".c", funcname, text=True)
  796. with os.fdopen(fd, "w", encoding='utf-8') as f:
  797. for incl in includes:
  798. f.write(f"""#include "{incl}"\n""")
  799. if not includes:
  800. # Use "char func(void);" as the prototype to follow
  801. # what autoconf does. This prototype does not match
  802. # any well-known function the compiler might recognize
  803. # as a builtin, so this ends up as a true link test.
  804. # Without a fake prototype, the test would need to
  805. # know the exact argument types, and the has_function
  806. # interface does not provide that level of information.
  807. f.write(
  808. f"""\
  809. #ifdef __cplusplus
  810. extern "C"
  811. #endif
  812. char {funcname}(void);
  813. """
  814. )
  815. f.write(
  816. f"""\
  817. int main (int argc, char **argv) {{
  818. {funcname}();
  819. return 0;
  820. }}
  821. """
  822. )
  823. try:
  824. objects = self.compile([fname], include_dirs=include_dirs)
  825. except CompileError:
  826. return False
  827. finally:
  828. os.remove(fname)
  829. try:
  830. self.link_executable(
  831. objects, "a.out", libraries=libraries, library_dirs=library_dirs
  832. )
  833. except (LinkError, TypeError):
  834. return False
  835. else:
  836. os.remove(
  837. self.executable_filename("a.out", output_dir=self.output_dir or '')
  838. )
  839. finally:
  840. for fn in objects:
  841. os.remove(fn)
  842. return True
  843. def find_library_file(
  844. self, dirs: Iterable[str], lib: str, debug: bool = False
  845. ) -> str | None:
  846. """Search the specified list of directories for a static or shared
  847. library file 'lib' and return the full path to that file. If
  848. 'debug' true, look for a debugging version (if that makes sense on
  849. the current platform). Return None if 'lib' wasn't found in any of
  850. the specified directories.
  851. """
  852. raise NotImplementedError
  853. # -- Filename generation methods -----------------------------------
  854. # The default implementation of the filename generating methods are
  855. # prejudiced towards the Unix/DOS/Windows view of the world:
  856. # * object files are named by replacing the source file extension
  857. # (eg. .c/.cpp -> .o/.obj)
  858. # * library files (shared or static) are named by plugging the
  859. # library name and extension into a format string, eg.
  860. # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
  861. # * executables are named by appending an extension (possibly
  862. # empty) to the program name: eg. progname + ".exe" for
  863. # Windows
  864. #
  865. # To reduce redundant code, these methods expect to find
  866. # several attributes in the current object (presumably defined
  867. # as class attributes):
  868. # * src_extensions -
  869. # list of C/C++ source file extensions, eg. ['.c', '.cpp']
  870. # * obj_extension -
  871. # object file extension, eg. '.o' or '.obj'
  872. # * static_lib_extension -
  873. # extension for static library files, eg. '.a' or '.lib'
  874. # * shared_lib_extension -
  875. # extension for shared library/object files, eg. '.so', '.dll'
  876. # * static_lib_format -
  877. # format string for generating static library filenames,
  878. # eg. 'lib%s.%s' or '%s.%s'
  879. # * shared_lib_format
  880. # format string for generating shared library filenames
  881. # (probably same as static_lib_format, since the extension
  882. # is one of the intended parameters to the format string)
  883. # * exe_extension -
  884. # extension for executable files, eg. '' or '.exe'
  885. def object_filenames(
  886. self,
  887. source_filenames: Iterable[str | os.PathLike[str]],
  888. strip_dir: bool = False,
  889. output_dir: str | os.PathLike[str] | None = '',
  890. ) -> list[str]:
  891. if output_dir is None:
  892. output_dir = ''
  893. return list(
  894. self._make_out_path(output_dir, strip_dir, src_name)
  895. for src_name in source_filenames
  896. )
  897. @property
  898. def out_extensions(self):
  899. return dict.fromkeys(self.src_extensions, self.obj_extension)
  900. def _make_out_path(self, output_dir, strip_dir, src_name):
  901. return self._make_out_path_exts(
  902. output_dir, strip_dir, src_name, self.out_extensions
  903. )
  904. @classmethod
  905. def _make_out_path_exts(cls, output_dir, strip_dir, src_name, extensions):
  906. r"""
  907. >>> exts = {'.c': '.o'}
  908. >>> Compiler._make_out_path_exts('.', False, '/foo/bar.c', exts).replace('\\', '/')
  909. './foo/bar.o'
  910. >>> Compiler._make_out_path_exts('.', True, '/foo/bar.c', exts).replace('\\', '/')
  911. './bar.o'
  912. """
  913. src = pathlib.PurePath(src_name)
  914. # Ensure base is relative to honor output_dir (python/cpython#37775).
  915. base = cls._make_relative(src)
  916. try:
  917. new_ext = extensions[src.suffix]
  918. except LookupError:
  919. raise UnknownFileType(f"unknown file type '{src.suffix}' (from '{src}')")
  920. if strip_dir:
  921. base = pathlib.PurePath(base.name)
  922. return os.path.join(output_dir, base.with_suffix(new_ext))
  923. @staticmethod
  924. def _make_relative(base: pathlib.Path):
  925. return base.relative_to(base.anchor)
  926. @overload
  927. def shared_object_filename(
  928. self,
  929. basename: str,
  930. strip_dir: Literal[False] = False,
  931. output_dir: str | os.PathLike[str] = "",
  932. ) -> str: ...
  933. @overload
  934. def shared_object_filename(
  935. self,
  936. basename: str | os.PathLike[str],
  937. strip_dir: Literal[True],
  938. output_dir: str | os.PathLike[str] = "",
  939. ) -> str: ...
  940. def shared_object_filename(
  941. self,
  942. basename: str | os.PathLike[str],
  943. strip_dir: bool = False,
  944. output_dir: str | os.PathLike[str] = '',
  945. ) -> str:
  946. assert output_dir is not None
  947. if strip_dir:
  948. basename = os.path.basename(basename)
  949. return os.path.join(output_dir, basename + self.shared_lib_extension)
  950. @overload
  951. def executable_filename(
  952. self,
  953. basename: str,
  954. strip_dir: Literal[False] = False,
  955. output_dir: str | os.PathLike[str] = "",
  956. ) -> str: ...
  957. @overload
  958. def executable_filename(
  959. self,
  960. basename: str | os.PathLike[str],
  961. strip_dir: Literal[True],
  962. output_dir: str | os.PathLike[str] = "",
  963. ) -> str: ...
  964. def executable_filename(
  965. self,
  966. basename: str | os.PathLike[str],
  967. strip_dir: bool = False,
  968. output_dir: str | os.PathLike[str] = '',
  969. ) -> str:
  970. assert output_dir is not None
  971. if strip_dir:
  972. basename = os.path.basename(basename)
  973. return os.path.join(output_dir, basename + (self.exe_extension or ''))
  974. def library_filename(
  975. self,
  976. libname: str,
  977. lib_type: str = "static",
  978. strip_dir: bool = False,
  979. output_dir: str | os.PathLike[str] = "", # or 'shared'
  980. ):
  981. assert output_dir is not None
  982. expected = '"static", "shared", "dylib", "xcode_stub"'
  983. if lib_type not in eval(expected):
  984. raise ValueError(f"'lib_type' must be {expected}")
  985. fmt = getattr(self, lib_type + "_lib_format")
  986. ext = getattr(self, lib_type + "_lib_extension")
  987. dir, base = os.path.split(libname)
  988. filename = fmt % (base, ext)
  989. if strip_dir:
  990. dir = ''
  991. return os.path.join(output_dir, dir, filename)
  992. # -- Utility methods -----------------------------------------------
  993. def announce(self, msg: object, level: int = 1) -> None:
  994. log.debug(msg)
  995. def debug_print(self, msg: object) -> None:
  996. from distutils.debug import DEBUG
  997. if DEBUG:
  998. print(msg)
  999. def warn(self, msg: object) -> None:
  1000. sys.stderr.write(f"warning: {msg}\n")
  1001. def execute(
  1002. self,
  1003. func: Callable[[Unpack[_Ts]], object],
  1004. args: tuple[Unpack[_Ts]],
  1005. msg: object = None,
  1006. level: int = 1,
  1007. ) -> None:
  1008. execute(func, args, msg, self.dry_run)
  1009. def spawn(
  1010. self, cmd: MutableSequence[bytes | str | os.PathLike[str]], **kwargs
  1011. ) -> None:
  1012. spawn(cmd, dry_run=self.dry_run, **kwargs)
  1013. @overload
  1014. def move_file(
  1015. self, src: str | os.PathLike[str], dst: _StrPathT
  1016. ) -> _StrPathT | str: ...
  1017. @overload
  1018. def move_file(
  1019. self, src: bytes | os.PathLike[bytes], dst: _BytesPathT
  1020. ) -> _BytesPathT | bytes: ...
  1021. def move_file(
  1022. self,
  1023. src: str | os.PathLike[str] | bytes | os.PathLike[bytes],
  1024. dst: str | os.PathLike[str] | bytes | os.PathLike[bytes],
  1025. ) -> str | os.PathLike[str] | bytes | os.PathLike[bytes]:
  1026. return move_file(src, dst, dry_run=self.dry_run)
  1027. def mkpath(self, name, mode=0o777):
  1028. mkpath(name, mode, dry_run=self.dry_run)
  1029. # Map a sys.platform/os.name ('posix', 'nt') to the default compiler
  1030. # type for that platform. Keys are interpreted as re match
  1031. # patterns. Order is important; platform mappings are preferred over
  1032. # OS names.
  1033. _default_compilers = (
  1034. # Platform string mappings
  1035. # on a cygwin built python we can use gcc like an ordinary UNIXish
  1036. # compiler
  1037. ('cygwin.*', 'unix'),
  1038. ('zos', 'zos'),
  1039. # OS name mappings
  1040. ('posix', 'unix'),
  1041. ('nt', 'msvc'),
  1042. )
  1043. def get_default_compiler(osname: str | None = None, platform: str | None = None) -> str:
  1044. """Determine the default compiler to use for the given platform.
  1045. osname should be one of the standard Python OS names (i.e. the
  1046. ones returned by os.name) and platform the common value
  1047. returned by sys.platform for the platform in question.
  1048. The default values are os.name and sys.platform in case the
  1049. parameters are not given.
  1050. """
  1051. if osname is None:
  1052. osname = os.name
  1053. if platform is None:
  1054. platform = sys.platform
  1055. # Mingw is a special case where sys.platform is 'win32' but we
  1056. # want to use the 'mingw32' compiler, so check it first
  1057. if is_mingw():
  1058. return 'mingw32'
  1059. for pattern, compiler in _default_compilers:
  1060. if (
  1061. re.match(pattern, platform) is not None
  1062. or re.match(pattern, osname) is not None
  1063. ):
  1064. return compiler
  1065. # Default to Unix compiler
  1066. return 'unix'
  1067. # Map compiler types to (module_name, class_name) pairs -- ie. where to
  1068. # find the code that implements an interface to this compiler. (The module
  1069. # is assumed to be in the 'distutils' package.)
  1070. compiler_class = {
  1071. 'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"),
  1072. 'msvc': ('_msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"),
  1073. 'cygwin': (
  1074. 'cygwinccompiler',
  1075. 'CygwinCCompiler',
  1076. "Cygwin port of GNU C Compiler for Win32",
  1077. ),
  1078. 'mingw32': (
  1079. 'cygwinccompiler',
  1080. 'Mingw32CCompiler',
  1081. "Mingw32 port of GNU C Compiler for Win32",
  1082. ),
  1083. 'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"),
  1084. 'zos': ('zosccompiler', 'zOSCCompiler', 'IBM XL C/C++ Compilers'),
  1085. }
  1086. def show_compilers() -> None:
  1087. """Print list of available compilers (used by the "--help-compiler"
  1088. options to "build", "build_ext", "build_clib").
  1089. """
  1090. # XXX this "knows" that the compiler option it's describing is
  1091. # "--compiler", which just happens to be the case for the three
  1092. # commands that use it.
  1093. from distutils.fancy_getopt import FancyGetopt
  1094. compilers = sorted(
  1095. ("compiler=" + compiler, None, compiler_class[compiler][2])
  1096. for compiler in compiler_class.keys()
  1097. )
  1098. pretty_printer = FancyGetopt(compilers)
  1099. pretty_printer.print_help("List of available compilers:")
  1100. def new_compiler(
  1101. plat: str | None = None,
  1102. compiler: str | None = None,
  1103. verbose: bool = False,
  1104. dry_run: bool = False,
  1105. force: bool = False,
  1106. ) -> Compiler:
  1107. """Generate an instance of some CCompiler subclass for the supplied
  1108. platform/compiler combination. 'plat' defaults to 'os.name'
  1109. (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler
  1110. for that platform. Currently only 'posix' and 'nt' are supported, and
  1111. the default compilers are "traditional Unix interface" (UnixCCompiler
  1112. class) and Visual C++ (MSVCCompiler class). Note that it's perfectly
  1113. possible to ask for a Unix compiler object under Windows, and a
  1114. Microsoft compiler object under Unix -- if you supply a value for
  1115. 'compiler', 'plat' is ignored.
  1116. """
  1117. if plat is None:
  1118. plat = os.name
  1119. try:
  1120. if compiler is None:
  1121. compiler = get_default_compiler(plat)
  1122. (module_name, class_name, long_description) = compiler_class[compiler]
  1123. except KeyError:
  1124. msg = f"don't know how to compile C/C++ code on platform '{plat}'"
  1125. if compiler is not None:
  1126. msg = msg + f" with '{compiler}' compiler"
  1127. raise DistutilsPlatformError(msg)
  1128. try:
  1129. module_name = "distutils." + module_name
  1130. __import__(module_name)
  1131. module = sys.modules[module_name]
  1132. klass = vars(module)[class_name]
  1133. except ImportError:
  1134. raise DistutilsModuleError(
  1135. f"can't compile C/C++ code: unable to load module '{module_name}'"
  1136. )
  1137. except KeyError:
  1138. raise DistutilsModuleError(
  1139. f"can't compile C/C++ code: unable to find class '{class_name}' "
  1140. f"in module '{module_name}'"
  1141. )
  1142. # XXX The None is necessary to preserve backwards compatibility
  1143. # with classes that expect verbose to be the first positional
  1144. # argument.
  1145. return klass(None, dry_run, force)
  1146. def gen_preprocess_options(
  1147. macros: Iterable[_Macro], include_dirs: Iterable[str]
  1148. ) -> list[str]:
  1149. """Generate C pre-processor options (-D, -U, -I) as used by at least
  1150. two types of compilers: the typical Unix compiler and Visual C++.
  1151. 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
  1152. means undefine (-U) macro 'name', and (name,value) means define (-D)
  1153. macro 'name' to 'value'. 'include_dirs' is just a list of directory
  1154. names to be added to the header file search path (-I). Returns a list
  1155. of command-line options suitable for either Unix compilers or Visual
  1156. C++.
  1157. """
  1158. # XXX it would be nice (mainly aesthetic, and so we don't generate
  1159. # stupid-looking command lines) to go over 'macros' and eliminate
  1160. # redundant definitions/undefinitions (ie. ensure that only the
  1161. # latest mention of a particular macro winds up on the command
  1162. # line). I don't think it's essential, though, since most (all?)
  1163. # Unix C compilers only pay attention to the latest -D or -U
  1164. # mention of a macro on their command line. Similar situation for
  1165. # 'include_dirs'. I'm punting on both for now. Anyways, weeding out
  1166. # redundancies like this should probably be the province of
  1167. # CCompiler, since the data structures used are inherited from it
  1168. # and therefore common to all CCompiler classes.
  1169. pp_opts = []
  1170. for macro in macros:
  1171. if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):
  1172. raise TypeError(
  1173. f"bad macro definition '{macro}': "
  1174. "each element of 'macros' list must be a 1- or 2-tuple"
  1175. )
  1176. if len(macro) == 1: # undefine this macro
  1177. pp_opts.append(f"-U{macro[0]}")
  1178. elif len(macro) == 2:
  1179. if macro[1] is None: # define with no explicit value
  1180. pp_opts.append(f"-D{macro[0]}")
  1181. else:
  1182. # XXX *don't* need to be clever about quoting the
  1183. # macro value here, because we're going to avoid the
  1184. # shell at all costs when we spawn the command!
  1185. pp_opts.append("-D{}={}".format(*macro))
  1186. pp_opts.extend(f"-I{dir}" for dir in include_dirs)
  1187. return pp_opts
  1188. def gen_lib_options(
  1189. compiler: Compiler,
  1190. library_dirs: Iterable[str],
  1191. runtime_library_dirs: Iterable[str],
  1192. libraries: Iterable[str],
  1193. ) -> list[str]:
  1194. """Generate linker options for searching library directories and
  1195. linking with specific libraries. 'libraries' and 'library_dirs' are,
  1196. respectively, lists of library names (not filenames!) and search
  1197. directories. Returns a list of command-line options suitable for use
  1198. with some compiler (depending on the two format strings passed in).
  1199. """
  1200. lib_opts = [compiler.library_dir_option(dir) for dir in library_dirs]
  1201. for dir in runtime_library_dirs:
  1202. lib_opts.extend(always_iterable(compiler.runtime_library_dir_option(dir)))
  1203. # XXX it's important that we *not* remove redundant library mentions!
  1204. # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
  1205. # resolve all symbols. I just hope we never have to say "-lfoo obj.o
  1206. # -lbar" to get things to work -- that's certainly a possibility, but a
  1207. # pretty nasty way to arrange your C code.
  1208. for lib in libraries:
  1209. (lib_dir, lib_name) = os.path.split(lib)
  1210. if lib_dir:
  1211. lib_file = compiler.find_library_file([lib_dir], lib_name)
  1212. if lib_file:
  1213. lib_opts.append(lib_file)
  1214. else:
  1215. compiler.warn(
  1216. f"no library file corresponding to '{lib}' found (skipping)"
  1217. )
  1218. else:
  1219. lib_opts.append(compiler.library_option(lib))
  1220. return lib_opts