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.

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