This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

678 lines
24 KiB

  1. from __future__ import absolute_import
  2. import unittest
  3. import logging
  4. import os
  5. import sys
  6. try:
  7. from cStringIO import StringIO as cStringIO
  8. except ImportError:
  9. # Available only in Python 2.x, 3.x only has io.StringIO from below
  10. cStringIO = None
  11. from io import (
  12. StringIO as uStringIO,
  13. open,
  14. )
  15. logging.basicConfig(level=logging.INFO)
  16. from lark.lark import Lark
  17. from lark.common import GrammarError, ParseError
  18. from lark.lexer import LexError
  19. from lark.tree import Tree
  20. __path__ = os.path.dirname(__file__)
  21. def _read(n, *args):
  22. with open(os.path.join(__path__, n), *args) as f:
  23. return f.read()
  24. class TestParsers(unittest.TestCase):
  25. def test_same_ast(self):
  26. "Tests that Earley and LALR parsers produce equal trees"
  27. g = Lark("""start: "(" name_list ("," "*" NAME)? ")"
  28. name_list: NAME | name_list "," NAME
  29. NAME: /\w+/ """, parser='lalr')
  30. l = g.parse('(a,b,c,*x)')
  31. g = Lark("""start: "(" name_list ("," "*" NAME)? ")"
  32. name_list: NAME | name_list "," NAME
  33. NAME: /\w/+ """)
  34. l2 = g.parse('(a,b,c,*x)')
  35. assert l == l2, '%s != %s' % (l.pretty(), l2.pretty())
  36. def test_infinite_recurse(self):
  37. g = """start: a
  38. a: a | "a"
  39. """
  40. self.assertRaises(GrammarError, Lark, g, parser='lalr')
  41. l = Lark(g, parser='earley')
  42. self.assertRaises(ParseError, l.parse, 'a')
  43. def _make_full_earley_test(LEXER):
  44. class _TestFullEarley(unittest.TestCase):
  45. def test_anon_in_scanless(self):
  46. # Fails an Earley implementation without special handling for empty rules,
  47. # or re-processing of already completed rules.
  48. g = Lark(r"""start: B
  49. B: ("ab"|/[^b]/)*
  50. """, lexer=LEXER)
  51. self.assertEqual( g.parse('abc').children[0], 'abc')
  52. def test_earley_scanless(self):
  53. g = Lark("""start: A "b" c
  54. A: "a"+
  55. c: "abc"
  56. """, parser="earley", lexer=LEXER)
  57. x = g.parse('aaaababc')
  58. def test_earley_scanless2(self):
  59. grammar = """
  60. start: statement+
  61. statement: "r"
  62. | "c" /[a-z]/+
  63. %ignore " "
  64. """
  65. program = """c b r"""
  66. l = Lark(grammar, parser='earley', lexer=LEXER)
  67. l.parse(program)
  68. def test_earley_scanless3(self):
  69. "Tests prioritization and disambiguation for pseudo-terminals (there should be only one result)"
  70. grammar = """
  71. start: A A
  72. A: "a"+
  73. """
  74. l = Lark(grammar, parser='earley', lexer=LEXER)
  75. res = l.parse("aaa")
  76. self.assertEqual(res.children, ['aa', 'a'])
  77. def test_earley_scanless4(self):
  78. grammar = """
  79. start: A A?
  80. A: "a"+
  81. """
  82. l = Lark(grammar, parser='earley', lexer=LEXER)
  83. res = l.parse("aaa")
  84. self.assertEqual(res.children, ['aaa'])
  85. def test_earley_repeating_empty(self):
  86. # This was a sneaky bug!
  87. grammar = """
  88. !start: "a" empty empty "b"
  89. empty: empty2
  90. empty2:
  91. """
  92. parser = Lark(grammar, parser='earley', lexer=LEXER)
  93. res = parser.parse('ab')
  94. empty_tree = Tree('empty', [Tree('empty2', [])])
  95. self.assertSequenceEqual(res.children, ['a', empty_tree, empty_tree, 'b'])
  96. def test_earley_explicit_ambiguity(self):
  97. # This was a sneaky bug!
  98. grammar = """
  99. start: a b | ab
  100. a: "a"
  101. b: "b"
  102. ab: "ab"
  103. """
  104. parser = Lark(grammar, parser='earley', lexer=LEXER, ambiguity='explicit')
  105. res = parser.parse('ab')
  106. self.assertEqual( res.data, '_ambig')
  107. self.assertEqual( len(res.children), 2)
  108. _NAME = "TestFullEarley" + (LEXER or 'Scanless').capitalize()
  109. _TestFullEarley.__name__ = _NAME
  110. globals()[_NAME] = _TestFullEarley
  111. def _make_parser_test(LEXER, PARSER):
  112. def _Lark(grammar, **kwargs):
  113. return Lark(grammar, lexer=LEXER, parser=PARSER, **kwargs)
  114. class _TestParser(unittest.TestCase):
  115. def test_basic1(self):
  116. g = _Lark("""start: a+ b a* "b" a*
  117. b: "b"
  118. a: "a"
  119. """)
  120. r = g.parse('aaabaab')
  121. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  122. r = g.parse('aaabaaba')
  123. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  124. self.assertRaises(ParseError, g.parse, 'aaabaa')
  125. def test_basic2(self):
  126. # Multiple parsers and colliding tokens
  127. g = _Lark("""start: B A
  128. B: "12"
  129. A: "1" """)
  130. g2 = _Lark("""start: B A
  131. B: "12"
  132. A: "2" """)
  133. x = g.parse('121')
  134. assert x.data == 'start' and x.children == ['12', '1'], x
  135. x = g2.parse('122')
  136. assert x.data == 'start' and x.children == ['12', '2'], x
  137. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  138. def test_stringio_bytes(self):
  139. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  140. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  141. def test_stringio_unicode(self):
  142. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  143. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  144. def test_unicode(self):
  145. g = _Lark(u"""start: UNIA UNIB UNIA
  146. UNIA: /\xa3/
  147. UNIB: /\u0101/
  148. """)
  149. g.parse(u'\xa3\u0101\u00a3')
  150. @unittest.skipIf(LEXER is None, "Regexps >1 not supported with scanless parsing")
  151. def test_unicode2(self):
  152. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  153. UNIA: /\xa3/
  154. UNIB: "a\u0101b\ "
  155. UNIC: /a?\u0101c\n/
  156. """)
  157. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  158. def test_unicode3(self):
  159. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  160. UNIA: /\xa3/
  161. UNIB: "\u0101"
  162. UNIC: /\u0203/ /\n/
  163. """)
  164. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  165. def test_stack_for_ebnf(self):
  166. """Verify that stack depth isn't an issue for EBNF grammars"""
  167. g = _Lark(r"""start: a+
  168. a : "a" """)
  169. g.parse("a" * (sys.getrecursionlimit()*2 ))
  170. def test_expand1_lists_with_one_item(self):
  171. g = _Lark(r"""start: list
  172. ?list: item+
  173. item : A
  174. A: "a"
  175. """)
  176. r = g.parse("a")
  177. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  178. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  179. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  180. self.assertEqual(len(r.children), 1)
  181. def test_expand1_lists_with_one_item_2(self):
  182. g = _Lark(r"""start: list
  183. ?list: item+ "!"
  184. item : A
  185. A: "a"
  186. """)
  187. r = g.parse("a!")
  188. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  189. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  190. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  191. self.assertEqual(len(r.children), 1)
  192. def test_dont_expand1_lists_with_multiple_items(self):
  193. g = _Lark(r"""start: list
  194. ?list: item+
  195. item : A
  196. A: "a"
  197. """)
  198. r = g.parse("aa")
  199. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  200. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  201. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  202. self.assertEqual(len(r.children), 1)
  203. # Sanity check: verify that 'list' contains the two 'item's we've given it
  204. [list] = r.children
  205. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  206. def test_dont_expand1_lists_with_multiple_items_2(self):
  207. g = _Lark(r"""start: list
  208. ?list: item+ "!"
  209. item : A
  210. A: "a"
  211. """)
  212. r = g.parse("aa!")
  213. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  214. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  215. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  216. self.assertEqual(len(r.children), 1)
  217. # Sanity check: verify that 'list' contains the two 'item's we've given it
  218. [list] = r.children
  219. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  220. def test_empty_expand1_list(self):
  221. g = _Lark(r"""start: list
  222. ?list: item*
  223. item : A
  224. A: "a"
  225. """)
  226. r = g.parse("")
  227. # because 'list' is an expand-if-contains-one rule and we've provided less than one element (i.e. none) it should *not* have expanded
  228. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  229. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  230. self.assertEqual(len(r.children), 1)
  231. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  232. [list] = r.children
  233. self.assertSequenceEqual([item.data for item in list.children], ())
  234. def test_empty_expand1_list_2(self):
  235. g = _Lark(r"""start: list
  236. ?list: item* "!"?
  237. item : A
  238. A: "a"
  239. """)
  240. r = g.parse("")
  241. # because 'list' is an expand-if-contains-one rule and we've provided less than one element (i.e. none) it should *not* have expanded
  242. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  243. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  244. self.assertEqual(len(r.children), 1)
  245. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  246. [list] = r.children
  247. self.assertSequenceEqual([item.data for item in list.children], ())
  248. def test_empty_flatten_list(self):
  249. g = _Lark(r"""start: list
  250. list: | item "," list
  251. item : A
  252. A: "a"
  253. """)
  254. r = g.parse("")
  255. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  256. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  257. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  258. [list] = r.children
  259. self.assertSequenceEqual([item.data for item in list.children], ())
  260. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  261. def test_single_item_flatten_list(self):
  262. g = _Lark(r"""start: list
  263. list: | item "," list
  264. item : A
  265. A: "a"
  266. """)
  267. r = g.parse("a,")
  268. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  269. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  270. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  271. [list] = r.children
  272. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  273. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  274. def test_multiple_item_flatten_list(self):
  275. g = _Lark(r"""start: list
  276. #list: | item "," list
  277. item : A
  278. A: "a"
  279. """)
  280. r = g.parse("a,a,")
  281. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  282. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  283. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  284. [list] = r.children
  285. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  286. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  287. def test_recurse_flatten(self):
  288. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  289. g = _Lark(r"""start: a | start a
  290. a : A
  291. A : "a" """)
  292. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  293. # STree data structures, which uses recursion).
  294. g.parse("a" * (sys.getrecursionlimit() // 4))
  295. def test_token_collision(self):
  296. g = _Lark("""start: "Hello" NAME
  297. NAME: /\w/+
  298. %ignore " "
  299. """)
  300. x = g.parse('Hello World')
  301. self.assertSequenceEqual(x.children, ['World'])
  302. x = g.parse('Hello HelloWorld')
  303. self.assertSequenceEqual(x.children, ['HelloWorld'])
  304. def test_token_collision2(self):
  305. # NOTE: This test reveals a bug in token reconstruction in Scanless Earley
  306. # I probably need to re-write grammar transformation
  307. g = _Lark("""
  308. !start: "starts"
  309. %import common.LCASE_LETTER
  310. """)
  311. x = g.parse("starts")
  312. self.assertSequenceEqual(x.children, ['starts'])
  313. # def test_string_priority(self):
  314. # g = _Lark("""start: (A | /a?bb/)+
  315. # A: "a" """)
  316. # x = g.parse('abb')
  317. # self.assertEqual(len(x.children), 2)
  318. # # This parse raises an exception because the lexer will always try to consume
  319. # # "a" first and will never match the regular expression
  320. # # This behavior is subject to change!!
  321. # # Thie won't happen with ambiguity handling.
  322. # g = _Lark("""start: (A | /a?ab/)+
  323. # A: "a" """)
  324. # self.assertRaises(LexError, g.parse, 'aab')
  325. def test_undefined_rule(self):
  326. self.assertRaises(GrammarError, _Lark, """start: a""")
  327. def test_undefined_token(self):
  328. self.assertRaises(GrammarError, _Lark, """start: A""")
  329. def test_rule_collision(self):
  330. g = _Lark("""start: "a"+ "b"
  331. | "a"+ """)
  332. x = g.parse('aaaa')
  333. x = g.parse('aaaab')
  334. def test_rule_collision2(self):
  335. g = _Lark("""start: "a"* "b"
  336. | "a"+ """)
  337. x = g.parse('aaaa')
  338. x = g.parse('aaaab')
  339. x = g.parse('b')
  340. @unittest.skipIf(LEXER is None, "Regexps >1 not supported with scanless parsing")
  341. def test_regex_embed(self):
  342. g = _Lark("""start: A B C
  343. A: /a/
  344. B: /${A}b/
  345. C: /${B}c/
  346. """)
  347. x = g.parse('aababc')
  348. def test_token_embed(self):
  349. g = _Lark("""start: A B C
  350. A: "a"
  351. B: A "b"
  352. C: B "c"
  353. """)
  354. x = g.parse('aababc')
  355. @unittest.skipIf(LEXER in (None, 'dynamic'), "Known bug with scanless parsing") # TODO
  356. def test_token_not_anon(self):
  357. """Tests that "a" is matched as A, rather than an anonymous token.
  358. That means that "a" is not filtered out, despite being an 'immediate string'.
  359. Whether or not this is the intuitive behavior, I'm not sure yet.
  360. Perhaps the right thing to do is report a collision (if such is relevant)
  361. -Erez
  362. """
  363. g = _Lark("""start: "a"
  364. A: "a" """)
  365. x = g.parse('a')
  366. self.assertEqual(len(x.children), 1, '"a" should not be considered anonymous')
  367. self.assertEqual(x.children[0].type, "A")
  368. g = _Lark("""start: /a/
  369. A: /a/ """)
  370. x = g.parse('a')
  371. self.assertEqual(len(x.children), 1, '/a/ should not be considered anonymous')
  372. self.assertEqual(x.children[0].type, "A")
  373. def test_maybe(self):
  374. g = _Lark("""start: ["a"] """)
  375. x = g.parse('a')
  376. x = g.parse('')
  377. def test_start(self):
  378. g = _Lark("""a: "a" a? """, start='a')
  379. x = g.parse('a')
  380. x = g.parse('aa')
  381. x = g.parse('aaa')
  382. def test_alias(self):
  383. g = _Lark("""start: "a" -> b """)
  384. x = g.parse('a')
  385. self.assertEqual(x.data, "b")
  386. def test_token_ebnf(self):
  387. g = _Lark("""start: A
  388. A: "a"* ("b"? "c".."e")+
  389. """)
  390. x = g.parse('abcde')
  391. x = g.parse('dd')
  392. def test_backslash(self):
  393. g = _Lark(r"""start: "\\" "a"
  394. """)
  395. x = g.parse(r'\a')
  396. g = _Lark(r"""start: /\\\\/ /a/
  397. """)
  398. x = g.parse(r'\a')
  399. def test_special_chars(self):
  400. g = _Lark(r"""start: "\n"
  401. """)
  402. x = g.parse('\n')
  403. g = _Lark(r"""start: /\n/
  404. """)
  405. x = g.parse('\n')
  406. def test_backslash2(self):
  407. g = _Lark(r"""start: "\"" "-"
  408. """)
  409. x = g.parse('"-')
  410. g = _Lark(r"""start: /\// /-/
  411. """)
  412. x = g.parse('/-')
  413. # def test_token_recurse(self):
  414. # g = _Lark("""start: A
  415. # A: B
  416. # B: A
  417. # """)
  418. def test_empty(self):
  419. # Fails an Earley implementation without special handling for empty rules,
  420. # or re-processing of already completed rules.
  421. g = _Lark(r"""start: _empty a "B"
  422. a: _empty "A"
  423. _empty:
  424. """)
  425. x = g.parse('AB')
  426. def test_lexer_token_limit(self):
  427. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  428. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  429. g = _Lark("""start: %s
  430. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  431. def test_float_without_lexer(self):
  432. g = _Lark("""start: ["+"|"-"] float
  433. float: digit* "." digit+ exp?
  434. | digit+ exp
  435. exp: ("e"|"E") ["+"|"-"] digit+
  436. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  437. """)
  438. g.parse("1.2")
  439. g.parse("-.2e9")
  440. g.parse("+2e-9")
  441. self.assertRaises(ParseError, g.parse, "+2e-9e")
  442. def test_keep_all_tokens(self):
  443. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  444. tree = l.parse('aaa')
  445. self.assertEqual(tree.children, ['a', 'a', 'a'])
  446. def test_token_flags(self):
  447. l = _Lark("""!start: "a"i+
  448. """
  449. )
  450. tree = l.parse('aA')
  451. self.assertEqual(tree.children, ['a', 'A'])
  452. l = _Lark("""!start: /a/i+
  453. """
  454. )
  455. tree = l.parse('aA')
  456. self.assertEqual(tree.children, ['a', 'A'])
  457. g = """!start: "a"i "a"
  458. """
  459. self.assertRaises(GrammarError, _Lark, g)
  460. g = """!start: /a/i /a/
  461. """
  462. self.assertRaises(GrammarError, _Lark, g)
  463. g = """start: NAME "," "a"
  464. NAME: /[a-z_]/i /[a-z0-9_]/i*
  465. """
  466. l = _Lark(g)
  467. tree = l.parse('ab,a')
  468. self.assertEqual(tree.children, ['ab'])
  469. tree = l.parse('AB,a')
  470. self.assertEqual(tree.children, ['AB'])
  471. def test_token_flags3(self):
  472. l = _Lark("""!start: ABC+
  473. ABC: "abc"i
  474. """
  475. )
  476. tree = l.parse('aBcAbC')
  477. self.assertEqual(tree.children, ['aBc', 'AbC'])
  478. def test_token_flags2(self):
  479. g = """!start: ("a"i | /a/ /b/?)+
  480. """
  481. l = _Lark(g)
  482. tree = l.parse('aA')
  483. self.assertEqual(tree.children, ['a', 'A'])
  484. def test_reduce_cycle(self):
  485. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  486. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  487. """
  488. l = _Lark("""
  489. term: A
  490. | term term
  491. A: "a"
  492. """, start='term')
  493. tree = l.parse("aa")
  494. self.assertEqual(len(tree.children), 2)
  495. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  496. def test_earley_prioritization(self):
  497. "Tests effect of priority on result"
  498. grammar = """
  499. start: a | b
  500. a.1: "a"
  501. b.2: "a"
  502. """
  503. l = Lark(grammar, parser='earley', lexer='standard')
  504. res = l.parse("a")
  505. self.assertEqual(res.children[0].data, 'b')
  506. grammar = """
  507. start: a | b
  508. a.2: "a"
  509. b.1: "a"
  510. """
  511. l = Lark(grammar, parser='earley', lexer='standard')
  512. res = l.parse("a")
  513. self.assertEqual(res.children[0].data, 'a')
  514. _NAME = "Test" + PARSER.capitalize() + (LEXER or 'Scanless').capitalize()
  515. _TestParser.__name__ = _NAME
  516. globals()[_NAME] = _TestParser
  517. # Note: You still have to import them in __main__ for the tests to run
  518. _TO_TEST = [
  519. ('standard', 'earley'),
  520. ('dynamic', 'earley'),
  521. ('standard', 'lalr'),
  522. ('contextual', 'lalr'),
  523. (None, 'earley'),
  524. ]
  525. for _LEXER, _PARSER in _TO_TEST:
  526. _make_parser_test(_LEXER, _PARSER)
  527. for _LEXER in (None, 'dynamic'):
  528. _make_full_earley_test(_LEXER)
  529. if __name__ == '__main__':
  530. unittest.main()