This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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