test_pgen2.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. """Test suite for 2to3's parser and grammar files.
  2. This is the place to add tests for changes to 2to3's grammar, such as those
  3. merging the grammars for Python 2 and 3. In addition to specific tests for
  4. parts of the grammar we've changed, we also make sure we can parse the
  5. test_grammar.py files from both Python 2 and Python 3.
  6. """
  7. from textwrap import dedent
  8. import pytest
  9. from parso import load_grammar
  10. from parso import ParserSyntaxError
  11. from parso.pgen2 import generate_grammar
  12. from parso.python import tokenize
  13. def _parse(code, version=None):
  14. code = dedent(code) + "\n\n"
  15. grammar = load_grammar(version=version)
  16. return grammar.parse(code, error_recovery=False)
  17. def _invalid_syntax(code, version=None, **kwargs):
  18. with pytest.raises(ParserSyntaxError):
  19. module = _parse(code, version=version, **kwargs)
  20. # For debugging
  21. print(module.children)
  22. def test_formfeed(each_version):
  23. s = u"foo\n\x0c\nfoo\n"
  24. t = _parse(s, each_version)
  25. assert t.children[0].children[0].type == 'name'
  26. assert t.children[1].children[0].type == 'name'
  27. s = u"1\n\x0c\x0c\n2\n"
  28. t = _parse(s, each_version)
  29. with pytest.raises(ParserSyntaxError):
  30. s = u"\n\x0c2\n"
  31. _parse(s, each_version)
  32. def test_matrix_multiplication_operator(works_ge_py35):
  33. works_ge_py35.parse("a @ b")
  34. works_ge_py35.parse("a @= b")
  35. def test_yield_from(works_ge_py3, each_version):
  36. works_ge_py3.parse("yield from x")
  37. works_ge_py3.parse("(yield from x) + y")
  38. _invalid_syntax("yield from", each_version)
  39. def test_await_expr(works_ge_py35):
  40. works_ge_py35.parse("""async def foo():
  41. await x
  42. """)
  43. works_ge_py35.parse("""async def foo():
  44. def foo(): pass
  45. def foo(): pass
  46. await x
  47. """)
  48. works_ge_py35.parse("""async def foo(): return await a""")
  49. works_ge_py35.parse("""def foo():
  50. def foo(): pass
  51. async def foo(): await x
  52. """)
  53. @pytest.mark.skipif('sys.version_info[:2] < (3, 5)')
  54. @pytest.mark.xfail(reason="acting like python 3.7")
  55. def test_async_var():
  56. _parse("""async = 1""", "3.5")
  57. _parse("""await = 1""", "3.5")
  58. _parse("""def async(): pass""", "3.5")
  59. def test_async_for(works_ge_py35):
  60. works_ge_py35.parse("async def foo():\n async for a in b: pass")
  61. @pytest.mark.parametrize("body", [
  62. """[1 async for a in b
  63. ]""",
  64. """[1 async
  65. for a in b
  66. ]""",
  67. """[
  68. 1
  69. async for a in b
  70. ]""",
  71. """[
  72. 1
  73. async for a
  74. in b
  75. ]""",
  76. """[
  77. 1
  78. async
  79. for
  80. a
  81. in
  82. b
  83. ]""",
  84. """ [
  85. 1 async for a in b
  86. ]""",
  87. ])
  88. def test_async_for_comprehension_newline(works_ge_py36, body):
  89. # Issue #139
  90. works_ge_py36.parse("""async def foo():
  91. {}""".format(body))
  92. def test_async_with(works_ge_py35):
  93. works_ge_py35.parse("async def foo():\n async with a: pass")
  94. @pytest.mark.skipif('sys.version_info[:2] < (3, 5)')
  95. @pytest.mark.xfail(reason="acting like python 3.7")
  96. def test_async_with_invalid():
  97. _invalid_syntax("""def foo():
  98. async with a: pass""", version="3.5")
  99. def test_raise_3x_style_1(each_version):
  100. _parse("raise", each_version)
  101. def test_raise_2x_style_2(works_in_py2):
  102. works_in_py2.parse("raise E, V")
  103. def test_raise_2x_style_3(works_in_py2):
  104. works_in_py2.parse("raise E, V, T")
  105. def test_raise_2x_style_invalid_1(each_version):
  106. _invalid_syntax("raise E, V, T, Z", version=each_version)
  107. def test_raise_3x_style(works_ge_py3):
  108. works_ge_py3.parse("raise E1 from E2")
  109. def test_raise_3x_style_invalid_1(each_version):
  110. _invalid_syntax("raise E, V from E1", each_version)
  111. def test_raise_3x_style_invalid_2(each_version):
  112. _invalid_syntax("raise E from E1, E2", each_version)
  113. def test_raise_3x_style_invalid_3(each_version):
  114. _invalid_syntax("raise from E1, E2", each_version)
  115. def test_raise_3x_style_invalid_4(each_version):
  116. _invalid_syntax("raise E from", each_version)
  117. # Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef
  118. def test_annotation_1(works_ge_py3):
  119. works_ge_py3.parse("""def f(x) -> list: pass""")
  120. def test_annotation_2(works_ge_py3):
  121. works_ge_py3.parse("""def f(x:int): pass""")
  122. def test_annotation_3(works_ge_py3):
  123. works_ge_py3.parse("""def f(*x:str): pass""")
  124. def test_annotation_4(works_ge_py3):
  125. works_ge_py3.parse("""def f(**x:float): pass""")
  126. def test_annotation_5(works_ge_py3):
  127. works_ge_py3.parse("""def f(x, y:1+2): pass""")
  128. def test_annotation_6(each_py3_version):
  129. _invalid_syntax("""def f(a, (b:1, c:2, d)): pass""", each_py3_version)
  130. def test_annotation_7(each_py3_version):
  131. _invalid_syntax("""def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6): pass""", each_py3_version)
  132. def test_annotation_8(each_py3_version):
  133. s = """def f(a, (b:1, c:2, d), e:3=4, f=5,
  134. *g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass"""
  135. _invalid_syntax(s, each_py3_version)
  136. def test_except_new(each_version):
  137. s = dedent("""
  138. try:
  139. x
  140. except E as N:
  141. y""")
  142. _parse(s, each_version)
  143. def test_except_old(works_in_py2):
  144. s = dedent("""
  145. try:
  146. x
  147. except E, N:
  148. y""")
  149. works_in_py2.parse(s)
  150. # Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testAtoms
  151. def test_set_literal_1(works_ge_py27):
  152. works_ge_py27.parse("""x = {'one'}""")
  153. def test_set_literal_2(works_ge_py27):
  154. works_ge_py27.parse("""x = {'one', 1,}""")
  155. def test_set_literal_3(works_ge_py27):
  156. works_ge_py27.parse("""x = {'one', 'two', 'three'}""")
  157. def test_set_literal_4(works_ge_py27):
  158. works_ge_py27.parse("""x = {2, 3, 4,}""")
  159. def test_new_octal_notation(each_version):
  160. _parse("""0o7777777777777""", each_version)
  161. _invalid_syntax("""0o7324528887""", each_version)
  162. def test_old_octal_notation(works_in_py2):
  163. works_in_py2.parse("07")
  164. def test_long_notation(works_in_py2):
  165. works_in_py2.parse("0xFl")
  166. works_in_py2.parse("0xFL")
  167. works_in_py2.parse("0b1l")
  168. works_in_py2.parse("0B1L")
  169. works_in_py2.parse("0o7l")
  170. works_in_py2.parse("0O7L")
  171. works_in_py2.parse("0l")
  172. works_in_py2.parse("0L")
  173. works_in_py2.parse("10l")
  174. works_in_py2.parse("10L")
  175. def test_new_binary_notation(each_version):
  176. _parse("""0b101010""", each_version)
  177. _invalid_syntax("""0b0101021""", each_version)
  178. def test_class_new_syntax(works_ge_py3):
  179. works_ge_py3.parse("class B(t=7): pass")
  180. works_ge_py3.parse("class B(t, *args): pass")
  181. works_ge_py3.parse("class B(t, **kwargs): pass")
  182. works_ge_py3.parse("class B(t, *args, **kwargs): pass")
  183. works_ge_py3.parse("class B(t, y=9, *args, **kwargs): pass")
  184. def test_parser_idempotency_extended_unpacking(works_ge_py3):
  185. """A cut-down version of pytree_idempotency.py."""
  186. works_ge_py3.parse("a, *b, c = x\n")
  187. works_ge_py3.parse("[*a, b] = x\n")
  188. works_ge_py3.parse("(z, *y, w) = m\n")
  189. works_ge_py3.parse("for *z, m in d: pass\n")
  190. def test_multiline_bytes_literals(each_version):
  191. """
  192. It's not possible to get the same result when using \xaa in Python 2/3,
  193. because it's treated differently.
  194. """
  195. s = u"""
  196. md5test(b"\xaa" * 80,
  197. (b"Test Using Larger Than Block-Size Key "
  198. b"and Larger Than One Block-Size Data"),
  199. "6f630fad67cda0ee1fb1f562db3aa53e")
  200. """
  201. _parse(s, each_version)
  202. def test_multiline_bytes_tripquote_literals(each_version):
  203. s = '''
  204. b"""
  205. <?xml version="1.0" encoding="UTF-8"?>
  206. <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN">
  207. """
  208. '''
  209. _parse(s, each_version)
  210. def test_ellipsis(works_ge_py3, each_version):
  211. works_ge_py3.parse("...")
  212. _parse("[0][...]", version=each_version)
  213. def test_dict_unpacking(works_ge_py35):
  214. works_ge_py35.parse("{**dict(a=3), foo:2}")
  215. def test_multiline_str_literals(each_version):
  216. s = u"""
  217. md5test("\xaa" * 80,
  218. ("Test Using Larger Than Block-Size Key "
  219. "and Larger Than One Block-Size Data"),
  220. "6f630fad67cda0ee1fb1f562db3aa53e")
  221. """
  222. _parse(s, each_version)
  223. def test_py2_backticks(works_in_py2):
  224. works_in_py2.parse("`1`")
  225. def test_py2_string_prefixes(works_in_py2):
  226. works_in_py2.parse("ur'1'")
  227. works_in_py2.parse("Ur'1'")
  228. works_in_py2.parse("UR'1'")
  229. _invalid_syntax("ru'1'", works_in_py2.version)
  230. def py_br(each_version):
  231. _parse('br""', each_version)
  232. def test_py3_rb(works_ge_py3):
  233. works_ge_py3.parse("rb'1'")
  234. works_ge_py3.parse("RB'1'")
  235. def test_left_recursion():
  236. with pytest.raises(ValueError, match='left recursion'):
  237. generate_grammar('foo: foo NAME\n', tokenize.PythonTokenTypes)
  238. @pytest.mark.parametrize(
  239. 'grammar, error_match', [
  240. ['foo: bar | baz\nbar: NAME\nbaz: NAME\n',
  241. r"foo is ambiguous.*given a TokenType\(NAME\).*bar or baz"],
  242. ['''foo: bar | baz\nbar: 'x'\nbaz: "x"\n''',
  243. r"foo is ambiguous.*given a ReservedString\(x\).*bar or baz"],
  244. ['''foo: bar | 'x'\nbar: 'x'\n''',
  245. r"foo is ambiguous.*given a ReservedString\(x\).*bar or foo"],
  246. # An ambiguity with the second (not the first) child of a production
  247. ['outer: "a" [inner] "b" "c"\ninner: "b" "c" [inner]\n',
  248. r"outer is ambiguous.*given a ReservedString\(b\).*inner or outer"],
  249. # An ambiguity hidden by a level of indirection (middle)
  250. ['outer: "a" [middle] "b" "c"\nmiddle: inner\ninner: "b" "c" [inner]\n',
  251. r"outer is ambiguous.*given a ReservedString\(b\).*middle or outer"],
  252. ]
  253. )
  254. def test_ambiguities(grammar, error_match):
  255. with pytest.raises(ValueError, match=error_match):
  256. generate_grammar(grammar, tokenize.PythonTokenTypes)