numpy 2.5.2__cp315-cp315-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (942) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +108 -0
  3. numpy/__init__.cython-30.pxd +1312 -0
  4. numpy/__init__.pxd +12 -0
  5. numpy/__init__.py +926 -0
  6. numpy/__init__.pyi +7691 -0
  7. numpy/_array_api_info.py +349 -0
  8. numpy/_array_api_info.pyi +177 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +203 -0
  12. numpy/_core/__init__.pyi +666 -0
  13. numpy/_core/_add_newdocs.py +7131 -0
  14. numpy/_core/_add_newdocs.pyi +2 -0
  15. numpy/_core/_add_newdocs_scalars.py +381 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +130 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +54 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +48 -0
  25. numpy/_core/_internal.py +964 -0
  26. numpy/_core/_internal.pyi +56 -0
  27. numpy/_core/_methods.py +252 -0
  28. numpy/_core/_methods.pyi +22 -0
  29. numpy/_core/_multiarray_tests.cp315-win32.lib +0 -0
  30. numpy/_core/_multiarray_tests.cp315-win32.pyd +0 -0
  31. numpy/_core/_multiarray_umath.cp315-win32.lib +0 -0
  32. numpy/_core/_multiarray_umath.cp315-win32.pyd +0 -0
  33. numpy/_core/_operand_flag_tests.cp315-win32.lib +0 -0
  34. numpy/_core/_operand_flag_tests.cp315-win32.pyd +0 -0
  35. numpy/_core/_rational_tests.cp315-win32.lib +0 -0
  36. numpy/_core/_rational_tests.cp315-win32.pyd +0 -0
  37. numpy/_core/_simd.cp315-win32.lib +0 -0
  38. numpy/_core/_simd.cp315-win32.pyd +0 -0
  39. numpy/_core/_simd.pyi +35 -0
  40. numpy/_core/_string_helpers.py +100 -0
  41. numpy/_core/_string_helpers.pyi +12 -0
  42. numpy/_core/_struct_ufunc_tests.cp315-win32.lib +0 -0
  43. numpy/_core/_struct_ufunc_tests.cp315-win32.pyd +0 -0
  44. numpy/_core/_type_aliases.py +130 -0
  45. numpy/_core/_type_aliases.pyi +86 -0
  46. numpy/_core/_ufunc_config.py +515 -0
  47. numpy/_core/_ufunc_config.pyi +67 -0
  48. numpy/_core/_umath_tests.cp315-win32.lib +0 -0
  49. numpy/_core/_umath_tests.cp315-win32.pyd +0 -0
  50. numpy/_core/_umath_tests.pyi +51 -0
  51. numpy/_core/arrayprint.py +1788 -0
  52. numpy/_core/arrayprint.pyi +152 -0
  53. numpy/_core/cversions.py +13 -0
  54. numpy/_core/defchararray.py +1429 -0
  55. numpy/_core/defchararray.pyi +778 -0
  56. numpy/_core/einsumfunc.py +1647 -0
  57. numpy/_core/einsumfunc.pyi +179 -0
  58. numpy/_core/fromnumeric.py +4271 -0
  59. numpy/_core/fromnumeric.pyi +3144 -0
  60. numpy/_core/function_base.py +547 -0
  61. numpy/_core/function_base.pyi +444 -0
  62. numpy/_core/getlimits.py +449 -0
  63. numpy/_core/getlimits.pyi +124 -0
  64. numpy/_core/include/numpy/__multiarray_api.c +386 -0
  65. numpy/_core/include/numpy/__multiarray_api.h +1708 -0
  66. numpy/_core/include/numpy/__ufunc_api.c +56 -0
  67. numpy/_core/include/numpy/__ufunc_api.h +357 -0
  68. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  69. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  70. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  71. numpy/_core/include/numpy/arrayobject.h +7 -0
  72. numpy/_core/include/numpy/arrayscalars.h +228 -0
  73. numpy/_core/include/numpy/dtype_api.h +557 -0
  74. numpy/_core/include/numpy/halffloat.h +70 -0
  75. numpy/_core/include/numpy/ndarrayobject.h +288 -0
  76. numpy/_core/include/numpy/ndarraytypes.h +2075 -0
  77. numpy/_core/include/numpy/npy_2_compat.h +430 -0
  78. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  79. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  80. numpy/_core/include/numpy/npy_common.h +989 -0
  81. numpy/_core/include/numpy/npy_cpu.h +126 -0
  82. numpy/_core/include/numpy/npy_endian.h +79 -0
  83. numpy/_core/include/numpy/npy_math.h +602 -0
  84. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  85. numpy/_core/include/numpy/npy_os.h +42 -0
  86. numpy/_core/include/numpy/numpyconfig.h +187 -0
  87. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  88. numpy/_core/include/numpy/random/bitgen.h +20 -0
  89. numpy/_core/include/numpy/random/distributions.h +209 -0
  90. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  91. numpy/_core/include/numpy/ufuncobject.h +368 -0
  92. numpy/_core/include/numpy/utils.h +99 -0
  93. numpy/_core/lib/npymath.lib +0 -0
  94. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  95. numpy/_core/memmap.py +362 -0
  96. numpy/_core/memmap.pyi +94 -0
  97. numpy/_core/multiarray.py +1743 -0
  98. numpy/_core/multiarray.pyi +1892 -0
  99. numpy/_core/numeric.py +2707 -0
  100. numpy/_core/numeric.pyi +1366 -0
  101. numpy/_core/numerictypes.py +576 -0
  102. numpy/_core/numerictypes.pyi +196 -0
  103. numpy/_core/overrides.py +188 -0
  104. numpy/_core/overrides.pyi +44 -0
  105. numpy/_core/printoptions.py +32 -0
  106. numpy/_core/printoptions.pyi +28 -0
  107. numpy/_core/records.py +1089 -0
  108. numpy/_core/records.pyi +336 -0
  109. numpy/_core/shape_base.py +996 -0
  110. numpy/_core/shape_base.pyi +210 -0
  111. numpy/_core/strings.py +1813 -0
  112. numpy/_core/strings.pyi +481 -0
  113. numpy/_core/tests/_locales.py +72 -0
  114. numpy/_core/tests/_natype.py +144 -0
  115. numpy/_core/tests/data/astype_copy.pkl +0 -0
  116. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  117. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  118. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  119. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  123. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  125. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  127. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  128. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  129. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  131. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  132. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  133. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  135. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  136. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  137. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  138. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  139. numpy/_core/tests/examples/cython/checks.pyx +381 -0
  140. numpy/_core/tests/examples/cython/meson.build +52 -0
  141. numpy/_core/tests/examples/cython/setup.py +39 -0
  142. numpy/_core/tests/examples/limited_api/limited_api.c +455 -0
  143. numpy/_core/tests/examples/limited_api/limited_api_cython.pyx +155 -0
  144. numpy/_core/tests/examples/limited_api/meson.build +94 -0
  145. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  146. numpy/_core/tests/test__exceptions.py +90 -0
  147. numpy/_core/tests/test_abc.py +54 -0
  148. numpy/_core/tests/test_api.py +668 -0
  149. numpy/_core/tests/test_argparse.py +90 -0
  150. numpy/_core/tests/test_array_api_info.py +113 -0
  151. numpy/_core/tests/test_array_coercion.py +943 -0
  152. numpy/_core/tests/test_array_interface.py +222 -0
  153. numpy/_core/tests/test_arraymethod.py +85 -0
  154. numpy/_core/tests/test_arrayobject.py +198 -0
  155. numpy/_core/tests/test_arrayprint.py +1363 -0
  156. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  157. numpy/_core/tests/test_casting_unittests.py +970 -0
  158. numpy/_core/tests/test_conversion_utils.py +209 -0
  159. numpy/_core/tests/test_cpu_dispatcher.py +48 -0
  160. numpy/_core/tests/test_cpu_features.py +533 -0
  161. numpy/_core/tests/test_custom_dtypes.py +511 -0
  162. numpy/_core/tests/test_cython.py +377 -0
  163. numpy/_core/tests/test_datetime.py +3220 -0
  164. numpy/_core/tests/test_defchararray.py +879 -0
  165. numpy/_core/tests/test_deprecations.py +511 -0
  166. numpy/_core/tests/test_dlpack.py +262 -0
  167. numpy/_core/tests/test_dtype.py +2107 -0
  168. numpy/_core/tests/test_einsum.py +1368 -0
  169. numpy/_core/tests/test_errstate.py +131 -0
  170. numpy/_core/tests/test_extint128.py +217 -0
  171. numpy/_core/tests/test_finfo.py +86 -0
  172. numpy/_core/tests/test_function_base.py +502 -0
  173. numpy/_core/tests/test_getlimits.py +188 -0
  174. numpy/_core/tests/test_half.py +589 -0
  175. numpy/_core/tests/test_hashtable.py +156 -0
  176. numpy/_core/tests/test_indexerrors.py +122 -0
  177. numpy/_core/tests/test_indexing.py +1717 -0
  178. numpy/_core/tests/test_item_selection.py +178 -0
  179. numpy/_core/tests/test_limited_api.py +254 -0
  180. numpy/_core/tests/test_longdouble.py +370 -0
  181. numpy/_core/tests/test_mem_overlap.py +933 -0
  182. numpy/_core/tests/test_mem_policy.py +448 -0
  183. numpy/_core/tests/test_memmap.py +286 -0
  184. numpy/_core/tests/test_multiarray.py +11569 -0
  185. numpy/_core/tests/test_multiprocessing.py +55 -0
  186. numpy/_core/tests/test_multithreading.py +746 -0
  187. numpy/_core/tests/test_nditer.py +3690 -0
  188. numpy/_core/tests/test_nep50_promotions.py +287 -0
  189. numpy/_core/tests/test_numeric.py +4278 -0
  190. numpy/_core/tests/test_numerictypes.py +640 -0
  191. numpy/_core/tests/test_overrides.py +800 -0
  192. numpy/_core/tests/test_print.py +202 -0
  193. numpy/_core/tests/test_protocols.py +46 -0
  194. numpy/_core/tests/test_records.py +595 -0
  195. numpy/_core/tests/test_regression.py +2672 -0
  196. numpy/_core/tests/test_scalar_ctors.py +203 -0
  197. numpy/_core/tests/test_scalar_methods.py +327 -0
  198. numpy/_core/tests/test_scalarbuffer.py +154 -0
  199. numpy/_core/tests/test_scalarinherit.py +105 -0
  200. numpy/_core/tests/test_scalarmath.py +1167 -0
  201. numpy/_core/tests/test_scalarprint.py +403 -0
  202. numpy/_core/tests/test_shape_base.py +899 -0
  203. numpy/_core/tests/test_simd.py +1345 -0
  204. numpy/_core/tests/test_simd_module.py +105 -0
  205. numpy/_core/tests/test_stringdtype.py +2573 -0
  206. numpy/_core/tests/test_strings.py +1506 -0
  207. numpy/_core/tests/test_ufunc.py +3452 -0
  208. numpy/_core/tests/test_umath.py +5231 -0
  209. numpy/_core/tests/test_umath_accuracy.py +92 -0
  210. numpy/_core/tests/test_umath_complex.py +631 -0
  211. numpy/_core/tests/test_unicode.py +369 -0
  212. numpy/_core/umath.py +59 -0
  213. numpy/_core/umath.pyi +232 -0
  214. numpy/_distributor_init.py +15 -0
  215. numpy/_distributor_init.pyi +1 -0
  216. numpy/_expired_attrs_2_0.py +78 -0
  217. numpy/_expired_attrs_2_0.pyi +61 -0
  218. numpy/_globals.py +121 -0
  219. numpy/_globals.pyi +17 -0
  220. numpy/_pyinstaller/__init__.py +0 -0
  221. numpy/_pyinstaller/__init__.pyi +0 -0
  222. numpy/_pyinstaller/hook-numpy.py +35 -0
  223. numpy/_pyinstaller/hook-numpy.pyi +6 -0
  224. numpy/_pyinstaller/tests/__init__.py +16 -0
  225. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  226. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  227. numpy/_pytesttester.py +186 -0
  228. numpy/_pytesttester.pyi +18 -0
  229. numpy/_typing/__init__.py +147 -0
  230. numpy/_typing/_add_docstring.py +153 -0
  231. numpy/_typing/_array_like.py +92 -0
  232. numpy/_typing/_char_codes.py +156 -0
  233. numpy/_typing/_dtype_like.py +108 -0
  234. numpy/_typing/_extended_precision.py +15 -0
  235. numpy/_typing/_nbit.py +17 -0
  236. numpy/_typing/_nbit_base.py +93 -0
  237. numpy/_typing/_nbit_base.pyi +39 -0
  238. numpy/_typing/_nested_sequence.py +85 -0
  239. numpy/_typing/_scalars.py +20 -0
  240. numpy/_typing/_shape.py +8 -0
  241. numpy/_typing/_ufunc.py +7 -0
  242. numpy/_typing/_ufunc.pyi +970 -0
  243. numpy/_utils/__init__.py +95 -0
  244. numpy/_utils/__init__.pyi +25 -0
  245. numpy/_utils/_conversions.py +18 -0
  246. numpy/_utils/_conversions.pyi +4 -0
  247. numpy/_utils/_inspect.py +192 -0
  248. numpy/_utils/_inspect.pyi +67 -0
  249. numpy/_utils/_pep440.py +486 -0
  250. numpy/_utils/_pep440.pyi +121 -0
  251. numpy/char/__init__.py +31 -0
  252. numpy/char/__init__.pyi +111 -0
  253. numpy/conftest.py +249 -0
  254. numpy/core/__init__.py +33 -0
  255. numpy/core/__init__.pyi +45 -0
  256. numpy/core/_dtype.py +10 -0
  257. numpy/core/_dtype.pyi +0 -0
  258. numpy/core/_dtype_ctypes.py +10 -0
  259. numpy/core/_dtype_ctypes.pyi +0 -0
  260. numpy/core/_internal.py +27 -0
  261. numpy/core/_internal.pyi +1 -0
  262. numpy/core/_multiarray_umath.py +57 -0
  263. numpy/core/_utils.py +21 -0
  264. numpy/core/arrayprint.py +10 -0
  265. numpy/core/arrayprint.pyi +4 -0
  266. numpy/core/defchararray.py +10 -0
  267. numpy/core/defchararray.pyi +4 -0
  268. numpy/core/einsumfunc.py +10 -0
  269. numpy/core/einsumfunc.pyi +4 -0
  270. numpy/core/fromnumeric.py +10 -0
  271. numpy/core/fromnumeric.pyi +4 -0
  272. numpy/core/function_base.py +10 -0
  273. numpy/core/function_base.pyi +4 -0
  274. numpy/core/getlimits.py +10 -0
  275. numpy/core/getlimits.pyi +4 -0
  276. numpy/core/multiarray.py +25 -0
  277. numpy/core/multiarray.pyi +4 -0
  278. numpy/core/numeric.py +12 -0
  279. numpy/core/numeric.pyi +4 -0
  280. numpy/core/numerictypes.py +10 -0
  281. numpy/core/numerictypes.pyi +4 -0
  282. numpy/core/overrides.py +10 -0
  283. numpy/core/overrides.pyi +7 -0
  284. numpy/core/records.py +10 -0
  285. numpy/core/records.pyi +4 -0
  286. numpy/core/shape_base.py +10 -0
  287. numpy/core/shape_base.pyi +4 -0
  288. numpy/core/umath.py +10 -0
  289. numpy/core/umath.pyi +4 -0
  290. numpy/ctypeslib/__init__.py +13 -0
  291. numpy/ctypeslib/__init__.pyi +15 -0
  292. numpy/ctypeslib/_ctypeslib.py +603 -0
  293. numpy/ctypeslib/_ctypeslib.pyi +222 -0
  294. numpy/doc/ufuncs.py +138 -0
  295. numpy/dtypes.py +86 -0
  296. numpy/dtypes.pyi +627 -0
  297. numpy/exceptions.py +246 -0
  298. numpy/exceptions.pyi +27 -0
  299. numpy/f2py/__init__.py +80 -0
  300. numpy/f2py/__init__.pyi +5 -0
  301. numpy/f2py/__main__.py +5 -0
  302. numpy/f2py/__version__.py +1 -0
  303. numpy/f2py/__version__.pyi +1 -0
  304. numpy/f2py/_backends/__init__.py +6 -0
  305. numpy/f2py/_backends/__init__.pyi +5 -0
  306. numpy/f2py/_backends/_backend.py +44 -0
  307. numpy/f2py/_backends/_backend.pyi +46 -0
  308. numpy/f2py/_backends/_meson.py +244 -0
  309. numpy/f2py/_backends/_meson.pyi +61 -0
  310. numpy/f2py/_backends/meson.build.template +63 -0
  311. numpy/f2py/_isocbind.py +62 -0
  312. numpy/f2py/_isocbind.pyi +13 -0
  313. numpy/f2py/_src_pyf.py +247 -0
  314. numpy/f2py/_src_pyf.pyi +28 -0
  315. numpy/f2py/auxfuncs.py +1005 -0
  316. numpy/f2py/auxfuncs.pyi +259 -0
  317. numpy/f2py/capi_maps.py +811 -0
  318. numpy/f2py/capi_maps.pyi +33 -0
  319. numpy/f2py/cb_rules.py +649 -0
  320. numpy/f2py/cb_rules.pyi +17 -0
  321. numpy/f2py/cfuncs.py +1579 -0
  322. numpy/f2py/cfuncs.pyi +31 -0
  323. numpy/f2py/common_rules.py +145 -0
  324. numpy/f2py/common_rules.pyi +9 -0
  325. numpy/f2py/crackfortran.py +3727 -0
  326. numpy/f2py/crackfortran.pyi +254 -0
  327. numpy/f2py/diagnose.py +57 -0
  328. numpy/f2py/diagnose.pyi +1 -0
  329. numpy/f2py/f2py2e.py +755 -0
  330. numpy/f2py/f2py2e.pyi +69 -0
  331. numpy/f2py/f90mod_rules.py +281 -0
  332. numpy/f2py/f90mod_rules.pyi +16 -0
  333. numpy/f2py/func2subr.py +329 -0
  334. numpy/f2py/func2subr.pyi +7 -0
  335. numpy/f2py/rules.py +1641 -0
  336. numpy/f2py/rules.pyi +36 -0
  337. numpy/f2py/setup.cfg +3 -0
  338. numpy/f2py/src/fortranobject.c +1471 -0
  339. numpy/f2py/src/fortranobject.h +173 -0
  340. numpy/f2py/symbolic.py +1518 -0
  341. numpy/f2py/symbolic.pyi +220 -0
  342. numpy/f2py/tests/__init__.py +16 -0
  343. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  344. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  345. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +262 -0
  346. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  347. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  348. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  349. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  350. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  351. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  352. numpy/f2py/tests/src/callback/foo.f +62 -0
  353. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  354. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  355. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  356. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  357. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  358. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  359. numpy/f2py/tests/src/cli/hi77.f +3 -0
  360. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  361. numpy/f2py/tests/src/common/block.f +11 -0
  362. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  363. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  365. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  366. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  367. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  368. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  369. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  370. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  371. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  372. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  373. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  374. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  375. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  376. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  377. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  378. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  379. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  380. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  381. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  382. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  383. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  384. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  385. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  386. numpy/f2py/tests/src/inplace/foo.f +31 -0
  387. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  388. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  389. numpy/f2py/tests/src/mixed/foo.f +5 -0
  390. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  391. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  392. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  393. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  394. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  395. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  396. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  397. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  398. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  399. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  400. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  401. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  402. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  403. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  404. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  405. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  406. numpy/f2py/tests/src/regression/AB.inc +1 -0
  407. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  408. numpy/f2py/tests/src/regression/complex_struct_compat.f90 +8 -0
  409. numpy/f2py/tests/src/regression/complex_struct_compat.pyf +12 -0
  410. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  411. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  412. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  413. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  414. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  415. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  416. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  417. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  418. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  419. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  420. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  421. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  422. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  423. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  424. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  425. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  426. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  427. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  428. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  429. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  430. numpy/f2py/tests/src/routines/subrout.f +4 -0
  431. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  432. numpy/f2py/tests/src/size/foo.f90 +44 -0
  433. numpy/f2py/tests/src/string/char.f90 +29 -0
  434. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  435. numpy/f2py/tests/src/string/gh24008.f +8 -0
  436. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  437. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  438. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  439. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  440. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  441. numpy/f2py/tests/src/string/string.f +12 -0
  442. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  443. numpy/f2py/tests/test_abstract_interface.py +26 -0
  444. numpy/f2py/tests/test_array_from_pyobj.py +732 -0
  445. numpy/f2py/tests/test_assumed_shape.py +52 -0
  446. numpy/f2py/tests/test_block_docstring.py +16 -0
  447. numpy/f2py/tests/test_callback.py +262 -0
  448. numpy/f2py/tests/test_capi_maps.py +10 -0
  449. numpy/f2py/tests/test_character.py +644 -0
  450. numpy/f2py/tests/test_common.py +24 -0
  451. numpy/f2py/tests/test_crackfortran.py +427 -0
  452. numpy/f2py/tests/test_data.py +74 -0
  453. numpy/f2py/tests/test_docs.py +66 -0
  454. numpy/f2py/tests/test_f2cmap.py +20 -0
  455. numpy/f2py/tests/test_f2py2e.py +1006 -0
  456. numpy/f2py/tests/test_inplace.py +49 -0
  457. numpy/f2py/tests/test_isoc.py +56 -0
  458. numpy/f2py/tests/test_kind.py +53 -0
  459. numpy/f2py/tests/test_mixed.py +31 -0
  460. numpy/f2py/tests/test_modules.py +87 -0
  461. numpy/f2py/tests/test_parameter.py +121 -0
  462. numpy/f2py/tests/test_pyf_src.py +43 -0
  463. numpy/f2py/tests/test_quoted_character.py +19 -0
  464. numpy/f2py/tests/test_regression.py +202 -0
  465. numpy/f2py/tests/test_return_character.py +48 -0
  466. numpy/f2py/tests/test_return_complex.py +67 -0
  467. numpy/f2py/tests/test_return_integer.py +55 -0
  468. numpy/f2py/tests/test_return_logical.py +66 -0
  469. numpy/f2py/tests/test_return_real.py +109 -0
  470. numpy/f2py/tests/test_routines.py +29 -0
  471. numpy/f2py/tests/test_semicolon_split.py +76 -0
  472. numpy/f2py/tests/test_size.py +42 -0
  473. numpy/f2py/tests/test_string.py +102 -0
  474. numpy/f2py/tests/test_symbolic.py +501 -0
  475. numpy/f2py/tests/test_value_attrspec.py +15 -0
  476. numpy/f2py/tests/util.py +442 -0
  477. numpy/f2py/use_rules.py +100 -0
  478. numpy/f2py/use_rules.pyi +9 -0
  479. numpy/fft/__init__.py +213 -0
  480. numpy/fft/__init__.pyi +38 -0
  481. numpy/fft/_helper.py +235 -0
  482. numpy/fft/_helper.pyi +145 -0
  483. numpy/fft/_pocketfft.py +1693 -0
  484. numpy/fft/_pocketfft.pyi +1131 -0
  485. numpy/fft/_pocketfft_umath.cp315-win32.lib +0 -0
  486. numpy/fft/_pocketfft_umath.cp315-win32.pyd +0 -0
  487. numpy/fft/tests/__init__.py +0 -0
  488. numpy/fft/tests/test_helper.py +167 -0
  489. numpy/fft/tests/test_pocketfft.py +609 -0
  490. numpy/lib/__init__.py +90 -0
  491. numpy/lib/__init__.pyi +52 -0
  492. numpy/lib/_array_utils_impl.py +62 -0
  493. numpy/lib/_array_utils_impl.pyi +10 -0
  494. numpy/lib/_arraypad_impl.py +926 -0
  495. numpy/lib/_arraypad_impl.pyi +99 -0
  496. numpy/lib/_arraysetops_impl.py +1158 -0
  497. numpy/lib/_arraysetops_impl.pyi +460 -0
  498. numpy/lib/_arrayterator_impl.py +224 -0
  499. numpy/lib/_arrayterator_impl.pyi +45 -0
  500. numpy/lib/_datasource.py +700 -0
  501. numpy/lib/_datasource.pyi +30 -0
  502. numpy/lib/_format_impl.py +1038 -0
  503. numpy/lib/_format_impl.pyi +56 -0
  504. numpy/lib/_function_base_impl.py +5775 -0
  505. numpy/lib/_function_base_impl.pyi +2315 -0
  506. numpy/lib/_histograms_impl.py +1085 -0
  507. numpy/lib/_histograms_impl.pyi +273 -0
  508. numpy/lib/_index_tricks_impl.py +1048 -0
  509. numpy/lib/_index_tricks_impl.pyi +350 -0
  510. numpy/lib/_iotools.py +900 -0
  511. numpy/lib/_iotools.pyi +113 -0
  512. numpy/lib/_nanfunctions_impl.py +2006 -0
  513. numpy/lib/_nanfunctions_impl.pyi +48 -0
  514. numpy/lib/_npyio_impl.py +2491 -0
  515. numpy/lib/_npyio_impl.pyi +288 -0
  516. numpy/lib/_polynomial_impl.py +1467 -0
  517. numpy/lib/_polynomial_impl.pyi +435 -0
  518. numpy/lib/_scimath_impl.py +642 -0
  519. numpy/lib/_scimath_impl.pyi +93 -0
  520. numpy/lib/_shape_base_impl.py +1247 -0
  521. numpy/lib/_shape_base_impl.pyi +256 -0
  522. numpy/lib/_stride_tricks_impl.py +656 -0
  523. numpy/lib/_stride_tricks_impl.pyi +75 -0
  524. numpy/lib/_twodim_base_impl.py +1242 -0
  525. numpy/lib/_twodim_base_impl.pyi +397 -0
  526. numpy/lib/_type_check_impl.py +714 -0
  527. numpy/lib/_type_check_impl.pyi +450 -0
  528. numpy/lib/_ufunclike_impl.py +212 -0
  529. numpy/lib/_ufunclike_impl.pyi +41 -0
  530. numpy/lib/_user_array_impl.py +310 -0
  531. numpy/lib/_user_array_impl.pyi +229 -0
  532. numpy/lib/_utils_impl.py +541 -0
  533. numpy/lib/_utils_impl.pyi +18 -0
  534. numpy/lib/_version.py +153 -0
  535. numpy/lib/_version.pyi +22 -0
  536. numpy/lib/array_utils.py +7 -0
  537. numpy/lib/array_utils.pyi +6 -0
  538. numpy/lib/format.py +24 -0
  539. numpy/lib/format.pyi +24 -0
  540. numpy/lib/introspect.py +94 -0
  541. numpy/lib/introspect.pyi +3 -0
  542. numpy/lib/mixins.py +180 -0
  543. numpy/lib/mixins.pyi +78 -0
  544. numpy/lib/npyio.py +1 -0
  545. numpy/lib/npyio.pyi +5 -0
  546. numpy/lib/recfunctions.py +1681 -0
  547. numpy/lib/recfunctions.pyi +436 -0
  548. numpy/lib/scimath.py +13 -0
  549. numpy/lib/scimath.pyi +12 -0
  550. numpy/lib/stride_tricks.py +1 -0
  551. numpy/lib/stride_tricks.pyi +4 -0
  552. numpy/lib/tests/__init__.py +0 -0
  553. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  554. numpy/lib/tests/data/py2-objarr.npy +0 -0
  555. numpy/lib/tests/data/py2-objarr.npz +0 -0
  556. numpy/lib/tests/data/py3-objarr.npy +0 -0
  557. numpy/lib/tests/data/py3-objarr.npz +0 -0
  558. numpy/lib/tests/data/python3.npy +0 -0
  559. numpy/lib/tests/data/win64python2.npy +0 -0
  560. numpy/lib/tests/test__datasource.py +328 -0
  561. numpy/lib/tests/test__iotools.py +358 -0
  562. numpy/lib/tests/test__version.py +64 -0
  563. numpy/lib/tests/test_array_utils.py +32 -0
  564. numpy/lib/tests/test_arraypad.py +1427 -0
  565. numpy/lib/tests/test_arraysetops.py +1304 -0
  566. numpy/lib/tests/test_arrayterator.py +45 -0
  567. numpy/lib/tests/test_format.py +1043 -0
  568. numpy/lib/tests/test_function_base.py +4787 -0
  569. numpy/lib/tests/test_histograms.py +855 -0
  570. numpy/lib/tests/test_index_tricks.py +703 -0
  571. numpy/lib/tests/test_io.py +2733 -0
  572. numpy/lib/tests/test_loadtxt.py +1077 -0
  573. numpy/lib/tests/test_mixins.py +215 -0
  574. numpy/lib/tests/test_nanfunctions.py +1449 -0
  575. numpy/lib/tests/test_packbits.py +374 -0
  576. numpy/lib/tests/test_polynomial.py +333 -0
  577. numpy/lib/tests/test_recfunctions.py +1042 -0
  578. numpy/lib/tests/test_regression.py +231 -0
  579. numpy/lib/tests/test_shape_base.py +813 -0
  580. numpy/lib/tests/test_stride_tricks.py +890 -0
  581. numpy/lib/tests/test_twodim_base.py +564 -0
  582. numpy/lib/tests/test_type_check.py +473 -0
  583. numpy/lib/tests/test_ufunclike.py +121 -0
  584. numpy/lib/tests/test_utils.py +80 -0
  585. numpy/lib/user_array.py +1 -0
  586. numpy/lib/user_array.pyi +1 -0
  587. numpy/linalg/__init__.py +95 -0
  588. numpy/linalg/__init__.pyi +71 -0
  589. numpy/linalg/_linalg.py +3649 -0
  590. numpy/linalg/_linalg.pyi +1230 -0
  591. numpy/linalg/_umath_linalg.cp315-win32.lib +0 -0
  592. numpy/linalg/_umath_linalg.cp315-win32.pyd +0 -0
  593. numpy/linalg/_umath_linalg.pyi +60 -0
  594. numpy/linalg/lapack_lite.cp315-win32.lib +0 -0
  595. numpy/linalg/lapack_lite.cp315-win32.pyd +0 -0
  596. numpy/linalg/lapack_lite.pyi +143 -0
  597. numpy/linalg/tests/__init__.py +0 -0
  598. numpy/linalg/tests/test_deprecations.py +21 -0
  599. numpy/linalg/tests/test_linalg.py +2492 -0
  600. numpy/linalg/tests/test_regression.py +191 -0
  601. numpy/ma/API_CHANGES.txt +135 -0
  602. numpy/ma/LICENSE +24 -0
  603. numpy/ma/README.rst +236 -0
  604. numpy/ma/__init__.py +53 -0
  605. numpy/ma/__init__.pyi +458 -0
  606. numpy/ma/core.py +9000 -0
  607. numpy/ma/core.pyi +4767 -0
  608. numpy/ma/extras.py +2266 -0
  609. numpy/ma/extras.pyi +770 -0
  610. numpy/ma/mrecords.py +739 -0
  611. numpy/ma/mrecords.pyi +313 -0
  612. numpy/ma/tests/__init__.py +0 -0
  613. numpy/ma/tests/test_arrayobject.py +40 -0
  614. numpy/ma/tests/test_core.py +6112 -0
  615. numpy/ma/tests/test_deprecations.py +73 -0
  616. numpy/ma/tests/test_extras.py +1945 -0
  617. numpy/ma/tests/test_mrecords.py +495 -0
  618. numpy/ma/tests/test_old_ma.py +939 -0
  619. numpy/ma/tests/test_regression.py +83 -0
  620. numpy/ma/tests/test_subclassing.py +469 -0
  621. numpy/ma/testutils.py +294 -0
  622. numpy/ma/testutils.pyi +69 -0
  623. numpy/matlib.py +380 -0
  624. numpy/matlib.pyi +580 -0
  625. numpy/matrixlib/__init__.py +12 -0
  626. numpy/matrixlib/__init__.pyi +3 -0
  627. numpy/matrixlib/defmatrix.py +1117 -0
  628. numpy/matrixlib/defmatrix.pyi +211 -0
  629. numpy/matrixlib/tests/__init__.py +0 -0
  630. numpy/matrixlib/tests/test_defmatrix.py +475 -0
  631. numpy/matrixlib/tests/test_interaction.py +360 -0
  632. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  633. numpy/matrixlib/tests/test_matrix_linalg.py +110 -0
  634. numpy/matrixlib/tests/test_multiarray.py +17 -0
  635. numpy/matrixlib/tests/test_numeric.py +18 -0
  636. numpy/matrixlib/tests/test_regression.py +31 -0
  637. numpy/polynomial/__init__.py +187 -0
  638. numpy/polynomial/__init__.pyi +31 -0
  639. numpy/polynomial/_polybase.py +1191 -0
  640. numpy/polynomial/_polybase.pyi +255 -0
  641. numpy/polynomial/_polytypes.pyi +536 -0
  642. numpy/polynomial/chebyshev.py +2053 -0
  643. numpy/polynomial/chebyshev.pyi +173 -0
  644. numpy/polynomial/hermite.py +1794 -0
  645. numpy/polynomial/hermite.pyi +110 -0
  646. numpy/polynomial/hermite_e.py +1692 -0
  647. numpy/polynomial/hermite_e.pyi +110 -0
  648. numpy/polynomial/laguerre.py +1729 -0
  649. numpy/polynomial/laguerre.pyi +103 -0
  650. numpy/polynomial/legendre.py +1655 -0
  651. numpy/polynomial/legendre.pyi +103 -0
  652. numpy/polynomial/polynomial.py +1683 -0
  653. numpy/polynomial/polynomial.pyi +112 -0
  654. numpy/polynomial/polyutils.py +759 -0
  655. numpy/polynomial/polyutils.pyi +295 -0
  656. numpy/polynomial/tests/__init__.py +0 -0
  657. numpy/polynomial/tests/test_chebyshev.py +639 -0
  658. numpy/polynomial/tests/test_classes.py +625 -0
  659. numpy/polynomial/tests/test_hermite.py +574 -0
  660. numpy/polynomial/tests/test_hermite_e.py +575 -0
  661. numpy/polynomial/tests/test_laguerre.py +556 -0
  662. numpy/polynomial/tests/test_legendre.py +587 -0
  663. numpy/polynomial/tests/test_polynomial.py +713 -0
  664. numpy/polynomial/tests/test_polyutils.py +123 -0
  665. numpy/polynomial/tests/test_printing.py +562 -0
  666. numpy/polynomial/tests/test_symbol.py +217 -0
  667. numpy/py.typed +0 -0
  668. numpy/random/LICENSE.md +71 -0
  669. numpy/random/__init__.pxd +14 -0
  670. numpy/random/__init__.py +213 -0
  671. numpy/random/__init__.pyi +124 -0
  672. numpy/random/_bounded_integers.cp315-win32.lib +0 -0
  673. numpy/random/_bounded_integers.cp315-win32.pyd +0 -0
  674. numpy/random/_bounded_integers.pxd +38 -0
  675. numpy/random/_bounded_integers.pyi +1 -0
  676. numpy/random/_common.cp315-win32.lib +0 -0
  677. numpy/random/_common.cp315-win32.pyd +0 -0
  678. numpy/random/_common.pxd +110 -0
  679. numpy/random/_common.pyi +17 -0
  680. numpy/random/_examples/cffi/extending.py +44 -0
  681. numpy/random/_examples/cffi/parse.py +53 -0
  682. numpy/random/_examples/cython/extending.pyx +77 -0
  683. numpy/random/_examples/cython/extending_distributions.pyx +117 -0
  684. numpy/random/_examples/cython/meson.build +53 -0
  685. numpy/random/_examples/numba/extending.py +86 -0
  686. numpy/random/_examples/numba/extending_distributions.py +67 -0
  687. numpy/random/_generator.cp315-win32.lib +0 -0
  688. numpy/random/_generator.cp315-win32.pyd +0 -0
  689. numpy/random/_generator.pyi +769 -0
  690. numpy/random/_mt19937.cp315-win32.lib +0 -0
  691. numpy/random/_mt19937.cp315-win32.pyd +0 -0
  692. numpy/random/_mt19937.pyi +27 -0
  693. numpy/random/_pcg64.cp315-win32.lib +0 -0
  694. numpy/random/_pcg64.cp315-win32.pyd +0 -0
  695. numpy/random/_pcg64.pyi +36 -0
  696. numpy/random/_philox.cp315-win32.lib +0 -0
  697. numpy/random/_philox.cp315-win32.pyd +0 -0
  698. numpy/random/_philox.pyi +36 -0
  699. numpy/random/_pickle.py +88 -0
  700. numpy/random/_pickle.pyi +43 -0
  701. numpy/random/_sfc64.cp315-win32.lib +0 -0
  702. numpy/random/_sfc64.cp315-win32.pyd +0 -0
  703. numpy/random/_sfc64.pyi +25 -0
  704. numpy/random/bit_generator.cp315-win32.lib +0 -0
  705. numpy/random/bit_generator.cp315-win32.pyd +0 -0
  706. numpy/random/bit_generator.pxd +35 -0
  707. numpy/random/bit_generator.pyi +122 -0
  708. numpy/random/c_distributions.pxd +119 -0
  709. numpy/random/lib/npyrandom.lib +0 -0
  710. numpy/random/mtrand.cp315-win32.lib +0 -0
  711. numpy/random/mtrand.cp315-win32.pyd +0 -0
  712. numpy/random/mtrand.pyi +996 -0
  713. numpy/random/tests/__init__.py +0 -0
  714. numpy/random/tests/data/__init__.py +0 -0
  715. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  716. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  717. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  718. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  719. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  720. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  721. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  722. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  723. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  724. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  725. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  726. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  727. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  728. numpy/random/tests/test_direct.py +620 -0
  729. numpy/random/tests/test_extending.py +129 -0
  730. numpy/random/tests/test_generator_mt19937.py +2830 -0
  731. numpy/random/tests/test_generator_mt19937_regressions.py +240 -0
  732. numpy/random/tests/test_random.py +1723 -0
  733. numpy/random/tests/test_randomstate.py +2107 -0
  734. numpy/random/tests/test_randomstate_regression.py +249 -0
  735. numpy/random/tests/test_regression.py +174 -0
  736. numpy/random/tests/test_seed_sequence.py +103 -0
  737. numpy/random/tests/test_smoke.py +882 -0
  738. numpy/rec/__init__.py +2 -0
  739. numpy/rec/__init__.pyi +23 -0
  740. numpy/strings/__init__.py +2 -0
  741. numpy/strings/__init__.pyi +97 -0
  742. numpy/testing/__init__.py +22 -0
  743. numpy/testing/__init__.pyi +107 -0
  744. numpy/testing/_private/__init__.py +0 -0
  745. numpy/testing/_private/__init__.pyi +0 -0
  746. numpy/testing/_private/extbuild.py +247 -0
  747. numpy/testing/_private/extbuild.pyi +25 -0
  748. numpy/testing/_private/utils.py +2899 -0
  749. numpy/testing/_private/utils.pyi +501 -0
  750. numpy/testing/overrides.py +84 -0
  751. numpy/testing/overrides.pyi +10 -0
  752. numpy/testing/print_coercion_tables.py +207 -0
  753. numpy/testing/print_coercion_tables.pyi +26 -0
  754. numpy/testing/tests/__init__.py +0 -0
  755. numpy/testing/tests/test_utils.py +2147 -0
  756. numpy/tests/__init__.py +0 -0
  757. numpy/tests/test__all__.py +10 -0
  758. numpy/tests/test_configtool.py +51 -0
  759. numpy/tests/test_ctypeslib.py +406 -0
  760. numpy/tests/test_lazyloading.py +35 -0
  761. numpy/tests/test_matlib.py +59 -0
  762. numpy/tests/test_numpy_config.py +47 -0
  763. numpy/tests/test_numpy_version.py +54 -0
  764. numpy/tests/test_public_api.py +723 -0
  765. numpy/tests/test_reloading.py +69 -0
  766. numpy/tests/test_scripts.py +45 -0
  767. numpy/tests/test_warnings.py +81 -0
  768. numpy/typing/__init__.py +225 -0
  769. numpy/typing/__init__.pyi +8 -0
  770. numpy/typing/mypy_plugin.py +200 -0
  771. numpy/typing/tests/__init__.py +0 -0
  772. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  773. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  774. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  775. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  776. numpy/typing/tests/data/fail/arrayprint.pyi +15 -0
  777. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  778. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  779. numpy/typing/tests/data/fail/char.pyi +60 -0
  780. numpy/typing/tests/data/fail/chararray.pyi +61 -0
  781. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  782. numpy/typing/tests/data/fail/constants.pyi +3 -0
  783. numpy/typing/tests/data/fail/datasource.pyi +16 -0
  784. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  785. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  786. numpy/typing/tests/data/fail/flatiter.pyi +38 -0
  787. numpy/typing/tests/data/fail/fromnumeric.pyi +149 -0
  788. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  789. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  790. numpy/typing/tests/data/fail/lib_function_base.pyi +60 -0
  791. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  792. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  793. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  794. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  795. numpy/typing/tests/data/fail/ma.pyi +152 -0
  796. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  797. numpy/typing/tests/data/fail/modules.pyi +17 -0
  798. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  799. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  800. numpy/typing/tests/data/fail/ndarray_misc.pyi +49 -0
  801. numpy/typing/tests/data/fail/nditer.pyi +7 -0
  802. numpy/typing/tests/data/fail/nested_sequence.pyi +17 -0
  803. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  804. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  805. numpy/typing/tests/data/fail/random.pyi +62 -0
  806. numpy/typing/tests/data/fail/rec.pyi +17 -0
  807. numpy/typing/tests/data/fail/scalars.pyi +86 -0
  808. numpy/typing/tests/data/fail/shape.pyi +7 -0
  809. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  810. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  811. numpy/typing/tests/data/fail/strings.pyi +41 -0
  812. numpy/typing/tests/data/fail/testing.pyi +28 -0
  813. numpy/typing/tests/data/fail/twodim_base.pyi +39 -0
  814. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  815. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  816. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  817. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  818. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  819. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  820. numpy/typing/tests/data/mypy.ini +8 -0
  821. numpy/typing/tests/data/pass/arithmetic.py +614 -0
  822. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  823. numpy/typing/tests/data/pass/array_like.py +37 -0
  824. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  825. numpy/typing/tests/data/pass/arrayterator.py +28 -0
  826. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  827. numpy/typing/tests/data/pass/comparisons.py +316 -0
  828. numpy/typing/tests/data/pass/dtype.py +57 -0
  829. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  830. numpy/typing/tests/data/pass/flatiter.py +26 -0
  831. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  832. numpy/typing/tests/data/pass/index_tricks.py +62 -0
  833. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  834. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  835. numpy/typing/tests/data/pass/lib_version.py +18 -0
  836. numpy/typing/tests/data/pass/literal.py +52 -0
  837. numpy/typing/tests/data/pass/ma.py +199 -0
  838. numpy/typing/tests/data/pass/mod.py +149 -0
  839. numpy/typing/tests/data/pass/modules.py +45 -0
  840. numpy/typing/tests/data/pass/multiarray.py +77 -0
  841. numpy/typing/tests/data/pass/ndarray_conversion.py +81 -0
  842. numpy/typing/tests/data/pass/ndarray_misc.py +199 -0
  843. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  844. numpy/typing/tests/data/pass/nditer.py +4 -0
  845. numpy/typing/tests/data/pass/numeric.py +90 -0
  846. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  847. numpy/typing/tests/data/pass/random.py +1498 -0
  848. numpy/typing/tests/data/pass/recfunctions.py +164 -0
  849. numpy/typing/tests/data/pass/scalars.py +262 -0
  850. numpy/typing/tests/data/pass/shape.py +19 -0
  851. numpy/typing/tests/data/pass/simple.py +170 -0
  852. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  853. numpy/typing/tests/data/pass/ufunclike.py +52 -0
  854. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  855. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  856. numpy/typing/tests/data/reveal/arithmetic.pyi +726 -0
  857. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  858. numpy/typing/tests/data/reveal/array_constructors.pyi +331 -0
  859. numpy/typing/tests/data/reveal/arraypad.pyi +32 -0
  860. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  861. numpy/typing/tests/data/reveal/arraysetops.pyi +80 -0
  862. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  863. numpy/typing/tests/data/reveal/bitwise_ops.pyi +166 -0
  864. numpy/typing/tests/data/reveal/char.pyi +228 -0
  865. numpy/typing/tests/data/reveal/chararray.pyi +138 -0
  866. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  867. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  868. numpy/typing/tests/data/reveal/ctypeslib.pyi +86 -0
  869. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  870. numpy/typing/tests/data/reveal/dtype.pyi +166 -0
  871. numpy/typing/tests/data/reveal/einsumfunc.pyi +46 -0
  872. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  873. numpy/typing/tests/data/reveal/fft.pyi +189 -0
  874. numpy/typing/tests/data/reveal/flatiter.pyi +86 -0
  875. numpy/typing/tests/data/reveal/fromnumeric.pyi +574 -0
  876. numpy/typing/tests/data/reveal/getlimits.pyi +53 -0
  877. numpy/typing/tests/data/reveal/histograms.pyi +69 -0
  878. numpy/typing/tests/data/reveal/index_tricks.pyi +148 -0
  879. numpy/typing/tests/data/reveal/lib_function_base.pyi +413 -0
  880. numpy/typing/tests/data/reveal/lib_polynomial.pyi +147 -0
  881. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  882. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  883. numpy/typing/tests/data/reveal/linalg.pyi +517 -0
  884. numpy/typing/tests/data/reveal/ma.pyi +1103 -0
  885. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  886. numpy/typing/tests/data/reveal/memmap.pyi +21 -0
  887. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  888. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  889. numpy/typing/tests/data/reveal/multiarray.pyi +336 -0
  890. numpy/typing/tests/data/reveal/nbit_base_example.pyi +17 -0
  891. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +79 -0
  892. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +83 -0
  893. numpy/typing/tests/data/reveal/ndarray_misc.pyi +428 -0
  894. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +47 -0
  895. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  896. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  897. numpy/typing/tests/data/reveal/npyio.pyi +85 -0
  898. numpy/typing/tests/data/reveal/numeric.pyi +176 -0
  899. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  900. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +216 -0
  901. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +218 -0
  902. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  903. numpy/typing/tests/data/reveal/random.pyi +1357 -0
  904. numpy/typing/tests/data/reveal/rec.pyi +177 -0
  905. numpy/typing/tests/data/reveal/scalars.pyi +288 -0
  906. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  907. numpy/typing/tests/data/reveal/shape_base.pyi +84 -0
  908. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  909. numpy/typing/tests/data/reveal/strings.pyi +198 -0
  910. numpy/typing/tests/data/reveal/testing.pyi +196 -0
  911. numpy/typing/tests/data/reveal/twodim_base.pyi +231 -0
  912. numpy/typing/tests/data/reveal/type_check.pyi +94 -0
  913. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  914. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  915. numpy/typing/tests/data/reveal/ufuncs.pyi +142 -0
  916. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  917. numpy/typing/tests/test_isfile.py +35 -0
  918. numpy/typing/tests/test_runtime.py +103 -0
  919. numpy/typing/tests/test_typing.py +207 -0
  920. numpy/version.py +11 -0
  921. numpy/version.pyi +9 -0
  922. numpy-2.5.2.dist-info/METADATA +139 -0
  923. numpy-2.5.2.dist-info/RECORD +942 -0
  924. numpy-2.5.2.dist-info/WHEEL +4 -0
  925. numpy-2.5.2.dist-info/entry_points.txt +13 -0
  926. numpy-2.5.2.dist-info/licenses/LICENSE.txt +914 -0
  927. numpy-2.5.2.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt +21 -0
  928. numpy-2.5.2.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING +14 -0
  929. numpy-2.5.2.dist-info/licenses/numpy/_core/src/highway/LICENSE +371 -0
  930. numpy-2.5.2.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt +27 -0
  931. numpy-2.5.2.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md +28 -0
  932. numpy-2.5.2.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE +30 -0
  933. numpy-2.5.2.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md +25 -0
  934. numpy-2.5.2.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt +48 -0
  935. numpy-2.5.2.dist-info/licenses/numpy/ma/LICENSE +24 -0
  936. numpy-2.5.2.dist-info/licenses/numpy/random/LICENSE.md +71 -0
  937. numpy-2.5.2.dist-info/licenses/numpy/random/src/distributions/LICENSE.md +61 -0
  938. numpy-2.5.2.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md +61 -0
  939. numpy-2.5.2.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md +22 -0
  940. numpy-2.5.2.dist-info/licenses/numpy/random/src/philox/LICENSE.md +31 -0
  941. numpy-2.5.2.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md +27 -0
  942. numpy-2.5.2.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md +9 -0
@@ -0,0 +1,3727 @@
1
+ """
2
+ crackfortran --- read fortran (77,90) code and extract declaration information.
3
+
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
+
9
+ NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
10
+
11
+
12
+ Usage of crackfortran:
13
+ ======================
14
+ Command line keys: -quiet,-verbose,-fix,-f77,-f90,-show,-h <pyffilename>
15
+ -m <module name for f77 routines>,--ignore-contains
16
+ Functions: crackfortran, crack2fortran
17
+ The following Fortran statements/constructions are supported
18
+ (or will be if needed):
19
+ block data,byte,call,character,common,complex,contains,data,
20
+ dimension,double complex,double precision,end,external,function,
21
+ implicit,integer,intent,interface,intrinsic,
22
+ logical,module,optional,parameter,private,public,
23
+ program,real,(sequence?),subroutine,type,use,virtual,
24
+ include,pythonmodule
25
+ Note: 'virtual' is mapped to 'dimension'.
26
+ Note: 'implicit integer (z) static (z)' is 'implicit static (z)' (this is minor bug).
27
+ Note: code after 'contains' will be ignored until its scope ends.
28
+ Note: 'common' statement is extended: dimensions are moved to variable definitions
29
+ Note: f2py directive: <commentchar>f2py<line> is read as <line>
30
+ Note: pythonmodule is introduced to represent Python module
31
+
32
+ Usage:
33
+ `postlist=crackfortran(files)`
34
+ `postlist` contains declaration information read from the list of files `files`.
35
+ `crack2fortran(postlist)` returns a fortran code to be saved to pyf-file
36
+
37
+ `postlist` has the following structure:
38
+ *** it is a list of dictionaries containing `blocks':
39
+ B = {'block','body','vars','parent_block'[,'name','prefix','args','result',
40
+ 'implicit','externals','interfaced','common','sortvars',
41
+ 'commonvars','note']}
42
+ B['block'] = 'interface' | 'function' | 'subroutine' | 'module' |
43
+ 'program' | 'block data' | 'type' | 'pythonmodule' |
44
+ 'abstract interface'
45
+ B['body'] --- list containing `subblocks' with the same structure as `blocks'
46
+ B['parent_block'] --- dictionary of a parent block:
47
+ C['body'][<index>]['parent_block'] is C
48
+ B['vars'] --- dictionary of variable definitions
49
+ B['sortvars'] --- dictionary of variable definitions sorted by dependence (independent first)
50
+ B['name'] --- name of the block (not if B['block']=='interface')
51
+ B['prefix'] --- prefix string (only if B['block']=='function')
52
+ B['args'] --- list of argument names if B['block']== 'function' | 'subroutine'
53
+ B['result'] --- name of the return value (only if B['block']=='function')
54
+ B['implicit'] --- dictionary {'a':<variable definition>,'b':...} | None
55
+ B['externals'] --- list of variables being external
56
+ B['interfaced'] --- list of variables being external and defined
57
+ B['common'] --- dictionary of common blocks (list of objects)
58
+ B['commonvars'] --- list of variables used in common blocks (dimensions are moved to variable definitions)
59
+ B['from'] --- string showing the 'parents' of the current block
60
+ B['use'] --- dictionary of modules used in current block:
61
+ {<modulename>:{['only':<0|1>],['map':{<local_name1>:<use_name1>,...}]}}
62
+ B['note'] --- list of LaTeX comments on the block
63
+ B['f2pyenhancements'] --- optional dictionary
64
+ {'threadsafe':'','fortranname':<name>,
65
+ 'callstatement':<C-expr>|<multi-line block>,
66
+ 'callprotoargument':<C-expr-list>,
67
+ 'usercode':<multi-line block>|<list of multi-line blocks>,
68
+ 'pymethoddef:<multi-line block>'
69
+ }
70
+ B['entry'] --- dictionary {entryname:argslist,..}
71
+ B['varnames'] --- list of variable names given in the order of reading the
72
+ Fortran code, useful for derived types.
73
+ B['saved_interface'] --- a string of scanned routine signature, defines explicit interface
74
+ *** Variable definition is a dictionary
75
+ D = B['vars'][<variable name>] =
76
+ {'typespec'[,'attrspec','kindselector','charselector','=','typename']}
77
+ D['typespec'] = 'byte' | 'character' | 'complex' | 'double complex' |
78
+ 'double precision' | 'integer' | 'logical' | 'real' | 'type'
79
+ D['attrspec'] --- list of attributes (e.g. 'dimension(<arrayspec>)',
80
+ 'external','intent(in|out|inout|hide|c|callback|cache|aligned4|aligned8|aligned16)',
81
+ 'optional','required', etc)
82
+ K = D['kindselector'] = {['*','kind']} (only if D['typespec'] =
83
+ 'complex' | 'integer' | 'logical' | 'real' )
84
+ C = D['charselector'] = {['*','len','kind','f2py_len']}
85
+ (only if D['typespec']=='character')
86
+ D['='] --- initialization expression string
87
+ D['typename'] --- name of the type if D['typespec']=='type'
88
+ D['dimension'] --- list of dimension bounds
89
+ D['intent'] --- list of intent specifications
90
+ D['depend'] --- list of variable names on which current variable depends on
91
+ D['check'] --- list of C-expressions; if C-expr returns zero, exception is raised
92
+ D['note'] --- list of LaTeX comments on the variable
93
+ *** Meaning of kind/char selectors (few examples):
94
+ D['typespec>']*K['*']
95
+ D['typespec'](kind=K['kind'])
96
+ character*C['*']
97
+ character(len=C['len'],kind=C['kind'], f2py_len=C['f2py_len'])
98
+ (see also fortran type declaration statement formats below)
99
+
100
+ Fortran 90 type declaration statement format
101
+ ============================================
102
+
103
+ F77 is subset of F90
104
+
105
+ (Main source: IBM XL Fortran 5.1 Language Reference Manual)
106
+ type declaration = <typespec> [[<attrspec>]::] <entitydecl>
107
+ <typespec> = byte |
108
+ character[<charselector>] |
109
+ complex[<kindselector>] |
110
+ double complex |
111
+ double precision |
112
+ integer[<kindselector>] |
113
+ logical[<kindselector>] |
114
+ real[<kindselector>] |
115
+ type(<typename>)
116
+ <charselector> = * <charlen> |
117
+ ([len=]<len>[,[kind=]<kind>]) |
118
+ (kind=<kind>[,len=<len>])
119
+ <kindselector> = * <intlen> |
120
+ ([kind=]<kind>)
121
+ <attrspec> = comma separated list of attributes.
122
+ Only the following attributes are used in
123
+ building up the interface:
124
+ external
125
+ (parameter --- affects '=' key)
126
+ optional
127
+ intent
128
+ Other attributes are ignored.
129
+ <intentspec> = in | out | inout
130
+ <arrayspec> = comma separated list of dimension bounds.
131
+ <entitydecl> = <name> [[*<charlen>][(<arrayspec>)] | [(<arrayspec>)]*<charlen>]
132
+ [/<init_expr>/ | =<init_expr>] [,<entitydecl>]
133
+
134
+ In addition, the following attributes are used: check,depend,note
135
+
136
+ TODO:
137
+ * Apply 'parameter' attribute (e.g. 'integer parameter :: i=2' 'real x(i)'
138
+ -> 'real x(2)')
139
+ The above may be solved by creating appropriate preprocessor program, for example.
140
+
141
+ """
142
+ import codecs
143
+ import copy
144
+ import fileinput
145
+ import os
146
+ import platform
147
+ import re
148
+ import string
149
+ import sys
150
+ from pathlib import Path
151
+
152
+ try:
153
+ import charset_normalizer
154
+ except ImportError:
155
+ charset_normalizer = None
156
+
157
+ from . import __version__, symbolic
158
+
159
+ # The environment provided by auxfuncs.py is needed for some calls to eval.
160
+ # As the needed functions cannot be determined by static inspection of the
161
+ # code, it is safest to use import * pending a major refactoring of f2py.
162
+ from .auxfuncs import *
163
+
164
+ f2py_version = __version__.version
165
+
166
+ # Global flags:
167
+ strictf77 = 1 # Ignore `!' comments unless line[0]=='!'
168
+ sourcecodeform = 'fix' # 'fix','free'
169
+ quiet = 0 # Be verbose if 0 (Obsolete: not used any more)
170
+ verbose = 1 # Be quiet if 0, extra verbose if > 1.
171
+ tabchar = 4 * ' '
172
+ pyffilename = ''
173
+ f77modulename = ''
174
+ skipemptyends = 0 # for old F77 programs without 'program' statement
175
+ ignorecontains = 1
176
+ dolowercase = 1
177
+ debug = []
178
+
179
+ # Global variables
180
+ beginpattern = ''
181
+ currentfilename = ''
182
+ expectbegin = 1
183
+ f90modulevars = {}
184
+ filepositiontext = ''
185
+ gotnextfile = 1
186
+ groupcache = None
187
+ groupcounter = 0
188
+ grouplist = {groupcounter: []}
189
+ groupname = ''
190
+ include_paths = []
191
+ neededmodule = -1
192
+ onlyfuncs = []
193
+ previous_context = None
194
+ skipblocksuntil = -1
195
+ skipfuncs = []
196
+ skipfunctions = []
197
+ usermodules = []
198
+
199
+
200
+ def reset_global_f2py_vars():
201
+ global groupcounter, grouplist, neededmodule, expectbegin
202
+ global skipblocksuntil, usermodules, f90modulevars, gotnextfile
203
+ global filepositiontext, currentfilename, skipfunctions, skipfuncs
204
+ global onlyfuncs, include_paths, previous_context
205
+ global strictf77, sourcecodeform, quiet, verbose, tabchar, pyffilename
206
+ global f77modulename, skipemptyends, ignorecontains, dolowercase, debug
207
+
208
+ # flags
209
+ strictf77 = 1
210
+ sourcecodeform = 'fix'
211
+ quiet = 0
212
+ verbose = 1
213
+ tabchar = 4 * ' '
214
+ pyffilename = ''
215
+ f77modulename = ''
216
+ skipemptyends = 0
217
+ ignorecontains = 1
218
+ dolowercase = 1
219
+ debug = []
220
+ # variables
221
+ groupcounter = 0
222
+ grouplist = {groupcounter: []}
223
+ neededmodule = -1
224
+ expectbegin = 1
225
+ skipblocksuntil = -1
226
+ usermodules = []
227
+ f90modulevars = {}
228
+ gotnextfile = 1
229
+ filepositiontext = ''
230
+ currentfilename = ''
231
+ skipfunctions = []
232
+ skipfuncs = []
233
+ onlyfuncs = []
234
+ include_paths = []
235
+ previous_context = None
236
+
237
+
238
+ def outmess(line, flag=1):
239
+ global filepositiontext
240
+
241
+ if not verbose:
242
+ return
243
+ if not quiet:
244
+ if flag:
245
+ sys.stdout.write(filepositiontext)
246
+ sys.stdout.write(line)
247
+
248
+
249
+ defaultimplicitrules = {}
250
+ for c in "abcdefghopqrstuvwxyz$_":
251
+ defaultimplicitrules[c] = {'typespec': 'real'}
252
+ for c in "ijklmn":
253
+ defaultimplicitrules[c] = {'typespec': 'integer'}
254
+ badnames = {}
255
+ invbadnames = {}
256
+ for n in ['int', 'double', 'float', 'char', 'short', 'long', 'void', 'case', 'while',
257
+ 'return', 'signed', 'unsigned', 'if', 'for', 'typedef', 'sizeof', 'union',
258
+ 'struct', 'static', 'register', 'new', 'break', 'do', 'goto', 'switch',
259
+ 'continue', 'else', 'inline', 'extern', 'delete', 'const', 'auto',
260
+ 'len', 'rank', 'shape', 'index', 'slen', 'size', '_i',
261
+ 'max', 'min',
262
+ 'flen', 'fshape',
263
+ 'string', 'complex_double', 'float_double', 'stdin', 'stderr', 'stdout',
264
+ 'type', 'default']:
265
+ badnames[n] = n + '_bn'
266
+ invbadnames[n + '_bn'] = n
267
+
268
+
269
+ def rmbadname1(name):
270
+ if name in badnames:
271
+ errmess(f'rmbadname1: Replacing "{name}" with "{badnames[name]}".\n')
272
+ return badnames[name]
273
+ return name
274
+
275
+
276
+ def rmbadname(names):
277
+ return [rmbadname1(_m) for _m in names]
278
+
279
+
280
+ def undo_rmbadname1(name):
281
+ if name in invbadnames:
282
+ errmess(f'undo_rmbadname1: Replacing "{name}" with "{invbadnames[name]}".\n')
283
+ return invbadnames[name]
284
+ return name
285
+
286
+
287
+ def undo_rmbadname(names):
288
+ return [undo_rmbadname1(_m) for _m in names]
289
+
290
+
291
+ _has_f_header = re.compile(r'-\*-\s*fortran\s*-\*-', re.I).search
292
+ _has_f90_header = re.compile(r'-\*-\s*f90\s*-\*-', re.I).search
293
+ _has_fix_header = re.compile(r'-\*-\s*fix\s*-\*-', re.I).search
294
+ _free_f90_start = re.compile(r'[^c*]\s*[^\s\d\t]', re.I).match
295
+
296
+ # Extensions
297
+ COMMON_FREE_EXTENSIONS = ['.f90', '.f95', '.f03', '.f08']
298
+ COMMON_FIXED_EXTENSIONS = ['.for', '.ftn', '.f77', '.f']
299
+
300
+
301
+ def openhook(filename, mode):
302
+ """Ensures that filename is opened with correct encoding parameter.
303
+
304
+ This function uses charset_normalizer package, when available, for
305
+ determining the encoding of the file to be opened. When charset_normalizer
306
+ is not available, the function detects only UTF encodings, otherwise, ASCII
307
+ encoding is used as fallback.
308
+ """
309
+ # Reads in the entire file. Robust detection of encoding.
310
+ # Correctly handles comments or late stage unicode characters
311
+ # gh-22871
312
+ if charset_normalizer is not None:
313
+ encoding = charset_normalizer.from_path(filename).best().encoding
314
+ else:
315
+ # hint: install charset_normalizer for correct encoding handling
316
+ # No need to read the whole file for trying with startswith
317
+ nbytes = min(32, os.path.getsize(filename))
318
+ with open(filename, 'rb') as fhandle:
319
+ raw = fhandle.read(nbytes)
320
+ if raw.startswith(codecs.BOM_UTF8):
321
+ encoding = 'UTF-8-SIG'
322
+ elif raw.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):
323
+ encoding = 'UTF-32'
324
+ elif raw.startswith((codecs.BOM_LE, codecs.BOM_BE)):
325
+ encoding = 'UTF-16'
326
+ else:
327
+ # Fallback, without charset_normalizer
328
+ encoding = 'ascii'
329
+ return open(filename, mode, encoding=encoding)
330
+
331
+
332
+ def is_free_format(fname):
333
+ """Check if file is in free format Fortran."""
334
+ # f90 allows both fixed and free format, assuming fixed unless
335
+ # signs of free format are detected.
336
+ result = False
337
+ if Path(fname).suffix.lower() in COMMON_FREE_EXTENSIONS:
338
+ result = True
339
+ with openhook(fname, 'r') as fhandle:
340
+ line = fhandle.readline()
341
+ n = 15 # the number of non-comment lines to scan for hints
342
+ if _has_f_header(line):
343
+ n = 0
344
+ elif _has_f90_header(line):
345
+ n = 0
346
+ result = True
347
+ while n > 0 and line:
348
+ if line[0] != '!' and line.strip():
349
+ n -= 1
350
+ if (line[0] != '\t' and _free_f90_start(line[:5])) or line[-2:-1] == '&':
351
+ result = True
352
+ break
353
+ line = fhandle.readline()
354
+ return result
355
+
356
+
357
+ # Read fortran (77,90) code
358
+ def readfortrancode(ffile, dowithline=show, istop=1):
359
+ """
360
+ Read fortran codes from files and
361
+ 1) Get rid of comments, line continuations, and empty lines; lower cases.
362
+ 2) Call dowithline(line) on every line.
363
+ 3) Recursively call itself when statement \"include '<filename>'\" is met.
364
+ """
365
+ global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77
366
+ global beginpattern, quiet, verbose, dolowercase, include_paths
367
+
368
+ if not istop:
369
+ saveglobals = gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\
370
+ beginpattern, quiet, verbose, dolowercase
371
+ if ffile == []:
372
+ return
373
+ localdolowercase = dolowercase
374
+ # cont: set to True when the content of the last line read
375
+ # indicates statement continuation
376
+ cont = False
377
+ finalline = ''
378
+ ll = ''
379
+ includeline = re.compile(
380
+ r'\s*include\s*(\'|")(?P<name>[^\'"]*)(\'|")', re.I)
381
+ cont1 = re.compile(r'(?P<line>.*)&\s*\Z')
382
+ cont2 = re.compile(r'(\s*&|)(?P<line>.*)')
383
+ mline_mark = re.compile(r".*?'''")
384
+ if istop:
385
+ dowithline('', -1)
386
+ ll, l1 = '', ''
387
+ spacedigits = [' '] + [str(_m) for _m in range(10)]
388
+ filepositiontext = ''
389
+ fin = fileinput.FileInput(ffile, openhook=openhook)
390
+ while True:
391
+ try:
392
+ l = fin.readline()
393
+ except UnicodeDecodeError as msg:
394
+ raise Exception(
395
+ f'readfortrancode: reading {fin.filename()}#{fin.lineno()}'
396
+ f' failed with\n{msg}.\nIt is likely that installing charset_normalizer'
397
+ ' package will help f2py determine the input file encoding'
398
+ ' correctly.')
399
+ if not l:
400
+ break
401
+ if fin.isfirstline():
402
+ filepositiontext = ''
403
+ currentfilename = fin.filename()
404
+ gotnextfile = 1
405
+ l1 = l
406
+ strictf77 = 0
407
+ sourcecodeform = 'fix'
408
+ ext = os.path.splitext(currentfilename)[1]
409
+ if Path(currentfilename).suffix.lower() in COMMON_FIXED_EXTENSIONS and \
410
+ not (_has_f90_header(l) or _has_fix_header(l)):
411
+ strictf77 = 1
412
+ elif is_free_format(currentfilename) and not _has_fix_header(l):
413
+ sourcecodeform = 'free'
414
+ if strictf77:
415
+ beginpattern = beginpattern77
416
+ else:
417
+ beginpattern = beginpattern90
418
+ outmess(f"\tReading file {currentfilename!r} "
419
+ f"(format:{sourcecodeform}{',strict' if strictf77 else ''})\n")
420
+
421
+ l = l.expandtabs().replace('\xa0', ' ')
422
+ # Get rid of newline characters
423
+ while not l == '':
424
+ if l[-1] not in "\n\r\f":
425
+ break
426
+ l = l[:-1]
427
+ # Do not lower for directives, gh-2547, gh-27697, gh-26681
428
+ is_f2py_directive = False
429
+ # Unconditionally remove comments
430
+ (l, rl) = split_by_unquoted(l, '!')
431
+ l += ' '
432
+ if rl[:5].lower() == '!f2py': # f2py directive
433
+ l, _ = split_by_unquoted(l + 4 * ' ' + rl[5:], '!')
434
+ is_f2py_directive = True
435
+ if l.strip() == '': # Skip empty line
436
+ if sourcecodeform == 'free':
437
+ # In free form, a statement continues in the next line
438
+ # that is not a comment line [3.3.2.4^1], lines with
439
+ # blanks are comment lines [3.3.2.3^1]. Hence, the
440
+ # line continuation flag must retain its state.
441
+ pass
442
+ else:
443
+ # In fixed form, statement continuation is determined
444
+ # by a non-blank character at the 6-th position. Empty
445
+ # line indicates a start of a new statement
446
+ # [3.3.3.3^1]. Hence, the line continuation flag must
447
+ # be reset.
448
+ cont = False
449
+ continue
450
+ if sourcecodeform == 'fix':
451
+ if l[0] in ['*', 'c', '!', 'C', '#']:
452
+ if l[1:5].lower() == 'f2py': # f2py directive
453
+ l = ' ' + l[5:]
454
+ is_f2py_directive = True
455
+ else: # Skip comment line
456
+ cont = False
457
+ is_f2py_directive = False
458
+ continue
459
+ elif strictf77:
460
+ if len(l) > 72:
461
+ l = l[:72]
462
+ if l[0] not in spacedigits:
463
+ raise Exception('readfortrancode: Found non-(space,digit) char '
464
+ 'in the first column.\n\tAre you sure that '
465
+ f'this code is in fix form?\n\tline={l!r}')
466
+
467
+ if (not cont or strictf77) and (len(l) > 5 and not l[5] == ' '):
468
+ # Continuation of a previous line
469
+ ll = ll + l[6:]
470
+ finalline = ''
471
+ origfinalline = ''
472
+ else:
473
+ r = cont1.match(l)
474
+ if r:
475
+ l = r.group('line') # Continuation follows ..
476
+ if cont:
477
+ ll = ll + cont2.match(l).group('line')
478
+ finalline = ''
479
+ origfinalline = ''
480
+ else:
481
+ # clean up line beginning from possible digits.
482
+ l = ' ' + l[5:]
483
+ # f2py directives are already stripped by this point
484
+ if localdolowercase:
485
+ finalline = ll.lower()
486
+ else:
487
+ finalline = ll
488
+ origfinalline = ll
489
+ ll = l
490
+
491
+ elif sourcecodeform == 'free':
492
+ if not cont and ext == '.pyf' and mline_mark.match(l):
493
+ l = l + '\n'
494
+ while True:
495
+ lc = fin.readline()
496
+ if not lc:
497
+ errmess(
498
+ 'Unexpected end of file when reading multiline\n')
499
+ break
500
+ l = l + lc
501
+ if mline_mark.match(lc):
502
+ break
503
+ l = l.rstrip()
504
+ r = cont1.match(l)
505
+ if r:
506
+ l = r.group('line') # Continuation follows ..
507
+ if cont:
508
+ ll = ll + cont2.match(l).group('line')
509
+ finalline = ''
510
+ origfinalline = ''
511
+ else:
512
+ if localdolowercase:
513
+ # only skip lowering for C style constructs
514
+ # gh-2547, gh-27697, gh-26681, gh-28014
515
+ finalline = ll.lower() if not (is_f2py_directive and iscstyledirective(ll)) else ll
516
+ else:
517
+ finalline = ll
518
+ origfinalline = ll
519
+ ll = l
520
+ cont = (r is not None)
521
+ else:
522
+ raise ValueError(
523
+ f"Flag sourcecodeform must be either 'fix' or 'free': {repr(sourcecodeform)}")
524
+ filepositiontext = (f'Line #{fin.filelineno() - 1} '
525
+ f'in {currentfilename}:"{l1}"\n\t')
526
+ m = includeline.match(origfinalline)
527
+ if m:
528
+ fn = m.group('name')
529
+ if os.path.isfile(fn):
530
+ readfortrancode(fn, dowithline=dowithline, istop=0)
531
+ else:
532
+ include_dirs = [
533
+ os.path.dirname(currentfilename)] + include_paths
534
+ foundfile = 0
535
+ for inc_dir in include_dirs:
536
+ fn1 = os.path.join(inc_dir, fn)
537
+ if os.path.isfile(fn1):
538
+ foundfile = 1
539
+ readfortrancode(fn1, dowithline=dowithline, istop=0)
540
+ break
541
+ if not foundfile:
542
+ outmess(f'readfortrancode: could not find include file {fn!r} '
543
+ f'in {os.pathsep.join(include_dirs)}. Ignoring.\n')
544
+ else:
545
+ dowithline(finalline)
546
+ l1 = ll
547
+ # Last line should never have an f2py directive anyway
548
+ if localdolowercase:
549
+ finalline = ll.lower()
550
+ else:
551
+ finalline = ll
552
+ origfinalline = ll
553
+ filepositiontext = f'Line #{fin.filelineno() - 1} in {currentfilename}:"{l1}"\n\t'
554
+ m = includeline.match(origfinalline)
555
+ if m:
556
+ fn = m.group('name')
557
+ if os.path.isfile(fn):
558
+ readfortrancode(fn, dowithline=dowithline, istop=0)
559
+ else:
560
+ include_dirs = [os.path.dirname(currentfilename)] + include_paths
561
+ foundfile = 0
562
+ for inc_dir in include_dirs:
563
+ fn1 = os.path.join(inc_dir, fn)
564
+ if os.path.isfile(fn1):
565
+ foundfile = 1
566
+ readfortrancode(fn1, dowithline=dowithline, istop=0)
567
+ break
568
+ if not foundfile:
569
+ outmess(f'readfortrancode: could not find include file {fn!r} '
570
+ f'in {os.pathsep.join(include_dirs)}. Ignoring.\n')
571
+ else:
572
+ dowithline(finalline)
573
+ filepositiontext = ''
574
+ fin.close()
575
+ if istop:
576
+ dowithline('', 1)
577
+ else:
578
+ gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\
579
+ beginpattern, quiet, verbose, dolowercase = saveglobals
580
+
581
+
582
+ # Crack line
583
+ beforethisafter = r'\s*(?P<before>%s(?=\s*(\b(%s)\b)))'\
584
+ r'\s*(?P<this>(\b(%s)\b))'\
585
+ r'\s*(?P<after>%s)\s*\Z'
586
+ ##
587
+ fortrantypes = r'character|logical|integer|real|complex|double\s*(precision\s*(complex|)|complex)|type(?=\s*\([\w\s,=(*)]*\))|byte'
588
+ typespattern = re.compile(
589
+ beforethisafter % ('', fortrantypes, fortrantypes, '.*'), re.I), 'type'
590
+ typespattern4implicit = re.compile(beforethisafter % (
591
+ '', fortrantypes + '|static|automatic|undefined', fortrantypes + '|static|automatic|undefined', '.*'), re.I)
592
+ #
593
+ functionpattern = re.compile(beforethisafter % (
594
+ r'([a-z]+[\w\s(=*+-/)]*?|)', 'function', 'function', '.*'), re.I), 'begin'
595
+ subroutinepattern = re.compile(beforethisafter % (
596
+ r'[a-z\s]*?', 'subroutine', 'subroutine', '.*'), re.I), 'begin'
597
+ # modulepattern=re.compile(beforethisafter%('[a-z\s]*?','module','module','.*'),re.I),'begin'
598
+ #
599
+ groupbegins77 = r'program|block\s*data'
600
+ beginpattern77 = re.compile(
601
+ beforethisafter % ('', groupbegins77, groupbegins77, '.*'), re.I), 'begin'
602
+ groupbegins90 = groupbegins77 + \
603
+ r'|module(?!\s*procedure)|python\s*module|(abstract|)\s*interface|'\
604
+ r'type(?!\s*\()'
605
+ beginpattern90 = re.compile(
606
+ beforethisafter % ('', groupbegins90, groupbegins90, '.*'), re.I), 'begin'
607
+ groupends = (r'end|endprogram|endblockdata|endmodule|endpythonmodule|'
608
+ r'endinterface|endsubroutine|endfunction')
609
+ endpattern = re.compile(
610
+ beforethisafter % ('', groupends, groupends, '.*'), re.I), 'end'
611
+ # block, the Fortran 2008 construct needs special handling in the rest of the file
612
+ endifs = r'end\s*(if|do|where|select|while|forall|associate|'\
613
+ r'critical|enum|team)'
614
+ endifpattern = re.compile(
615
+ beforethisafter % (r'[\w]*?', endifs, endifs, '.*'), re.I), 'endif'
616
+ #
617
+ moduleprocedures = r'module\s*procedure'
618
+ moduleprocedurepattern = re.compile(
619
+ beforethisafter % ('', moduleprocedures, moduleprocedures, '.*'), re.I), \
620
+ 'moduleprocedure'
621
+ implicitpattern = re.compile(
622
+ beforethisafter % ('', 'implicit', 'implicit', '.*'), re.I), 'implicit'
623
+ dimensionpattern = re.compile(beforethisafter % (
624
+ '', 'dimension|virtual', 'dimension|virtual', '.*'), re.I), 'dimension'
625
+ externalpattern = re.compile(
626
+ beforethisafter % ('', 'external', 'external', '.*'), re.I), 'external'
627
+ optionalpattern = re.compile(
628
+ beforethisafter % ('', 'optional', 'optional', '.*'), re.I), 'optional'
629
+ requiredpattern = re.compile(
630
+ beforethisafter % ('', 'required', 'required', '.*'), re.I), 'required'
631
+ publicpattern = re.compile(
632
+ beforethisafter % ('', 'public', 'public', '.*'), re.I), 'public'
633
+ privatepattern = re.compile(
634
+ beforethisafter % ('', 'private', 'private', '.*'), re.I), 'private'
635
+ intrinsicpattern = re.compile(
636
+ beforethisafter % ('', 'intrinsic', 'intrinsic', '.*'), re.I), 'intrinsic'
637
+ intentpattern = re.compile(beforethisafter % (
638
+ '', 'intent|depend|note|check', 'intent|depend|note|check', r'\s*\(.*?\).*'), re.I), 'intent'
639
+ parameterpattern = re.compile(
640
+ beforethisafter % ('', 'parameter', 'parameter', r'\s*\(.*'), re.I), 'parameter'
641
+ datapattern = re.compile(
642
+ beforethisafter % ('', 'data', 'data', '.*'), re.I), 'data'
643
+ callpattern = re.compile(
644
+ beforethisafter % ('', 'call', 'call', '.*'), re.I), 'call'
645
+ entrypattern = re.compile(
646
+ beforethisafter % ('', 'entry', 'entry', '.*'), re.I), 'entry'
647
+ callfunpattern = re.compile(
648
+ beforethisafter % ('', 'callfun', 'callfun', '.*'), re.I), 'callfun'
649
+ commonpattern = re.compile(
650
+ beforethisafter % ('', 'common', 'common', '.*'), re.I), 'common'
651
+ usepattern = re.compile(
652
+ beforethisafter % ('', 'use', 'use', '.*'), re.I), 'use'
653
+ containspattern = re.compile(
654
+ beforethisafter % ('', 'contains', 'contains', ''), re.I), 'contains'
655
+ formatpattern = re.compile(
656
+ beforethisafter % ('', 'format', 'format', '.*'), re.I), 'format'
657
+ # Non-fortran and f2py-specific statements
658
+ f2pyenhancementspattern = re.compile(beforethisafter % ('', 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef',
659
+ 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef', '.*'), re.I | re.S), 'f2pyenhancements'
660
+ multilinepattern = re.compile(
661
+ r"\s*(?P<before>''')(?P<this>.*?)(?P<after>''')\s*\Z", re.S), 'multiline'
662
+ ##
663
+
664
+ def split_by_unquoted(line, characters):
665
+ """
666
+ Splits the line into (line[:i], line[i:]),
667
+ where i is the index of first occurrence of one of the characters
668
+ not within quotes, or len(line) if no such index exists
669
+ """
670
+ assert not (set('"\'') & set(characters)), "cannot split by unquoted quotes"
671
+ r = re.compile(
672
+ r"\A(?P<before>({single_quoted}|{double_quoted}|{not_quoted})*)"
673
+ r"(?P<after>{char}.*)\Z".format(
674
+ not_quoted=f"[^\"'{re.escape(characters)}]",
675
+ char=f"[{re.escape(characters)}]",
676
+ single_quoted=r"('([^'\\]|(\\.))*')",
677
+ double_quoted=r'("([^"\\]|(\\.))*")'))
678
+ m = r.match(line)
679
+ if m:
680
+ d = m.groupdict()
681
+ return (d["before"], d["after"])
682
+ return (line, "")
683
+
684
+ def _simplifyargs(argsline):
685
+ a = []
686
+ for n in markoutercomma(argsline).split('@,@'):
687
+ for r in '(),':
688
+ n = n.replace(r, '_')
689
+ a.append(n)
690
+ return ','.join(a)
691
+
692
+
693
+ crackline_re_1 = re.compile(r'\s*(?P<result>\b[a-z]+\w*\b)\s*=.*', re.I)
694
+ crackline_bind_1 = re.compile(r'\s*(?P<bind>\b[a-z]+\w*\b)\s*=.*', re.I)
695
+ crackline_bindlang = re.compile(r'\s*bind\(\s*(?P<lang>[^,]+)\s*,\s*name\s*=\s*"(?P<lang_name>[^"]+)"\s*\)', re.I)
696
+
697
+ def crackline(line, reset=0):
698
+ """
699
+ reset=-1 --- initialize
700
+ reset=0 --- crack the line
701
+ reset=1 --- final check if mismatch of blocks occurred
702
+
703
+ Cracked data is saved in grouplist[0].
704
+ """
705
+ global beginpattern, groupcounter, groupname, groupcache, grouplist
706
+ global filepositiontext, currentfilename, neededmodule, expectbegin
707
+ global skipblocksuntil, skipemptyends, previous_context, gotnextfile
708
+
709
+ _, has_semicolon = split_by_unquoted(line, ";")
710
+ if has_semicolon and not (f2pyenhancementspattern[0].match(line) or
711
+ multilinepattern[0].match(line)):
712
+ # XXX: non-zero reset values need testing
713
+ assert reset == 0, repr(reset)
714
+ # split line on unquoted semicolons
715
+ line, semicolon_line = split_by_unquoted(line, ";")
716
+ while semicolon_line:
717
+ crackline(line, reset)
718
+ line, semicolon_line = split_by_unquoted(semicolon_line[1:], ";")
719
+ crackline(line, reset)
720
+ return
721
+ if reset < 0:
722
+ groupcounter = 0
723
+ groupname = {groupcounter: ''}
724
+ groupcache = {groupcounter: {}}
725
+ grouplist = {groupcounter: []}
726
+ groupcache[groupcounter]['body'] = []
727
+ groupcache[groupcounter]['vars'] = {}
728
+ groupcache[groupcounter]['block'] = ''
729
+ groupcache[groupcounter]['name'] = ''
730
+ neededmodule = -1
731
+ skipblocksuntil = -1
732
+ return
733
+ if reset > 0:
734
+ fl = 0
735
+ if f77modulename and neededmodule == groupcounter:
736
+ fl = 2
737
+ while groupcounter > fl:
738
+ outmess(f'crackline: groupcounter={groupcounter!r} groupname={groupname!r}\n')
739
+ outmess(
740
+ 'crackline: Mismatch of blocks encountered. Trying to fix it by assuming "end" statement.\n')
741
+ grouplist[groupcounter - 1].append(groupcache[groupcounter])
742
+ grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
743
+ del grouplist[groupcounter]
744
+ groupcounter = groupcounter - 1
745
+ if f77modulename and neededmodule == groupcounter:
746
+ grouplist[groupcounter - 1].append(groupcache[groupcounter])
747
+ grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
748
+ del grouplist[groupcounter]
749
+ groupcounter = groupcounter - 1 # end interface
750
+ grouplist[groupcounter - 1].append(groupcache[groupcounter])
751
+ grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
752
+ del grouplist[groupcounter]
753
+ groupcounter = groupcounter - 1 # end module
754
+ neededmodule = -1
755
+ return
756
+ if line == '':
757
+ return
758
+ flag = 0
759
+ for pat in [dimensionpattern, externalpattern, intentpattern, optionalpattern,
760
+ requiredpattern,
761
+ parameterpattern, datapattern, publicpattern, privatepattern,
762
+ intrinsicpattern,
763
+ endifpattern, endpattern,
764
+ formatpattern,
765
+ beginpattern, functionpattern, subroutinepattern,
766
+ implicitpattern, typespattern, commonpattern,
767
+ callpattern, usepattern, containspattern,
768
+ entrypattern,
769
+ f2pyenhancementspattern,
770
+ multilinepattern,
771
+ moduleprocedurepattern
772
+ ]:
773
+ m = pat[0].match(line)
774
+ if m:
775
+ break
776
+ flag = flag + 1
777
+ if not m:
778
+ re_1 = crackline_re_1
779
+ if 0 <= skipblocksuntil <= groupcounter:
780
+ return
781
+ if 'externals' in groupcache[groupcounter]:
782
+ for name in groupcache[groupcounter]['externals']:
783
+ if name in invbadnames:
784
+ name = invbadnames[name]
785
+ if 'interfaced' in groupcache[groupcounter] and name in groupcache[groupcounter]['interfaced']:
786
+ continue
787
+ m1 = re.match(
788
+ rf'(?P<before>[^"]*)\b{name}\b\s*@\(@(?P<args>[^@]*)@\)@.*\Z',
789
+ markouterparen(line), re.I)
790
+ if m1:
791
+ m2 = re_1.match(m1.group('before'))
792
+ a = _simplifyargs(m1.group('args'))
793
+ if m2:
794
+ line = f"callfun {name}({a}) result ({m2.group('result')})"
795
+ else:
796
+ line = f'callfun {name}({a})'
797
+ m = callfunpattern[0].match(line)
798
+ if not m:
799
+ outmess(
800
+ f'crackline: could not resolve function call for line={repr(line)}.\n')
801
+ return
802
+ analyzeline(m, 'callfun', line)
803
+ return
804
+ if verbose > 1 or (verbose == 1 and currentfilename.lower().endswith('.pyf')):
805
+ previous_context = None
806
+ outmess(f'crackline:{groupcounter}: No pattern for line\n')
807
+ return
808
+ elif pat[1] == 'end':
809
+ if 0 <= skipblocksuntil < groupcounter:
810
+ groupcounter = groupcounter - 1
811
+ if skipblocksuntil <= groupcounter:
812
+ return
813
+ if groupcounter <= 0:
814
+ raise Exception(f'crackline: groupcounter(={groupcounter}) is nonpositive. '
815
+ 'Check the blocks.')
816
+ m1 = beginpattern[0].match(line)
817
+ if (m1) and (not m1.group('this') == groupname[groupcounter]):
818
+ raise Exception(f'crackline: End group {m1.group("this")!r} '
819
+ 'does not match with previous Begin group '
820
+ f'{groupname[groupcounter]!r}\n\t{filepositiontext}')
821
+ if skipblocksuntil == groupcounter:
822
+ skipblocksuntil = -1
823
+ grouplist[groupcounter - 1].append(groupcache[groupcounter])
824
+ grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
825
+ del grouplist[groupcounter]
826
+ groupcounter = groupcounter - 1
827
+ if not skipemptyends:
828
+ expectbegin = 1
829
+ elif pat[1] == 'begin':
830
+ if 0 <= skipblocksuntil <= groupcounter:
831
+ groupcounter = groupcounter + 1
832
+ return
833
+ gotnextfile = 0
834
+ analyzeline(m, pat[1], line)
835
+ expectbegin = 0
836
+ elif pat[1] == 'endif':
837
+ pass
838
+ elif pat[1] == 'moduleprocedure':
839
+ analyzeline(m, pat[1], line)
840
+ elif pat[1] == 'contains':
841
+ if ignorecontains:
842
+ return
843
+ if 0 <= skipblocksuntil <= groupcounter:
844
+ return
845
+ skipblocksuntil = groupcounter
846
+ else:
847
+ if 0 <= skipblocksuntil <= groupcounter:
848
+ return
849
+ analyzeline(m, pat[1], line)
850
+
851
+
852
+ def markouterparen(line):
853
+ l = ''
854
+ f = 0
855
+ for c in line:
856
+ if c == '(':
857
+ f = f + 1
858
+ if f == 1:
859
+ l = l + '@(@'
860
+ continue
861
+ elif c == ')':
862
+ f = f - 1
863
+ if f == 0:
864
+ l = l + '@)@'
865
+ continue
866
+ l = l + c
867
+ return l
868
+
869
+
870
+ def markoutercomma(line, comma=','):
871
+ l = ''
872
+ f = 0
873
+ before, after = split_by_unquoted(line, comma + '()')
874
+ l += before
875
+ while after:
876
+ if (after[0] == comma) and (f == 0):
877
+ l += '@' + comma + '@'
878
+ else:
879
+ l += after[0]
880
+ if after[0] == '(':
881
+ f += 1
882
+ elif after[0] == ')':
883
+ f -= 1
884
+ before, after = split_by_unquoted(after[1:], comma + '()')
885
+ l += before
886
+ assert not f, repr((f, line, l))
887
+ return l
888
+
889
+ def unmarkouterparen(line):
890
+ r = line.replace('@(@', '(').replace('@)@', ')')
891
+ return r
892
+
893
+
894
+ def appenddecl(decl, decl2, force=1):
895
+ if not decl:
896
+ decl = {}
897
+ if not decl2:
898
+ return decl
899
+ if decl is decl2:
900
+ return decl
901
+ for k in list(decl2.keys()):
902
+ if k == 'typespec':
903
+ if force or k not in decl:
904
+ decl[k] = decl2[k]
905
+ elif k == 'attrspec':
906
+ for l in decl2[k]:
907
+ decl = setattrspec(decl, l, force)
908
+ elif k == 'kindselector':
909
+ decl = setkindselector(decl, decl2[k], force)
910
+ elif k == 'charselector':
911
+ decl = setcharselector(decl, decl2[k], force)
912
+ elif k in ['=', 'typename']:
913
+ if force or k not in decl:
914
+ decl[k] = decl2[k]
915
+ elif k == 'note':
916
+ pass
917
+ elif k in ['intent', 'check', 'dimension', 'optional',
918
+ 'required', 'depend']:
919
+ errmess(f'appenddecl: "{k}" not implemented.\n')
920
+ else:
921
+ raise Exception('appenddecl: Unknown variable definition key: ' +
922
+ str(k))
923
+ return decl
924
+
925
+
926
+ selectpattern = re.compile(
927
+ r'\s*(?P<this>(@\(@.*?@\)@|\*[\d*]+|\*\s*@\(@.*?@\)@|))(?P<after>.*)\Z', re.I)
928
+ typedefpattern = re.compile(
929
+ r'(?:,(?P<attributes>[\w(),]+))?(::)?(?P<name>\b[a-z$_][\w$]*\b)'
930
+ r'(?:\((?P<params>[\w,]*)\))?\Z', re.I)
931
+ nameargspattern = re.compile(
932
+ r'\s*(?P<name>\b[\w$]+\b)\s*(@\(@\s*(?P<args>[\w\s,]*)\s*@\)@|)\s*((result(\s*@\(@\s*(?P<result>\b[\w$]+\b)\s*@\)@|))|(bind\s*@\(@\s*(?P<bind>(?:(?!@\)@).)*)\s*@\)@))*\s*\Z', re.I)
933
+ operatorpattern = re.compile(
934
+ r'\s*(?P<scheme>(operator|assignment))'
935
+ r'@\(@\s*(?P<name>[^)]+)\s*@\)@\s*\Z', re.I)
936
+ callnameargspattern = re.compile(
937
+ r'\s*(?P<name>\b[\w$]+\b)\s*@\(@\s*(?P<args>.*)\s*@\)@\s*\Z', re.I)
938
+ real16pattern = re.compile(
939
+ r'([-+]?(?:\d+(?:\.\d*)?|\d*\.\d+))[dD]((?:[-+]?\d+)?)')
940
+ real8pattern = re.compile(
941
+ r'([-+]?((?:\d+(?:\.\d*)?|\d*\.\d+))[eE]((?:[-+]?\d+)?)|(\d+\.\d*))')
942
+
943
+ _intentcallbackpattern = re.compile(r'intent\s*\(.*?\bcallback\b', re.I)
944
+
945
+
946
+ def _is_intent_callback(vdecl):
947
+ for a in vdecl.get('attrspec', []):
948
+ if _intentcallbackpattern.match(a):
949
+ return 1
950
+ return 0
951
+
952
+
953
+ def _resolvetypedefpattern(line):
954
+ line = ''.join(line.split()) # removes whitespace
955
+ m1 = typedefpattern.match(line)
956
+ print(line, m1)
957
+ if m1:
958
+ attrs = m1.group('attributes')
959
+ attrs = [a.lower() for a in attrs.split(',')] if attrs else []
960
+ return m1.group('name'), attrs, m1.group('params')
961
+ return None, [], None
962
+
963
+ def parse_name_for_bind(line):
964
+ pattern = re.compile(r'bind\(\s*(?P<lang>[^,]+)(?:\s*,\s*name\s*=\s*["\'](?P<name>[^"\']+)["\']\s*)?\)', re.I)
965
+ match = pattern.search(line)
966
+ bind_statement = None
967
+ if match:
968
+ bind_statement = match.group(0)
969
+ # Remove the 'bind' construct from the line.
970
+ line = line[:match.start()] + line[match.end():]
971
+ return line, bind_statement
972
+
973
+ def _resolvenameargspattern(line):
974
+ line, bind_cname = parse_name_for_bind(line)
975
+ line = markouterparen(line)
976
+ m1 = nameargspattern.match(line)
977
+ if m1:
978
+ return m1.group('name'), m1.group('args'), m1.group('result'), bind_cname
979
+ m1 = operatorpattern.match(line)
980
+ if m1:
981
+ name = m1.group('scheme') + '(' + m1.group('name') + ')'
982
+ return name, [], None, None
983
+ m1 = callnameargspattern.match(line)
984
+ if m1:
985
+ return m1.group('name'), m1.group('args'), None, None
986
+ return None, [], None, None
987
+
988
+
989
+ def analyzeline(m, case, line):
990
+ """
991
+ Reads each line in the input file in sequence and updates global vars.
992
+
993
+ Effectively reads and collects information from the input file to the
994
+ global variable groupcache, a dictionary containing info about each part
995
+ of the fortran module.
996
+
997
+ At the end of analyzeline, information is filtered into the correct dict
998
+ keys, but parameter values and dimensions are not yet interpreted.
999
+ """
1000
+ global groupcounter, groupname, groupcache, grouplist, filepositiontext
1001
+ global currentfilename, f77modulename, neededinterface, neededmodule
1002
+ global expectbegin, gotnextfile, previous_context
1003
+
1004
+ block = m.group('this')
1005
+ if case != 'multiline':
1006
+ previous_context = None
1007
+ if expectbegin and case not in ['begin', 'call', 'callfun', 'type'] \
1008
+ and not skipemptyends and groupcounter < 1:
1009
+ newname = os.path.basename(currentfilename).split('.')[0]
1010
+ outmess(
1011
+ f'analyzeline: no group yet. Creating program group with name "{newname}".\n')
1012
+ gotnextfile = 0
1013
+ groupcounter = groupcounter + 1
1014
+ groupname[groupcounter] = 'program'
1015
+ groupcache[groupcounter] = {}
1016
+ grouplist[groupcounter] = []
1017
+ groupcache[groupcounter]['body'] = []
1018
+ groupcache[groupcounter]['vars'] = {}
1019
+ groupcache[groupcounter]['block'] = 'program'
1020
+ groupcache[groupcounter]['name'] = newname
1021
+ groupcache[groupcounter]['from'] = 'fromsky'
1022
+ expectbegin = 0
1023
+ if case in ['begin', 'call', 'callfun']:
1024
+ # Crack line => block,name,args,result
1025
+ block = block.lower()
1026
+ if re.match(r'block\s*data', block, re.I):
1027
+ block = 'block data'
1028
+ elif re.match(r'python\s*module', block, re.I):
1029
+ block = 'python module'
1030
+ elif re.match(r'abstract\s*interface', block, re.I):
1031
+ block = 'abstract interface'
1032
+ if block == 'type':
1033
+ name, attrs, _ = _resolvetypedefpattern(m.group('after'))
1034
+ groupcache[groupcounter]['vars'][name] = {'attrspec': attrs}
1035
+ args = []
1036
+ result = None
1037
+ else:
1038
+ name, args, result, bindcline = _resolvenameargspattern(m.group('after'))
1039
+ if name is None:
1040
+ if block == 'block data':
1041
+ name = '_BLOCK_DATA_'
1042
+ else:
1043
+ name = ''
1044
+ if block not in ['interface', 'block data', 'abstract interface']:
1045
+ outmess('analyzeline: No name/args pattern found for line.\n')
1046
+
1047
+ previous_context = (block, name, groupcounter)
1048
+ if args:
1049
+ args = rmbadname([x.strip()
1050
+ for x in markoutercomma(args).split('@,@')])
1051
+ else:
1052
+ args = []
1053
+ if '' in args:
1054
+ while '' in args:
1055
+ args.remove('')
1056
+ outmess(
1057
+ 'analyzeline: argument list is malformed (missing argument).\n')
1058
+
1059
+ # end of crack line => block,name,args,result
1060
+ needmodule = 0
1061
+ needinterface = 0
1062
+
1063
+ if case in ['call', 'callfun']:
1064
+ needinterface = 1
1065
+ if 'args' not in groupcache[groupcounter]:
1066
+ return
1067
+ if name not in groupcache[groupcounter]['args']:
1068
+ return
1069
+ for it in grouplist[groupcounter]:
1070
+ if it['name'] == name:
1071
+ return
1072
+ if name in groupcache[groupcounter]['interfaced']:
1073
+ return
1074
+ block = {'call': 'subroutine', 'callfun': 'function'}[case]
1075
+ if f77modulename and neededmodule == -1 and groupcounter <= 1:
1076
+ neededmodule = groupcounter + 2
1077
+ needmodule = 1
1078
+ if block not in ['interface', 'abstract interface']:
1079
+ needinterface = 1
1080
+ # Create new block(s)
1081
+ groupcounter = groupcounter + 1
1082
+ groupcache[groupcounter] = {}
1083
+ grouplist[groupcounter] = []
1084
+ if needmodule:
1085
+ if verbose > 1:
1086
+ outmess(f'analyzeline: Creating module block {f77modulename!r}\n', 0)
1087
+ groupname[groupcounter] = 'module'
1088
+ groupcache[groupcounter]['block'] = 'python module'
1089
+ groupcache[groupcounter]['name'] = f77modulename
1090
+ groupcache[groupcounter]['from'] = ''
1091
+ groupcache[groupcounter]['body'] = []
1092
+ groupcache[groupcounter]['externals'] = []
1093
+ groupcache[groupcounter]['interfaced'] = []
1094
+ groupcache[groupcounter]['vars'] = {}
1095
+ groupcounter = groupcounter + 1
1096
+ groupcache[groupcounter] = {}
1097
+ grouplist[groupcounter] = []
1098
+ if needinterface:
1099
+ if verbose > 1:
1100
+ outmess('analyzeline: Creating additional interface block '
1101
+ f'({groupcounter=}).\n', 0)
1102
+ groupname[groupcounter] = 'interface'
1103
+ groupcache[groupcounter]['block'] = 'interface'
1104
+ groupcache[groupcounter]['name'] = 'unknown_interface'
1105
+ prev_group = groupcache[groupcounter - 1]
1106
+ groupcache[groupcounter]['from'] = f"{prev_group['from']}:{prev_group['name']}"
1107
+ groupcache[groupcounter]['body'] = []
1108
+ groupcache[groupcounter]['externals'] = []
1109
+ groupcache[groupcounter]['interfaced'] = []
1110
+ groupcache[groupcounter]['vars'] = {}
1111
+ groupcounter = groupcounter + 1
1112
+ groupcache[groupcounter] = {}
1113
+ grouplist[groupcounter] = []
1114
+ groupname[groupcounter] = block
1115
+ groupcache[groupcounter]['block'] = block
1116
+ if not name:
1117
+ name = 'unknown_' + block.replace(' ', '_')
1118
+ groupcache[groupcounter]['prefix'] = m.group('before')
1119
+ groupcache[groupcounter]['name'] = rmbadname1(name)
1120
+ groupcache[groupcounter]['result'] = result
1121
+ if groupcounter == 1:
1122
+ groupcache[groupcounter]['from'] = currentfilename
1123
+ elif f77modulename and groupcounter == 3:
1124
+ groupcache[groupcounter]['from'] = f"{groupcache[groupcounter - 1]['from']}:{currentfilename}"
1125
+ else:
1126
+ prev_group = groupcache[groupcounter - 1]
1127
+ groupcache[groupcounter]['from'] = f"{prev_group['from']}:{prev_group['name']}"
1128
+ for k in list(groupcache[groupcounter].keys()):
1129
+ if not groupcache[groupcounter][k]:
1130
+ del groupcache[groupcounter][k]
1131
+
1132
+ groupcache[groupcounter]['args'] = args
1133
+ groupcache[groupcounter]['body'] = []
1134
+ groupcache[groupcounter]['externals'] = []
1135
+ groupcache[groupcounter]['interfaced'] = []
1136
+ groupcache[groupcounter]['vars'] = {}
1137
+ groupcache[groupcounter]['entry'] = {}
1138
+ # end of creation
1139
+ if block == 'type':
1140
+ groupcache[groupcounter]['varnames'] = []
1141
+
1142
+ if case in ['call', 'callfun']: # set parents variables
1143
+ if name not in groupcache[groupcounter - 2]['externals']:
1144
+ groupcache[groupcounter - 2]['externals'].append(name)
1145
+ groupcache[groupcounter]['vars'] = copy.deepcopy(
1146
+ groupcache[groupcounter - 2]['vars'])
1147
+ try:
1148
+ del groupcache[groupcounter]['vars'][name][
1149
+ groupcache[groupcounter]['vars'][name]['attrspec'].index('external')]
1150
+ except Exception:
1151
+ pass
1152
+ if block in ['function', 'subroutine']: # set global attributes
1153
+ # name is fortran name
1154
+ if bindcline:
1155
+ bindcdat = re.search(crackline_bindlang, bindcline)
1156
+ if bindcdat:
1157
+ groupcache[groupcounter]['bindlang'] = {name: {}}
1158
+ groupcache[groupcounter]['bindlang'][name]["lang"] = bindcdat.group('lang')
1159
+ if bindcdat.group('lang_name'):
1160
+ groupcache[groupcounter]['bindlang'][name]["name"] = bindcdat.group('lang_name')
1161
+ try:
1162
+ groupcache[groupcounter]['vars'][name] = appenddecl(
1163
+ groupcache[groupcounter]['vars'][name], groupcache[groupcounter - 2]['vars'][''])
1164
+ except Exception:
1165
+ pass
1166
+ if case == 'callfun': # return type
1167
+ if result and result in groupcache[groupcounter]['vars']:
1168
+ if not name == result:
1169
+ groupcache[groupcounter]['vars'][name] = appenddecl(
1170
+ groupcache[groupcounter]['vars'][name], groupcache[groupcounter]['vars'][result])
1171
+ # if groupcounter>1: # name is interfaced
1172
+ try:
1173
+ groupcache[groupcounter - 2]['interfaced'].append(name)
1174
+ except Exception:
1175
+ pass
1176
+ if block == 'function':
1177
+ t = typespattern[0].match(m.group('before') + ' ' + name)
1178
+ if t:
1179
+ typespec, selector, attr, edecl = cracktypespec0(
1180
+ t.group('this'), t.group('after'))
1181
+ updatevars(typespec, selector, attr, edecl)
1182
+
1183
+ if case in ['call', 'callfun']:
1184
+ grouplist[groupcounter - 1].append(groupcache[groupcounter])
1185
+ grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
1186
+ del grouplist[groupcounter]
1187
+ groupcounter = groupcounter - 1 # end routine
1188
+ grouplist[groupcounter - 1].append(groupcache[groupcounter])
1189
+ grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
1190
+ del grouplist[groupcounter]
1191
+ groupcounter = groupcounter - 1 # end interface
1192
+
1193
+ elif case == 'entry':
1194
+ name, args, result, _ = _resolvenameargspattern(m.group('after'))
1195
+ if name is not None:
1196
+ if args:
1197
+ args = rmbadname([x.strip()
1198
+ for x in markoutercomma(args).split('@,@')])
1199
+ else:
1200
+ args = []
1201
+ assert result is None, repr(result)
1202
+ groupcache[groupcounter]['entry'][name] = args
1203
+ previous_context = ('entry', name, groupcounter)
1204
+ elif case == 'type':
1205
+ typespec, selector, attr, edecl = cracktypespec0(
1206
+ block, m.group('after'))
1207
+ last_name = updatevars(typespec, selector, attr, edecl)
1208
+ if last_name is not None:
1209
+ previous_context = ('variable', last_name, groupcounter)
1210
+ elif case in ['dimension', 'intent', 'optional', 'required', 'external', 'public', 'private', 'intrinsic']:
1211
+ edecl = groupcache[groupcounter]['vars']
1212
+ ll = m.group('after').strip()
1213
+ i = ll.find('::')
1214
+ if i < 0 and case == 'intent':
1215
+ i = markouterparen(ll).find('@)@') - 2
1216
+ ll = ll[:i + 1] + '::' + ll[i + 1:]
1217
+ i = ll.find('::')
1218
+ if ll[i:] == '::' and 'args' in groupcache[groupcounter]:
1219
+ outmess('All arguments will have attribute '
1220
+ f'{m.group("this")}{ll[:i]}\n')
1221
+ ll = ll + ','.join(groupcache[groupcounter]['args'])
1222
+ if i < 0:
1223
+ i = 0
1224
+ pl = ''
1225
+ else:
1226
+ pl = ll[:i].strip()
1227
+ ll = ll[i + 2:]
1228
+ ch = markoutercomma(pl).split('@,@')
1229
+ if len(ch) > 1:
1230
+ pl = ch[0]
1231
+ outmess("analyzeline: cannot handle multiple attributes without "
1232
+ f"type specification. Ignoring {','.join(ch[1:])!r}.\n")
1233
+ last_name = None
1234
+
1235
+ for e in [x.strip() for x in markoutercomma(ll).split('@,@')]:
1236
+ m1 = namepattern.match(e)
1237
+ if not m1:
1238
+ if case in ['public', 'private']:
1239
+ k = ''
1240
+ else:
1241
+ print(m.groupdict())
1242
+ outmess(f'analyzeline: no name pattern found in {case} statement '
1243
+ f'for {e!r}. Skipping.\n')
1244
+ continue
1245
+ else:
1246
+ k = rmbadname1(m1.group('name'))
1247
+ if case in ['public', 'private'] and k in {'operator', 'assignment'}:
1248
+ k += m1.group('after')
1249
+ if k not in edecl:
1250
+ edecl[k] = {}
1251
+ if case == 'dimension':
1252
+ ap = case + m1.group('after')
1253
+ if case == 'intent':
1254
+ ap = m.group('this') + pl
1255
+ if _intentcallbackpattern.match(ap):
1256
+ if k not in groupcache[groupcounter]['args']:
1257
+ if groupcounter > 1:
1258
+ if '__user__' not in groupcache[groupcounter - 2]['name']:
1259
+ outmess(
1260
+ 'analyzeline: missing __user__ module (could be nothing)\n')
1261
+ # fixes ticket 1693
1262
+ if k != groupcache[groupcounter]['name']:
1263
+ outmess(f"analyzeline: appending intent(callback) {k}"
1264
+ f" to {groupcache[groupcounter]['name']} "
1265
+ "arguments\n")
1266
+ groupcache[groupcounter]['args'].append(k)
1267
+ else:
1268
+ errmess(
1269
+ f'analyzeline: intent(callback) {k} is ignored\n')
1270
+ else:
1271
+ errmess(f'analyzeline: intent(callback) {k} is already'
1272
+ ' in argument list\n')
1273
+ if case in ['optional', 'required', 'public', 'external', 'private', 'intrinsic']:
1274
+ ap = case
1275
+ if 'attrspec' in edecl[k]:
1276
+ edecl[k]['attrspec'].append(ap)
1277
+ else:
1278
+ edecl[k]['attrspec'] = [ap]
1279
+ if case == 'external':
1280
+ if groupcache[groupcounter]['block'] == 'program':
1281
+ outmess('analyzeline: ignoring program arguments\n')
1282
+ continue
1283
+ if k not in groupcache[groupcounter]['args']:
1284
+ continue
1285
+ if 'externals' not in groupcache[groupcounter]:
1286
+ groupcache[groupcounter]['externals'] = []
1287
+ groupcache[groupcounter]['externals'].append(k)
1288
+ last_name = k
1289
+ groupcache[groupcounter]['vars'] = edecl
1290
+ if last_name is not None:
1291
+ previous_context = ('variable', last_name, groupcounter)
1292
+ elif case == 'moduleprocedure':
1293
+ groupcache[groupcounter]['implementedby'] = \
1294
+ [x.strip() for x in m.group('after').split(',')]
1295
+ elif case == 'parameter':
1296
+ edecl = groupcache[groupcounter]['vars']
1297
+ ll = m.group('after').strip()[1:-1]
1298
+ last_name = None
1299
+ for e in markoutercomma(ll).split('@,@'):
1300
+ try:
1301
+ k, initexpr = [x.strip() for x in e.split('=')]
1302
+ except Exception:
1303
+ outmess(
1304
+ f'analyzeline: could not extract name,expr in parameter statement "{e}" of "{ll}\"\n')
1305
+ continue
1306
+ params = get_parameters(edecl)
1307
+ k = rmbadname1(k)
1308
+ if k not in edecl:
1309
+ edecl[k] = {}
1310
+ if '=' in edecl[k] and (not edecl[k]['='] == initexpr):
1311
+ outmess(f'analyzeline: Overwriting the value of parameter "{k}" '
1312
+ f'("{edecl[k]["="]}") with "{initexpr}".\n')
1313
+ t = determineexprtype(initexpr, params)
1314
+ if t:
1315
+ if t.get('typespec') == 'real':
1316
+ tt = list(initexpr)
1317
+ for m in real16pattern.finditer(initexpr):
1318
+ tt[m.start():m.end()] = list(
1319
+ initexpr[m.start():m.end()].lower().replace('d', 'e'))
1320
+ initexpr = ''.join(tt)
1321
+ elif t.get('typespec') == 'complex':
1322
+ initexpr = initexpr[1:].lower().replace('d', 'e').\
1323
+ replace(',', '+1j*(')
1324
+ try:
1325
+ v = eval(initexpr, {}, params)
1326
+ except (SyntaxError, NameError, TypeError) as msg:
1327
+ errmess(f'analyzeline: Failed to evaluate {initexpr!r}. '
1328
+ f'Ignoring: {msg}\n')
1329
+ continue
1330
+ edecl[k]['='] = repr(v)
1331
+ if 'attrspec' in edecl[k]:
1332
+ edecl[k]['attrspec'].append('parameter')
1333
+ else:
1334
+ edecl[k]['attrspec'] = ['parameter']
1335
+ last_name = k
1336
+ groupcache[groupcounter]['vars'] = edecl
1337
+ if last_name is not None:
1338
+ previous_context = ('variable', last_name, groupcounter)
1339
+ elif case == 'implicit':
1340
+ if m.group('after').strip().lower() == 'none':
1341
+ groupcache[groupcounter]['implicit'] = None
1342
+ elif m.group('after'):
1343
+ impl = groupcache[groupcounter].get('implicit', {})
1344
+ if impl is None:
1345
+ outmess(
1346
+ 'analyzeline: Overwriting earlier "implicit none" statement.\n')
1347
+ impl = {}
1348
+ for e in markoutercomma(m.group('after')).split('@,@'):
1349
+ decl = {}
1350
+ m1 = re.match(
1351
+ r'\s*(?P<this>.*?)\s*(\(\s*(?P<after>[a-z-, ]+)\s*\)\s*|)\Z', e, re.I)
1352
+ if not m1:
1353
+ outmess(
1354
+ f'analyzeline: could not extract info of implicit statement part "{e}\"\n')
1355
+ continue
1356
+ m2 = typespattern4implicit.match(m1.group('this'))
1357
+ if not m2:
1358
+ outmess(
1359
+ f'analyzeline: could not extract types pattern of implicit statement part "{e}\"\n')
1360
+ continue
1361
+ typespec, selector, attr, edecl = cracktypespec0(
1362
+ m2.group('this'), m2.group('after'))
1363
+ kindselect, charselect, typename = cracktypespec(
1364
+ typespec, selector)
1365
+ decl['typespec'] = typespec
1366
+ decl['kindselector'] = kindselect
1367
+ decl['charselector'] = charselect
1368
+ decl['typename'] = typename
1369
+ for k in list(decl.keys()):
1370
+ if not decl[k]:
1371
+ del decl[k]
1372
+ for r in markoutercomma(m1.group('after')).split('@,@'):
1373
+ if '-' in r:
1374
+ try:
1375
+ begc, endc = [x.strip() for x in r.split('-')]
1376
+ except Exception:
1377
+ outmess(
1378
+ f'analyzeline: expected "<char>-<char>" instead of "{r}" in range list of implicit statement\n')
1379
+ continue
1380
+ else:
1381
+ begc = endc = r.strip()
1382
+ if not len(begc) == len(endc) == 1:
1383
+ outmess(
1384
+ f'analyzeline: expected "<char>-<char>" instead of "{r}" in range list of implicit statement (2)\n')
1385
+ continue
1386
+ for o in range(ord(begc), ord(endc) + 1):
1387
+ impl[chr(o)] = decl
1388
+ groupcache[groupcounter]['implicit'] = impl
1389
+ elif case == 'data':
1390
+ ll = []
1391
+ dl = ''
1392
+ il = ''
1393
+ f = 0
1394
+ fc = 1
1395
+ inp = 0
1396
+ for c in m.group('after'):
1397
+ if not inp:
1398
+ if c == "'":
1399
+ fc = not fc
1400
+ if c == '/' and fc:
1401
+ f = f + 1
1402
+ continue
1403
+ if c == '(':
1404
+ inp = inp + 1
1405
+ elif c == ')':
1406
+ inp = inp - 1
1407
+ if f == 0:
1408
+ dl = dl + c
1409
+ elif f == 1:
1410
+ il = il + c
1411
+ elif f == 2:
1412
+ dl = dl.strip()
1413
+ if dl.startswith(','):
1414
+ dl = dl[1:].strip()
1415
+ ll.append([dl, il])
1416
+ dl = c
1417
+ il = ''
1418
+ f = 0
1419
+ if f == 2:
1420
+ dl = dl.strip()
1421
+ if dl.startswith(','):
1422
+ dl = dl[1:].strip()
1423
+ ll.append([dl, il])
1424
+ vars = groupcache[groupcounter].get('vars', {})
1425
+ last_name = None
1426
+ for l in ll:
1427
+ l[0], l[1] = l[0].strip().removeprefix(','), l[1].strip()
1428
+ if l[0].startswith('('):
1429
+ outmess(f'analyzeline: implied-DO list "{l[0]}" is not supported. Skipping.\n')
1430
+ continue
1431
+ for idx, v in enumerate(rmbadname([x.strip() for x in markoutercomma(l[0]).split('@,@')])):
1432
+ if v.startswith('('):
1433
+ outmess(f'analyzeline: implied-DO list "{v}" is not supported. Skipping.\n')
1434
+ # XXX: subsequent init expressions may get wrong values.
1435
+ # Ignoring since data statements are irrelevant for
1436
+ # wrapping.
1437
+ continue
1438
+ if '!' in l[1]:
1439
+ # Fixes gh-24746 pyf generation
1440
+ # XXX: This essentially ignores the value for generating the pyf which is fine:
1441
+ # integer dimension(3) :: mytab
1442
+ # common /mycom/ mytab
1443
+ # Since in any case it is initialized in the Fortran code
1444
+ outmess(f'Comment line in declaration "{l[1]}" is not supported. Skipping.\n')
1445
+ continue
1446
+ vars.setdefault(v, {})
1447
+ vtype = vars[v].get('typespec')
1448
+ vdim = getdimension(vars[v])
1449
+ matches = re.findall(r"\(.*?\)", l[1]) if vtype == 'complex' else l[1].split(',')
1450
+ try:
1451
+ new_val = f"(/{', '.join(matches)}/)" if vdim else matches[idx]
1452
+ except IndexError:
1453
+ # gh-24746
1454
+ # Runs only if above code fails. Fixes the line
1455
+ # DATA IVAR1, IVAR2, IVAR3, IVAR4, EVAR5 /4*0,0.0D0/
1456
+ # by expanding to ['0', '0', '0', '0', '0.0d0']
1457
+ if any("*" in m for m in matches):
1458
+ expanded_list = []
1459
+ for match in matches:
1460
+ if "*" in match:
1461
+ try:
1462
+ multiplier, value = match.split("*")
1463
+ expanded_list.extend([value.strip()] * int(multiplier))
1464
+ except ValueError: # if int(multiplier) fails
1465
+ expanded_list.append(match.strip())
1466
+ else:
1467
+ expanded_list.append(match.strip())
1468
+ matches = expanded_list
1469
+ new_val = f"(/{', '.join(matches)}/)" if vdim else matches[idx]
1470
+ current_val = vars[v].get('=')
1471
+ if current_val and (current_val != new_val):
1472
+ outmess(f'analyzeline: changing init expression of "{v}" ("{current_val}") to "{new_val}\"\n')
1473
+ vars[v]['='] = new_val
1474
+ last_name = v
1475
+ groupcache[groupcounter]['vars'] = vars
1476
+ if last_name:
1477
+ previous_context = ('variable', last_name, groupcounter)
1478
+ elif case == 'common':
1479
+ line = m.group('after').strip()
1480
+ if not line[0] == '/':
1481
+ line = '//' + line
1482
+
1483
+ cl = []
1484
+ [_, bn, ol] = re.split('/', line, maxsplit=2)
1485
+ bn = bn.strip()
1486
+ if not bn:
1487
+ bn = '_BLNK_'
1488
+ cl.append([bn, ol])
1489
+ commonkey = {}
1490
+ if 'common' in groupcache[groupcounter]:
1491
+ commonkey = groupcache[groupcounter]['common']
1492
+ for c in cl:
1493
+ if c[0] not in commonkey:
1494
+ commonkey[c[0]] = []
1495
+ for i in [x.strip() for x in markoutercomma(c[1]).split('@,@')]:
1496
+ if i:
1497
+ commonkey[c[0]].append(i)
1498
+ groupcache[groupcounter]['common'] = commonkey
1499
+ previous_context = ('common', bn, groupcounter)
1500
+ elif case == 'use':
1501
+ m1 = re.match(
1502
+ r'\A\s*(?P<name>\b\w+\b)\s*((,(\s*\bonly\b\s*:|(?P<notonly>))\s*(?P<list>.*))|)\s*\Z', m.group('after'), re.I)
1503
+ if m1:
1504
+ mm = m1.groupdict()
1505
+ if 'use' not in groupcache[groupcounter]:
1506
+ groupcache[groupcounter]['use'] = {}
1507
+ name = m1.group('name')
1508
+ groupcache[groupcounter]['use'][name] = {}
1509
+ isonly = 0
1510
+ if 'list' in mm and mm['list'] is not None:
1511
+ if 'notonly' in mm and mm['notonly'] is None:
1512
+ isonly = 1
1513
+ groupcache[groupcounter]['use'][name]['only'] = isonly
1514
+ ll = [x.strip() for x in mm['list'].split(',')]
1515
+ rl = {}
1516
+ for l in ll:
1517
+ if '=' in l:
1518
+ m2 = re.match(
1519
+ r'\A\s*(?P<local>\b\w+\b)\s*=\s*>\s*(?P<use>\b\w+\b)\s*\Z', l, re.I)
1520
+ if m2:
1521
+ rl[m2.group('local').strip()] = m2.group(
1522
+ 'use').strip()
1523
+ else:
1524
+ outmess(
1525
+ f'analyzeline: Not local=>use pattern found in {repr(l)}\n')
1526
+ else:
1527
+ rl[l] = l
1528
+ groupcache[groupcounter]['use'][name]['map'] = rl
1529
+ else:
1530
+ print(m.groupdict())
1531
+ outmess('analyzeline: Could not crack the use statement.\n')
1532
+ elif case in ['f2pyenhancements']:
1533
+ if 'f2pyenhancements' not in groupcache[groupcounter]:
1534
+ groupcache[groupcounter]['f2pyenhancements'] = {}
1535
+ d = groupcache[groupcounter]['f2pyenhancements']
1536
+ if m.group('this') == 'usercode' and 'usercode' in d:
1537
+ if isinstance(d['usercode'], str):
1538
+ d['usercode'] = [d['usercode']]
1539
+ d['usercode'].append(m.group('after'))
1540
+ else:
1541
+ d[m.group('this')] = m.group('after')
1542
+ elif case == 'multiline':
1543
+ if previous_context is None:
1544
+ if verbose:
1545
+ outmess('analyzeline: No context for multiline block.\n')
1546
+ return
1547
+ gc = groupcounter
1548
+ appendmultiline(groupcache[gc],
1549
+ previous_context[:2],
1550
+ m.group('this'))
1551
+ elif verbose > 1:
1552
+ print(m.groupdict())
1553
+ outmess('analyzeline: No code implemented for line.\n')
1554
+
1555
+
1556
+ def appendmultiline(group, context_name, ml):
1557
+ if 'f2pymultilines' not in group:
1558
+ group['f2pymultilines'] = {}
1559
+ d = group['f2pymultilines']
1560
+ if context_name not in d:
1561
+ d[context_name] = []
1562
+ d[context_name].append(ml)
1563
+
1564
+
1565
+ def cracktypespec0(typespec, ll):
1566
+ selector = None
1567
+ attr = None
1568
+ if re.match(r'double\s*complex', typespec, re.I):
1569
+ typespec = 'double complex'
1570
+ elif re.match(r'double\s*precision', typespec, re.I):
1571
+ typespec = 'double precision'
1572
+ else:
1573
+ typespec = typespec.strip().lower()
1574
+ m1 = selectpattern.match(markouterparen(ll))
1575
+ if not m1:
1576
+ outmess(
1577
+ 'cracktypespec0: no kind/char_selector pattern found for line.\n')
1578
+ return
1579
+ d = m1.groupdict()
1580
+ for k in list(d.keys()):
1581
+ d[k] = unmarkouterparen(d[k])
1582
+ if typespec in ['complex', 'integer', 'logical', 'real', 'character', 'type']:
1583
+ selector = d['this']
1584
+ ll = d['after']
1585
+ i = ll.find('::')
1586
+ if i >= 0:
1587
+ attr = ll[:i].strip()
1588
+ ll = ll[i + 2:]
1589
+ return typespec, selector, attr, ll
1590
+
1591
+
1592
+ #####
1593
+ namepattern = re.compile(r'\s*(?P<name>\b\w+\b)\s*(?P<after>.*)\s*\Z', re.I)
1594
+ kindselector = re.compile(
1595
+ r'\s*(\(\s*(kind\s*=)?\s*(?P<kind>.*)\s*\)|\*\s*(?P<kind2>.*?))\s*\Z', re.I)
1596
+ charselector = re.compile(
1597
+ r'\s*(\((?P<lenkind>.*)\)|\*\s*(?P<charlen>.*))\s*\Z', re.I)
1598
+ lenkindpattern = re.compile(
1599
+ r'\s*(kind\s*=\s*(?P<kind>.*?)\s*(@,@\s*len\s*=\s*(?P<len>.*)|)'
1600
+ r'|(len\s*=\s*|)(?P<len2>.*?)\s*(@,@\s*(kind\s*=\s*|)(?P<kind2>.*)'
1601
+ r'|(f2py_len\s*=\s*(?P<f2py_len>.*))|))\s*\Z', re.I)
1602
+ lenarraypattern = re.compile(
1603
+ r'\s*(@\(@\s*(?!/)\s*(?P<array>.*?)\s*@\)@\s*\*\s*(?P<len>.*?)|(\*\s*(?P<len2>.*?)|)\s*(@\(@\s*(?!/)\s*(?P<array2>.*?)\s*@\)@|))\s*(=\s*(?P<init>.*?)|(@\(@|)/\s*(?P<init2>.*?)\s*/(@\)@|)|)\s*\Z', re.I)
1604
+
1605
+
1606
+ def removespaces(expr):
1607
+ expr = expr.strip()
1608
+ if len(expr) <= 1:
1609
+ return expr
1610
+ expr2 = expr[0]
1611
+ for i in range(1, len(expr) - 1):
1612
+ if (expr[i] == ' ' and
1613
+ ((expr[i + 1] in "()[]{}=+-/* ") or
1614
+ (expr[i - 1] in "()[]{}=+-/* "))):
1615
+ continue
1616
+ expr2 = expr2 + expr[i]
1617
+ expr2 = expr2 + expr[-1]
1618
+ return expr2
1619
+
1620
+
1621
+ def markinnerspaces(line):
1622
+ """
1623
+ The function replace all spaces in the input variable line which are
1624
+ surrounded with quotation marks, with the triplet "@_@".
1625
+
1626
+ For instance, for the input "a 'b c'" the function returns "a 'b@_@c'"
1627
+
1628
+ Parameters
1629
+ ----------
1630
+ line : str
1631
+
1632
+ Returns
1633
+ -------
1634
+ str
1635
+
1636
+ """
1637
+ fragment = ''
1638
+ inside = False
1639
+ current_quote = None
1640
+ escaped = ''
1641
+ for c in line:
1642
+ if escaped == '\\' and c in ['\\', '\'', '"']:
1643
+ fragment += c
1644
+ escaped = c
1645
+ continue
1646
+ if not inside and c in ['\'', '"']:
1647
+ current_quote = c
1648
+ if c == current_quote:
1649
+ inside = not inside
1650
+ elif c == ' ' and inside:
1651
+ fragment += '@_@'
1652
+ continue
1653
+ fragment += c
1654
+ escaped = c # reset to non-backslash
1655
+ return fragment
1656
+
1657
+
1658
+ def updatevars(typespec, selector, attrspec, entitydecl):
1659
+ """
1660
+ Returns last_name, the variable name without special chars, parenthesis
1661
+ or dimension specifiers.
1662
+
1663
+ Alters groupcache to add the name, typespec, attrspec (and possibly value)
1664
+ of current variable.
1665
+ """
1666
+ global groupcache, groupcounter
1667
+
1668
+ last_name = None
1669
+ kindselect, charselect, typename = cracktypespec(typespec, selector)
1670
+ # Clean up outer commas, whitespace and undesired chars from attrspec
1671
+ if attrspec:
1672
+ attrspec = [x.strip() for x in markoutercomma(attrspec).split('@,@')]
1673
+ l = []
1674
+ c = re.compile(r'(?P<start>[a-zA-Z]+)')
1675
+ for a in attrspec:
1676
+ if not a:
1677
+ continue
1678
+ m = c.match(a)
1679
+ if m:
1680
+ s = m.group('start').lower()
1681
+ a = s + a[len(s):]
1682
+ l.append(a)
1683
+ attrspec = l
1684
+ el = [x.strip() for x in markoutercomma(entitydecl).split('@,@')]
1685
+ el1 = []
1686
+ for e in el:
1687
+ for e1 in [x.strip() for x in markoutercomma(removespaces(markinnerspaces(e)), comma=' ').split('@ @')]:
1688
+ if e1:
1689
+ el1.append(e1.replace('@_@', ' '))
1690
+ for e in el1:
1691
+ m = namepattern.match(e)
1692
+ if not m:
1693
+ outmess(
1694
+ f'updatevars: no name pattern found for entity={repr(e)}. Skipping.\n')
1695
+ continue
1696
+ ename = rmbadname1(m.group('name'))
1697
+ edecl = {}
1698
+ if ename in groupcache[groupcounter]['vars']:
1699
+ edecl = groupcache[groupcounter]['vars'][ename].copy()
1700
+ not_has_typespec = 'typespec' not in edecl
1701
+ if not_has_typespec:
1702
+ edecl['typespec'] = typespec
1703
+ elif typespec and (not typespec == edecl['typespec']):
1704
+ current_typespec = edecl['typespec']
1705
+ outmess(f'updatevars: attempt to change the type of "{ename}" '
1706
+ f'("{current_typespec}") to "{typespec}". Ignoring.\n')
1707
+ if 'kindselector' not in edecl:
1708
+ edecl['kindselector'] = copy.copy(kindselect)
1709
+ elif kindselect:
1710
+ for k in list(kindselect.keys()):
1711
+ if k in edecl['kindselector'] and (not kindselect[k] == edecl['kindselector'][k]):
1712
+ current_kind = edecl['kindselector'][k]
1713
+ outmess('updatevars: attempt to change the kindselector '
1714
+ f'"{k}" of "{ename}" ("{current_kind}") to '
1715
+ f'"{kindselect[k]}". Ignoring.\n')
1716
+ else:
1717
+ edecl['kindselector'][k] = copy.copy(kindselect[k])
1718
+ if 'charselector' not in edecl and charselect:
1719
+ if not_has_typespec:
1720
+ edecl['charselector'] = charselect
1721
+ else:
1722
+ errmess(f'updatevars:{ename}: attempt to change empty charselector '
1723
+ f'to {charselect!r}. Ignoring.\n')
1724
+ elif charselect:
1725
+ for k in list(charselect.keys()):
1726
+ if k in edecl['charselector'] and (not charselect[k] == edecl['charselector'][k]):
1727
+ outmess(f'updatevars: attempt to change the charselector "{k}" '
1728
+ f'of "{ename}" ("{edecl["charselector"][k]}") to '
1729
+ f'"{charselect[k]}". Ignoring.\n')
1730
+ else:
1731
+ edecl['charselector'][k] = copy.copy(charselect[k])
1732
+ if 'typename' not in edecl:
1733
+ edecl['typename'] = typename
1734
+ elif typename and (not edecl['typename'] == typename):
1735
+ outmess(f'updatevars: attempt to change the typename of "{ename}" '
1736
+ f'("{edecl["typename"]}") to "{typename}". Ignoring.\n')
1737
+ if 'attrspec' not in edecl:
1738
+ edecl['attrspec'] = copy.copy(attrspec)
1739
+ elif attrspec:
1740
+ for a in attrspec:
1741
+ if a not in edecl['attrspec']:
1742
+ edecl['attrspec'].append(a)
1743
+ else:
1744
+ edecl['typespec'] = copy.copy(typespec)
1745
+ edecl['kindselector'] = copy.copy(kindselect)
1746
+ edecl['charselector'] = copy.copy(charselect)
1747
+ edecl['typename'] = typename
1748
+ edecl['attrspec'] = copy.copy(attrspec)
1749
+ if 'external' in (edecl.get('attrspec') or []) and e in groupcache[groupcounter]['args']:
1750
+ if 'externals' not in groupcache[groupcounter]:
1751
+ groupcache[groupcounter]['externals'] = []
1752
+ groupcache[groupcounter]['externals'].append(e)
1753
+ if m.group('after'):
1754
+ m1 = lenarraypattern.match(markouterparen(m.group('after')))
1755
+ if m1:
1756
+ d1 = m1.groupdict()
1757
+ for lk in ['len', 'array', 'init']:
1758
+ if d1[lk + '2'] is not None:
1759
+ d1[lk] = d1[lk + '2']
1760
+ del d1[lk + '2']
1761
+ for k in list(d1.keys()):
1762
+ if d1[k] is not None:
1763
+ d1[k] = unmarkouterparen(d1[k])
1764
+ else:
1765
+ del d1[k]
1766
+
1767
+ if 'len' in d1 and 'array' in d1:
1768
+ if d1['len'] == '':
1769
+ d1['len'] = d1['array']
1770
+ del d1['array']
1771
+ elif typespec == 'character':
1772
+ if ('charselector' not in edecl) or (not edecl['charselector']):
1773
+ edecl['charselector'] = {}
1774
+ if 'len' in edecl['charselector']:
1775
+ del edecl['charselector']['len']
1776
+ edecl['charselector']['*'] = d1['len']
1777
+ del d1['len']
1778
+ else:
1779
+ d1['array'] = d1['array'] + ',' + d1['len']
1780
+ del d1['len']
1781
+ array_spec = d1['array']
1782
+ errmess(f'updatevars: "{typespec} {e}" is mapped to '
1783
+ f'"{typespec} {ename}({array_spec})"\n')
1784
+
1785
+ if 'len' in d1:
1786
+ if typespec in ['complex', 'integer', 'logical', 'real']:
1787
+ if ('kindselector' not in edecl) or (not edecl['kindselector']):
1788
+ edecl['kindselector'] = {}
1789
+ edecl['kindselector']['*'] = d1['len']
1790
+ del d1['len']
1791
+ elif typespec == 'character':
1792
+ if ('charselector' not in edecl) or (not edecl['charselector']):
1793
+ edecl['charselector'] = {}
1794
+ if 'len' in edecl['charselector']:
1795
+ del edecl['charselector']['len']
1796
+ edecl['charselector']['*'] = d1['len']
1797
+ del d1['len']
1798
+
1799
+ if 'init' in d1:
1800
+ if '=' in edecl and (not edecl['='] == d1['init']):
1801
+ current_init = edecl['=']
1802
+ new_init = d1['init']
1803
+ outmess('updatevars: attempt to change the init expression of '
1804
+ f'"{ename}" ("{current_init}") to "{new_init}". '
1805
+ f'Ignoring.\n')
1806
+ else:
1807
+ edecl['='] = d1['init']
1808
+
1809
+ if 'array' in d1:
1810
+ dm = f"dimension({d1['array']})"
1811
+ if 'attrspec' not in edecl or (not edecl['attrspec']):
1812
+ edecl['attrspec'] = [dm]
1813
+ else:
1814
+ edecl['attrspec'].append(dm)
1815
+ for dm1 in edecl['attrspec']:
1816
+ if dm1[:9] == 'dimension' and dm1 != dm:
1817
+ del edecl['attrspec'][-1]
1818
+ errmess(f'updatevars:{ename}: attempt to change '
1819
+ f'{dm1!r} to {dm!r}. Ignoring.\n')
1820
+ break
1821
+
1822
+ else:
1823
+ outmess('updatevars: could not crack entity declaration "%s". Ignoring.\n' % (
1824
+ ename + m.group('after')))
1825
+ for k in list(edecl.keys()):
1826
+ if not edecl[k]:
1827
+ del edecl[k]
1828
+ groupcache[groupcounter]['vars'][ename] = edecl
1829
+ if 'varnames' in groupcache[groupcounter]:
1830
+ groupcache[groupcounter]['varnames'].append(ename)
1831
+ last_name = ename
1832
+ return last_name
1833
+
1834
+
1835
+ def cracktypespec(typespec, selector):
1836
+ kindselect = None
1837
+ charselect = None
1838
+ typename = None
1839
+ if selector:
1840
+ if typespec in ['complex', 'integer', 'logical', 'real']:
1841
+ kindselect = kindselector.match(selector)
1842
+ if not kindselect:
1843
+ outmess(
1844
+ f'cracktypespec: no kindselector pattern found for {repr(selector)}\n')
1845
+ return
1846
+ kindselect = kindselect.groupdict()
1847
+ kindselect['*'] = kindselect['kind2']
1848
+ del kindselect['kind2']
1849
+ for k in list(kindselect.keys()):
1850
+ if not kindselect[k]:
1851
+ del kindselect[k]
1852
+ for k, i in list(kindselect.items()):
1853
+ kindselect[k] = rmbadname1(i)
1854
+ elif typespec == 'character':
1855
+ charselect = charselector.match(selector)
1856
+ if not charselect:
1857
+ outmess(
1858
+ f'cracktypespec: no charselector pattern found for {repr(selector)}\n')
1859
+ return
1860
+ charselect = charselect.groupdict()
1861
+ charselect['*'] = charselect['charlen']
1862
+ del charselect['charlen']
1863
+ if charselect['lenkind']:
1864
+ lenkind = lenkindpattern.match(
1865
+ markoutercomma(charselect['lenkind']))
1866
+ lenkind = lenkind.groupdict()
1867
+ for lk in ['len', 'kind']:
1868
+ if lenkind[lk + '2']:
1869
+ lenkind[lk] = lenkind[lk + '2']
1870
+ charselect[lk] = lenkind[lk]
1871
+ del lenkind[lk + '2']
1872
+ if lenkind['f2py_len'] is not None:
1873
+ # used to specify the length of assumed length strings
1874
+ charselect['f2py_len'] = lenkind['f2py_len']
1875
+ del charselect['lenkind']
1876
+ for k in list(charselect.keys()):
1877
+ if not charselect[k]:
1878
+ del charselect[k]
1879
+ for k, i in list(charselect.items()):
1880
+ charselect[k] = rmbadname1(i)
1881
+ elif typespec == 'type':
1882
+ typename = re.match(r'\s*\(\s*(?P<name>\w+)\s*\)', selector, re.I)
1883
+ if typename:
1884
+ typename = typename.group('name')
1885
+ else:
1886
+ outmess(f'cracktypespec: no typename found in {typespec + selector}\n')
1887
+ else:
1888
+ outmess(f'cracktypespec: no selector used for {repr(selector)}\n')
1889
+ return kindselect, charselect, typename
1890
+ ######
1891
+
1892
+
1893
+ def setattrspec(decl, attr, force=0):
1894
+ if not decl:
1895
+ decl = {}
1896
+ if not attr:
1897
+ return decl
1898
+ if 'attrspec' not in decl:
1899
+ decl['attrspec'] = [attr]
1900
+ return decl
1901
+ if force:
1902
+ decl['attrspec'].append(attr)
1903
+ if attr in decl['attrspec']:
1904
+ return decl
1905
+ if attr == 'static' and 'automatic' not in decl['attrspec']:
1906
+ decl['attrspec'].append(attr)
1907
+ elif attr == 'automatic' and 'static' not in decl['attrspec']:
1908
+ decl['attrspec'].append(attr)
1909
+ elif attr == 'public':
1910
+ if 'private' not in decl['attrspec']:
1911
+ decl['attrspec'].append(attr)
1912
+ elif attr == 'private':
1913
+ if 'public' not in decl['attrspec']:
1914
+ decl['attrspec'].append(attr)
1915
+ else:
1916
+ decl['attrspec'].append(attr)
1917
+ return decl
1918
+
1919
+
1920
+ def setkindselector(decl, sel, force=0):
1921
+ if not decl:
1922
+ decl = {}
1923
+ if not sel:
1924
+ return decl
1925
+ if 'kindselector' not in decl:
1926
+ decl['kindselector'] = sel
1927
+ return decl
1928
+ for k in list(sel.keys()):
1929
+ if force or k not in decl['kindselector']:
1930
+ decl['kindselector'][k] = sel[k]
1931
+ return decl
1932
+
1933
+
1934
+ def setcharselector(decl, sel, force=0):
1935
+ if not decl:
1936
+ decl = {}
1937
+ if not sel:
1938
+ return decl
1939
+ if 'charselector' not in decl:
1940
+ decl['charselector'] = sel
1941
+ return decl
1942
+
1943
+ for k in list(sel.keys()):
1944
+ if force or k not in decl['charselector']:
1945
+ decl['charselector'][k] = sel[k]
1946
+ return decl
1947
+
1948
+
1949
+ def getblockname(block, unknown='unknown'):
1950
+ if 'name' in block:
1951
+ return block['name']
1952
+ return unknown
1953
+
1954
+ # post processing
1955
+
1956
+
1957
+ def setmesstext(block):
1958
+ global filepositiontext
1959
+
1960
+ try:
1961
+ filepositiontext = f"In: {block['from']}:{block['name']}\n"
1962
+ except Exception:
1963
+ pass
1964
+
1965
+
1966
+ def get_usedict(block):
1967
+ usedict = {}
1968
+ if 'parent_block' in block:
1969
+ usedict = get_usedict(block['parent_block'])
1970
+ if 'use' in block:
1971
+ usedict.update(block['use'])
1972
+ return usedict
1973
+
1974
+
1975
+ def get_useparameters(block, param_map=None):
1976
+ global f90modulevars
1977
+
1978
+ if param_map is None:
1979
+ param_map = {}
1980
+ usedict = get_usedict(block)
1981
+ if not usedict:
1982
+ return param_map
1983
+ for usename, mapping in list(usedict.items()):
1984
+ usename = usename.lower()
1985
+ if usename not in f90modulevars:
1986
+ outmess(f'get_useparameters: no module {usename} info used by '
1987
+ f'{block.get("name")}\n')
1988
+ continue
1989
+ mvars = f90modulevars[usename]
1990
+ params = get_parameters(mvars)
1991
+ if not params:
1992
+ continue
1993
+ # XXX: apply mapping
1994
+ if mapping:
1995
+ errmess(f'get_useparameters: mapping for {mapping} not impl.\n')
1996
+ for k, v in list(params.items()):
1997
+ if k in param_map:
1998
+ outmess(f'get_useparameters: overriding parameter {k!r} with'
1999
+ f' value from module {usename!r}\n')
2000
+ param_map[k] = v
2001
+
2002
+ return param_map
2003
+
2004
+
2005
+ def postcrack2(block, tab='', param_map=None):
2006
+ global f90modulevars
2007
+
2008
+ if not f90modulevars:
2009
+ return block
2010
+ if isinstance(block, list):
2011
+ ret = [postcrack2(g, tab=tab + '\t', param_map=param_map)
2012
+ for g in block]
2013
+ return ret
2014
+ setmesstext(block)
2015
+ outmess(f"{tab}Block: {block['name']}\n", 0)
2016
+
2017
+ if param_map is None:
2018
+ param_map = get_useparameters(block)
2019
+
2020
+ if param_map is not None and 'vars' in block:
2021
+ vars = block['vars']
2022
+ for n in list(vars.keys()):
2023
+ var = vars[n]
2024
+ if 'kindselector' in var:
2025
+ kind = var['kindselector']
2026
+ if 'kind' in kind:
2027
+ val = kind['kind']
2028
+ if val in param_map:
2029
+ kind['kind'] = param_map[val]
2030
+ new_body = [postcrack2(b, tab=tab + '\t', param_map=param_map)
2031
+ for b in block['body']]
2032
+ block['body'] = new_body
2033
+
2034
+ return block
2035
+
2036
+
2037
+ def postcrack(block, args=None, tab=''):
2038
+ """
2039
+ TODO:
2040
+ function return values
2041
+ determine expression types if in argument list
2042
+ """
2043
+ global usermodules, onlyfunctions
2044
+
2045
+ if isinstance(block, list):
2046
+ gret = []
2047
+ uret = []
2048
+ for g in block:
2049
+ setmesstext(g)
2050
+ g = postcrack(g, tab=tab + '\t')
2051
+ # sort user routines to appear first
2052
+ if 'name' in g and '__user__' in g['name']:
2053
+ uret.append(g)
2054
+ else:
2055
+ gret.append(g)
2056
+ return uret + gret
2057
+ setmesstext(block)
2058
+ if not isinstance(block, dict) and 'block' not in block:
2059
+ raise Exception('postcrack: Expected block dictionary instead of ' +
2060
+ str(block))
2061
+ if 'name' in block and not block['name'] == 'unknown_interface':
2062
+ outmess(f"{tab}Block: {block['name']}\n", 0)
2063
+ block = analyzeargs(block)
2064
+ block = analyzecommon(block)
2065
+ block['vars'] = analyzevars(block)
2066
+ block['sortvars'] = sortvarnames(block['vars'])
2067
+ if block.get('args'):
2068
+ args = block['args']
2069
+ block['body'] = analyzebody(block, args, tab=tab)
2070
+
2071
+ userisdefined = []
2072
+ if 'use' in block:
2073
+ useblock = block['use']
2074
+ for k in list(useblock.keys()):
2075
+ if '__user__' in k:
2076
+ userisdefined.append(k)
2077
+ else:
2078
+ useblock = {}
2079
+ name = ''
2080
+ if 'name' in block:
2081
+ name = block['name']
2082
+ # and not userisdefined: # Build a __user__ module
2083
+ if block.get('externals'):
2084
+ interfaced = []
2085
+ if 'interfaced' in block:
2086
+ interfaced = block['interfaced']
2087
+ mvars = copy.copy(block['vars'])
2088
+ if name:
2089
+ mname = name + '__user__routines'
2090
+ else:
2091
+ mname = 'unknown__user__routines'
2092
+ if mname in userisdefined:
2093
+ i = 1
2094
+ while f"{mname}_{i}" in userisdefined:
2095
+ i = i + 1
2096
+ mname = f"{mname}_{i}"
2097
+ interface = {'block': 'interface', 'body': [],
2098
+ 'vars': {}, 'name': name + '_user_interface'}
2099
+ for e in block['externals']:
2100
+ if e in interfaced:
2101
+ edef = []
2102
+ j = -1
2103
+ for b in block['body']:
2104
+ j = j + 1
2105
+ if b['block'] == 'interface':
2106
+ i = -1
2107
+ for bb in b['body']:
2108
+ i = i + 1
2109
+ if 'name' in bb and bb['name'] == e:
2110
+ edef = copy.copy(bb)
2111
+ del b['body'][i]
2112
+ break
2113
+ if edef:
2114
+ if not b['body']:
2115
+ del block['body'][j]
2116
+ del interfaced[interfaced.index(e)]
2117
+ break
2118
+ interface['body'].append(edef)
2119
+ elif e in mvars and not isexternal(mvars[e]):
2120
+ interface['vars'][e] = mvars[e]
2121
+ if interface['vars'] or interface['body']:
2122
+ block['interfaced'] = interfaced
2123
+ mblock = {'block': 'python module', 'body': [
2124
+ interface], 'vars': {}, 'name': mname, 'interfaced': block['externals']}
2125
+ useblock[mname] = {}
2126
+ usermodules.append(mblock)
2127
+ if useblock:
2128
+ block['use'] = useblock
2129
+ return block
2130
+
2131
+
2132
+ def sortvarnames(vars):
2133
+ indep = []
2134
+ dep = []
2135
+ for v in list(vars.keys()):
2136
+ if 'depend' in vars[v] and vars[v]['depend']:
2137
+ dep.append(v)
2138
+ else:
2139
+ indep.append(v)
2140
+ n = len(dep)
2141
+ i = 0
2142
+ while dep: # XXX: How to catch dependence cycles correctly?
2143
+ v = dep[0]
2144
+ fl = 0
2145
+ for w in dep[1:]:
2146
+ if w in vars[v]['depend']:
2147
+ fl = 1
2148
+ break
2149
+ if fl:
2150
+ dep = dep[1:] + [v]
2151
+ i = i + 1
2152
+ if i > n:
2153
+ errmess('sortvarnames: failed to compute dependencies because'
2154
+ ' of cyclic dependencies between '
2155
+ + ', '.join(dep) + '\n')
2156
+ indep = indep + dep
2157
+ break
2158
+ else:
2159
+ indep.append(v)
2160
+ dep = dep[1:]
2161
+ n = len(dep)
2162
+ i = 0
2163
+ return indep
2164
+
2165
+
2166
+ def analyzecommon(block):
2167
+ if not hascommon(block):
2168
+ return block
2169
+ commonvars = []
2170
+ for k in list(block['common'].keys()):
2171
+ comvars = []
2172
+ for e in block['common'][k]:
2173
+ m = re.match(
2174
+ r'\A\s*\b(?P<name>.*?)\b\s*(\((?P<dims>.*?)\)|)\s*\Z', e, re.I)
2175
+ if m:
2176
+ dims = []
2177
+ if m.group('dims'):
2178
+ dims = [x.strip()
2179
+ for x in markoutercomma(m.group('dims')).split('@,@')]
2180
+ n = rmbadname1(m.group('name').strip())
2181
+ if n in block['vars']:
2182
+ if 'attrspec' in block['vars'][n]:
2183
+ block['vars'][n]['attrspec'].append(
2184
+ f"dimension({','.join(dims)})")
2185
+ else:
2186
+ block['vars'][n]['attrspec'] = [
2187
+ f"dimension({','.join(dims)})"]
2188
+ elif dims:
2189
+ block['vars'][n] = {
2190
+ 'attrspec': [f"dimension({','.join(dims)})"]}
2191
+ else:
2192
+ block['vars'][n] = {}
2193
+ if n not in commonvars:
2194
+ commonvars.append(n)
2195
+ else:
2196
+ n = e
2197
+ errmess(
2198
+ f'analyzecommon: failed to extract "<name>[(<dims>)]" from "{e}" in common /{k}/.\n')
2199
+ comvars.append(n)
2200
+ block['common'][k] = comvars
2201
+ if 'commonvars' not in block:
2202
+ block['commonvars'] = commonvars
2203
+ else:
2204
+ block['commonvars'] = block['commonvars'] + commonvars
2205
+ return block
2206
+
2207
+
2208
+ def analyzebody(block, args, tab=''):
2209
+ global usermodules, skipfuncs, onlyfuncs, f90modulevars
2210
+
2211
+ setmesstext(block)
2212
+
2213
+ maybe_private = {
2214
+ key: value
2215
+ for key, value in block['vars'].items()
2216
+ if 'attrspec' not in value or 'public' not in value['attrspec']
2217
+ }
2218
+
2219
+ body = []
2220
+ for b in block['body']:
2221
+ b['parent_block'] = block
2222
+ if b['block'] in ['function', 'subroutine']:
2223
+ if args is not None and b['name'] not in args:
2224
+ continue
2225
+ else:
2226
+ as_ = b['args']
2227
+ # Add private members to skipfuncs for gh-23879
2228
+ if b['name'] in maybe_private.keys():
2229
+ skipfuncs.append(b['name'])
2230
+ if b['name'] in skipfuncs:
2231
+ continue
2232
+ if onlyfuncs and b['name'] not in onlyfuncs:
2233
+ continue
2234
+ b['saved_interface'] = crack2fortrangen(
2235
+ b, '\n' + ' ' * 6, as_interface=True)
2236
+
2237
+ else:
2238
+ as_ = args
2239
+ b = postcrack(b, as_, tab=tab + '\t')
2240
+ if b['block'] in ['interface', 'abstract interface'] and \
2241
+ not b['body'] and not b.get('implementedby'):
2242
+ if 'f2pyenhancements' not in b:
2243
+ continue
2244
+ if b['block'].replace(' ', '') == 'pythonmodule':
2245
+ usermodules.append(b)
2246
+ else:
2247
+ if b['block'] == 'module':
2248
+ f90modulevars[b['name']] = b['vars']
2249
+ body.append(b)
2250
+ return body
2251
+
2252
+
2253
+ def buildimplicitrules(block):
2254
+ setmesstext(block)
2255
+ implicitrules = defaultimplicitrules
2256
+ attrrules = {}
2257
+ if 'implicit' in block:
2258
+ if block['implicit'] is None:
2259
+ implicitrules = None
2260
+ if verbose > 1:
2261
+ outmess(
2262
+ f"buildimplicitrules: no implicit rules for routine {repr(block['name'])}.\n")
2263
+ else:
2264
+ for k in list(block['implicit'].keys()):
2265
+ if block['implicit'][k].get('typespec') not in ['static', 'automatic']:
2266
+ implicitrules[k] = block['implicit'][k]
2267
+ else:
2268
+ attrrules[k] = block['implicit'][k]['typespec']
2269
+ return implicitrules, attrrules
2270
+
2271
+
2272
+ def myeval(e, g=None, l=None):
2273
+ """ Like `eval` but returns only integers and floats """
2274
+ r = eval(e, g, l)
2275
+ if type(r) in [int, float]:
2276
+ return r
2277
+ raise ValueError(f'r={r!r}')
2278
+
2279
+
2280
+ getlincoef_re_1 = re.compile(r'\A\b\w+\b\Z', re.I)
2281
+
2282
+
2283
+ def getlincoef(e, xset): # e = a*x+b ; x in xset
2284
+ """
2285
+ Obtain ``a`` and ``b`` when ``e == "a*x+b"``, where ``x`` is a symbol in
2286
+ xset.
2287
+
2288
+ >>> getlincoef('2*x + 1', {'x'})
2289
+ (2, 1, 'x')
2290
+ >>> getlincoef('3*x + x*2 + 2 + 1', {'x'})
2291
+ (5, 3, 'x')
2292
+ >>> getlincoef('0', {'x'})
2293
+ (0, 0, None)
2294
+ >>> getlincoef('0*x', {'x'})
2295
+ (0, 0, 'x')
2296
+ >>> getlincoef('x*x', {'x'})
2297
+ (None, None, None)
2298
+
2299
+ This can be tricked by sufficiently complex expressions
2300
+
2301
+ >>> getlincoef('(x - 0.5)*(x - 1.5)*(x - 1)*x + 2*x + 3', {'x'})
2302
+ (2.0, 3.0, 'x')
2303
+ """
2304
+ try:
2305
+ c = int(myeval(e, {}, {}))
2306
+ return 0, c, None
2307
+ except Exception:
2308
+ pass
2309
+ if getlincoef_re_1.match(e):
2310
+ return 1, 0, e
2311
+ len_e = len(e)
2312
+ for x in xset:
2313
+ if len(x) > len_e:
2314
+ continue
2315
+ if re.search(r'\w\s*\([^)]*\b' + x + r'\b', e):
2316
+ # skip function calls having x as an argument, e.g max(1, x)
2317
+ continue
2318
+ re_1 = re.compile(r'(?P<before>.*?)\b' + x + r'\b(?P<after>.*)', re.I)
2319
+ m = re_1.match(e)
2320
+ if m:
2321
+ try:
2322
+ m1 = re_1.match(e)
2323
+ while m1:
2324
+ ee = f"{m1.group('before')}({0}){m1.group('after')}"
2325
+ m1 = re_1.match(ee)
2326
+ b = myeval(ee, {}, {})
2327
+ m1 = re_1.match(e)
2328
+ while m1:
2329
+ ee = f"{m1.group('before')}({1}){m1.group('after')}"
2330
+ m1 = re_1.match(ee)
2331
+ a = myeval(ee, {}, {}) - b
2332
+ m1 = re_1.match(e)
2333
+ while m1:
2334
+ ee = f"{m1.group('before')}({0.5}){m1.group('after')}"
2335
+ m1 = re_1.match(ee)
2336
+ c = myeval(ee, {}, {})
2337
+ # computing another point to be sure that expression is linear
2338
+ m1 = re_1.match(e)
2339
+ while m1:
2340
+ ee = f"{m1.group('before')}({1.5}){m1.group('after')}"
2341
+ m1 = re_1.match(ee)
2342
+ c2 = myeval(ee, {}, {})
2343
+ if (a * 0.5 + b == c and a * 1.5 + b == c2):
2344
+ return a, b, x
2345
+ except Exception:
2346
+ pass
2347
+ break
2348
+ return None, None, None
2349
+
2350
+
2351
+ word_pattern = re.compile(r'\b[a-z][\w$]*\b', re.I)
2352
+
2353
+
2354
+ def _get_depend_dict(name, vars, deps):
2355
+ if name in vars:
2356
+ words = vars[name].get('depend', [])
2357
+
2358
+ if '=' in vars[name] and not isstring(vars[name]):
2359
+ for word in word_pattern.findall(vars[name]['=']):
2360
+ # The word_pattern may return values that are not
2361
+ # only variables, they can be string content for instance
2362
+ if word not in words and word in vars and word != name:
2363
+ words.append(word)
2364
+ for word in words[:]:
2365
+ for w in deps.get(word, []) \
2366
+ or _get_depend_dict(word, vars, deps):
2367
+ if w not in words:
2368
+ words.append(w)
2369
+ else:
2370
+ outmess(f'_get_depend_dict: no dependence info for {repr(name)}\n')
2371
+ words = []
2372
+ deps[name] = words
2373
+ return words
2374
+
2375
+
2376
+ def _calc_depend_dict(vars):
2377
+ names = list(vars.keys())
2378
+ depend_dict = {}
2379
+ for n in names:
2380
+ _get_depend_dict(n, vars, depend_dict)
2381
+ return depend_dict
2382
+
2383
+
2384
+ def get_sorted_names(vars):
2385
+ depend_dict = _calc_depend_dict(vars)
2386
+ names = []
2387
+ for name in list(depend_dict.keys()):
2388
+ if not depend_dict[name]:
2389
+ names.append(name)
2390
+ del depend_dict[name]
2391
+ while depend_dict:
2392
+ for name, lst in list(depend_dict.items()):
2393
+ new_lst = [n for n in lst if n in depend_dict]
2394
+ if not new_lst:
2395
+ names.append(name)
2396
+ del depend_dict[name]
2397
+ else:
2398
+ depend_dict[name] = new_lst
2399
+ return [name for name in names if name in vars]
2400
+
2401
+
2402
+ def _kind_func(string):
2403
+ # XXX: return something sensible.
2404
+ if string[0] in "'\"":
2405
+ string = string[1:-1]
2406
+ if real16pattern.match(string):
2407
+ return 8
2408
+ elif real8pattern.match(string):
2409
+ return 4
2410
+ return 'kind(' + string + ')'
2411
+
2412
+
2413
+ def _selected_int_kind_func(r):
2414
+ # XXX: This should be processor dependent
2415
+ m = 10 ** r
2416
+ if m <= 2 ** 8:
2417
+ return 1
2418
+ if m <= 2 ** 16:
2419
+ return 2
2420
+ if m <= 2 ** 32:
2421
+ return 4
2422
+ if m <= 2 ** 63:
2423
+ return 8
2424
+ if m <= 2 ** 128:
2425
+ return 16
2426
+ return -1
2427
+
2428
+
2429
+ def _selected_real_kind_func(p, r=0, radix=0):
2430
+ # XXX: This should be processor dependent
2431
+ # This is only verified for 0 <= p <= 20, possibly good for p <= 33 and above
2432
+ if p < 7:
2433
+ return 4
2434
+ if p < 16:
2435
+ return 8
2436
+ machine = platform.machine().lower()
2437
+ if machine.startswith(('aarch64', 'alpha', 'arm64', 'loongarch', 'mips', 'power', 'ppc', 'riscv', 's390x', 'sparc')):
2438
+ if p <= 33:
2439
+ return 16
2440
+ elif p < 19:
2441
+ return 10
2442
+ elif p <= 33:
2443
+ return 16
2444
+ return -1
2445
+
2446
+
2447
+ def get_parameters(vars, global_params={}):
2448
+ params = copy.copy(global_params)
2449
+ g_params = copy.copy(global_params)
2450
+ for name, func in [('kind', _kind_func),
2451
+ ('selected_int_kind', _selected_int_kind_func),
2452
+ ('selected_real_kind', _selected_real_kind_func), ]:
2453
+ if name not in g_params:
2454
+ g_params[name] = func
2455
+ param_names = []
2456
+ for n in get_sorted_names(vars):
2457
+ if 'attrspec' in vars[n] and 'parameter' in vars[n]['attrspec']:
2458
+ param_names.append(n)
2459
+ kind_re = re.compile(r'\bkind\s*\(\s*(?P<value>.*)\s*\)', re.I)
2460
+ selected_int_kind_re = re.compile(
2461
+ r'\bselected_int_kind\s*\(\s*(?P<value>.*)\s*\)', re.I)
2462
+ selected_kind_re = re.compile(
2463
+ r'\bselected_(int|real)_kind\s*\(\s*(?P<value>.*)\s*\)', re.I)
2464
+ for n in param_names:
2465
+ if '=' in vars[n]:
2466
+ v = vars[n]['=']
2467
+ if islogical(vars[n]):
2468
+ v = v.lower()
2469
+ for repl in [
2470
+ ('.false.', 'False'),
2471
+ ('.true.', 'True'),
2472
+ # TODO: test .eq., .neq., etc replacements.
2473
+ ]:
2474
+ v = v.replace(*repl)
2475
+
2476
+ v = kind_re.sub(r'kind("\1")', v)
2477
+ v = selected_int_kind_re.sub(r'selected_int_kind(\1)', v)
2478
+
2479
+ # We need to act according to the data.
2480
+ # The easy case is if the data has a kind-specifier,
2481
+ # then we may easily remove those specifiers.
2482
+ # However, it may be that the user uses other specifiers...(!)
2483
+ is_replaced = False
2484
+
2485
+ if 'kindselector' in vars[n]:
2486
+ # Remove kind specifier (including those defined
2487
+ # by parameters)
2488
+ if 'kind' in vars[n]['kindselector']:
2489
+ orig_v_len = len(v)
2490
+ v = v.replace('_' + vars[n]['kindselector']['kind'], '')
2491
+ # Again, this will be true if even a single specifier
2492
+ # has been replaced, see comment above.
2493
+ is_replaced = len(v) < orig_v_len
2494
+
2495
+ if not is_replaced:
2496
+ if not selected_kind_re.match(v):
2497
+ v_ = v.split('_')
2498
+ # In case there are additive parameters
2499
+ if len(v_) > 1:
2500
+ v = ''.join(v_[:-1]).lower().replace(v_[-1].lower(), '')
2501
+
2502
+ # Currently this will not work for complex numbers.
2503
+ # There is missing code for extracting a complex number,
2504
+ # which may be defined in either of these:
2505
+ # a) (Re, Im)
2506
+ # b) cmplx(Re, Im)
2507
+ # c) dcmplx(Re, Im)
2508
+ # d) cmplx(Re, Im, <prec>)
2509
+
2510
+ if isdouble(vars[n]):
2511
+ tt = list(v)
2512
+ for m in real16pattern.finditer(v):
2513
+ tt[m.start():m.end()] = list(
2514
+ v[m.start():m.end()].lower().replace('d', 'e'))
2515
+ v = ''.join(tt)
2516
+
2517
+ elif iscomplex(vars[n]):
2518
+ outmess(f'get_parameters[TODO]: '
2519
+ f'implement evaluation of complex expression {v}\n')
2520
+
2521
+ dimspec = ([s.removeprefix('dimension').strip()
2522
+ for s in vars[n]['attrspec']
2523
+ if s.startswith('dimension')] or [None])[0]
2524
+
2525
+ # Handle _dp for gh-6624
2526
+ # Also fixes gh-20460
2527
+ if real16pattern.search(v):
2528
+ v = 8
2529
+ elif real8pattern.search(v):
2530
+ v = 4
2531
+ try:
2532
+ params[n] = param_eval(v, g_params, params, dimspec=dimspec)
2533
+ except Exception as msg:
2534
+ params[n] = v
2535
+ outmess(f'get_parameters: got "{msg}" on {n!r}\n')
2536
+
2537
+ if isstring(vars[n]) and isinstance(params[n], int):
2538
+ params[n] = chr(params[n])
2539
+ nl = n.lower()
2540
+ if nl != n:
2541
+ params[nl] = params[n]
2542
+ else:
2543
+ print(vars[n])
2544
+ outmess(f'get_parameters:parameter {n!r} does not have value?!\n')
2545
+ return params
2546
+
2547
+
2548
+ def _eval_length(length, params):
2549
+ if length in ['(:)', '(*)', '*']:
2550
+ return '(*)'
2551
+ return _eval_scalar(length, params)
2552
+
2553
+
2554
+ _is_kind_number = re.compile(r'\d+_').match
2555
+
2556
+
2557
+ def _eval_scalar(value, params):
2558
+ if _is_kind_number(value):
2559
+ value = value.split('_')[0]
2560
+ try:
2561
+ # TODO: use symbolic from PR #19805
2562
+ value = eval(value, {}, params)
2563
+ value = (repr if isinstance(value, str) else str)(value)
2564
+ except (NameError, SyntaxError, TypeError):
2565
+ return value
2566
+ except Exception as msg:
2567
+ errmess(f'"{msg}" in evaluating {value!r} '
2568
+ f'(available names: {list(params)})\n')
2569
+ return value
2570
+
2571
+
2572
+ def analyzevars(block):
2573
+ """
2574
+ Sets correct dimension information for each variable/parameter
2575
+ """
2576
+
2577
+ global f90modulevars
2578
+
2579
+ setmesstext(block)
2580
+ implicitrules, attrrules = buildimplicitrules(block)
2581
+ vars = copy.copy(block['vars'])
2582
+ if block['block'] == 'function' and block['name'] not in vars:
2583
+ vars[block['name']] = {}
2584
+ if '' in block['vars']:
2585
+ del vars['']
2586
+ if 'attrspec' in block['vars']['']:
2587
+ gen = block['vars']['']['attrspec']
2588
+ for n in set(vars) | {b['name'] for b in block['body']}:
2589
+ for k in ['public', 'private']:
2590
+ if k in gen:
2591
+ vars[n] = setattrspec(vars.get(n, {}), k)
2592
+ svars = []
2593
+ args = block['args']
2594
+ for a in args:
2595
+ try:
2596
+ vars[a]
2597
+ svars.append(a)
2598
+ except KeyError:
2599
+ pass
2600
+ for n in list(vars.keys()):
2601
+ if n not in args:
2602
+ svars.append(n)
2603
+
2604
+ params = get_parameters(vars, get_useparameters(block))
2605
+ # At this point, params are read and interpreted, but
2606
+ # the params used to define vars are not yet parsed
2607
+ dep_matches = {}
2608
+ name_match = re.compile(r'[A-Za-z][\w$]*').match
2609
+ for v in list(vars.keys()):
2610
+ m = name_match(v)
2611
+ if m:
2612
+ n = v[m.start():m.end()]
2613
+ try:
2614
+ dep_matches[n]
2615
+ except KeyError:
2616
+ dep_matches[n] = re.compile(rf'.*\b{v}\b', re.I).match
2617
+ for n in svars:
2618
+ if n[0] in list(attrrules.keys()):
2619
+ vars[n] = setattrspec(vars[n], attrrules[n[0]])
2620
+ if 'typespec' not in vars[n]:
2621
+ if not ('attrspec' in vars[n] and 'external' in vars[n]['attrspec']):
2622
+ if implicitrules:
2623
+ ln0 = n[0].lower()
2624
+ for k in list(implicitrules[ln0].keys()):
2625
+ if k == 'typespec' and implicitrules[ln0][k] == 'undefined':
2626
+ continue
2627
+ if k not in vars[n]:
2628
+ vars[n][k] = implicitrules[ln0][k]
2629
+ elif k == 'attrspec':
2630
+ for l in implicitrules[ln0][k]:
2631
+ vars[n] = setattrspec(vars[n], l)
2632
+ elif n in block['args']:
2633
+ outmess(f"analyzevars: typespec of variable {n!r} is not defined "
2634
+ f"in routine {block['name']}.\n")
2635
+ if 'charselector' in vars[n]:
2636
+ if 'len' in vars[n]['charselector']:
2637
+ l = vars[n]['charselector']['len']
2638
+ try:
2639
+ l = str(eval(l, {}, params))
2640
+ except Exception:
2641
+ pass
2642
+ vars[n]['charselector']['len'] = l
2643
+
2644
+ if 'kindselector' in vars[n]:
2645
+ if 'kind' in vars[n]['kindselector']:
2646
+ l = vars[n]['kindselector']['kind']
2647
+ try:
2648
+ l = str(eval(l, {}, params))
2649
+ except Exception:
2650
+ pass
2651
+ vars[n]['kindselector']['kind'] = l
2652
+
2653
+ dimension_exprs = {}
2654
+ if 'attrspec' in vars[n]:
2655
+ attr = vars[n]['attrspec']
2656
+ attr.reverse()
2657
+ vars[n]['attrspec'] = []
2658
+ dim, intent, depend, check, note = None, None, None, None, None
2659
+ for a in attr:
2660
+ if a[:9] == 'dimension':
2661
+ dim = (a[9:].strip())[1:-1]
2662
+ elif a[:6] == 'intent':
2663
+ intent = (a[6:].strip())[1:-1]
2664
+ elif a[:6] == 'depend':
2665
+ depend = (a[6:].strip())[1:-1]
2666
+ elif a[:5] == 'check':
2667
+ check = (a[5:].strip())[1:-1]
2668
+ elif a[:4] == 'note':
2669
+ note = (a[4:].strip())[1:-1]
2670
+ else:
2671
+ vars[n] = setattrspec(vars[n], a)
2672
+ if intent:
2673
+ if 'intent' not in vars[n]:
2674
+ vars[n]['intent'] = []
2675
+ for c in [x.strip() for x in markoutercomma(intent).split('@,@')]:
2676
+ # Remove spaces so that 'in out' becomes 'inout'
2677
+ tmp = c.replace(' ', '')
2678
+ if tmp not in vars[n]['intent']:
2679
+ vars[n]['intent'].append(tmp)
2680
+ intent = None
2681
+ if note:
2682
+ note = note.replace('\\n\\n', '\n\n')
2683
+ note = note.replace('\\n ', '\n')
2684
+ if 'note' not in vars[n]:
2685
+ vars[n]['note'] = [note]
2686
+ else:
2687
+ vars[n]['note'].append(note)
2688
+ note = None
2689
+ if depend is not None:
2690
+ if 'depend' not in vars[n]:
2691
+ vars[n]['depend'] = []
2692
+ for c in rmbadname([x.strip() for x in markoutercomma(depend).split('@,@')]):
2693
+ if c not in vars[n]['depend']:
2694
+ vars[n]['depend'].append(c)
2695
+ depend = None
2696
+ if check is not None:
2697
+ if 'check' not in vars[n]:
2698
+ vars[n]['check'] = []
2699
+ for c in [x.strip() for x in markoutercomma(check).split('@,@')]:
2700
+ if c not in vars[n]['check']:
2701
+ vars[n]['check'].append(c)
2702
+ check = None
2703
+ if dim and 'dimension' not in vars[n]:
2704
+ vars[n]['dimension'] = []
2705
+ for d in rmbadname(
2706
+ [x.strip() for x in markoutercomma(dim).split('@,@')]
2707
+ ):
2708
+ # d is the expression inside the dimension declaration
2709
+ # Evaluate `d` with respect to params
2710
+ try:
2711
+ # the dimension for this variable depends on a
2712
+ # previously defined parameter
2713
+ d = param_parse(d, params)
2714
+ except (ValueError, IndexError, KeyError):
2715
+ outmess(
2716
+ 'analyzevars: could not parse dimension for '
2717
+ f'variable {d!r}\n'
2718
+ )
2719
+
2720
+ dim_char = ':' if d == ':' else '*'
2721
+ if d == dim_char:
2722
+ dl = [dim_char]
2723
+ else:
2724
+ dl = markoutercomma(d, ':').split('@:@')
2725
+ if len(dl) == 2 and '*' in dl: # e.g. dimension(5:*)
2726
+ dl = ['*']
2727
+ d = '*'
2728
+ if len(dl) == 1 and dl[0] != dim_char:
2729
+ dl = ['1', dl[0]]
2730
+ if len(dl) == 2:
2731
+ d1, d2 = map(symbolic.Expr.parse, dl)
2732
+ dsize = d2 - d1 + 1
2733
+ d = dsize.tostring(language=symbolic.Language.C)
2734
+ # find variables v that define d as a linear
2735
+ # function, `d == a * v + b`, and store
2736
+ # coefficients a and b for further analysis.
2737
+ solver_and_deps = {}
2738
+ for v in block['vars']:
2739
+ s = symbolic.as_symbol(v)
2740
+ if dsize.contains(s):
2741
+ try:
2742
+ a, b = dsize.linear_solve(s)
2743
+
2744
+ def solve_v(s, a=a, b=b):
2745
+ return (s - b) / a
2746
+
2747
+ all_symbols = set(a.symbols())
2748
+ all_symbols.update(b.symbols())
2749
+ except RuntimeError as msg:
2750
+ # d is not a linear function of v,
2751
+ # however, if v can be determined
2752
+ # from d using other means,
2753
+ # implement the corresponding
2754
+ # solve_v function here.
2755
+ solve_v = None
2756
+ all_symbols = set(dsize.symbols())
2757
+ v_deps = {
2758
+ s.data for s in all_symbols
2759
+ if s.data in vars}
2760
+ solver_and_deps[v] = solve_v, list(v_deps)
2761
+ # Note that dsize may contain symbols that are
2762
+ # not defined in block['vars']. Here we assume
2763
+ # these correspond to Fortran/C intrinsic
2764
+ # functions or that are defined by other
2765
+ # means. We'll let the compiler validate the
2766
+ # definiteness of such symbols.
2767
+ dimension_exprs[d] = solver_and_deps
2768
+ vars[n]['dimension'].append(d)
2769
+
2770
+ if 'check' not in vars[n] and 'args' in block and n in block['args']:
2771
+ # n is an argument that has no checks defined. Here we
2772
+ # generate some consistency checks for n, and when n is an
2773
+ # array, generate checks for its dimensions and construct
2774
+ # initialization expressions.
2775
+ n_deps = vars[n].get('depend', [])
2776
+ n_checks = []
2777
+ n_is_input = l_or(isintent_in, isintent_inout,
2778
+ isintent_inplace)(vars[n])
2779
+ if isarray(vars[n]): # n is array
2780
+ for i, d in enumerate(vars[n]['dimension']):
2781
+ coeffs_and_deps = dimension_exprs.get(d)
2782
+ if coeffs_and_deps is None:
2783
+ # d is `:` or `*` or a constant expression
2784
+ pass
2785
+ elif n_is_input:
2786
+ # n is an input array argument and its shape
2787
+ # may define variables used in dimension
2788
+ # specifications.
2789
+ for v, (solver, deps) in coeffs_and_deps.items():
2790
+ def compute_deps(v, deps):
2791
+ for v1 in coeffs_and_deps.get(v, [None, []])[1]:
2792
+ if v1 not in deps:
2793
+ deps.add(v1)
2794
+ compute_deps(v1, deps)
2795
+ all_deps = set()
2796
+ compute_deps(v, all_deps)
2797
+ if (v in n_deps
2798
+ or '=' in vars[v]
2799
+ or 'depend' in vars[v]):
2800
+ # Skip a variable that
2801
+ # - n depends on
2802
+ # - has user-defined initialization expression
2803
+ # - has user-defined dependencies
2804
+ continue
2805
+ if solver is not None and v not in all_deps:
2806
+ # v can be solved from d, hence, we
2807
+ # make it an optional argument with
2808
+ # initialization expression:
2809
+ is_required = False
2810
+ init = solver(symbolic.as_symbol(
2811
+ f'shape({n}, {i})'))
2812
+ init = init.tostring(
2813
+ language=symbolic.Language.C)
2814
+ vars[v]['='] = init
2815
+ # n needs to be initialized before v. So,
2816
+ # making v dependent on n and on any
2817
+ # variables in solver or d.
2818
+ vars[v]['depend'] = [n] + deps
2819
+ if 'check' not in vars[v]:
2820
+ # add check only when no
2821
+ # user-specified checks exist
2822
+ vars[v]['check'] = [
2823
+ f'shape({n}, {i}) == {d}']
2824
+ else:
2825
+ # d is a non-linear function on v,
2826
+ # hence, v must be a required input
2827
+ # argument that n will depend on
2828
+ is_required = True
2829
+ if 'intent' not in vars[v]:
2830
+ vars[v]['intent'] = []
2831
+ if 'in' not in vars[v]['intent']:
2832
+ vars[v]['intent'].append('in')
2833
+ # v needs to be initialized before n
2834
+ n_deps.append(v)
2835
+ n_checks.append(
2836
+ f'shape({n}, {i}) == {d}')
2837
+ v_attr = vars[v].get('attrspec', [])
2838
+ if not ('optional' in v_attr
2839
+ or 'required' in v_attr):
2840
+ v_attr.append(
2841
+ 'required' if is_required else 'optional')
2842
+ if v_attr:
2843
+ vars[v]['attrspec'] = v_attr
2844
+ if coeffs_and_deps is not None:
2845
+ # extend v dependencies with ones specified in attrspec
2846
+ for v, (solver, deps) in coeffs_and_deps.items():
2847
+ v_deps = vars[v].get('depend', [])
2848
+ for aa in vars[v].get('attrspec', []):
2849
+ if aa.startswith('depend'):
2850
+ aa = ''.join(aa.split())
2851
+ v_deps.extend(aa[7:-1].split(','))
2852
+ if v_deps:
2853
+ vars[v]['depend'] = list(set(v_deps))
2854
+ if n not in v_deps:
2855
+ n_deps.append(v)
2856
+ elif isstring(vars[n]):
2857
+ if 'charselector' in vars[n]:
2858
+ if '*' in vars[n]['charselector']:
2859
+ length = _eval_length(vars[n]['charselector']['*'],
2860
+ params)
2861
+ vars[n]['charselector']['*'] = length
2862
+ elif 'len' in vars[n]['charselector']:
2863
+ length = _eval_length(vars[n]['charselector']['len'],
2864
+ params)
2865
+ del vars[n]['charselector']['len']
2866
+ vars[n]['charselector']['*'] = length
2867
+ if n_checks:
2868
+ vars[n]['check'] = n_checks
2869
+ if n_deps:
2870
+ vars[n]['depend'] = list(set(n_deps))
2871
+
2872
+ if '=' in vars[n]:
2873
+ if 'attrspec' not in vars[n]:
2874
+ vars[n]['attrspec'] = []
2875
+ if ('optional' not in vars[n]['attrspec']) and \
2876
+ ('required' not in vars[n]['attrspec']):
2877
+ vars[n]['attrspec'].append('optional')
2878
+ if 'depend' not in vars[n]:
2879
+ vars[n]['depend'] = []
2880
+ for v, m in list(dep_matches.items()):
2881
+ if m(vars[n]['=']):
2882
+ vars[n]['depend'].append(v)
2883
+ if not vars[n]['depend']:
2884
+ del vars[n]['depend']
2885
+ if isscalar(vars[n]):
2886
+ vars[n]['='] = _eval_scalar(vars[n]['='], params)
2887
+
2888
+ for n in list(vars.keys()):
2889
+ if n == block['name']: # n is block name
2890
+ if 'note' in vars[n]:
2891
+ block['note'] = vars[n]['note']
2892
+ if block['block'] == 'function':
2893
+ if 'result' in block and block['result'] in vars:
2894
+ vars[n] = appenddecl(vars[n], vars[block['result']])
2895
+ if 'prefix' in block:
2896
+ pr = block['prefix']
2897
+ pr1 = pr.replace('pure', '')
2898
+ ispure = (not pr == pr1)
2899
+ pr = pr1.replace('recursive', '')
2900
+ isrec = (not pr == pr1)
2901
+ m = typespattern[0].match(pr)
2902
+ if m:
2903
+ typespec, selector, attr, edecl = cracktypespec0(
2904
+ m.group('this'), m.group('after'))
2905
+ kindselect, charselect, typename = cracktypespec(
2906
+ typespec, selector)
2907
+ vars[n]['typespec'] = typespec
2908
+ try:
2909
+ if block['result']:
2910
+ vars[block['result']]['typespec'] = typespec
2911
+ except Exception:
2912
+ pass
2913
+ if kindselect:
2914
+ if 'kind' in kindselect:
2915
+ try:
2916
+ kindselect['kind'] = eval(
2917
+ kindselect['kind'], {}, params)
2918
+ except Exception:
2919
+ pass
2920
+ vars[n]['kindselector'] = kindselect
2921
+ if charselect:
2922
+ vars[n]['charselector'] = charselect
2923
+ if typename:
2924
+ vars[n]['typename'] = typename
2925
+ if ispure:
2926
+ vars[n] = setattrspec(vars[n], 'pure')
2927
+ if isrec:
2928
+ vars[n] = setattrspec(vars[n], 'recursive')
2929
+ else:
2930
+ outmess(
2931
+ f"analyzevars: prefix ({repr(block['prefix'])}) were not used\n")
2932
+ if block['block'] not in ['module', 'pythonmodule', 'python module', 'block data']:
2933
+ if 'commonvars' in block:
2934
+ neededvars = copy.copy(block['args'] + block['commonvars'])
2935
+ else:
2936
+ neededvars = copy.copy(block['args'])
2937
+ for n in list(vars.keys()):
2938
+ if l_or(isintent_callback, isintent_aux)(vars[n]):
2939
+ neededvars.append(n)
2940
+ if 'entry' in block:
2941
+ neededvars.extend(list(block['entry'].keys()))
2942
+ for k in list(block['entry'].keys()):
2943
+ for n in block['entry'][k]:
2944
+ if n not in neededvars:
2945
+ neededvars.append(n)
2946
+ if block['block'] == 'function':
2947
+ if 'result' in block:
2948
+ neededvars.append(block['result'])
2949
+ else:
2950
+ neededvars.append(block['name'])
2951
+ if block['block'] in ['subroutine', 'function']:
2952
+ name = block['name']
2953
+ if name in vars and 'intent' in vars[name]:
2954
+ block['intent'] = vars[name]['intent']
2955
+ if block['block'] == 'type':
2956
+ neededvars.extend(list(vars.keys()))
2957
+ for n in list(vars.keys()):
2958
+ if n not in neededvars:
2959
+ del vars[n]
2960
+ return vars
2961
+
2962
+
2963
+ analyzeargs_re_1 = re.compile(r'\A[a-z]+[\w$]*\Z', re.I)
2964
+
2965
+
2966
+ def param_eval(v, g_params, params, dimspec=None):
2967
+ """
2968
+ Creates a dictionary of indices and values for each parameter in a
2969
+ parameter array to be evaluated later.
2970
+
2971
+ WARNING: It is not possible to initialize multidimensional array
2972
+ parameters e.g. dimension(-3:1, 4, 3:5) at this point. This is because in
2973
+ Fortran initialization through array constructor requires the RESHAPE
2974
+ intrinsic function. Since the right-hand side of the parameter declaration
2975
+ is not executed in f2py, but rather at the compiled c/fortran extension,
2976
+ later, it is not possible to execute a reshape of a parameter array.
2977
+ One issue remains: if the user wants to access the array parameter from
2978
+ python, we should either
2979
+ 1) allow them to access the parameter array using python standard indexing
2980
+ (which is often incompatible with the original fortran indexing)
2981
+ 2) allow the parameter array to be accessed in python as a dictionary with
2982
+ fortran indices as keys
2983
+ We are choosing 2 for now.
2984
+ """
2985
+ if dimspec is None:
2986
+ try:
2987
+ p = eval(v, g_params, params)
2988
+ except Exception as msg:
2989
+ p = v
2990
+ outmess(f'param_eval: got "{msg}" on {v!r}\n')
2991
+ return p
2992
+
2993
+ # This is an array parameter.
2994
+ # First, we parse the dimension information
2995
+ if len(dimspec) < 2 or dimspec[::len(dimspec) - 1] != "()":
2996
+ raise ValueError(f'param_eval: dimension {dimspec} can\'t be parsed')
2997
+ dimrange = dimspec[1:-1].split(',')
2998
+ if len(dimrange) == 1:
2999
+ # e.g. dimension(2) or dimension(-1:1)
3000
+ dimrange = dimrange[0].split(':')
3001
+ # now, dimrange is a list of 1 or 2 elements
3002
+ if len(dimrange) == 1:
3003
+ bound = param_parse(dimrange[0], params)
3004
+ dimrange = range(1, int(bound) + 1)
3005
+ else:
3006
+ lbound = param_parse(dimrange[0], params)
3007
+ ubound = param_parse(dimrange[1], params)
3008
+ dimrange = range(int(lbound), int(ubound) + 1)
3009
+ else:
3010
+ raise ValueError('param_eval: multidimensional array parameters '
3011
+ f'{dimspec} not supported')
3012
+
3013
+ # Parse parameter value
3014
+ v = (v[2:-2] if v.startswith('(/') else v).split(',')
3015
+ v_eval = []
3016
+ for item in v:
3017
+ try:
3018
+ item = eval(item, g_params, params)
3019
+ except Exception as msg:
3020
+ outmess(f'param_eval: got "{msg}" on {item!r}\n')
3021
+ v_eval.append(item)
3022
+
3023
+ p = dict(zip(dimrange, v_eval))
3024
+
3025
+ return p
3026
+
3027
+
3028
+ def param_parse(d, params):
3029
+ """Recursively parse array dimensions.
3030
+
3031
+ Parses the declaration of an array variable or parameter
3032
+ `dimension` keyword, and is called recursively if the
3033
+ dimension for this array is a previously defined parameter
3034
+ (found in `params`).
3035
+
3036
+ Parameters
3037
+ ----------
3038
+ d : str
3039
+ Fortran expression describing the dimension of an array.
3040
+ params : dict
3041
+ Previously parsed parameters declared in the Fortran source file.
3042
+
3043
+ Returns
3044
+ -------
3045
+ out : str
3046
+ Parsed dimension expression.
3047
+
3048
+ Examples
3049
+ --------
3050
+
3051
+ * If the line being analyzed is
3052
+
3053
+ `integer, parameter, dimension(2) :: pa = (/ 3, 5 /)`
3054
+
3055
+ then `d = 2` and we return immediately, with
3056
+
3057
+ >>> d = '2'
3058
+ >>> param_parse(d, params)
3059
+ 2
3060
+
3061
+ * If the line being analyzed is
3062
+
3063
+ `integer, parameter, dimension(pa) :: pb = (/1, 2, 3/)`
3064
+
3065
+ then `d = 'pa'`; since `pa` is a previously parsed parameter,
3066
+ and `pa = 3`, we call `param_parse` recursively, to obtain
3067
+
3068
+ >>> d = 'pa'
3069
+ >>> params = {'pa': 3}
3070
+ >>> param_parse(d, params)
3071
+ 3
3072
+
3073
+ * If the line being analyzed is
3074
+
3075
+ `integer, parameter, dimension(pa(1)) :: pb = (/1, 2, 3/)`
3076
+
3077
+ then `d = 'pa(1)'`; since `pa` is a previously parsed parameter,
3078
+ and `pa(1) = 3`, we call `param_parse` recursively, to obtain
3079
+
3080
+ >>> d = 'pa(1)'
3081
+ >>> params = dict(pa={1: 3, 2: 5})
3082
+ >>> param_parse(d, params)
3083
+ 3
3084
+ """
3085
+ if "(" in d:
3086
+ # this dimension expression is an array
3087
+ dname = d[:d.find("(")]
3088
+ ddims = d[d.find("(") + 1:d.rfind(")")]
3089
+ # this dimension expression is also a parameter;
3090
+ # parse it recursively
3091
+ index = int(param_parse(ddims, params))
3092
+ return str(params[dname][index])
3093
+ elif d in params:
3094
+ return str(params[d])
3095
+ else:
3096
+ for p in params:
3097
+ re_1 = re.compile(
3098
+ r'(?P<before>.*?)\b' + p + r'\b(?P<after>.*)', re.I
3099
+ )
3100
+ m = re_1.match(d)
3101
+ while m:
3102
+ d = m.group('before') + \
3103
+ str(params[p]) + m.group('after')
3104
+ m = re_1.match(d)
3105
+ return d
3106
+
3107
+
3108
+ def expr2name(a, block, args=[]):
3109
+ orig_a = a
3110
+ a_is_expr = not analyzeargs_re_1.match(a)
3111
+ if a_is_expr: # `a` is an expression
3112
+ implicitrules, attrrules = buildimplicitrules(block)
3113
+ at = determineexprtype(a, block['vars'], implicitrules)
3114
+ na = 'e_'
3115
+ for c in a:
3116
+ c = c.lower()
3117
+ if c not in string.ascii_lowercase + string.digits:
3118
+ c = '_'
3119
+ na = na + c
3120
+ if na[-1] == '_':
3121
+ na = na + 'e'
3122
+ else:
3123
+ na = na + '_e'
3124
+ a = na
3125
+ while a in block['vars'] or a in block['args']:
3126
+ a = a + 'r'
3127
+ if a in args:
3128
+ k = 1
3129
+ while a + str(k) in args:
3130
+ k = k + 1
3131
+ a = a + str(k)
3132
+ if a_is_expr:
3133
+ block['vars'][a] = at
3134
+ else:
3135
+ if a not in block['vars']:
3136
+ block['vars'][a] = block['vars'].get(orig_a, {})
3137
+ if 'externals' in block and orig_a in block['externals'] + block['interfaced']:
3138
+ block['vars'][a] = setattrspec(block['vars'][a], 'external')
3139
+ return a
3140
+
3141
+
3142
+ def analyzeargs(block):
3143
+ setmesstext(block)
3144
+ implicitrules, _ = buildimplicitrules(block)
3145
+ if 'args' not in block:
3146
+ block['args'] = []
3147
+ args = []
3148
+ for a in block['args']:
3149
+ a = expr2name(a, block, args)
3150
+ args.append(a)
3151
+ block['args'] = args
3152
+ if 'entry' in block:
3153
+ for k, args1 in list(block['entry'].items()):
3154
+ for a in args1:
3155
+ if a not in block['vars']:
3156
+ block['vars'][a] = {}
3157
+
3158
+ for b in block['body']:
3159
+ if b['name'] in args:
3160
+ if 'externals' not in block:
3161
+ block['externals'] = []
3162
+ if b['name'] not in block['externals']:
3163
+ block['externals'].append(b['name'])
3164
+ if 'result' in block and block['result'] not in block['vars']:
3165
+ block['vars'][block['result']] = {}
3166
+ return block
3167
+
3168
+
3169
+ determineexprtype_re_1 = re.compile(r'\A\(.+?,.+?\)\Z', re.I)
3170
+ determineexprtype_re_2 = re.compile(r'\A[+-]?\d+(_(?P<name>\w+)|)\Z', re.I)
3171
+ determineexprtype_re_3 = re.compile(
3172
+ r'\A[+-]?[\d.]+[-\d+de.]*(_(?P<name>\w+)|)\Z', re.I)
3173
+ determineexprtype_re_4 = re.compile(r'\A\(.*\)\Z', re.I)
3174
+ determineexprtype_re_5 = re.compile(r'\A(?P<name>\w+)\s*\(.*?\)\s*\Z', re.I)
3175
+
3176
+
3177
+ def _ensure_exprdict(r):
3178
+ if isinstance(r, int):
3179
+ return {'typespec': 'integer'}
3180
+ if isinstance(r, float):
3181
+ return {'typespec': 'real'}
3182
+ if isinstance(r, complex):
3183
+ return {'typespec': 'complex'}
3184
+ if isinstance(r, dict):
3185
+ return r
3186
+ raise AssertionError(repr(r))
3187
+
3188
+
3189
+ def determineexprtype(expr, vars, rules={}):
3190
+ if expr in vars:
3191
+ return _ensure_exprdict(vars[expr])
3192
+ expr = expr.strip()
3193
+ if determineexprtype_re_1.match(expr):
3194
+ return {'typespec': 'complex'}
3195
+ m = determineexprtype_re_2.match(expr)
3196
+ if m:
3197
+ if 'name' in m.groupdict() and m.group('name'):
3198
+ outmess(
3199
+ f'determineexprtype: selected kind types not supported ({repr(expr)})\n')
3200
+ return {'typespec': 'integer'}
3201
+ m = determineexprtype_re_3.match(expr)
3202
+ if m:
3203
+ if 'name' in m.groupdict() and m.group('name'):
3204
+ outmess(
3205
+ f'determineexprtype: selected kind types not supported ({repr(expr)})\n')
3206
+ return {'typespec': 'real'}
3207
+ for op in ['+', '-', '*', '/']:
3208
+ for e in [x.strip() for x in markoutercomma(expr, comma=op).split('@' + op + '@')]:
3209
+ if e in vars:
3210
+ return _ensure_exprdict(vars[e])
3211
+ t = {}
3212
+ if determineexprtype_re_4.match(expr): # in parenthesis
3213
+ t = determineexprtype(expr[1:-1], vars, rules)
3214
+ else:
3215
+ m = determineexprtype_re_5.match(expr)
3216
+ if m:
3217
+ rn = m.group('name')
3218
+ t = determineexprtype(m.group('name'), vars, rules)
3219
+ if t and 'attrspec' in t:
3220
+ del t['attrspec']
3221
+ if not t:
3222
+ if rn[0] in rules:
3223
+ return _ensure_exprdict(rules[rn[0]])
3224
+ if expr[0] in '\'"':
3225
+ return {'typespec': 'character', 'charselector': {'*': '*'}}
3226
+ if not t:
3227
+ outmess(
3228
+ f'determineexprtype: could not determine expressions ({repr(expr)}) type.\n')
3229
+ return t
3230
+
3231
+ ######
3232
+
3233
+
3234
+ def crack2fortrangen(block, tab='\n', as_interface=False):
3235
+ global skipfuncs, onlyfuncs
3236
+
3237
+ setmesstext(block)
3238
+ ret = ''
3239
+ if isinstance(block, list):
3240
+ for g in block:
3241
+ if g and g['block'] in ['function', 'subroutine']:
3242
+ if g['name'] in skipfuncs:
3243
+ continue
3244
+ if onlyfuncs and g['name'] not in onlyfuncs:
3245
+ continue
3246
+ ret = ret + crack2fortrangen(g, tab, as_interface=as_interface)
3247
+ return ret
3248
+ prefix = ''
3249
+ name = ''
3250
+ args = ''
3251
+ blocktype = block['block']
3252
+ if blocktype == 'program':
3253
+ return ''
3254
+ argsl = []
3255
+ if 'name' in block:
3256
+ name = block['name']
3257
+ if 'args' in block:
3258
+ vars = block['vars']
3259
+ for a in block['args']:
3260
+ a = expr2name(a, block, argsl)
3261
+ if not isintent_callback(vars[a]):
3262
+ argsl.append(a)
3263
+ if block['block'] == 'function' or argsl:
3264
+ args = f"({','.join(argsl)})"
3265
+ f2pyenhancements = ''
3266
+ if 'f2pyenhancements' in block:
3267
+ for k in list(block['f2pyenhancements'].keys()):
3268
+ f2pyenhancements = (f"{f2pyenhancements}{tab + tabchar}{k} "
3269
+ f"{block['f2pyenhancements'][k]}")
3270
+ intent_lst = block.get('intent', [])[:]
3271
+ if blocktype == 'function' and 'callback' in intent_lst:
3272
+ intent_lst.remove('callback')
3273
+ if intent_lst:
3274
+ f2pyenhancements = (f"{f2pyenhancements}{tab + tabchar}"
3275
+ f"intent({','.join(intent_lst)}) {name}")
3276
+ use = ''
3277
+ if 'use' in block:
3278
+ use = use2fortran(block['use'], tab + tabchar)
3279
+ common = ''
3280
+ if 'common' in block:
3281
+ common = common2fortran(block['common'], tab + tabchar)
3282
+ if name == 'unknown_interface':
3283
+ name = ''
3284
+ result = ''
3285
+ if 'result' in block:
3286
+ result = f" result ({block['result']})"
3287
+ if block['result'] not in argsl:
3288
+ argsl.append(block['result'])
3289
+ body = crack2fortrangen(block['body'], tab + tabchar, as_interface=as_interface)
3290
+ vars = vars2fortran(
3291
+ block, block['vars'], argsl, tab + tabchar, as_interface=as_interface)
3292
+ mess = ''
3293
+ if 'from' in block and not as_interface:
3294
+ mess = f"! in {block['from']}"
3295
+ if 'entry' in block:
3296
+ entry_stmts = ''
3297
+ for k, i in list(block['entry'].items()):
3298
+ entry_stmts = f"{entry_stmts}{tab + tabchar}entry {k}({','.join(i)})"
3299
+ body = body + entry_stmts
3300
+ if blocktype == 'block data' and name == '_BLOCK_DATA_':
3301
+ name = ''
3302
+ ret = (f'{tab}{prefix}{blocktype} {name}{args}{result} '
3303
+ f'{mess}{f2pyenhancements}{use}{vars}{common}{body}{tab}end '
3304
+ f'{blocktype} {name}')
3305
+ return ret
3306
+
3307
+
3308
+ def common2fortran(common, tab=''):
3309
+ ret = ''
3310
+ for k in list(common.keys()):
3311
+ if k == '_BLNK_':
3312
+ ret = f"{ret}{tab}common {','.join(common[k])}"
3313
+ else:
3314
+ ret = f"{ret}{tab}common /{k}/ {','.join(common[k])}"
3315
+ return ret
3316
+
3317
+
3318
+ def use2fortran(use, tab=''):
3319
+ ret = ''
3320
+ for m in list(use.keys()):
3321
+ ret = f'{ret}{tab}use {m},'
3322
+ if use[m] == {}:
3323
+ if ret and ret[-1] == ',':
3324
+ ret = ret[:-1]
3325
+ continue
3326
+ if 'only' in use[m] and use[m]['only']:
3327
+ ret = f'{ret} only:'
3328
+ if 'map' in use[m] and use[m]['map']:
3329
+ c = ' '
3330
+ for k in list(use[m]['map'].keys()):
3331
+ if k == use[m]['map'][k]:
3332
+ ret = f'{ret}{c}{k}'
3333
+ c = ','
3334
+ else:
3335
+ ret = f"{ret}{c}{k}=>{use[m]['map'][k]}"
3336
+ c = ','
3337
+ if ret and ret[-1] == ',':
3338
+ ret = ret[:-1]
3339
+ return ret
3340
+
3341
+
3342
+ def true_intent_list(var):
3343
+ lst = var['intent']
3344
+ ret = []
3345
+ for intent in lst:
3346
+ try:
3347
+ f = globals()[f'isintent_{intent}']
3348
+ except KeyError:
3349
+ pass
3350
+ else:
3351
+ if f(var):
3352
+ ret.append(intent)
3353
+ return ret
3354
+
3355
+
3356
+ def vars2fortran(block, vars, args, tab='', as_interface=False):
3357
+ setmesstext(block)
3358
+ ret = ''
3359
+ nout = []
3360
+ for a in args:
3361
+ if a in block['vars']:
3362
+ nout.append(a)
3363
+ if 'commonvars' in block:
3364
+ for a in block['commonvars']:
3365
+ if a in vars:
3366
+ if a not in nout:
3367
+ nout.append(a)
3368
+ else:
3369
+ errmess(
3370
+ f'vars2fortran: Confused?!: "{a}" is not defined in vars.\n')
3371
+ if 'varnames' in block:
3372
+ nout.extend(block['varnames'])
3373
+ if not as_interface:
3374
+ for a in list(vars.keys()):
3375
+ if a not in nout:
3376
+ nout.append(a)
3377
+ for a in nout:
3378
+ if 'depend' in vars[a]:
3379
+ for d in vars[a]['depend']:
3380
+ if d in vars and 'depend' in vars[d] and a in vars[d]['depend']:
3381
+ errmess(
3382
+ f'vars2fortran: Warning: cross-dependence between variables "{a}" and "{d}\"\n')
3383
+ if 'externals' in block and a in block['externals']:
3384
+ if isintent_callback(vars[a]):
3385
+ ret = f'{ret}{tab}intent(callback) {a}'
3386
+ ret = f'{ret}{tab}external {a}'
3387
+ if isoptional(vars[a]):
3388
+ ret = f'{ret}{tab}optional {a}'
3389
+ if a in vars and 'typespec' not in vars[a]:
3390
+ continue
3391
+ cont = 1
3392
+ for b in block['body']:
3393
+ if a == b['name'] and b['block'] == 'function':
3394
+ cont = 0
3395
+ break
3396
+ if cont:
3397
+ continue
3398
+ if a not in vars:
3399
+ show(vars)
3400
+ outmess(f'vars2fortran: No definition for argument "{a}".\n')
3401
+ continue
3402
+ if a == block['name']:
3403
+ if block['block'] != 'function' or block.get('result'):
3404
+ # 1) skip declaring a variable that name matches with
3405
+ # subroutine name
3406
+ # 2) skip declaring function when its type is
3407
+ # declared via `result` construction
3408
+ continue
3409
+ if 'typespec' not in vars[a]:
3410
+ if 'attrspec' in vars[a] and 'external' in vars[a]['attrspec']:
3411
+ if a in args:
3412
+ ret = f'{ret}{tab}external {a}'
3413
+ continue
3414
+ show(vars[a])
3415
+ outmess(f'vars2fortran: No typespec for argument "{a}".\n')
3416
+ continue
3417
+ vardef = vars[a]['typespec']
3418
+ if vardef == 'type' and 'typename' in vars[a]:
3419
+ vardef = f"{vardef}({vars[a]['typename']})"
3420
+ selector = {}
3421
+ if 'kindselector' in vars[a]:
3422
+ selector = vars[a]['kindselector']
3423
+ elif 'charselector' in vars[a]:
3424
+ selector = vars[a]['charselector']
3425
+ if '*' in selector:
3426
+ if selector['*'] in ['*', ':']:
3427
+ vardef = f"{vardef}*({selector['*']})"
3428
+ else:
3429
+ vardef = f"{vardef}*{selector['*']}"
3430
+ elif 'len' in selector:
3431
+ vardef = f"{vardef}(len={selector['len']}"
3432
+ if 'kind' in selector:
3433
+ vardef = f"{vardef},kind={selector['kind']})"
3434
+ else:
3435
+ vardef = f'{vardef})'
3436
+ elif 'kind' in selector:
3437
+ vardef = f"{vardef}(kind={selector['kind']})"
3438
+ c = ' '
3439
+ if 'attrspec' in vars[a]:
3440
+ attr = [l for l in vars[a]['attrspec']
3441
+ if l not in ['external']]
3442
+ if as_interface and 'intent(in)' in attr and 'intent(out)' in attr:
3443
+ # In Fortran, intent(in, out) are conflicting while
3444
+ # intent(in, out) can be specified only via
3445
+ # `!f2py intent(out) ..`.
3446
+ # So, for the Fortran interface, we'll drop
3447
+ # intent(out) to resolve the conflict.
3448
+ attr.remove('intent(out)')
3449
+ if attr:
3450
+ vardef = f"{vardef}, {','.join(attr)}"
3451
+ c = ','
3452
+ if 'dimension' in vars[a]:
3453
+ vardef = f"{vardef}{c}dimension({','.join(vars[a]['dimension'])})"
3454
+ c = ','
3455
+ if 'intent' in vars[a]:
3456
+ lst = true_intent_list(vars[a])
3457
+ if lst:
3458
+ vardef = f"{vardef}{c}intent({','.join(lst)})"
3459
+ c = ','
3460
+ if 'check' in vars[a]:
3461
+ vardef = f"{vardef}{c}check({','.join(vars[a]['check'])})"
3462
+ c = ','
3463
+ if 'depend' in vars[a]:
3464
+ vardef = f"{vardef}{c}depend({','.join(vars[a]['depend'])})"
3465
+ c = ','
3466
+ if '=' in vars[a]:
3467
+ v = vars[a]['=']
3468
+ if vars[a]['typespec'] in ['complex', 'double complex']:
3469
+ try:
3470
+ v = eval(v)
3471
+ v = f'({v.real},{v.imag})'
3472
+ except Exception:
3473
+ pass
3474
+ vardef = f'{vardef} :: {a}={v}'
3475
+ else:
3476
+ vardef = f'{vardef} :: {a}'
3477
+ ret = f'{ret}{tab}{vardef}'
3478
+ return ret
3479
+ ######
3480
+
3481
+
3482
+ # We expose post_processing_hooks as global variable so that
3483
+ # user-libraries could register their own hooks to f2py.
3484
+ post_processing_hooks = []
3485
+
3486
+
3487
+ def crackfortran(files):
3488
+ global usermodules, post_processing_hooks
3489
+
3490
+ outmess('Reading fortran codes...\n', 0)
3491
+ readfortrancode(files, crackline)
3492
+ outmess('Post-processing...\n', 0)
3493
+ usermodules = []
3494
+ postlist = postcrack(grouplist[0])
3495
+ outmess('Applying post-processing hooks...\n', 0)
3496
+ for hook in post_processing_hooks:
3497
+ outmess(f' {hook.__name__}\n', 0)
3498
+ postlist = traverse(postlist, hook)
3499
+ outmess('Post-processing (stage 2)...\n', 0)
3500
+ postlist = postcrack2(postlist)
3501
+ return usermodules + postlist
3502
+
3503
+
3504
+ def crack2fortran(block):
3505
+ global f2py_version
3506
+
3507
+ pyf = crack2fortrangen(block) + '\n'
3508
+ header = """! -*- f90 -*-
3509
+ ! Note: the context of this file is case sensitive.
3510
+ """
3511
+ footer = f"""
3512
+ ! This file was auto-generated with f2py (version:{f2py_version}).
3513
+ ! See:
3514
+ ! https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e
3515
+ """
3516
+ return header + pyf + footer
3517
+
3518
+
3519
+ def _is_visit_pair(obj):
3520
+ return (isinstance(obj, tuple)
3521
+ and len(obj) == 2
3522
+ and isinstance(obj[0], (int, str)))
3523
+
3524
+
3525
+ def traverse(obj, visit, parents=[], result=None, *args, **kwargs):
3526
+ '''Traverse f2py data structure with the following visit function:
3527
+
3528
+ def visit(item, parents, result, *args, **kwargs):
3529
+ """
3530
+
3531
+ parents is a list of key-"f2py data structure" pairs from which
3532
+ items are taken from.
3533
+
3534
+ result is a f2py data structure that is filled with the
3535
+ return value of the visit function.
3536
+
3537
+ item is 2-tuple (index, value) if parents[-1][1] is a list
3538
+ item is 2-tuple (key, value) if parents[-1][1] is a dict
3539
+
3540
+ The return value of visit must be None, or of the same kind as
3541
+ item, that is, if parents[-1] is a list, the return value must
3542
+ be 2-tuple (new_index, new_value), or if parents[-1] is a
3543
+ dict, the return value must be 2-tuple (new_key, new_value).
3544
+
3545
+ If new_index or new_value is None, the return value of visit
3546
+ is ignored, that is, it will not be added to the result.
3547
+
3548
+ If the return value is None, the content of obj will be
3549
+ traversed, otherwise not.
3550
+ """
3551
+ '''
3552
+
3553
+ if _is_visit_pair(obj):
3554
+ if obj[0] == 'parent_block':
3555
+ # avoid infinite recursion
3556
+ return obj
3557
+ new_result = visit(obj, parents, result, *args, **kwargs)
3558
+ if new_result is not None:
3559
+ assert _is_visit_pair(new_result)
3560
+ return new_result
3561
+ parent = obj
3562
+ result_key, obj = obj
3563
+ else:
3564
+ parent = (None, obj)
3565
+ result_key = None
3566
+
3567
+ if isinstance(obj, list):
3568
+ new_result = []
3569
+ for index, value in enumerate(obj):
3570
+ new_index, new_item = traverse((index, value), visit,
3571
+ parents + [parent], result,
3572
+ *args, **kwargs)
3573
+ if new_index is not None:
3574
+ new_result.append(new_item)
3575
+ elif isinstance(obj, dict):
3576
+ new_result = {}
3577
+ for key, value in obj.items():
3578
+ new_key, new_value = traverse((key, value), visit,
3579
+ parents + [parent], result,
3580
+ *args, **kwargs)
3581
+ if new_key is not None:
3582
+ new_result[new_key] = new_value
3583
+ else:
3584
+ new_result = obj
3585
+
3586
+ if result_key is None:
3587
+ return new_result
3588
+ return result_key, new_result
3589
+
3590
+
3591
+ def character_backward_compatibility_hook(item, parents, result,
3592
+ *args, **kwargs):
3593
+ """Previously, Fortran character was incorrectly treated as
3594
+ character*1. This hook fixes the usage of the corresponding
3595
+ variables in `check`, `dimension`, `=`, and `callstatement`
3596
+ expressions.
3597
+
3598
+ The usage of `char*` in `callprotoargument` expression can be left
3599
+ unchanged because C `character` is C typedef of `char`, although,
3600
+ new implementations should use `character*` in the corresponding
3601
+ expressions.
3602
+
3603
+ See https://github.com/numpy/numpy/pull/19388 for more information.
3604
+
3605
+ """
3606
+ parent_key, parent_value = parents[-1]
3607
+ key, value = item
3608
+
3609
+ def fix_usage(varname, value):
3610
+ value = re.sub(r'[*]\s*\b' + varname + r'\b', varname, value)
3611
+ value = re.sub(r'\b' + varname + r'\b\s*[\[]\s*0\s*[\]]',
3612
+ varname, value)
3613
+ return value
3614
+
3615
+ if parent_key in ['dimension', 'check']:
3616
+ assert parents[-3][0] == 'vars'
3617
+ vars_dict = parents[-3][1]
3618
+ elif key == '=':
3619
+ assert parents[-2][0] == 'vars'
3620
+ vars_dict = parents[-2][1]
3621
+ else:
3622
+ vars_dict = None
3623
+
3624
+ new_value = None
3625
+ if vars_dict is not None:
3626
+ new_value = value
3627
+ for varname, vd in vars_dict.items():
3628
+ if ischaracter(vd):
3629
+ new_value = fix_usage(varname, new_value)
3630
+ elif key == 'callstatement':
3631
+ vars_dict = parents[-2][1]['vars']
3632
+ new_value = value
3633
+ for varname, vd in vars_dict.items():
3634
+ if ischaracter(vd):
3635
+ # replace all occurrences of `<varname>` with
3636
+ # `&<varname>` in argument passing
3637
+ new_value = re.sub(
3638
+ r'(?<![&])\b' + varname + r'\b', '&' + varname, new_value)
3639
+
3640
+ if new_value is not None:
3641
+ if new_value != value:
3642
+ # We report the replacements here so that downstream
3643
+ # software could update their source codes
3644
+ # accordingly. However, such updates are recommended only
3645
+ # when BC with numpy 1.21 or older is not required.
3646
+ outmess(f'character_bc_hook[{parent_key}.{key}]:'
3647
+ f' replaced `{value}` -> `{new_value}`\n', 1)
3648
+ return (key, new_value)
3649
+
3650
+
3651
+ post_processing_hooks.append(character_backward_compatibility_hook)
3652
+
3653
+
3654
+ if __name__ == "__main__":
3655
+ files = []
3656
+ funcs = []
3657
+ f = 1
3658
+ f2 = 0
3659
+ f3 = 0
3660
+ showblocklist = 0
3661
+ for l in sys.argv[1:]:
3662
+ if l == '':
3663
+ pass
3664
+ elif l[0] == ':':
3665
+ f = 0
3666
+ elif l == '-quiet':
3667
+ quiet = 1
3668
+ verbose = 0
3669
+ elif l == '-verbose':
3670
+ verbose = 2
3671
+ quiet = 0
3672
+ elif l == '-fix':
3673
+ if strictf77:
3674
+ outmess(
3675
+ 'Use option -f90 before -fix if Fortran 90 code is in fix form.\n', 0)
3676
+ skipemptyends = 1
3677
+ sourcecodeform = 'fix'
3678
+ elif l == '-skipemptyends':
3679
+ skipemptyends = 1
3680
+ elif l == '--ignore-contains':
3681
+ ignorecontains = 1
3682
+ elif l == '-f77':
3683
+ strictf77 = 1
3684
+ sourcecodeform = 'fix'
3685
+ elif l == '-f90':
3686
+ strictf77 = 0
3687
+ sourcecodeform = 'free'
3688
+ skipemptyends = 1
3689
+ elif l == '-h':
3690
+ f2 = 1
3691
+ elif l == '-show':
3692
+ showblocklist = 1
3693
+ elif l == '-m':
3694
+ f3 = 1
3695
+ elif l[0] == '-':
3696
+ errmess(f'Unknown option {repr(l)}\n')
3697
+ elif f2:
3698
+ f2 = 0
3699
+ pyffilename = l
3700
+ elif f3:
3701
+ f3 = 0
3702
+ f77modulename = l
3703
+ elif f:
3704
+ try:
3705
+ open(l).close()
3706
+ files.append(l)
3707
+ except OSError as detail:
3708
+ errmess(f'OSError: {detail!s}\n')
3709
+ else:
3710
+ funcs.append(l)
3711
+ if not strictf77 and f77modulename and not skipemptyends:
3712
+ outmess("""\
3713
+ Warning: You have specified module name for non Fortran 77 code that
3714
+ should not need one (expect if you are scanning F90 code for non
3715
+ module blocks but then you should use flag -skipemptyends and also
3716
+ be sure that the files do not contain programs without program
3717
+ statement).
3718
+ """, 0)
3719
+
3720
+ postlist = crackfortran(files)
3721
+ if pyffilename:
3722
+ outmess(f'Writing fortran code to file {repr(pyffilename)}\n', 0)
3723
+ pyf = crack2fortran(postlist)
3724
+ with open(pyffilename, 'w') as f:
3725
+ f.write(pyf)
3726
+ if showblocklist:
3727
+ show(postlist)