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.

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