test_crackfortran.py 13 KB

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