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.

1608 lines
54 KiB

  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import
  3. import unittest
  4. import logging
  5. import os
  6. import sys
  7. try:
  8. from cStringIO import StringIO as cStringIO
  9. except ImportError:
  10. # Available only in Python 2.x, 3.x only has io.StringIO from below
  11. cStringIO = None
  12. from io import (
  13. StringIO as uStringIO,
  14. open,
  15. )
  16. logging.basicConfig(level=logging.INFO)
  17. from lark.lark import Lark
  18. from lark.exceptions import GrammarError, ParseError, UnexpectedToken, UnexpectedInput, UnexpectedCharacters
  19. from lark.tree import Tree
  20. from lark.visitors import Transformer, Transformer_InPlace, v_args
  21. from lark.grammar import Rule
  22. from lark.lexer import TerminalDef
  23. __path__ = os.path.dirname(__file__)
  24. def _read(n, *args):
  25. with open(os.path.join(__path__, n), *args) as f:
  26. return f.read()
  27. class TestParsers(unittest.TestCase):
  28. def test_same_ast(self):
  29. "Tests that Earley and LALR parsers produce equal trees"
  30. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  31. name_list: NAME | name_list "," NAME
  32. NAME: /\w+/ """, parser='lalr')
  33. l = g.parse('(a,b,c,*x)')
  34. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  35. name_list: NAME | name_list "," NAME
  36. NAME: /\w/+ """)
  37. l2 = g.parse('(a,b,c,*x)')
  38. assert l == l2, '%s != %s' % (l.pretty(), l2.pretty())
  39. def test_infinite_recurse(self):
  40. g = """start: a
  41. a: a | "a"
  42. """
  43. self.assertRaises(GrammarError, Lark, g, parser='lalr')
  44. # TODO: should it? shouldn't it?
  45. # l = Lark(g, parser='earley', lexer='dynamic')
  46. # self.assertRaises(ParseError, l.parse, 'a')
  47. def test_propagate_positions(self):
  48. g = Lark("""start: a
  49. a: "a"
  50. """, propagate_positions=True)
  51. r = g.parse('a')
  52. self.assertEqual( r.children[0].meta.line, 1 )
  53. def test_expand1(self):
  54. g = Lark("""start: a
  55. ?a: b
  56. b: "x"
  57. """)
  58. r = g.parse('x')
  59. self.assertEqual( r.children[0].data, "b" )
  60. g = Lark("""start: a
  61. ?a: b -> c
  62. b: "x"
  63. """)
  64. r = g.parse('x')
  65. self.assertEqual( r.children[0].data, "c" )
  66. g = Lark("""start: a
  67. ?a: B -> c
  68. B: "x"
  69. """)
  70. self.assertEqual( r.children[0].data, "c" )
  71. g = Lark("""start: a
  72. ?a: b b -> c
  73. b: "x"
  74. """)
  75. r = g.parse('xx')
  76. self.assertEqual( r.children[0].data, "c" )
  77. def test_embedded_transformer(self):
  78. class T(Transformer):
  79. def a(self, children):
  80. return "<a>"
  81. def b(self, children):
  82. return "<b>"
  83. def c(self, children):
  84. return "<c>"
  85. # Test regular
  86. g = Lark("""start: a
  87. a : "x"
  88. """, parser='lalr')
  89. r = T().transform(g.parse("x"))
  90. self.assertEqual( r.children, ["<a>"] )
  91. g = Lark("""start: a
  92. a : "x"
  93. """, parser='lalr', transformer=T())
  94. r = g.parse("x")
  95. self.assertEqual( r.children, ["<a>"] )
  96. # Test Expand1
  97. g = Lark("""start: a
  98. ?a : b
  99. b : "x"
  100. """, parser='lalr')
  101. r = T().transform(g.parse("x"))
  102. self.assertEqual( r.children, ["<b>"] )
  103. g = Lark("""start: a
  104. ?a : b
  105. b : "x"
  106. """, parser='lalr', transformer=T())
  107. r = g.parse("x")
  108. self.assertEqual( r.children, ["<b>"] )
  109. # Test Expand1 -> Alias
  110. g = Lark("""start: a
  111. ?a : b b -> c
  112. b : "x"
  113. """, parser='lalr')
  114. r = T().transform(g.parse("xx"))
  115. self.assertEqual( r.children, ["<c>"] )
  116. g = Lark("""start: a
  117. ?a : b b -> c
  118. b : "x"
  119. """, parser='lalr', transformer=T())
  120. r = g.parse("xx")
  121. self.assertEqual( r.children, ["<c>"] )
  122. def test_embedded_transformer_inplace(self):
  123. @v_args(tree=True)
  124. class T1(Transformer_InPlace):
  125. def a(self, tree):
  126. assert isinstance(tree, Tree), tree
  127. tree.children.append("tested")
  128. return tree
  129. def b(self, tree):
  130. return Tree(tree.data, tree.children + ['tested2'])
  131. @v_args(tree=True)
  132. class T2(Transformer):
  133. def a(self, tree):
  134. assert isinstance(tree, Tree)
  135. tree.children.append("tested")
  136. return tree
  137. def b(self, tree):
  138. return Tree(tree.data, tree.children + ['tested2'])
  139. class T3(Transformer):
  140. @v_args(tree=True)
  141. def a(self, tree):
  142. assert isinstance(tree, Tree)
  143. tree.children.append("tested")
  144. return tree
  145. @v_args(tree=True)
  146. def b(self, tree):
  147. return Tree(tree.data, tree.children + ['tested2'])
  148. for t in [T1(), T2(), T3()]:
  149. for internal in [False, True]:
  150. g = Lark("""start: a b
  151. a : "x"
  152. b : "y"
  153. """, parser='lalr', transformer=t if internal else None)
  154. r = g.parse("xy")
  155. if not internal:
  156. r = t.transform(r)
  157. a, b = r.children
  158. self.assertEqual(a.children, ["tested"])
  159. self.assertEqual(b.children, ["tested2"])
  160. def test_alias(self):
  161. Lark("""start: ["a"] "b" ["c"] "e" ["f"] ["g"] ["h"] "x" -> d """)
  162. def _make_full_earley_test(LEXER):
  163. def _Lark(grammar, **kwargs):
  164. return Lark(grammar, lexer=LEXER, parser='earley', propagate_positions=True, **kwargs)
  165. class _TestFullEarley(unittest.TestCase):
  166. def test_anon(self):
  167. # Fails an Earley implementation without special handling for empty rules,
  168. # or re-processing of already completed rules.
  169. g = Lark(r"""start: B
  170. B: ("ab"|/[^b]/)+
  171. """, lexer=LEXER)
  172. self.assertEqual( g.parse('abc').children[0], 'abc')
  173. def test_earley(self):
  174. g = Lark("""start: A "b" c
  175. A: "a"+
  176. c: "abc"
  177. """, parser="earley", lexer=LEXER)
  178. x = g.parse('aaaababc')
  179. def test_earley2(self):
  180. grammar = """
  181. start: statement+
  182. statement: "r"
  183. | "c" /[a-z]/+
  184. %ignore " "
  185. """
  186. program = """c b r"""
  187. l = Lark(grammar, parser='earley', lexer=LEXER)
  188. l.parse(program)
  189. @unittest.skipIf(LEXER=='dynamic', "Only relevant for the dynamic_complete parser")
  190. def test_earley3(self):
  191. """Tests prioritization and disambiguation for pseudo-terminals (there should be only one result)
  192. By default, `+` should immitate regexp greedy-matching
  193. """
  194. grammar = """
  195. start: A A
  196. A: "a"+
  197. """
  198. l = Lark(grammar, parser='earley', lexer=LEXER)
  199. res = l.parse("aaa")
  200. self.assertEqual(set(res.children), {'aa', 'a'})
  201. # XXX TODO fix Earley to maintain correct order
  202. # i.e. terminals it imitate greedy search for terminals, but lazy search for rules
  203. # self.assertEqual(res.children, ['aa', 'a'])
  204. def test_earley4(self):
  205. grammar = """
  206. start: A A?
  207. A: "a"+
  208. """
  209. l = Lark(grammar, parser='earley', lexer=LEXER)
  210. res = l.parse("aaa")
  211. assert set(res.children) == {'aa', 'a'} or res.children == ['aaa']
  212. # XXX TODO fix Earley to maintain correct order
  213. # i.e. terminals it imitate greedy search for terminals, but lazy search for rules
  214. # self.assertEqual(res.children, ['aaa'])
  215. def test_earley_repeating_empty(self):
  216. # This was a sneaky bug!
  217. grammar = """
  218. !start: "a" empty empty "b"
  219. empty: empty2
  220. empty2:
  221. """
  222. parser = Lark(grammar, parser='earley', lexer=LEXER)
  223. res = parser.parse('ab')
  224. empty_tree = Tree('empty', [Tree('empty2', [])])
  225. self.assertSequenceEqual(res.children, ['a', empty_tree, empty_tree, 'b'])
  226. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  227. def test_earley_explicit_ambiguity(self):
  228. # This was a sneaky bug!
  229. grammar = """
  230. start: a b | ab
  231. a: "a"
  232. b: "b"
  233. ab: "ab"
  234. """
  235. parser = Lark(grammar, parser='earley', lexer=LEXER, ambiguity='explicit')
  236. ambig_tree = parser.parse('ab')
  237. self.assertEqual( ambig_tree.data, '_ambig')
  238. self.assertEqual( len(ambig_tree.children), 2)
  239. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  240. def test_ambiguity1(self):
  241. grammar = """
  242. start: cd+ "e"
  243. !cd: "c"
  244. | "d"
  245. | "cd"
  246. """
  247. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  248. ambig_tree = l.parse('cde')
  249. assert ambig_tree.data == '_ambig', ambig_tree
  250. assert len(ambig_tree.children) == 2
  251. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  252. def test_ambiguity2(self):
  253. grammar = """
  254. ANY: /[a-zA-Z0-9 ]+/
  255. a.2: "A" b+
  256. b.2: "B"
  257. c: ANY
  258. start: (a|c)*
  259. """
  260. l = Lark(grammar, parser='earley', lexer=LEXER)
  261. res = l.parse('ABX')
  262. expected = Tree('start', [
  263. Tree('a', [
  264. Tree('b', [])
  265. ]),
  266. Tree('c', [
  267. 'X'
  268. ])
  269. ])
  270. self.assertEqual(res, expected)
  271. def test_fruitflies_ambig(self):
  272. grammar = """
  273. start: noun verb noun -> simple
  274. | noun verb "like" noun -> comparative
  275. noun: adj? NOUN
  276. verb: VERB
  277. adj: ADJ
  278. NOUN: "flies" | "bananas" | "fruit"
  279. VERB: "like" | "flies"
  280. ADJ: "fruit"
  281. %import common.WS
  282. %ignore WS
  283. """
  284. parser = Lark(grammar, ambiguity='explicit', lexer=LEXER)
  285. tree = parser.parse('fruit flies like bananas')
  286. expected = Tree('_ambig', [
  287. Tree('comparative', [
  288. Tree('noun', ['fruit']),
  289. Tree('verb', ['flies']),
  290. Tree('noun', ['bananas'])
  291. ]),
  292. Tree('simple', [
  293. Tree('noun', [Tree('adj', ['fruit']), 'flies']),
  294. Tree('verb', ['like']),
  295. Tree('noun', ['bananas'])
  296. ])
  297. ])
  298. # self.assertEqual(tree, expected)
  299. self.assertEqual(tree.data, expected.data)
  300. self.assertEqual(set(tree.children), set(expected.children))
  301. @unittest.skipIf(LEXER!='dynamic_complete', "Only relevant for the dynamic_complete parser")
  302. def test_explicit_ambiguity2(self):
  303. grammar = r"""
  304. start: NAME+
  305. NAME: /\w+/
  306. %ignore " "
  307. """
  308. text = """cat"""
  309. parser = _Lark(grammar, start='start', ambiguity='explicit')
  310. tree = parser.parse(text)
  311. self.assertEqual(tree.data, '_ambig')
  312. combinations = {tuple(str(s) for s in t.children) for t in tree.children}
  313. self.assertEqual(combinations, {
  314. ('cat',),
  315. ('ca', 't'),
  316. ('c', 'at'),
  317. ('c', 'a' ,'t')
  318. })
  319. def test_term_ambig_resolve(self):
  320. grammar = r"""
  321. !start: NAME+
  322. NAME: /\w+/
  323. %ignore " "
  324. """
  325. text = """foo bar"""
  326. parser = Lark(grammar)
  327. tree = parser.parse(text)
  328. self.assertEqual(tree.children, ['foo', 'bar'])
  329. # @unittest.skipIf(LEXER=='dynamic', "Not implemented in Dynamic Earley yet") # TODO
  330. # def test_not_all_derivations(self):
  331. # grammar = """
  332. # start: cd+ "e"
  333. # !cd: "c"
  334. # | "d"
  335. # | "cd"
  336. # """
  337. # l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER, earley__all_derivations=False)
  338. # x = l.parse('cde')
  339. # assert x.data != '_ambig', x
  340. # assert len(x.children) == 1
  341. _NAME = "TestFullEarley" + LEXER.capitalize()
  342. _TestFullEarley.__name__ = _NAME
  343. globals()[_NAME] = _TestFullEarley
  344. def _make_parser_test(LEXER, PARSER):
  345. def _Lark(grammar, **kwargs):
  346. return Lark(grammar, lexer=LEXER, parser=PARSER, propagate_positions=True, **kwargs)
  347. def _Lark_open(gfilename, **kwargs):
  348. return Lark.open(gfilename, lexer=LEXER, parser=PARSER, propagate_positions=True, **kwargs)
  349. class _TestParser(unittest.TestCase):
  350. def test_basic1(self):
  351. g = _Lark("""start: a+ b a* "b" a*
  352. b: "b"
  353. a: "a"
  354. """)
  355. r = g.parse('aaabaab')
  356. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  357. r = g.parse('aaabaaba')
  358. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  359. self.assertRaises(ParseError, g.parse, 'aaabaa')
  360. def test_basic2(self):
  361. # Multiple parsers and colliding tokens
  362. g = _Lark("""start: B A
  363. B: "12"
  364. A: "1" """)
  365. g2 = _Lark("""start: B A
  366. B: "12"
  367. A: "2" """)
  368. x = g.parse('121')
  369. assert x.data == 'start' and x.children == ['12', '1'], x
  370. x = g2.parse('122')
  371. assert x.data == 'start' and x.children == ['12', '2'], x
  372. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  373. def test_stringio_bytes(self):
  374. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  375. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  376. def test_stringio_unicode(self):
  377. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  378. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  379. def test_unicode(self):
  380. g = _Lark(u"""start: UNIA UNIB UNIA
  381. UNIA: /\xa3/
  382. UNIB: /\u0101/
  383. """)
  384. g.parse(u'\xa3\u0101\u00a3')
  385. def test_unicode2(self):
  386. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  387. UNIA: /\xa3/
  388. UNIB: "a\u0101b\ "
  389. UNIC: /a?\u0101c\n/
  390. """)
  391. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  392. def test_unicode3(self):
  393. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  394. UNIA: /\xa3/
  395. UNIB: "\u0101"
  396. UNIC: /\u0203/ /\n/
  397. """)
  398. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  399. def test_hex_escape(self):
  400. g = _Lark(r"""start: A B C
  401. A: "\x01"
  402. B: /\x02/
  403. C: "\xABCD"
  404. """)
  405. g.parse('\x01\x02\xABCD')
  406. def test_unicode_literal_range_escape(self):
  407. g = _Lark(r"""start: A+
  408. A: "\u0061".."\u0063"
  409. """)
  410. g.parse('abc')
  411. def test_hex_literal_range_escape(self):
  412. g = _Lark(r"""start: A+
  413. A: "\x01".."\x03"
  414. """)
  415. g.parse('\x01\x02\x03')
  416. @unittest.skipIf(PARSER == 'cyk', "Takes forever")
  417. def test_stack_for_ebnf(self):
  418. """Verify that stack depth isn't an issue for EBNF grammars"""
  419. g = _Lark(r"""start: a+
  420. a : "a" """)
  421. g.parse("a" * (sys.getrecursionlimit()*2 ))
  422. def test_expand1_lists_with_one_item(self):
  423. g = _Lark(r"""start: list
  424. ?list: item+
  425. item : A
  426. A: "a"
  427. """)
  428. r = g.parse("a")
  429. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  430. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  431. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  432. self.assertEqual(len(r.children), 1)
  433. def test_expand1_lists_with_one_item_2(self):
  434. g = _Lark(r"""start: list
  435. ?list: item+ "!"
  436. item : A
  437. A: "a"
  438. """)
  439. r = g.parse("a!")
  440. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  441. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  442. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  443. self.assertEqual(len(r.children), 1)
  444. def test_dont_expand1_lists_with_multiple_items(self):
  445. g = _Lark(r"""start: list
  446. ?list: item+
  447. item : A
  448. A: "a"
  449. """)
  450. r = g.parse("aa")
  451. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  452. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  453. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  454. self.assertEqual(len(r.children), 1)
  455. # Sanity check: verify that 'list' contains the two 'item's we've given it
  456. [list] = r.children
  457. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  458. def test_dont_expand1_lists_with_multiple_items_2(self):
  459. g = _Lark(r"""start: list
  460. ?list: item+ "!"
  461. item : A
  462. A: "a"
  463. """)
  464. r = g.parse("aa!")
  465. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  466. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  467. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  468. self.assertEqual(len(r.children), 1)
  469. # Sanity check: verify that 'list' contains the two 'item's we've given it
  470. [list] = r.children
  471. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  472. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  473. def test_empty_expand1_list(self):
  474. g = _Lark(r"""start: list
  475. ?list: item*
  476. item : A
  477. A: "a"
  478. """)
  479. r = g.parse("")
  480. # 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
  481. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  482. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  483. self.assertEqual(len(r.children), 1)
  484. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  485. [list] = r.children
  486. self.assertSequenceEqual([item.data for item in list.children], ())
  487. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  488. def test_empty_expand1_list_2(self):
  489. g = _Lark(r"""start: list
  490. ?list: item* "!"?
  491. item : A
  492. A: "a"
  493. """)
  494. r = g.parse("")
  495. # 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
  496. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  497. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  498. self.assertEqual(len(r.children), 1)
  499. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  500. [list] = r.children
  501. self.assertSequenceEqual([item.data for item in list.children], ())
  502. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  503. def test_empty_flatten_list(self):
  504. g = _Lark(r"""start: list
  505. list: | item "," list
  506. item : A
  507. A: "a"
  508. """)
  509. r = g.parse("")
  510. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  511. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  512. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  513. [list] = r.children
  514. self.assertSequenceEqual([item.data for item in list.children], ())
  515. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  516. def test_single_item_flatten_list(self):
  517. g = _Lark(r"""start: list
  518. list: | item "," list
  519. item : A
  520. A: "a"
  521. """)
  522. r = g.parse("a,")
  523. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  524. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  525. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  526. [list] = r.children
  527. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  528. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  529. def test_multiple_item_flatten_list(self):
  530. g = _Lark(r"""start: list
  531. #list: | item "," list
  532. item : A
  533. A: "a"
  534. """)
  535. r = g.parse("a,a,")
  536. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  537. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  538. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  539. [list] = r.children
  540. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  541. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  542. def test_recurse_flatten(self):
  543. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  544. g = _Lark(r"""start: a | start a
  545. a : A
  546. A : "a" """)
  547. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  548. # STree data structures, which uses recursion).
  549. g.parse("a" * (sys.getrecursionlimit() // 4))
  550. def test_token_collision(self):
  551. g = _Lark(r"""start: "Hello" NAME
  552. NAME: /\w/+
  553. %ignore " "
  554. """)
  555. x = g.parse('Hello World')
  556. self.assertSequenceEqual(x.children, ['World'])
  557. x = g.parse('Hello HelloWorld')
  558. self.assertSequenceEqual(x.children, ['HelloWorld'])
  559. def test_token_collision_WS(self):
  560. g = _Lark(r"""start: "Hello" NAME
  561. NAME: /\w/+
  562. %import common.WS
  563. %ignore WS
  564. """)
  565. x = g.parse('Hello World')
  566. self.assertSequenceEqual(x.children, ['World'])
  567. x = g.parse('Hello HelloWorld')
  568. self.assertSequenceEqual(x.children, ['HelloWorld'])
  569. def test_token_collision2(self):
  570. g = _Lark("""
  571. !start: "starts"
  572. %import common.LCASE_LETTER
  573. """)
  574. x = g.parse("starts")
  575. self.assertSequenceEqual(x.children, ['starts'])
  576. # def test_string_priority(self):
  577. # g = _Lark("""start: (A | /a?bb/)+
  578. # A: "a" """)
  579. # x = g.parse('abb')
  580. # self.assertEqual(len(x.children), 2)
  581. # # This parse raises an exception because the lexer will always try to consume
  582. # # "a" first and will never match the regular expression
  583. # # This behavior is subject to change!!
  584. # # Thie won't happen with ambiguity handling.
  585. # g = _Lark("""start: (A | /a?ab/)+
  586. # A: "a" """)
  587. # self.assertRaises(LexError, g.parse, 'aab')
  588. def test_undefined_rule(self):
  589. self.assertRaises(GrammarError, _Lark, """start: a""")
  590. def test_undefined_token(self):
  591. self.assertRaises(GrammarError, _Lark, """start: A""")
  592. def test_rule_collision(self):
  593. g = _Lark("""start: "a"+ "b"
  594. | "a"+ """)
  595. x = g.parse('aaaa')
  596. x = g.parse('aaaab')
  597. def test_rule_collision2(self):
  598. g = _Lark("""start: "a"* "b"
  599. | "a"+ """)
  600. x = g.parse('aaaa')
  601. x = g.parse('aaaab')
  602. x = g.parse('b')
  603. def test_token_not_anon(self):
  604. """Tests that "a" is matched as an anonymous token, and not A.
  605. """
  606. g = _Lark("""start: "a"
  607. A: "a" """)
  608. x = g.parse('a')
  609. self.assertEqual(len(x.children), 0, '"a" should be considered anonymous')
  610. g = _Lark("""start: "a" A
  611. A: "a" """)
  612. x = g.parse('aa')
  613. self.assertEqual(len(x.children), 1, 'only "a" should be considered anonymous')
  614. self.assertEqual(x.children[0].type, "A")
  615. g = _Lark("""start: /a/
  616. A: /a/ """)
  617. x = g.parse('a')
  618. self.assertEqual(len(x.children), 1)
  619. self.assertEqual(x.children[0].type, "A", "A isn't associated with /a/")
  620. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  621. def test_maybe(self):
  622. g = _Lark("""start: ["a"] """)
  623. x = g.parse('a')
  624. x = g.parse('')
  625. def test_start(self):
  626. g = _Lark("""a: "a" a? """, start='a')
  627. x = g.parse('a')
  628. x = g.parse('aa')
  629. x = g.parse('aaa')
  630. def test_alias(self):
  631. g = _Lark("""start: "a" -> b """)
  632. x = g.parse('a')
  633. self.assertEqual(x.data, "b")
  634. def test_token_ebnf(self):
  635. g = _Lark("""start: A
  636. A: "a"* ("b"? "c".."e")+
  637. """)
  638. x = g.parse('abcde')
  639. x = g.parse('dd')
  640. def test_backslash(self):
  641. g = _Lark(r"""start: "\\" "a"
  642. """)
  643. x = g.parse(r'\a')
  644. g = _Lark(r"""start: /\\/ /a/
  645. """)
  646. x = g.parse(r'\a')
  647. def test_backslash2(self):
  648. g = _Lark(r"""start: "\"" "-"
  649. """)
  650. x = g.parse('"-')
  651. g = _Lark(r"""start: /\// /-/
  652. """)
  653. x = g.parse('/-')
  654. def test_special_chars(self):
  655. g = _Lark(r"""start: "\n"
  656. """)
  657. x = g.parse('\n')
  658. g = _Lark(r"""start: /\n/
  659. """)
  660. x = g.parse('\n')
  661. # def test_token_recurse(self):
  662. # g = _Lark("""start: A
  663. # A: B
  664. # B: A
  665. # """)
  666. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  667. def test_empty(self):
  668. # Fails an Earley implementation without special handling for empty rules,
  669. # or re-processing of already completed rules.
  670. g = _Lark(r"""start: _empty a "B"
  671. a: _empty "A"
  672. _empty:
  673. """)
  674. x = g.parse('AB')
  675. def test_regex_quote(self):
  676. g = r"""
  677. start: SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING
  678. SINGLE_QUOTED_STRING : /'[^']*'/
  679. DOUBLE_QUOTED_STRING : /"[^"]*"/
  680. """
  681. g = _Lark(g)
  682. self.assertEqual( g.parse('"hello"').children, ['"hello"'])
  683. self.assertEqual( g.parse("'hello'").children, ["'hello'"])
  684. def test_lexer_token_limit(self):
  685. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  686. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  687. g = _Lark("""start: %s
  688. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  689. def test_float_without_lexer(self):
  690. expected_error = UnexpectedCharacters if LEXER.startswith('dynamic') else UnexpectedToken
  691. if PARSER == 'cyk':
  692. expected_error = ParseError
  693. g = _Lark("""start: ["+"|"-"] float
  694. float: digit* "." digit+ exp?
  695. | digit+ exp
  696. exp: ("e"|"E") ["+"|"-"] digit+
  697. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  698. """)
  699. g.parse("1.2")
  700. g.parse("-.2e9")
  701. g.parse("+2e-9")
  702. self.assertRaises( expected_error, g.parse, "+2e-9e")
  703. def test_keep_all_tokens(self):
  704. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  705. tree = l.parse('aaa')
  706. self.assertEqual(tree.children, ['a', 'a', 'a'])
  707. def test_token_flags(self):
  708. l = _Lark("""!start: "a"i+
  709. """
  710. )
  711. tree = l.parse('aA')
  712. self.assertEqual(tree.children, ['a', 'A'])
  713. l = _Lark("""!start: /a/i+
  714. """
  715. )
  716. tree = l.parse('aA')
  717. self.assertEqual(tree.children, ['a', 'A'])
  718. # g = """!start: "a"i "a"
  719. # """
  720. # self.assertRaises(GrammarError, _Lark, g)
  721. # g = """!start: /a/i /a/
  722. # """
  723. # self.assertRaises(GrammarError, _Lark, g)
  724. g = """start: NAME "," "a"
  725. NAME: /[a-z_]/i /[a-z0-9_]/i*
  726. """
  727. l = _Lark(g)
  728. tree = l.parse('ab,a')
  729. self.assertEqual(tree.children, ['ab'])
  730. tree = l.parse('AB,a')
  731. self.assertEqual(tree.children, ['AB'])
  732. def test_token_flags3(self):
  733. l = _Lark("""!start: ABC+
  734. ABC: "abc"i
  735. """
  736. )
  737. tree = l.parse('aBcAbC')
  738. self.assertEqual(tree.children, ['aBc', 'AbC'])
  739. def test_token_flags2(self):
  740. g = """!start: ("a"i | /a/ /b/?)+
  741. """
  742. l = _Lark(g)
  743. tree = l.parse('aA')
  744. self.assertEqual(tree.children, ['a', 'A'])
  745. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  746. def test_twice_empty(self):
  747. g = """!start: [["A"]]
  748. """
  749. l = _Lark(g)
  750. tree = l.parse('A')
  751. self.assertEqual(tree.children, ['A'])
  752. tree = l.parse('')
  753. self.assertEqual(tree.children, [])
  754. def test_undefined_ignore(self):
  755. g = """!start: "A"
  756. %ignore B
  757. """
  758. self.assertRaises( GrammarError, _Lark, g)
  759. def test_alias_in_terminal(self):
  760. g = """start: TERM
  761. TERM: "a" -> alias
  762. """
  763. self.assertRaises( GrammarError, _Lark, g)
  764. def test_line_and_column(self):
  765. g = r"""!start: "A" bc "D"
  766. !bc: "B\nC"
  767. """
  768. l = _Lark(g)
  769. a, bc, d = l.parse("AB\nCD").children
  770. self.assertEqual(a.line, 1)
  771. self.assertEqual(a.column, 1)
  772. bc ,= bc.children
  773. self.assertEqual(bc.line, 1)
  774. self.assertEqual(bc.column, 2)
  775. self.assertEqual(d.line, 2)
  776. self.assertEqual(d.column, 2)
  777. if LEXER != 'dynamic':
  778. self.assertEqual(a.end_line, 1)
  779. self.assertEqual(a.end_column, 2)
  780. self.assertEqual(bc.end_line, 2)
  781. self.assertEqual(bc.end_column, 2)
  782. self.assertEqual(d.end_line, 2)
  783. self.assertEqual(d.end_column, 3)
  784. def test_reduce_cycle(self):
  785. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  786. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  787. """
  788. l = _Lark("""
  789. term: A
  790. | term term
  791. A: "a"
  792. """, start='term')
  793. tree = l.parse("aa")
  794. self.assertEqual(len(tree.children), 2)
  795. @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority")
  796. def test_lexer_prioritization(self):
  797. "Tests effect of priority on result"
  798. grammar = """
  799. start: A B | AB
  800. A.2: "a"
  801. B: "b"
  802. AB: "ab"
  803. """
  804. l = _Lark(grammar)
  805. res = l.parse("ab")
  806. self.assertEqual(res.children, ['a', 'b'])
  807. self.assertNotEqual(res.children, ['ab'])
  808. grammar = """
  809. start: A B | AB
  810. A: "a"
  811. B: "b"
  812. AB.3: "ab"
  813. """
  814. l = _Lark(grammar)
  815. res = l.parse("ab")
  816. self.assertNotEqual(res.children, ['a', 'b'])
  817. self.assertEqual(res.children, ['ab'])
  818. grammar = """
  819. start: A B | AB
  820. A: "a"
  821. B.-20: "b"
  822. AB.-10: "ab"
  823. """
  824. l = _Lark(grammar)
  825. res = l.parse("ab")
  826. self.assertEqual(res.children, ['a', 'b'])
  827. grammar = """
  828. start: A B | AB
  829. A.-99999999999999999999999: "a"
  830. B: "b"
  831. AB: "ab"
  832. """
  833. l = _Lark(grammar)
  834. res = l.parse("ab")
  835. self.assertEqual(res.children, ['ab'])
  836. def test_import(self):
  837. grammar = """
  838. start: NUMBER WORD
  839. %import common.NUMBER
  840. %import common.WORD
  841. %import common.WS
  842. %ignore WS
  843. """
  844. l = _Lark(grammar)
  845. x = l.parse('12 elephants')
  846. self.assertEqual(x.children, ['12', 'elephants'])
  847. def test_import_rename(self):
  848. grammar = """
  849. start: N W
  850. %import common.NUMBER -> N
  851. %import common.WORD -> W
  852. %import common.WS
  853. %ignore WS
  854. """
  855. l = _Lark(grammar)
  856. x = l.parse('12 elephants')
  857. self.assertEqual(x.children, ['12', 'elephants'])
  858. def test_relative_import(self):
  859. l = _Lark_open('test_relative_import.lark', rel_to=__file__)
  860. x = l.parse('12 lions')
  861. self.assertEqual(x.children, ['12', 'lions'])
  862. def test_relative_import_rename(self):
  863. l = _Lark_open('test_relative_import_rename.lark', rel_to=__file__)
  864. x = l.parse('12 lions')
  865. self.assertEqual(x.children, ['12', 'lions'])
  866. def test_relative_rule_import(self):
  867. l = _Lark_open('test_relative_rule_import.lark', rel_to=__file__)
  868. x = l.parse('xaabby')
  869. self.assertEqual(x.children, [
  870. 'x',
  871. Tree('expr', ['a', Tree('expr', ['a', 'b']), 'b']),
  872. 'y'])
  873. def test_relative_rule_import_drop_ignore(self):
  874. # %ignore rules are dropped on import
  875. l = _Lark_open('test_relative_rule_import_drop_ignore.lark',
  876. rel_to=__file__)
  877. self.assertRaises((ParseError, UnexpectedInput),
  878. l.parse, 'xa abby')
  879. def test_relative_rule_import_subrule(self):
  880. l = _Lark_open('test_relative_rule_import_subrule.lark',
  881. rel_to=__file__)
  882. x = l.parse('xaabby')
  883. self.assertEqual(x.children, [
  884. 'x',
  885. Tree('startab', [
  886. Tree('grammars__ab__expr', [
  887. 'a', Tree('grammars__ab__expr', ['a', 'b']), 'b',
  888. ]),
  889. ]),
  890. 'y'])
  891. def test_relative_rule_import_subrule_no_conflict(self):
  892. l = _Lark_open(
  893. 'test_relative_rule_import_subrule_no_conflict.lark',
  894. rel_to=__file__)
  895. x = l.parse('xaby')
  896. self.assertEqual(x.children, [Tree('expr', [
  897. 'x',
  898. Tree('startab', [
  899. Tree('grammars__ab__expr', ['a', 'b']),
  900. ]),
  901. 'y'])])
  902. self.assertRaises((ParseError, UnexpectedInput),
  903. l.parse, 'xaxabyby')
  904. def test_relative_rule_import_rename(self):
  905. l = _Lark_open('test_relative_rule_import_rename.lark',
  906. rel_to=__file__)
  907. x = l.parse('xaabby')
  908. self.assertEqual(x.children, [
  909. 'x',
  910. Tree('ab', ['a', Tree('ab', ['a', 'b']), 'b']),
  911. 'y'])
  912. def test_multi_import(self):
  913. grammar = """
  914. start: NUMBER WORD
  915. %import common (NUMBER, WORD, WS)
  916. %ignore WS
  917. """
  918. l = _Lark(grammar)
  919. x = l.parse('12 toucans')
  920. self.assertEqual(x.children, ['12', 'toucans'])
  921. def test_relative_multi_import(self):
  922. l = _Lark_open("test_relative_multi_import.lark", rel_to=__file__)
  923. x = l.parse('12 capybaras')
  924. self.assertEqual(x.children, ['12', 'capybaras'])
  925. def test_relative_import_preserves_leading_underscore(self):
  926. l = _Lark_open("test_relative_import_preserves_leading_underscore.lark", rel_to=__file__)
  927. x = l.parse('Ax')
  928. self.assertEqual(next(x.find_data('c')).children, ['A'])
  929. def test_relative_import_of_nested_grammar(self):
  930. l = _Lark_open("grammars/test_relative_import_of_nested_grammar.lark", rel_to=__file__)
  931. x = l.parse('N')
  932. self.assertEqual(next(x.find_data('rule_to_import')).children, ['N'])
  933. def test_relative_import_rules_dependencies_imported_only_once(self):
  934. l = _Lark_open("test_relative_import_rules_dependencies_imported_only_once.lark", rel_to=__file__)
  935. x = l.parse('AAA')
  936. self.assertEqual(next(x.find_data('a')).children, ['A'])
  937. self.assertEqual(next(x.find_data('b')).children, ['A'])
  938. self.assertEqual(next(x.find_data('d')).children, ['A'])
  939. def test_import_errors(self):
  940. grammar = """
  941. start: NUMBER WORD
  942. %import .grammars.bad_test.NUMBER
  943. """
  944. self.assertRaises(IOError, _Lark, grammar)
  945. grammar = """
  946. start: NUMBER WORD
  947. %import bad_test.NUMBER
  948. """
  949. self.assertRaises(IOError, _Lark, grammar)
  950. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  951. def test_earley_prioritization(self):
  952. "Tests effect of priority on result"
  953. grammar = """
  954. start: a | b
  955. a.1: "a"
  956. b.2: "a"
  957. """
  958. # l = Lark(grammar, parser='earley', lexer='standard')
  959. l = _Lark(grammar)
  960. res = l.parse("a")
  961. self.assertEqual(res.children[0].data, 'b')
  962. grammar = """
  963. start: a | b
  964. a.2: "a"
  965. b.1: "a"
  966. """
  967. l = _Lark(grammar)
  968. # l = Lark(grammar, parser='earley', lexer='standard')
  969. res = l.parse("a")
  970. self.assertEqual(res.children[0].data, 'a')
  971. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  972. def test_earley_prioritization_sum(self):
  973. "Tests effect of priority on result"
  974. grammar = """
  975. start: ab_ b_ a_ | indirection
  976. indirection: a_ bb_ a_
  977. a_: "a"
  978. b_: "b"
  979. ab_: "ab"
  980. bb_.1: "bb"
  981. """
  982. l = Lark(grammar, priority="invert")
  983. res = l.parse('abba')
  984. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  985. grammar = """
  986. start: ab_ b_ a_ | indirection
  987. indirection: a_ bb_ a_
  988. a_: "a"
  989. b_: "b"
  990. ab_.1: "ab"
  991. bb_: "bb"
  992. """
  993. l = Lark(grammar, priority="invert")
  994. res = l.parse('abba')
  995. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  996. grammar = """
  997. start: ab_ b_ a_ | indirection
  998. indirection: a_ bb_ a_
  999. a_.2: "a"
  1000. b_.1: "b"
  1001. ab_.3: "ab"
  1002. bb_.3: "bb"
  1003. """
  1004. l = Lark(grammar, priority="invert")
  1005. res = l.parse('abba')
  1006. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1007. grammar = """
  1008. start: ab_ b_ a_ | indirection
  1009. indirection: a_ bb_ a_
  1010. a_.1: "a"
  1011. b_.1: "b"
  1012. ab_.4: "ab"
  1013. bb_.3: "bb"
  1014. """
  1015. l = Lark(grammar, priority="invert")
  1016. res = l.parse('abba')
  1017. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1018. def test_utf8(self):
  1019. g = u"""start: a
  1020. a: "±a"
  1021. """
  1022. l = _Lark(g)
  1023. self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])]))
  1024. g = u"""start: A
  1025. A: "±a"
  1026. """
  1027. l = _Lark(g)
  1028. self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a']))
  1029. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1030. def test_ignore(self):
  1031. grammar = r"""
  1032. COMMENT: /(!|(\/\/))[^\n]*/
  1033. %ignore COMMENT
  1034. %import common.WS -> _WS
  1035. %import common.INT
  1036. start: "INT"i _WS+ INT _WS*
  1037. """
  1038. parser = _Lark(grammar)
  1039. tree = parser.parse("int 1 ! This is a comment\n")
  1040. self.assertEqual(tree.children, ['1'])
  1041. tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky!
  1042. self.assertEqual(tree.children, ['1'])
  1043. parser = _Lark(r"""
  1044. start : "a"*
  1045. %ignore "b"
  1046. """)
  1047. tree = parser.parse("bb")
  1048. self.assertEqual(tree.children, [])
  1049. def test_regex_escaping(self):
  1050. g = _Lark("start: /[ab]/")
  1051. g.parse('a')
  1052. g.parse('b')
  1053. self.assertRaises( UnexpectedInput, g.parse, 'c')
  1054. _Lark(r'start: /\w/').parse('a')
  1055. g = _Lark(r'start: /\\w/')
  1056. self.assertRaises( UnexpectedInput, g.parse, 'a')
  1057. g.parse(r'\w')
  1058. _Lark(r'start: /\[/').parse('[')
  1059. _Lark(r'start: /\//').parse('/')
  1060. _Lark(r'start: /\\/').parse('\\')
  1061. _Lark(r'start: /\[ab]/').parse('[ab]')
  1062. _Lark(r'start: /\\[ab]/').parse('\\a')
  1063. _Lark(r'start: /\t/').parse('\t')
  1064. _Lark(r'start: /\\t/').parse('\\t')
  1065. _Lark(r'start: /\\\t/').parse('\\\t')
  1066. _Lark(r'start: "\t"').parse('\t')
  1067. _Lark(r'start: "\\t"').parse('\\t')
  1068. _Lark(r'start: "\\\t"').parse('\\\t')
  1069. def test_ranged_repeat_rules(self):
  1070. g = u"""!start: "A"~3
  1071. """
  1072. l = _Lark(g)
  1073. self.assertEqual(l.parse(u'AAA'), Tree('start', ["A", "A", "A"]))
  1074. self.assertRaises(ParseError, l.parse, u'AA')
  1075. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1076. g = u"""!start: "A"~0..2
  1077. """
  1078. if PARSER != 'cyk': # XXX CYK currently doesn't support empty grammars
  1079. l = _Lark(g)
  1080. self.assertEqual(l.parse(u''), Tree('start', []))
  1081. self.assertEqual(l.parse(u'A'), Tree('start', ['A']))
  1082. self.assertEqual(l.parse(u'AA'), Tree('start', ['A', 'A']))
  1083. self.assertRaises((UnexpectedToken, UnexpectedInput), l.parse, u'AAA')
  1084. g = u"""!start: "A"~3..2
  1085. """
  1086. self.assertRaises(GrammarError, _Lark, g)
  1087. g = u"""!start: "A"~2..3 "B"~2
  1088. """
  1089. l = _Lark(g)
  1090. self.assertEqual(l.parse(u'AABB'), Tree('start', ['A', 'A', 'B', 'B']))
  1091. self.assertEqual(l.parse(u'AAABB'), Tree('start', ['A', 'A', 'A', 'B', 'B']))
  1092. self.assertRaises(ParseError, l.parse, u'AAAB')
  1093. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1094. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1095. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1096. def test_ranged_repeat_terms(self):
  1097. g = u"""!start: AAA
  1098. AAA: "A"~3
  1099. """
  1100. l = _Lark(g)
  1101. self.assertEqual(l.parse(u'AAA'), Tree('start', ["AAA"]))
  1102. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AA')
  1103. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1104. g = u"""!start: AABB CC
  1105. AABB: "A"~0..2 "B"~2
  1106. CC: "C"~1..2
  1107. """
  1108. l = _Lark(g)
  1109. self.assertEqual(l.parse(u'AABBCC'), Tree('start', ['AABB', 'CC']))
  1110. self.assertEqual(l.parse(u'BBC'), Tree('start', ['BB', 'C']))
  1111. self.assertEqual(l.parse(u'ABBCC'), Tree('start', ['ABB', 'CC']))
  1112. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAB')
  1113. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1114. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1115. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1116. @unittest.skipIf(PARSER=='earley', "Priority not handled correctly right now") # TODO XXX
  1117. def test_priority_vs_embedded(self):
  1118. g = """
  1119. A.2: "a"
  1120. WORD: ("a".."z")+
  1121. start: (A | WORD)+
  1122. """
  1123. l = _Lark(g)
  1124. t = l.parse('abc')
  1125. self.assertEqual(t.children, ['a', 'bc'])
  1126. self.assertEqual(t.children[0].type, 'A')
  1127. def test_line_counting(self):
  1128. p = _Lark("start: /[^x]+/")
  1129. text = 'hello\nworld'
  1130. t = p.parse(text)
  1131. tok = t.children[0]
  1132. self.assertEqual(tok, text)
  1133. self.assertEqual(tok.line, 1)
  1134. self.assertEqual(tok.column, 1)
  1135. if _LEXER != 'dynamic':
  1136. self.assertEqual(tok.end_line, 2)
  1137. self.assertEqual(tok.end_column, 6)
  1138. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1139. def test_empty_end(self):
  1140. p = _Lark("""
  1141. start: b c d
  1142. b: "B"
  1143. c: | "C"
  1144. d: | "D"
  1145. """)
  1146. res = p.parse('B')
  1147. self.assertEqual(len(res.children), 3)
  1148. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1149. def test_maybe_placeholders(self):
  1150. # Anonymous tokens shouldn't count
  1151. p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1152. self.assertEqual(p.parse("").children, [])
  1153. # All invisible constructs shouldn't count
  1154. p = _Lark("""start: [A] ["b"] [_c] ["e" "f" _c]
  1155. A: "a"
  1156. _c: "c" """, maybe_placeholders=True)
  1157. self.assertEqual(p.parse("").children, [None])
  1158. self.assertEqual(p.parse("c").children, [None])
  1159. self.assertEqual(p.parse("aefc").children, ['a'])
  1160. # ? shouldn't apply
  1161. p = _Lark("""!start: ["a"] "b"? ["c"] """, maybe_placeholders=True)
  1162. self.assertEqual(p.parse("").children, [None, None])
  1163. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1164. p = _Lark("""!start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1165. self.assertEqual(p.parse("").children, [None, None, None])
  1166. self.assertEqual(p.parse("a").children, ['a', None, None])
  1167. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1168. self.assertEqual(p.parse("c").children, [None, None, 'c'])
  1169. self.assertEqual(p.parse("ab").children, ['a', 'b', None])
  1170. self.assertEqual(p.parse("ac").children, ['a', None, 'c'])
  1171. self.assertEqual(p.parse("bc").children, [None, 'b', 'c'])
  1172. self.assertEqual(p.parse("abc").children, ['a', 'b', 'c'])
  1173. p = _Lark("""!start: (["a"] "b" ["c"])+ """, maybe_placeholders=True)
  1174. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1175. self.assertEqual(p.parse("bb").children, [None, 'b', None, None, 'b', None])
  1176. self.assertEqual(p.parse("abbc").children, ['a', 'b', None, None, 'b', 'c'])
  1177. self.assertEqual(p.parse("babbcabcb").children,
  1178. [None, 'b', None,
  1179. 'a', 'b', None,
  1180. None, 'b', 'c',
  1181. 'a', 'b', 'c',
  1182. None, 'b', None])
  1183. p = _Lark("""!start: ["a"] ["c"] "b"+ ["a"] ["d"] """, maybe_placeholders=True)
  1184. self.assertEqual(p.parse("bb").children, [None, None, 'b', 'b', None, None])
  1185. self.assertEqual(p.parse("bd").children, [None, None, 'b', None, 'd'])
  1186. self.assertEqual(p.parse("abba").children, ['a', None, 'b', 'b', 'a', None])
  1187. self.assertEqual(p.parse("cbbbb").children, [None, 'c', 'b', 'b', 'b', 'b', None, None])
  1188. def test_escaped_string(self):
  1189. "Tests common.ESCAPED_STRING"
  1190. grammar = r"""
  1191. start: ESCAPED_STRING+
  1192. %import common (WS_INLINE, ESCAPED_STRING)
  1193. %ignore WS_INLINE
  1194. """
  1195. parser = _Lark(grammar)
  1196. parser.parse(r'"\\" "b" "c"')
  1197. parser.parse(r'"That" "And a \"b"')
  1198. def test_meddling_unused(self):
  1199. "Unless 'unused' is removed, LALR analysis will fail on reduce-reduce collision"
  1200. grammar = """
  1201. start: EKS* x
  1202. x: EKS
  1203. unused: x*
  1204. EKS: "x"
  1205. """
  1206. parser = _Lark(grammar)
  1207. @unittest.skipIf(PARSER!='lalr', "Serialize currently only works for LALR parsers (though it should be easy to extend)")
  1208. def test_serialize(self):
  1209. grammar = """
  1210. start: _ANY b "C"
  1211. _ANY: /./
  1212. b: "B"
  1213. """
  1214. parser = _Lark(grammar)
  1215. d = parser.serialize()
  1216. parser2 = Lark.deserialize(d, {}, {})
  1217. self.assertEqual(parser2.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1218. namespace = {'Rule': Rule, 'TerminalDef': TerminalDef}
  1219. d, m = parser.memo_serialize(namespace.values())
  1220. parser3 = Lark.deserialize(d, namespace, m)
  1221. self.assertEqual(parser3.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1222. def test_multi_start(self):
  1223. parser = _Lark('''
  1224. a: "x" "a"?
  1225. b: "x" "b"?
  1226. ''', start=['a', 'b'])
  1227. self.assertEqual(parser.parse('xa', 'a'), Tree('a', []))
  1228. self.assertEqual(parser.parse('xb', 'b'), Tree('b', []))
  1229. def test_lexer_detect_newline_tokens(self):
  1230. # Detect newlines in regular tokens
  1231. g = _Lark(r"""start: "go" tail*
  1232. !tail : SA "@" | SB "@" | SC "@" | SD "@"
  1233. SA : "a" /\n/
  1234. SB : /b./s
  1235. SC : "c" /[^a-z]/
  1236. SD : "d" /\s/
  1237. """)
  1238. a,b,c,d = [x.children[1] for x in g.parse('goa\n@b\n@c\n@d\n@').children]
  1239. self.assertEqual(a.line, 2)
  1240. self.assertEqual(b.line, 3)
  1241. self.assertEqual(c.line, 4)
  1242. self.assertEqual(d.line, 5)
  1243. # Detect newlines in ignored tokens
  1244. for re in ['/\\n/', '/[^a-z]/', '/\\s/']:
  1245. g = _Lark('''!start: "a" "a"
  1246. %ignore {}'''.format(re))
  1247. a, b = g.parse('a\na').children
  1248. self.assertEqual(a.line, 1)
  1249. self.assertEqual(b.line, 2)
  1250. _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize()
  1251. _TestParser.__name__ = _NAME
  1252. globals()[_NAME] = _TestParser
  1253. # Note: You still have to import them in __main__ for the tests to run
  1254. _TO_TEST = [
  1255. ('standard', 'earley'),
  1256. ('standard', 'cyk'),
  1257. ('dynamic', 'earley'),
  1258. ('dynamic_complete', 'earley'),
  1259. ('standard', 'lalr'),
  1260. ('contextual', 'lalr'),
  1261. # (None, 'earley'),
  1262. ]
  1263. for _LEXER, _PARSER in _TO_TEST:
  1264. _make_parser_test(_LEXER, _PARSER)
  1265. for _LEXER in ('dynamic', 'dynamic_complete'):
  1266. _make_full_earley_test(_LEXER)
  1267. if __name__ == '__main__':
  1268. unittest.main()