extension.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. """distutils.extension
  2. Provides the Extension class, used to describe C/C++ extension
  3. modules in setup scripts."""
  4. import os
  5. import warnings
  6. # This class is really only used by the "build_ext" command, so it might
  7. # make sense to put it in distutils.command.build_ext. However, that
  8. # module is already big enough, and I want to make this class a bit more
  9. # complex to simplify some common cases ("foo" module in "foo.c") and do
  10. # better error-checking ("foo.c" actually exists).
  11. #
  12. # Also, putting this in build_ext.py means every setup script would have to
  13. # import that large-ish module (indirectly, through distutils.core) in
  14. # order to do anything.
  15. class Extension:
  16. """Just a collection of attributes that describes an extension
  17. module and everything needed to build it (hopefully in a portable
  18. way, but there are hooks that let you be as unportable as you need).
  19. Instance attributes:
  20. name : string
  21. the full name of the extension, including any packages -- ie.
  22. *not* a filename or pathname, but Python dotted name
  23. sources : [string]
  24. list of source filenames, relative to the distribution root
  25. (where the setup script lives), in Unix form (slash-separated)
  26. for portability. Source files may be C, C++, SWIG (.i),
  27. platform-specific resource files, or whatever else is recognized
  28. by the "build_ext" command as source for a Python extension.
  29. include_dirs : [string]
  30. list of directories to search for C/C++ header files (in Unix
  31. form for portability)
  32. define_macros : [(name : string, value : string|None)]
  33. list of macros to define; each macro is defined using a 2-tuple,
  34. where 'value' is either the string to define it to or None to
  35. define it without a particular value (equivalent of "#define
  36. FOO" in source or -DFOO on Unix C compiler command line)
  37. undef_macros : [string]
  38. list of macros to undefine explicitly
  39. library_dirs : [string]
  40. list of directories to search for C/C++ libraries at link time
  41. libraries : [string]
  42. list of library names (not filenames or paths) to link against
  43. runtime_library_dirs : [string]
  44. list of directories to search for C/C++ libraries at run time
  45. (for shared extensions, this is when the extension is loaded)
  46. extra_objects : [string]
  47. list of extra files to link with (eg. object files not implied
  48. by 'sources', static library that must be explicitly specified,
  49. binary resource files, etc.)
  50. extra_compile_args : [string]
  51. any extra platform- and compiler-specific information to use
  52. when compiling the source files in 'sources'. For platforms and
  53. compilers where "command line" makes sense, this is typically a
  54. list of command-line arguments, but for other platforms it could
  55. be anything.
  56. extra_link_args : [string]
  57. any extra platform- and compiler-specific information to use
  58. when linking object files together to create the extension (or
  59. to create a new static Python interpreter). Similar
  60. interpretation as for 'extra_compile_args'.
  61. export_symbols : [string]
  62. list of symbols to be exported from a shared extension. Not
  63. used on all platforms, and not generally necessary for Python
  64. extensions, which typically export exactly one symbol: "init" +
  65. extension_name.
  66. swig_opts : [string]
  67. any extra options to pass to SWIG if a source file has the .i
  68. extension.
  69. depends : [string]
  70. list of files that the extension depends on
  71. language : string
  72. extension language (i.e. "c", "c++", "objc"). Will be detected
  73. from the source extensions if not provided.
  74. optional : boolean
  75. specifies that a build failure in the extension should not abort the
  76. build process, but simply not install the failing extension.
  77. """
  78. # When adding arguments to this constructor, be sure to update
  79. # setup_keywords in core.py.
  80. def __init__(
  81. self,
  82. name,
  83. sources,
  84. include_dirs=None,
  85. define_macros=None,
  86. undef_macros=None,
  87. library_dirs=None,
  88. libraries=None,
  89. runtime_library_dirs=None,
  90. extra_objects=None,
  91. extra_compile_args=None,
  92. extra_link_args=None,
  93. export_symbols=None,
  94. swig_opts=None,
  95. depends=None,
  96. language=None,
  97. optional=None,
  98. **kw # To catch unknown keywords
  99. ):
  100. if not isinstance(name, str):
  101. raise AssertionError("'name' must be a string")
  102. if not (isinstance(sources, list) and all(isinstance(v, str) for v in sources)):
  103. raise AssertionError("'sources' must be a list of strings")
  104. self.name = name
  105. self.sources = sources
  106. self.include_dirs = include_dirs or []
  107. self.define_macros = define_macros or []
  108. self.undef_macros = undef_macros or []
  109. self.library_dirs = library_dirs or []
  110. self.libraries = libraries or []
  111. self.runtime_library_dirs = runtime_library_dirs or []
  112. self.extra_objects = extra_objects or []
  113. self.extra_compile_args = extra_compile_args or []
  114. self.extra_link_args = extra_link_args or []
  115. self.export_symbols = export_symbols or []
  116. self.swig_opts = swig_opts or []
  117. self.depends = depends or []
  118. self.language = language
  119. self.optional = optional
  120. # If there are unknown keyword options, warn about them
  121. if len(kw) > 0:
  122. options = [repr(option) for option in kw]
  123. options = ', '.join(sorted(options))
  124. msg = "Unknown Extension options: %s" % options
  125. warnings.warn(msg)
  126. def __repr__(self):
  127. return '<{}.{}({!r}) at {:#x}>'.format(
  128. self.__class__.__module__,
  129. self.__class__.__qualname__,
  130. self.name,
  131. id(self),
  132. )
  133. def read_setup_file(filename): # noqa: C901
  134. """Reads a Setup file and returns Extension instances."""
  135. from distutils.sysconfig import parse_makefile, expand_makefile_vars, _variable_rx
  136. from distutils.text_file import TextFile
  137. from distutils.util import split_quoted
  138. # First pass over the file to gather "VAR = VALUE" assignments.
  139. vars = parse_makefile(filename)
  140. # Second pass to gobble up the real content: lines of the form
  141. # <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...]
  142. file = TextFile(
  143. filename,
  144. strip_comments=1,
  145. skip_blanks=1,
  146. join_lines=1,
  147. lstrip_ws=1,
  148. rstrip_ws=1,
  149. )
  150. try:
  151. extensions = []
  152. while True:
  153. line = file.readline()
  154. if line is None: # eof
  155. break
  156. if _variable_rx.match(line): # VAR=VALUE, handled in first pass
  157. continue
  158. if line[0] == line[-1] == "*":
  159. file.warn("'%s' lines not handled yet" % line)
  160. continue
  161. line = expand_makefile_vars(line, vars)
  162. words = split_quoted(line)
  163. # NB. this parses a slightly different syntax than the old
  164. # makesetup script: here, there must be exactly one extension per
  165. # line, and it must be the first word of the line. I have no idea
  166. # why the old syntax supported multiple extensions per line, as
  167. # they all wind up being the same.
  168. module = words[0]
  169. ext = Extension(module, [])
  170. append_next_word = None
  171. for word in words[1:]:
  172. if append_next_word is not None:
  173. append_next_word.append(word)
  174. append_next_word = None
  175. continue
  176. suffix = os.path.splitext(word)[1]
  177. switch = word[0:2]
  178. value = word[2:]
  179. if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"):
  180. # hmm, should we do something about C vs. C++ sources?
  181. # or leave it up to the CCompiler implementation to
  182. # worry about?
  183. ext.sources.append(word)
  184. elif switch == "-I":
  185. ext.include_dirs.append(value)
  186. elif switch == "-D":
  187. equals = value.find("=")
  188. if equals == -1: # bare "-DFOO" -- no value
  189. ext.define_macros.append((value, None))
  190. else: # "-DFOO=blah"
  191. ext.define_macros.append((value[0:equals], value[equals + 2 :]))
  192. elif switch == "-U":
  193. ext.undef_macros.append(value)
  194. elif switch == "-C": # only here 'cause makesetup has it!
  195. ext.extra_compile_args.append(word)
  196. elif switch == "-l":
  197. ext.libraries.append(value)
  198. elif switch == "-L":
  199. ext.library_dirs.append(value)
  200. elif switch == "-R":
  201. ext.runtime_library_dirs.append(value)
  202. elif word == "-rpath":
  203. append_next_word = ext.runtime_library_dirs
  204. elif word == "-Xlinker":
  205. append_next_word = ext.extra_link_args
  206. elif word == "-Xcompiler":
  207. append_next_word = ext.extra_compile_args
  208. elif switch == "-u":
  209. ext.extra_link_args.append(word)
  210. if not value:
  211. append_next_word = ext.extra_link_args
  212. elif suffix in (".a", ".so", ".sl", ".o", ".dylib"):
  213. # NB. a really faithful emulation of makesetup would
  214. # append a .o file to extra_objects only if it
  215. # had a slash in it; otherwise, it would s/.o/.c/
  216. # and append it to sources. Hmmmm.
  217. ext.extra_objects.append(word)
  218. else:
  219. file.warn("unrecognized argument '%s'" % word)
  220. extensions.append(ext)
  221. finally:
  222. file.close()
  223. return extensions