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.

1761 lines
60 KiB

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