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.

1301 lines
43 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. from lark.parsers.earley_forest import ForestToAmbiguousTreeVisitor
  22. from lark.parsers.earley import ApplyCallbacks
  23. __path__ = os.path.dirname(__file__)
  24. def _read(n, *args):
  25. with open(os.path.join(__path__, n), *args) as f:
  26. return f.read()
  27. class TestParsers(unittest.TestCase):
  28. def test_same_ast(self):
  29. "Tests that Earley and LALR parsers produce equal trees"
  30. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  31. name_list: NAME | name_list "," NAME
  32. NAME: /\w+/ """, parser='lalr')
  33. l = g.parse('(a,b,c,*x)')
  34. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  35. name_list: NAME | name_list "," NAME
  36. NAME: /\w/+ """)
  37. l2 = g.parse('(a,b,c,*x)')
  38. assert l == l2, '%s != %s' % (l.pretty(), l2.pretty())
  39. def test_infinite_recurse(self):
  40. g = """start: a
  41. a: a | "a"
  42. """
  43. self.assertRaises(GrammarError, Lark, g, parser='lalr')
  44. l = Lark(g, parser='earley', lexer='dynamic')
  45. self.assertRaises(ParseError, l.parse, 'a')
  46. def test_propagate_positions(self):
  47. g = Lark("""start: a
  48. a: "a"
  49. """, propagate_positions=True)
  50. r = g.parse('a')
  51. self.assertEqual( r.children[0].meta.line, 1 )
  52. def test_expand1(self):
  53. g = Lark("""start: a
  54. ?a: b
  55. b: "x"
  56. """)
  57. r = g.parse('x')
  58. self.assertEqual( r.children[0].data, "b" )
  59. g = Lark("""start: a
  60. ?a: b -> c
  61. b: "x"
  62. """)
  63. r = g.parse('x')
  64. self.assertEqual( r.children[0].data, "c" )
  65. g = Lark("""start: a
  66. ?a: B -> c
  67. B: "x"
  68. """)
  69. self.assertEqual( r.children[0].data, "c" )
  70. g = Lark("""start: a
  71. ?a: b b -> c
  72. b: "x"
  73. """)
  74. r = g.parse('xx')
  75. self.assertEqual( r.children[0].data, "c" )
  76. def test_embedded_transformer(self):
  77. class T(Transformer):
  78. def a(self, children):
  79. return "<a>"
  80. def b(self, children):
  81. return "<b>"
  82. def c(self, children):
  83. return "<c>"
  84. # Test regular
  85. g = Lark("""start: a
  86. a : "x"
  87. """, parser='lalr')
  88. r = T().transform(g.parse("x"))
  89. self.assertEqual( r.children, ["<a>"] )
  90. g = Lark("""start: a
  91. a : "x"
  92. """, parser='lalr', transformer=T())
  93. r = g.parse("x")
  94. self.assertEqual( r.children, ["<a>"] )
  95. # Test Expand1
  96. g = Lark("""start: a
  97. ?a : b
  98. b : "x"
  99. """, parser='lalr')
  100. r = T().transform(g.parse("x"))
  101. self.assertEqual( r.children, ["<b>"] )
  102. g = Lark("""start: a
  103. ?a : b
  104. b : "x"
  105. """, parser='lalr', transformer=T())
  106. r = g.parse("x")
  107. self.assertEqual( r.children, ["<b>"] )
  108. # Test Expand1 -> Alias
  109. g = Lark("""start: a
  110. ?a : b b -> c
  111. b : "x"
  112. """, parser='lalr')
  113. r = T().transform(g.parse("xx"))
  114. self.assertEqual( r.children, ["<c>"] )
  115. g = Lark("""start: a
  116. ?a : b b -> c
  117. b : "x"
  118. """, parser='lalr', transformer=T())
  119. r = g.parse("xx")
  120. self.assertEqual( r.children, ["<c>"] )
  121. def test_alias(self):
  122. Lark("""start: ["a"] "b" ["c"] "e" ["f"] ["g"] ["h"] "x" -> d """)
  123. def _make_full_earley_test(LEXER):
  124. class _TestFullEarley(unittest.TestCase):
  125. def test_anon(self):
  126. # Fails an Earley implementation without special handling for empty rules,
  127. # or re-processing of already completed rules.
  128. g = Lark(r"""start: B
  129. B: ("ab"|/[^b]/)+
  130. """, lexer=LEXER)
  131. self.assertEqual( g.parse('abc').children[0], 'abc')
  132. def test_earley(self):
  133. g = Lark("""start: A "b" c
  134. A: "a"+
  135. c: "abc"
  136. """, parser="earley", lexer=LEXER)
  137. x = g.parse('aaaababc')
  138. def test_earley2(self):
  139. grammar = """
  140. start: statement+
  141. statement: "r"
  142. | "c" /[a-z]/+
  143. %ignore " "
  144. """
  145. program = """c b r"""
  146. l = Lark(grammar, parser='earley', lexer=LEXER)
  147. l.parse(program)
  148. @unittest.skipIf(LEXER=='dynamic', "Only relevant for the dynamic_complete parser")
  149. def test_earley3(self):
  150. "Tests prioritization and disambiguation for pseudo-terminals (there should be only one result)"
  151. grammar = """
  152. start: A A
  153. A: "a"+
  154. """
  155. l = Lark(grammar, parser='earley', lexer=LEXER)
  156. res = l.parse("aaa")
  157. self.assertEqual(res.children, ['aa', 'a'])
  158. def test_earley4(self):
  159. grammar = """
  160. start: A A?
  161. A: "a"+
  162. """
  163. l = Lark(grammar, parser='earley', lexer=LEXER)
  164. res = l.parse("aaa")
  165. self.assertEqual(res.children, ['aaa'])
  166. def test_earley_repeating_empty(self):
  167. # This was a sneaky bug!
  168. grammar = """
  169. !start: "a" empty empty "b"
  170. empty: empty2
  171. empty2:
  172. """
  173. parser = Lark(grammar, parser='earley', lexer=LEXER)
  174. res = parser.parse('ab')
  175. empty_tree = Tree('empty', [Tree('empty2', [])])
  176. self.assertSequenceEqual(res.children, ['a', empty_tree, empty_tree, 'b'])
  177. def test_earley_explicit_ambiguity(self):
  178. # This was a sneaky bug!
  179. grammar = """
  180. start: a b | ab
  181. a: "a"
  182. b: "b"
  183. ab: "ab"
  184. """
  185. parser = Lark(grammar, parser='earley', lexer=LEXER, ambiguity='explicit')
  186. root_symbol = parser.parse('ab')
  187. ambig_tree = ForestToAmbiguousTreeVisitor(root_symbol, parser.parser.parser.callbacks).go()
  188. # print(ambig_tree.pretty())
  189. self.assertEqual( ambig_tree.data, '_ambig')
  190. self.assertEqual( len(ambig_tree.children), 2)
  191. def test_ambiguity1(self):
  192. grammar = """
  193. start: cd+ "e"
  194. !cd: "c"
  195. | "d"
  196. | "cd"
  197. """
  198. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  199. root_symbol = l.parse('cde')
  200. ambig_tree = ForestToAmbiguousTreeVisitor(root_symbol, l.parser.parser.callbacks).go()
  201. # print(ambig_tree.pretty())
  202. # tree = ApplyCallbacks(l.parser.parser.postprocess).transform(ambig_tree)
  203. assert ambig_tree.data == '_ambig', ambig_tree
  204. assert len(ambig_tree.children) == 2
  205. @unittest.skipIf(LEXER==None, "Scanless doesn't support regular expressions")
  206. def test_ambiguity2(self):
  207. grammar = """
  208. ANY: /[a-zA-Z0-9 ]+/
  209. a.2: "A" b+
  210. b.2: "B"
  211. c: ANY
  212. start: (a|c)*
  213. """
  214. l = Lark(grammar, parser='earley', lexer=LEXER)
  215. res = l.parse('ABX')
  216. expected = Tree('start', [
  217. Tree('a', [
  218. Tree('b', [])
  219. ]),
  220. Tree('c', [
  221. 'X'
  222. ])
  223. ])
  224. self.assertEqual(res, expected)
  225. def test_fruitflies_ambig(self):
  226. grammar = """
  227. start: noun verb noun -> simple
  228. | noun verb "like" noun -> comparative
  229. noun: adj? NOUN
  230. verb: VERB
  231. adj: ADJ
  232. NOUN: "flies" | "bananas" | "fruit"
  233. VERB: "like" | "flies"
  234. ADJ: "fruit"
  235. %import common.WS
  236. %ignore WS
  237. """
  238. parser = Lark(grammar, ambiguity='explicit', lexer=LEXER)
  239. root_symbol = parser.parse('fruit flies like bananas')
  240. tree = ForestToAmbiguousTreeVisitor(root_symbol, parser.parser.parser.callbacks).go()
  241. # tree = ApplyCallbacks(parser.parser.parser.postprocess).transform(ambig_tree)
  242. expected = Tree('_ambig', [
  243. Tree('comparative', [
  244. Tree('noun', ['fruit']),
  245. Tree('verb', ['flies']),
  246. Tree('noun', ['bananas'])
  247. ]),
  248. Tree('simple', [
  249. Tree('noun', [Tree('adj', ['fruit']), 'flies']),
  250. Tree('verb', ['like']),
  251. Tree('noun', ['bananas'])
  252. ])
  253. ])
  254. # print res.pretty()
  255. # print expected.pretty()
  256. # self.assertEqual(tree, expected)
  257. self.assertEqual(tree.data, expected.data)
  258. self.assertEqual(set(tree.children), set(expected.children))
  259. @unittest.skipIf(LEXER=='dynamic', "Only relevant for the dynamic_complete parser")
  260. def test_explicit_ambiguity2(self):
  261. grammar = r"""
  262. start: NAME+
  263. NAME: /\w+/
  264. %ignore " "
  265. """
  266. text = """cat"""
  267. parser = Lark(grammar, start='start', ambiguity='explicit')
  268. root_symbol = parser.parse(text)
  269. ambig_tree = ForestToAmbiguousTreeVisitor(root_symbol).go()
  270. tree = ApplyCallbacks(parser.parser.parser.postprocess).transform(ambig_tree)
  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_special_chars(self):
  589. g = _Lark(r"""start: "\n"
  590. """)
  591. x = g.parse('\n')
  592. g = _Lark(r"""start: /\n/
  593. """)
  594. x = g.parse('\n')
  595. def test_backslash2(self):
  596. g = _Lark(r"""start: "\"" "-"
  597. """)
  598. x = g.parse('"-')
  599. g = _Lark(r"""start: /\// /-/
  600. """)
  601. x = g.parse('/-')
  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, ambiguity='resolve__antiscore_sum')
  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, parser='earley', ambiguity='resolve__antiscore_sum')
  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, parser='earley', ambiguity='resolve__antiscore_sum')
  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, parser='earley', ambiguity='resolve__antiscore_sum')
  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. _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize()
  999. _TestParser.__name__ = _NAME
  1000. globals()[_NAME] = _TestParser
  1001. # Note: You still have to import them in __main__ for the tests to run
  1002. _TO_TEST = [
  1003. ('standard', 'earley'),
  1004. ('standard', 'cyk'),
  1005. ('dynamic', 'earley'),
  1006. ('dynamic_complete', 'earley'),
  1007. ('standard', 'lalr'),
  1008. ('contextual', 'lalr'),
  1009. # (None, 'earley'),
  1010. ]
  1011. for _LEXER, _PARSER in _TO_TEST:
  1012. _make_parser_test(_LEXER, _PARSER)
  1013. for _LEXER in ('dynamic',):
  1014. _make_full_earley_test(_LEXER)
  1015. if __name__ == '__main__':
  1016. unittest.main()