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.

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