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.

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