test_crackfortran.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. import importlib
  2. import time
  3. import pytest
  4. import numpy as np
  5. from numpy.f2py.crackfortran import markinnerspaces, nameargspattern
  6. from . import util
  7. from numpy.f2py import crackfortran
  8. import textwrap
  9. import contextlib
  10. import io
  11. class TestNoSpace(util.F2PyTest):
  12. # issue gh-15035: add handling for endsubroutine, endfunction with no space
  13. # between "end" and the block name
  14. sources = [util.getpath("tests", "src", "crackfortran", "gh15035.f")]
  15. def test_module(self):
  16. k = np.array([1, 2, 3], dtype=np.float64)
  17. w = np.array([1, 2, 3], dtype=np.float64)
  18. self.module.subb(k)
  19. assert np.allclose(k, w + 1)
  20. self.module.subc([w, k])
  21. assert np.allclose(k, w + 1)
  22. assert self.module.t0("23") == b"2"
  23. class TestPublicPrivate:
  24. def test_defaultPrivate(self):
  25. fpath = util.getpath("tests", "src", "crackfortran", "privatemod.f90")
  26. mod = crackfortran.crackfortran([str(fpath)])
  27. assert len(mod) == 1
  28. mod = mod[0]
  29. assert "private" in mod["vars"]["a"]["attrspec"]
  30. assert "public" not in mod["vars"]["a"]["attrspec"]
  31. assert "private" in mod["vars"]["b"]["attrspec"]
  32. assert "public" not in mod["vars"]["b"]["attrspec"]
  33. assert "private" not in mod["vars"]["seta"]["attrspec"]
  34. assert "public" in mod["vars"]["seta"]["attrspec"]
  35. def test_defaultPublic(self, tmp_path):
  36. fpath = util.getpath("tests", "src", "crackfortran", "publicmod.f90")
  37. mod = crackfortran.crackfortran([str(fpath)])
  38. assert len(mod) == 1
  39. mod = mod[0]
  40. assert "private" in mod["vars"]["a"]["attrspec"]
  41. assert "public" not in mod["vars"]["a"]["attrspec"]
  42. assert "private" not in mod["vars"]["seta"]["attrspec"]
  43. assert "public" in mod["vars"]["seta"]["attrspec"]
  44. def test_access_type(self, tmp_path):
  45. fpath = util.getpath("tests", "src", "crackfortran", "accesstype.f90")
  46. mod = crackfortran.crackfortran([str(fpath)])
  47. assert len(mod) == 1
  48. tt = mod[0]['vars']
  49. assert set(tt['a']['attrspec']) == {'private', 'bind(c)'}
  50. assert set(tt['b_']['attrspec']) == {'public', 'bind(c)'}
  51. assert set(tt['c']['attrspec']) == {'public'}
  52. def test_nowrap_private_proceedures(self, tmp_path):
  53. fpath = util.getpath("tests", "src", "crackfortran", "gh23879.f90")
  54. mod = crackfortran.crackfortran([str(fpath)])
  55. assert len(mod) == 1
  56. pyf = crackfortran.crack2fortran(mod)
  57. assert 'bar' not in pyf
  58. class TestModuleProcedure:
  59. def test_moduleOperators(self, tmp_path):
  60. fpath = util.getpath("tests", "src", "crackfortran", "operators.f90")
  61. mod = crackfortran.crackfortran([str(fpath)])
  62. assert len(mod) == 1
  63. mod = mod[0]
  64. assert "body" in mod and len(mod["body"]) == 9
  65. assert mod["body"][1]["name"] == "operator(.item.)"
  66. assert "implementedby" in mod["body"][1]
  67. assert mod["body"][1]["implementedby"] == \
  68. ["item_int", "item_real"]
  69. assert mod["body"][2]["name"] == "operator(==)"
  70. assert "implementedby" in mod["body"][2]
  71. assert mod["body"][2]["implementedby"] == ["items_are_equal"]
  72. assert mod["body"][3]["name"] == "assignment(=)"
  73. assert "implementedby" in mod["body"][3]
  74. assert mod["body"][3]["implementedby"] == \
  75. ["get_int", "get_real"]
  76. def test_notPublicPrivate(self, tmp_path):
  77. fpath = util.getpath("tests", "src", "crackfortran", "pubprivmod.f90")
  78. mod = crackfortran.crackfortran([str(fpath)])
  79. assert len(mod) == 1
  80. mod = mod[0]
  81. assert mod['vars']['a']['attrspec'] == ['private', ]
  82. assert mod['vars']['b']['attrspec'] == ['public', ]
  83. assert mod['vars']['seta']['attrspec'] == ['public', ]
  84. class TestExternal(util.F2PyTest):
  85. # issue gh-17859: add external attribute support
  86. sources = [util.getpath("tests", "src", "crackfortran", "gh17859.f")]
  87. def test_external_as_statement(self):
  88. def incr(x):
  89. return x + 123
  90. r = self.module.external_as_statement(incr)
  91. assert r == 123
  92. def test_external_as_attribute(self):
  93. def incr(x):
  94. return x + 123
  95. r = self.module.external_as_attribute(incr)
  96. assert r == 123
  97. class TestCrackFortran(util.F2PyTest):
  98. # gh-2848: commented lines between parameters in subroutine parameter lists
  99. sources = [util.getpath("tests", "src", "crackfortran", "gh2848.f90"),
  100. util.getpath("tests", "src", "crackfortran", "common_with_division.f")
  101. ]
  102. def test_gh2848(self):
  103. r = self.module.gh2848(1, 2)
  104. assert r == (1, 2)
  105. def test_common_with_division(self):
  106. assert len(self.module.mortmp.ctmp) == 11
  107. class TestMarkinnerspaces:
  108. # gh-14118: markinnerspaces does not handle multiple quotations
  109. def test_do_not_touch_normal_spaces(self):
  110. test_list = ["a ", " a", "a b c", "'abcdefghij'"]
  111. for i in test_list:
  112. assert markinnerspaces(i) == i
  113. def test_one_relevant_space(self):
  114. assert markinnerspaces("a 'b c' \\' \\'") == "a 'b@_@c' \\' \\'"
  115. assert markinnerspaces(r'a "b c" \" \"') == r'a "b@_@c" \" \"'
  116. def test_ignore_inner_quotes(self):
  117. assert markinnerspaces("a 'b c\" \" d' e") == "a 'b@_@c\"@_@\"@_@d' e"
  118. assert markinnerspaces("a \"b c' ' d\" e") == "a \"b@_@c'@_@'@_@d\" e"
  119. def test_multiple_relevant_spaces(self):
  120. assert markinnerspaces("a 'b c' 'd e'") == "a 'b@_@c' 'd@_@e'"
  121. assert markinnerspaces(r'a "b c" "d e"') == r'a "b@_@c" "d@_@e"'
  122. class TestDimSpec(util.F2PyTest):
  123. """This test suite tests various expressions that are used as dimension
  124. specifications.
  125. There exists two usage cases where analyzing dimensions
  126. specifications are important.
  127. In the first case, the size of output arrays must be defined based
  128. on the inputs to a Fortran function. Because Fortran supports
  129. arbitrary bases for indexing, for instance, `arr(lower:upper)`,
  130. f2py has to evaluate an expression `upper - lower + 1` where
  131. `lower` and `upper` are arbitrary expressions of input parameters.
  132. The evaluation is performed in C, so f2py has to translate Fortran
  133. expressions to valid C expressions (an alternative approach is
  134. that a developer specifies the corresponding C expressions in a
  135. .pyf file).
  136. In the second case, when user provides an input array with a given
  137. size but some hidden parameters used in dimensions specifications
  138. need to be determined based on the input array size. This is a
  139. harder problem because f2py has to solve the inverse problem: find
  140. a parameter `p` such that `upper(p) - lower(p) + 1` equals to the
  141. size of input array. In the case when this equation cannot be
  142. solved (e.g. because the input array size is wrong), raise an
  143. error before calling the Fortran function (that otherwise would
  144. likely crash Python process when the size of input arrays is
  145. wrong). f2py currently supports this case only when the equation
  146. is linear with respect to unknown parameter.
  147. """
  148. suffix = ".f90"
  149. code_template = textwrap.dedent("""
  150. function get_arr_size_{count}(a, n) result (length)
  151. integer, intent(in) :: n
  152. integer, dimension({dimspec}), intent(out) :: a
  153. integer length
  154. length = size(a)
  155. end function
  156. subroutine get_inv_arr_size_{count}(a, n)
  157. integer :: n
  158. ! the value of n is computed in f2py wrapper
  159. !f2py intent(out) n
  160. integer, dimension({dimspec}), intent(in) :: a
  161. if (a({first}).gt.0) then
  162. ! print*, "a=", a
  163. endif
  164. end subroutine
  165. """)
  166. linear_dimspecs = [
  167. "n", "2*n", "2:n", "n/2", "5 - n/2", "3*n:20", "n*(n+1):n*(n+5)",
  168. "2*n, n"
  169. ]
  170. nonlinear_dimspecs = ["2*n:3*n*n+2*n"]
  171. all_dimspecs = linear_dimspecs + nonlinear_dimspecs
  172. code = ""
  173. for count, dimspec in enumerate(all_dimspecs):
  174. lst = [(d.split(":")[0] if ":" in d else "1") for d in dimspec.split(',')]
  175. code += code_template.format(
  176. count=count,
  177. dimspec=dimspec,
  178. first=", ".join(lst),
  179. )
  180. @pytest.mark.parametrize("dimspec", all_dimspecs)
  181. @pytest.mark.slow
  182. def test_array_size(self, dimspec):
  183. count = self.all_dimspecs.index(dimspec)
  184. get_arr_size = getattr(self.module, f"get_arr_size_{count}")
  185. for n in [1, 2, 3, 4, 5]:
  186. sz, a = get_arr_size(n)
  187. assert a.size == sz
  188. @pytest.mark.parametrize("dimspec", all_dimspecs)
  189. def test_inv_array_size(self, dimspec):
  190. count = self.all_dimspecs.index(dimspec)
  191. get_arr_size = getattr(self.module, f"get_arr_size_{count}")
  192. get_inv_arr_size = getattr(self.module, f"get_inv_arr_size_{count}")
  193. for n in [1, 2, 3, 4, 5]:
  194. sz, a = get_arr_size(n)
  195. if dimspec in self.nonlinear_dimspecs:
  196. # one must specify n as input, the call we'll ensure
  197. # that a and n are compatible:
  198. n1 = get_inv_arr_size(a, n)
  199. else:
  200. # in case of linear dependence, n can be determined
  201. # from the shape of a:
  202. n1 = get_inv_arr_size(a)
  203. # n1 may be different from n (for instance, when `a` size
  204. # is a function of some `n` fraction) but it must produce
  205. # the same sized array
  206. sz1, _ = get_arr_size(n1)
  207. assert sz == sz1, (n, n1, sz, sz1)
  208. class TestModuleDeclaration:
  209. def test_dependencies(self, tmp_path):
  210. fpath = util.getpath("tests", "src", "crackfortran", "foo_deps.f90")
  211. mod = crackfortran.crackfortran([str(fpath)])
  212. assert len(mod) == 1
  213. assert mod[0]["vars"]["abar"]["="] == "bar('abar')"
  214. class TestEval(util.F2PyTest):
  215. def test_eval_scalar(self):
  216. eval_scalar = crackfortran._eval_scalar
  217. assert eval_scalar('123', {}) == '123'
  218. assert eval_scalar('12 + 3', {}) == '15'
  219. assert eval_scalar('a + b', dict(a=1, b=2)) == '3'
  220. assert eval_scalar('"123"', {}) == "'123'"
  221. class TestFortranReader(util.F2PyTest):
  222. @pytest.mark.parametrize("encoding",
  223. ['ascii', 'utf-8', 'utf-16', 'utf-32'])
  224. def test_input_encoding(self, tmp_path, encoding):
  225. # gh-635
  226. f_path = tmp_path / f"input_with_{encoding}_encoding.f90"
  227. with f_path.open('w', encoding=encoding) as ff:
  228. ff.write("""
  229. subroutine foo()
  230. end subroutine foo
  231. """)
  232. mod = crackfortran.crackfortran([str(f_path)])
  233. assert mod[0]['name'] == 'foo'
  234. @pytest.mark.slow
  235. class TestUnicodeComment(util.F2PyTest):
  236. sources = [util.getpath("tests", "src", "crackfortran", "unicode_comment.f90")]
  237. @pytest.mark.skipif(
  238. (importlib.util.find_spec("charset_normalizer") is None),
  239. reason="test requires charset_normalizer which is not installed",
  240. )
  241. def test_encoding_comment(self):
  242. self.module.foo(3)
  243. class TestNameArgsPatternBacktracking:
  244. @pytest.mark.parametrize(
  245. ['adversary'],
  246. [
  247. ('@)@bind@(@',),
  248. ('@)@bind @(@',),
  249. ('@)@bind foo bar baz@(@',)
  250. ]
  251. )
  252. def test_nameargspattern_backtracking(self, adversary):
  253. '''address ReDOS vulnerability:
  254. https://github.com/numpy/numpy/issues/23338'''
  255. trials_per_batch = 12
  256. batches_per_regex = 4
  257. start_reps, end_reps = 15, 25
  258. for ii in range(start_reps, end_reps):
  259. repeated_adversary = adversary * ii
  260. # test times in small batches.
  261. # this gives us more chances to catch a bad regex
  262. # while still catching it before too long if it is bad
  263. for _ in range(batches_per_regex):
  264. times = []
  265. for _ in range(trials_per_batch):
  266. t0 = time.perf_counter()
  267. mtch = nameargspattern.search(repeated_adversary)
  268. times.append(time.perf_counter() - t0)
  269. # our pattern should be much faster than 0.2s per search
  270. # it's unlikely that a bad regex will pass even on fast CPUs
  271. assert np.median(times) < 0.2
  272. assert not mtch
  273. # if the adversary is capped with @)@, it becomes acceptable
  274. # according to the old version of the regex.
  275. # that should still be true.
  276. good_version_of_adversary = repeated_adversary + '@)@'
  277. assert nameargspattern.search(good_version_of_adversary)
  278. class TestFunctionReturn(util.F2PyTest):
  279. sources = [util.getpath("tests", "src", "crackfortran", "gh23598.f90")]
  280. @pytest.mark.slow
  281. def test_function_rettype(self):
  282. # gh-23598
  283. assert self.module.intproduct(3, 4) == 12
  284. class TestFortranGroupCounters(util.F2PyTest):
  285. def test_end_if_comment(self):
  286. # gh-23533
  287. fpath = util.getpath("tests", "src", "crackfortran", "gh23533.f")
  288. try:
  289. crackfortran.crackfortran([str(fpath)])
  290. except Exception as exc:
  291. assert False, f"'crackfortran.crackfortran' raised an exception {exc}"
  292. class TestF77CommonBlockReader:
  293. def test_gh22648(self, tmp_path):
  294. fpath = util.getpath("tests", "src", "crackfortran", "gh22648.pyf")
  295. with contextlib.redirect_stdout(io.StringIO()) as stdout_f2py:
  296. mod = crackfortran.crackfortran([str(fpath)])
  297. assert "Mismatch" not in stdout_f2py.getvalue()
  298. class TestParamEval:
  299. # issue gh-11612, array parameter parsing
  300. def test_param_eval_nested(self):
  301. v = '(/3.14, 4./)'
  302. g_params = dict(kind=crackfortran._kind_func,
  303. selected_int_kind=crackfortran._selected_int_kind_func,
  304. selected_real_kind=crackfortran._selected_real_kind_func)
  305. params = {'dp': 8, 'intparamarray': {1: 3, 2: 5},
  306. 'nested': {1: 1, 2: 2, 3: 3}}
  307. dimspec = '(2)'
  308. ret = crackfortran.param_eval(v, g_params, params, dimspec=dimspec)
  309. assert ret == {1: 3.14, 2: 4.0}
  310. def test_param_eval_nonstandard_range(self):
  311. v = '(/ 6, 3, 1 /)'
  312. g_params = dict(kind=crackfortran._kind_func,
  313. selected_int_kind=crackfortran._selected_int_kind_func,
  314. selected_real_kind=crackfortran._selected_real_kind_func)
  315. params = {}
  316. dimspec = '(-1:1)'
  317. ret = crackfortran.param_eval(v, g_params, params, dimspec=dimspec)
  318. assert ret == {-1: 6, 0: 3, 1: 1}
  319. def test_param_eval_empty_range(self):
  320. v = '6'
  321. g_params = dict(kind=crackfortran._kind_func,
  322. selected_int_kind=crackfortran._selected_int_kind_func,
  323. selected_real_kind=crackfortran._selected_real_kind_func)
  324. params = {}
  325. dimspec = ''
  326. pytest.raises(ValueError, crackfortran.param_eval, v, g_params, params,
  327. dimspec=dimspec)
  328. def test_param_eval_non_array_param(self):
  329. v = '3.14_dp'
  330. g_params = dict(kind=crackfortran._kind_func,
  331. selected_int_kind=crackfortran._selected_int_kind_func,
  332. selected_real_kind=crackfortran._selected_real_kind_func)
  333. params = {}
  334. ret = crackfortran.param_eval(v, g_params, params, dimspec=None)
  335. assert ret == '3.14_dp'
  336. def test_param_eval_too_many_dims(self):
  337. v = 'reshape((/ (i, i=1, 250) /), (/5, 10, 5/))'
  338. g_params = dict(kind=crackfortran._kind_func,
  339. selected_int_kind=crackfortran._selected_int_kind_func,
  340. selected_real_kind=crackfortran._selected_real_kind_func)
  341. params = {}
  342. dimspec = '(0:4, 3:12, 5)'
  343. pytest.raises(ValueError, crackfortran.param_eval, v, g_params, params,
  344. dimspec=dimspec)
  345. @pytest.mark.slow
  346. class TestLowerF2PYDirective(util.F2PyTest):
  347. sources = [util.getpath("tests", "src", "crackfortran", "gh27697.f90")]
  348. options = ['--lower']
  349. def test_no_lower_fail(self):
  350. with pytest.raises(ValueError, match='aborting directly') as exc:
  351. self.module.utils.my_abort('aborting directly')