__init__.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. """numpy.distutils.fcompiler
  2. Contains FCompiler, an abstract base class that defines the interface
  3. for the numpy.distutils Fortran compiler abstraction model.
  4. Terminology:
  5. To be consistent, where the term 'executable' is used, it means the single
  6. file, like 'gcc', that is executed, and should be a string. In contrast,
  7. 'command' means the entire command line, like ['gcc', '-c', 'file.c'], and
  8. should be a list.
  9. But note that FCompiler.executables is actually a dictionary of commands.
  10. """
  11. from __future__ import division, absolute_import, print_function
  12. __all__ = ['FCompiler', 'new_fcompiler', 'show_fcompilers',
  13. 'dummy_fortran_file']
  14. import os
  15. import sys
  16. import re
  17. import types
  18. from numpy.compat import open_latin1
  19. from distutils.sysconfig import get_python_lib
  20. from distutils.fancy_getopt import FancyGetopt
  21. from distutils.errors import DistutilsModuleError, \
  22. DistutilsExecError, CompileError, LinkError, DistutilsPlatformError
  23. from distutils.util import split_quoted, strtobool
  24. from numpy.distutils.ccompiler import CCompiler, gen_lib_options
  25. from numpy.distutils import log
  26. from numpy.distutils.misc_util import is_string, all_strings, is_sequence, \
  27. make_temp_file, get_shared_lib_extension
  28. from numpy.distutils.exec_command import find_executable
  29. from numpy.distutils.compat import get_exception
  30. from numpy.distutils import _shell_utils
  31. from .environment import EnvironmentConfig
  32. __metaclass__ = type
  33. class CompilerNotFound(Exception):
  34. pass
  35. def flaglist(s):
  36. if is_string(s):
  37. return split_quoted(s)
  38. else:
  39. return s
  40. def str2bool(s):
  41. if is_string(s):
  42. return strtobool(s)
  43. return bool(s)
  44. def is_sequence_of_strings(seq):
  45. return is_sequence(seq) and all_strings(seq)
  46. class FCompiler(CCompiler):
  47. """Abstract base class to define the interface that must be implemented
  48. by real Fortran compiler classes.
  49. Methods that subclasses may redefine:
  50. update_executables(), find_executables(), get_version()
  51. get_flags(), get_flags_opt(), get_flags_arch(), get_flags_debug()
  52. get_flags_f77(), get_flags_opt_f77(), get_flags_arch_f77(),
  53. get_flags_debug_f77(), get_flags_f90(), get_flags_opt_f90(),
  54. get_flags_arch_f90(), get_flags_debug_f90(),
  55. get_flags_fix(), get_flags_linker_so()
  56. DON'T call these methods (except get_version) after
  57. constructing a compiler instance or inside any other method.
  58. All methods, except update_executables() and find_executables(),
  59. may call the get_version() method.
  60. After constructing a compiler instance, always call customize(dist=None)
  61. method that finalizes compiler construction and makes the following
  62. attributes available:
  63. compiler_f77
  64. compiler_f90
  65. compiler_fix
  66. linker_so
  67. archiver
  68. ranlib
  69. libraries
  70. library_dirs
  71. """
  72. # These are the environment variables and distutils keys used.
  73. # Each configuration description is
  74. # (<hook name>, <environment variable>, <key in distutils.cfg>, <convert>, <append>)
  75. # The hook names are handled by the self._environment_hook method.
  76. # - names starting with 'self.' call methods in this class
  77. # - names starting with 'exe.' return the key in the executables dict
  78. # - names like 'flags.YYY' return self.get_flag_YYY()
  79. # convert is either None or a function to convert a string to the
  80. # appropriate type used.
  81. distutils_vars = EnvironmentConfig(
  82. distutils_section='config_fc',
  83. noopt = (None, None, 'noopt', str2bool, False),
  84. noarch = (None, None, 'noarch', str2bool, False),
  85. debug = (None, None, 'debug', str2bool, False),
  86. verbose = (None, None, 'verbose', str2bool, False),
  87. )
  88. command_vars = EnvironmentConfig(
  89. distutils_section='config_fc',
  90. compiler_f77 = ('exe.compiler_f77', 'F77', 'f77exec', None, False),
  91. compiler_f90 = ('exe.compiler_f90', 'F90', 'f90exec', None, False),
  92. compiler_fix = ('exe.compiler_fix', 'F90', 'f90exec', None, False),
  93. version_cmd = ('exe.version_cmd', None, None, None, False),
  94. linker_so = ('exe.linker_so', 'LDSHARED', 'ldshared', None, False),
  95. linker_exe = ('exe.linker_exe', 'LD', 'ld', None, False),
  96. archiver = (None, 'AR', 'ar', None, False),
  97. ranlib = (None, 'RANLIB', 'ranlib', None, False),
  98. )
  99. flag_vars = EnvironmentConfig(
  100. distutils_section='config_fc',
  101. f77 = ('flags.f77', 'F77FLAGS', 'f77flags', flaglist, True),
  102. f90 = ('flags.f90', 'F90FLAGS', 'f90flags', flaglist, True),
  103. free = ('flags.free', 'FREEFLAGS', 'freeflags', flaglist, True),
  104. fix = ('flags.fix', None, None, flaglist, False),
  105. opt = ('flags.opt', 'FOPT', 'opt', flaglist, True),
  106. opt_f77 = ('flags.opt_f77', None, None, flaglist, False),
  107. opt_f90 = ('flags.opt_f90', None, None, flaglist, False),
  108. arch = ('flags.arch', 'FARCH', 'arch', flaglist, False),
  109. arch_f77 = ('flags.arch_f77', None, None, flaglist, False),
  110. arch_f90 = ('flags.arch_f90', None, None, flaglist, False),
  111. debug = ('flags.debug', 'FDEBUG', 'fdebug', flaglist, True),
  112. debug_f77 = ('flags.debug_f77', None, None, flaglist, False),
  113. debug_f90 = ('flags.debug_f90', None, None, flaglist, False),
  114. flags = ('self.get_flags', 'FFLAGS', 'fflags', flaglist, True),
  115. linker_so = ('flags.linker_so', 'LDFLAGS', 'ldflags', flaglist, True),
  116. linker_exe = ('flags.linker_exe', 'LDFLAGS', 'ldflags', flaglist, True),
  117. ar = ('flags.ar', 'ARFLAGS', 'arflags', flaglist, True),
  118. )
  119. language_map = {'.f': 'f77',
  120. '.for': 'f77',
  121. '.F': 'f77', # XXX: needs preprocessor
  122. '.ftn': 'f77',
  123. '.f77': 'f77',
  124. '.f90': 'f90',
  125. '.F90': 'f90', # XXX: needs preprocessor
  126. '.f95': 'f90',
  127. }
  128. language_order = ['f90', 'f77']
  129. # These will be set by the subclass
  130. compiler_type = None
  131. compiler_aliases = ()
  132. version_pattern = None
  133. possible_executables = []
  134. executables = {
  135. 'version_cmd': ["f77", "-v"],
  136. 'compiler_f77': ["f77"],
  137. 'compiler_f90': ["f90"],
  138. 'compiler_fix': ["f90", "-fixed"],
  139. 'linker_so': ["f90", "-shared"],
  140. 'linker_exe': ["f90"],
  141. 'archiver': ["ar", "-cr"],
  142. 'ranlib': None,
  143. }
  144. # If compiler does not support compiling Fortran 90 then it can
  145. # suggest using another compiler. For example, gnu would suggest
  146. # gnu95 compiler type when there are F90 sources.
  147. suggested_f90_compiler = None
  148. compile_switch = "-c"
  149. object_switch = "-o " # Ending space matters! It will be stripped
  150. # but if it is missing then object_switch
  151. # will be prefixed to object file name by
  152. # string concatenation.
  153. library_switch = "-o " # Ditto!
  154. # Switch to specify where module files are created and searched
  155. # for USE statement. Normally it is a string and also here ending
  156. # space matters. See above.
  157. module_dir_switch = None
  158. # Switch to specify where module files are searched for USE statement.
  159. module_include_switch = '-I'
  160. pic_flags = [] # Flags to create position-independent code
  161. src_extensions = ['.for', '.ftn', '.f77', '.f', '.f90', '.f95', '.F', '.F90', '.FOR']
  162. obj_extension = ".o"
  163. shared_lib_extension = get_shared_lib_extension()
  164. static_lib_extension = ".a" # or .lib
  165. static_lib_format = "lib%s%s" # or %s%s
  166. shared_lib_format = "%s%s"
  167. exe_extension = ""
  168. _exe_cache = {}
  169. _executable_keys = ['version_cmd', 'compiler_f77', 'compiler_f90',
  170. 'compiler_fix', 'linker_so', 'linker_exe', 'archiver',
  171. 'ranlib']
  172. # This will be set by new_fcompiler when called in
  173. # command/{build_ext.py, build_clib.py, config.py} files.
  174. c_compiler = None
  175. # extra_{f77,f90}_compile_args are set by build_ext.build_extension method
  176. extra_f77_compile_args = []
  177. extra_f90_compile_args = []
  178. def __init__(self, *args, **kw):
  179. CCompiler.__init__(self, *args, **kw)
  180. self.distutils_vars = self.distutils_vars.clone(self._environment_hook)
  181. self.command_vars = self.command_vars.clone(self._environment_hook)
  182. self.flag_vars = self.flag_vars.clone(self._environment_hook)
  183. self.executables = self.executables.copy()
  184. for e in self._executable_keys:
  185. if e not in self.executables:
  186. self.executables[e] = None
  187. # Some methods depend on .customize() being called first, so
  188. # this keeps track of whether that's happened yet.
  189. self._is_customised = False
  190. def __copy__(self):
  191. obj = self.__new__(self.__class__)
  192. obj.__dict__.update(self.__dict__)
  193. obj.distutils_vars = obj.distutils_vars.clone(obj._environment_hook)
  194. obj.command_vars = obj.command_vars.clone(obj._environment_hook)
  195. obj.flag_vars = obj.flag_vars.clone(obj._environment_hook)
  196. obj.executables = obj.executables.copy()
  197. return obj
  198. def copy(self):
  199. return self.__copy__()
  200. # Use properties for the attributes used by CCompiler. Setting them
  201. # as attributes from the self.executables dictionary is error-prone,
  202. # so we get them from there each time.
  203. def _command_property(key):
  204. def fget(self):
  205. assert self._is_customised
  206. return self.executables[key]
  207. return property(fget=fget)
  208. version_cmd = _command_property('version_cmd')
  209. compiler_f77 = _command_property('compiler_f77')
  210. compiler_f90 = _command_property('compiler_f90')
  211. compiler_fix = _command_property('compiler_fix')
  212. linker_so = _command_property('linker_so')
  213. linker_exe = _command_property('linker_exe')
  214. archiver = _command_property('archiver')
  215. ranlib = _command_property('ranlib')
  216. # Make our terminology consistent.
  217. def set_executable(self, key, value):
  218. self.set_command(key, value)
  219. def set_commands(self, **kw):
  220. for k, v in kw.items():
  221. self.set_command(k, v)
  222. def set_command(self, key, value):
  223. if not key in self._executable_keys:
  224. raise ValueError(
  225. "unknown executable '%s' for class %s" %
  226. (key, self.__class__.__name__))
  227. if is_string(value):
  228. value = split_quoted(value)
  229. assert value is None or is_sequence_of_strings(value[1:]), (key, value)
  230. self.executables[key] = value
  231. ######################################################################
  232. ## Methods that subclasses may redefine. But don't call these methods!
  233. ## They are private to FCompiler class and may return unexpected
  234. ## results if used elsewhere. So, you have been warned..
  235. def find_executables(self):
  236. """Go through the self.executables dictionary, and attempt to
  237. find and assign appropriate executables.
  238. Executable names are looked for in the environment (environment
  239. variables, the distutils.cfg, and command line), the 0th-element of
  240. the command list, and the self.possible_executables list.
  241. Also, if the 0th element is "<F77>" or "<F90>", the Fortran 77
  242. or the Fortran 90 compiler executable is used, unless overridden
  243. by an environment setting.
  244. Subclasses should call this if overridden.
  245. """
  246. assert self._is_customised
  247. exe_cache = self._exe_cache
  248. def cached_find_executable(exe):
  249. if exe in exe_cache:
  250. return exe_cache[exe]
  251. fc_exe = find_executable(exe)
  252. exe_cache[exe] = exe_cache[fc_exe] = fc_exe
  253. return fc_exe
  254. def verify_command_form(name, value):
  255. if value is not None and not is_sequence_of_strings(value):
  256. raise ValueError(
  257. "%s value %r is invalid in class %s" %
  258. (name, value, self.__class__.__name__))
  259. def set_exe(exe_key, f77=None, f90=None):
  260. cmd = self.executables.get(exe_key, None)
  261. if not cmd:
  262. return None
  263. # Note that we get cmd[0] here if the environment doesn't
  264. # have anything set
  265. exe_from_environ = getattr(self.command_vars, exe_key)
  266. if not exe_from_environ:
  267. possibles = [f90, f77] + self.possible_executables
  268. else:
  269. possibles = [exe_from_environ] + self.possible_executables
  270. seen = set()
  271. unique_possibles = []
  272. for e in possibles:
  273. if e == '<F77>':
  274. e = f77
  275. elif e == '<F90>':
  276. e = f90
  277. if not e or e in seen:
  278. continue
  279. seen.add(e)
  280. unique_possibles.append(e)
  281. for exe in unique_possibles:
  282. fc_exe = cached_find_executable(exe)
  283. if fc_exe:
  284. cmd[0] = fc_exe
  285. return fc_exe
  286. self.set_command(exe_key, None)
  287. return None
  288. ctype = self.compiler_type
  289. f90 = set_exe('compiler_f90')
  290. if not f90:
  291. f77 = set_exe('compiler_f77')
  292. if f77:
  293. log.warn('%s: no Fortran 90 compiler found' % ctype)
  294. else:
  295. raise CompilerNotFound('%s: f90 nor f77' % ctype)
  296. else:
  297. f77 = set_exe('compiler_f77', f90=f90)
  298. if not f77:
  299. log.warn('%s: no Fortran 77 compiler found' % ctype)
  300. set_exe('compiler_fix', f90=f90)
  301. set_exe('linker_so', f77=f77, f90=f90)
  302. set_exe('linker_exe', f77=f77, f90=f90)
  303. set_exe('version_cmd', f77=f77, f90=f90)
  304. set_exe('archiver')
  305. set_exe('ranlib')
  306. def update_executables(elf):
  307. """Called at the beginning of customisation. Subclasses should
  308. override this if they need to set up the executables dictionary.
  309. Note that self.find_executables() is run afterwards, so the
  310. self.executables dictionary values can contain <F77> or <F90> as
  311. the command, which will be replaced by the found F77 or F90
  312. compiler.
  313. """
  314. pass
  315. def get_flags(self):
  316. """List of flags common to all compiler types."""
  317. return [] + self.pic_flags
  318. def _get_command_flags(self, key):
  319. cmd = self.executables.get(key, None)
  320. if cmd is None:
  321. return []
  322. return cmd[1:]
  323. def get_flags_f77(self):
  324. """List of Fortran 77 specific flags."""
  325. return self._get_command_flags('compiler_f77')
  326. def get_flags_f90(self):
  327. """List of Fortran 90 specific flags."""
  328. return self._get_command_flags('compiler_f90')
  329. def get_flags_free(self):
  330. """List of Fortran 90 free format specific flags."""
  331. return []
  332. def get_flags_fix(self):
  333. """List of Fortran 90 fixed format specific flags."""
  334. return self._get_command_flags('compiler_fix')
  335. def get_flags_linker_so(self):
  336. """List of linker flags to build a shared library."""
  337. return self._get_command_flags('linker_so')
  338. def get_flags_linker_exe(self):
  339. """List of linker flags to build an executable."""
  340. return self._get_command_flags('linker_exe')
  341. def get_flags_ar(self):
  342. """List of archiver flags. """
  343. return self._get_command_flags('archiver')
  344. def get_flags_opt(self):
  345. """List of architecture independent compiler flags."""
  346. return []
  347. def get_flags_arch(self):
  348. """List of architecture dependent compiler flags."""
  349. return []
  350. def get_flags_debug(self):
  351. """List of compiler flags to compile with debugging information."""
  352. return []
  353. get_flags_opt_f77 = get_flags_opt_f90 = get_flags_opt
  354. get_flags_arch_f77 = get_flags_arch_f90 = get_flags_arch
  355. get_flags_debug_f77 = get_flags_debug_f90 = get_flags_debug
  356. def get_libraries(self):
  357. """List of compiler libraries."""
  358. return self.libraries[:]
  359. def get_library_dirs(self):
  360. """List of compiler library directories."""
  361. return self.library_dirs[:]
  362. def get_version(self, force=False, ok_status=[0]):
  363. assert self._is_customised
  364. version = CCompiler.get_version(self, force=force, ok_status=ok_status)
  365. if version is None:
  366. raise CompilerNotFound()
  367. return version
  368. ############################################################
  369. ## Public methods:
  370. def customize(self, dist = None):
  371. """Customize Fortran compiler.
  372. This method gets Fortran compiler specific information from
  373. (i) class definition, (ii) environment, (iii) distutils config
  374. files, and (iv) command line (later overrides earlier).
  375. This method should be always called after constructing a
  376. compiler instance. But not in __init__ because Distribution
  377. instance is needed for (iii) and (iv).
  378. """
  379. log.info('customize %s' % (self.__class__.__name__))
  380. self._is_customised = True
  381. self.distutils_vars.use_distribution(dist)
  382. self.command_vars.use_distribution(dist)
  383. self.flag_vars.use_distribution(dist)
  384. self.update_executables()
  385. # find_executables takes care of setting the compiler commands,
  386. # version_cmd, linker_so, linker_exe, ar, and ranlib
  387. self.find_executables()
  388. noopt = self.distutils_vars.get('noopt', False)
  389. noarch = self.distutils_vars.get('noarch', noopt)
  390. debug = self.distutils_vars.get('debug', False)
  391. f77 = self.command_vars.compiler_f77
  392. f90 = self.command_vars.compiler_f90
  393. f77flags = []
  394. f90flags = []
  395. freeflags = []
  396. fixflags = []
  397. if f77:
  398. f77 = _shell_utils.NativeParser.split(f77)
  399. f77flags = self.flag_vars.f77
  400. if f90:
  401. f90 = _shell_utils.NativeParser.split(f90)
  402. f90flags = self.flag_vars.f90
  403. freeflags = self.flag_vars.free
  404. # XXX Assuming that free format is default for f90 compiler.
  405. fix = self.command_vars.compiler_fix
  406. # NOTE: this and similar examples are probably just
  407. # exluding --coverage flag when F90 = gfortran --coverage
  408. # instead of putting that flag somewhere more appropriate
  409. # this and similar examples where a Fortran compiler
  410. # environment variable has been customized by CI or a user
  411. # should perhaps eventually be more throughly tested and more
  412. # robustly handled
  413. if fix:
  414. fix = _shell_utils.NativeParser.split(fix)
  415. fixflags = self.flag_vars.fix + f90flags
  416. oflags, aflags, dflags = [], [], []
  417. # examine get_flags_<tag>_<compiler> for extra flags
  418. # only add them if the method is different from get_flags_<tag>
  419. def get_flags(tag, flags):
  420. # note that self.flag_vars.<tag> calls self.get_flags_<tag>()
  421. flags.extend(getattr(self.flag_vars, tag))
  422. this_get = getattr(self, 'get_flags_' + tag)
  423. for name, c, flagvar in [('f77', f77, f77flags),
  424. ('f90', f90, f90flags),
  425. ('f90', fix, fixflags)]:
  426. t = '%s_%s' % (tag, name)
  427. if c and this_get is not getattr(self, 'get_flags_' + t):
  428. flagvar.extend(getattr(self.flag_vars, t))
  429. if not noopt:
  430. get_flags('opt', oflags)
  431. if not noarch:
  432. get_flags('arch', aflags)
  433. if debug:
  434. get_flags('debug', dflags)
  435. fflags = self.flag_vars.flags + dflags + oflags + aflags
  436. if f77:
  437. self.set_commands(compiler_f77=f77+f77flags+fflags)
  438. if f90:
  439. self.set_commands(compiler_f90=f90+freeflags+f90flags+fflags)
  440. if fix:
  441. self.set_commands(compiler_fix=fix+fixflags+fflags)
  442. #XXX: Do we need LDSHARED->SOSHARED, LDFLAGS->SOFLAGS
  443. linker_so = self.linker_so
  444. if linker_so:
  445. linker_so_flags = self.flag_vars.linker_so
  446. if sys.platform.startswith('aix'):
  447. python_lib = get_python_lib(standard_lib=1)
  448. ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')
  449. python_exp = os.path.join(python_lib, 'config', 'python.exp')
  450. linker_so = [ld_so_aix] + linker_so + ['-bI:'+python_exp]
  451. self.set_commands(linker_so=linker_so+linker_so_flags)
  452. linker_exe = self.linker_exe
  453. if linker_exe:
  454. linker_exe_flags = self.flag_vars.linker_exe
  455. self.set_commands(linker_exe=linker_exe+linker_exe_flags)
  456. ar = self.command_vars.archiver
  457. if ar:
  458. arflags = self.flag_vars.ar
  459. self.set_commands(archiver=[ar]+arflags)
  460. self.set_library_dirs(self.get_library_dirs())
  461. self.set_libraries(self.get_libraries())
  462. def dump_properties(self):
  463. """Print out the attributes of a compiler instance."""
  464. props = []
  465. for key in list(self.executables.keys()) + \
  466. ['version', 'libraries', 'library_dirs',
  467. 'object_switch', 'compile_switch']:
  468. if hasattr(self, key):
  469. v = getattr(self, key)
  470. props.append((key, None, '= '+repr(v)))
  471. props.sort()
  472. pretty_printer = FancyGetopt(props)
  473. for l in pretty_printer.generate_help("%s instance properties:" \
  474. % (self.__class__.__name__)):
  475. if l[:4]==' --':
  476. l = ' ' + l[4:]
  477. print(l)
  478. ###################
  479. def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
  480. """Compile 'src' to product 'obj'."""
  481. src_flags = {}
  482. if is_f_file(src) and not has_f90_header(src):
  483. flavor = ':f77'
  484. compiler = self.compiler_f77
  485. src_flags = get_f77flags(src)
  486. extra_compile_args = self.extra_f77_compile_args or []
  487. elif is_free_format(src):
  488. flavor = ':f90'
  489. compiler = self.compiler_f90
  490. if compiler is None:
  491. raise DistutilsExecError('f90 not supported by %s needed for %s'\
  492. % (self.__class__.__name__, src))
  493. extra_compile_args = self.extra_f90_compile_args or []
  494. else:
  495. flavor = ':fix'
  496. compiler = self.compiler_fix
  497. if compiler is None:
  498. raise DistutilsExecError('f90 (fixed) not supported by %s needed for %s'\
  499. % (self.__class__.__name__, src))
  500. extra_compile_args = self.extra_f90_compile_args or []
  501. if self.object_switch[-1]==' ':
  502. o_args = [self.object_switch.strip(), obj]
  503. else:
  504. o_args = [self.object_switch.strip()+obj]
  505. assert self.compile_switch.strip()
  506. s_args = [self.compile_switch, src]
  507. if extra_compile_args:
  508. log.info('extra %s options: %r' \
  509. % (flavor[1:], ' '.join(extra_compile_args)))
  510. extra_flags = src_flags.get(self.compiler_type, [])
  511. if extra_flags:
  512. log.info('using compile options from source: %r' \
  513. % ' '.join(extra_flags))
  514. command = compiler + cc_args + extra_flags + s_args + o_args \
  515. + extra_postargs + extra_compile_args
  516. display = '%s: %s' % (os.path.basename(compiler[0]) + flavor,
  517. src)
  518. try:
  519. self.spawn(command, display=display)
  520. except DistutilsExecError:
  521. msg = str(get_exception())
  522. raise CompileError(msg)
  523. def module_options(self, module_dirs, module_build_dir):
  524. options = []
  525. if self.module_dir_switch is not None:
  526. if self.module_dir_switch[-1]==' ':
  527. options.extend([self.module_dir_switch.strip(), module_build_dir])
  528. else:
  529. options.append(self.module_dir_switch.strip()+module_build_dir)
  530. else:
  531. print('XXX: module_build_dir=%r option ignored' % (module_build_dir))
  532. print('XXX: Fix module_dir_switch for ', self.__class__.__name__)
  533. if self.module_include_switch is not None:
  534. for d in [module_build_dir]+module_dirs:
  535. options.append('%s%s' % (self.module_include_switch, d))
  536. else:
  537. print('XXX: module_dirs=%r option ignored' % (module_dirs))
  538. print('XXX: Fix module_include_switch for ', self.__class__.__name__)
  539. return options
  540. def library_option(self, lib):
  541. return "-l" + lib
  542. def library_dir_option(self, dir):
  543. return "-L" + dir
  544. def link(self, target_desc, objects,
  545. output_filename, output_dir=None, libraries=None,
  546. library_dirs=None, runtime_library_dirs=None,
  547. export_symbols=None, debug=0, extra_preargs=None,
  548. extra_postargs=None, build_temp=None, target_lang=None):
  549. objects, output_dir = self._fix_object_args(objects, output_dir)
  550. libraries, library_dirs, runtime_library_dirs = \
  551. self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
  552. lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
  553. libraries)
  554. if is_string(output_dir):
  555. output_filename = os.path.join(output_dir, output_filename)
  556. elif output_dir is not None:
  557. raise TypeError("'output_dir' must be a string or None")
  558. if self._need_link(objects, output_filename):
  559. if self.library_switch[-1]==' ':
  560. o_args = [self.library_switch.strip(), output_filename]
  561. else:
  562. o_args = [self.library_switch.strip()+output_filename]
  563. if is_string(self.objects):
  564. ld_args = objects + [self.objects]
  565. else:
  566. ld_args = objects + self.objects
  567. ld_args = ld_args + lib_opts + o_args
  568. if debug:
  569. ld_args[:0] = ['-g']
  570. if extra_preargs:
  571. ld_args[:0] = extra_preargs
  572. if extra_postargs:
  573. ld_args.extend(extra_postargs)
  574. self.mkpath(os.path.dirname(output_filename))
  575. if target_desc == CCompiler.EXECUTABLE:
  576. linker = self.linker_exe[:]
  577. else:
  578. linker = self.linker_so[:]
  579. command = linker + ld_args
  580. try:
  581. self.spawn(command)
  582. except DistutilsExecError:
  583. msg = str(get_exception())
  584. raise LinkError(msg)
  585. else:
  586. log.debug("skipping %s (up-to-date)", output_filename)
  587. def _environment_hook(self, name, hook_name):
  588. if hook_name is None:
  589. return None
  590. if is_string(hook_name):
  591. if hook_name.startswith('self.'):
  592. hook_name = hook_name[5:]
  593. hook = getattr(self, hook_name)
  594. return hook()
  595. elif hook_name.startswith('exe.'):
  596. hook_name = hook_name[4:]
  597. var = self.executables[hook_name]
  598. if var:
  599. return var[0]
  600. else:
  601. return None
  602. elif hook_name.startswith('flags.'):
  603. hook_name = hook_name[6:]
  604. hook = getattr(self, 'get_flags_' + hook_name)
  605. return hook()
  606. else:
  607. return hook_name()
  608. def can_ccompiler_link(self, ccompiler):
  609. """
  610. Check if the given C compiler can link objects produced by
  611. this compiler.
  612. """
  613. return True
  614. def wrap_unlinkable_objects(self, objects, output_dir, extra_dll_dir):
  615. """
  616. Convert a set of object files that are not compatible with the default
  617. linker, to a file that is compatible.
  618. Parameters
  619. ----------
  620. objects : list
  621. List of object files to include.
  622. output_dir : str
  623. Output directory to place generated object files.
  624. extra_dll_dir : str
  625. Output directory to place extra DLL files that need to be
  626. included on Windows.
  627. Returns
  628. -------
  629. converted_objects : list of str
  630. List of converted object files.
  631. Note that the number of output files is not necessarily
  632. the same as inputs.
  633. """
  634. raise NotImplementedError()
  635. ## class FCompiler
  636. _default_compilers = (
  637. # sys.platform mappings
  638. ('win32', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95',
  639. 'intelvem', 'intelem', 'flang')),
  640. ('cygwin.*', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95')),
  641. ('linux.*', ('gnu95', 'intel', 'lahey', 'pg', 'absoft', 'nag', 'vast', 'compaq',
  642. 'intele', 'intelem', 'gnu', 'g95', 'pathf95', 'nagfor')),
  643. ('darwin.*', ('gnu95', 'nag', 'absoft', 'ibm', 'intel', 'gnu', 'g95', 'pg')),
  644. ('sunos.*', ('sun', 'gnu', 'gnu95', 'g95')),
  645. ('irix.*', ('mips', 'gnu', 'gnu95',)),
  646. ('aix.*', ('ibm', 'gnu', 'gnu95',)),
  647. # os.name mappings
  648. ('posix', ('gnu', 'gnu95',)),
  649. ('nt', ('gnu', 'gnu95',)),
  650. ('mac', ('gnu95', 'gnu', 'pg')),
  651. )
  652. fcompiler_class = None
  653. fcompiler_aliases = None
  654. def load_all_fcompiler_classes():
  655. """Cache all the FCompiler classes found in modules in the
  656. numpy.distutils.fcompiler package.
  657. """
  658. from glob import glob
  659. global fcompiler_class, fcompiler_aliases
  660. if fcompiler_class is not None:
  661. return
  662. pys = os.path.join(os.path.dirname(__file__), '*.py')
  663. fcompiler_class = {}
  664. fcompiler_aliases = {}
  665. for fname in glob(pys):
  666. module_name, ext = os.path.splitext(os.path.basename(fname))
  667. module_name = 'numpy.distutils.fcompiler.' + module_name
  668. __import__ (module_name)
  669. module = sys.modules[module_name]
  670. if hasattr(module, 'compilers'):
  671. for cname in module.compilers:
  672. klass = getattr(module, cname)
  673. desc = (klass.compiler_type, klass, klass.description)
  674. fcompiler_class[klass.compiler_type] = desc
  675. for alias in klass.compiler_aliases:
  676. if alias in fcompiler_aliases:
  677. raise ValueError("alias %r defined for both %s and %s"
  678. % (alias, klass.__name__,
  679. fcompiler_aliases[alias][1].__name__))
  680. fcompiler_aliases[alias] = desc
  681. def _find_existing_fcompiler(compiler_types,
  682. osname=None, platform=None,
  683. requiref90=False,
  684. c_compiler=None):
  685. from numpy.distutils.core import get_distribution
  686. dist = get_distribution(always=True)
  687. for compiler_type in compiler_types:
  688. v = None
  689. try:
  690. c = new_fcompiler(plat=platform, compiler=compiler_type,
  691. c_compiler=c_compiler)
  692. c.customize(dist)
  693. v = c.get_version()
  694. if requiref90 and c.compiler_f90 is None:
  695. v = None
  696. new_compiler = c.suggested_f90_compiler
  697. if new_compiler:
  698. log.warn('Trying %r compiler as suggested by %r '
  699. 'compiler for f90 support.' % (compiler_type,
  700. new_compiler))
  701. c = new_fcompiler(plat=platform, compiler=new_compiler,
  702. c_compiler=c_compiler)
  703. c.customize(dist)
  704. v = c.get_version()
  705. if v is not None:
  706. compiler_type = new_compiler
  707. if requiref90 and c.compiler_f90 is None:
  708. raise ValueError('%s does not support compiling f90 codes, '
  709. 'skipping.' % (c.__class__.__name__))
  710. except DistutilsModuleError:
  711. log.debug("_find_existing_fcompiler: compiler_type='%s' raised DistutilsModuleError", compiler_type)
  712. except CompilerNotFound:
  713. log.debug("_find_existing_fcompiler: compiler_type='%s' not found", compiler_type)
  714. if v is not None:
  715. return compiler_type
  716. return None
  717. def available_fcompilers_for_platform(osname=None, platform=None):
  718. if osname is None:
  719. osname = os.name
  720. if platform is None:
  721. platform = sys.platform
  722. matching_compiler_types = []
  723. for pattern, compiler_type in _default_compilers:
  724. if re.match(pattern, platform) or re.match(pattern, osname):
  725. for ct in compiler_type:
  726. if ct not in matching_compiler_types:
  727. matching_compiler_types.append(ct)
  728. if not matching_compiler_types:
  729. matching_compiler_types.append('gnu')
  730. return matching_compiler_types
  731. def get_default_fcompiler(osname=None, platform=None, requiref90=False,
  732. c_compiler=None):
  733. """Determine the default Fortran compiler to use for the given
  734. platform."""
  735. matching_compiler_types = available_fcompilers_for_platform(osname,
  736. platform)
  737. log.info("get_default_fcompiler: matching types: '%s'",
  738. matching_compiler_types)
  739. compiler_type = _find_existing_fcompiler(matching_compiler_types,
  740. osname=osname,
  741. platform=platform,
  742. requiref90=requiref90,
  743. c_compiler=c_compiler)
  744. return compiler_type
  745. # Flag to avoid rechecking for Fortran compiler every time
  746. failed_fcompilers = set()
  747. def new_fcompiler(plat=None,
  748. compiler=None,
  749. verbose=0,
  750. dry_run=0,
  751. force=0,
  752. requiref90=False,
  753. c_compiler = None):
  754. """Generate an instance of some FCompiler subclass for the supplied
  755. platform/compiler combination.
  756. """
  757. global failed_fcompilers
  758. fcompiler_key = (plat, compiler)
  759. if fcompiler_key in failed_fcompilers:
  760. return None
  761. load_all_fcompiler_classes()
  762. if plat is None:
  763. plat = os.name
  764. if compiler is None:
  765. compiler = get_default_fcompiler(plat, requiref90=requiref90,
  766. c_compiler=c_compiler)
  767. if compiler in fcompiler_class:
  768. module_name, klass, long_description = fcompiler_class[compiler]
  769. elif compiler in fcompiler_aliases:
  770. module_name, klass, long_description = fcompiler_aliases[compiler]
  771. else:
  772. msg = "don't know how to compile Fortran code on platform '%s'" % plat
  773. if compiler is not None:
  774. msg = msg + " with '%s' compiler." % compiler
  775. msg = msg + " Supported compilers are: %s)" \
  776. % (','.join(fcompiler_class.keys()))
  777. log.warn(msg)
  778. failed_fcompilers.add(fcompiler_key)
  779. return None
  780. compiler = klass(verbose=verbose, dry_run=dry_run, force=force)
  781. compiler.c_compiler = c_compiler
  782. return compiler
  783. def show_fcompilers(dist=None):
  784. """Print list of available compilers (used by the "--help-fcompiler"
  785. option to "config_fc").
  786. """
  787. if dist is None:
  788. from distutils.dist import Distribution
  789. from numpy.distutils.command.config_compiler import config_fc
  790. dist = Distribution()
  791. dist.script_name = os.path.basename(sys.argv[0])
  792. dist.script_args = ['config_fc'] + sys.argv[1:]
  793. try:
  794. dist.script_args.remove('--help-fcompiler')
  795. except ValueError:
  796. pass
  797. dist.cmdclass['config_fc'] = config_fc
  798. dist.parse_config_files()
  799. dist.parse_command_line()
  800. compilers = []
  801. compilers_na = []
  802. compilers_ni = []
  803. if not fcompiler_class:
  804. load_all_fcompiler_classes()
  805. platform_compilers = available_fcompilers_for_platform()
  806. for compiler in platform_compilers:
  807. v = None
  808. log.set_verbosity(-2)
  809. try:
  810. c = new_fcompiler(compiler=compiler, verbose=dist.verbose)
  811. c.customize(dist)
  812. v = c.get_version()
  813. except (DistutilsModuleError, CompilerNotFound):
  814. e = get_exception()
  815. log.debug("show_fcompilers: %s not found" % (compiler,))
  816. log.debug(repr(e))
  817. if v is None:
  818. compilers_na.append(("fcompiler="+compiler, None,
  819. fcompiler_class[compiler][2]))
  820. else:
  821. c.dump_properties()
  822. compilers.append(("fcompiler="+compiler, None,
  823. fcompiler_class[compiler][2] + ' (%s)' % v))
  824. compilers_ni = list(set(fcompiler_class.keys()) - set(platform_compilers))
  825. compilers_ni = [("fcompiler="+fc, None, fcompiler_class[fc][2])
  826. for fc in compilers_ni]
  827. compilers.sort()
  828. compilers_na.sort()
  829. compilers_ni.sort()
  830. pretty_printer = FancyGetopt(compilers)
  831. pretty_printer.print_help("Fortran compilers found:")
  832. pretty_printer = FancyGetopt(compilers_na)
  833. pretty_printer.print_help("Compilers available for this "
  834. "platform, but not found:")
  835. if compilers_ni:
  836. pretty_printer = FancyGetopt(compilers_ni)
  837. pretty_printer.print_help("Compilers not available on this platform:")
  838. print("For compiler details, run 'config_fc --verbose' setup command.")
  839. def dummy_fortran_file():
  840. fo, name = make_temp_file(suffix='.f')
  841. fo.write(" subroutine dummy()\n end\n")
  842. fo.close()
  843. return name[:-2]
  844. is_f_file = re.compile(r'.*[.](for|ftn|f77|f)\Z', re.I).match
  845. _has_f_header = re.compile(r'-[*]-\s*fortran\s*-[*]-', re.I).search
  846. _has_f90_header = re.compile(r'-[*]-\s*f90\s*-[*]-', re.I).search
  847. _has_fix_header = re.compile(r'-[*]-\s*fix\s*-[*]-', re.I).search
  848. _free_f90_start = re.compile(r'[^c*!]\s*[^\s\d\t]', re.I).match
  849. def is_free_format(file):
  850. """Check if file is in free format Fortran."""
  851. # f90 allows both fixed and free format, assuming fixed unless
  852. # signs of free format are detected.
  853. result = 0
  854. f = open_latin1(file, 'r')
  855. line = f.readline()
  856. n = 10000 # the number of non-comment lines to scan for hints
  857. if _has_f_header(line):
  858. n = 0
  859. elif _has_f90_header(line):
  860. n = 0
  861. result = 1
  862. while n>0 and line:
  863. line = line.rstrip()
  864. if line and line[0]!='!':
  865. n -= 1
  866. if (line[0]!='\t' and _free_f90_start(line[:5])) or line[-1:]=='&':
  867. result = 1
  868. break
  869. line = f.readline()
  870. f.close()
  871. return result
  872. def has_f90_header(src):
  873. f = open_latin1(src, 'r')
  874. line = f.readline()
  875. f.close()
  876. return _has_f90_header(line) or _has_fix_header(line)
  877. _f77flags_re = re.compile(r'(c|)f77flags\s*\(\s*(?P<fcname>\w+)\s*\)\s*=\s*(?P<fflags>.*)', re.I)
  878. def get_f77flags(src):
  879. """
  880. Search the first 20 lines of fortran 77 code for line pattern
  881. `CF77FLAGS(<fcompiler type>)=<f77 flags>`
  882. Return a dictionary {<fcompiler type>:<f77 flags>}.
  883. """
  884. flags = {}
  885. f = open_latin1(src, 'r')
  886. i = 0
  887. for line in f:
  888. i += 1
  889. if i>20: break
  890. m = _f77flags_re.match(line)
  891. if not m: continue
  892. fcname = m.group('fcname').strip()
  893. fflags = m.group('fflags').strip()
  894. flags[fcname] = split_quoted(fflags)
  895. f.close()
  896. return flags
  897. # TODO: implement get_f90flags and use it in _compile similarly to get_f77flags
  898. if __name__ == '__main__':
  899. show_fcompilers()