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.

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