build_clib.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. """ Modified version of build_clib that handles fortran source files.
  2. """
  3. from __future__ import division, absolute_import, print_function
  4. import os
  5. from glob import glob
  6. import shutil
  7. from distutils.command.build_clib import build_clib as old_build_clib
  8. from distutils.errors import DistutilsSetupError, DistutilsError, \
  9. DistutilsFileError
  10. from numpy.distutils import log
  11. from distutils.dep_util import newer_group
  12. from numpy.distutils.misc_util import filter_sources, has_f_sources,\
  13. has_cxx_sources, all_strings, get_lib_source_files, is_sequence, \
  14. get_numpy_include_dirs
  15. # Fix Python distutils bug sf #1718574:
  16. _l = old_build_clib.user_options
  17. for _i in range(len(_l)):
  18. if _l[_i][0] in ['build-clib', 'build-temp']:
  19. _l[_i] = (_l[_i][0] + '=',) + _l[_i][1:]
  20. #
  21. class build_clib(old_build_clib):
  22. description = "build C/C++/F libraries used by Python extensions"
  23. user_options = old_build_clib.user_options + [
  24. ('fcompiler=', None,
  25. "specify the Fortran compiler type"),
  26. ('inplace', 'i', 'Build in-place'),
  27. ('parallel=', 'j',
  28. "number of parallel jobs"),
  29. ]
  30. boolean_options = old_build_clib.boolean_options + ['inplace']
  31. def initialize_options(self):
  32. old_build_clib.initialize_options(self)
  33. self.fcompiler = None
  34. self.inplace = 0
  35. self.parallel = None
  36. def finalize_options(self):
  37. if self.parallel:
  38. try:
  39. self.parallel = int(self.parallel)
  40. except ValueError:
  41. raise ValueError("--parallel/-j argument must be an integer")
  42. old_build_clib.finalize_options(self)
  43. self.set_undefined_options('build', ('parallel', 'parallel'))
  44. def have_f_sources(self):
  45. for (lib_name, build_info) in self.libraries:
  46. if has_f_sources(build_info.get('sources', [])):
  47. return True
  48. return False
  49. def have_cxx_sources(self):
  50. for (lib_name, build_info) in self.libraries:
  51. if has_cxx_sources(build_info.get('sources', [])):
  52. return True
  53. return False
  54. def run(self):
  55. if not self.libraries:
  56. return
  57. # Make sure that library sources are complete.
  58. languages = []
  59. # Make sure that extension sources are complete.
  60. self.run_command('build_src')
  61. for (lib_name, build_info) in self.libraries:
  62. l = build_info.get('language', None)
  63. if l and l not in languages:
  64. languages.append(l)
  65. from distutils.ccompiler import new_compiler
  66. self.compiler = new_compiler(compiler=self.compiler,
  67. dry_run=self.dry_run,
  68. force=self.force)
  69. self.compiler.customize(self.distribution,
  70. need_cxx=self.have_cxx_sources())
  71. libraries = self.libraries
  72. self.libraries = None
  73. self.compiler.customize_cmd(self)
  74. self.libraries = libraries
  75. self.compiler.show_customization()
  76. if self.have_f_sources():
  77. from numpy.distutils.fcompiler import new_fcompiler
  78. self._f_compiler = new_fcompiler(compiler=self.fcompiler,
  79. verbose=self.verbose,
  80. dry_run=self.dry_run,
  81. force=self.force,
  82. requiref90='f90' in languages,
  83. c_compiler=self.compiler)
  84. if self._f_compiler is not None:
  85. self._f_compiler.customize(self.distribution)
  86. libraries = self.libraries
  87. self.libraries = None
  88. self._f_compiler.customize_cmd(self)
  89. self.libraries = libraries
  90. self._f_compiler.show_customization()
  91. else:
  92. self._f_compiler = None
  93. self.build_libraries(self.libraries)
  94. if self.inplace:
  95. for l in self.distribution.installed_libraries:
  96. libname = self.compiler.library_filename(l.name)
  97. source = os.path.join(self.build_clib, libname)
  98. target = os.path.join(l.target_dir, libname)
  99. self.mkpath(l.target_dir)
  100. shutil.copy(source, target)
  101. def get_source_files(self):
  102. self.check_library_list(self.libraries)
  103. filenames = []
  104. for lib in self.libraries:
  105. filenames.extend(get_lib_source_files(lib))
  106. return filenames
  107. def build_libraries(self, libraries):
  108. for (lib_name, build_info) in libraries:
  109. self.build_a_library(build_info, lib_name, libraries)
  110. def build_a_library(self, build_info, lib_name, libraries):
  111. # default compilers
  112. compiler = self.compiler
  113. fcompiler = self._f_compiler
  114. sources = build_info.get('sources')
  115. if sources is None or not is_sequence(sources):
  116. raise DistutilsSetupError(("in 'libraries' option (library '%s'), " +
  117. "'sources' must be present and must be " +
  118. "a list of source filenames") % lib_name)
  119. sources = list(sources)
  120. c_sources, cxx_sources, f_sources, fmodule_sources \
  121. = filter_sources(sources)
  122. requiref90 = not not fmodule_sources or \
  123. build_info.get('language', 'c') == 'f90'
  124. # save source type information so that build_ext can use it.
  125. source_languages = []
  126. if c_sources:
  127. source_languages.append('c')
  128. if cxx_sources:
  129. source_languages.append('c++')
  130. if requiref90:
  131. source_languages.append('f90')
  132. elif f_sources:
  133. source_languages.append('f77')
  134. build_info['source_languages'] = source_languages
  135. lib_file = compiler.library_filename(lib_name,
  136. output_dir=self.build_clib)
  137. depends = sources + build_info.get('depends', [])
  138. if not (self.force or newer_group(depends, lib_file, 'newer')):
  139. log.debug("skipping '%s' library (up-to-date)", lib_name)
  140. return
  141. else:
  142. log.info("building '%s' library", lib_name)
  143. config_fc = build_info.get('config_fc', {})
  144. if fcompiler is not None and config_fc:
  145. log.info('using additional config_fc from setup script '
  146. 'for fortran compiler: %s'
  147. % (config_fc,))
  148. from numpy.distutils.fcompiler import new_fcompiler
  149. fcompiler = new_fcompiler(compiler=fcompiler.compiler_type,
  150. verbose=self.verbose,
  151. dry_run=self.dry_run,
  152. force=self.force,
  153. requiref90=requiref90,
  154. c_compiler=self.compiler)
  155. if fcompiler is not None:
  156. dist = self.distribution
  157. base_config_fc = dist.get_option_dict('config_fc').copy()
  158. base_config_fc.update(config_fc)
  159. fcompiler.customize(base_config_fc)
  160. # check availability of Fortran compilers
  161. if (f_sources or fmodule_sources) and fcompiler is None:
  162. raise DistutilsError("library %s has Fortran sources"
  163. " but no Fortran compiler found" % (lib_name))
  164. if fcompiler is not None:
  165. fcompiler.extra_f77_compile_args = build_info.get(
  166. 'extra_f77_compile_args') or []
  167. fcompiler.extra_f90_compile_args = build_info.get(
  168. 'extra_f90_compile_args') or []
  169. macros = build_info.get('macros')
  170. include_dirs = build_info.get('include_dirs')
  171. if include_dirs is None:
  172. include_dirs = []
  173. extra_postargs = build_info.get('extra_compiler_args') or []
  174. include_dirs.extend(get_numpy_include_dirs())
  175. # where compiled F90 module files are:
  176. module_dirs = build_info.get('module_dirs') or []
  177. module_build_dir = os.path.dirname(lib_file)
  178. if requiref90:
  179. self.mkpath(module_build_dir)
  180. if compiler.compiler_type == 'msvc':
  181. # this hack works around the msvc compiler attributes
  182. # problem, msvc uses its own convention :(
  183. c_sources += cxx_sources
  184. cxx_sources = []
  185. objects = []
  186. if c_sources:
  187. log.info("compiling C sources")
  188. objects = compiler.compile(c_sources,
  189. output_dir=self.build_temp,
  190. macros=macros,
  191. include_dirs=include_dirs,
  192. debug=self.debug,
  193. extra_postargs=extra_postargs)
  194. if cxx_sources:
  195. log.info("compiling C++ sources")
  196. cxx_compiler = compiler.cxx_compiler()
  197. cxx_objects = cxx_compiler.compile(cxx_sources,
  198. output_dir=self.build_temp,
  199. macros=macros,
  200. include_dirs=include_dirs,
  201. debug=self.debug,
  202. extra_postargs=extra_postargs)
  203. objects.extend(cxx_objects)
  204. if f_sources or fmodule_sources:
  205. extra_postargs = []
  206. f_objects = []
  207. if requiref90:
  208. if fcompiler.module_dir_switch is None:
  209. existing_modules = glob('*.mod')
  210. extra_postargs += fcompiler.module_options(
  211. module_dirs, module_build_dir)
  212. if fmodule_sources:
  213. log.info("compiling Fortran 90 module sources")
  214. f_objects += fcompiler.compile(fmodule_sources,
  215. output_dir=self.build_temp,
  216. macros=macros,
  217. include_dirs=include_dirs,
  218. debug=self.debug,
  219. extra_postargs=extra_postargs)
  220. if requiref90 and self._f_compiler.module_dir_switch is None:
  221. # move new compiled F90 module files to module_build_dir
  222. for f in glob('*.mod'):
  223. if f in existing_modules:
  224. continue
  225. t = os.path.join(module_build_dir, f)
  226. if os.path.abspath(f) == os.path.abspath(t):
  227. continue
  228. if os.path.isfile(t):
  229. os.remove(t)
  230. try:
  231. self.move_file(f, module_build_dir)
  232. except DistutilsFileError:
  233. log.warn('failed to move %r to %r'
  234. % (f, module_build_dir))
  235. if f_sources:
  236. log.info("compiling Fortran sources")
  237. f_objects += fcompiler.compile(f_sources,
  238. output_dir=self.build_temp,
  239. macros=macros,
  240. include_dirs=include_dirs,
  241. debug=self.debug,
  242. extra_postargs=extra_postargs)
  243. else:
  244. f_objects = []
  245. if f_objects and not fcompiler.can_ccompiler_link(compiler):
  246. # Default linker cannot link Fortran object files, and results
  247. # need to be wrapped later. Instead of creating a real static
  248. # library, just keep track of the object files.
  249. listfn = os.path.join(self.build_clib,
  250. lib_name + '.fobjects')
  251. with open(listfn, 'w') as f:
  252. f.write("\n".join(os.path.abspath(obj) for obj in f_objects))
  253. listfn = os.path.join(self.build_clib,
  254. lib_name + '.cobjects')
  255. with open(listfn, 'w') as f:
  256. f.write("\n".join(os.path.abspath(obj) for obj in objects))
  257. # create empty "library" file for dependency tracking
  258. lib_fname = os.path.join(self.build_clib,
  259. lib_name + compiler.static_lib_extension)
  260. with open(lib_fname, 'wb') as f:
  261. pass
  262. else:
  263. # assume that default linker is suitable for
  264. # linking Fortran object files
  265. objects.extend(f_objects)
  266. compiler.create_static_lib(objects, lib_name,
  267. output_dir=self.build_clib,
  268. debug=self.debug)
  269. # fix library dependencies
  270. clib_libraries = build_info.get('libraries', [])
  271. for lname, binfo in libraries:
  272. if lname in clib_libraries:
  273. clib_libraries.extend(binfo.get('libraries', []))
  274. if clib_libraries:
  275. build_info['libraries'] = clib_libraries