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.

2472 lines
84 KiB

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