1
0

extension.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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__(self, name, sources,
  81. include_dirs=None,
  82. define_macros=None,
  83. undef_macros=None,
  84. library_dirs=None,
  85. libraries=None,
  86. runtime_library_dirs=None,
  87. extra_objects=None,
  88. extra_compile_args=None,
  89. extra_link_args=None,
  90. export_symbols=None,
  91. swig_opts = None,
  92. depends=None,
  93. language=None,
  94. optional=None,
  95. **kw # To catch unknown keywords
  96. ):
  97. if not isinstance(name, str):
  98. raise AssertionError("'name' must be a string")
  99. if not (isinstance(sources, list) and
  100. all(isinstance(v, str) for v in sources)):
  101. raise AssertionError("'sources' must be a list of strings")
  102. self.name = name
  103. self.sources = sources
  104. self.include_dirs = include_dirs or []
  105. self.define_macros = define_macros or []
  106. self.undef_macros = undef_macros or []
  107. self.library_dirs = library_dirs or []
  108. self.libraries = libraries or []
  109. self.runtime_library_dirs = runtime_library_dirs or []
  110. self.extra_objects = extra_objects or []
  111. self.extra_compile_args = extra_compile_args or []
  112. self.extra_link_args = extra_link_args or []
  113. self.export_symbols = export_symbols or []
  114. self.swig_opts = swig_opts or []
  115. self.depends = depends or []
  116. self.language = language
  117. self.optional = optional
  118. # If there are unknown keyword options, warn about them
  119. if len(kw) > 0:
  120. options = [repr(option) for option in kw]
  121. options = ', '.join(sorted(options))
  122. msg = "Unknown Extension options: %s" % options
  123. warnings.warn(msg)
  124. def __repr__(self):
  125. return '<%s.%s(%r) at %#x>' % (
  126. self.__class__.__module__,
  127. self.__class__.__qualname__,
  128. self.name,
  129. id(self))
  130. def read_setup_file(filename):
  131. """Reads a Setup file and returns Extension instances."""
  132. from distutils.sysconfig import (parse_makefile, expand_makefile_vars,
  133. _variable_rx)
  134. from distutils.text_file import TextFile
  135. from distutils.util import split_quoted
  136. # First pass over the file to gather "VAR = VALUE" assignments.
  137. vars = parse_makefile(filename)
  138. # Second pass to gobble up the real content: lines of the form
  139. # <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...]
  140. file = TextFile(filename,
  141. strip_comments=1, skip_blanks=1, join_lines=1,
  142. lstrip_ws=1, rstrip_ws=1)
  143. try:
  144. extensions = []
  145. while True:
  146. line = file.readline()
  147. if line is None: # eof
  148. break
  149. if _variable_rx.match(line): # VAR=VALUE, handled in first pass
  150. continue
  151. if line[0] == line[-1] == "*":
  152. file.warn("'%s' lines not handled yet" % line)
  153. continue
  154. line = expand_makefile_vars(line, vars)
  155. words = split_quoted(line)
  156. # NB. this parses a slightly different syntax than the old
  157. # makesetup script: here, there must be exactly one extension per
  158. # line, and it must be the first word of the line. I have no idea
  159. # why the old syntax supported multiple extensions per line, as
  160. # they all wind up being the same.
  161. module = words[0]
  162. ext = Extension(module, [])
  163. append_next_word = None
  164. for word in words[1:]:
  165. if append_next_word is not None:
  166. append_next_word.append(word)
  167. append_next_word = None
  168. continue
  169. suffix = os.path.splitext(word)[1]
  170. switch = word[0:2] ; value = word[2:]
  171. if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"):
  172. # hmm, should we do something about C vs. C++ sources?
  173. # or leave it up to the CCompiler implementation to
  174. # worry about?
  175. ext.sources.append(word)
  176. elif switch == "-I":
  177. ext.include_dirs.append(value)
  178. elif switch == "-D":
  179. equals = value.find("=")
  180. if equals == -1: # bare "-DFOO" -- no value
  181. ext.define_macros.append((value, None))
  182. else: # "-DFOO=blah"
  183. ext.define_macros.append((value[0:equals],
  184. value[equals+2:]))
  185. elif switch == "-U":
  186. ext.undef_macros.append(value)
  187. elif switch == "-C": # only here 'cause makesetup has it!
  188. ext.extra_compile_args.append(word)
  189. elif switch == "-l":
  190. ext.libraries.append(value)
  191. elif switch == "-L":
  192. ext.library_dirs.append(value)
  193. elif switch == "-R":
  194. ext.runtime_library_dirs.append(value)
  195. elif word == "-rpath":
  196. append_next_word = ext.runtime_library_dirs
  197. elif word == "-Xlinker":
  198. append_next_word = ext.extra_link_args
  199. elif word == "-Xcompiler":
  200. append_next_word = ext.extra_compile_args
  201. elif switch == "-u":
  202. ext.extra_link_args.append(word)
  203. if not value:
  204. append_next_word = ext.extra_link_args
  205. elif suffix in (".a", ".so", ".sl", ".o", ".dylib"):
  206. # NB. a really faithful emulation of makesetup would
  207. # append a .o file to extra_objects only if it
  208. # had a slash in it; otherwise, it would s/.o/.c/
  209. # and append it to sources. Hmmmm.
  210. ext.extra_objects.append(word)
  211. else:
  212. file.warn("unrecognized argument '%s'" % word)
  213. extensions.append(ext)
  214. finally:
  215. file.close()
  216. return extensions