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.

1372 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. def test_hex_escape(self):
  358. g = _Lark(r"""start: A B
  359. A: "\x01"
  360. B: /\x02/
  361. """)
  362. g.parse('\x01\x02')
  363. @unittest.skipIf(PARSER == 'cyk', "Takes forever")
  364. def test_stack_for_ebnf(self):
  365. """Verify that stack depth isn't an issue for EBNF grammars"""
  366. g = _Lark(r"""start: a+
  367. a : "a" """)
  368. g.parse("a" * (sys.getrecursionlimit()*2 ))
  369. def test_expand1_lists_with_one_item(self):
  370. g = _Lark(r"""start: list
  371. ?list: item+
  372. item : A
  373. A: "a"
  374. """)
  375. r = g.parse("a")
  376. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  377. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  378. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  379. self.assertEqual(len(r.children), 1)
  380. def test_expand1_lists_with_one_item_2(self):
  381. g = _Lark(r"""start: list
  382. ?list: item+ "!"
  383. item : A
  384. A: "a"
  385. """)
  386. r = g.parse("a!")
  387. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  388. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  389. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  390. self.assertEqual(len(r.children), 1)
  391. def test_dont_expand1_lists_with_multiple_items(self):
  392. g = _Lark(r"""start: list
  393. ?list: item+
  394. item : A
  395. A: "a"
  396. """)
  397. r = g.parse("aa")
  398. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  399. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  400. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  401. self.assertEqual(len(r.children), 1)
  402. # Sanity check: verify that 'list' contains the two 'item's we've given it
  403. [list] = r.children
  404. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  405. def test_dont_expand1_lists_with_multiple_items_2(self):
  406. g = _Lark(r"""start: list
  407. ?list: item+ "!"
  408. item : A
  409. A: "a"
  410. """)
  411. r = g.parse("aa!")
  412. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  413. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  414. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  415. self.assertEqual(len(r.children), 1)
  416. # Sanity check: verify that 'list' contains the two 'item's we've given it
  417. [list] = r.children
  418. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  419. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  420. def test_empty_expand1_list(self):
  421. g = _Lark(r"""start: list
  422. ?list: item*
  423. item : A
  424. A: "a"
  425. """)
  426. r = g.parse("")
  427. # 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
  428. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  429. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  430. self.assertEqual(len(r.children), 1)
  431. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  432. [list] = r.children
  433. self.assertSequenceEqual([item.data for item in list.children], ())
  434. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  435. def test_empty_expand1_list_2(self):
  436. g = _Lark(r"""start: list
  437. ?list: item* "!"?
  438. item : A
  439. A: "a"
  440. """)
  441. r = g.parse("")
  442. # 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
  443. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  444. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  445. self.assertEqual(len(r.children), 1)
  446. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  447. [list] = r.children
  448. self.assertSequenceEqual([item.data for item in list.children], ())
  449. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  450. def test_empty_flatten_list(self):
  451. g = _Lark(r"""start: list
  452. list: | item "," list
  453. item : A
  454. A: "a"
  455. """)
  456. r = g.parse("")
  457. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  458. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  459. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  460. [list] = r.children
  461. self.assertSequenceEqual([item.data for item in list.children], ())
  462. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  463. def test_single_item_flatten_list(self):
  464. g = _Lark(r"""start: list
  465. list: | item "," list
  466. item : A
  467. A: "a"
  468. """)
  469. r = g.parse("a,")
  470. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  471. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  472. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  473. [list] = r.children
  474. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  475. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  476. def test_multiple_item_flatten_list(self):
  477. g = _Lark(r"""start: list
  478. #list: | item "," list
  479. item : A
  480. A: "a"
  481. """)
  482. r = g.parse("a,a,")
  483. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  484. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  485. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  486. [list] = r.children
  487. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  488. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  489. def test_recurse_flatten(self):
  490. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  491. g = _Lark(r"""start: a | start a
  492. a : A
  493. A : "a" """)
  494. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  495. # STree data structures, which uses recursion).
  496. g.parse("a" * (sys.getrecursionlimit() // 4))
  497. def test_token_collision(self):
  498. g = _Lark(r"""start: "Hello" NAME
  499. NAME: /\w/+
  500. %ignore " "
  501. """)
  502. x = g.parse('Hello World')
  503. self.assertSequenceEqual(x.children, ['World'])
  504. x = g.parse('Hello HelloWorld')
  505. self.assertSequenceEqual(x.children, ['HelloWorld'])
  506. def test_token_collision_WS(self):
  507. g = _Lark(r"""start: "Hello" NAME
  508. NAME: /\w/+
  509. %import common.WS
  510. %ignore WS
  511. """)
  512. x = g.parse('Hello World')
  513. self.assertSequenceEqual(x.children, ['World'])
  514. x = g.parse('Hello HelloWorld')
  515. self.assertSequenceEqual(x.children, ['HelloWorld'])
  516. def test_token_collision2(self):
  517. g = _Lark("""
  518. !start: "starts"
  519. %import common.LCASE_LETTER
  520. """)
  521. x = g.parse("starts")
  522. self.assertSequenceEqual(x.children, ['starts'])
  523. # def test_string_priority(self):
  524. # g = _Lark("""start: (A | /a?bb/)+
  525. # A: "a" """)
  526. # x = g.parse('abb')
  527. # self.assertEqual(len(x.children), 2)
  528. # # This parse raises an exception because the lexer will always try to consume
  529. # # "a" first and will never match the regular expression
  530. # # This behavior is subject to change!!
  531. # # Thie won't happen with ambiguity handling.
  532. # g = _Lark("""start: (A | /a?ab/)+
  533. # A: "a" """)
  534. # self.assertRaises(LexError, g.parse, 'aab')
  535. def test_undefined_rule(self):
  536. self.assertRaises(GrammarError, _Lark, """start: a""")
  537. def test_undefined_token(self):
  538. self.assertRaises(GrammarError, _Lark, """start: A""")
  539. def test_rule_collision(self):
  540. g = _Lark("""start: "a"+ "b"
  541. | "a"+ """)
  542. x = g.parse('aaaa')
  543. x = g.parse('aaaab')
  544. def test_rule_collision2(self):
  545. g = _Lark("""start: "a"* "b"
  546. | "a"+ """)
  547. x = g.parse('aaaa')
  548. x = g.parse('aaaab')
  549. x = g.parse('b')
  550. def test_token_not_anon(self):
  551. """Tests that "a" is matched as an anonymous token, and not A.
  552. """
  553. g = _Lark("""start: "a"
  554. A: "a" """)
  555. x = g.parse('a')
  556. self.assertEqual(len(x.children), 0, '"a" should be considered anonymous')
  557. g = _Lark("""start: "a" A
  558. A: "a" """)
  559. x = g.parse('aa')
  560. self.assertEqual(len(x.children), 1, 'only "a" should be considered anonymous')
  561. self.assertEqual(x.children[0].type, "A")
  562. g = _Lark("""start: /a/
  563. A: /a/ """)
  564. x = g.parse('a')
  565. self.assertEqual(len(x.children), 1)
  566. self.assertEqual(x.children[0].type, "A", "A isn't associated with /a/")
  567. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  568. def test_maybe(self):
  569. g = _Lark("""start: ["a"] """)
  570. x = g.parse('a')
  571. x = g.parse('')
  572. def test_start(self):
  573. g = _Lark("""a: "a" a? """, start='a')
  574. x = g.parse('a')
  575. x = g.parse('aa')
  576. x = g.parse('aaa')
  577. def test_alias(self):
  578. g = _Lark("""start: "a" -> b """)
  579. x = g.parse('a')
  580. self.assertEqual(x.data, "b")
  581. def test_token_ebnf(self):
  582. g = _Lark("""start: A
  583. A: "a"* ("b"? "c".."e")+
  584. """)
  585. x = g.parse('abcde')
  586. x = g.parse('dd')
  587. def test_backslash(self):
  588. g = _Lark(r"""start: "\\" "a"
  589. """)
  590. x = g.parse(r'\a')
  591. g = _Lark(r"""start: /\\/ /a/
  592. """)
  593. x = g.parse(r'\a')
  594. def test_backslash2(self):
  595. g = _Lark(r"""start: "\"" "-"
  596. """)
  597. x = g.parse('"-')
  598. g = _Lark(r"""start: /\// /-/
  599. """)
  600. x = g.parse('/-')
  601. def test_special_chars(self):
  602. g = _Lark(r"""start: "\n"
  603. """)
  604. x = g.parse('\n')
  605. g = _Lark(r"""start: /\n/
  606. """)
  607. x = g.parse('\n')
  608. # def test_token_recurse(self):
  609. # g = _Lark("""start: A
  610. # A: B
  611. # B: A
  612. # """)
  613. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  614. def test_empty(self):
  615. # Fails an Earley implementation without special handling for empty rules,
  616. # or re-processing of already completed rules.
  617. g = _Lark(r"""start: _empty a "B"
  618. a: _empty "A"
  619. _empty:
  620. """)
  621. x = g.parse('AB')
  622. def test_regex_quote(self):
  623. g = r"""
  624. start: SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING
  625. SINGLE_QUOTED_STRING : /'[^']*'/
  626. DOUBLE_QUOTED_STRING : /"[^"]*"/
  627. """
  628. g = _Lark(g)
  629. self.assertEqual( g.parse('"hello"').children, ['"hello"'])
  630. self.assertEqual( g.parse("'hello'").children, ["'hello'"])
  631. def test_lexer_token_limit(self):
  632. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  633. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  634. g = _Lark("""start: %s
  635. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  636. def test_float_without_lexer(self):
  637. expected_error = UnexpectedInput if LEXER == 'dynamic' else UnexpectedToken
  638. if PARSER == 'cyk':
  639. expected_error = ParseError
  640. g = _Lark("""start: ["+"|"-"] float
  641. float: digit* "." digit+ exp?
  642. | digit+ exp
  643. exp: ("e"|"E") ["+"|"-"] digit+
  644. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  645. """)
  646. g.parse("1.2")
  647. g.parse("-.2e9")
  648. g.parse("+2e-9")
  649. self.assertRaises( expected_error, g.parse, "+2e-9e")
  650. def test_keep_all_tokens(self):
  651. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  652. tree = l.parse('aaa')
  653. self.assertEqual(tree.children, ['a', 'a', 'a'])
  654. def test_token_flags(self):
  655. l = _Lark("""!start: "a"i+
  656. """
  657. )
  658. tree = l.parse('aA')
  659. self.assertEqual(tree.children, ['a', 'A'])
  660. l = _Lark("""!start: /a/i+
  661. """
  662. )
  663. tree = l.parse('aA')
  664. self.assertEqual(tree.children, ['a', 'A'])
  665. # g = """!start: "a"i "a"
  666. # """
  667. # self.assertRaises(GrammarError, _Lark, g)
  668. # g = """!start: /a/i /a/
  669. # """
  670. # self.assertRaises(GrammarError, _Lark, g)
  671. g = """start: NAME "," "a"
  672. NAME: /[a-z_]/i /[a-z0-9_]/i*
  673. """
  674. l = _Lark(g)
  675. tree = l.parse('ab,a')
  676. self.assertEqual(tree.children, ['ab'])
  677. tree = l.parse('AB,a')
  678. self.assertEqual(tree.children, ['AB'])
  679. def test_token_flags3(self):
  680. l = _Lark("""!start: ABC+
  681. ABC: "abc"i
  682. """
  683. )
  684. tree = l.parse('aBcAbC')
  685. self.assertEqual(tree.children, ['aBc', 'AbC'])
  686. def test_token_flags2(self):
  687. g = """!start: ("a"i | /a/ /b/?)+
  688. """
  689. l = _Lark(g)
  690. tree = l.parse('aA')
  691. self.assertEqual(tree.children, ['a', 'A'])
  692. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  693. def test_twice_empty(self):
  694. g = """!start: [["A"]]
  695. """
  696. l = _Lark(g)
  697. tree = l.parse('A')
  698. self.assertEqual(tree.children, ['A'])
  699. tree = l.parse('')
  700. self.assertEqual(tree.children, [])
  701. def test_undefined_ignore(self):
  702. g = """!start: "A"
  703. %ignore B
  704. """
  705. self.assertRaises( GrammarError, _Lark, g)
  706. def test_alias_in_terminal(self):
  707. g = """start: TERM
  708. TERM: "a" -> alias
  709. """
  710. self.assertRaises( GrammarError, _Lark, g)
  711. def test_line_and_column(self):
  712. g = r"""!start: "A" bc "D"
  713. !bc: "B\nC"
  714. """
  715. l = _Lark(g)
  716. a, bc, d = l.parse("AB\nCD").children
  717. self.assertEqual(a.line, 1)
  718. self.assertEqual(a.column, 1)
  719. bc ,= bc.children
  720. self.assertEqual(bc.line, 1)
  721. self.assertEqual(bc.column, 2)
  722. self.assertEqual(d.line, 2)
  723. self.assertEqual(d.column, 2)
  724. if LEXER != 'dynamic':
  725. self.assertEqual(a.end_line, 1)
  726. self.assertEqual(a.end_column, 2)
  727. self.assertEqual(bc.end_line, 2)
  728. self.assertEqual(bc.end_column, 2)
  729. self.assertEqual(d.end_line, 2)
  730. self.assertEqual(d.end_column, 3)
  731. def test_reduce_cycle(self):
  732. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  733. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  734. """
  735. l = _Lark("""
  736. term: A
  737. | term term
  738. A: "a"
  739. """, start='term')
  740. tree = l.parse("aa")
  741. self.assertEqual(len(tree.children), 2)
  742. @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority")
  743. def test_lexer_prioritization(self):
  744. "Tests effect of priority on result"
  745. grammar = """
  746. start: A B | AB
  747. A.2: "a"
  748. B: "b"
  749. AB: "ab"
  750. """
  751. l = _Lark(grammar)
  752. res = l.parse("ab")
  753. self.assertEqual(res.children, ['a', 'b'])
  754. self.assertNotEqual(res.children, ['ab'])
  755. grammar = """
  756. start: A B | AB
  757. A: "a"
  758. B: "b"
  759. AB.3: "ab"
  760. """
  761. l = _Lark(grammar)
  762. res = l.parse("ab")
  763. self.assertNotEqual(res.children, ['a', 'b'])
  764. self.assertEqual(res.children, ['ab'])
  765. def test_import(self):
  766. grammar = """
  767. start: NUMBER WORD
  768. %import common.NUMBER
  769. %import common.WORD
  770. %import common.WS
  771. %ignore WS
  772. """
  773. l = _Lark(grammar)
  774. x = l.parse('12 elephants')
  775. self.assertEqual(x.children, ['12', 'elephants'])
  776. def test_relative_import(self):
  777. grammar = """
  778. start: NUMBER WORD
  779. %import .grammars.test.NUMBER
  780. %import common.WORD
  781. %import common.WS
  782. %ignore WS
  783. """
  784. l = _Lark(grammar)
  785. x = l.parse('12 lions')
  786. self.assertEqual(x.children, ['12', 'lions'])
  787. def test_multi_import(self):
  788. grammar = """
  789. start: NUMBER WORD
  790. %import common (NUMBER, WORD, WS)
  791. %ignore WS
  792. """
  793. l = _Lark(grammar)
  794. x = l.parse('12 toucans')
  795. self.assertEqual(x.children, ['12', 'toucans'])
  796. def test_relative_multi_import(self):
  797. grammar = """
  798. start: NUMBER WORD
  799. %import .grammars.test (NUMBER, WORD, WS)
  800. %ignore WS
  801. """
  802. l = _Lark(grammar)
  803. x = l.parse('12 capybaras')
  804. self.assertEqual(x.children, ['12', 'capybaras'])
  805. def test_import_errors(self):
  806. grammar = """
  807. start: NUMBER WORD
  808. %import .grammars.bad_test.NUMBER
  809. """
  810. self.assertRaises(IOError, _Lark, grammar)
  811. grammar = """
  812. start: NUMBER WORD
  813. %import bad_test.NUMBER
  814. """
  815. self.assertRaises(IOError, _Lark, grammar)
  816. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  817. def test_earley_prioritization(self):
  818. "Tests effect of priority on result"
  819. grammar = """
  820. start: a | b
  821. a.1: "a"
  822. b.2: "a"
  823. """
  824. # l = Lark(grammar, parser='earley', lexer='standard')
  825. l = _Lark(grammar)
  826. res = l.parse("a")
  827. self.assertEqual(res.children[0].data, 'b')
  828. grammar = """
  829. start: a | b
  830. a.2: "a"
  831. b.1: "a"
  832. """
  833. l = _Lark(grammar)
  834. # l = Lark(grammar, parser='earley', lexer='standard')
  835. res = l.parse("a")
  836. self.assertEqual(res.children[0].data, 'a')
  837. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  838. def test_earley_prioritization_sum(self):
  839. "Tests effect of priority on result"
  840. grammar = """
  841. start: ab_ b_ a_ | indirection
  842. indirection: a_ bb_ a_
  843. a_: "a"
  844. b_: "b"
  845. ab_: "ab"
  846. bb_.1: "bb"
  847. """
  848. l = Lark(grammar, priority="invert")
  849. res = l.parse('abba')
  850. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  851. grammar = """
  852. start: ab_ b_ a_ | indirection
  853. indirection: a_ bb_ a_
  854. a_: "a"
  855. b_: "b"
  856. ab_.1: "ab"
  857. bb_: "bb"
  858. """
  859. l = Lark(grammar, priority="invert")
  860. res = l.parse('abba')
  861. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  862. grammar = """
  863. start: ab_ b_ a_ | indirection
  864. indirection: a_ bb_ a_
  865. a_.2: "a"
  866. b_.1: "b"
  867. ab_.3: "ab"
  868. bb_.3: "bb"
  869. """
  870. l = Lark(grammar, priority="invert")
  871. res = l.parse('abba')
  872. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  873. grammar = """
  874. start: ab_ b_ a_ | indirection
  875. indirection: a_ bb_ a_
  876. a_.1: "a"
  877. b_.1: "b"
  878. ab_.4: "ab"
  879. bb_.3: "bb"
  880. """
  881. l = Lark(grammar, priority="invert")
  882. res = l.parse('abba')
  883. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  884. def test_utf8(self):
  885. g = u"""start: a
  886. a: "±a"
  887. """
  888. l = _Lark(g)
  889. self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])]))
  890. g = u"""start: A
  891. A: "±a"
  892. """
  893. l = _Lark(g)
  894. self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a']))
  895. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  896. def test_ignore(self):
  897. grammar = r"""
  898. COMMENT: /(!|(\/\/))[^\n]*/
  899. %ignore COMMENT
  900. %import common.WS -> _WS
  901. %import common.INT
  902. start: "INT"i _WS+ INT _WS*
  903. """
  904. parser = _Lark(grammar)
  905. tree = parser.parse("int 1 ! This is a comment\n")
  906. self.assertEqual(tree.children, ['1'])
  907. tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky!
  908. self.assertEqual(tree.children, ['1'])
  909. parser = _Lark(r"""
  910. start : "a"*
  911. %ignore "b"
  912. """)
  913. tree = parser.parse("bb")
  914. self.assertEqual(tree.children, [])
  915. def test_regex_escaping(self):
  916. g = _Lark("start: /[ab]/")
  917. g.parse('a')
  918. g.parse('b')
  919. self.assertRaises( UnexpectedInput, g.parse, 'c')
  920. _Lark(r'start: /\w/').parse('a')
  921. g = _Lark(r'start: /\\w/')
  922. self.assertRaises( UnexpectedInput, g.parse, 'a')
  923. g.parse(r'\w')
  924. _Lark(r'start: /\[/').parse('[')
  925. _Lark(r'start: /\//').parse('/')
  926. _Lark(r'start: /\\/').parse('\\')
  927. _Lark(r'start: /\[ab]/').parse('[ab]')
  928. _Lark(r'start: /\\[ab]/').parse('\\a')
  929. _Lark(r'start: /\t/').parse('\t')
  930. _Lark(r'start: /\\t/').parse('\\t')
  931. _Lark(r'start: /\\\t/').parse('\\\t')
  932. _Lark(r'start: "\t"').parse('\t')
  933. _Lark(r'start: "\\t"').parse('\\t')
  934. _Lark(r'start: "\\\t"').parse('\\\t')
  935. def test_ranged_repeat_rules(self):
  936. g = u"""!start: "A"~3
  937. """
  938. l = _Lark(g)
  939. self.assertEqual(l.parse(u'AAA'), Tree('start', ["A", "A", "A"]))
  940. self.assertRaises(ParseError, l.parse, u'AA')
  941. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  942. g = u"""!start: "A"~0..2
  943. """
  944. if PARSER != 'cyk': # XXX CYK currently doesn't support empty grammars
  945. l = _Lark(g)
  946. self.assertEqual(l.parse(u''), Tree('start', []))
  947. self.assertEqual(l.parse(u'A'), Tree('start', ['A']))
  948. self.assertEqual(l.parse(u'AA'), Tree('start', ['A', 'A']))
  949. self.assertRaises((UnexpectedToken, UnexpectedInput), l.parse, u'AAA')
  950. g = u"""!start: "A"~3..2
  951. """
  952. self.assertRaises(GrammarError, _Lark, g)
  953. g = u"""!start: "A"~2..3 "B"~2
  954. """
  955. l = _Lark(g)
  956. self.assertEqual(l.parse(u'AABB'), Tree('start', ['A', 'A', 'B', 'B']))
  957. self.assertEqual(l.parse(u'AAABB'), Tree('start', ['A', 'A', 'A', 'B', 'B']))
  958. self.assertRaises(ParseError, l.parse, u'AAAB')
  959. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  960. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  961. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  962. def test_ranged_repeat_terms(self):
  963. g = u"""!start: AAA
  964. AAA: "A"~3
  965. """
  966. l = _Lark(g)
  967. self.assertEqual(l.parse(u'AAA'), Tree('start', ["AAA"]))
  968. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AA')
  969. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  970. g = u"""!start: AABB CC
  971. AABB: "A"~0..2 "B"~2
  972. CC: "C"~1..2
  973. """
  974. l = _Lark(g)
  975. self.assertEqual(l.parse(u'AABBCC'), Tree('start', ['AABB', 'CC']))
  976. self.assertEqual(l.parse(u'BBC'), Tree('start', ['BB', 'C']))
  977. self.assertEqual(l.parse(u'ABBCC'), Tree('start', ['ABB', 'CC']))
  978. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAB')
  979. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  980. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  981. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  982. @unittest.skipIf(PARSER=='earley', "Priority not handled correctly right now") # TODO XXX
  983. def test_priority_vs_embedded(self):
  984. g = """
  985. A.2: "a"
  986. WORD: ("a".."z")+
  987. start: (A | WORD)+
  988. """
  989. l = _Lark(g)
  990. t = l.parse('abc')
  991. self.assertEqual(t.children, ['a', 'bc'])
  992. self.assertEqual(t.children[0].type, 'A')
  993. def test_line_counting(self):
  994. p = _Lark("start: /[^x]+/")
  995. text = 'hello\nworld'
  996. t = p.parse(text)
  997. tok = t.children[0]
  998. self.assertEqual(tok, text)
  999. self.assertEqual(tok.line, 1)
  1000. self.assertEqual(tok.column, 1)
  1001. if _LEXER != 'dynamic':
  1002. self.assertEqual(tok.end_line, 2)
  1003. self.assertEqual(tok.end_column, 6)
  1004. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1005. def test_empty_end(self):
  1006. p = _Lark("""
  1007. start: b c d
  1008. b: "B"
  1009. c: | "C"
  1010. d: | "D"
  1011. """)
  1012. res = p.parse('B')
  1013. self.assertEqual(len(res.children), 3)
  1014. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1015. def test_maybe_placeholders(self):
  1016. # Anonymous tokens shouldn't count
  1017. p = _Lark("""start: "a"? "b"? "c"? """, maybe_placeholders=True)
  1018. self.assertEqual(p.parse("").children, [])
  1019. # Anonymous tokens shouldn't count, other constructs should
  1020. p = _Lark("""start: A? "b"? _c?
  1021. A: "a"
  1022. _c: "c" """, maybe_placeholders=True)
  1023. self.assertEqual(p.parse("").children, [None])
  1024. p = _Lark("""!start: "a"? "b"? "c"? """, maybe_placeholders=True)
  1025. self.assertEqual(p.parse("").children, [None, None, None])
  1026. self.assertEqual(p.parse("a").children, ['a', None, None])
  1027. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1028. self.assertEqual(p.parse("c").children, [None, None, 'c'])
  1029. self.assertEqual(p.parse("ab").children, ['a', 'b', None])
  1030. self.assertEqual(p.parse("ac").children, ['a', None, 'c'])
  1031. self.assertEqual(p.parse("bc").children, [None, 'b', 'c'])
  1032. self.assertEqual(p.parse("abc").children, ['a', 'b', 'c'])
  1033. p = _Lark("""!start: ("a"? "b" "c"?)+ """, maybe_placeholders=True)
  1034. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1035. self.assertEqual(p.parse("bb").children, [None, 'b', None, None, 'b', None])
  1036. self.assertEqual(p.parse("abbc").children, ['a', 'b', None, None, 'b', 'c'])
  1037. self.assertEqual(p.parse("babbcabcb").children,
  1038. [None, 'b', None,
  1039. 'a', 'b', None,
  1040. None, 'b', 'c',
  1041. 'a', 'b', 'c',
  1042. None, 'b', None])
  1043. p = _Lark("""!start: "a"? "c"? "b"+ "a"? "d"? """, maybe_placeholders=True)
  1044. self.assertEqual(p.parse("bb").children, [None, None, 'b', 'b', None, None])
  1045. self.assertEqual(p.parse("bd").children, [None, None, 'b', None, 'd'])
  1046. self.assertEqual(p.parse("abba").children, ['a', None, 'b', 'b', 'a', None])
  1047. self.assertEqual(p.parse("cbbbb").children, [None, 'c', 'b', 'b', 'b', 'b', None, None])
  1048. def test_escaped_string(self):
  1049. "Tests common.ESCAPED_STRING"
  1050. grammar = r"""
  1051. start: ESCAPED_STRING+
  1052. %import common (WS_INLINE, ESCAPED_STRING)
  1053. %ignore WS_INLINE
  1054. """
  1055. parser = _Lark(grammar)
  1056. parser.parse(r'"\\" "b" "c"')
  1057. parser.parse(r'"That" "And a \"b"')
  1058. _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize()
  1059. _TestParser.__name__ = _NAME
  1060. globals()[_NAME] = _TestParser
  1061. # Note: You still have to import them in __main__ for the tests to run
  1062. _TO_TEST = [
  1063. ('standard', 'earley'),
  1064. ('standard', 'cyk'),
  1065. ('dynamic', 'earley'),
  1066. ('dynamic_complete', 'earley'),
  1067. ('standard', 'lalr'),
  1068. ('contextual', 'lalr'),
  1069. # (None, 'earley'),
  1070. ]
  1071. for _LEXER, _PARSER in _TO_TEST:
  1072. _make_parser_test(_LEXER, _PARSER)
  1073. for _LEXER in ('dynamic', 'dynamic_complete'):
  1074. _make_full_earley_test(_LEXER)
  1075. if __name__ == '__main__':
  1076. unittest.main()