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.

2202 lines
76 KiB

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