f2py2e.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. """
  2. f2py2e - Fortran to Python C/API generator. 2nd Edition.
  3. See __usage__ below.
  4. Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
  5. Copyright 2011 -- present NumPy Developers.
  6. Permission to use, modify, and distribute this software is given under the
  7. terms of the NumPy License.
  8. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  9. """
  10. import sys
  11. import os
  12. import pprint
  13. import re
  14. import argparse
  15. from . import crackfortran
  16. from . import rules
  17. from . import cb_rules
  18. from . import auxfuncs
  19. from . import cfuncs
  20. from . import f90mod_rules
  21. from . import __version__
  22. from . import capi_maps
  23. from .cfuncs import errmess
  24. from numpy.f2py._backends import f2py_build_generator
  25. f2py_version = __version__.version
  26. numpy_version = __version__.version
  27. # outmess=sys.stdout.write
  28. show = pprint.pprint
  29. outmess = auxfuncs.outmess
  30. MESON_ONLY_VER = (sys.version_info >= (3, 12))
  31. __usage__ =\
  32. f"""Usage:
  33. 1) To construct extension module sources:
  34. f2py [<options>] <fortran files> [[[only:]||[skip:]] \\
  35. <fortran functions> ] \\
  36. [: <fortran files> ...]
  37. 2) To compile fortran files and build extension modules:
  38. f2py -c [<options>, <build_flib options>, <extra options>] <fortran files>
  39. 3) To generate signature files:
  40. f2py -h <filename.pyf> ...< same options as in (1) >
  41. Description: This program generates a Python C/API file (<modulename>module.c)
  42. that contains wrappers for given fortran functions so that they
  43. can be called from Python. With the -c option the corresponding
  44. extension modules are built.
  45. Options:
  46. -h <filename> Write signatures of the fortran routines to file <filename>
  47. and exit. You can then edit <filename> and use it instead
  48. of <fortran files>. If <filename>==stdout then the
  49. signatures are printed to stdout.
  50. <fortran functions> Names of fortran routines for which Python C/API
  51. functions will be generated. Default is all that are found
  52. in <fortran files>.
  53. <fortran files> Paths to fortran/signature files that will be scanned for
  54. <fortran functions> in order to determine their signatures.
  55. skip: Ignore fortran functions that follow until `:'.
  56. only: Use only fortran functions that follow until `:'.
  57. : Get back to <fortran files> mode.
  58. -m <modulename> Name of the module; f2py generates a Python/C API
  59. file <modulename>module.c or extension module <modulename>.
  60. Default is 'untitled'.
  61. '-include<header>' Writes additional headers in the C wrapper, can be passed
  62. multiple times, generates #include <header> each time.
  63. --[no-]lower Do [not] lower the cases in <fortran files>. By default,
  64. --lower is assumed with -h key, and --no-lower without -h key.
  65. --build-dir <dirname> All f2py generated files are created in <dirname>.
  66. Default is tempfile.mkdtemp().
  67. --overwrite-signature Overwrite existing signature file.
  68. --[no-]latex-doc Create (or not) <modulename>module.tex.
  69. Default is --no-latex-doc.
  70. --short-latex Create 'incomplete' LaTeX document (without commands
  71. \\documentclass, \\tableofcontents, and \\begin{{document}},
  72. \\end{{document}}).
  73. --[no-]rest-doc Create (or not) <modulename>module.rst.
  74. Default is --no-rest-doc.
  75. --debug-capi Create C/API code that reports the state of the wrappers
  76. during runtime. Useful for debugging.
  77. --[no-]wrap-functions Create Fortran subroutine wrappers to Fortran 77
  78. functions. --wrap-functions is default because it ensures
  79. maximum portability/compiler independence.
  80. --[no-]freethreading-compatible Create a module that declares it does or
  81. doesn't require the GIL. The default is
  82. --freethreading-compatible for backward
  83. compatibility. Inspect the Fortran code you are wrapping for
  84. thread safety issues before passing
  85. --no-freethreading-compatible, as f2py does not analyze
  86. fortran code for thread safety issues.
  87. --include-paths <path1>:<path2>:... Search include files from the given
  88. directories.
  89. --help-link [..] List system resources found by system_info.py. See also
  90. --link-<resource> switch below. [..] is optional list
  91. of resources names. E.g. try 'f2py --help-link lapack_opt'.
  92. --f2cmap <filename> Load Fortran-to-Python KIND specification from the given
  93. file. Default: .f2py_f2cmap in current directory.
  94. --quiet Run quietly.
  95. --verbose Run with extra verbosity.
  96. --skip-empty-wrappers Only generate wrapper files when needed.
  97. -v Print f2py version ID and exit.
  98. build backend options (only effective with -c)
  99. [NO_MESON] is used to indicate an option not meant to be used
  100. with the meson backend or above Python 3.12:
  101. --fcompiler= Specify Fortran compiler type by vendor [NO_MESON]
  102. --compiler= Specify distutils C compiler type [NO_MESON]
  103. --help-fcompiler List available Fortran compilers and exit [NO_MESON]
  104. --f77exec= Specify the path to F77 compiler [NO_MESON]
  105. --f90exec= Specify the path to F90 compiler [NO_MESON]
  106. --f77flags= Specify F77 compiler flags
  107. --f90flags= Specify F90 compiler flags
  108. --opt= Specify optimization flags [NO_MESON]
  109. --arch= Specify architecture specific optimization flags [NO_MESON]
  110. --noopt Compile without optimization [NO_MESON]
  111. --noarch Compile without arch-dependent optimization [NO_MESON]
  112. --debug Compile with debugging information
  113. --dep <dependency>
  114. Specify a meson dependency for the module. This may
  115. be passed multiple times for multiple dependencies.
  116. Dependencies are stored in a list for further processing.
  117. Example: --dep lapack --dep scalapack
  118. This will identify "lapack" and "scalapack" as dependencies
  119. and remove them from argv, leaving a dependencies list
  120. containing ["lapack", "scalapack"].
  121. --backend <backend_type>
  122. Specify the build backend for the compilation process.
  123. The supported backends are 'meson' and 'distutils'.
  124. If not specified, defaults to 'distutils'. On
  125. Python 3.12 or higher, the default is 'meson'.
  126. Extra options (only effective with -c):
  127. --link-<resource> Link extension module with <resource> as defined
  128. by numpy.distutils/system_info.py. E.g. to link
  129. with optimized LAPACK libraries (vecLib on MacOSX,
  130. ATLAS elsewhere), use --link-lapack_opt.
  131. See also --help-link switch. [NO_MESON]
  132. -L/path/to/lib/ -l<libname>
  133. -D<define> -U<name>
  134. -I/path/to/include/
  135. <filename>.o <filename>.so <filename>.a
  136. Using the following macros may be required with non-gcc Fortran
  137. compilers:
  138. -DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN
  139. When using -DF2PY_REPORT_ATEXIT, a performance report of F2PY
  140. interface is printed out at exit (platforms: Linux).
  141. When using -DF2PY_REPORT_ON_ARRAY_COPY=<int>, a message is
  142. sent to stderr whenever F2PY interface makes a copy of an
  143. array. Integer <int> sets the threshold for array sizes when
  144. a message should be shown.
  145. Version: {f2py_version}
  146. numpy Version: {numpy_version}
  147. License: NumPy license (see LICENSE.txt in the NumPy source code)
  148. Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
  149. Copyright 2011 -- present NumPy Developers.
  150. https://numpy.org/doc/stable/f2py/index.html\n"""
  151. def scaninputline(inputline):
  152. files, skipfuncs, onlyfuncs, debug = [], [], [], []
  153. f, f2, f3, f5, f6, f8, f9, f10 = 1, 0, 0, 0, 0, 0, 0, 0
  154. verbose = 1
  155. emptygen = True
  156. dolc = -1
  157. dolatexdoc = 0
  158. dorestdoc = 0
  159. wrapfuncs = 1
  160. buildpath = '.'
  161. include_paths, freethreading_compatible, inputline = get_newer_options(inputline)
  162. signsfile, modulename = None, None
  163. options = {'buildpath': buildpath,
  164. 'coutput': None,
  165. 'f2py_wrapper_output': None}
  166. for l in inputline:
  167. if l == '':
  168. pass
  169. elif l == 'only:':
  170. f = 0
  171. elif l == 'skip:':
  172. f = -1
  173. elif l == ':':
  174. f = 1
  175. elif l[:8] == '--debug-':
  176. debug.append(l[8:])
  177. elif l == '--lower':
  178. dolc = 1
  179. elif l == '--build-dir':
  180. f6 = 1
  181. elif l == '--no-lower':
  182. dolc = 0
  183. elif l == '--quiet':
  184. verbose = 0
  185. elif l == '--verbose':
  186. verbose += 1
  187. elif l == '--latex-doc':
  188. dolatexdoc = 1
  189. elif l == '--no-latex-doc':
  190. dolatexdoc = 0
  191. elif l == '--rest-doc':
  192. dorestdoc = 1
  193. elif l == '--no-rest-doc':
  194. dorestdoc = 0
  195. elif l == '--wrap-functions':
  196. wrapfuncs = 1
  197. elif l == '--no-wrap-functions':
  198. wrapfuncs = 0
  199. elif l == '--short-latex':
  200. options['shortlatex'] = 1
  201. elif l == '--coutput':
  202. f8 = 1
  203. elif l == '--f2py-wrapper-output':
  204. f9 = 1
  205. elif l == '--f2cmap':
  206. f10 = 1
  207. elif l == '--overwrite-signature':
  208. options['h-overwrite'] = 1
  209. elif l == '-h':
  210. f2 = 1
  211. elif l == '-m':
  212. f3 = 1
  213. elif l[:2] == '-v':
  214. print(f2py_version)
  215. sys.exit()
  216. elif l == '--show-compilers':
  217. f5 = 1
  218. elif l[:8] == '-include':
  219. cfuncs.outneeds['userincludes'].append(l[9:-1])
  220. cfuncs.userincludes[l[9:-1]] = '#include ' + l[8:]
  221. elif l == '--skip-empty-wrappers':
  222. emptygen = False
  223. elif l[0] == '-':
  224. errmess('Unknown option %s\n' % repr(l))
  225. sys.exit()
  226. elif f2:
  227. f2 = 0
  228. signsfile = l
  229. elif f3:
  230. f3 = 0
  231. modulename = l
  232. elif f6:
  233. f6 = 0
  234. buildpath = l
  235. elif f8:
  236. f8 = 0
  237. options["coutput"] = l
  238. elif f9:
  239. f9 = 0
  240. options["f2py_wrapper_output"] = l
  241. elif f10:
  242. f10 = 0
  243. options["f2cmap_file"] = l
  244. elif f == 1:
  245. try:
  246. with open(l):
  247. pass
  248. files.append(l)
  249. except OSError as detail:
  250. errmess(f'OSError: {detail!s}. Skipping file "{l!s}".\n')
  251. elif f == -1:
  252. skipfuncs.append(l)
  253. elif f == 0:
  254. onlyfuncs.append(l)
  255. if not f5 and not files and not modulename:
  256. print(__usage__)
  257. sys.exit()
  258. if not os.path.isdir(buildpath):
  259. if not verbose:
  260. outmess('Creating build directory %s\n' % (buildpath))
  261. os.mkdir(buildpath)
  262. if signsfile:
  263. signsfile = os.path.join(buildpath, signsfile)
  264. if signsfile and os.path.isfile(signsfile) and 'h-overwrite' not in options:
  265. errmess(
  266. 'Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n' % (signsfile))
  267. sys.exit()
  268. options['emptygen'] = emptygen
  269. options['debug'] = debug
  270. options['verbose'] = verbose
  271. if dolc == -1 and not signsfile:
  272. options['do-lower'] = 0
  273. else:
  274. options['do-lower'] = dolc
  275. if modulename:
  276. options['module'] = modulename
  277. if signsfile:
  278. options['signsfile'] = signsfile
  279. if onlyfuncs:
  280. options['onlyfuncs'] = onlyfuncs
  281. if skipfuncs:
  282. options['skipfuncs'] = skipfuncs
  283. options['dolatexdoc'] = dolatexdoc
  284. options['dorestdoc'] = dorestdoc
  285. options['wrapfuncs'] = wrapfuncs
  286. options['buildpath'] = buildpath
  287. options['include_paths'] = include_paths
  288. options['requires_gil'] = not freethreading_compatible
  289. options.setdefault('f2cmap_file', None)
  290. return files, options
  291. def callcrackfortran(files, options):
  292. rules.options = options
  293. crackfortran.debug = options['debug']
  294. crackfortran.verbose = options['verbose']
  295. if 'module' in options:
  296. crackfortran.f77modulename = options['module']
  297. if 'skipfuncs' in options:
  298. crackfortran.skipfuncs = options['skipfuncs']
  299. if 'onlyfuncs' in options:
  300. crackfortran.onlyfuncs = options['onlyfuncs']
  301. crackfortran.include_paths[:] = options['include_paths']
  302. crackfortran.dolowercase = options['do-lower']
  303. postlist = crackfortran.crackfortran(files)
  304. if 'signsfile' in options:
  305. outmess('Saving signatures to file "%s"\n' % (options['signsfile']))
  306. pyf = crackfortran.crack2fortran(postlist)
  307. if options['signsfile'][-6:] == 'stdout':
  308. sys.stdout.write(pyf)
  309. else:
  310. with open(options['signsfile'], 'w') as f:
  311. f.write(pyf)
  312. if options["coutput"] is None:
  313. for mod in postlist:
  314. mod["coutput"] = "%smodule.c" % mod["name"]
  315. else:
  316. for mod in postlist:
  317. mod["coutput"] = options["coutput"]
  318. if options["f2py_wrapper_output"] is None:
  319. for mod in postlist:
  320. mod["f2py_wrapper_output"] = "%s-f2pywrappers.f" % mod["name"]
  321. else:
  322. for mod in postlist:
  323. mod["f2py_wrapper_output"] = options["f2py_wrapper_output"]
  324. for mod in postlist:
  325. if options["requires_gil"]:
  326. mod['gil_used'] = 'Py_MOD_GIL_USED'
  327. else:
  328. mod['gil_used'] = 'Py_MOD_GIL_NOT_USED'
  329. return postlist
  330. def buildmodules(lst):
  331. cfuncs.buildcfuncs()
  332. outmess('Building modules...\n')
  333. modules, mnames, isusedby = [], [], {}
  334. for item in lst:
  335. if '__user__' in item['name']:
  336. cb_rules.buildcallbacks(item)
  337. else:
  338. if 'use' in item:
  339. for u in item['use'].keys():
  340. if u not in isusedby:
  341. isusedby[u] = []
  342. isusedby[u].append(item['name'])
  343. modules.append(item)
  344. mnames.append(item['name'])
  345. ret = {}
  346. for module, name in zip(modules, mnames):
  347. if name in isusedby:
  348. outmess('\tSkipping module "%s" which is used by %s.\n' % (
  349. name, ','.join('"%s"' % s for s in isusedby[name])))
  350. else:
  351. um = []
  352. if 'use' in module:
  353. for u in module['use'].keys():
  354. if u in isusedby and u in mnames:
  355. um.append(modules[mnames.index(u)])
  356. else:
  357. outmess(
  358. f'\tModule "{name}" uses nonexisting "{u}" '
  359. 'which will be ignored.\n')
  360. ret[name] = {}
  361. dict_append(ret[name], rules.buildmodule(module, um))
  362. return ret
  363. def dict_append(d_out, d_in):
  364. for (k, v) in d_in.items():
  365. if k not in d_out:
  366. d_out[k] = []
  367. if isinstance(v, list):
  368. d_out[k] = d_out[k] + v
  369. else:
  370. d_out[k].append(v)
  371. def run_main(comline_list):
  372. """
  373. Equivalent to running::
  374. f2py <args>
  375. where ``<args>=string.join(<list>,' ')``, but in Python. Unless
  376. ``-h`` is used, this function returns a dictionary containing
  377. information on generated modules and their dependencies on source
  378. files.
  379. You cannot build extension modules with this function, that is,
  380. using ``-c`` is not allowed. Use the ``compile`` command instead.
  381. Examples
  382. --------
  383. The command ``f2py -m scalar scalar.f`` can be executed from Python as
  384. follows.
  385. .. literalinclude:: ../../source/f2py/code/results/run_main_session.dat
  386. :language: python
  387. """
  388. crackfortran.reset_global_f2py_vars()
  389. f2pydir = os.path.dirname(os.path.abspath(cfuncs.__file__))
  390. fobjhsrc = os.path.join(f2pydir, 'src', 'fortranobject.h')
  391. fobjcsrc = os.path.join(f2pydir, 'src', 'fortranobject.c')
  392. # gh-22819 -- begin
  393. parser = make_f2py_compile_parser()
  394. args, comline_list = parser.parse_known_args(comline_list)
  395. pyf_files, _ = filter_files("", "[.]pyf([.]src|)", comline_list)
  396. # Checks that no existing modulename is defined in a pyf file
  397. # TODO: Remove all this when scaninputline is replaced
  398. if args.module_name:
  399. if "-h" in comline_list:
  400. modname = (
  401. args.module_name
  402. ) # Directly use from args when -h is present
  403. else:
  404. modname = validate_modulename(
  405. pyf_files, args.module_name
  406. ) # Validate modname when -h is not present
  407. comline_list += ['-m', modname] # needed for the rest of scaninputline
  408. # gh-22819 -- end
  409. files, options = scaninputline(comline_list)
  410. auxfuncs.options = options
  411. capi_maps.load_f2cmap_file(options['f2cmap_file'])
  412. postlist = callcrackfortran(files, options)
  413. isusedby = {}
  414. for plist in postlist:
  415. if 'use' in plist:
  416. for u in plist['use'].keys():
  417. if u not in isusedby:
  418. isusedby[u] = []
  419. isusedby[u].append(plist['name'])
  420. for plist in postlist:
  421. if plist['block'] == 'python module' and '__user__' in plist['name']:
  422. if plist['name'] in isusedby:
  423. # if not quiet:
  424. outmess(
  425. f'Skipping Makefile build for module "{plist["name"]}" '
  426. 'which is used by {}\n'.format(
  427. ','.join(f'"{s}"' for s in isusedby[plist['name']])))
  428. if 'signsfile' in options:
  429. if options['verbose'] > 1:
  430. outmess(
  431. 'Stopping. Edit the signature file and then run f2py on the signature file: ')
  432. outmess('%s %s\n' %
  433. (os.path.basename(sys.argv[0]), options['signsfile']))
  434. return
  435. for plist in postlist:
  436. if plist['block'] != 'python module':
  437. if 'python module' not in options:
  438. errmess(
  439. 'Tip: If your original code is Fortran source then you must use -m option.\n')
  440. raise TypeError('All blocks must be python module blocks but got %s' % (
  441. repr(plist['block'])))
  442. auxfuncs.debugoptions = options['debug']
  443. f90mod_rules.options = options
  444. auxfuncs.wrapfuncs = options['wrapfuncs']
  445. ret = buildmodules(postlist)
  446. for mn in ret.keys():
  447. dict_append(ret[mn], {'csrc': fobjcsrc, 'h': fobjhsrc})
  448. return ret
  449. def filter_files(prefix, suffix, files, remove_prefix=None):
  450. """
  451. Filter files by prefix and suffix.
  452. """
  453. filtered, rest = [], []
  454. match = re.compile(prefix + r'.*' + suffix + r'\Z').match
  455. if remove_prefix:
  456. ind = len(prefix)
  457. else:
  458. ind = 0
  459. for file in [x.strip() for x in files]:
  460. if match(file):
  461. filtered.append(file[ind:])
  462. else:
  463. rest.append(file)
  464. return filtered, rest
  465. def get_prefix(module):
  466. p = os.path.dirname(os.path.dirname(module.__file__))
  467. return p
  468. class CombineIncludePaths(argparse.Action):
  469. def __call__(self, parser, namespace, values, option_string=None):
  470. include_paths_set = set(getattr(namespace, 'include_paths', []) or [])
  471. if option_string == "--include_paths":
  472. outmess("Use --include-paths or -I instead of --include_paths which will be removed")
  473. if option_string == "--include-paths" or option_string == "--include_paths":
  474. include_paths_set.update(values.split(':'))
  475. else:
  476. include_paths_set.add(values)
  477. namespace.include_paths = list(include_paths_set)
  478. def f2py_parser():
  479. parser = argparse.ArgumentParser(add_help=False)
  480. parser.add_argument("-I", dest="include_paths", action=CombineIncludePaths)
  481. parser.add_argument("--include-paths", dest="include_paths", action=CombineIncludePaths)
  482. parser.add_argument("--include_paths", dest="include_paths", action=CombineIncludePaths)
  483. parser.add_argument("--freethreading-compatible", dest="ftcompat", action=argparse.BooleanOptionalAction)
  484. return parser
  485. def get_newer_options(iline):
  486. iline = (' '.join(iline)).split()
  487. parser = f2py_parser()
  488. args, remain = parser.parse_known_args(iline)
  489. ipaths = args.include_paths
  490. if args.include_paths is None:
  491. ipaths = []
  492. return ipaths, args.ftcompat, remain
  493. def make_f2py_compile_parser():
  494. parser = argparse.ArgumentParser(add_help=False)
  495. parser.add_argument("--dep", action="append", dest="dependencies")
  496. parser.add_argument("--backend", choices=['meson', 'distutils'], default='distutils')
  497. parser.add_argument("-m", dest="module_name")
  498. return parser
  499. def preparse_sysargv():
  500. # To keep backwards bug compatibility, newer flags are handled by argparse,
  501. # and `sys.argv` is passed to the rest of `f2py` as is.
  502. parser = make_f2py_compile_parser()
  503. args, remaining_argv = parser.parse_known_args()
  504. sys.argv = [sys.argv[0]] + remaining_argv
  505. backend_key = args.backend
  506. if MESON_ONLY_VER and backend_key == 'distutils':
  507. outmess("Cannot use distutils backend with Python>=3.12,"
  508. " using meson backend instead.\n")
  509. backend_key = "meson"
  510. return {
  511. "dependencies": args.dependencies or [],
  512. "backend": backend_key,
  513. "modulename": args.module_name,
  514. }
  515. def run_compile():
  516. """
  517. Do it all in one call!
  518. """
  519. import tempfile
  520. # Collect dependency flags, preprocess sys.argv
  521. argy = preparse_sysargv()
  522. modulename = argy["modulename"]
  523. if modulename is None:
  524. modulename = 'untitled'
  525. dependencies = argy["dependencies"]
  526. backend_key = argy["backend"]
  527. build_backend = f2py_build_generator(backend_key)
  528. i = sys.argv.index('-c')
  529. del sys.argv[i]
  530. remove_build_dir = 0
  531. try:
  532. i = sys.argv.index('--build-dir')
  533. except ValueError:
  534. i = None
  535. if i is not None:
  536. build_dir = sys.argv[i + 1]
  537. del sys.argv[i + 1]
  538. del sys.argv[i]
  539. else:
  540. remove_build_dir = 1
  541. build_dir = tempfile.mkdtemp()
  542. _reg1 = re.compile(r'--link-')
  543. sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)]
  544. sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags]
  545. if sysinfo_flags:
  546. sysinfo_flags = [f[7:] for f in sysinfo_flags]
  547. _reg2 = re.compile(
  548. r'--((no-|)(wrap-functions|lower|freethreading-compatible)|debug-capi|quiet|skip-empty-wrappers)|-include')
  549. f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)]
  550. sys.argv = [_m for _m in sys.argv if _m not in f2py_flags]
  551. f2py_flags2 = []
  552. fl = 0
  553. for a in sys.argv[1:]:
  554. if a in ['only:', 'skip:']:
  555. fl = 1
  556. elif a == ':':
  557. fl = 0
  558. if fl or a == ':':
  559. f2py_flags2.append(a)
  560. if f2py_flags2 and f2py_flags2[-1] != ':':
  561. f2py_flags2.append(':')
  562. f2py_flags.extend(f2py_flags2)
  563. sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2]
  564. _reg3 = re.compile(
  565. r'--((f(90)?compiler(-exec|)|compiler)=|help-compiler)')
  566. flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)]
  567. sys.argv = [_m for _m in sys.argv if _m not in flib_flags]
  568. # TODO: Once distutils is dropped completely, i.e. min_ver >= 3.12, unify into --fflags
  569. reg_f77_f90_flags = re.compile(r'--f(77|90)flags=')
  570. reg_distutils_flags = re.compile(r'--((f(77|90)exec|opt|arch)=|(debug|noopt|noarch|help-fcompiler))')
  571. fc_flags = [_m for _m in sys.argv[1:] if reg_f77_f90_flags.match(_m)]
  572. distutils_flags = [_m for _m in sys.argv[1:] if reg_distutils_flags.match(_m)]
  573. if not (MESON_ONLY_VER or backend_key == 'meson'):
  574. fc_flags.extend(distutils_flags)
  575. sys.argv = [_m for _m in sys.argv if _m not in (fc_flags + distutils_flags)]
  576. del_list = []
  577. for s in flib_flags:
  578. v = '--fcompiler='
  579. if s[:len(v)] == v:
  580. if MESON_ONLY_VER or backend_key == 'meson':
  581. outmess(
  582. "--fcompiler cannot be used with meson,"
  583. "set compiler with the FC environment variable\n"
  584. )
  585. else:
  586. from numpy.distutils import fcompiler
  587. fcompiler.load_all_fcompiler_classes()
  588. allowed_keys = list(fcompiler.fcompiler_class.keys())
  589. nv = ov = s[len(v):].lower()
  590. if ov not in allowed_keys:
  591. vmap = {} # XXX
  592. try:
  593. nv = vmap[ov]
  594. except KeyError:
  595. if ov not in vmap.values():
  596. print('Unknown vendor: "%s"' % (s[len(v):]))
  597. nv = ov
  598. i = flib_flags.index(s)
  599. flib_flags[i] = '--fcompiler=' + nv
  600. continue
  601. for s in del_list:
  602. i = flib_flags.index(s)
  603. del flib_flags[i]
  604. assert len(flib_flags) <= 2, repr(flib_flags)
  605. _reg5 = re.compile(r'--(verbose)')
  606. setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)]
  607. sys.argv = [_m for _m in sys.argv if _m not in setup_flags]
  608. if '--quiet' in f2py_flags:
  609. setup_flags.append('--quiet')
  610. # Ugly filter to remove everything but sources
  611. sources = sys.argv[1:]
  612. f2cmapopt = '--f2cmap'
  613. if f2cmapopt in sys.argv:
  614. i = sys.argv.index(f2cmapopt)
  615. f2py_flags.extend(sys.argv[i:i + 2])
  616. del sys.argv[i + 1], sys.argv[i]
  617. sources = sys.argv[1:]
  618. pyf_files, _sources = filter_files("", "[.]pyf([.]src|)", sources)
  619. sources = pyf_files + _sources
  620. modulename = validate_modulename(pyf_files, modulename)
  621. extra_objects, sources = filter_files('', '[.](o|a|so|dylib)', sources)
  622. library_dirs, sources = filter_files('-L', '', sources, remove_prefix=1)
  623. libraries, sources = filter_files('-l', '', sources, remove_prefix=1)
  624. undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1)
  625. define_macros, sources = filter_files('-D', '', sources, remove_prefix=1)
  626. for i in range(len(define_macros)):
  627. name_value = define_macros[i].split('=', 1)
  628. if len(name_value) == 1:
  629. name_value.append(None)
  630. if len(name_value) == 2:
  631. define_macros[i] = tuple(name_value)
  632. else:
  633. print('Invalid use of -D:', name_value)
  634. # Construct wrappers / signatures / things
  635. if backend_key == 'meson':
  636. if not pyf_files:
  637. outmess('Using meson backend\nWill pass --lower to f2py\nSee https://numpy.org/doc/stable/f2py/buildtools/meson.html\n')
  638. f2py_flags.append('--lower')
  639. run_main(f" {' '.join(f2py_flags)} -m {modulename} {' '.join(sources)}".split())
  640. else:
  641. run_main(f" {' '.join(f2py_flags)} {' '.join(pyf_files)}".split())
  642. # Order matters here, includes are needed for run_main above
  643. include_dirs, _, sources = get_newer_options(sources)
  644. # Now use the builder
  645. builder = build_backend(
  646. modulename,
  647. sources,
  648. extra_objects,
  649. build_dir,
  650. include_dirs,
  651. library_dirs,
  652. libraries,
  653. define_macros,
  654. undef_macros,
  655. f2py_flags,
  656. sysinfo_flags,
  657. fc_flags,
  658. flib_flags,
  659. setup_flags,
  660. remove_build_dir,
  661. {"dependencies": dependencies},
  662. )
  663. builder.compile()
  664. def validate_modulename(pyf_files, modulename='untitled'):
  665. if len(pyf_files) > 1:
  666. raise ValueError("Only one .pyf file per call")
  667. if pyf_files:
  668. pyff = pyf_files[0]
  669. pyf_modname = auxfuncs.get_f2py_modulename(pyff)
  670. if modulename != pyf_modname:
  671. outmess(
  672. f"Ignoring -m {modulename}.\n"
  673. f"{pyff} defines {pyf_modname} to be the modulename.\n"
  674. )
  675. modulename = pyf_modname
  676. return modulename
  677. def main():
  678. if '--help-link' in sys.argv[1:]:
  679. sys.argv.remove('--help-link')
  680. if MESON_ONLY_VER:
  681. outmess("Use --dep for meson builds\n")
  682. else:
  683. from numpy.distutils.system_info import show_all
  684. show_all()
  685. return
  686. if '-c' in sys.argv[1:]:
  687. run_compile()
  688. else:
  689. run_main(sys.argv[1:])