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.

824 lines
28 KiB

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