extension.py 10 KB

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