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.

2441 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. try:
  12. from cStringIO import StringIO as cStringIO
  13. except ImportError:
  14. # Available only in Python 2.x, 3.x only has io.StringIO from below
  15. cStringIO = None
  16. from io import (
  17. StringIO as uStringIO,
  18. BytesIO,
  19. open,
  20. )
  21. try:
  22. import regex
  23. except ImportError:
  24. regex = None
  25. import lark
  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_cycle2(self):
  651. grammar = """
  652. start: _operation
  653. _operation: value
  654. value: "b"
  655. | "a" value
  656. | _operation
  657. """
  658. l = Lark(grammar, ambiguity="explicit", lexer=LEXER)
  659. tree = l.parse("ab")
  660. self.assertEqual(tree, Tree('start', [Tree('value', [Tree('value', [])])]))
  661. def test_cycles(self):
  662. grammar = """
  663. a: b
  664. b: c*
  665. c: a
  666. """
  667. l = Lark(grammar, start='a', ambiguity='resolve', lexer=LEXER)
  668. tree = l.parse('')
  669. self.assertEqual(tree, Tree('a', [Tree('b', [])]))
  670. l = Lark(grammar, start='a', ambiguity='explicit', lexer=LEXER)
  671. tree = l.parse('')
  672. self.assertEqual(tree, Tree('a', [Tree('b', [])]))
  673. def test_many_cycles(self):
  674. grammar = """
  675. start: a? | start start
  676. !a: "a"
  677. """
  678. l = Lark(grammar, ambiguity='resolve', lexer=LEXER)
  679. tree = l.parse('a')
  680. self.assertEqual(tree, Tree('start', [Tree('a', ['a'])]))
  681. l = Lark(grammar, ambiguity='explicit', lexer=LEXER)
  682. tree = l.parse('a')
  683. self.assertEqual(tree, Tree('start', [Tree('a', ['a'])]))
  684. def test_cycles_with_child_filter(self):
  685. grammar = """
  686. a: _x
  687. _x: _x? b
  688. b:
  689. """
  690. grammar2 = """
  691. a: x
  692. x: x? b
  693. b:
  694. """
  695. l = Lark(grammar, start='a', ambiguity='resolve', lexer=LEXER)
  696. tree = l.parse('')
  697. self.assertEqual(tree, Tree('a', [Tree('b', [])]))
  698. l = Lark(grammar, start='a', ambiguity='explicit', lexer=LEXER)
  699. tree = l.parse('');
  700. self.assertEqual(tree, Tree('a', [Tree('b', [])]))
  701. l = Lark(grammar2, start='a', ambiguity='resolve', lexer=LEXER)
  702. tree = l.parse('');
  703. self.assertEqual(tree, Tree('a', [Tree('x', [Tree('b', [])])]))
  704. l = Lark(grammar2, start='a', ambiguity='explicit', lexer=LEXER)
  705. tree = l.parse('');
  706. self.assertEqual(tree, Tree('a', [Tree('x', [Tree('b', [])])]))
  707. # @unittest.skipIf(LEXER=='dynamic', "Not implemented in Dynamic Earley yet") # TODO
  708. # def test_not_all_derivations(self):
  709. # grammar = """
  710. # start: cd+ "e"
  711. # !cd: "c"
  712. # | "d"
  713. # | "cd"
  714. # """
  715. # l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER, earley__all_derivations=False)
  716. # x = l.parse('cde')
  717. # assert x.data != '_ambig', x
  718. # assert len(x.children) == 1
  719. _NAME = "TestFullEarley" + LEXER.capitalize()
  720. _TestFullEarley.__name__ = _NAME
  721. globals()[_NAME] = _TestFullEarley
  722. __all__.append(_NAME)
  723. class CustomLexerNew(Lexer):
  724. """
  725. Purpose of this custom lexer is to test the integration,
  726. so it uses the traditionalparser as implementation without custom lexing behaviour.
  727. """
  728. def __init__(self, lexer_conf):
  729. self.lexer = TraditionalLexer(copy(lexer_conf))
  730. def lex(self, lexer_state, parser_state):
  731. return self.lexer.lex(lexer_state, parser_state)
  732. __future_interface__ = True
  733. class CustomLexerOld(Lexer):
  734. """
  735. Purpose of this custom lexer is to test the integration,
  736. so it uses the traditionalparser as implementation without custom lexing behaviour.
  737. """
  738. def __init__(self, lexer_conf):
  739. self.lexer = TraditionalLexer(copy(lexer_conf))
  740. def lex(self, text):
  741. ls = self.lexer.make_lexer_state(text)
  742. return self.lexer.lex(ls, None)
  743. __future_interface__ = False
  744. def _tree_structure_check(a, b):
  745. """
  746. Checks that both Tree objects have the same structure, without checking their values.
  747. """
  748. assert a.data == b.data and len(a.children) == len(b.children)
  749. for ca,cb in zip(a.children, b.children):
  750. assert type(ca) == type(cb)
  751. if isinstance(ca, Tree):
  752. _tree_structure_check(ca, cb)
  753. elif isinstance(ca, Token):
  754. assert ca.type == cb.type
  755. else:
  756. assert ca == cb
  757. class DualBytesLark:
  758. """
  759. A helper class that wraps both a normal parser, and a parser for bytes.
  760. It automatically transforms `.parse` calls for both lexer, returning the value from the text lexer
  761. It always checks that both produce the same output/error
  762. NOTE: Not currently used, but left here for future debugging.
  763. """
  764. def __init__(self, g, *args, **kwargs):
  765. self.text_lexer = Lark(g, *args, use_bytes=False, **kwargs)
  766. g = self.text_lexer.grammar_source.lower()
  767. if '\\u' in g or not isascii(g):
  768. # Bytes re can't deal with uniode escapes
  769. self.bytes_lark = None
  770. else:
  771. # Everything here should work, so use `use_bytes='force'`
  772. self.bytes_lark = Lark(self.text_lexer.grammar_source, *args, use_bytes='force', **kwargs)
  773. def parse(self, text, start=None):
  774. # TODO: Easy workaround, more complex checks would be beneficial
  775. if not isascii(text) or self.bytes_lark is None:
  776. return self.text_lexer.parse(text, start)
  777. try:
  778. rv = self.text_lexer.parse(text, start)
  779. except Exception as e:
  780. try:
  781. self.bytes_lark.parse(text.encode(), start)
  782. except Exception as be:
  783. assert type(e) == type(be), "Parser with and without `use_bytes` raise different exceptions"
  784. raise e
  785. assert False, "Parser without `use_bytes` raises exception, with doesn't"
  786. try:
  787. bv = self.bytes_lark.parse(text.encode(), start)
  788. except Exception as be:
  789. assert False, "Parser without `use_bytes` doesn't raise an exception, with does"
  790. _tree_structure_check(rv, bv)
  791. return rv
  792. @classmethod
  793. def open(cls, grammar_filename, rel_to=None, **options):
  794. if rel_to:
  795. basepath = os.path.dirname(rel_to)
  796. grammar_filename = os.path.join(basepath, grammar_filename)
  797. with open(grammar_filename, encoding='utf8') as f:
  798. return cls(f, **options)
  799. def save(self,f):
  800. self.text_lexer.save(f)
  801. if self.bytes_lark is not None:
  802. self.bytes_lark.save(f)
  803. def load(self,f):
  804. self.text_lexer = self.text_lexer.load(f)
  805. if self.bytes_lark is not None:
  806. self.bytes_lark.load(f)
  807. def _make_parser_test(LEXER, PARSER):
  808. lexer_class_or_name = {
  809. 'custom_new': CustomLexerNew,
  810. 'custom_old': CustomLexerOld,
  811. }.get(LEXER, LEXER)
  812. def _Lark(grammar, **kwargs):
  813. return Lark(grammar, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  814. def _Lark_open(gfilename, **kwargs):
  815. return Lark.open(gfilename, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  816. if (LEXER, PARSER) == ('standard', 'earley'):
  817. # Check that the `lark.lark` grammar represents can parse every example used in these tests.
  818. # Standard-Earley was an arbitrary choice, to make sure it only ran once.
  819. lalr_parser = Lark.open(os.path.join(os.path.dirname(lark.__file__), 'grammars/lark.lark'), parser='lalr')
  820. def wrap_with_test_grammar(f):
  821. def _f(x, **kwargs):
  822. inst = f(x, **kwargs)
  823. lalr_parser.parse(inst.source_grammar) # Test after instance creation. When the grammar should fail, don't test it.
  824. return inst
  825. return _f
  826. _Lark = wrap_with_test_grammar(_Lark)
  827. _Lark_open = wrap_with_test_grammar(_Lark_open)
  828. class _TestParser(unittest.TestCase):
  829. def test_basic1(self):
  830. g = _Lark("""start: a+ b a* "b" a*
  831. b: "b"
  832. a: "a"
  833. """)
  834. r = g.parse('aaabaab')
  835. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  836. r = g.parse('aaabaaba')
  837. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  838. self.assertRaises(ParseError, g.parse, 'aaabaa')
  839. def test_basic2(self):
  840. # Multiple parsers and colliding tokens
  841. g = _Lark("""start: B A
  842. B: "12"
  843. A: "1" """)
  844. g2 = _Lark("""start: B A
  845. B: "12"
  846. A: "2" """)
  847. x = g.parse('121')
  848. assert x.data == 'start' and x.children == ['12', '1'], x
  849. x = g2.parse('122')
  850. assert x.data == 'start' and x.children == ['12', '2'], x
  851. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  852. def test_stringio_bytes(self):
  853. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  854. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  855. def test_stringio_unicode(self):
  856. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  857. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  858. def test_unicode(self):
  859. g = _Lark(u"""start: UNIA UNIB UNIA
  860. UNIA: /\xa3/
  861. UNIB: /\u0101/
  862. """)
  863. g.parse(u'\xa3\u0101\u00a3')
  864. def test_unicode2(self):
  865. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  866. UNIA: /\xa3/
  867. UNIB: "a\u0101b\ "
  868. UNIC: /a?\u0101c\n/
  869. """)
  870. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  871. def test_unicode3(self):
  872. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  873. UNIA: /\xa3/
  874. UNIB: "\u0101"
  875. UNIC: /\u0203/ /\n/
  876. """)
  877. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  878. def test_hex_escape(self):
  879. g = _Lark(r"""start: A B C
  880. A: "\x01"
  881. B: /\x02/
  882. C: "\xABCD"
  883. """)
  884. g.parse('\x01\x02\xABCD')
  885. def test_unicode_literal_range_escape(self):
  886. g = _Lark(r"""start: A+
  887. A: "\u0061".."\u0063"
  888. """)
  889. g.parse('abc')
  890. def test_hex_literal_range_escape(self):
  891. g = _Lark(r"""start: A+
  892. A: "\x01".."\x03"
  893. """)
  894. g.parse('\x01\x02\x03')
  895. @unittest.skipIf(sys.version_info[0]==2 or sys.version_info[:2]==(3, 4),
  896. "bytes parser isn't perfect in Python2, exceptions don't work correctly")
  897. def test_bytes_utf8(self):
  898. g = r"""
  899. start: BOM? char+
  900. BOM: "\xef\xbb\xbf"
  901. char: CHAR1 | CHAR2 | CHAR3 | CHAR4
  902. CONTINUATION_BYTE: "\x80" .. "\xbf"
  903. CHAR1: "\x00" .. "\x7f"
  904. CHAR2: "\xc0" .. "\xdf" CONTINUATION_BYTE
  905. CHAR3: "\xe0" .. "\xef" CONTINUATION_BYTE CONTINUATION_BYTE
  906. CHAR4: "\xf0" .. "\xf7" CONTINUATION_BYTE CONTINUATION_BYTE CONTINUATION_BYTE
  907. """
  908. g = _Lark(g, use_bytes=True)
  909. s = u"🔣 地? gurīn".encode('utf-8')
  910. self.assertEqual(len(g.parse(s).children), 10)
  911. for enc, j in [("sjis", u"地球の絵はグリーンでグッド? Chikyuu no e wa guriin de guddo"),
  912. ("sjis", u"売春婦"),
  913. ("euc-jp", u"乂鵬鵠")]:
  914. s = j.encode(enc)
  915. self.assertRaises(UnexpectedCharacters, g.parse, s)
  916. @unittest.skipIf(PARSER == 'cyk', "Takes forever")
  917. def test_stack_for_ebnf(self):
  918. """Verify that stack depth isn't an issue for EBNF grammars"""
  919. g = _Lark(r"""start: a+
  920. a : "a" """)
  921. g.parse("a" * (sys.getrecursionlimit()*2 ))
  922. def test_expand1_lists_with_one_item(self):
  923. g = _Lark(r"""start: list
  924. ?list: item+
  925. item : A
  926. A: "a"
  927. """)
  928. r = g.parse("a")
  929. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  930. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  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. def test_expand1_lists_with_one_item_2(self):
  934. g = _Lark(r"""start: list
  935. ?list: item+ "!"
  936. item : A
  937. A: "a"
  938. """)
  939. r = g.parse("a!")
  940. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  941. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  942. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  943. self.assertEqual(len(r.children), 1)
  944. def test_dont_expand1_lists_with_multiple_items(self):
  945. g = _Lark(r"""start: list
  946. ?list: item+
  947. item : A
  948. A: "a"
  949. """)
  950. r = g.parse("aa")
  951. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  952. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  953. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  954. self.assertEqual(len(r.children), 1)
  955. # Sanity check: verify that 'list' contains the two 'item's we've given it
  956. [list] = r.children
  957. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  958. def test_dont_expand1_lists_with_multiple_items_2(self):
  959. g = _Lark(r"""start: list
  960. ?list: item+ "!"
  961. item : A
  962. A: "a"
  963. """)
  964. r = g.parse("aa!")
  965. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  966. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  967. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  968. self.assertEqual(len(r.children), 1)
  969. # Sanity check: verify that 'list' contains the two 'item's we've given it
  970. [list] = r.children
  971. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  972. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  973. def test_empty_expand1_list(self):
  974. g = _Lark(r"""start: list
  975. ?list: item*
  976. item : A
  977. A: "a"
  978. """)
  979. r = g.parse("")
  980. # 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
  981. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  982. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  983. self.assertEqual(len(r.children), 1)
  984. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  985. [list] = r.children
  986. self.assertSequenceEqual([item.data for item in list.children], ())
  987. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  988. def test_empty_expand1_list_2(self):
  989. g = _Lark(r"""start: list
  990. ?list: item* "!"?
  991. item : A
  992. A: "a"
  993. """)
  994. r = g.parse("")
  995. # 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
  996. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  997. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  998. self.assertEqual(len(r.children), 1)
  999. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  1000. [list] = r.children
  1001. self.assertSequenceEqual([item.data for item in list.children], ())
  1002. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1003. def test_empty_flatten_list(self):
  1004. g = _Lark(r"""start: list
  1005. list: | item "," list
  1006. item : A
  1007. A: "a"
  1008. """)
  1009. r = g.parse("")
  1010. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  1011. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  1012. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  1013. [list] = r.children
  1014. self.assertSequenceEqual([item.data for item in list.children], ())
  1015. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  1016. def test_single_item_flatten_list(self):
  1017. g = _Lark(r"""start: list
  1018. list: | item "," list
  1019. item : A
  1020. A: "a"
  1021. """)
  1022. r = g.parse("a,")
  1023. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  1024. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  1025. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  1026. [list] = r.children
  1027. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  1028. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  1029. def test_multiple_item_flatten_list(self):
  1030. g = _Lark(r"""start: list
  1031. #list: | item "," list
  1032. item : A
  1033. A: "a"
  1034. """)
  1035. r = g.parse("a,a,")
  1036. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  1037. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  1038. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  1039. [list] = r.children
  1040. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  1041. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  1042. def test_recurse_flatten(self):
  1043. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  1044. g = _Lark(r"""start: a | start a
  1045. a : A
  1046. A : "a" """)
  1047. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  1048. # STree data structures, which uses recursion).
  1049. g.parse("a" * (sys.getrecursionlimit() // 4))
  1050. def test_token_collision(self):
  1051. g = _Lark(r"""start: "Hello" NAME
  1052. NAME: /\w/+
  1053. %ignore " "
  1054. """)
  1055. x = g.parse('Hello World')
  1056. self.assertSequenceEqual(x.children, ['World'])
  1057. x = g.parse('Hello HelloWorld')
  1058. self.assertSequenceEqual(x.children, ['HelloWorld'])
  1059. def test_token_collision_WS(self):
  1060. g = _Lark(r"""start: "Hello" NAME
  1061. NAME: /\w/+
  1062. %import common.WS
  1063. %ignore WS
  1064. """)
  1065. x = g.parse('Hello World')
  1066. self.assertSequenceEqual(x.children, ['World'])
  1067. x = g.parse('Hello HelloWorld')
  1068. self.assertSequenceEqual(x.children, ['HelloWorld'])
  1069. def test_token_collision2(self):
  1070. g = _Lark("""
  1071. !start: "starts"
  1072. %import common.LCASE_LETTER
  1073. """)
  1074. x = g.parse("starts")
  1075. self.assertSequenceEqual(x.children, ['starts'])
  1076. def test_templates(self):
  1077. g = _Lark(r"""
  1078. start: "[" sep{NUMBER, ","} "]"
  1079. sep{item, delim}: item (delim item)*
  1080. NUMBER: /\d+/
  1081. %ignore " "
  1082. """)
  1083. x = g.parse("[1, 2, 3, 4]")
  1084. self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])])
  1085. x = g.parse("[1]")
  1086. self.assertSequenceEqual(x.children, [Tree('sep', ['1'])])
  1087. def test_templates_recursion(self):
  1088. g = _Lark(r"""
  1089. start: "[" _sep{NUMBER, ","} "]"
  1090. _sep{item, delim}: item | _sep{item, delim} delim item
  1091. NUMBER: /\d+/
  1092. %ignore " "
  1093. """)
  1094. x = g.parse("[1, 2, 3, 4]")
  1095. self.assertSequenceEqual(x.children, ['1', '2', '3', '4'])
  1096. x = g.parse("[1]")
  1097. self.assertSequenceEqual(x.children, ['1'])
  1098. def test_templates_import(self):
  1099. g = _Lark_open("test_templates_import.lark", rel_to=__file__)
  1100. x = g.parse("[1, 2, 3, 4]")
  1101. self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])])
  1102. x = g.parse("[1]")
  1103. self.assertSequenceEqual(x.children, [Tree('sep', ['1'])])
  1104. def test_templates_alias(self):
  1105. g = _Lark(r"""
  1106. start: expr{"C"}
  1107. expr{t}: "A" t
  1108. | "B" t -> b
  1109. """)
  1110. x = g.parse("AC")
  1111. self.assertSequenceEqual(x.children, [Tree('expr', [])])
  1112. x = g.parse("BC")
  1113. self.assertSequenceEqual(x.children, [Tree('b', [])])
  1114. def test_templates_modifiers(self):
  1115. g = _Lark(r"""
  1116. start: expr{"B"}
  1117. !expr{t}: "A" t
  1118. """)
  1119. x = g.parse("AB")
  1120. self.assertSequenceEqual(x.children, [Tree('expr', ["A", "B"])])
  1121. g = _Lark(r"""
  1122. start: _expr{"B"}
  1123. !_expr{t}: "A" t
  1124. """)
  1125. x = g.parse("AB")
  1126. self.assertSequenceEqual(x.children, ["A", "B"])
  1127. g = _Lark(r"""
  1128. start: expr{b}
  1129. b: "B"
  1130. ?expr{t}: "A" t
  1131. """)
  1132. x = g.parse("AB")
  1133. self.assertSequenceEqual(x.children, [Tree('b',[])])
  1134. def test_templates_templates(self):
  1135. g = _Lark('''start: a{b}
  1136. a{t}: t{"a"}
  1137. b{x}: x''')
  1138. x = g.parse('a')
  1139. self.assertSequenceEqual(x.children, [Tree('a', [Tree('b',[])])])
  1140. def test_g_regex_flags(self):
  1141. g = _Lark("""
  1142. start: "a" /b+/ C
  1143. C: "C" | D
  1144. D: "D" E
  1145. E: "e"
  1146. """, g_regex_flags=re.I)
  1147. x1 = g.parse("ABBc")
  1148. x2 = g.parse("abdE")
  1149. # def test_string_priority(self):
  1150. # g = _Lark("""start: (A | /a?bb/)+
  1151. # A: "a" """)
  1152. # x = g.parse('abb')
  1153. # self.assertEqual(len(x.children), 2)
  1154. # # This parse raises an exception because the lexer will always try to consume
  1155. # # "a" first and will never match the regular expression
  1156. # # This behavior is subject to change!!
  1157. # # Thie won't happen with ambiguity handling.
  1158. # g = _Lark("""start: (A | /a?ab/)+
  1159. # A: "a" """)
  1160. # self.assertRaises(LexError, g.parse, 'aab')
  1161. def test_rule_collision(self):
  1162. g = _Lark("""start: "a"+ "b"
  1163. | "a"+ """)
  1164. x = g.parse('aaaa')
  1165. x = g.parse('aaaab')
  1166. def test_rule_collision2(self):
  1167. g = _Lark("""start: "a"* "b"
  1168. | "a"+ """)
  1169. x = g.parse('aaaa')
  1170. x = g.parse('aaaab')
  1171. x = g.parse('b')
  1172. def test_token_not_anon(self):
  1173. """Tests that "a" is matched as an anonymous token, and not A.
  1174. """
  1175. g = _Lark("""start: "a"
  1176. A: "a" """)
  1177. x = g.parse('a')
  1178. self.assertEqual(len(x.children), 0, '"a" should be considered anonymous')
  1179. g = _Lark("""start: "a" A
  1180. A: "a" """)
  1181. x = g.parse('aa')
  1182. self.assertEqual(len(x.children), 1, 'only "a" should be considered anonymous')
  1183. self.assertEqual(x.children[0].type, "A")
  1184. g = _Lark("""start: /a/
  1185. A: /a/ """)
  1186. x = g.parse('a')
  1187. self.assertEqual(len(x.children), 1)
  1188. self.assertEqual(x.children[0].type, "A", "A isn't associated with /a/")
  1189. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1190. def test_maybe(self):
  1191. g = _Lark("""start: ["a"] """)
  1192. x = g.parse('a')
  1193. x = g.parse('')
  1194. def test_start(self):
  1195. g = _Lark("""a: "a" a? """, start='a')
  1196. x = g.parse('a')
  1197. x = g.parse('aa')
  1198. x = g.parse('aaa')
  1199. def test_alias(self):
  1200. g = _Lark("""start: "a" -> b """)
  1201. x = g.parse('a')
  1202. self.assertEqual(x.data, "b")
  1203. def test_token_ebnf(self):
  1204. g = _Lark("""start: A
  1205. A: "a"* ("b"? "c".."e")+
  1206. """)
  1207. x = g.parse('abcde')
  1208. x = g.parse('dd')
  1209. def test_backslash(self):
  1210. g = _Lark(r"""start: "\\" "a"
  1211. """)
  1212. x = g.parse(r'\a')
  1213. g = _Lark(r"""start: /\\/ /a/
  1214. """)
  1215. x = g.parse(r'\a')
  1216. def test_backslash2(self):
  1217. g = _Lark(r"""start: "\"" "-"
  1218. """)
  1219. x = g.parse('"-')
  1220. g = _Lark(r"""start: /\// /-/
  1221. """)
  1222. x = g.parse('/-')
  1223. def test_special_chars(self):
  1224. g = _Lark(r"""start: "\n"
  1225. """)
  1226. x = g.parse('\n')
  1227. g = _Lark(r"""start: /\n/
  1228. """)
  1229. x = g.parse('\n')
  1230. # def test_token_recurse(self):
  1231. # g = _Lark("""start: A
  1232. # A: B
  1233. # B: A
  1234. # """)
  1235. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1236. def test_empty(self):
  1237. # Fails an Earley implementation without special handling for empty rules,
  1238. # or re-processing of already completed rules.
  1239. g = _Lark(r"""start: _empty a "B"
  1240. a: _empty "A"
  1241. _empty:
  1242. """)
  1243. x = g.parse('AB')
  1244. def test_regex_quote(self):
  1245. g = r"""
  1246. start: SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING
  1247. SINGLE_QUOTED_STRING : /'[^']*'/
  1248. DOUBLE_QUOTED_STRING : /"[^"]*"/
  1249. """
  1250. g = _Lark(g)
  1251. self.assertEqual( g.parse('"hello"').children, ['"hello"'])
  1252. self.assertEqual( g.parse("'hello'").children, ["'hello'"])
  1253. @unittest.skipIf(not Py36, "Required re syntax only exists in python3.6+")
  1254. def test_join_regex_flags(self):
  1255. g = r"""
  1256. start: A
  1257. A: B C
  1258. B: /./s
  1259. C: /./
  1260. """
  1261. g = _Lark(g)
  1262. self.assertEqual(g.parse(" ").children,[" "])
  1263. self.assertEqual(g.parse("\n ").children,["\n "])
  1264. self.assertRaises(UnexpectedCharacters, g.parse, "\n\n")
  1265. g = r"""
  1266. start: A
  1267. A: B | C
  1268. B: "b"i
  1269. C: "c"
  1270. """
  1271. g = _Lark(g)
  1272. self.assertEqual(g.parse("b").children,["b"])
  1273. self.assertEqual(g.parse("B").children,["B"])
  1274. self.assertEqual(g.parse("c").children,["c"])
  1275. self.assertRaises(UnexpectedCharacters, g.parse, "C")
  1276. def test_lexer_token_limit(self):
  1277. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  1278. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  1279. g = _Lark("""start: %s
  1280. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  1281. def test_float_without_lexer(self):
  1282. expected_error = UnexpectedCharacters if 'dynamic' in LEXER else UnexpectedToken
  1283. if PARSER == 'cyk':
  1284. expected_error = ParseError
  1285. g = _Lark("""start: ["+"|"-"] float
  1286. float: digit* "." digit+ exp?
  1287. | digit+ exp
  1288. exp: ("e"|"E") ["+"|"-"] digit+
  1289. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  1290. """)
  1291. g.parse("1.2")
  1292. g.parse("-.2e9")
  1293. g.parse("+2e-9")
  1294. self.assertRaises( expected_error, g.parse, "+2e-9e")
  1295. def test_keep_all_tokens(self):
  1296. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  1297. tree = l.parse('aaa')
  1298. self.assertEqual(tree.children, ['a', 'a', 'a'])
  1299. def test_token_flags(self):
  1300. l = _Lark("""!start: "a"i+
  1301. """
  1302. )
  1303. tree = l.parse('aA')
  1304. self.assertEqual(tree.children, ['a', 'A'])
  1305. l = _Lark("""!start: /a/i+
  1306. """
  1307. )
  1308. tree = l.parse('aA')
  1309. self.assertEqual(tree.children, ['a', 'A'])
  1310. # g = """!start: "a"i "a"
  1311. # """
  1312. # self.assertRaises(GrammarError, _Lark, g)
  1313. # g = """!start: /a/i /a/
  1314. # """
  1315. # self.assertRaises(GrammarError, _Lark, g)
  1316. g = """start: NAME "," "a"
  1317. NAME: /[a-z_]/i /[a-z0-9_]/i*
  1318. """
  1319. l = _Lark(g)
  1320. tree = l.parse('ab,a')
  1321. self.assertEqual(tree.children, ['ab'])
  1322. tree = l.parse('AB,a')
  1323. self.assertEqual(tree.children, ['AB'])
  1324. def test_token_flags3(self):
  1325. l = _Lark("""!start: ABC+
  1326. ABC: "abc"i
  1327. """
  1328. )
  1329. tree = l.parse('aBcAbC')
  1330. self.assertEqual(tree.children, ['aBc', 'AbC'])
  1331. def test_token_flags2(self):
  1332. g = """!start: ("a"i | /a/ /b/?)+
  1333. """
  1334. l = _Lark(g)
  1335. tree = l.parse('aA')
  1336. self.assertEqual(tree.children, ['a', 'A'])
  1337. def test_token_flags_verbose(self):
  1338. g = _Lark(r"""start: NL | ABC
  1339. ABC: / [a-z] /x
  1340. NL: /\n/
  1341. """)
  1342. x = g.parse('a')
  1343. self.assertEqual(x.children, ['a'])
  1344. def test_token_flags_verbose_multiline(self):
  1345. g = _Lark(r"""start: ABC
  1346. ABC: / a b c
  1347. d
  1348. e f
  1349. /x
  1350. """)
  1351. x = g.parse('abcdef')
  1352. self.assertEqual(x.children, ['abcdef'])
  1353. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1354. def test_twice_empty(self):
  1355. g = """!start: ("A"?)?
  1356. """
  1357. l = _Lark(g)
  1358. tree = l.parse('A')
  1359. self.assertEqual(tree.children, ['A'])
  1360. tree = l.parse('')
  1361. self.assertEqual(tree.children, [])
  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('dynamic' in LEXER, "%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('dynamic' in LEXER, "%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. @unittest.skipIf(PARSER == 'cyk', "Doesn't work for CYK")
  1589. def test_prioritization(self):
  1590. "Tests effect of priority on result"
  1591. grammar = """
  1592. start: a | b
  1593. a.1: "a"
  1594. b.2: "a"
  1595. """
  1596. l = _Lark(grammar)
  1597. res = l.parse("a")
  1598. self.assertEqual(res.children[0].data, 'b')
  1599. grammar = """
  1600. start: a | b
  1601. a.2: "a"
  1602. b.1: "a"
  1603. """
  1604. l = _Lark(grammar)
  1605. res = l.parse("a")
  1606. self.assertEqual(res.children[0].data, 'a')
  1607. grammar = """
  1608. start: a | b
  1609. a.2: "A"+
  1610. b.1: "A"+ "B"?
  1611. """
  1612. l = _Lark(grammar)
  1613. res = l.parse("AAAA")
  1614. self.assertEqual(res.children[0].data, 'a')
  1615. l = _Lark(grammar)
  1616. res = l.parse("AAAB")
  1617. self.assertEqual(res.children[0].data, 'b')
  1618. l = _Lark(grammar, priority="invert")
  1619. res = l.parse("AAAA")
  1620. self.assertEqual(res.children[0].data, 'b')
  1621. @unittest.skipIf(PARSER != 'earley' or 'dynamic' not in LEXER, "Currently only Earley supports priority sum in rules")
  1622. def test_prioritization_sum(self):
  1623. "Tests effect of priority on result"
  1624. grammar = """
  1625. start: ab_ b_ a_ | indirection
  1626. indirection: a_ bb_ a_
  1627. a_: "a"
  1628. b_: "b"
  1629. ab_: "ab"
  1630. bb_.1: "bb"
  1631. """
  1632. l = _Lark(grammar, priority="invert")
  1633. res = l.parse('abba')
  1634. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1635. grammar = """
  1636. start: ab_ b_ a_ | indirection
  1637. indirection: a_ bb_ a_
  1638. a_: "a"
  1639. b_: "b"
  1640. ab_.1: "ab"
  1641. bb_: "bb"
  1642. """
  1643. l = _Lark(grammar, priority="invert")
  1644. res = l.parse('abba')
  1645. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1646. grammar = """
  1647. start: ab_ b_ a_ | indirection
  1648. indirection: a_ bb_ a_
  1649. a_.2: "a"
  1650. b_.1: "b"
  1651. ab_.3: "ab"
  1652. bb_.3: "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_.1: "a"
  1661. b_.1: "b"
  1662. ab_.4: "ab"
  1663. bb_.3: "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. def test_utf8(self):
  1669. g = u"""start: a
  1670. a: "±a"
  1671. """
  1672. l = _Lark(g)
  1673. self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])]))
  1674. g = u"""start: A
  1675. A: "±a"
  1676. """
  1677. l = _Lark(g)
  1678. self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a']))
  1679. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1680. def test_ignore(self):
  1681. grammar = r"""
  1682. COMMENT: /(!|(\/\/))[^\n]*/
  1683. %ignore COMMENT
  1684. %import common.WS -> _WS
  1685. %import common.INT
  1686. start: "INT"i _WS+ INT _WS*
  1687. """
  1688. parser = _Lark(grammar)
  1689. tree = parser.parse("int 1 ! This is a comment\n")
  1690. self.assertEqual(tree.children, ['1'])
  1691. tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky!
  1692. self.assertEqual(tree.children, ['1'])
  1693. parser = _Lark(r"""
  1694. start : "a"*
  1695. %ignore "b"
  1696. """)
  1697. tree = parser.parse("bb")
  1698. self.assertEqual(tree.children, [])
  1699. def test_regex_escaping(self):
  1700. g = _Lark("start: /[ab]/")
  1701. g.parse('a')
  1702. g.parse('b')
  1703. self.assertRaises( UnexpectedInput, g.parse, 'c')
  1704. _Lark(r'start: /\w/').parse('a')
  1705. g = _Lark(r'start: /\\w/')
  1706. self.assertRaises( UnexpectedInput, g.parse, 'a')
  1707. g.parse(r'\w')
  1708. _Lark(r'start: /\[/').parse('[')
  1709. _Lark(r'start: /\//').parse('/')
  1710. _Lark(r'start: /\\/').parse('\\')
  1711. _Lark(r'start: /\[ab]/').parse('[ab]')
  1712. _Lark(r'start: /\\[ab]/').parse('\\a')
  1713. _Lark(r'start: /\t/').parse('\t')
  1714. _Lark(r'start: /\\t/').parse('\\t')
  1715. _Lark(r'start: /\\\t/').parse('\\\t')
  1716. _Lark(r'start: "\t"').parse('\t')
  1717. _Lark(r'start: "\\t"').parse('\\t')
  1718. _Lark(r'start: "\\\t"').parse('\\\t')
  1719. def test_ranged_repeat_rules(self):
  1720. g = u"""!start: "A"~3
  1721. """
  1722. l = _Lark(g)
  1723. self.assertEqual(l.parse(u'AAA'), Tree('start', ["A", "A", "A"]))
  1724. self.assertRaises(ParseError, l.parse, u'AA')
  1725. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1726. g = u"""!start: "A"~0..2
  1727. """
  1728. if PARSER != 'cyk': # XXX CYK currently doesn't support empty grammars
  1729. l = _Lark(g)
  1730. self.assertEqual(l.parse(u''), Tree('start', []))
  1731. self.assertEqual(l.parse(u'A'), Tree('start', ['A']))
  1732. self.assertEqual(l.parse(u'AA'), Tree('start', ['A', 'A']))
  1733. self.assertRaises((UnexpectedToken, UnexpectedInput), l.parse, u'AAA')
  1734. g = u"""!start: "A"~3..2
  1735. """
  1736. self.assertRaises(GrammarError, _Lark, g)
  1737. g = u"""!start: "A"~2..3 "B"~2
  1738. """
  1739. l = _Lark(g)
  1740. self.assertEqual(l.parse(u'AABB'), Tree('start', ['A', 'A', 'B', 'B']))
  1741. self.assertEqual(l.parse(u'AAABB'), Tree('start', ['A', 'A', 'A', 'B', 'B']))
  1742. self.assertRaises(ParseError, l.parse, u'AAAB')
  1743. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1744. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1745. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1746. def test_ranged_repeat_terms(self):
  1747. g = u"""!start: AAA
  1748. AAA: "A"~3
  1749. """
  1750. l = _Lark(g)
  1751. self.assertEqual(l.parse(u'AAA'), Tree('start', ["AAA"]))
  1752. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AA')
  1753. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1754. g = u"""!start: AABB CC
  1755. AABB: "A"~0..2 "B"~2
  1756. CC: "C"~1..2
  1757. """
  1758. l = _Lark(g)
  1759. self.assertEqual(l.parse(u'AABBCC'), Tree('start', ['AABB', 'CC']))
  1760. self.assertEqual(l.parse(u'BBC'), Tree('start', ['BB', 'C']))
  1761. self.assertEqual(l.parse(u'ABBCC'), Tree('start', ['ABB', 'CC']))
  1762. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAB')
  1763. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1764. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1765. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1766. @unittest.skipIf(PARSER=='earley', "Priority not handled correctly right now") # TODO XXX
  1767. def test_priority_vs_embedded(self):
  1768. g = """
  1769. A.2: "a"
  1770. WORD: ("a".."z")+
  1771. start: (A | WORD)+
  1772. """
  1773. l = _Lark(g)
  1774. t = l.parse('abc')
  1775. self.assertEqual(t.children, ['a', 'bc'])
  1776. self.assertEqual(t.children[0].type, 'A')
  1777. def test_line_counting(self):
  1778. p = _Lark("start: /[^x]+/")
  1779. text = 'hello\nworld'
  1780. t = p.parse(text)
  1781. tok = t.children[0]
  1782. self.assertEqual(tok, text)
  1783. self.assertEqual(tok.line, 1)
  1784. self.assertEqual(tok.column, 1)
  1785. # if _LEXER != 'dynamic':
  1786. self.assertEqual(tok.end_line, 2)
  1787. self.assertEqual(tok.end_column, 6)
  1788. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1789. def test_empty_end(self):
  1790. p = _Lark("""
  1791. start: b c d
  1792. b: "B"
  1793. c: | "C"
  1794. d: | "D"
  1795. """)
  1796. res = p.parse('B')
  1797. self.assertEqual(len(res.children), 3)
  1798. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1799. def test_maybe_placeholders(self):
  1800. # Anonymous tokens shouldn't count
  1801. p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1802. self.assertEqual(p.parse("").children, [])
  1803. # Unless keep_all_tokens=True
  1804. p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True, keep_all_tokens=True)
  1805. self.assertEqual(p.parse("").children, [None, None, None])
  1806. # All invisible constructs shouldn't count
  1807. p = _Lark("""start: [A] ["b"] [_c] ["e" "f" _c]
  1808. A: "a"
  1809. _c: "c" """, maybe_placeholders=True)
  1810. self.assertEqual(p.parse("").children, [None])
  1811. self.assertEqual(p.parse("c").children, [None])
  1812. self.assertEqual(p.parse("aefc").children, ['a'])
  1813. # ? shouldn't apply
  1814. p = _Lark("""!start: ["a"] "b"? ["c"] """, maybe_placeholders=True)
  1815. self.assertEqual(p.parse("").children, [None, None])
  1816. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1817. p = _Lark("""!start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1818. self.assertEqual(p.parse("").children, [None, None, None])
  1819. self.assertEqual(p.parse("a").children, ['a', None, None])
  1820. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1821. self.assertEqual(p.parse("c").children, [None, None, 'c'])
  1822. self.assertEqual(p.parse("ab").children, ['a', 'b', None])
  1823. self.assertEqual(p.parse("ac").children, ['a', None, 'c'])
  1824. self.assertEqual(p.parse("bc").children, [None, 'b', 'c'])
  1825. self.assertEqual(p.parse("abc").children, ['a', 'b', 'c'])
  1826. p = _Lark("""!start: (["a"] "b" ["c"])+ """, maybe_placeholders=True)
  1827. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1828. self.assertEqual(p.parse("bb").children, [None, 'b', None, None, 'b', None])
  1829. self.assertEqual(p.parse("abbc").children, ['a', 'b', None, None, 'b', 'c'])
  1830. self.assertEqual(p.parse("babbcabcb").children,
  1831. [None, 'b', None,
  1832. 'a', 'b', None,
  1833. None, 'b', 'c',
  1834. 'a', 'b', 'c',
  1835. None, 'b', None])
  1836. p = _Lark("""!start: ["a"] ["c"] "b"+ ["a"] ["d"] """, maybe_placeholders=True)
  1837. self.assertEqual(p.parse("bb").children, [None, None, 'b', 'b', None, None])
  1838. self.assertEqual(p.parse("bd").children, [None, None, 'b', None, 'd'])
  1839. self.assertEqual(p.parse("abba").children, ['a', None, 'b', 'b', 'a', None])
  1840. self.assertEqual(p.parse("cbbbb").children, [None, 'c', 'b', 'b', 'b', 'b', None, None])
  1841. def test_escaped_string(self):
  1842. "Tests common.ESCAPED_STRING"
  1843. grammar = r"""
  1844. start: ESCAPED_STRING+
  1845. %import common (WS_INLINE, ESCAPED_STRING)
  1846. %ignore WS_INLINE
  1847. """
  1848. parser = _Lark(grammar)
  1849. parser.parse(r'"\\" "b" "c"')
  1850. parser.parse(r'"That" "And a \"b"')
  1851. def test_meddling_unused(self):
  1852. "Unless 'unused' is removed, LALR analysis will fail on reduce-reduce collision"
  1853. grammar = """
  1854. start: EKS* x
  1855. x: EKS
  1856. unused: x*
  1857. EKS: "x"
  1858. """
  1859. parser = _Lark(grammar)
  1860. @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)")
  1861. def test_serialize(self):
  1862. grammar = """
  1863. start: _ANY b "C"
  1864. _ANY: /./
  1865. b: "B"
  1866. """
  1867. parser = _Lark(grammar)
  1868. s = BytesIO()
  1869. parser.save(s)
  1870. s.seek(0)
  1871. parser2 = Lark.load(s)
  1872. self.assertEqual(parser2.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1873. def test_multi_start(self):
  1874. parser = _Lark('''
  1875. a: "x" "a"?
  1876. b: "x" "b"?
  1877. ''', start=['a', 'b'])
  1878. self.assertEqual(parser.parse('xa', 'a'), Tree('a', []))
  1879. self.assertEqual(parser.parse('xb', 'b'), Tree('b', []))
  1880. def test_lexer_detect_newline_tokens(self):
  1881. # Detect newlines in regular tokens
  1882. g = _Lark(r"""start: "go" tail*
  1883. !tail : SA "@" | SB "@" | SC "@" | SD "@"
  1884. SA : "a" /\n/
  1885. SB : /b./s
  1886. SC : "c" /[^a-z]/
  1887. SD : "d" /\s/
  1888. """)
  1889. a,b,c,d = [x.children[1] for x in g.parse('goa\n@b\n@c\n@d\n@').children]
  1890. self.assertEqual(a.line, 2)
  1891. self.assertEqual(b.line, 3)
  1892. self.assertEqual(c.line, 4)
  1893. self.assertEqual(d.line, 5)
  1894. # Detect newlines in ignored tokens
  1895. for re in ['/\\n/', '/[^a-z]/', '/\\s/']:
  1896. g = _Lark('''!start: "a" "a"
  1897. %ignore {}'''.format(re))
  1898. a, b = g.parse('a\na').children
  1899. self.assertEqual(a.line, 1)
  1900. self.assertEqual(b.line, 2)
  1901. @unittest.skipIf(PARSER=='cyk' or LEXER=='custom_old', "match_examples() not supported for CYK/old custom lexer")
  1902. def test_match_examples(self):
  1903. p = _Lark(r"""
  1904. start: "a" "b" "c"
  1905. """)
  1906. def match_error(s):
  1907. try:
  1908. _ = p.parse(s)
  1909. except UnexpectedInput as u:
  1910. return u.match_examples(p.parse, {
  1911. 0: ['abe'],
  1912. 1: ['ab'],
  1913. 2: ['cbc', 'dbc'],
  1914. })
  1915. assert False
  1916. assert match_error("abe") == 0
  1917. assert match_error("ab") == 1
  1918. assert match_error("bbc") == 2
  1919. assert match_error("cbc") == 2
  1920. self.assertEqual( match_error("dbc"), 2 )
  1921. self.assertEqual( match_error("ebc"), 2 )
  1922. @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.')
  1923. def test_unicode_class(self):
  1924. "Tests that character classes from the `regex` module work correctly."
  1925. g = _Lark(r"""?start: NAME
  1926. NAME: ID_START ID_CONTINUE*
  1927. ID_START: /[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_]+/
  1928. ID_CONTINUE: ID_START | /[\p{Mn}\p{Mc}\p{Nd}\p{Pc}]+/""", regex=True)
  1929. self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்')
  1930. @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.')
  1931. def test_unicode_word(self):
  1932. "Tests that a persistent bug in the `re` module works when `regex` is enabled."
  1933. g = _Lark(r"""?start: NAME
  1934. NAME: /[\w]+/
  1935. """, regex=True)
  1936. self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்')
  1937. @unittest.skipIf(PARSER!='lalr', "Puppet error handling only works with LALR for now")
  1938. def test_error_with_puppet(self):
  1939. def ignore_errors(e):
  1940. if isinstance(e, UnexpectedCharacters):
  1941. # Skip bad character
  1942. return True
  1943. # Must be UnexpectedToken
  1944. if e.token.type == 'COMMA':
  1945. # Skip comma
  1946. return True
  1947. elif e.token.type == 'SIGNED_NUMBER':
  1948. # Try to feed a comma and retry the number
  1949. e.puppet.feed_token(Token('COMMA', ','))
  1950. e.puppet.feed_token(e.token)
  1951. return True
  1952. # Unhandled error. Will stop parse and raise exception
  1953. return False
  1954. g = _Lark(r'''
  1955. start: "[" num ("," num)* "]"
  1956. ?num: SIGNED_NUMBER
  1957. %import common.SIGNED_NUMBER
  1958. %ignore " "
  1959. ''')
  1960. s = "[0 1, 2,, 3,,, 4, 5 6 ]"
  1961. tree = g.parse(s, on_error=ignore_errors)
  1962. res = [int(x) for x in tree.children]
  1963. assert res == list(range(7))
  1964. s = "[0 1, 2,@, 3,,, 4, 5 6 ]$"
  1965. tree = g.parse(s, on_error=ignore_errors)
  1966. _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize()
  1967. _TestParser.__name__ = _NAME
  1968. _TestParser.__qualname__ = "tests.test_parser." + _NAME
  1969. globals()[_NAME] = _TestParser
  1970. __all__.append(_NAME)
  1971. _TO_TEST = [
  1972. ('standard', 'earley'),
  1973. ('standard', 'cyk'),
  1974. ('standard', 'lalr'),
  1975. ('dynamic', 'earley'),
  1976. ('dynamic_complete', 'earley'),
  1977. ('contextual', 'lalr'),
  1978. ('custom_new', 'lalr'),
  1979. ('custom_new', 'cyk'),
  1980. ('custom_old', '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()