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.

2449 lines
83 KiB

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