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.

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