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.

1713 lines
58 KiB

  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import
  3. import unittest
  4. import logging
  5. import os
  6. import sys
  7. from copy import deepcopy
  8. try:
  9. from cStringIO import StringIO as cStringIO
  10. except ImportError:
  11. # Available only in Python 2.x, 3.x only has io.StringIO from below
  12. cStringIO = None
  13. from io import (
  14. StringIO as uStringIO,
  15. open,
  16. )
  17. logging.basicConfig(level=logging.INFO)
  18. from lark.lark import Lark
  19. from lark.exceptions import GrammarError, ParseError, UnexpectedToken, UnexpectedInput, UnexpectedCharacters
  20. from lark.tree import Tree
  21. from lark.visitors import Transformer, Transformer_InPlace, v_args
  22. from lark.grammar import Rule
  23. from lark.lexer import TerminalDef, Lexer, TraditionalLexer
  24. __path__ = os.path.dirname(__file__)
  25. def _read(n, *args):
  26. with open(os.path.join(__path__, n), *args) as f:
  27. return f.read()
  28. class TestParsers(unittest.TestCase):
  29. def test_same_ast(self):
  30. "Tests that Earley and LALR parsers produce equal trees"
  31. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  32. name_list: NAME | name_list "," NAME
  33. NAME: /\w+/ """, parser='lalr')
  34. l = g.parse('(a,b,c,*x)')
  35. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  36. name_list: NAME | name_list "," NAME
  37. NAME: /\w/+ """)
  38. l2 = g.parse('(a,b,c,*x)')
  39. assert l == l2, '%s != %s' % (l.pretty(), l2.pretty())
  40. def test_infinite_recurse(self):
  41. g = """start: a
  42. a: a | "a"
  43. """
  44. self.assertRaises(GrammarError, Lark, g, parser='lalr')
  45. # TODO: should it? shouldn't it?
  46. # l = Lark(g, parser='earley', lexer='dynamic')
  47. # self.assertRaises(ParseError, l.parse, 'a')
  48. def test_propagate_positions(self):
  49. g = Lark("""start: a
  50. a: "a"
  51. """, propagate_positions=True)
  52. r = g.parse('a')
  53. self.assertEqual( r.children[0].meta.line, 1 )
  54. g = Lark("""start: x
  55. x: a
  56. a: "a"
  57. """, propagate_positions=True)
  58. r = g.parse('a')
  59. self.assertEqual( r.children[0].meta.line, 1 )
  60. def test_expand1(self):
  61. g = Lark("""start: a
  62. ?a: b
  63. b: "x"
  64. """)
  65. r = g.parse('x')
  66. self.assertEqual( r.children[0].data, "b" )
  67. g = Lark("""start: a
  68. ?a: b -> c
  69. b: "x"
  70. """)
  71. r = g.parse('x')
  72. self.assertEqual( r.children[0].data, "c" )
  73. g = Lark("""start: a
  74. ?a: B -> c
  75. B: "x"
  76. """)
  77. self.assertEqual( r.children[0].data, "c" )
  78. g = Lark("""start: a
  79. ?a: b b -> c
  80. b: "x"
  81. """)
  82. r = g.parse('xx')
  83. self.assertEqual( r.children[0].data, "c" )
  84. def test_visit_tokens(self):
  85. class T(Transformer):
  86. def a(self, children):
  87. return children[0] + "!"
  88. def A(self, tok):
  89. return tok.update(value=tok.upper())
  90. # Test regular
  91. g = """start: a
  92. a : A
  93. A: "x"
  94. """
  95. p = Lark(g, parser='lalr')
  96. r = T(False).transform(p.parse("x"))
  97. self.assertEqual( r.children, ["x!"] )
  98. r = T().transform(p.parse("x"))
  99. self.assertEqual( r.children, ["X!"] )
  100. # Test internal transformer
  101. p = Lark(g, parser='lalr', transformer=T())
  102. r = p.parse("x")
  103. self.assertEqual( r.children, ["X!"] )
  104. def test_vargs_meta(self):
  105. @v_args(meta=True)
  106. class T1(Transformer):
  107. def a(self, children, meta):
  108. assert not children
  109. return meta.line
  110. def start(self, children, meta):
  111. return children
  112. @v_args(meta=True, inline=True)
  113. class T2(Transformer):
  114. def a(self, meta):
  115. return meta.line
  116. def start(self, meta, *res):
  117. return list(res)
  118. for T in (T1, T2):
  119. for internal in [False, True]:
  120. try:
  121. g = Lark(r"""start: a+
  122. a : "x" _NL?
  123. _NL: /\n/+
  124. """, parser='lalr', transformer=T() if internal else None, propagate_positions=True)
  125. except NotImplementedError:
  126. assert internal
  127. continue
  128. res = g.parse("xx\nx\nxxx\n\n\nxx")
  129. assert not internal
  130. res = T().transform(res)
  131. self.assertEqual(res, [1, 1, 2, 3, 3, 3, 6, 6])
  132. def test_vargs_tree(self):
  133. tree = Lark('''
  134. start: a a a
  135. !a: "A"
  136. ''').parse('AAA')
  137. tree_copy = deepcopy(tree)
  138. @v_args(tree=True)
  139. class T(Transformer):
  140. def a(self, tree):
  141. return 1
  142. def start(self, tree):
  143. return tree.children
  144. res = T().transform(tree)
  145. self.assertEqual(res, [1, 1, 1])
  146. self.assertEqual(tree, tree_copy)
  147. def test_embedded_transformer(self):
  148. class T(Transformer):
  149. def a(self, children):
  150. return "<a>"
  151. def b(self, children):
  152. return "<b>"
  153. def c(self, children):
  154. return "<c>"
  155. # Test regular
  156. g = Lark("""start: a
  157. a : "x"
  158. """, parser='lalr')
  159. r = T().transform(g.parse("x"))
  160. self.assertEqual( r.children, ["<a>"] )
  161. g = Lark("""start: a
  162. a : "x"
  163. """, parser='lalr', transformer=T())
  164. r = g.parse("x")
  165. self.assertEqual( r.children, ["<a>"] )
  166. # Test Expand1
  167. g = Lark("""start: a
  168. ?a : b
  169. b : "x"
  170. """, parser='lalr')
  171. r = T().transform(g.parse("x"))
  172. self.assertEqual( r.children, ["<b>"] )
  173. g = Lark("""start: a
  174. ?a : b
  175. b : "x"
  176. """, parser='lalr', transformer=T())
  177. r = g.parse("x")
  178. self.assertEqual( r.children, ["<b>"] )
  179. # Test Expand1 -> Alias
  180. g = Lark("""start: a
  181. ?a : b b -> c
  182. b : "x"
  183. """, parser='lalr')
  184. r = T().transform(g.parse("xx"))
  185. self.assertEqual( r.children, ["<c>"] )
  186. g = Lark("""start: a
  187. ?a : b b -> c
  188. b : "x"
  189. """, parser='lalr', transformer=T())
  190. r = g.parse("xx")
  191. self.assertEqual( r.children, ["<c>"] )
  192. def test_embedded_transformer_inplace(self):
  193. @v_args(tree=True)
  194. class T1(Transformer_InPlace):
  195. def a(self, tree):
  196. assert isinstance(tree, Tree), tree
  197. tree.children.append("tested")
  198. return tree
  199. def b(self, tree):
  200. return Tree(tree.data, tree.children + ['tested2'])
  201. @v_args(tree=True)
  202. class T2(Transformer):
  203. def a(self, tree):
  204. assert isinstance(tree, Tree), tree
  205. tree.children.append("tested")
  206. return tree
  207. def b(self, tree):
  208. return Tree(tree.data, tree.children + ['tested2'])
  209. class T3(Transformer):
  210. @v_args(tree=True)
  211. def a(self, tree):
  212. assert isinstance(tree, Tree)
  213. tree.children.append("tested")
  214. return tree
  215. @v_args(tree=True)
  216. def b(self, tree):
  217. return Tree(tree.data, tree.children + ['tested2'])
  218. for t in [T1(), T2(), T3()]:
  219. for internal in [False, True]:
  220. g = Lark("""start: a b
  221. a : "x"
  222. b : "y"
  223. """, parser='lalr', transformer=t if internal else None)
  224. r = g.parse("xy")
  225. if not internal:
  226. r = t.transform(r)
  227. a, b = r.children
  228. self.assertEqual(a.children, ["tested"])
  229. self.assertEqual(b.children, ["tested2"])
  230. def test_alias(self):
  231. Lark("""start: ["a"] "b" ["c"] "e" ["f"] ["g"] ["h"] "x" -> d """)
  232. def _make_full_earley_test(LEXER):
  233. def _Lark(grammar, **kwargs):
  234. return Lark(grammar, lexer=LEXER, parser='earley', propagate_positions=True, **kwargs)
  235. class _TestFullEarley(unittest.TestCase):
  236. def test_anon(self):
  237. # Fails an Earley implementation without special handling for empty rules,
  238. # or re-processing of already completed rules.
  239. g = Lark(r"""start: B
  240. B: ("ab"|/[^b]/)+
  241. """, lexer=LEXER)
  242. self.assertEqual( g.parse('abc').children[0], 'abc')
  243. def test_earley(self):
  244. g = Lark("""start: A "b" c
  245. A: "a"+
  246. c: "abc"
  247. """, parser="earley", lexer=LEXER)
  248. x = g.parse('aaaababc')
  249. def test_earley2(self):
  250. grammar = """
  251. start: statement+
  252. statement: "r"
  253. | "c" /[a-z]/+
  254. %ignore " "
  255. """
  256. program = """c b r"""
  257. l = Lark(grammar, parser='earley', lexer=LEXER)
  258. l.parse(program)
  259. @unittest.skipIf(LEXER=='dynamic', "Only relevant for the dynamic_complete parser")
  260. def test_earley3(self):
  261. """Tests prioritization and disambiguation for pseudo-terminals (there should be only one result)
  262. By default, `+` should immitate regexp greedy-matching
  263. """
  264. grammar = """
  265. start: A A
  266. A: "a"+
  267. """
  268. l = Lark(grammar, parser='earley', lexer=LEXER)
  269. res = l.parse("aaa")
  270. self.assertEqual(set(res.children), {'aa', 'a'})
  271. # XXX TODO fix Earley to maintain correct order
  272. # i.e. terminals it imitate greedy search for terminals, but lazy search for rules
  273. # self.assertEqual(res.children, ['aa', 'a'])
  274. def test_earley4(self):
  275. grammar = """
  276. start: A A?
  277. A: "a"+
  278. """
  279. l = Lark(grammar, parser='earley', lexer=LEXER)
  280. res = l.parse("aaa")
  281. assert set(res.children) == {'aa', 'a'} or res.children == ['aaa']
  282. # XXX TODO fix Earley to maintain correct order
  283. # i.e. terminals it imitate greedy search for terminals, but lazy search for rules
  284. # self.assertEqual(res.children, ['aaa'])
  285. def test_earley_repeating_empty(self):
  286. # This was a sneaky bug!
  287. grammar = """
  288. !start: "a" empty empty "b"
  289. empty: empty2
  290. empty2:
  291. """
  292. parser = Lark(grammar, parser='earley', lexer=LEXER)
  293. res = parser.parse('ab')
  294. empty_tree = Tree('empty', [Tree('empty2', [])])
  295. self.assertSequenceEqual(res.children, ['a', empty_tree, empty_tree, 'b'])
  296. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  297. def test_earley_explicit_ambiguity(self):
  298. # This was a sneaky bug!
  299. grammar = """
  300. start: a b | ab
  301. a: "a"
  302. b: "b"
  303. ab: "ab"
  304. """
  305. parser = Lark(grammar, parser='earley', lexer=LEXER, ambiguity='explicit')
  306. ambig_tree = parser.parse('ab')
  307. self.assertEqual( ambig_tree.data, '_ambig')
  308. self.assertEqual( len(ambig_tree.children), 2)
  309. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  310. def test_ambiguity1(self):
  311. grammar = """
  312. start: cd+ "e"
  313. !cd: "c"
  314. | "d"
  315. | "cd"
  316. """
  317. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  318. ambig_tree = l.parse('cde')
  319. assert ambig_tree.data == '_ambig', ambig_tree
  320. assert len(ambig_tree.children) == 2
  321. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  322. def test_ambiguity2(self):
  323. grammar = """
  324. ANY: /[a-zA-Z0-9 ]+/
  325. a.2: "A" b+
  326. b.2: "B"
  327. c: ANY
  328. start: (a|c)*
  329. """
  330. l = Lark(grammar, parser='earley', lexer=LEXER)
  331. res = l.parse('ABX')
  332. expected = Tree('start', [
  333. Tree('a', [
  334. Tree('b', [])
  335. ]),
  336. Tree('c', [
  337. 'X'
  338. ])
  339. ])
  340. self.assertEqual(res, expected)
  341. def test_fruitflies_ambig(self):
  342. grammar = """
  343. start: noun verb noun -> simple
  344. | noun verb "like" noun -> comparative
  345. noun: adj? NOUN
  346. verb: VERB
  347. adj: ADJ
  348. NOUN: "flies" | "bananas" | "fruit"
  349. VERB: "like" | "flies"
  350. ADJ: "fruit"
  351. %import common.WS
  352. %ignore WS
  353. """
  354. parser = Lark(grammar, ambiguity='explicit', lexer=LEXER)
  355. tree = parser.parse('fruit flies like bananas')
  356. expected = Tree('_ambig', [
  357. Tree('comparative', [
  358. Tree('noun', ['fruit']),
  359. Tree('verb', ['flies']),
  360. Tree('noun', ['bananas'])
  361. ]),
  362. Tree('simple', [
  363. Tree('noun', [Tree('adj', ['fruit']), 'flies']),
  364. Tree('verb', ['like']),
  365. Tree('noun', ['bananas'])
  366. ])
  367. ])
  368. # self.assertEqual(tree, expected)
  369. self.assertEqual(tree.data, expected.data)
  370. self.assertEqual(set(tree.children), set(expected.children))
  371. @unittest.skipIf(LEXER!='dynamic_complete', "Only relevant for the dynamic_complete parser")
  372. def test_explicit_ambiguity2(self):
  373. grammar = r"""
  374. start: NAME+
  375. NAME: /\w+/
  376. %ignore " "
  377. """
  378. text = """cat"""
  379. parser = _Lark(grammar, start='start', ambiguity='explicit')
  380. tree = parser.parse(text)
  381. self.assertEqual(tree.data, '_ambig')
  382. combinations = {tuple(str(s) for s in t.children) for t in tree.children}
  383. self.assertEqual(combinations, {
  384. ('cat',),
  385. ('ca', 't'),
  386. ('c', 'at'),
  387. ('c', 'a' ,'t')
  388. })
  389. def test_term_ambig_resolve(self):
  390. grammar = r"""
  391. !start: NAME+
  392. NAME: /\w+/
  393. %ignore " "
  394. """
  395. text = """foo bar"""
  396. parser = Lark(grammar)
  397. tree = parser.parse(text)
  398. self.assertEqual(tree.children, ['foo', 'bar'])
  399. # @unittest.skipIf(LEXER=='dynamic', "Not implemented in Dynamic Earley yet") # TODO
  400. # def test_not_all_derivations(self):
  401. # grammar = """
  402. # start: cd+ "e"
  403. # !cd: "c"
  404. # | "d"
  405. # | "cd"
  406. # """
  407. # l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER, earley__all_derivations=False)
  408. # x = l.parse('cde')
  409. # assert x.data != '_ambig', x
  410. # assert len(x.children) == 1
  411. _NAME = "TestFullEarley" + LEXER.capitalize()
  412. _TestFullEarley.__name__ = _NAME
  413. globals()[_NAME] = _TestFullEarley
  414. class CustomLexer(Lexer):
  415. """
  416. Purpose of this custom lexer is to test the integration,
  417. so it uses the traditionalparser as implementation without custom lexing behaviour.
  418. """
  419. def __init__(self, lexer_conf):
  420. self.lexer = TraditionalLexer(lexer_conf.tokens, ignore=lexer_conf.ignore, user_callbacks=lexer_conf.callbacks)
  421. def lex(self, *args, **kwargs):
  422. return self.lexer.lex(*args, **kwargs)
  423. def _make_parser_test(LEXER, PARSER):
  424. lexer_class_or_name = CustomLexer if LEXER == 'custom' else LEXER
  425. def _Lark(grammar, **kwargs):
  426. return Lark(grammar, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  427. def _Lark_open(gfilename, **kwargs):
  428. return Lark.open(gfilename, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  429. class _TestParser(unittest.TestCase):
  430. def test_basic1(self):
  431. g = _Lark("""start: a+ b a* "b" a*
  432. b: "b"
  433. a: "a"
  434. """)
  435. r = g.parse('aaabaab')
  436. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  437. r = g.parse('aaabaaba')
  438. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  439. self.assertRaises(ParseError, g.parse, 'aaabaa')
  440. def test_basic2(self):
  441. # Multiple parsers and colliding tokens
  442. g = _Lark("""start: B A
  443. B: "12"
  444. A: "1" """)
  445. g2 = _Lark("""start: B A
  446. B: "12"
  447. A: "2" """)
  448. x = g.parse('121')
  449. assert x.data == 'start' and x.children == ['12', '1'], x
  450. x = g2.parse('122')
  451. assert x.data == 'start' and x.children == ['12', '2'], x
  452. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  453. def test_stringio_bytes(self):
  454. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  455. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  456. def test_stringio_unicode(self):
  457. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  458. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  459. def test_unicode(self):
  460. g = _Lark(u"""start: UNIA UNIB UNIA
  461. UNIA: /\xa3/
  462. UNIB: /\u0101/
  463. """)
  464. g.parse(u'\xa3\u0101\u00a3')
  465. def test_unicode2(self):
  466. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  467. UNIA: /\xa3/
  468. UNIB: "a\u0101b\ "
  469. UNIC: /a?\u0101c\n/
  470. """)
  471. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  472. def test_unicode3(self):
  473. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  474. UNIA: /\xa3/
  475. UNIB: "\u0101"
  476. UNIC: /\u0203/ /\n/
  477. """)
  478. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  479. def test_hex_escape(self):
  480. g = _Lark(r"""start: A B C
  481. A: "\x01"
  482. B: /\x02/
  483. C: "\xABCD"
  484. """)
  485. g.parse('\x01\x02\xABCD')
  486. def test_unicode_literal_range_escape(self):
  487. g = _Lark(r"""start: A+
  488. A: "\u0061".."\u0063"
  489. """)
  490. g.parse('abc')
  491. def test_hex_literal_range_escape(self):
  492. g = _Lark(r"""start: A+
  493. A: "\x01".."\x03"
  494. """)
  495. g.parse('\x01\x02\x03')
  496. @unittest.skipIf(PARSER == 'cyk', "Takes forever")
  497. def test_stack_for_ebnf(self):
  498. """Verify that stack depth isn't an issue for EBNF grammars"""
  499. g = _Lark(r"""start: a+
  500. a : "a" """)
  501. g.parse("a" * (sys.getrecursionlimit()*2 ))
  502. def test_expand1_lists_with_one_item(self):
  503. g = _Lark(r"""start: list
  504. ?list: item+
  505. item : A
  506. A: "a"
  507. """)
  508. r = g.parse("a")
  509. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  510. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  511. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  512. self.assertEqual(len(r.children), 1)
  513. def test_expand1_lists_with_one_item_2(self):
  514. g = _Lark(r"""start: list
  515. ?list: item+ "!"
  516. item : A
  517. A: "a"
  518. """)
  519. r = g.parse("a!")
  520. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  521. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  522. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  523. self.assertEqual(len(r.children), 1)
  524. def test_dont_expand1_lists_with_multiple_items(self):
  525. g = _Lark(r"""start: list
  526. ?list: item+
  527. item : A
  528. A: "a"
  529. """)
  530. r = g.parse("aa")
  531. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  532. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  533. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  534. self.assertEqual(len(r.children), 1)
  535. # Sanity check: verify that 'list' contains the two 'item's we've given it
  536. [list] = r.children
  537. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  538. def test_dont_expand1_lists_with_multiple_items_2(self):
  539. g = _Lark(r"""start: list
  540. ?list: item+ "!"
  541. item : A
  542. A: "a"
  543. """)
  544. r = g.parse("aa!")
  545. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  546. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  547. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  548. self.assertEqual(len(r.children), 1)
  549. # Sanity check: verify that 'list' contains the two 'item's we've given it
  550. [list] = r.children
  551. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  552. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  553. def test_empty_expand1_list(self):
  554. g = _Lark(r"""start: list
  555. ?list: item*
  556. item : A
  557. A: "a"
  558. """)
  559. r = g.parse("")
  560. # 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
  561. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  562. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  563. self.assertEqual(len(r.children), 1)
  564. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  565. [list] = r.children
  566. self.assertSequenceEqual([item.data for item in list.children], ())
  567. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  568. def test_empty_expand1_list_2(self):
  569. g = _Lark(r"""start: list
  570. ?list: item* "!"?
  571. item : A
  572. A: "a"
  573. """)
  574. r = g.parse("")
  575. # 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
  576. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  577. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  578. self.assertEqual(len(r.children), 1)
  579. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  580. [list] = r.children
  581. self.assertSequenceEqual([item.data for item in list.children], ())
  582. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  583. def test_empty_flatten_list(self):
  584. g = _Lark(r"""start: list
  585. list: | item "," list
  586. item : A
  587. A: "a"
  588. """)
  589. r = g.parse("")
  590. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  591. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  592. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  593. [list] = r.children
  594. self.assertSequenceEqual([item.data for item in list.children], ())
  595. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  596. def test_single_item_flatten_list(self):
  597. g = _Lark(r"""start: list
  598. list: | item "," list
  599. item : A
  600. A: "a"
  601. """)
  602. r = g.parse("a,")
  603. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  604. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  605. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  606. [list] = r.children
  607. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  608. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  609. def test_multiple_item_flatten_list(self):
  610. g = _Lark(r"""start: list
  611. #list: | item "," list
  612. item : A
  613. A: "a"
  614. """)
  615. r = g.parse("a,a,")
  616. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  617. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  618. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  619. [list] = r.children
  620. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  621. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  622. def test_recurse_flatten(self):
  623. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  624. g = _Lark(r"""start: a | start a
  625. a : A
  626. A : "a" """)
  627. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  628. # STree data structures, which uses recursion).
  629. g.parse("a" * (sys.getrecursionlimit() // 4))
  630. def test_token_collision(self):
  631. g = _Lark(r"""start: "Hello" NAME
  632. NAME: /\w/+
  633. %ignore " "
  634. """)
  635. x = g.parse('Hello World')
  636. self.assertSequenceEqual(x.children, ['World'])
  637. x = g.parse('Hello HelloWorld')
  638. self.assertSequenceEqual(x.children, ['HelloWorld'])
  639. def test_token_collision_WS(self):
  640. g = _Lark(r"""start: "Hello" NAME
  641. NAME: /\w/+
  642. %import common.WS
  643. %ignore WS
  644. """)
  645. x = g.parse('Hello World')
  646. self.assertSequenceEqual(x.children, ['World'])
  647. x = g.parse('Hello HelloWorld')
  648. self.assertSequenceEqual(x.children, ['HelloWorld'])
  649. def test_token_collision2(self):
  650. g = _Lark("""
  651. !start: "starts"
  652. %import common.LCASE_LETTER
  653. """)
  654. x = g.parse("starts")
  655. self.assertSequenceEqual(x.children, ['starts'])
  656. # def test_string_priority(self):
  657. # g = _Lark("""start: (A | /a?bb/)+
  658. # A: "a" """)
  659. # x = g.parse('abb')
  660. # self.assertEqual(len(x.children), 2)
  661. # # This parse raises an exception because the lexer will always try to consume
  662. # # "a" first and will never match the regular expression
  663. # # This behavior is subject to change!!
  664. # # Thie won't happen with ambiguity handling.
  665. # g = _Lark("""start: (A | /a?ab/)+
  666. # A: "a" """)
  667. # self.assertRaises(LexError, g.parse, 'aab')
  668. def test_undefined_rule(self):
  669. self.assertRaises(GrammarError, _Lark, """start: a""")
  670. def test_undefined_token(self):
  671. self.assertRaises(GrammarError, _Lark, """start: A""")
  672. def test_rule_collision(self):
  673. g = _Lark("""start: "a"+ "b"
  674. | "a"+ """)
  675. x = g.parse('aaaa')
  676. x = g.parse('aaaab')
  677. def test_rule_collision2(self):
  678. g = _Lark("""start: "a"* "b"
  679. | "a"+ """)
  680. x = g.parse('aaaa')
  681. x = g.parse('aaaab')
  682. x = g.parse('b')
  683. def test_token_not_anon(self):
  684. """Tests that "a" is matched as an anonymous token, and not A.
  685. """
  686. g = _Lark("""start: "a"
  687. A: "a" """)
  688. x = g.parse('a')
  689. self.assertEqual(len(x.children), 0, '"a" should be considered anonymous')
  690. g = _Lark("""start: "a" A
  691. A: "a" """)
  692. x = g.parse('aa')
  693. self.assertEqual(len(x.children), 1, 'only "a" should be considered anonymous')
  694. self.assertEqual(x.children[0].type, "A")
  695. g = _Lark("""start: /a/
  696. A: /a/ """)
  697. x = g.parse('a')
  698. self.assertEqual(len(x.children), 1)
  699. self.assertEqual(x.children[0].type, "A", "A isn't associated with /a/")
  700. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  701. def test_maybe(self):
  702. g = _Lark("""start: ["a"] """)
  703. x = g.parse('a')
  704. x = g.parse('')
  705. def test_start(self):
  706. g = _Lark("""a: "a" a? """, start='a')
  707. x = g.parse('a')
  708. x = g.parse('aa')
  709. x = g.parse('aaa')
  710. def test_alias(self):
  711. g = _Lark("""start: "a" -> b """)
  712. x = g.parse('a')
  713. self.assertEqual(x.data, "b")
  714. def test_token_ebnf(self):
  715. g = _Lark("""start: A
  716. A: "a"* ("b"? "c".."e")+
  717. """)
  718. x = g.parse('abcde')
  719. x = g.parse('dd')
  720. def test_backslash(self):
  721. g = _Lark(r"""start: "\\" "a"
  722. """)
  723. x = g.parse(r'\a')
  724. g = _Lark(r"""start: /\\/ /a/
  725. """)
  726. x = g.parse(r'\a')
  727. def test_backslash2(self):
  728. g = _Lark(r"""start: "\"" "-"
  729. """)
  730. x = g.parse('"-')
  731. g = _Lark(r"""start: /\// /-/
  732. """)
  733. x = g.parse('/-')
  734. def test_special_chars(self):
  735. g = _Lark(r"""start: "\n"
  736. """)
  737. x = g.parse('\n')
  738. g = _Lark(r"""start: /\n/
  739. """)
  740. x = g.parse('\n')
  741. # def test_token_recurse(self):
  742. # g = _Lark("""start: A
  743. # A: B
  744. # B: A
  745. # """)
  746. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  747. def test_empty(self):
  748. # Fails an Earley implementation without special handling for empty rules,
  749. # or re-processing of already completed rules.
  750. g = _Lark(r"""start: _empty a "B"
  751. a: _empty "A"
  752. _empty:
  753. """)
  754. x = g.parse('AB')
  755. def test_regex_quote(self):
  756. g = r"""
  757. start: SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING
  758. SINGLE_QUOTED_STRING : /'[^']*'/
  759. DOUBLE_QUOTED_STRING : /"[^"]*"/
  760. """
  761. g = _Lark(g)
  762. self.assertEqual( g.parse('"hello"').children, ['"hello"'])
  763. self.assertEqual( g.parse("'hello'").children, ["'hello'"])
  764. def test_lexer_token_limit(self):
  765. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  766. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  767. g = _Lark("""start: %s
  768. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  769. def test_float_without_lexer(self):
  770. expected_error = UnexpectedCharacters if LEXER.startswith('dynamic') else UnexpectedToken
  771. if PARSER == 'cyk':
  772. expected_error = ParseError
  773. g = _Lark("""start: ["+"|"-"] float
  774. float: digit* "." digit+ exp?
  775. | digit+ exp
  776. exp: ("e"|"E") ["+"|"-"] digit+
  777. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  778. """)
  779. g.parse("1.2")
  780. g.parse("-.2e9")
  781. g.parse("+2e-9")
  782. self.assertRaises( expected_error, g.parse, "+2e-9e")
  783. def test_keep_all_tokens(self):
  784. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  785. tree = l.parse('aaa')
  786. self.assertEqual(tree.children, ['a', 'a', 'a'])
  787. def test_token_flags(self):
  788. l = _Lark("""!start: "a"i+
  789. """
  790. )
  791. tree = l.parse('aA')
  792. self.assertEqual(tree.children, ['a', 'A'])
  793. l = _Lark("""!start: /a/i+
  794. """
  795. )
  796. tree = l.parse('aA')
  797. self.assertEqual(tree.children, ['a', 'A'])
  798. # g = """!start: "a"i "a"
  799. # """
  800. # self.assertRaises(GrammarError, _Lark, g)
  801. # g = """!start: /a/i /a/
  802. # """
  803. # self.assertRaises(GrammarError, _Lark, g)
  804. g = """start: NAME "," "a"
  805. NAME: /[a-z_]/i /[a-z0-9_]/i*
  806. """
  807. l = _Lark(g)
  808. tree = l.parse('ab,a')
  809. self.assertEqual(tree.children, ['ab'])
  810. tree = l.parse('AB,a')
  811. self.assertEqual(tree.children, ['AB'])
  812. def test_token_flags3(self):
  813. l = _Lark("""!start: ABC+
  814. ABC: "abc"i
  815. """
  816. )
  817. tree = l.parse('aBcAbC')
  818. self.assertEqual(tree.children, ['aBc', 'AbC'])
  819. def test_token_flags2(self):
  820. g = """!start: ("a"i | /a/ /b/?)+
  821. """
  822. l = _Lark(g)
  823. tree = l.parse('aA')
  824. self.assertEqual(tree.children, ['a', 'A'])
  825. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  826. def test_twice_empty(self):
  827. g = """!start: ("A"?)?
  828. """
  829. l = _Lark(g)
  830. tree = l.parse('A')
  831. self.assertEqual(tree.children, ['A'])
  832. tree = l.parse('')
  833. self.assertEqual(tree.children, [])
  834. def test_undefined_ignore(self):
  835. g = """!start: "A"
  836. %ignore B
  837. """
  838. self.assertRaises( GrammarError, _Lark, g)
  839. def test_alias_in_terminal(self):
  840. g = """start: TERM
  841. TERM: "a" -> alias
  842. """
  843. self.assertRaises( GrammarError, _Lark, g)
  844. def test_line_and_column(self):
  845. g = r"""!start: "A" bc "D"
  846. !bc: "B\nC"
  847. """
  848. l = _Lark(g)
  849. a, bc, d = l.parse("AB\nCD").children
  850. self.assertEqual(a.line, 1)
  851. self.assertEqual(a.column, 1)
  852. bc ,= bc.children
  853. self.assertEqual(bc.line, 1)
  854. self.assertEqual(bc.column, 2)
  855. self.assertEqual(d.line, 2)
  856. self.assertEqual(d.column, 2)
  857. if LEXER != 'dynamic':
  858. self.assertEqual(a.end_line, 1)
  859. self.assertEqual(a.end_column, 2)
  860. self.assertEqual(bc.end_line, 2)
  861. self.assertEqual(bc.end_column, 2)
  862. self.assertEqual(d.end_line, 2)
  863. self.assertEqual(d.end_column, 3)
  864. def test_reduce_cycle(self):
  865. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  866. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  867. """
  868. l = _Lark("""
  869. term: A
  870. | term term
  871. A: "a"
  872. """, start='term')
  873. tree = l.parse("aa")
  874. self.assertEqual(len(tree.children), 2)
  875. @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority")
  876. def test_lexer_prioritization(self):
  877. "Tests effect of priority on result"
  878. grammar = """
  879. start: A B | AB
  880. A.2: "a"
  881. B: "b"
  882. AB: "ab"
  883. """
  884. l = _Lark(grammar)
  885. res = l.parse("ab")
  886. self.assertEqual(res.children, ['a', 'b'])
  887. self.assertNotEqual(res.children, ['ab'])
  888. grammar = """
  889. start: A B | AB
  890. A: "a"
  891. B: "b"
  892. AB.3: "ab"
  893. """
  894. l = _Lark(grammar)
  895. res = l.parse("ab")
  896. self.assertNotEqual(res.children, ['a', 'b'])
  897. self.assertEqual(res.children, ['ab'])
  898. grammar = """
  899. start: A B | AB
  900. A: "a"
  901. B.-20: "b"
  902. AB.-10: "ab"
  903. """
  904. l = _Lark(grammar)
  905. res = l.parse("ab")
  906. self.assertEqual(res.children, ['a', 'b'])
  907. grammar = """
  908. start: A B | AB
  909. A.-99999999999999999999999: "a"
  910. B: "b"
  911. AB: "ab"
  912. """
  913. l = _Lark(grammar)
  914. res = l.parse("ab")
  915. self.assertEqual(res.children, ['ab'])
  916. def test_import(self):
  917. grammar = """
  918. start: NUMBER WORD
  919. %import common.NUMBER
  920. %import common.WORD
  921. %import common.WS
  922. %ignore WS
  923. """
  924. l = _Lark(grammar)
  925. x = l.parse('12 elephants')
  926. self.assertEqual(x.children, ['12', 'elephants'])
  927. def test_import_rename(self):
  928. grammar = """
  929. start: N W
  930. %import common.NUMBER -> N
  931. %import common.WORD -> W
  932. %import common.WS
  933. %ignore WS
  934. """
  935. l = _Lark(grammar)
  936. x = l.parse('12 elephants')
  937. self.assertEqual(x.children, ['12', 'elephants'])
  938. def test_relative_import(self):
  939. l = _Lark_open('test_relative_import.lark', rel_to=__file__)
  940. x = l.parse('12 lions')
  941. self.assertEqual(x.children, ['12', 'lions'])
  942. def test_relative_import_unicode(self):
  943. l = _Lark_open('test_relative_import_unicode.lark', rel_to=__file__)
  944. x = l.parse(u'Ø')
  945. self.assertEqual(x.children, [u'Ø'])
  946. def test_relative_import_rename(self):
  947. l = _Lark_open('test_relative_import_rename.lark', rel_to=__file__)
  948. x = l.parse('12 lions')
  949. self.assertEqual(x.children, ['12', 'lions'])
  950. def test_relative_rule_import(self):
  951. l = _Lark_open('test_relative_rule_import.lark', rel_to=__file__)
  952. x = l.parse('xaabby')
  953. self.assertEqual(x.children, [
  954. 'x',
  955. Tree('expr', ['a', Tree('expr', ['a', 'b']), 'b']),
  956. 'y'])
  957. def test_relative_rule_import_drop_ignore(self):
  958. # %ignore rules are dropped on import
  959. l = _Lark_open('test_relative_rule_import_drop_ignore.lark',
  960. rel_to=__file__)
  961. self.assertRaises((ParseError, UnexpectedInput),
  962. l.parse, 'xa abby')
  963. def test_relative_rule_import_subrule(self):
  964. l = _Lark_open('test_relative_rule_import_subrule.lark',
  965. rel_to=__file__)
  966. x = l.parse('xaabby')
  967. self.assertEqual(x.children, [
  968. 'x',
  969. Tree('startab', [
  970. Tree('grammars__ab__expr', [
  971. 'a', Tree('grammars__ab__expr', ['a', 'b']), 'b',
  972. ]),
  973. ]),
  974. 'y'])
  975. def test_relative_rule_import_subrule_no_conflict(self):
  976. l = _Lark_open(
  977. 'test_relative_rule_import_subrule_no_conflict.lark',
  978. rel_to=__file__)
  979. x = l.parse('xaby')
  980. self.assertEqual(x.children, [Tree('expr', [
  981. 'x',
  982. Tree('startab', [
  983. Tree('grammars__ab__expr', ['a', 'b']),
  984. ]),
  985. 'y'])])
  986. self.assertRaises((ParseError, UnexpectedInput),
  987. l.parse, 'xaxabyby')
  988. def test_relative_rule_import_rename(self):
  989. l = _Lark_open('test_relative_rule_import_rename.lark',
  990. rel_to=__file__)
  991. x = l.parse('xaabby')
  992. self.assertEqual(x.children, [
  993. 'x',
  994. Tree('ab', ['a', Tree('ab', ['a', 'b']), 'b']),
  995. 'y'])
  996. def test_multi_import(self):
  997. grammar = """
  998. start: NUMBER WORD
  999. %import common (NUMBER, WORD, WS)
  1000. %ignore WS
  1001. """
  1002. l = _Lark(grammar)
  1003. x = l.parse('12 toucans')
  1004. self.assertEqual(x.children, ['12', 'toucans'])
  1005. def test_relative_multi_import(self):
  1006. l = _Lark_open("test_relative_multi_import.lark", rel_to=__file__)
  1007. x = l.parse('12 capybaras')
  1008. self.assertEqual(x.children, ['12', 'capybaras'])
  1009. def test_relative_import_preserves_leading_underscore(self):
  1010. l = _Lark_open("test_relative_import_preserves_leading_underscore.lark", rel_to=__file__)
  1011. x = l.parse('Ax')
  1012. self.assertEqual(next(x.find_data('c')).children, ['A'])
  1013. def test_relative_import_of_nested_grammar(self):
  1014. l = _Lark_open("grammars/test_relative_import_of_nested_grammar.lark", rel_to=__file__)
  1015. x = l.parse('N')
  1016. self.assertEqual(next(x.find_data('rule_to_import')).children, ['N'])
  1017. def test_relative_import_rules_dependencies_imported_only_once(self):
  1018. l = _Lark_open("test_relative_import_rules_dependencies_imported_only_once.lark", rel_to=__file__)
  1019. x = l.parse('AAA')
  1020. self.assertEqual(next(x.find_data('a')).children, ['A'])
  1021. self.assertEqual(next(x.find_data('b')).children, ['A'])
  1022. self.assertEqual(next(x.find_data('d')).children, ['A'])
  1023. def test_import_errors(self):
  1024. grammar = """
  1025. start: NUMBER WORD
  1026. %import .grammars.bad_test.NUMBER
  1027. """
  1028. self.assertRaises(IOError, _Lark, grammar)
  1029. grammar = """
  1030. start: NUMBER WORD
  1031. %import bad_test.NUMBER
  1032. """
  1033. self.assertRaises(IOError, _Lark, grammar)
  1034. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  1035. def test_earley_prioritization(self):
  1036. "Tests effect of priority on result"
  1037. grammar = """
  1038. start: a | b
  1039. a.1: "a"
  1040. b.2: "a"
  1041. """
  1042. # l = Lark(grammar, parser='earley', lexer='standard')
  1043. l = _Lark(grammar)
  1044. res = l.parse("a")
  1045. self.assertEqual(res.children[0].data, 'b')
  1046. grammar = """
  1047. start: a | b
  1048. a.2: "a"
  1049. b.1: "a"
  1050. """
  1051. l = _Lark(grammar)
  1052. # l = Lark(grammar, parser='earley', lexer='standard')
  1053. res = l.parse("a")
  1054. self.assertEqual(res.children[0].data, 'a')
  1055. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  1056. def test_earley_prioritization_sum(self):
  1057. "Tests effect of priority on result"
  1058. grammar = """
  1059. start: ab_ b_ a_ | indirection
  1060. indirection: a_ bb_ a_
  1061. a_: "a"
  1062. b_: "b"
  1063. ab_: "ab"
  1064. bb_.1: "bb"
  1065. """
  1066. l = Lark(grammar, priority="invert")
  1067. res = l.parse('abba')
  1068. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1069. grammar = """
  1070. start: ab_ b_ a_ | indirection
  1071. indirection: a_ bb_ a_
  1072. a_: "a"
  1073. b_: "b"
  1074. ab_.1: "ab"
  1075. bb_: "bb"
  1076. """
  1077. l = Lark(grammar, priority="invert")
  1078. res = l.parse('abba')
  1079. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1080. grammar = """
  1081. start: ab_ b_ a_ | indirection
  1082. indirection: a_ bb_ a_
  1083. a_.2: "a"
  1084. b_.1: "b"
  1085. ab_.3: "ab"
  1086. bb_.3: "bb"
  1087. """
  1088. l = Lark(grammar, priority="invert")
  1089. res = l.parse('abba')
  1090. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1091. grammar = """
  1092. start: ab_ b_ a_ | indirection
  1093. indirection: a_ bb_ a_
  1094. a_.1: "a"
  1095. b_.1: "b"
  1096. ab_.4: "ab"
  1097. bb_.3: "bb"
  1098. """
  1099. l = Lark(grammar, priority="invert")
  1100. res = l.parse('abba')
  1101. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1102. def test_utf8(self):
  1103. g = u"""start: a
  1104. a: "±a"
  1105. """
  1106. l = _Lark(g)
  1107. self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])]))
  1108. g = u"""start: A
  1109. A: "±a"
  1110. """
  1111. l = _Lark(g)
  1112. self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a']))
  1113. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1114. def test_ignore(self):
  1115. grammar = r"""
  1116. COMMENT: /(!|(\/\/))[^\n]*/
  1117. %ignore COMMENT
  1118. %import common.WS -> _WS
  1119. %import common.INT
  1120. start: "INT"i _WS+ INT _WS*
  1121. """
  1122. parser = _Lark(grammar)
  1123. tree = parser.parse("int 1 ! This is a comment\n")
  1124. self.assertEqual(tree.children, ['1'])
  1125. tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky!
  1126. self.assertEqual(tree.children, ['1'])
  1127. parser = _Lark(r"""
  1128. start : "a"*
  1129. %ignore "b"
  1130. """)
  1131. tree = parser.parse("bb")
  1132. self.assertEqual(tree.children, [])
  1133. def test_regex_escaping(self):
  1134. g = _Lark("start: /[ab]/")
  1135. g.parse('a')
  1136. g.parse('b')
  1137. self.assertRaises( UnexpectedInput, g.parse, 'c')
  1138. _Lark(r'start: /\w/').parse('a')
  1139. g = _Lark(r'start: /\\w/')
  1140. self.assertRaises( UnexpectedInput, g.parse, 'a')
  1141. g.parse(r'\w')
  1142. _Lark(r'start: /\[/').parse('[')
  1143. _Lark(r'start: /\//').parse('/')
  1144. _Lark(r'start: /\\/').parse('\\')
  1145. _Lark(r'start: /\[ab]/').parse('[ab]')
  1146. _Lark(r'start: /\\[ab]/').parse('\\a')
  1147. _Lark(r'start: /\t/').parse('\t')
  1148. _Lark(r'start: /\\t/').parse('\\t')
  1149. _Lark(r'start: /\\\t/').parse('\\\t')
  1150. _Lark(r'start: "\t"').parse('\t')
  1151. _Lark(r'start: "\\t"').parse('\\t')
  1152. _Lark(r'start: "\\\t"').parse('\\\t')
  1153. def test_ranged_repeat_rules(self):
  1154. g = u"""!start: "A"~3
  1155. """
  1156. l = _Lark(g)
  1157. self.assertEqual(l.parse(u'AAA'), Tree('start', ["A", "A", "A"]))
  1158. self.assertRaises(ParseError, l.parse, u'AA')
  1159. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1160. g = u"""!start: "A"~0..2
  1161. """
  1162. if PARSER != 'cyk': # XXX CYK currently doesn't support empty grammars
  1163. l = _Lark(g)
  1164. self.assertEqual(l.parse(u''), Tree('start', []))
  1165. self.assertEqual(l.parse(u'A'), Tree('start', ['A']))
  1166. self.assertEqual(l.parse(u'AA'), Tree('start', ['A', 'A']))
  1167. self.assertRaises((UnexpectedToken, UnexpectedInput), l.parse, u'AAA')
  1168. g = u"""!start: "A"~3..2
  1169. """
  1170. self.assertRaises(GrammarError, _Lark, g)
  1171. g = u"""!start: "A"~2..3 "B"~2
  1172. """
  1173. l = _Lark(g)
  1174. self.assertEqual(l.parse(u'AABB'), Tree('start', ['A', 'A', 'B', 'B']))
  1175. self.assertEqual(l.parse(u'AAABB'), Tree('start', ['A', 'A', 'A', 'B', 'B']))
  1176. self.assertRaises(ParseError, l.parse, u'AAAB')
  1177. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1178. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1179. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1180. def test_ranged_repeat_terms(self):
  1181. g = u"""!start: AAA
  1182. AAA: "A"~3
  1183. """
  1184. l = _Lark(g)
  1185. self.assertEqual(l.parse(u'AAA'), Tree('start', ["AAA"]))
  1186. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AA')
  1187. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1188. g = u"""!start: AABB CC
  1189. AABB: "A"~0..2 "B"~2
  1190. CC: "C"~1..2
  1191. """
  1192. l = _Lark(g)
  1193. self.assertEqual(l.parse(u'AABBCC'), Tree('start', ['AABB', 'CC']))
  1194. self.assertEqual(l.parse(u'BBC'), Tree('start', ['BB', 'C']))
  1195. self.assertEqual(l.parse(u'ABBCC'), Tree('start', ['ABB', 'CC']))
  1196. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAB')
  1197. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1198. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1199. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1200. @unittest.skipIf(PARSER=='earley', "Priority not handled correctly right now") # TODO XXX
  1201. def test_priority_vs_embedded(self):
  1202. g = """
  1203. A.2: "a"
  1204. WORD: ("a".."z")+
  1205. start: (A | WORD)+
  1206. """
  1207. l = _Lark(g)
  1208. t = l.parse('abc')
  1209. self.assertEqual(t.children, ['a', 'bc'])
  1210. self.assertEqual(t.children[0].type, 'A')
  1211. def test_line_counting(self):
  1212. p = _Lark("start: /[^x]+/")
  1213. text = 'hello\nworld'
  1214. t = p.parse(text)
  1215. tok = t.children[0]
  1216. self.assertEqual(tok, text)
  1217. self.assertEqual(tok.line, 1)
  1218. self.assertEqual(tok.column, 1)
  1219. if _LEXER != 'dynamic':
  1220. self.assertEqual(tok.end_line, 2)
  1221. self.assertEqual(tok.end_column, 6)
  1222. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1223. def test_empty_end(self):
  1224. p = _Lark("""
  1225. start: b c d
  1226. b: "B"
  1227. c: | "C"
  1228. d: | "D"
  1229. """)
  1230. res = p.parse('B')
  1231. self.assertEqual(len(res.children), 3)
  1232. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1233. def test_maybe_placeholders(self):
  1234. # Anonymous tokens shouldn't count
  1235. p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1236. self.assertEqual(p.parse("").children, [])
  1237. # All invisible constructs shouldn't count
  1238. p = _Lark("""start: [A] ["b"] [_c] ["e" "f" _c]
  1239. A: "a"
  1240. _c: "c" """, maybe_placeholders=True)
  1241. self.assertEqual(p.parse("").children, [None])
  1242. self.assertEqual(p.parse("c").children, [None])
  1243. self.assertEqual(p.parse("aefc").children, ['a'])
  1244. # ? shouldn't apply
  1245. p = _Lark("""!start: ["a"] "b"? ["c"] """, maybe_placeholders=True)
  1246. self.assertEqual(p.parse("").children, [None, None])
  1247. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1248. p = _Lark("""!start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1249. self.assertEqual(p.parse("").children, [None, None, None])
  1250. self.assertEqual(p.parse("a").children, ['a', None, None])
  1251. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1252. self.assertEqual(p.parse("c").children, [None, None, 'c'])
  1253. self.assertEqual(p.parse("ab").children, ['a', 'b', None])
  1254. self.assertEqual(p.parse("ac").children, ['a', None, 'c'])
  1255. self.assertEqual(p.parse("bc").children, [None, 'b', 'c'])
  1256. self.assertEqual(p.parse("abc").children, ['a', 'b', 'c'])
  1257. p = _Lark("""!start: (["a"] "b" ["c"])+ """, maybe_placeholders=True)
  1258. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1259. self.assertEqual(p.parse("bb").children, [None, 'b', None, None, 'b', None])
  1260. self.assertEqual(p.parse("abbc").children, ['a', 'b', None, None, 'b', 'c'])
  1261. self.assertEqual(p.parse("babbcabcb").children,
  1262. [None, 'b', None,
  1263. 'a', 'b', None,
  1264. None, 'b', 'c',
  1265. 'a', 'b', 'c',
  1266. None, 'b', None])
  1267. p = _Lark("""!start: ["a"] ["c"] "b"+ ["a"] ["d"] """, maybe_placeholders=True)
  1268. self.assertEqual(p.parse("bb").children, [None, None, 'b', 'b', None, None])
  1269. self.assertEqual(p.parse("bd").children, [None, None, 'b', None, 'd'])
  1270. self.assertEqual(p.parse("abba").children, ['a', None, 'b', 'b', 'a', None])
  1271. self.assertEqual(p.parse("cbbbb").children, [None, 'c', 'b', 'b', 'b', 'b', None, None])
  1272. def test_escaped_string(self):
  1273. "Tests common.ESCAPED_STRING"
  1274. grammar = r"""
  1275. start: ESCAPED_STRING+
  1276. %import common (WS_INLINE, ESCAPED_STRING)
  1277. %ignore WS_INLINE
  1278. """
  1279. parser = _Lark(grammar)
  1280. parser.parse(r'"\\" "b" "c"')
  1281. parser.parse(r'"That" "And a \"b"')
  1282. def test_meddling_unused(self):
  1283. "Unless 'unused' is removed, LALR analysis will fail on reduce-reduce collision"
  1284. grammar = """
  1285. start: EKS* x
  1286. x: EKS
  1287. unused: x*
  1288. EKS: "x"
  1289. """
  1290. parser = _Lark(grammar)
  1291. @unittest.skipIf(PARSER!='lalr' or LEXER=='custom', "Serialize currently only works for LALR parsers without custom lexers (though it should be easy to extend)")
  1292. def test_serialize(self):
  1293. grammar = """
  1294. start: _ANY b "C"
  1295. _ANY: /./
  1296. b: "B"
  1297. """
  1298. parser = _Lark(grammar)
  1299. d = parser.serialize()
  1300. parser2 = Lark.deserialize(d, {}, {})
  1301. self.assertEqual(parser2.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1302. namespace = {'Rule': Rule, 'TerminalDef': TerminalDef}
  1303. d, m = parser.memo_serialize(namespace.values())
  1304. parser3 = Lark.deserialize(d, namespace, m)
  1305. self.assertEqual(parser3.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1306. def test_multi_start(self):
  1307. parser = _Lark('''
  1308. a: "x" "a"?
  1309. b: "x" "b"?
  1310. ''', start=['a', 'b'])
  1311. self.assertEqual(parser.parse('xa', 'a'), Tree('a', []))
  1312. self.assertEqual(parser.parse('xb', 'b'), Tree('b', []))
  1313. def test_lexer_detect_newline_tokens(self):
  1314. # Detect newlines in regular tokens
  1315. g = _Lark(r"""start: "go" tail*
  1316. !tail : SA "@" | SB "@" | SC "@" | SD "@"
  1317. SA : "a" /\n/
  1318. SB : /b./s
  1319. SC : "c" /[^a-z]/
  1320. SD : "d" /\s/
  1321. """)
  1322. a,b,c,d = [x.children[1] for x in g.parse('goa\n@b\n@c\n@d\n@').children]
  1323. self.assertEqual(a.line, 2)
  1324. self.assertEqual(b.line, 3)
  1325. self.assertEqual(c.line, 4)
  1326. self.assertEqual(d.line, 5)
  1327. # Detect newlines in ignored tokens
  1328. for re in ['/\\n/', '/[^a-z]/', '/\\s/']:
  1329. g = _Lark('''!start: "a" "a"
  1330. %ignore {}'''.format(re))
  1331. a, b = g.parse('a\na').children
  1332. self.assertEqual(a.line, 1)
  1333. self.assertEqual(b.line, 2)
  1334. _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize()
  1335. _TestParser.__name__ = _NAME
  1336. globals()[_NAME] = _TestParser
  1337. # Note: You still have to import them in __main__ for the tests to run
  1338. _TO_TEST = [
  1339. ('standard', 'earley'),
  1340. ('standard', 'cyk'),
  1341. ('dynamic', 'earley'),
  1342. ('dynamic_complete', 'earley'),
  1343. ('standard', 'lalr'),
  1344. ('contextual', 'lalr'),
  1345. ('custom', 'lalr'),
  1346. # (None, 'earley'),
  1347. ]
  1348. for _LEXER, _PARSER in _TO_TEST:
  1349. _make_parser_test(_LEXER, _PARSER)
  1350. for _LEXER in ('dynamic', 'dynamic_complete'):
  1351. _make_full_earley_test(_LEXER)
  1352. if __name__ == '__main__':
  1353. unittest.main()