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.

808 lines
28 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. def test_ambiguity1(self):
  111. grammar = """
  112. start: cd+ "e"
  113. !cd: "c"
  114. | "d"
  115. | "cd"
  116. """
  117. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  118. x = l.parse('cde')
  119. assert x.data == '_ambig', x
  120. assert len(x.children) == 2
  121. @unittest.skipIf(LEXER=='dynamic', "Not implemented in Dynamic Earley yet") # TODO
  122. def test_not_all_derivations(self):
  123. grammar = """
  124. start: cd+ "e"
  125. !cd: "c"
  126. | "d"
  127. | "cd"
  128. """
  129. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER, earley__all_derivations=False)
  130. x = l.parse('cde')
  131. assert x.data != '_ambig', x
  132. assert len(x.children) == 1
  133. _NAME = "TestFullEarley" + (LEXER or 'Scanless').capitalize()
  134. _TestFullEarley.__name__ = _NAME
  135. globals()[_NAME] = _TestFullEarley
  136. def _make_parser_test(LEXER, PARSER):
  137. def _Lark(grammar, **kwargs):
  138. return Lark(grammar, lexer=LEXER, parser=PARSER, **kwargs)
  139. class _TestParser(unittest.TestCase):
  140. def test_basic1(self):
  141. g = _Lark("""start: a+ b a* "b" a*
  142. b: "b"
  143. a: "a"
  144. """)
  145. r = g.parse('aaabaab')
  146. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  147. r = g.parse('aaabaaba')
  148. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  149. self.assertRaises(ParseError, g.parse, 'aaabaa')
  150. def test_basic2(self):
  151. # Multiple parsers and colliding tokens
  152. g = _Lark("""start: B A
  153. B: "12"
  154. A: "1" """)
  155. g2 = _Lark("""start: B A
  156. B: "12"
  157. A: "2" """)
  158. x = g.parse('121')
  159. assert x.data == 'start' and x.children == ['12', '1'], x
  160. x = g2.parse('122')
  161. assert x.data == 'start' and x.children == ['12', '2'], x
  162. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  163. def test_stringio_bytes(self):
  164. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  165. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  166. def test_stringio_unicode(self):
  167. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  168. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  169. def test_unicode(self):
  170. g = _Lark(u"""start: UNIA UNIB UNIA
  171. UNIA: /\xa3/
  172. UNIB: /\u0101/
  173. """)
  174. g.parse(u'\xa3\u0101\u00a3')
  175. @unittest.skipIf(LEXER is None, "Regexps >1 not supported with scanless parsing")
  176. def test_unicode2(self):
  177. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  178. UNIA: /\xa3/
  179. UNIB: "a\u0101b\ "
  180. UNIC: /a?\u0101c\n/
  181. """)
  182. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  183. def test_unicode3(self):
  184. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  185. UNIA: /\xa3/
  186. UNIB: "\u0101"
  187. UNIC: /\u0203/ /\n/
  188. """)
  189. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  190. def test_stack_for_ebnf(self):
  191. """Verify that stack depth isn't an issue for EBNF grammars"""
  192. g = _Lark(r"""start: a+
  193. a : "a" """)
  194. g.parse("a" * (sys.getrecursionlimit()*2 ))
  195. def test_expand1_lists_with_one_item(self):
  196. g = _Lark(r"""start: list
  197. ?list: item+
  198. item : A
  199. A: "a"
  200. """)
  201. r = g.parse("a")
  202. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  203. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  204. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  205. self.assertEqual(len(r.children), 1)
  206. def test_expand1_lists_with_one_item_2(self):
  207. g = _Lark(r"""start: list
  208. ?list: item+ "!"
  209. item : A
  210. A: "a"
  211. """)
  212. r = g.parse("a!")
  213. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  214. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  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. def test_dont_expand1_lists_with_multiple_items(self):
  218. g = _Lark(r"""start: list
  219. ?list: item+
  220. item : A
  221. A: "a"
  222. """)
  223. r = g.parse("aa")
  224. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  225. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  226. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  227. self.assertEqual(len(r.children), 1)
  228. # Sanity check: verify that 'list' contains the two 'item's we've given it
  229. [list] = r.children
  230. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  231. def test_dont_expand1_lists_with_multiple_items_2(self):
  232. g = _Lark(r"""start: list
  233. ?list: item+ "!"
  234. item : A
  235. A: "a"
  236. """)
  237. r = g.parse("aa!")
  238. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  239. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  240. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  241. self.assertEqual(len(r.children), 1)
  242. # Sanity check: verify that 'list' contains the two 'item's we've given it
  243. [list] = r.children
  244. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  245. def test_empty_expand1_list(self):
  246. g = _Lark(r"""start: list
  247. ?list: item*
  248. item : A
  249. A: "a"
  250. """)
  251. r = g.parse("")
  252. # 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
  253. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  254. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  255. self.assertEqual(len(r.children), 1)
  256. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  257. [list] = r.children
  258. self.assertSequenceEqual([item.data for item in list.children], ())
  259. def test_empty_expand1_list_2(self):
  260. g = _Lark(r"""start: list
  261. ?list: item* "!"?
  262. item : A
  263. A: "a"
  264. """)
  265. r = g.parse("")
  266. # 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
  267. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  268. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  269. self.assertEqual(len(r.children), 1)
  270. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  271. [list] = r.children
  272. self.assertSequenceEqual([item.data for item in list.children], ())
  273. def test_empty_flatten_list(self):
  274. g = _Lark(r"""start: list
  275. list: | item "," list
  276. item : A
  277. A: "a"
  278. """)
  279. r = g.parse("")
  280. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  281. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  282. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  283. [list] = r.children
  284. self.assertSequenceEqual([item.data for item in list.children], ())
  285. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  286. def test_single_item_flatten_list(self):
  287. g = _Lark(r"""start: list
  288. list: | item "," list
  289. item : A
  290. A: "a"
  291. """)
  292. r = g.parse("a,")
  293. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  294. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  295. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  296. [list] = r.children
  297. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  298. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  299. def test_multiple_item_flatten_list(self):
  300. g = _Lark(r"""start: list
  301. #list: | item "," list
  302. item : A
  303. A: "a"
  304. """)
  305. r = g.parse("a,a,")
  306. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  307. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  308. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  309. [list] = r.children
  310. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  311. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  312. def test_recurse_flatten(self):
  313. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  314. g = _Lark(r"""start: a | start a
  315. a : A
  316. A : "a" """)
  317. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  318. # STree data structures, which uses recursion).
  319. g.parse("a" * (sys.getrecursionlimit() // 4))
  320. def test_token_collision(self):
  321. g = _Lark("""start: "Hello" NAME
  322. NAME: /\w/+
  323. %ignore " "
  324. """)
  325. x = g.parse('Hello World')
  326. self.assertSequenceEqual(x.children, ['World'])
  327. x = g.parse('Hello HelloWorld')
  328. self.assertSequenceEqual(x.children, ['HelloWorld'])
  329. def test_token_collision_WS(self):
  330. g = _Lark("""start: "Hello" NAME
  331. NAME: /\w/+
  332. %import common.WS
  333. %ignore WS
  334. """)
  335. x = g.parse('Hello World')
  336. self.assertSequenceEqual(x.children, ['World'])
  337. x = g.parse('Hello HelloWorld')
  338. self.assertSequenceEqual(x.children, ['HelloWorld'])
  339. @unittest.skipIf(LEXER is None, "Known bug with scanless parsing") # TODO
  340. def test_token_collision2(self):
  341. # NOTE: This test reveals a bug in token reconstruction in Scanless Earley
  342. # I probably need to re-write grammar transformation
  343. g = _Lark("""
  344. !start: "starts"
  345. %import common.LCASE_LETTER
  346. """)
  347. x = g.parse("starts")
  348. self.assertSequenceEqual(x.children, ['starts'])
  349. # def test_string_priority(self):
  350. # g = _Lark("""start: (A | /a?bb/)+
  351. # A: "a" """)
  352. # x = g.parse('abb')
  353. # self.assertEqual(len(x.children), 2)
  354. # # This parse raises an exception because the lexer will always try to consume
  355. # # "a" first and will never match the regular expression
  356. # # This behavior is subject to change!!
  357. # # Thie won't happen with ambiguity handling.
  358. # g = _Lark("""start: (A | /a?ab/)+
  359. # A: "a" """)
  360. # self.assertRaises(LexError, g.parse, 'aab')
  361. def test_undefined_rule(self):
  362. self.assertRaises(GrammarError, _Lark, """start: a""")
  363. def test_undefined_token(self):
  364. self.assertRaises(GrammarError, _Lark, """start: A""")
  365. def test_rule_collision(self):
  366. g = _Lark("""start: "a"+ "b"
  367. | "a"+ """)
  368. x = g.parse('aaaa')
  369. x = g.parse('aaaab')
  370. def test_rule_collision2(self):
  371. g = _Lark("""start: "a"* "b"
  372. | "a"+ """)
  373. x = g.parse('aaaa')
  374. x = g.parse('aaaab')
  375. x = g.parse('b')
  376. @unittest.skipIf(LEXER in (None, 'dynamic'), "Known bug with scanless parsing") # TODO
  377. def test_token_not_anon(self):
  378. """Tests that "a" is matched as A, rather than an anonymous token.
  379. That means that "a" is not filtered out, despite being an 'immediate string'.
  380. Whether or not this is the intuitive behavior, I'm not sure yet.
  381. Perhaps the right thing to do is report a collision (if such is relevant)
  382. -Erez
  383. """
  384. g = _Lark("""start: "a"
  385. A: "a" """)
  386. x = g.parse('a')
  387. self.assertEqual(len(x.children), 1, '"a" should not be considered anonymous')
  388. self.assertEqual(x.children[0].type, "A")
  389. g = _Lark("""start: /a/
  390. A: /a/ """)
  391. x = g.parse('a')
  392. self.assertEqual(len(x.children), 1, '/a/ should not be considered anonymous')
  393. self.assertEqual(x.children[0].type, "A")
  394. def test_maybe(self):
  395. g = _Lark("""start: ["a"] """)
  396. x = g.parse('a')
  397. x = g.parse('')
  398. def test_start(self):
  399. g = _Lark("""a: "a" a? """, start='a')
  400. x = g.parse('a')
  401. x = g.parse('aa')
  402. x = g.parse('aaa')
  403. def test_alias(self):
  404. g = _Lark("""start: "a" -> b """)
  405. x = g.parse('a')
  406. self.assertEqual(x.data, "b")
  407. def test_token_ebnf(self):
  408. g = _Lark("""start: A
  409. A: "a"* ("b"? "c".."e")+
  410. """)
  411. x = g.parse('abcde')
  412. x = g.parse('dd')
  413. def test_backslash(self):
  414. g = _Lark(r"""start: "\\" "a"
  415. """)
  416. x = g.parse(r'\a')
  417. g = _Lark(r"""start: /\\\\/ /a/
  418. """)
  419. x = g.parse(r'\a')
  420. def test_special_chars(self):
  421. g = _Lark(r"""start: "\n"
  422. """)
  423. x = g.parse('\n')
  424. g = _Lark(r"""start: /\n/
  425. """)
  426. x = g.parse('\n')
  427. def test_backslash2(self):
  428. g = _Lark(r"""start: "\"" "-"
  429. """)
  430. x = g.parse('"-')
  431. g = _Lark(r"""start: /\// /-/
  432. """)
  433. x = g.parse('/-')
  434. # def test_token_recurse(self):
  435. # g = _Lark("""start: A
  436. # A: B
  437. # B: A
  438. # """)
  439. def test_empty(self):
  440. # Fails an Earley implementation without special handling for empty rules,
  441. # or re-processing of already completed rules.
  442. g = _Lark(r"""start: _empty a "B"
  443. a: _empty "A"
  444. _empty:
  445. """)
  446. x = g.parse('AB')
  447. def test_lexer_token_limit(self):
  448. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  449. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  450. g = _Lark("""start: %s
  451. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  452. def test_float_without_lexer(self):
  453. g = _Lark("""start: ["+"|"-"] float
  454. float: digit* "." digit+ exp?
  455. | digit+ exp
  456. exp: ("e"|"E") ["+"|"-"] digit+
  457. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  458. """)
  459. g.parse("1.2")
  460. g.parse("-.2e9")
  461. g.parse("+2e-9")
  462. self.assertRaises(ParseError, g.parse, "+2e-9e")
  463. def test_keep_all_tokens(self):
  464. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  465. tree = l.parse('aaa')
  466. self.assertEqual(tree.children, ['a', 'a', 'a'])
  467. def test_token_flags(self):
  468. l = _Lark("""!start: "a"i+
  469. """
  470. )
  471. tree = l.parse('aA')
  472. self.assertEqual(tree.children, ['a', 'A'])
  473. l = _Lark("""!start: /a/i+
  474. """
  475. )
  476. tree = l.parse('aA')
  477. self.assertEqual(tree.children, ['a', 'A'])
  478. g = """!start: "a"i "a"
  479. """
  480. self.assertRaises(GrammarError, _Lark, g)
  481. g = """!start: /a/i /a/
  482. """
  483. self.assertRaises(GrammarError, _Lark, g)
  484. g = """start: NAME "," "a"
  485. NAME: /[a-z_]/i /[a-z0-9_]/i*
  486. """
  487. l = _Lark(g)
  488. tree = l.parse('ab,a')
  489. self.assertEqual(tree.children, ['ab'])
  490. tree = l.parse('AB,a')
  491. self.assertEqual(tree.children, ['AB'])
  492. def test_token_flags3(self):
  493. l = _Lark("""!start: ABC+
  494. ABC: "abc"i
  495. """
  496. )
  497. tree = l.parse('aBcAbC')
  498. self.assertEqual(tree.children, ['aBc', 'AbC'])
  499. def test_token_flags2(self):
  500. g = """!start: ("a"i | /a/ /b/?)+
  501. """
  502. l = _Lark(g)
  503. tree = l.parse('aA')
  504. self.assertEqual(tree.children, ['a', 'A'])
  505. def test_reduce_cycle(self):
  506. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  507. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  508. """
  509. l = _Lark("""
  510. term: A
  511. | term term
  512. A: "a"
  513. """, start='term')
  514. tree = l.parse("aa")
  515. self.assertEqual(len(tree.children), 2)
  516. @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority")
  517. def test_lexer_prioritization(self):
  518. "Tests effect of priority on result"
  519. grammar = """
  520. start: A B | AB
  521. A.2: "a"
  522. B: "b"
  523. AB: "ab"
  524. """
  525. l = _Lark(grammar)
  526. res = l.parse("ab")
  527. self.assertEqual(res.children, ['a', 'b'])
  528. self.assertNotEqual(res.children, ['ab'])
  529. grammar = """
  530. start: A B | AB
  531. A: "a"
  532. B: "b"
  533. AB.3: "ab"
  534. """
  535. l = _Lark(grammar)
  536. res = l.parse("ab")
  537. self.assertNotEqual(res.children, ['a', 'b'])
  538. self.assertEqual(res.children, ['ab'])
  539. def test_import(self):
  540. grammar = """
  541. start: NUMBER WORD
  542. %import common.NUMBER
  543. %import common.WORD
  544. %import common.WS
  545. %ignore WS
  546. """
  547. l = _Lark(grammar)
  548. x = l.parse('12 elephants')
  549. self.assertEqual(x.children, ['12', 'elephants'])
  550. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  551. def test_earley_prioritization(self):
  552. "Tests effect of priority on result"
  553. grammar = """
  554. start: a | b
  555. a.1: "a"
  556. b.2: "a"
  557. """
  558. # l = Lark(grammar, parser='earley', lexer='standard')
  559. l = _Lark(grammar)
  560. res = l.parse("a")
  561. self.assertEqual(res.children[0].data, 'b')
  562. grammar = """
  563. start: a | b
  564. a.2: "a"
  565. b.1: "a"
  566. """
  567. l = _Lark(grammar)
  568. # l = Lark(grammar, parser='earley', lexer='standard')
  569. res = l.parse("a")
  570. self.assertEqual(res.children[0].data, 'a')
  571. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  572. def test_earley_prioritization_sum(self):
  573. "Tests effect of priority on result"
  574. grammar = """
  575. start: ab_ b_ a_ | indirection
  576. indirection: a_ bb_ a_
  577. a_: "a"
  578. b_: "b"
  579. ab_: "ab"
  580. bb_.1: "bb"
  581. """
  582. l = Lark(grammar, parser='earley', ambiguity='resolve__antiscore_sum')
  583. res = l.parse('abba')
  584. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  585. grammar = """
  586. start: ab_ b_ a_ | indirection
  587. indirection: a_ bb_ a_
  588. a_: "a"
  589. b_: "b"
  590. ab_.1: "ab"
  591. bb_: "bb"
  592. """
  593. l = Lark(grammar, parser='earley', ambiguity='resolve__antiscore_sum')
  594. res = l.parse('abba')
  595. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  596. grammar = """
  597. start: ab_ b_ a_ | indirection
  598. indirection: a_ bb_ a_
  599. a_.2: "a"
  600. b_.1: "b"
  601. ab_.3: "ab"
  602. bb_.3: "bb"
  603. """
  604. l = Lark(grammar, parser='earley', ambiguity='resolve__antiscore_sum')
  605. res = l.parse('abba')
  606. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  607. grammar = """
  608. start: ab_ b_ a_ | indirection
  609. indirection: a_ bb_ a_
  610. a_.1: "a"
  611. b_.1: "b"
  612. ab_.4: "ab"
  613. bb_.3: "bb"
  614. """
  615. l = Lark(grammar, parser='earley', ambiguity='resolve__antiscore_sum')
  616. res = l.parse('abba')
  617. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  618. _NAME = "Test" + PARSER.capitalize() + (LEXER or 'Scanless').capitalize()
  619. _TestParser.__name__ = _NAME
  620. globals()[_NAME] = _TestParser
  621. # Note: You still have to import them in __main__ for the tests to run
  622. _TO_TEST = [
  623. ('standard', 'earley'),
  624. ('dynamic', 'earley'),
  625. ('standard', 'lalr'),
  626. ('contextual', 'lalr'),
  627. (None, 'earley'),
  628. ]
  629. for _LEXER, _PARSER in _TO_TEST:
  630. _make_parser_test(_LEXER, _PARSER)
  631. for _LEXER in (None, 'dynamic'):
  632. _make_full_earley_test(_LEXER)
  633. if __name__ == '__main__':
  634. unittest.main()