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.

1737 lines
59 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_token_collision_WS(self):
  652. g = _Lark(r"""start: "Hello" NAME
  653. NAME: /\w/+
  654. %import common.WS
  655. %ignore WS
  656. """)
  657. x = g.parse('Hello World')
  658. self.assertSequenceEqual(x.children, ['World'])
  659. x = g.parse('Hello HelloWorld')
  660. self.assertSequenceEqual(x.children, ['HelloWorld'])
  661. def test_token_collision2(self):
  662. g = _Lark("""
  663. !start: "starts"
  664. %import common.LCASE_LETTER
  665. """)
  666. x = g.parse("starts")
  667. self.assertSequenceEqual(x.children, ['starts'])
  668. def test_g_regex_flags(self):
  669. g = _Lark("""
  670. start: "a" /b+/ C
  671. C: "C" | D
  672. D: "D" E
  673. E: "e"
  674. """, g_regex_flags=re.I)
  675. x1 = g.parse("ABBc")
  676. x2 = g.parse("abdE")
  677. # def test_string_priority(self):
  678. # g = _Lark("""start: (A | /a?bb/)+
  679. # A: "a" """)
  680. # x = g.parse('abb')
  681. # self.assertEqual(len(x.children), 2)
  682. # # This parse raises an exception because the lexer will always try to consume
  683. # # "a" first and will never match the regular expression
  684. # # This behavior is subject to change!!
  685. # # Thie won't happen with ambiguity handling.
  686. # g = _Lark("""start: (A | /a?ab/)+
  687. # A: "a" """)
  688. # self.assertRaises(LexError, g.parse, 'aab')
  689. def test_undefined_rule(self):
  690. self.assertRaises(GrammarError, _Lark, """start: a""")
  691. def test_undefined_token(self):
  692. self.assertRaises(GrammarError, _Lark, """start: A""")
  693. def test_rule_collision(self):
  694. g = _Lark("""start: "a"+ "b"
  695. | "a"+ """)
  696. x = g.parse('aaaa')
  697. x = g.parse('aaaab')
  698. def test_rule_collision2(self):
  699. g = _Lark("""start: "a"* "b"
  700. | "a"+ """)
  701. x = g.parse('aaaa')
  702. x = g.parse('aaaab')
  703. x = g.parse('b')
  704. def test_token_not_anon(self):
  705. """Tests that "a" is matched as an anonymous token, and not A.
  706. """
  707. g = _Lark("""start: "a"
  708. A: "a" """)
  709. x = g.parse('a')
  710. self.assertEqual(len(x.children), 0, '"a" should be considered anonymous')
  711. g = _Lark("""start: "a" A
  712. A: "a" """)
  713. x = g.parse('aa')
  714. self.assertEqual(len(x.children), 1, 'only "a" should be considered anonymous')
  715. self.assertEqual(x.children[0].type, "A")
  716. g = _Lark("""start: /a/
  717. A: /a/ """)
  718. x = g.parse('a')
  719. self.assertEqual(len(x.children), 1)
  720. self.assertEqual(x.children[0].type, "A", "A isn't associated with /a/")
  721. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  722. def test_maybe(self):
  723. g = _Lark("""start: ["a"] """)
  724. x = g.parse('a')
  725. x = g.parse('')
  726. def test_start(self):
  727. g = _Lark("""a: "a" a? """, start='a')
  728. x = g.parse('a')
  729. x = g.parse('aa')
  730. x = g.parse('aaa')
  731. def test_alias(self):
  732. g = _Lark("""start: "a" -> b """)
  733. x = g.parse('a')
  734. self.assertEqual(x.data, "b")
  735. def test_token_ebnf(self):
  736. g = _Lark("""start: A
  737. A: "a"* ("b"? "c".."e")+
  738. """)
  739. x = g.parse('abcde')
  740. x = g.parse('dd')
  741. def test_backslash(self):
  742. g = _Lark(r"""start: "\\" "a"
  743. """)
  744. x = g.parse(r'\a')
  745. g = _Lark(r"""start: /\\/ /a/
  746. """)
  747. x = g.parse(r'\a')
  748. def test_backslash2(self):
  749. g = _Lark(r"""start: "\"" "-"
  750. """)
  751. x = g.parse('"-')
  752. g = _Lark(r"""start: /\// /-/
  753. """)
  754. x = g.parse('/-')
  755. def test_special_chars(self):
  756. g = _Lark(r"""start: "\n"
  757. """)
  758. x = g.parse('\n')
  759. g = _Lark(r"""start: /\n/
  760. """)
  761. x = g.parse('\n')
  762. # def test_token_recurse(self):
  763. # g = _Lark("""start: A
  764. # A: B
  765. # B: A
  766. # """)
  767. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  768. def test_empty(self):
  769. # Fails an Earley implementation without special handling for empty rules,
  770. # or re-processing of already completed rules.
  771. g = _Lark(r"""start: _empty a "B"
  772. a: _empty "A"
  773. _empty:
  774. """)
  775. x = g.parse('AB')
  776. def test_regex_quote(self):
  777. g = r"""
  778. start: SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING
  779. SINGLE_QUOTED_STRING : /'[^']*'/
  780. DOUBLE_QUOTED_STRING : /"[^"]*"/
  781. """
  782. g = _Lark(g)
  783. self.assertEqual( g.parse('"hello"').children, ['"hello"'])
  784. self.assertEqual( g.parse("'hello'").children, ["'hello'"])
  785. def test_lexer_token_limit(self):
  786. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  787. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  788. g = _Lark("""start: %s
  789. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  790. def test_float_without_lexer(self):
  791. expected_error = UnexpectedCharacters if LEXER.startswith('dynamic') else UnexpectedToken
  792. if PARSER == 'cyk':
  793. expected_error = ParseError
  794. g = _Lark("""start: ["+"|"-"] float
  795. float: digit* "." digit+ exp?
  796. | digit+ exp
  797. exp: ("e"|"E") ["+"|"-"] digit+
  798. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  799. """)
  800. g.parse("1.2")
  801. g.parse("-.2e9")
  802. g.parse("+2e-9")
  803. self.assertRaises( expected_error, g.parse, "+2e-9e")
  804. def test_keep_all_tokens(self):
  805. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  806. tree = l.parse('aaa')
  807. self.assertEqual(tree.children, ['a', 'a', 'a'])
  808. def test_token_flags(self):
  809. l = _Lark("""!start: "a"i+
  810. """
  811. )
  812. tree = l.parse('aA')
  813. self.assertEqual(tree.children, ['a', 'A'])
  814. l = _Lark("""!start: /a/i+
  815. """
  816. )
  817. tree = l.parse('aA')
  818. self.assertEqual(tree.children, ['a', 'A'])
  819. # g = """!start: "a"i "a"
  820. # """
  821. # self.assertRaises(GrammarError, _Lark, g)
  822. # g = """!start: /a/i /a/
  823. # """
  824. # self.assertRaises(GrammarError, _Lark, g)
  825. g = """start: NAME "," "a"
  826. NAME: /[a-z_]/i /[a-z0-9_]/i*
  827. """
  828. l = _Lark(g)
  829. tree = l.parse('ab,a')
  830. self.assertEqual(tree.children, ['ab'])
  831. tree = l.parse('AB,a')
  832. self.assertEqual(tree.children, ['AB'])
  833. def test_token_flags3(self):
  834. l = _Lark("""!start: ABC+
  835. ABC: "abc"i
  836. """
  837. )
  838. tree = l.parse('aBcAbC')
  839. self.assertEqual(tree.children, ['aBc', 'AbC'])
  840. def test_token_flags2(self):
  841. g = """!start: ("a"i | /a/ /b/?)+
  842. """
  843. l = _Lark(g)
  844. tree = l.parse('aA')
  845. self.assertEqual(tree.children, ['a', 'A'])
  846. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  847. def test_twice_empty(self):
  848. g = """!start: ("A"?)?
  849. """
  850. l = _Lark(g)
  851. tree = l.parse('A')
  852. self.assertEqual(tree.children, ['A'])
  853. tree = l.parse('')
  854. self.assertEqual(tree.children, [])
  855. def test_undefined_ignore(self):
  856. g = """!start: "A"
  857. %ignore B
  858. """
  859. self.assertRaises( GrammarError, _Lark, g)
  860. def test_alias_in_terminal(self):
  861. g = """start: TERM
  862. TERM: "a" -> alias
  863. """
  864. self.assertRaises( GrammarError, _Lark, g)
  865. def test_line_and_column(self):
  866. g = r"""!start: "A" bc "D"
  867. !bc: "B\nC"
  868. """
  869. l = _Lark(g)
  870. a, bc, d = l.parse("AB\nCD").children
  871. self.assertEqual(a.line, 1)
  872. self.assertEqual(a.column, 1)
  873. bc ,= bc.children
  874. self.assertEqual(bc.line, 1)
  875. self.assertEqual(bc.column, 2)
  876. self.assertEqual(d.line, 2)
  877. self.assertEqual(d.column, 2)
  878. if LEXER != 'dynamic':
  879. self.assertEqual(a.end_line, 1)
  880. self.assertEqual(a.end_column, 2)
  881. self.assertEqual(bc.end_line, 2)
  882. self.assertEqual(bc.end_column, 2)
  883. self.assertEqual(d.end_line, 2)
  884. self.assertEqual(d.end_column, 3)
  885. def test_reduce_cycle(self):
  886. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  887. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  888. """
  889. l = _Lark("""
  890. term: A
  891. | term term
  892. A: "a"
  893. """, start='term')
  894. tree = l.parse("aa")
  895. self.assertEqual(len(tree.children), 2)
  896. @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority")
  897. def test_lexer_prioritization(self):
  898. "Tests effect of priority on result"
  899. grammar = """
  900. start: A B | AB
  901. A.2: "a"
  902. B: "b"
  903. AB: "ab"
  904. """
  905. l = _Lark(grammar)
  906. res = l.parse("ab")
  907. self.assertEqual(res.children, ['a', 'b'])
  908. self.assertNotEqual(res.children, ['ab'])
  909. grammar = """
  910. start: A B | AB
  911. A: "a"
  912. B: "b"
  913. AB.3: "ab"
  914. """
  915. l = _Lark(grammar)
  916. res = l.parse("ab")
  917. self.assertNotEqual(res.children, ['a', 'b'])
  918. self.assertEqual(res.children, ['ab'])
  919. grammar = """
  920. start: A B | AB
  921. A: "a"
  922. B.-20: "b"
  923. AB.-10: "ab"
  924. """
  925. l = _Lark(grammar)
  926. res = l.parse("ab")
  927. self.assertEqual(res.children, ['a', 'b'])
  928. grammar = """
  929. start: A B | AB
  930. A.-99999999999999999999999: "a"
  931. B: "b"
  932. AB: "ab"
  933. """
  934. l = _Lark(grammar)
  935. res = l.parse("ab")
  936. self.assertEqual(res.children, ['ab'])
  937. def test_import(self):
  938. grammar = """
  939. start: NUMBER WORD
  940. %import common.NUMBER
  941. %import common.WORD
  942. %import common.WS
  943. %ignore WS
  944. """
  945. l = _Lark(grammar)
  946. x = l.parse('12 elephants')
  947. self.assertEqual(x.children, ['12', 'elephants'])
  948. def test_import_rename(self):
  949. grammar = """
  950. start: N W
  951. %import common.NUMBER -> N
  952. %import common.WORD -> W
  953. %import common.WS
  954. %ignore WS
  955. """
  956. l = _Lark(grammar)
  957. x = l.parse('12 elephants')
  958. self.assertEqual(x.children, ['12', 'elephants'])
  959. def test_relative_import(self):
  960. l = _Lark_open('test_relative_import.lark', rel_to=__file__)
  961. x = l.parse('12 lions')
  962. self.assertEqual(x.children, ['12', 'lions'])
  963. def test_relative_import_unicode(self):
  964. l = _Lark_open('test_relative_import_unicode.lark', rel_to=__file__)
  965. x = l.parse(u'Ø')
  966. self.assertEqual(x.children, [u'Ø'])
  967. def test_relative_import_rename(self):
  968. l = _Lark_open('test_relative_import_rename.lark', rel_to=__file__)
  969. x = l.parse('12 lions')
  970. self.assertEqual(x.children, ['12', 'lions'])
  971. def test_relative_rule_import(self):
  972. l = _Lark_open('test_relative_rule_import.lark', rel_to=__file__)
  973. x = l.parse('xaabby')
  974. self.assertEqual(x.children, [
  975. 'x',
  976. Tree('expr', ['a', Tree('expr', ['a', 'b']), 'b']),
  977. 'y'])
  978. def test_relative_rule_import_drop_ignore(self):
  979. # %ignore rules are dropped on import
  980. l = _Lark_open('test_relative_rule_import_drop_ignore.lark',
  981. rel_to=__file__)
  982. self.assertRaises((ParseError, UnexpectedInput),
  983. l.parse, 'xa abby')
  984. def test_relative_rule_import_subrule(self):
  985. l = _Lark_open('test_relative_rule_import_subrule.lark',
  986. rel_to=__file__)
  987. x = l.parse('xaabby')
  988. self.assertEqual(x.children, [
  989. 'x',
  990. Tree('startab', [
  991. Tree('grammars__ab__expr', [
  992. 'a', Tree('grammars__ab__expr', ['a', 'b']), 'b',
  993. ]),
  994. ]),
  995. 'y'])
  996. def test_relative_rule_import_subrule_no_conflict(self):
  997. l = _Lark_open(
  998. 'test_relative_rule_import_subrule_no_conflict.lark',
  999. rel_to=__file__)
  1000. x = l.parse('xaby')
  1001. self.assertEqual(x.children, [Tree('expr', [
  1002. 'x',
  1003. Tree('startab', [
  1004. Tree('grammars__ab__expr', ['a', 'b']),
  1005. ]),
  1006. 'y'])])
  1007. self.assertRaises((ParseError, UnexpectedInput),
  1008. l.parse, 'xaxabyby')
  1009. def test_relative_rule_import_rename(self):
  1010. l = _Lark_open('test_relative_rule_import_rename.lark',
  1011. rel_to=__file__)
  1012. x = l.parse('xaabby')
  1013. self.assertEqual(x.children, [
  1014. 'x',
  1015. Tree('ab', ['a', Tree('ab', ['a', 'b']), 'b']),
  1016. 'y'])
  1017. def test_multi_import(self):
  1018. grammar = """
  1019. start: NUMBER WORD
  1020. %import common (NUMBER, WORD, WS)
  1021. %ignore WS
  1022. """
  1023. l = _Lark(grammar)
  1024. x = l.parse('12 toucans')
  1025. self.assertEqual(x.children, ['12', 'toucans'])
  1026. def test_relative_multi_import(self):
  1027. l = _Lark_open("test_relative_multi_import.lark", rel_to=__file__)
  1028. x = l.parse('12 capybaras')
  1029. self.assertEqual(x.children, ['12', 'capybaras'])
  1030. def test_relative_import_preserves_leading_underscore(self):
  1031. l = _Lark_open("test_relative_import_preserves_leading_underscore.lark", rel_to=__file__)
  1032. x = l.parse('Ax')
  1033. self.assertEqual(next(x.find_data('c')).children, ['A'])
  1034. def test_relative_import_of_nested_grammar(self):
  1035. l = _Lark_open("grammars/test_relative_import_of_nested_grammar.lark", rel_to=__file__)
  1036. x = l.parse('N')
  1037. self.assertEqual(next(x.find_data('rule_to_import')).children, ['N'])
  1038. def test_relative_import_rules_dependencies_imported_only_once(self):
  1039. l = _Lark_open("test_relative_import_rules_dependencies_imported_only_once.lark", rel_to=__file__)
  1040. x = l.parse('AAA')
  1041. self.assertEqual(next(x.find_data('a')).children, ['A'])
  1042. self.assertEqual(next(x.find_data('b')).children, ['A'])
  1043. self.assertEqual(next(x.find_data('d')).children, ['A'])
  1044. def test_import_errors(self):
  1045. grammar = """
  1046. start: NUMBER WORD
  1047. %import .grammars.bad_test.NUMBER
  1048. """
  1049. self.assertRaises(IOError, _Lark, grammar)
  1050. grammar = """
  1051. start: NUMBER WORD
  1052. %import bad_test.NUMBER
  1053. """
  1054. self.assertRaises(IOError, _Lark, grammar)
  1055. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  1056. def test_earley_prioritization(self):
  1057. "Tests effect of priority on result"
  1058. grammar = """
  1059. start: a | b
  1060. a.1: "a"
  1061. b.2: "a"
  1062. """
  1063. # l = Lark(grammar, parser='earley', lexer='standard')
  1064. l = _Lark(grammar)
  1065. res = l.parse("a")
  1066. self.assertEqual(res.children[0].data, 'b')
  1067. grammar = """
  1068. start: a | b
  1069. a.2: "a"
  1070. b.1: "a"
  1071. """
  1072. l = _Lark(grammar)
  1073. # l = Lark(grammar, parser='earley', lexer='standard')
  1074. res = l.parse("a")
  1075. self.assertEqual(res.children[0].data, 'a')
  1076. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  1077. def test_earley_prioritization_sum(self):
  1078. "Tests effect of priority on result"
  1079. grammar = """
  1080. start: ab_ b_ a_ | indirection
  1081. indirection: a_ bb_ a_
  1082. a_: "a"
  1083. b_: "b"
  1084. ab_: "ab"
  1085. bb_.1: "bb"
  1086. """
  1087. l = Lark(grammar, priority="invert")
  1088. res = l.parse('abba')
  1089. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1090. grammar = """
  1091. start: ab_ b_ a_ | indirection
  1092. indirection: a_ bb_ a_
  1093. a_: "a"
  1094. b_: "b"
  1095. ab_.1: "ab"
  1096. bb_: "bb"
  1097. """
  1098. l = Lark(grammar, priority="invert")
  1099. res = l.parse('abba')
  1100. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1101. grammar = """
  1102. start: ab_ b_ a_ | indirection
  1103. indirection: a_ bb_ a_
  1104. a_.2: "a"
  1105. b_.1: "b"
  1106. ab_.3: "ab"
  1107. bb_.3: "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_.1: "a"
  1116. b_.1: "b"
  1117. ab_.4: "ab"
  1118. bb_.3: "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. def test_utf8(self):
  1124. g = u"""start: a
  1125. a: "±a"
  1126. """
  1127. l = _Lark(g)
  1128. self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])]))
  1129. g = u"""start: A
  1130. A: "±a"
  1131. """
  1132. l = _Lark(g)
  1133. self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a']))
  1134. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1135. def test_ignore(self):
  1136. grammar = r"""
  1137. COMMENT: /(!|(\/\/))[^\n]*/
  1138. %ignore COMMENT
  1139. %import common.WS -> _WS
  1140. %import common.INT
  1141. start: "INT"i _WS+ INT _WS*
  1142. """
  1143. parser = _Lark(grammar)
  1144. tree = parser.parse("int 1 ! This is a comment\n")
  1145. self.assertEqual(tree.children, ['1'])
  1146. tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky!
  1147. self.assertEqual(tree.children, ['1'])
  1148. parser = _Lark(r"""
  1149. start : "a"*
  1150. %ignore "b"
  1151. """)
  1152. tree = parser.parse("bb")
  1153. self.assertEqual(tree.children, [])
  1154. def test_regex_escaping(self):
  1155. g = _Lark("start: /[ab]/")
  1156. g.parse('a')
  1157. g.parse('b')
  1158. self.assertRaises( UnexpectedInput, g.parse, 'c')
  1159. _Lark(r'start: /\w/').parse('a')
  1160. g = _Lark(r'start: /\\w/')
  1161. self.assertRaises( UnexpectedInput, g.parse, 'a')
  1162. g.parse(r'\w')
  1163. _Lark(r'start: /\[/').parse('[')
  1164. _Lark(r'start: /\//').parse('/')
  1165. _Lark(r'start: /\\/').parse('\\')
  1166. _Lark(r'start: /\[ab]/').parse('[ab]')
  1167. _Lark(r'start: /\\[ab]/').parse('\\a')
  1168. _Lark(r'start: /\t/').parse('\t')
  1169. _Lark(r'start: /\\t/').parse('\\t')
  1170. _Lark(r'start: /\\\t/').parse('\\\t')
  1171. _Lark(r'start: "\t"').parse('\t')
  1172. _Lark(r'start: "\\t"').parse('\\t')
  1173. _Lark(r'start: "\\\t"').parse('\\\t')
  1174. def test_ranged_repeat_rules(self):
  1175. g = u"""!start: "A"~3
  1176. """
  1177. l = _Lark(g)
  1178. self.assertEqual(l.parse(u'AAA'), Tree('start', ["A", "A", "A"]))
  1179. self.assertRaises(ParseError, l.parse, u'AA')
  1180. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1181. g = u"""!start: "A"~0..2
  1182. """
  1183. if PARSER != 'cyk': # XXX CYK currently doesn't support empty grammars
  1184. l = _Lark(g)
  1185. self.assertEqual(l.parse(u''), Tree('start', []))
  1186. self.assertEqual(l.parse(u'A'), Tree('start', ['A']))
  1187. self.assertEqual(l.parse(u'AA'), Tree('start', ['A', 'A']))
  1188. self.assertRaises((UnexpectedToken, UnexpectedInput), l.parse, u'AAA')
  1189. g = u"""!start: "A"~3..2
  1190. """
  1191. self.assertRaises(GrammarError, _Lark, g)
  1192. g = u"""!start: "A"~2..3 "B"~2
  1193. """
  1194. l = _Lark(g)
  1195. self.assertEqual(l.parse(u'AABB'), Tree('start', ['A', 'A', 'B', 'B']))
  1196. self.assertEqual(l.parse(u'AAABB'), Tree('start', ['A', 'A', 'A', 'B', 'B']))
  1197. self.assertRaises(ParseError, l.parse, u'AAAB')
  1198. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1199. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1200. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1201. def test_ranged_repeat_terms(self):
  1202. g = u"""!start: AAA
  1203. AAA: "A"~3
  1204. """
  1205. l = _Lark(g)
  1206. self.assertEqual(l.parse(u'AAA'), Tree('start', ["AAA"]))
  1207. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AA')
  1208. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1209. g = u"""!start: AABB CC
  1210. AABB: "A"~0..2 "B"~2
  1211. CC: "C"~1..2
  1212. """
  1213. l = _Lark(g)
  1214. self.assertEqual(l.parse(u'AABBCC'), Tree('start', ['AABB', 'CC']))
  1215. self.assertEqual(l.parse(u'BBC'), Tree('start', ['BB', 'C']))
  1216. self.assertEqual(l.parse(u'ABBCC'), Tree('start', ['ABB', 'CC']))
  1217. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAB')
  1218. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1219. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1220. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1221. @unittest.skipIf(PARSER=='earley', "Priority not handled correctly right now") # TODO XXX
  1222. def test_priority_vs_embedded(self):
  1223. g = """
  1224. A.2: "a"
  1225. WORD: ("a".."z")+
  1226. start: (A | WORD)+
  1227. """
  1228. l = _Lark(g)
  1229. t = l.parse('abc')
  1230. self.assertEqual(t.children, ['a', 'bc'])
  1231. self.assertEqual(t.children[0].type, 'A')
  1232. def test_line_counting(self):
  1233. p = _Lark("start: /[^x]+/")
  1234. text = 'hello\nworld'
  1235. t = p.parse(text)
  1236. tok = t.children[0]
  1237. self.assertEqual(tok, text)
  1238. self.assertEqual(tok.line, 1)
  1239. self.assertEqual(tok.column, 1)
  1240. if _LEXER != 'dynamic':
  1241. self.assertEqual(tok.end_line, 2)
  1242. self.assertEqual(tok.end_column, 6)
  1243. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1244. def test_empty_end(self):
  1245. p = _Lark("""
  1246. start: b c d
  1247. b: "B"
  1248. c: | "C"
  1249. d: | "D"
  1250. """)
  1251. res = p.parse('B')
  1252. self.assertEqual(len(res.children), 3)
  1253. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1254. def test_maybe_placeholders(self):
  1255. # Anonymous tokens shouldn't count
  1256. p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1257. self.assertEqual(p.parse("").children, [])
  1258. # All invisible constructs shouldn't count
  1259. p = _Lark("""start: [A] ["b"] [_c] ["e" "f" _c]
  1260. A: "a"
  1261. _c: "c" """, maybe_placeholders=True)
  1262. self.assertEqual(p.parse("").children, [None])
  1263. self.assertEqual(p.parse("c").children, [None])
  1264. self.assertEqual(p.parse("aefc").children, ['a'])
  1265. # ? shouldn't apply
  1266. p = _Lark("""!start: ["a"] "b"? ["c"] """, maybe_placeholders=True)
  1267. self.assertEqual(p.parse("").children, [None, None])
  1268. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1269. p = _Lark("""!start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1270. self.assertEqual(p.parse("").children, [None, None, None])
  1271. self.assertEqual(p.parse("a").children, ['a', None, None])
  1272. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1273. self.assertEqual(p.parse("c").children, [None, None, 'c'])
  1274. self.assertEqual(p.parse("ab").children, ['a', 'b', None])
  1275. self.assertEqual(p.parse("ac").children, ['a', None, 'c'])
  1276. self.assertEqual(p.parse("bc").children, [None, 'b', 'c'])
  1277. self.assertEqual(p.parse("abc").children, ['a', 'b', 'c'])
  1278. p = _Lark("""!start: (["a"] "b" ["c"])+ """, maybe_placeholders=True)
  1279. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1280. self.assertEqual(p.parse("bb").children, [None, 'b', None, None, 'b', None])
  1281. self.assertEqual(p.parse("abbc").children, ['a', 'b', None, None, 'b', 'c'])
  1282. self.assertEqual(p.parse("babbcabcb").children,
  1283. [None, 'b', None,
  1284. 'a', 'b', None,
  1285. None, 'b', 'c',
  1286. 'a', 'b', 'c',
  1287. None, 'b', None])
  1288. p = _Lark("""!start: ["a"] ["c"] "b"+ ["a"] ["d"] """, maybe_placeholders=True)
  1289. self.assertEqual(p.parse("bb").children, [None, None, 'b', 'b', None, None])
  1290. self.assertEqual(p.parse("bd").children, [None, None, 'b', None, 'd'])
  1291. self.assertEqual(p.parse("abba").children, ['a', None, 'b', 'b', 'a', None])
  1292. self.assertEqual(p.parse("cbbbb").children, [None, 'c', 'b', 'b', 'b', 'b', None, None])
  1293. def test_escaped_string(self):
  1294. "Tests common.ESCAPED_STRING"
  1295. grammar = r"""
  1296. start: ESCAPED_STRING+
  1297. %import common (WS_INLINE, ESCAPED_STRING)
  1298. %ignore WS_INLINE
  1299. """
  1300. parser = _Lark(grammar)
  1301. parser.parse(r'"\\" "b" "c"')
  1302. parser.parse(r'"That" "And a \"b"')
  1303. def test_meddling_unused(self):
  1304. "Unless 'unused' is removed, LALR analysis will fail on reduce-reduce collision"
  1305. grammar = """
  1306. start: EKS* x
  1307. x: EKS
  1308. unused: x*
  1309. EKS: "x"
  1310. """
  1311. parser = _Lark(grammar)
  1312. @unittest.skipIf(PARSER!='lalr' or LEXER=='custom', "Serialize currently only works for LALR parsers without custom lexers (though it should be easy to extend)")
  1313. def test_serialize(self):
  1314. grammar = """
  1315. start: _ANY b "C"
  1316. _ANY: /./
  1317. b: "B"
  1318. """
  1319. parser = _Lark(grammar)
  1320. d = parser.serialize()
  1321. parser2 = Lark.deserialize(d, {}, {})
  1322. self.assertEqual(parser2.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1323. namespace = {'Rule': Rule, 'TerminalDef': TerminalDef}
  1324. d, m = parser.memo_serialize(namespace.values())
  1325. parser3 = Lark.deserialize(d, namespace, m)
  1326. self.assertEqual(parser3.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1327. def test_multi_start(self):
  1328. parser = _Lark('''
  1329. a: "x" "a"?
  1330. b: "x" "b"?
  1331. ''', start=['a', 'b'])
  1332. self.assertEqual(parser.parse('xa', 'a'), Tree('a', []))
  1333. self.assertEqual(parser.parse('xb', 'b'), Tree('b', []))
  1334. def test_lexer_detect_newline_tokens(self):
  1335. # Detect newlines in regular tokens
  1336. g = _Lark(r"""start: "go" tail*
  1337. !tail : SA "@" | SB "@" | SC "@" | SD "@"
  1338. SA : "a" /\n/
  1339. SB : /b./s
  1340. SC : "c" /[^a-z]/
  1341. SD : "d" /\s/
  1342. """)
  1343. a,b,c,d = [x.children[1] for x in g.parse('goa\n@b\n@c\n@d\n@').children]
  1344. self.assertEqual(a.line, 2)
  1345. self.assertEqual(b.line, 3)
  1346. self.assertEqual(c.line, 4)
  1347. self.assertEqual(d.line, 5)
  1348. # Detect newlines in ignored tokens
  1349. for re in ['/\\n/', '/[^a-z]/', '/\\s/']:
  1350. g = _Lark('''!start: "a" "a"
  1351. %ignore {}'''.format(re))
  1352. a, b = g.parse('a\na').children
  1353. self.assertEqual(a.line, 1)
  1354. self.assertEqual(b.line, 2)
  1355. _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize()
  1356. _TestParser.__name__ = _NAME
  1357. _TestParser.__qualname__ = "tests.test_parser." + _NAME
  1358. globals()[_NAME] = _TestParser
  1359. # Note: You still have to import them in __main__ for the tests to run
  1360. _TO_TEST = [
  1361. ('standard', 'earley'),
  1362. ('standard', 'cyk'),
  1363. ('dynamic', 'earley'),
  1364. ('dynamic_complete', 'earley'),
  1365. ('standard', 'lalr'),
  1366. ('contextual', 'lalr'),
  1367. ('custom', 'lalr'),
  1368. # (None, 'earley'),
  1369. ]
  1370. for _LEXER, _PARSER in _TO_TEST:
  1371. _make_parser_test(_LEXER, _PARSER)
  1372. for _LEXER in ('dynamic', 'dynamic_complete'):
  1373. _make_full_earley_test(_LEXER)
  1374. if __name__ == '__main__':
  1375. unittest.main()