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.
 
 

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