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.

2383 lines
82 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 copy, deepcopy
  9. from lark.utils import Py36, isascii
  10. from lark import Token
  11. from lark.load_grammar import FromPackageLoader
  12. try:
  13. from cStringIO import StringIO as cStringIO
  14. except ImportError:
  15. # Available only in Python 2.x, 3.x only has io.StringIO from below
  16. cStringIO = None
  17. from io import (
  18. StringIO as uStringIO,
  19. BytesIO,
  20. open,
  21. )
  22. try:
  23. import regex
  24. except ImportError:
  25. regex = None
  26. from lark import logger
  27. from lark.lark import Lark
  28. from lark.exceptions import GrammarError, ParseError, UnexpectedToken, UnexpectedInput, UnexpectedCharacters
  29. from lark.tree import Tree
  30. from lark.visitors import Transformer, Transformer_InPlace, v_args
  31. from lark.grammar import Rule
  32. from lark.lexer import TerminalDef, Lexer, TraditionalLexer
  33. logger.setLevel(logging.INFO)
  34. __path__ = os.path.dirname(__file__)
  35. def _read(n, *args):
  36. with open(os.path.join(__path__, n), *args) as f:
  37. return f.read()
  38. class TestParsers(unittest.TestCase):
  39. def test_big_list(self):
  40. Lark(r"""
  41. start: {}
  42. """.format(
  43. "|".join(['"%s"'%i for i in range(250)])
  44. ))
  45. def test_same_ast(self):
  46. "Tests that Earley and LALR parsers produce equal trees"
  47. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  48. name_list: NAME | name_list "," NAME
  49. NAME: /\w+/ """, parser='lalr')
  50. l = g.parse('(a,b,c,*x)')
  51. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  52. name_list: NAME | name_list "," NAME
  53. NAME: /\w/+ """)
  54. l2 = g.parse('(a,b,c,*x)')
  55. assert l == l2, '%s != %s' % (l.pretty(), l2.pretty())
  56. def test_infinite_recurse(self):
  57. g = """start: a
  58. a: a | "a"
  59. """
  60. self.assertRaises(GrammarError, Lark, g, parser='lalr')
  61. # TODO: should it? shouldn't it?
  62. # l = Lark(g, parser='earley', lexer='dynamic')
  63. # self.assertRaises(ParseError, l.parse, 'a')
  64. def test_propagate_positions(self):
  65. g = Lark("""start: a
  66. a: "a"
  67. """, propagate_positions=True)
  68. r = g.parse('a')
  69. self.assertEqual( r.children[0].meta.line, 1 )
  70. g = Lark("""start: x
  71. x: a
  72. a: "a"
  73. """, propagate_positions=True)
  74. r = g.parse('a')
  75. self.assertEqual( r.children[0].meta.line, 1 )
  76. def test_expand1(self):
  77. g = Lark("""start: a
  78. ?a: b
  79. b: "x"
  80. """)
  81. r = g.parse('x')
  82. self.assertEqual( r.children[0].data, "b" )
  83. g = Lark("""start: a
  84. ?a: b -> c
  85. b: "x"
  86. """)
  87. r = g.parse('x')
  88. self.assertEqual( r.children[0].data, "c" )
  89. g = Lark("""start: a
  90. ?a: B -> c
  91. B: "x"
  92. """)
  93. self.assertEqual( r.children[0].data, "c" )
  94. g = Lark("""start: a
  95. ?a: b b -> c
  96. b: "x"
  97. """)
  98. r = g.parse('xx')
  99. self.assertEqual( r.children[0].data, "c" )
  100. def test_comment_in_rule_definition(self):
  101. g = Lark("""start: a
  102. a: "a"
  103. // A comment
  104. // Another comment
  105. | "b"
  106. // Still more
  107. c: "unrelated"
  108. """)
  109. r = g.parse('b')
  110. self.assertEqual( r.children[0].data, "a" )
  111. def test_visit_tokens(self):
  112. class T(Transformer):
  113. def a(self, children):
  114. return children[0] + "!"
  115. def A(self, tok):
  116. return tok.update(value=tok.upper())
  117. # Test regular
  118. g = """start: a
  119. a : A
  120. A: "x"
  121. """
  122. p = Lark(g, parser='lalr')
  123. r = T(False).transform(p.parse("x"))
  124. self.assertEqual( r.children, ["x!"] )
  125. r = T().transform(p.parse("x"))
  126. self.assertEqual( r.children, ["X!"] )
  127. # Test internal transformer
  128. p = Lark(g, parser='lalr', transformer=T())
  129. r = p.parse("x")
  130. self.assertEqual( r.children, ["X!"] )
  131. def test_vargs_meta(self):
  132. @v_args(meta=True)
  133. class T1(Transformer):
  134. def a(self, children, meta):
  135. assert not children
  136. return meta.line
  137. def start(self, children, meta):
  138. return children
  139. @v_args(meta=True, inline=True)
  140. class T2(Transformer):
  141. def a(self, meta):
  142. return meta.line
  143. def start(self, meta, *res):
  144. return list(res)
  145. for T in (T1, T2):
  146. for internal in [False, True]:
  147. try:
  148. g = Lark(r"""start: a+
  149. a : "x" _NL?
  150. _NL: /\n/+
  151. """, parser='lalr', transformer=T() if internal else None, propagate_positions=True)
  152. except NotImplementedError:
  153. assert internal
  154. continue
  155. res = g.parse("xx\nx\nxxx\n\n\nxx")
  156. assert not internal
  157. res = T().transform(res)
  158. self.assertEqual(res, [1, 1, 2, 3, 3, 3, 6, 6])
  159. def test_vargs_tree(self):
  160. tree = Lark('''
  161. start: a a a
  162. !a: "A"
  163. ''').parse('AAA')
  164. tree_copy = deepcopy(tree)
  165. @v_args(tree=True)
  166. class T(Transformer):
  167. def a(self, tree):
  168. return 1
  169. def start(self, tree):
  170. return tree.children
  171. res = T().transform(tree)
  172. self.assertEqual(res, [1, 1, 1])
  173. self.assertEqual(tree, tree_copy)
  174. def test_embedded_transformer(self):
  175. class T(Transformer):
  176. def a(self, children):
  177. return "<a>"
  178. def b(self, children):
  179. return "<b>"
  180. def c(self, children):
  181. return "<c>"
  182. # Test regular
  183. g = Lark("""start: a
  184. a : "x"
  185. """, parser='lalr')
  186. r = T().transform(g.parse("x"))
  187. self.assertEqual( r.children, ["<a>"] )
  188. g = Lark("""start: a
  189. a : "x"
  190. """, parser='lalr', transformer=T())
  191. r = g.parse("x")
  192. self.assertEqual( r.children, ["<a>"] )
  193. # Test Expand1
  194. g = Lark("""start: a
  195. ?a : b
  196. b : "x"
  197. """, parser='lalr')
  198. r = T().transform(g.parse("x"))
  199. self.assertEqual( r.children, ["<b>"] )
  200. g = Lark("""start: a
  201. ?a : b
  202. b : "x"
  203. """, parser='lalr', transformer=T())
  204. r = g.parse("x")
  205. self.assertEqual( r.children, ["<b>"] )
  206. # Test Expand1 -> Alias
  207. g = Lark("""start: a
  208. ?a : b b -> c
  209. b : "x"
  210. """, parser='lalr')
  211. r = T().transform(g.parse("xx"))
  212. self.assertEqual( r.children, ["<c>"] )
  213. g = Lark("""start: a
  214. ?a : b b -> c
  215. b : "x"
  216. """, parser='lalr', transformer=T())
  217. r = g.parse("xx")
  218. self.assertEqual( r.children, ["<c>"] )
  219. def test_embedded_transformer_inplace(self):
  220. @v_args(tree=True)
  221. class T1(Transformer_InPlace):
  222. def a(self, tree):
  223. assert isinstance(tree, Tree), tree
  224. tree.children.append("tested")
  225. return tree
  226. def b(self, tree):
  227. return Tree(tree.data, tree.children + ['tested2'])
  228. @v_args(tree=True)
  229. class T2(Transformer):
  230. def a(self, tree):
  231. assert isinstance(tree, Tree), tree
  232. tree.children.append("tested")
  233. return tree
  234. def b(self, tree):
  235. return Tree(tree.data, tree.children + ['tested2'])
  236. class T3(Transformer):
  237. @v_args(tree=True)
  238. def a(self, tree):
  239. assert isinstance(tree, Tree)
  240. tree.children.append("tested")
  241. return tree
  242. @v_args(tree=True)
  243. def b(self, tree):
  244. return Tree(tree.data, tree.children + ['tested2'])
  245. for t in [T1(), T2(), T3()]:
  246. for internal in [False, True]:
  247. g = Lark("""start: a b
  248. a : "x"
  249. b : "y"
  250. """, parser='lalr', transformer=t if internal else None)
  251. r = g.parse("xy")
  252. if not internal:
  253. r = t.transform(r)
  254. a, b = r.children
  255. self.assertEqual(a.children, ["tested"])
  256. self.assertEqual(b.children, ["tested2"])
  257. def test_alias(self):
  258. Lark("""start: ["a"] "b" ["c"] "e" ["f"] ["g"] ["h"] "x" -> d """)
  259. def _make_full_earley_test(LEXER):
  260. def _Lark(grammar, **kwargs):
  261. return Lark(grammar, lexer=LEXER, parser='earley', propagate_positions=True, **kwargs)
  262. class _TestFullEarley(unittest.TestCase):
  263. def test_anon(self):
  264. # Fails an Earley implementation without special handling for empty rules,
  265. # or re-processing of already completed rules.
  266. g = Lark(r"""start: B
  267. B: ("ab"|/[^b]/)+
  268. """, lexer=LEXER)
  269. self.assertEqual( g.parse('abc').children[0], 'abc')
  270. def test_earley(self):
  271. g = Lark("""start: A "b" c
  272. A: "a"+
  273. c: "abc"
  274. """, parser="earley", lexer=LEXER)
  275. x = g.parse('aaaababc')
  276. def test_earley2(self):
  277. grammar = """
  278. start: statement+
  279. statement: "r"
  280. | "c" /[a-z]/+
  281. %ignore " "
  282. """
  283. program = """c b r"""
  284. l = Lark(grammar, parser='earley', lexer=LEXER)
  285. l.parse(program)
  286. @unittest.skipIf(LEXER=='dynamic', "Only relevant for the dynamic_complete parser")
  287. def test_earley3(self):
  288. """Tests prioritization and disambiguation for pseudo-terminals (there should be only one result)
  289. By default, `+` should immitate regexp greedy-matching
  290. """
  291. grammar = """
  292. start: A A
  293. A: "a"+
  294. """
  295. l = Lark(grammar, parser='earley', lexer=LEXER)
  296. res = l.parse("aaa")
  297. self.assertEqual(set(res.children), {'aa', 'a'})
  298. # XXX TODO fix Earley to maintain correct order
  299. # i.e. terminals it imitate greedy search for terminals, but lazy search for rules
  300. # self.assertEqual(res.children, ['aa', 'a'])
  301. def test_earley4(self):
  302. grammar = """
  303. start: A A?
  304. A: "a"+
  305. """
  306. l = Lark(grammar, parser='earley', lexer=LEXER)
  307. res = l.parse("aaa")
  308. assert set(res.children) == {'aa', 'a'} or res.children == ['aaa']
  309. # XXX TODO fix Earley to maintain correct order
  310. # i.e. terminals it imitate greedy search for terminals, but lazy search for rules
  311. # self.assertEqual(res.children, ['aaa'])
  312. def test_earley_repeating_empty(self):
  313. # This was a sneaky bug!
  314. grammar = """
  315. !start: "a" empty empty "b"
  316. empty: empty2
  317. empty2:
  318. """
  319. parser = Lark(grammar, parser='earley', lexer=LEXER)
  320. res = parser.parse('ab')
  321. empty_tree = Tree('empty', [Tree('empty2', [])])
  322. self.assertSequenceEqual(res.children, ['a', empty_tree, empty_tree, 'b'])
  323. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  324. def test_earley_explicit_ambiguity(self):
  325. # This was a sneaky bug!
  326. grammar = """
  327. start: a b | ab
  328. a: "a"
  329. b: "b"
  330. ab: "ab"
  331. """
  332. parser = Lark(grammar, parser='earley', lexer=LEXER, ambiguity='explicit')
  333. ambig_tree = parser.parse('ab')
  334. self.assertEqual( ambig_tree.data, '_ambig')
  335. self.assertEqual( len(ambig_tree.children), 2)
  336. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  337. def test_ambiguity1(self):
  338. grammar = """
  339. start: cd+ "e"
  340. !cd: "c"
  341. | "d"
  342. | "cd"
  343. """
  344. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  345. ambig_tree = l.parse('cde')
  346. assert ambig_tree.data == '_ambig', ambig_tree
  347. assert len(ambig_tree.children) == 2
  348. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  349. def test_ambiguity2(self):
  350. grammar = """
  351. ANY: /[a-zA-Z0-9 ]+/
  352. a.2: "A" b+
  353. b.2: "B"
  354. c: ANY
  355. start: (a|c)*
  356. """
  357. l = Lark(grammar, parser='earley', lexer=LEXER)
  358. res = l.parse('ABX')
  359. expected = Tree('start', [
  360. Tree('a', [
  361. Tree('b', [])
  362. ]),
  363. Tree('c', [
  364. 'X'
  365. ])
  366. ])
  367. self.assertEqual(res, expected)
  368. def test_ambiguous_intermediate_node(self):
  369. grammar = """
  370. start: ab bc d?
  371. !ab: "A" "B"?
  372. !bc: "B"? "C"
  373. !d: "D"
  374. """
  375. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  376. ambig_tree = l.parse("ABCD")
  377. expected = {
  378. Tree('start', [Tree('ab', ['A']), Tree('bc', ['B', 'C']), Tree('d', ['D'])]),
  379. Tree('start', [Tree('ab', ['A', 'B']), Tree('bc', ['C']), Tree('d', ['D'])])
  380. }
  381. self.assertEqual(ambig_tree.data, '_ambig')
  382. self.assertEqual(set(ambig_tree.children), expected)
  383. def test_ambiguous_symbol_and_intermediate_nodes(self):
  384. grammar = """
  385. start: ab bc cd
  386. !ab: "A" "B"?
  387. !bc: "B"? "C"?
  388. !cd: "C"? "D"
  389. """
  390. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  391. ambig_tree = l.parse("ABCD")
  392. expected = {
  393. Tree('start', [
  394. Tree('ab', ['A', 'B']),
  395. Tree('bc', ['C']),
  396. Tree('cd', ['D'])
  397. ]),
  398. Tree('start', [
  399. Tree('ab', ['A', 'B']),
  400. Tree('bc', []),
  401. Tree('cd', ['C', 'D'])
  402. ]),
  403. Tree('start', [
  404. Tree('ab', ['A']),
  405. Tree('bc', ['B', 'C']),
  406. Tree('cd', ['D'])
  407. ]),
  408. Tree('start', [
  409. Tree('ab', ['A']),
  410. Tree('bc', ['B']),
  411. Tree('cd', ['C', 'D'])
  412. ]),
  413. }
  414. self.assertEqual(ambig_tree.data, '_ambig')
  415. self.assertEqual(set(ambig_tree.children), expected)
  416. def test_nested_ambiguous_intermediate_nodes(self):
  417. grammar = """
  418. start: ab bc cd e?
  419. !ab: "A" "B"?
  420. !bc: "B"? "C"?
  421. !cd: "C"? "D"
  422. !e: "E"
  423. """
  424. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  425. ambig_tree = l.parse("ABCDE")
  426. expected = {
  427. Tree('start', [
  428. Tree('ab', ['A', 'B']),
  429. Tree('bc', ['C']),
  430. Tree('cd', ['D']),
  431. Tree('e', ['E'])
  432. ]),
  433. Tree('start', [
  434. Tree('ab', ['A']),
  435. Tree('bc', ['B', 'C']),
  436. Tree('cd', ['D']),
  437. Tree('e', ['E'])
  438. ]),
  439. Tree('start', [
  440. Tree('ab', ['A']),
  441. Tree('bc', ['B']),
  442. Tree('cd', ['C', 'D']),
  443. Tree('e', ['E'])
  444. ]),
  445. Tree('start', [
  446. Tree('ab', ['A', 'B']),
  447. Tree('bc', []),
  448. Tree('cd', ['C', 'D']),
  449. Tree('e', ['E'])
  450. ]),
  451. }
  452. self.assertEqual(ambig_tree.data, '_ambig')
  453. self.assertEqual(set(ambig_tree.children), expected)
  454. def test_nested_ambiguous_intermediate_nodes2(self):
  455. grammar = """
  456. start: ab bc cd de f
  457. !ab: "A" "B"?
  458. !bc: "B"? "C"?
  459. !cd: "C"? "D"?
  460. !de: "D"? "E"
  461. !f: "F"
  462. """
  463. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  464. ambig_tree = l.parse("ABCDEF")
  465. expected = {
  466. Tree('start', [
  467. Tree('ab', ['A', 'B']),
  468. Tree('bc', ['C']),
  469. Tree('cd', ['D']),
  470. Tree('de', ['E']),
  471. Tree('f', ['F']),
  472. ]),
  473. Tree('start', [
  474. Tree('ab', ['A']),
  475. Tree('bc', ['B', 'C']),
  476. Tree('cd', ['D']),
  477. Tree('de', ['E']),
  478. Tree('f', ['F']),
  479. ]),
  480. Tree('start', [
  481. Tree('ab', ['A']),
  482. Tree('bc', ['B']),
  483. Tree('cd', ['C', 'D']),
  484. Tree('de', ['E']),
  485. Tree('f', ['F']),
  486. ]),
  487. Tree('start', [
  488. Tree('ab', ['A']),
  489. Tree('bc', ['B']),
  490. Tree('cd', ['C']),
  491. Tree('de', ['D', 'E']),
  492. Tree('f', ['F']),
  493. ]),
  494. Tree('start', [
  495. Tree('ab', ['A', "B"]),
  496. Tree('bc', []),
  497. Tree('cd', ['C']),
  498. Tree('de', ['D', 'E']),
  499. Tree('f', ['F']),
  500. ]),
  501. Tree('start', [
  502. Tree('ab', ['A']),
  503. Tree('bc', ['B', 'C']),
  504. Tree('cd', []),
  505. Tree('de', ['D', 'E']),
  506. Tree('f', ['F']),
  507. ]),
  508. Tree('start', [
  509. Tree('ab', ['A', 'B']),
  510. Tree('bc', []),
  511. Tree('cd', ['C', 'D']),
  512. Tree('de', ['E']),
  513. Tree('f', ['F']),
  514. ]),
  515. Tree('start', [
  516. Tree('ab', ['A', 'B']),
  517. Tree('bc', ['C']),
  518. Tree('cd', []),
  519. Tree('de', ['D', 'E']),
  520. Tree('f', ['F']),
  521. ]),
  522. }
  523. self.assertEqual(ambig_tree.data, '_ambig')
  524. self.assertEqual(set(ambig_tree.children), expected)
  525. def test_ambiguous_intermediate_node_unnamed_token(self):
  526. grammar = """
  527. start: ab bc "D"
  528. !ab: "A" "B"?
  529. !bc: "B"? "C"
  530. """
  531. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  532. ambig_tree = l.parse("ABCD")
  533. expected = {
  534. Tree('start', [Tree('ab', ['A']), Tree('bc', ['B', 'C'])]),
  535. Tree('start', [Tree('ab', ['A', 'B']), Tree('bc', ['C'])])
  536. }
  537. self.assertEqual(ambig_tree.data, '_ambig')
  538. self.assertEqual(set(ambig_tree.children), expected)
  539. def test_ambiguous_intermediate_node_inlined_rule(self):
  540. grammar = """
  541. start: ab _bc d?
  542. !ab: "A" "B"?
  543. _bc: "B"? "C"
  544. !d: "D"
  545. """
  546. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  547. ambig_tree = l.parse("ABCD")
  548. expected = {
  549. Tree('start', [Tree('ab', ['A']), Tree('d', ['D'])]),
  550. Tree('start', [Tree('ab', ['A', 'B']), Tree('d', ['D'])])
  551. }
  552. self.assertEqual(ambig_tree.data, '_ambig')
  553. self.assertEqual(set(ambig_tree.children), expected)
  554. def test_ambiguous_intermediate_node_conditionally_inlined_rule(self):
  555. grammar = """
  556. start: ab bc d?
  557. !ab: "A" "B"?
  558. !?bc: "B"? "C"
  559. !d: "D"
  560. """
  561. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  562. ambig_tree = l.parse("ABCD")
  563. expected = {
  564. Tree('start', [Tree('ab', ['A']), Tree('bc', ['B', 'C']), Tree('d', ['D'])]),
  565. Tree('start', [Tree('ab', ['A', 'B']), 'C', Tree('d', ['D'])])
  566. }
  567. self.assertEqual(ambig_tree.data, '_ambig')
  568. self.assertEqual(set(ambig_tree.children), expected)
  569. def test_fruitflies_ambig(self):
  570. grammar = """
  571. start: noun verb noun -> simple
  572. | noun verb "like" noun -> comparative
  573. noun: adj? NOUN
  574. verb: VERB
  575. adj: ADJ
  576. NOUN: "flies" | "bananas" | "fruit"
  577. VERB: "like" | "flies"
  578. ADJ: "fruit"
  579. %import common.WS
  580. %ignore WS
  581. """
  582. parser = Lark(grammar, ambiguity='explicit', lexer=LEXER)
  583. tree = parser.parse('fruit flies like bananas')
  584. expected = Tree('_ambig', [
  585. Tree('comparative', [
  586. Tree('noun', ['fruit']),
  587. Tree('verb', ['flies']),
  588. Tree('noun', ['bananas'])
  589. ]),
  590. Tree('simple', [
  591. Tree('noun', [Tree('adj', ['fruit']), 'flies']),
  592. Tree('verb', ['like']),
  593. Tree('noun', ['bananas'])
  594. ])
  595. ])
  596. # self.assertEqual(tree, expected)
  597. self.assertEqual(tree.data, expected.data)
  598. self.assertEqual(set(tree.children), set(expected.children))
  599. @unittest.skipIf(LEXER!='dynamic_complete', "Only relevant for the dynamic_complete parser")
  600. def test_explicit_ambiguity2(self):
  601. grammar = r"""
  602. start: NAME+
  603. NAME: /\w+/
  604. %ignore " "
  605. """
  606. text = """cat"""
  607. parser = _Lark(grammar, start='start', ambiguity='explicit')
  608. tree = parser.parse(text)
  609. self.assertEqual(tree.data, '_ambig')
  610. combinations = {tuple(str(s) for s in t.children) for t in tree.children}
  611. self.assertEqual(combinations, {
  612. ('cat',),
  613. ('ca', 't'),
  614. ('c', 'at'),
  615. ('c', 'a' ,'t')
  616. })
  617. def test_term_ambig_resolve(self):
  618. grammar = r"""
  619. !start: NAME+
  620. NAME: /\w+/
  621. %ignore " "
  622. """
  623. text = """foo bar"""
  624. parser = Lark(grammar)
  625. tree = parser.parse(text)
  626. self.assertEqual(tree.children, ['foo', 'bar'])
  627. def test_cycle(self):
  628. grammar = """
  629. start: start?
  630. """
  631. l = Lark(grammar, ambiguity='resolve', lexer=LEXER)
  632. tree = l.parse('')
  633. self.assertEqual(tree, Tree('start', []))
  634. l = Lark(grammar, ambiguity='explicit', lexer=LEXER)
  635. tree = l.parse('')
  636. self.assertEqual(tree, Tree('start', []))
  637. def test_cycles(self):
  638. grammar = """
  639. a: b
  640. b: c*
  641. c: a
  642. """
  643. l = Lark(grammar, start='a', ambiguity='resolve', lexer=LEXER)
  644. tree = l.parse('')
  645. self.assertEqual(tree, Tree('a', [Tree('b', [])]))
  646. l = Lark(grammar, start='a', ambiguity='explicit', lexer=LEXER)
  647. tree = l.parse('')
  648. self.assertEqual(tree, Tree('a', [Tree('b', [])]))
  649. def test_many_cycles(self):
  650. grammar = """
  651. start: a? | start start
  652. !a: "a"
  653. """
  654. l = Lark(grammar, ambiguity='resolve', lexer=LEXER)
  655. tree = l.parse('a')
  656. self.assertEqual(tree, Tree('start', [Tree('a', ['a'])]))
  657. l = Lark(grammar, ambiguity='explicit', lexer=LEXER)
  658. tree = l.parse('a')
  659. self.assertEqual(tree, Tree('start', [Tree('a', ['a'])]))
  660. def test_cycles_with_child_filter(self):
  661. grammar = """
  662. a: _x
  663. _x: _x? b
  664. b:
  665. """
  666. grammar2 = """
  667. a: x
  668. x: x? b
  669. b:
  670. """
  671. l = Lark(grammar, start='a', ambiguity='resolve', lexer=LEXER)
  672. tree = l.parse('')
  673. self.assertEqual(tree, Tree('a', [Tree('b', [])]))
  674. l = Lark(grammar, start='a', ambiguity='explicit', lexer=LEXER)
  675. tree = l.parse('');
  676. self.assertEqual(tree, Tree('a', [Tree('b', [])]))
  677. l = Lark(grammar2, start='a', ambiguity='resolve', lexer=LEXER)
  678. tree = l.parse('');
  679. self.assertEqual(tree, Tree('a', [Tree('x', [Tree('b', [])])]))
  680. l = Lark(grammar2, start='a', ambiguity='explicit', lexer=LEXER)
  681. tree = l.parse('');
  682. self.assertEqual(tree, Tree('a', [Tree('x', [Tree('b', [])])]))
  683. # @unittest.skipIf(LEXER=='dynamic', "Not implemented in Dynamic Earley yet") # TODO
  684. # def test_not_all_derivations(self):
  685. # grammar = """
  686. # start: cd+ "e"
  687. # !cd: "c"
  688. # | "d"
  689. # | "cd"
  690. # """
  691. # l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER, earley__all_derivations=False)
  692. # x = l.parse('cde')
  693. # assert x.data != '_ambig', x
  694. # assert len(x.children) == 1
  695. _NAME = "TestFullEarley" + LEXER.capitalize()
  696. _TestFullEarley.__name__ = _NAME
  697. globals()[_NAME] = _TestFullEarley
  698. class CustomLexer(Lexer):
  699. """
  700. Purpose of this custom lexer is to test the integration,
  701. so it uses the traditionalparser as implementation without custom lexing behaviour.
  702. """
  703. def __init__(self, lexer_conf):
  704. self.lexer = TraditionalLexer(copy(lexer_conf))
  705. def lex(self, *args, **kwargs):
  706. return self.lexer.lex(*args, **kwargs)
  707. def _tree_structure_check(a, b):
  708. """
  709. Checks that both Tree objects have the same structure, without checking their values.
  710. """
  711. assert a.data == b.data and len(a.children) == len(b.children)
  712. for ca,cb in zip(a.children, b.children):
  713. assert type(ca) == type(cb)
  714. if isinstance(ca, Tree):
  715. _tree_structure_check(ca, cb)
  716. elif isinstance(ca, Token):
  717. assert ca.type == cb.type
  718. else:
  719. assert ca == cb
  720. class DualBytesLark:
  721. """
  722. A helper class that wraps both a normal parser, and a parser for bytes.
  723. It automatically transforms `.parse` calls for both lexer, returning the value from the text lexer
  724. It always checks that both produce the same output/error
  725. NOTE: Not currently used, but left here for future debugging.
  726. """
  727. def __init__(self, g, *args, **kwargs):
  728. self.text_lexer = Lark(g, *args, use_bytes=False, **kwargs)
  729. g = self.text_lexer.grammar_source.lower()
  730. if '\\u' in g or not isascii(g):
  731. # Bytes re can't deal with uniode escapes
  732. self.bytes_lark = None
  733. else:
  734. # Everything here should work, so use `use_bytes='force'`
  735. self.bytes_lark = Lark(self.text_lexer.grammar_source, *args, use_bytes='force', **kwargs)
  736. def parse(self, text, start=None):
  737. # TODO: Easy workaround, more complex checks would be beneficial
  738. if not isascii(text) or self.bytes_lark is None:
  739. return self.text_lexer.parse(text, start)
  740. try:
  741. rv = self.text_lexer.parse(text, start)
  742. except Exception as e:
  743. try:
  744. self.bytes_lark.parse(text.encode(), start)
  745. except Exception as be:
  746. assert type(e) == type(be), "Parser with and without `use_bytes` raise different exceptions"
  747. raise e
  748. assert False, "Parser without `use_bytes` raises exception, with doesn't"
  749. try:
  750. bv = self.bytes_lark.parse(text.encode(), start)
  751. except Exception as be:
  752. assert False, "Parser without `use_bytes` doesn't raise an exception, with does"
  753. _tree_structure_check(rv, bv)
  754. return rv
  755. @classmethod
  756. def open(cls, grammar_filename, rel_to=None, **options):
  757. if rel_to:
  758. basepath = os.path.dirname(rel_to)
  759. grammar_filename = os.path.join(basepath, grammar_filename)
  760. with open(grammar_filename, encoding='utf8') as f:
  761. return cls(f, **options)
  762. def save(self,f):
  763. self.text_lexer.save(f)
  764. if self.bytes_lark is not None:
  765. self.bytes_lark.save(f)
  766. def load(self,f):
  767. self.text_lexer = self.text_lexer.load(f)
  768. if self.bytes_lark is not None:
  769. self.bytes_lark.load(f)
  770. def _make_parser_test(LEXER, PARSER):
  771. lexer_class_or_name = CustomLexer if LEXER == 'custom' else LEXER
  772. def _Lark(grammar, **kwargs):
  773. return Lark(grammar, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  774. def _Lark_open(gfilename, **kwargs):
  775. return Lark.open(gfilename, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  776. class _TestParser(unittest.TestCase):
  777. def test_basic1(self):
  778. g = _Lark("""start: a+ b a* "b" a*
  779. b: "b"
  780. a: "a"
  781. """)
  782. r = g.parse('aaabaab')
  783. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  784. r = g.parse('aaabaaba')
  785. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  786. self.assertRaises(ParseError, g.parse, 'aaabaa')
  787. def test_basic2(self):
  788. # Multiple parsers and colliding tokens
  789. g = _Lark("""start: B A
  790. B: "12"
  791. A: "1" """)
  792. g2 = _Lark("""start: B A
  793. B: "12"
  794. A: "2" """)
  795. x = g.parse('121')
  796. assert x.data == 'start' and x.children == ['12', '1'], x
  797. x = g2.parse('122')
  798. assert x.data == 'start' and x.children == ['12', '2'], x
  799. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  800. def test_stringio_bytes(self):
  801. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  802. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  803. def test_stringio_unicode(self):
  804. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  805. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  806. def test_unicode(self):
  807. g = _Lark(u"""start: UNIA UNIB UNIA
  808. UNIA: /\xa3/
  809. UNIB: /\u0101/
  810. """)
  811. g.parse(u'\xa3\u0101\u00a3')
  812. def test_unicode2(self):
  813. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  814. UNIA: /\xa3/
  815. UNIB: "a\u0101b\ "
  816. UNIC: /a?\u0101c\n/
  817. """)
  818. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  819. def test_unicode3(self):
  820. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  821. UNIA: /\xa3/
  822. UNIB: "\u0101"
  823. UNIC: /\u0203/ /\n/
  824. """)
  825. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  826. def test_hex_escape(self):
  827. g = _Lark(r"""start: A B C
  828. A: "\x01"
  829. B: /\x02/
  830. C: "\xABCD"
  831. """)
  832. g.parse('\x01\x02\xABCD')
  833. def test_unicode_literal_range_escape(self):
  834. g = _Lark(r"""start: A+
  835. A: "\u0061".."\u0063"
  836. """)
  837. g.parse('abc')
  838. def test_hex_literal_range_escape(self):
  839. g = _Lark(r"""start: A+
  840. A: "\x01".."\x03"
  841. """)
  842. g.parse('\x01\x02\x03')
  843. @unittest.skipIf(sys.version_info[0]==2 or sys.version_info[:2]==(3, 4),
  844. "bytes parser isn't perfect in Python2, exceptions don't work correctly")
  845. def test_bytes_utf8(self):
  846. g = r"""
  847. start: BOM? char+
  848. BOM: "\xef\xbb\xbf"
  849. char: CHAR1 | CHAR2 | CHAR3 | CHAR4
  850. CONTINUATION_BYTE: "\x80" .. "\xbf"
  851. CHAR1: "\x00" .. "\x7f"
  852. CHAR2: "\xc0" .. "\xdf" CONTINUATION_BYTE
  853. CHAR3: "\xe0" .. "\xef" CONTINUATION_BYTE CONTINUATION_BYTE
  854. CHAR4: "\xf0" .. "\xf7" CONTINUATION_BYTE CONTINUATION_BYTE CONTINUATION_BYTE
  855. """
  856. g = _Lark(g, use_bytes=True)
  857. s = u"🔣 地? gurīn".encode('utf-8')
  858. self.assertEqual(len(g.parse(s).children), 10)
  859. for enc, j in [("sjis", u"地球の絵はグリーンでグッド? Chikyuu no e wa guriin de guddo"),
  860. ("sjis", u"売春婦"),
  861. ("euc-jp", u"乂鵬鵠")]:
  862. s = j.encode(enc)
  863. self.assertRaises(UnexpectedCharacters, g.parse, s)
  864. @unittest.skipIf(PARSER == 'cyk', "Takes forever")
  865. def test_stack_for_ebnf(self):
  866. """Verify that stack depth isn't an issue for EBNF grammars"""
  867. g = _Lark(r"""start: a+
  868. a : "a" """)
  869. g.parse("a" * (sys.getrecursionlimit()*2 ))
  870. def test_expand1_lists_with_one_item(self):
  871. g = _Lark(r"""start: list
  872. ?list: item+
  873. item : A
  874. A: "a"
  875. """)
  876. r = g.parse("a")
  877. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  878. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  879. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  880. self.assertEqual(len(r.children), 1)
  881. def test_expand1_lists_with_one_item_2(self):
  882. g = _Lark(r"""start: list
  883. ?list: item+ "!"
  884. item : A
  885. A: "a"
  886. """)
  887. r = g.parse("a!")
  888. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  889. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  890. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  891. self.assertEqual(len(r.children), 1)
  892. def test_dont_expand1_lists_with_multiple_items(self):
  893. g = _Lark(r"""start: list
  894. ?list: item+
  895. item : A
  896. A: "a"
  897. """)
  898. r = g.parse("aa")
  899. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  900. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  901. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  902. self.assertEqual(len(r.children), 1)
  903. # Sanity check: verify that 'list' contains the two 'item's we've given it
  904. [list] = r.children
  905. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  906. def test_dont_expand1_lists_with_multiple_items_2(self):
  907. g = _Lark(r"""start: list
  908. ?list: item+ "!"
  909. item : A
  910. A: "a"
  911. """)
  912. r = g.parse("aa!")
  913. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  914. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  915. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  916. self.assertEqual(len(r.children), 1)
  917. # Sanity check: verify that 'list' contains the two 'item's we've given it
  918. [list] = r.children
  919. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  920. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  921. def test_empty_expand1_list(self):
  922. g = _Lark(r"""start: list
  923. ?list: item*
  924. item : A
  925. A: "a"
  926. """)
  927. r = g.parse("")
  928. # 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
  929. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  930. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  931. self.assertEqual(len(r.children), 1)
  932. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  933. [list] = r.children
  934. self.assertSequenceEqual([item.data for item in list.children], ())
  935. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  936. def test_empty_expand1_list_2(self):
  937. g = _Lark(r"""start: list
  938. ?list: item* "!"?
  939. item : A
  940. A: "a"
  941. """)
  942. r = g.parse("")
  943. # 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
  944. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  945. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  946. self.assertEqual(len(r.children), 1)
  947. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  948. [list] = r.children
  949. self.assertSequenceEqual([item.data for item in list.children], ())
  950. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  951. def test_empty_flatten_list(self):
  952. g = _Lark(r"""start: list
  953. list: | item "," list
  954. item : A
  955. A: "a"
  956. """)
  957. r = g.parse("")
  958. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  959. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  960. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  961. [list] = r.children
  962. self.assertSequenceEqual([item.data for item in list.children], ())
  963. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  964. def test_single_item_flatten_list(self):
  965. g = _Lark(r"""start: list
  966. list: | item "," list
  967. item : A
  968. A: "a"
  969. """)
  970. r = g.parse("a,")
  971. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  972. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  973. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  974. [list] = r.children
  975. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  976. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  977. def test_multiple_item_flatten_list(self):
  978. g = _Lark(r"""start: list
  979. #list: | item "," list
  980. item : A
  981. A: "a"
  982. """)
  983. r = g.parse("a,a,")
  984. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  985. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  986. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  987. [list] = r.children
  988. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  989. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  990. def test_recurse_flatten(self):
  991. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  992. g = _Lark(r"""start: a | start a
  993. a : A
  994. A : "a" """)
  995. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  996. # STree data structures, which uses recursion).
  997. g.parse("a" * (sys.getrecursionlimit() // 4))
  998. def test_token_collision(self):
  999. g = _Lark(r"""start: "Hello" NAME
  1000. NAME: /\w/+
  1001. %ignore " "
  1002. """)
  1003. x = g.parse('Hello World')
  1004. self.assertSequenceEqual(x.children, ['World'])
  1005. x = g.parse('Hello HelloWorld')
  1006. self.assertSequenceEqual(x.children, ['HelloWorld'])
  1007. def test_token_collision_WS(self):
  1008. g = _Lark(r"""start: "Hello" NAME
  1009. NAME: /\w/+
  1010. %import common.WS
  1011. %ignore WS
  1012. """)
  1013. x = g.parse('Hello World')
  1014. self.assertSequenceEqual(x.children, ['World'])
  1015. x = g.parse('Hello HelloWorld')
  1016. self.assertSequenceEqual(x.children, ['HelloWorld'])
  1017. def test_token_collision2(self):
  1018. g = _Lark("""
  1019. !start: "starts"
  1020. %import common.LCASE_LETTER
  1021. """)
  1022. x = g.parse("starts")
  1023. self.assertSequenceEqual(x.children, ['starts'])
  1024. def test_templates(self):
  1025. g = _Lark(r"""
  1026. start: "[" sep{NUMBER, ","} "]"
  1027. sep{item, delim}: item (delim item)*
  1028. NUMBER: /\d+/
  1029. %ignore " "
  1030. """)
  1031. x = g.parse("[1, 2, 3, 4]")
  1032. self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])])
  1033. x = g.parse("[1]")
  1034. self.assertSequenceEqual(x.children, [Tree('sep', ['1'])])
  1035. def test_templates_recursion(self):
  1036. g = _Lark(r"""
  1037. start: "[" _sep{NUMBER, ","} "]"
  1038. _sep{item, delim}: item | _sep{item, delim} delim item
  1039. NUMBER: /\d+/
  1040. %ignore " "
  1041. """)
  1042. x = g.parse("[1, 2, 3, 4]")
  1043. self.assertSequenceEqual(x.children, ['1', '2', '3', '4'])
  1044. x = g.parse("[1]")
  1045. self.assertSequenceEqual(x.children, ['1'])
  1046. def test_templates_import(self):
  1047. g = _Lark_open("test_templates_import.lark", rel_to=__file__)
  1048. x = g.parse("[1, 2, 3, 4]")
  1049. self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])])
  1050. x = g.parse("[1]")
  1051. self.assertSequenceEqual(x.children, [Tree('sep', ['1'])])
  1052. def test_templates_alias(self):
  1053. g = _Lark(r"""
  1054. start: expr{"C"}
  1055. expr{t}: "A" t
  1056. | "B" t -> b
  1057. """)
  1058. x = g.parse("AC")
  1059. self.assertSequenceEqual(x.children, [Tree('expr', [])])
  1060. x = g.parse("BC")
  1061. self.assertSequenceEqual(x.children, [Tree('b', [])])
  1062. def test_templates_modifiers(self):
  1063. g = _Lark(r"""
  1064. start: expr{"B"}
  1065. !expr{t}: "A" t
  1066. """)
  1067. x = g.parse("AB")
  1068. self.assertSequenceEqual(x.children, [Tree('expr', ["A", "B"])])
  1069. g = _Lark(r"""
  1070. start: _expr{"B"}
  1071. !_expr{t}: "A" t
  1072. """)
  1073. x = g.parse("AB")
  1074. self.assertSequenceEqual(x.children, ["A", "B"])
  1075. g = _Lark(r"""
  1076. start: expr{b}
  1077. b: "B"
  1078. ?expr{t}: "A" t
  1079. """)
  1080. x = g.parse("AB")
  1081. self.assertSequenceEqual(x.children, [Tree('b',[])])
  1082. def test_templates_templates(self):
  1083. g = _Lark('''start: a{b}
  1084. a{t}: t{"a"}
  1085. b{x}: x''')
  1086. x = g.parse('a')
  1087. self.assertSequenceEqual(x.children, [Tree('a', [Tree('b',[])])])
  1088. def test_g_regex_flags(self):
  1089. g = _Lark("""
  1090. start: "a" /b+/ C
  1091. C: "C" | D
  1092. D: "D" E
  1093. E: "e"
  1094. """, g_regex_flags=re.I)
  1095. x1 = g.parse("ABBc")
  1096. x2 = g.parse("abdE")
  1097. # def test_string_priority(self):
  1098. # g = _Lark("""start: (A | /a?bb/)+
  1099. # A: "a" """)
  1100. # x = g.parse('abb')
  1101. # self.assertEqual(len(x.children), 2)
  1102. # # This parse raises an exception because the lexer will always try to consume
  1103. # # "a" first and will never match the regular expression
  1104. # # This behavior is subject to change!!
  1105. # # Thie won't happen with ambiguity handling.
  1106. # g = _Lark("""start: (A | /a?ab/)+
  1107. # A: "a" """)
  1108. # self.assertRaises(LexError, g.parse, 'aab')
  1109. def test_undefined_rule(self):
  1110. self.assertRaises(GrammarError, _Lark, """start: a""")
  1111. def test_undefined_token(self):
  1112. self.assertRaises(GrammarError, _Lark, """start: A""")
  1113. def test_rule_collision(self):
  1114. g = _Lark("""start: "a"+ "b"
  1115. | "a"+ """)
  1116. x = g.parse('aaaa')
  1117. x = g.parse('aaaab')
  1118. def test_rule_collision2(self):
  1119. g = _Lark("""start: "a"* "b"
  1120. | "a"+ """)
  1121. x = g.parse('aaaa')
  1122. x = g.parse('aaaab')
  1123. x = g.parse('b')
  1124. def test_token_not_anon(self):
  1125. """Tests that "a" is matched as an anonymous token, and not A.
  1126. """
  1127. g = _Lark("""start: "a"
  1128. A: "a" """)
  1129. x = g.parse('a')
  1130. self.assertEqual(len(x.children), 0, '"a" should be considered anonymous')
  1131. g = _Lark("""start: "a" A
  1132. A: "a" """)
  1133. x = g.parse('aa')
  1134. self.assertEqual(len(x.children), 1, 'only "a" should be considered anonymous')
  1135. self.assertEqual(x.children[0].type, "A")
  1136. g = _Lark("""start: /a/
  1137. A: /a/ """)
  1138. x = g.parse('a')
  1139. self.assertEqual(len(x.children), 1)
  1140. self.assertEqual(x.children[0].type, "A", "A isn't associated with /a/")
  1141. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1142. def test_maybe(self):
  1143. g = _Lark("""start: ["a"] """)
  1144. x = g.parse('a')
  1145. x = g.parse('')
  1146. def test_start(self):
  1147. g = _Lark("""a: "a" a? """, start='a')
  1148. x = g.parse('a')
  1149. x = g.parse('aa')
  1150. x = g.parse('aaa')
  1151. def test_alias(self):
  1152. g = _Lark("""start: "a" -> b """)
  1153. x = g.parse('a')
  1154. self.assertEqual(x.data, "b")
  1155. def test_token_ebnf(self):
  1156. g = _Lark("""start: A
  1157. A: "a"* ("b"? "c".."e")+
  1158. """)
  1159. x = g.parse('abcde')
  1160. x = g.parse('dd')
  1161. def test_backslash(self):
  1162. g = _Lark(r"""start: "\\" "a"
  1163. """)
  1164. x = g.parse(r'\a')
  1165. g = _Lark(r"""start: /\\/ /a/
  1166. """)
  1167. x = g.parse(r'\a')
  1168. def test_backslash2(self):
  1169. g = _Lark(r"""start: "\"" "-"
  1170. """)
  1171. x = g.parse('"-')
  1172. g = _Lark(r"""start: /\// /-/
  1173. """)
  1174. x = g.parse('/-')
  1175. def test_special_chars(self):
  1176. g = _Lark(r"""start: "\n"
  1177. """)
  1178. x = g.parse('\n')
  1179. g = _Lark(r"""start: /\n/
  1180. """)
  1181. x = g.parse('\n')
  1182. # def test_token_recurse(self):
  1183. # g = _Lark("""start: A
  1184. # A: B
  1185. # B: A
  1186. # """)
  1187. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1188. def test_empty(self):
  1189. # Fails an Earley implementation without special handling for empty rules,
  1190. # or re-processing of already completed rules.
  1191. g = _Lark(r"""start: _empty a "B"
  1192. a: _empty "A"
  1193. _empty:
  1194. """)
  1195. x = g.parse('AB')
  1196. def test_regex_quote(self):
  1197. g = r"""
  1198. start: SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING
  1199. SINGLE_QUOTED_STRING : /'[^']*'/
  1200. DOUBLE_QUOTED_STRING : /"[^"]*"/
  1201. """
  1202. g = _Lark(g)
  1203. self.assertEqual( g.parse('"hello"').children, ['"hello"'])
  1204. self.assertEqual( g.parse("'hello'").children, ["'hello'"])
  1205. @unittest.skipIf(not Py36, "Required re syntax only exists in python3.6+")
  1206. def test_join_regex_flags(self):
  1207. g = r"""
  1208. start: A
  1209. A: B C
  1210. B: /./s
  1211. C: /./
  1212. """
  1213. g = _Lark(g)
  1214. self.assertEqual(g.parse(" ").children,[" "])
  1215. self.assertEqual(g.parse("\n ").children,["\n "])
  1216. self.assertRaises(UnexpectedCharacters, g.parse, "\n\n")
  1217. g = r"""
  1218. start: A
  1219. A: B | C
  1220. B: "b"i
  1221. C: "c"
  1222. """
  1223. g = _Lark(g)
  1224. self.assertEqual(g.parse("b").children,["b"])
  1225. self.assertEqual(g.parse("B").children,["B"])
  1226. self.assertEqual(g.parse("c").children,["c"])
  1227. self.assertRaises(UnexpectedCharacters, g.parse, "C")
  1228. def test_lexer_token_limit(self):
  1229. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  1230. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  1231. g = _Lark("""start: %s
  1232. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  1233. def test_float_without_lexer(self):
  1234. expected_error = UnexpectedCharacters if LEXER.startswith('dynamic') else UnexpectedToken
  1235. if PARSER == 'cyk':
  1236. expected_error = ParseError
  1237. g = _Lark("""start: ["+"|"-"] float
  1238. float: digit* "." digit+ exp?
  1239. | digit+ exp
  1240. exp: ("e"|"E") ["+"|"-"] digit+
  1241. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  1242. """)
  1243. g.parse("1.2")
  1244. g.parse("-.2e9")
  1245. g.parse("+2e-9")
  1246. self.assertRaises( expected_error, g.parse, "+2e-9e")
  1247. def test_keep_all_tokens(self):
  1248. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  1249. tree = l.parse('aaa')
  1250. self.assertEqual(tree.children, ['a', 'a', 'a'])
  1251. def test_token_flags(self):
  1252. l = _Lark("""!start: "a"i+
  1253. """
  1254. )
  1255. tree = l.parse('aA')
  1256. self.assertEqual(tree.children, ['a', 'A'])
  1257. l = _Lark("""!start: /a/i+
  1258. """
  1259. )
  1260. tree = l.parse('aA')
  1261. self.assertEqual(tree.children, ['a', 'A'])
  1262. # g = """!start: "a"i "a"
  1263. # """
  1264. # self.assertRaises(GrammarError, _Lark, g)
  1265. # g = """!start: /a/i /a/
  1266. # """
  1267. # self.assertRaises(GrammarError, _Lark, g)
  1268. g = """start: NAME "," "a"
  1269. NAME: /[a-z_]/i /[a-z0-9_]/i*
  1270. """
  1271. l = _Lark(g)
  1272. tree = l.parse('ab,a')
  1273. self.assertEqual(tree.children, ['ab'])
  1274. tree = l.parse('AB,a')
  1275. self.assertEqual(tree.children, ['AB'])
  1276. def test_token_flags3(self):
  1277. l = _Lark("""!start: ABC+
  1278. ABC: "abc"i
  1279. """
  1280. )
  1281. tree = l.parse('aBcAbC')
  1282. self.assertEqual(tree.children, ['aBc', 'AbC'])
  1283. def test_token_flags2(self):
  1284. g = """!start: ("a"i | /a/ /b/?)+
  1285. """
  1286. l = _Lark(g)
  1287. tree = l.parse('aA')
  1288. self.assertEqual(tree.children, ['a', 'A'])
  1289. def test_token_flags_verbose(self):
  1290. g = _Lark(r"""start: NL | ABC
  1291. ABC: / [a-z] /x
  1292. NL: /\n/
  1293. """)
  1294. x = g.parse('a')
  1295. self.assertEqual(x.children, ['a'])
  1296. def test_token_flags_verbose_multiline(self):
  1297. g = _Lark(r"""start: ABC
  1298. ABC: / a b c
  1299. d
  1300. e f
  1301. /x
  1302. """)
  1303. x = g.parse('abcdef')
  1304. self.assertEqual(x.children, ['abcdef'])
  1305. def test_token_multiline_only_works_with_x_flag(self):
  1306. g = r"""start: ABC
  1307. ABC: / a b c
  1308. d
  1309. e f
  1310. /i
  1311. """
  1312. self.assertRaises( GrammarError, _Lark, g)
  1313. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1314. def test_twice_empty(self):
  1315. g = """!start: ("A"?)?
  1316. """
  1317. l = _Lark(g)
  1318. tree = l.parse('A')
  1319. self.assertEqual(tree.children, ['A'])
  1320. tree = l.parse('')
  1321. self.assertEqual(tree.children, [])
  1322. def test_undefined_ignore(self):
  1323. g = """!start: "A"
  1324. %ignore B
  1325. """
  1326. self.assertRaises( GrammarError, _Lark, g)
  1327. def test_alias_in_terminal(self):
  1328. g = """start: TERM
  1329. TERM: "a" -> alias
  1330. """
  1331. self.assertRaises( GrammarError, _Lark, g)
  1332. def test_line_and_column(self):
  1333. g = r"""!start: "A" bc "D"
  1334. !bc: "B\nC"
  1335. """
  1336. l = _Lark(g)
  1337. a, bc, d = l.parse("AB\nCD").children
  1338. self.assertEqual(a.line, 1)
  1339. self.assertEqual(a.column, 1)
  1340. bc ,= bc.children
  1341. self.assertEqual(bc.line, 1)
  1342. self.assertEqual(bc.column, 2)
  1343. self.assertEqual(d.line, 2)
  1344. self.assertEqual(d.column, 2)
  1345. if LEXER != 'dynamic':
  1346. self.assertEqual(a.end_line, 1)
  1347. self.assertEqual(a.end_column, 2)
  1348. self.assertEqual(bc.end_line, 2)
  1349. self.assertEqual(bc.end_column, 2)
  1350. self.assertEqual(d.end_line, 2)
  1351. self.assertEqual(d.end_column, 3)
  1352. def test_reduce_cycle(self):
  1353. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  1354. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  1355. """
  1356. l = _Lark("""
  1357. term: A
  1358. | term term
  1359. A: "a"
  1360. """, start='term')
  1361. tree = l.parse("aa")
  1362. self.assertEqual(len(tree.children), 2)
  1363. @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority")
  1364. def test_lexer_prioritization(self):
  1365. "Tests effect of priority on result"
  1366. grammar = """
  1367. start: A B | AB
  1368. A.2: "a"
  1369. B: "b"
  1370. AB: "ab"
  1371. """
  1372. l = _Lark(grammar)
  1373. res = l.parse("ab")
  1374. self.assertEqual(res.children, ['a', 'b'])
  1375. self.assertNotEqual(res.children, ['ab'])
  1376. grammar = """
  1377. start: A B | AB
  1378. A: "a"
  1379. B: "b"
  1380. AB.3: "ab"
  1381. """
  1382. l = _Lark(grammar)
  1383. res = l.parse("ab")
  1384. self.assertNotEqual(res.children, ['a', 'b'])
  1385. self.assertEqual(res.children, ['ab'])
  1386. grammar = """
  1387. start: A B | AB
  1388. A: "a"
  1389. B.-20: "b"
  1390. AB.-10: "ab"
  1391. """
  1392. l = _Lark(grammar)
  1393. res = l.parse("ab")
  1394. self.assertEqual(res.children, ['a', 'b'])
  1395. grammar = """
  1396. start: A B | AB
  1397. A.-99999999999999999999999: "a"
  1398. B: "b"
  1399. AB: "ab"
  1400. """
  1401. l = _Lark(grammar)
  1402. res = l.parse("ab")
  1403. self.assertEqual(res.children, ['ab'])
  1404. def test_import(self):
  1405. grammar = """
  1406. start: NUMBER WORD
  1407. %import common.NUMBER
  1408. %import common.WORD
  1409. %import common.WS
  1410. %ignore WS
  1411. """
  1412. l = _Lark(grammar)
  1413. x = l.parse('12 elephants')
  1414. self.assertEqual(x.children, ['12', 'elephants'])
  1415. def test_import_rename(self):
  1416. grammar = """
  1417. start: N W
  1418. %import common.NUMBER -> N
  1419. %import common.WORD -> W
  1420. %import common.WS
  1421. %ignore WS
  1422. """
  1423. l = _Lark(grammar)
  1424. x = l.parse('12 elephants')
  1425. self.assertEqual(x.children, ['12', 'elephants'])
  1426. def test_relative_import(self):
  1427. l = _Lark_open('test_relative_import.lark', rel_to=__file__)
  1428. x = l.parse('12 lions')
  1429. self.assertEqual(x.children, ['12', 'lions'])
  1430. def test_relative_import_unicode(self):
  1431. l = _Lark_open('test_relative_import_unicode.lark', rel_to=__file__)
  1432. x = l.parse(u'Ø')
  1433. self.assertEqual(x.children, [u'Ø'])
  1434. def test_relative_import_rename(self):
  1435. l = _Lark_open('test_relative_import_rename.lark', rel_to=__file__)
  1436. x = l.parse('12 lions')
  1437. self.assertEqual(x.children, ['12', 'lions'])
  1438. def test_relative_rule_import(self):
  1439. l = _Lark_open('test_relative_rule_import.lark', rel_to=__file__)
  1440. x = l.parse('xaabby')
  1441. self.assertEqual(x.children, [
  1442. 'x',
  1443. Tree('expr', ['a', Tree('expr', ['a', 'b']), 'b']),
  1444. 'y'])
  1445. def test_relative_rule_import_drop_ignore(self):
  1446. # %ignore rules are dropped on import
  1447. l = _Lark_open('test_relative_rule_import_drop_ignore.lark',
  1448. rel_to=__file__)
  1449. self.assertRaises((ParseError, UnexpectedInput),
  1450. l.parse, 'xa abby')
  1451. def test_relative_rule_import_subrule(self):
  1452. l = _Lark_open('test_relative_rule_import_subrule.lark',
  1453. rel_to=__file__)
  1454. x = l.parse('xaabby')
  1455. self.assertEqual(x.children, [
  1456. 'x',
  1457. Tree('startab', [
  1458. Tree('grammars__ab__expr', [
  1459. 'a', Tree('grammars__ab__expr', ['a', 'b']), 'b',
  1460. ]),
  1461. ]),
  1462. 'y'])
  1463. def test_relative_rule_import_subrule_no_conflict(self):
  1464. l = _Lark_open(
  1465. 'test_relative_rule_import_subrule_no_conflict.lark',
  1466. rel_to=__file__)
  1467. x = l.parse('xaby')
  1468. self.assertEqual(x.children, [Tree('expr', [
  1469. 'x',
  1470. Tree('startab', [
  1471. Tree('grammars__ab__expr', ['a', 'b']),
  1472. ]),
  1473. 'y'])])
  1474. self.assertRaises((ParseError, UnexpectedInput),
  1475. l.parse, 'xaxabyby')
  1476. def test_relative_rule_import_rename(self):
  1477. l = _Lark_open('test_relative_rule_import_rename.lark',
  1478. rel_to=__file__)
  1479. x = l.parse('xaabby')
  1480. self.assertEqual(x.children, [
  1481. 'x',
  1482. Tree('ab', ['a', Tree('ab', ['a', 'b']), 'b']),
  1483. 'y'])
  1484. def test_multi_import(self):
  1485. grammar = """
  1486. start: NUMBER WORD
  1487. %import common (NUMBER, WORD, WS)
  1488. %ignore WS
  1489. """
  1490. l = _Lark(grammar)
  1491. x = l.parse('12 toucans')
  1492. self.assertEqual(x.children, ['12', 'toucans'])
  1493. def test_relative_multi_import(self):
  1494. l = _Lark_open("test_relative_multi_import.lark", rel_to=__file__)
  1495. x = l.parse('12 capybaras')
  1496. self.assertEqual(x.children, ['12', 'capybaras'])
  1497. def test_relative_import_preserves_leading_underscore(self):
  1498. l = _Lark_open("test_relative_import_preserves_leading_underscore.lark", rel_to=__file__)
  1499. x = l.parse('Ax')
  1500. self.assertEqual(next(x.find_data('c')).children, ['A'])
  1501. def test_relative_import_of_nested_grammar(self):
  1502. l = _Lark_open("grammars/test_relative_import_of_nested_grammar.lark", rel_to=__file__)
  1503. x = l.parse('N')
  1504. self.assertEqual(next(x.find_data('rule_to_import')).children, ['N'])
  1505. def test_relative_import_rules_dependencies_imported_only_once(self):
  1506. l = _Lark_open("test_relative_import_rules_dependencies_imported_only_once.lark", rel_to=__file__)
  1507. x = l.parse('AAA')
  1508. self.assertEqual(next(x.find_data('a')).children, ['A'])
  1509. self.assertEqual(next(x.find_data('b')).children, ['A'])
  1510. self.assertEqual(next(x.find_data('d')).children, ['A'])
  1511. def test_import_errors(self):
  1512. grammar = """
  1513. start: NUMBER WORD
  1514. %import .grammars.bad_test.NUMBER
  1515. """
  1516. self.assertRaises(IOError, _Lark, grammar)
  1517. grammar = """
  1518. start: NUMBER WORD
  1519. %import bad_test.NUMBER
  1520. """
  1521. self.assertRaises(IOError, _Lark, grammar)
  1522. @unittest.skipIf(LEXER=='dynamic', "%declare/postlex doesn't work with dynamic")
  1523. def test_postlex_declare(self): # Note: this test does a lot. maybe split it up?
  1524. class TestPostLexer:
  1525. def process(self, stream):
  1526. for t in stream:
  1527. if t.type == 'A':
  1528. t.type = 'B'
  1529. yield t
  1530. else:
  1531. yield t
  1532. always_accept = ('A',)
  1533. parser = _Lark("""
  1534. start: B
  1535. A: "A"
  1536. %declare B
  1537. """, postlex=TestPostLexer())
  1538. test_file = "A"
  1539. tree = parser.parse(test_file)
  1540. self.assertEqual(tree.children, [Token('B', 'A')])
  1541. def test_import_custom_sources(self):
  1542. custom_loader = FromPackageLoader('tests', ('grammars', ))
  1543. grammar = """
  1544. start: startab
  1545. %import ab.startab
  1546. """
  1547. p = _Lark(grammar, import_paths=[custom_loader])
  1548. self.assertEqual(p.parse('ab'),
  1549. Tree('start', [Tree('startab', [Tree('ab__expr', [Token('ab__A', 'a'), Token('ab__B', 'b')])])]))
  1550. grammar = """
  1551. start: rule_to_import
  1552. %import test_relative_import_of_nested_grammar__grammar_to_import.rule_to_import
  1553. """
  1554. p = _Lark(grammar, import_paths=[custom_loader])
  1555. x = p.parse('N')
  1556. self.assertEqual(next(x.find_data('rule_to_import')).children, ['N'])
  1557. custom_loader2 = FromPackageLoader('tests')
  1558. grammar = """
  1559. %import .test_relative_import (start, WS)
  1560. %ignore WS
  1561. """
  1562. p = _Lark(grammar, import_paths=[custom_loader2])
  1563. x = p.parse('12 capybaras')
  1564. self.assertEqual(x.children, ['12', 'capybaras'])
  1565. @unittest.skipIf(PARSER == 'cyk', "Doesn't work for CYK")
  1566. def test_prioritization(self):
  1567. "Tests effect of priority on result"
  1568. grammar = """
  1569. start: a | b
  1570. a.1: "a"
  1571. b.2: "a"
  1572. """
  1573. l = _Lark(grammar)
  1574. res = l.parse("a")
  1575. self.assertEqual(res.children[0].data, 'b')
  1576. grammar = """
  1577. start: a | b
  1578. a.2: "a"
  1579. b.1: "a"
  1580. """
  1581. l = _Lark(grammar)
  1582. res = l.parse("a")
  1583. self.assertEqual(res.children[0].data, 'a')
  1584. grammar = """
  1585. start: a | b
  1586. a.2: "A"+
  1587. b.1: "A"+ "B"?
  1588. """
  1589. l = _Lark(grammar)
  1590. res = l.parse("AAAA")
  1591. self.assertEqual(res.children[0].data, 'a')
  1592. l = _Lark(grammar)
  1593. res = l.parse("AAAB")
  1594. self.assertEqual(res.children[0].data, 'b')
  1595. l = _Lark(grammar, priority="invert")
  1596. res = l.parse("AAAA")
  1597. self.assertEqual(res.children[0].data, 'b')
  1598. @unittest.skipIf(PARSER != 'earley' or LEXER == 'standard', "Currently only Earley supports priority sum in rules")
  1599. def test_prioritization_sum(self):
  1600. "Tests effect of priority on result"
  1601. grammar = """
  1602. start: ab_ b_ a_ | indirection
  1603. indirection: a_ bb_ a_
  1604. a_: "a"
  1605. b_: "b"
  1606. ab_: "ab"
  1607. bb_.1: "bb"
  1608. """
  1609. l = _Lark(grammar, priority="invert")
  1610. res = l.parse('abba')
  1611. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1612. grammar = """
  1613. start: ab_ b_ a_ | indirection
  1614. indirection: a_ bb_ a_
  1615. a_: "a"
  1616. b_: "b"
  1617. ab_.1: "ab"
  1618. bb_: "bb"
  1619. """
  1620. l = _Lark(grammar, priority="invert")
  1621. res = l.parse('abba')
  1622. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1623. grammar = """
  1624. start: ab_ b_ a_ | indirection
  1625. indirection: a_ bb_ a_
  1626. a_.2: "a"
  1627. b_.1: "b"
  1628. ab_.3: "ab"
  1629. bb_.3: "bb"
  1630. """
  1631. l = _Lark(grammar, priority="invert")
  1632. res = l.parse('abba')
  1633. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1634. grammar = """
  1635. start: ab_ b_ a_ | indirection
  1636. indirection: a_ bb_ a_
  1637. a_.1: "a"
  1638. b_.1: "b"
  1639. ab_.4: "ab"
  1640. bb_.3: "bb"
  1641. """
  1642. l = _Lark(grammar, priority="invert")
  1643. res = l.parse('abba')
  1644. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1645. def test_utf8(self):
  1646. g = u"""start: a
  1647. a: "±a"
  1648. """
  1649. l = _Lark(g)
  1650. self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])]))
  1651. g = u"""start: A
  1652. A: "±a"
  1653. """
  1654. l = _Lark(g)
  1655. self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a']))
  1656. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1657. def test_ignore(self):
  1658. grammar = r"""
  1659. COMMENT: /(!|(\/\/))[^\n]*/
  1660. %ignore COMMENT
  1661. %import common.WS -> _WS
  1662. %import common.INT
  1663. start: "INT"i _WS+ INT _WS*
  1664. """
  1665. parser = _Lark(grammar)
  1666. tree = parser.parse("int 1 ! This is a comment\n")
  1667. self.assertEqual(tree.children, ['1'])
  1668. tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky!
  1669. self.assertEqual(tree.children, ['1'])
  1670. parser = _Lark(r"""
  1671. start : "a"*
  1672. %ignore "b"
  1673. """)
  1674. tree = parser.parse("bb")
  1675. self.assertEqual(tree.children, [])
  1676. def test_regex_escaping(self):
  1677. g = _Lark("start: /[ab]/")
  1678. g.parse('a')
  1679. g.parse('b')
  1680. self.assertRaises( UnexpectedInput, g.parse, 'c')
  1681. _Lark(r'start: /\w/').parse('a')
  1682. g = _Lark(r'start: /\\w/')
  1683. self.assertRaises( UnexpectedInput, g.parse, 'a')
  1684. g.parse(r'\w')
  1685. _Lark(r'start: /\[/').parse('[')
  1686. _Lark(r'start: /\//').parse('/')
  1687. _Lark(r'start: /\\/').parse('\\')
  1688. _Lark(r'start: /\[ab]/').parse('[ab]')
  1689. _Lark(r'start: /\\[ab]/').parse('\\a')
  1690. _Lark(r'start: /\t/').parse('\t')
  1691. _Lark(r'start: /\\t/').parse('\\t')
  1692. _Lark(r'start: /\\\t/').parse('\\\t')
  1693. _Lark(r'start: "\t"').parse('\t')
  1694. _Lark(r'start: "\\t"').parse('\\t')
  1695. _Lark(r'start: "\\\t"').parse('\\\t')
  1696. def test_ranged_repeat_rules(self):
  1697. g = u"""!start: "A"~3
  1698. """
  1699. l = _Lark(g)
  1700. self.assertEqual(l.parse(u'AAA'), Tree('start', ["A", "A", "A"]))
  1701. self.assertRaises(ParseError, l.parse, u'AA')
  1702. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1703. g = u"""!start: "A"~0..2
  1704. """
  1705. if PARSER != 'cyk': # XXX CYK currently doesn't support empty grammars
  1706. l = _Lark(g)
  1707. self.assertEqual(l.parse(u''), Tree('start', []))
  1708. self.assertEqual(l.parse(u'A'), Tree('start', ['A']))
  1709. self.assertEqual(l.parse(u'AA'), Tree('start', ['A', 'A']))
  1710. self.assertRaises((UnexpectedToken, UnexpectedInput), l.parse, u'AAA')
  1711. g = u"""!start: "A"~3..2
  1712. """
  1713. self.assertRaises(GrammarError, _Lark, g)
  1714. g = u"""!start: "A"~2..3 "B"~2
  1715. """
  1716. l = _Lark(g)
  1717. self.assertEqual(l.parse(u'AABB'), Tree('start', ['A', 'A', 'B', 'B']))
  1718. self.assertEqual(l.parse(u'AAABB'), Tree('start', ['A', 'A', 'A', 'B', 'B']))
  1719. self.assertRaises(ParseError, l.parse, u'AAAB')
  1720. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1721. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1722. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1723. def test_ranged_repeat_terms(self):
  1724. g = u"""!start: AAA
  1725. AAA: "A"~3
  1726. """
  1727. l = _Lark(g)
  1728. self.assertEqual(l.parse(u'AAA'), Tree('start', ["AAA"]))
  1729. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AA')
  1730. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1731. g = u"""!start: AABB CC
  1732. AABB: "A"~0..2 "B"~2
  1733. CC: "C"~1..2
  1734. """
  1735. l = _Lark(g)
  1736. self.assertEqual(l.parse(u'AABBCC'), Tree('start', ['AABB', 'CC']))
  1737. self.assertEqual(l.parse(u'BBC'), Tree('start', ['BB', 'C']))
  1738. self.assertEqual(l.parse(u'ABBCC'), Tree('start', ['ABB', 'CC']))
  1739. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAB')
  1740. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1741. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1742. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1743. @unittest.skipIf(PARSER=='earley', "Priority not handled correctly right now") # TODO XXX
  1744. def test_priority_vs_embedded(self):
  1745. g = """
  1746. A.2: "a"
  1747. WORD: ("a".."z")+
  1748. start: (A | WORD)+
  1749. """
  1750. l = _Lark(g)
  1751. t = l.parse('abc')
  1752. self.assertEqual(t.children, ['a', 'bc'])
  1753. self.assertEqual(t.children[0].type, 'A')
  1754. def test_line_counting(self):
  1755. p = _Lark("start: /[^x]+/")
  1756. text = 'hello\nworld'
  1757. t = p.parse(text)
  1758. tok = t.children[0]
  1759. self.assertEqual(tok, text)
  1760. self.assertEqual(tok.line, 1)
  1761. self.assertEqual(tok.column, 1)
  1762. if _LEXER != 'dynamic':
  1763. self.assertEqual(tok.end_line, 2)
  1764. self.assertEqual(tok.end_column, 6)
  1765. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1766. def test_empty_end(self):
  1767. p = _Lark("""
  1768. start: b c d
  1769. b: "B"
  1770. c: | "C"
  1771. d: | "D"
  1772. """)
  1773. res = p.parse('B')
  1774. self.assertEqual(len(res.children), 3)
  1775. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1776. def test_maybe_placeholders(self):
  1777. # Anonymous tokens shouldn't count
  1778. p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1779. self.assertEqual(p.parse("").children, [])
  1780. # Unless keep_all_tokens=True
  1781. p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True, keep_all_tokens=True)
  1782. self.assertEqual(p.parse("").children, [None, None, None])
  1783. # All invisible constructs shouldn't count
  1784. p = _Lark("""start: [A] ["b"] [_c] ["e" "f" _c]
  1785. A: "a"
  1786. _c: "c" """, maybe_placeholders=True)
  1787. self.assertEqual(p.parse("").children, [None])
  1788. self.assertEqual(p.parse("c").children, [None])
  1789. self.assertEqual(p.parse("aefc").children, ['a'])
  1790. # ? shouldn't apply
  1791. p = _Lark("""!start: ["a"] "b"? ["c"] """, maybe_placeholders=True)
  1792. self.assertEqual(p.parse("").children, [None, None])
  1793. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1794. p = _Lark("""!start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1795. self.assertEqual(p.parse("").children, [None, None, None])
  1796. self.assertEqual(p.parse("a").children, ['a', None, None])
  1797. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1798. self.assertEqual(p.parse("c").children, [None, None, 'c'])
  1799. self.assertEqual(p.parse("ab").children, ['a', 'b', None])
  1800. self.assertEqual(p.parse("ac").children, ['a', None, 'c'])
  1801. self.assertEqual(p.parse("bc").children, [None, 'b', 'c'])
  1802. self.assertEqual(p.parse("abc").children, ['a', 'b', 'c'])
  1803. p = _Lark("""!start: (["a"] "b" ["c"])+ """, maybe_placeholders=True)
  1804. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1805. self.assertEqual(p.parse("bb").children, [None, 'b', None, None, 'b', None])
  1806. self.assertEqual(p.parse("abbc").children, ['a', 'b', None, None, 'b', 'c'])
  1807. self.assertEqual(p.parse("babbcabcb").children,
  1808. [None, 'b', None,
  1809. 'a', 'b', None,
  1810. None, 'b', 'c',
  1811. 'a', 'b', 'c',
  1812. None, 'b', None])
  1813. p = _Lark("""!start: ["a"] ["c"] "b"+ ["a"] ["d"] """, maybe_placeholders=True)
  1814. self.assertEqual(p.parse("bb").children, [None, None, 'b', 'b', None, None])
  1815. self.assertEqual(p.parse("bd").children, [None, None, 'b', None, 'd'])
  1816. self.assertEqual(p.parse("abba").children, ['a', None, 'b', 'b', 'a', None])
  1817. self.assertEqual(p.parse("cbbbb").children, [None, 'c', 'b', 'b', 'b', 'b', None, None])
  1818. def test_escaped_string(self):
  1819. "Tests common.ESCAPED_STRING"
  1820. grammar = r"""
  1821. start: ESCAPED_STRING+
  1822. %import common (WS_INLINE, ESCAPED_STRING)
  1823. %ignore WS_INLINE
  1824. """
  1825. parser = _Lark(grammar)
  1826. parser.parse(r'"\\" "b" "c"')
  1827. parser.parse(r'"That" "And a \"b"')
  1828. def test_meddling_unused(self):
  1829. "Unless 'unused' is removed, LALR analysis will fail on reduce-reduce collision"
  1830. grammar = """
  1831. start: EKS* x
  1832. x: EKS
  1833. unused: x*
  1834. EKS: "x"
  1835. """
  1836. parser = _Lark(grammar)
  1837. @unittest.skipIf(PARSER!='lalr' or LEXER=='custom', "Serialize currently only works for LALR parsers without custom lexers (though it should be easy to extend)")
  1838. def test_serialize(self):
  1839. grammar = """
  1840. start: _ANY b "C"
  1841. _ANY: /./
  1842. b: "B"
  1843. """
  1844. parser = _Lark(grammar)
  1845. s = BytesIO()
  1846. parser.save(s)
  1847. s.seek(0)
  1848. parser2 = Lark.load(s)
  1849. self.assertEqual(parser2.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1850. def test_multi_start(self):
  1851. parser = _Lark('''
  1852. a: "x" "a"?
  1853. b: "x" "b"?
  1854. ''', start=['a', 'b'])
  1855. self.assertEqual(parser.parse('xa', 'a'), Tree('a', []))
  1856. self.assertEqual(parser.parse('xb', 'b'), Tree('b', []))
  1857. def test_lexer_detect_newline_tokens(self):
  1858. # Detect newlines in regular tokens
  1859. g = _Lark(r"""start: "go" tail*
  1860. !tail : SA "@" | SB "@" | SC "@" | SD "@"
  1861. SA : "a" /\n/
  1862. SB : /b./s
  1863. SC : "c" /[^a-z]/
  1864. SD : "d" /\s/
  1865. """)
  1866. a,b,c,d = [x.children[1] for x in g.parse('goa\n@b\n@c\n@d\n@').children]
  1867. self.assertEqual(a.line, 2)
  1868. self.assertEqual(b.line, 3)
  1869. self.assertEqual(c.line, 4)
  1870. self.assertEqual(d.line, 5)
  1871. # Detect newlines in ignored tokens
  1872. for re in ['/\\n/', '/[^a-z]/', '/\\s/']:
  1873. g = _Lark('''!start: "a" "a"
  1874. %ignore {}'''.format(re))
  1875. a, b = g.parse('a\na').children
  1876. self.assertEqual(a.line, 1)
  1877. self.assertEqual(b.line, 2)
  1878. @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.')
  1879. def test_unicode_class(self):
  1880. "Tests that character classes from the `regex` module work correctly."
  1881. g = _Lark(r"""?start: NAME
  1882. NAME: ID_START ID_CONTINUE*
  1883. ID_START: /[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_]+/
  1884. ID_CONTINUE: ID_START | /[\p{Mn}\p{Mc}\p{Nd}\p{Pc}]+/""", regex=True)
  1885. self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்')
  1886. @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.')
  1887. def test_unicode_word(self):
  1888. "Tests that a persistent bug in the `re` module works when `regex` is enabled."
  1889. g = _Lark(r"""?start: NAME
  1890. NAME: /[\w]+/
  1891. """, regex=True)
  1892. self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்')
  1893. @unittest.skipIf(PARSER!='lalr', "Puppet error handling only works with LALR for now")
  1894. def test_error_with_puppet(self):
  1895. def ignore_errors(e):
  1896. if isinstance(e, UnexpectedCharacters):
  1897. # Skip bad character
  1898. return True
  1899. # Must be UnexpectedToken
  1900. if e.token.type == 'COMMA':
  1901. # Skip comma
  1902. return True
  1903. elif e.token.type == 'SIGNED_NUMBER':
  1904. # Try to feed a comma and retry the number
  1905. e.puppet.feed_token(Token('COMMA', ','))
  1906. e.puppet.feed_token(e.token)
  1907. return True
  1908. # Unhandled error. Will stop parse and raise exception
  1909. return False
  1910. g = _Lark(r'''
  1911. start: "[" num ("," num)* "]"
  1912. ?num: SIGNED_NUMBER
  1913. %import common.SIGNED_NUMBER
  1914. %ignore " "
  1915. ''')
  1916. s = "[0 1, 2,, 3,,, 4, 5 6 ]"
  1917. tree = g.parse(s, on_error=ignore_errors)
  1918. res = [int(x) for x in tree.children]
  1919. assert res == list(range(7))
  1920. s = "[0 1, 2,@, 3,,, 4, 5 6 ]$"
  1921. tree = g.parse(s, on_error=ignore_errors)
  1922. _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize()
  1923. _TestParser.__name__ = _NAME
  1924. _TestParser.__qualname__ = "tests.test_parser." + _NAME
  1925. globals()[_NAME] = _TestParser
  1926. # Note: You still have to import them in __main__ for the tests to run
  1927. _TO_TEST = [
  1928. ('standard', 'earley'),
  1929. ('standard', 'cyk'),
  1930. ('dynamic', 'earley'),
  1931. ('dynamic_complete', 'earley'),
  1932. ('standard', 'lalr'),
  1933. ('contextual', 'lalr'),
  1934. ('custom', 'lalr'),
  1935. # (None, 'earley'),
  1936. ]
  1937. for _LEXER, _PARSER in _TO_TEST:
  1938. _make_parser_test(_LEXER, _PARSER)
  1939. for _LEXER in ('dynamic', 'dynamic_complete'):
  1940. _make_full_earley_test(_LEXER)
  1941. if __name__ == '__main__':
  1942. unittest.main()