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.

987 lines
33 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
  19. from lark.lexer import LexError
  20. from lark.tree import Tree, 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. l = Lark(g, parser='earley', lexer=None)
  43. self.assertRaises(ParseError, l.parse, 'a')
  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].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 _make_full_earley_test(LEXER):
  122. class _TestFullEarley(unittest.TestCase):
  123. def test_anon_in_scanless(self):
  124. # Fails an Earley implementation without special handling for empty rules,
  125. # or re-processing of already completed rules.
  126. g = Lark(r"""start: B
  127. B: ("ab"|/[^b]/)*
  128. """, lexer=LEXER)
  129. self.assertEqual( g.parse('abc').children[0], 'abc')
  130. def test_earley_scanless(self):
  131. g = Lark("""start: A "b" c
  132. A: "a"+
  133. c: "abc"
  134. """, parser="earley", lexer=LEXER)
  135. x = g.parse('aaaababc')
  136. def test_earley_scanless2(self):
  137. grammar = """
  138. start: statement+
  139. statement: "r"
  140. | "c" /[a-z]/+
  141. %ignore " "
  142. """
  143. program = """c b r"""
  144. l = Lark(grammar, parser='earley', lexer=LEXER)
  145. l.parse(program)
  146. def test_earley_scanless3(self):
  147. "Tests prioritization and disambiguation for pseudo-terminals (there should be only one result)"
  148. grammar = """
  149. start: A A
  150. A: "a"+
  151. """
  152. l = Lark(grammar, parser='earley', lexer=LEXER)
  153. res = l.parse("aaa")
  154. self.assertEqual(res.children, ['aa', 'a'])
  155. def test_earley_scanless4(self):
  156. grammar = """
  157. start: A A?
  158. A: "a"+
  159. """
  160. l = Lark(grammar, parser='earley', lexer=LEXER)
  161. res = l.parse("aaa")
  162. self.assertEqual(res.children, ['aaa'])
  163. def test_earley_repeating_empty(self):
  164. # This was a sneaky bug!
  165. grammar = """
  166. !start: "a" empty empty "b"
  167. empty: empty2
  168. empty2:
  169. """
  170. parser = Lark(grammar, parser='earley', lexer=LEXER)
  171. res = parser.parse('ab')
  172. empty_tree = Tree('empty', [Tree('empty2', [])])
  173. self.assertSequenceEqual(res.children, ['a', empty_tree, empty_tree, 'b'])
  174. def test_earley_explicit_ambiguity(self):
  175. # This was a sneaky bug!
  176. grammar = """
  177. start: a b | ab
  178. a: "a"
  179. b: "b"
  180. ab: "ab"
  181. """
  182. parser = Lark(grammar, parser='earley', lexer=LEXER, ambiguity='explicit')
  183. res = parser.parse('ab')
  184. self.assertEqual( res.data, '_ambig')
  185. self.assertEqual( len(res.children), 2)
  186. def test_ambiguity1(self):
  187. grammar = """
  188. start: cd+ "e"
  189. !cd: "c"
  190. | "d"
  191. | "cd"
  192. """
  193. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  194. x = l.parse('cde')
  195. assert x.data == '_ambig', x
  196. assert len(x.children) == 2
  197. @unittest.skipIf(LEXER==None, "BUG in scanless parsing!") # TODO fix bug!
  198. def test_fruitflies_ambig(self):
  199. grammar = """
  200. start: noun verb noun -> simple
  201. | noun verb "like" noun -> comparative
  202. noun: adj? NOUN
  203. verb: VERB
  204. adj: ADJ
  205. NOUN: "flies" | "bananas" | "fruit"
  206. VERB: "like" | "flies"
  207. ADJ: "fruit"
  208. %import common.WS
  209. %ignore WS
  210. """
  211. parser = Lark(grammar, ambiguity='explicit', lexer=LEXER)
  212. res = parser.parse('fruit flies like bananas')
  213. expected = Tree('_ambig', [
  214. Tree('comparative', [
  215. Tree('noun', ['fruit']),
  216. Tree('verb', ['flies']),
  217. Tree('noun', ['bananas'])
  218. ]),
  219. Tree('simple', [
  220. Tree('noun', [Tree('adj', ['fruit']), 'flies']),
  221. Tree('verb', ['like']),
  222. Tree('noun', ['bananas'])
  223. ])
  224. ])
  225. # print res.pretty()
  226. # print expected.pretty()
  227. self.assertEqual(res, expected)
  228. # @unittest.skipIf(LEXER=='dynamic', "Not implemented in Dynamic Earley yet") # TODO
  229. # def test_not_all_derivations(self):
  230. # grammar = """
  231. # start: cd+ "e"
  232. # !cd: "c"
  233. # | "d"
  234. # | "cd"
  235. # """
  236. # l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER, earley__all_derivations=False)
  237. # x = l.parse('cde')
  238. # assert x.data != '_ambig', x
  239. # assert len(x.children) == 1
  240. _NAME = "TestFullEarley" + (LEXER or 'Scanless').capitalize()
  241. _TestFullEarley.__name__ = _NAME
  242. globals()[_NAME] = _TestFullEarley
  243. def _make_parser_test(LEXER, PARSER):
  244. def _Lark(grammar, **kwargs):
  245. return Lark(grammar, lexer=LEXER, parser=PARSER, **kwargs)
  246. class _TestParser(unittest.TestCase):
  247. def test_basic1(self):
  248. g = _Lark("""start: a+ b a* "b" a*
  249. b: "b"
  250. a: "a"
  251. """)
  252. r = g.parse('aaabaab')
  253. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  254. r = g.parse('aaabaaba')
  255. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  256. self.assertRaises(ParseError, g.parse, 'aaabaa')
  257. def test_basic2(self):
  258. # Multiple parsers and colliding tokens
  259. g = _Lark("""start: B A
  260. B: "12"
  261. A: "1" """)
  262. g2 = _Lark("""start: B A
  263. B: "12"
  264. A: "2" """)
  265. x = g.parse('121')
  266. assert x.data == 'start' and x.children == ['12', '1'], x
  267. x = g2.parse('122')
  268. assert x.data == 'start' and x.children == ['12', '2'], x
  269. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  270. def test_stringio_bytes(self):
  271. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  272. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  273. def test_stringio_unicode(self):
  274. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  275. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  276. def test_unicode(self):
  277. g = _Lark(u"""start: UNIA UNIB UNIA
  278. UNIA: /\xa3/
  279. UNIB: /\u0101/
  280. """)
  281. g.parse(u'\xa3\u0101\u00a3')
  282. @unittest.skipIf(LEXER is None, "Regexps >1 not supported with scanless parsing")
  283. def test_unicode2(self):
  284. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  285. UNIA: /\xa3/
  286. UNIB: "a\u0101b\ "
  287. UNIC: /a?\u0101c\n/
  288. """)
  289. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  290. def test_unicode3(self):
  291. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  292. UNIA: /\xa3/
  293. UNIB: "\u0101"
  294. UNIC: /\u0203/ /\n/
  295. """)
  296. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  297. def test_stack_for_ebnf(self):
  298. """Verify that stack depth isn't an issue for EBNF grammars"""
  299. g = _Lark(r"""start: a+
  300. a : "a" """)
  301. g.parse("a" * (sys.getrecursionlimit()*2 ))
  302. def test_expand1_lists_with_one_item(self):
  303. g = _Lark(r"""start: list
  304. ?list: item+
  305. item : A
  306. A: "a"
  307. """)
  308. r = g.parse("a")
  309. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  310. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  311. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  312. self.assertEqual(len(r.children), 1)
  313. def test_expand1_lists_with_one_item_2(self):
  314. g = _Lark(r"""start: list
  315. ?list: item+ "!"
  316. item : A
  317. A: "a"
  318. """)
  319. r = g.parse("a!")
  320. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  321. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  322. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  323. self.assertEqual(len(r.children), 1)
  324. def test_dont_expand1_lists_with_multiple_items(self):
  325. g = _Lark(r"""start: list
  326. ?list: item+
  327. item : A
  328. A: "a"
  329. """)
  330. r = g.parse("aa")
  331. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  332. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  333. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  334. self.assertEqual(len(r.children), 1)
  335. # Sanity check: verify that 'list' contains the two 'item's we've given it
  336. [list] = r.children
  337. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  338. def test_dont_expand1_lists_with_multiple_items_2(self):
  339. g = _Lark(r"""start: list
  340. ?list: item+ "!"
  341. item : A
  342. A: "a"
  343. """)
  344. r = g.parse("aa!")
  345. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  346. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  347. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  348. self.assertEqual(len(r.children), 1)
  349. # Sanity check: verify that 'list' contains the two 'item's we've given it
  350. [list] = r.children
  351. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  352. def test_empty_expand1_list(self):
  353. g = _Lark(r"""start: list
  354. ?list: item*
  355. item : A
  356. A: "a"
  357. """)
  358. r = g.parse("")
  359. # 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
  360. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  361. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  362. self.assertEqual(len(r.children), 1)
  363. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  364. [list] = r.children
  365. self.assertSequenceEqual([item.data for item in list.children], ())
  366. def test_empty_expand1_list_2(self):
  367. g = _Lark(r"""start: list
  368. ?list: item* "!"?
  369. item : A
  370. A: "a"
  371. """)
  372. r = g.parse("")
  373. # 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
  374. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  375. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  376. self.assertEqual(len(r.children), 1)
  377. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  378. [list] = r.children
  379. self.assertSequenceEqual([item.data for item in list.children], ())
  380. def test_empty_flatten_list(self):
  381. g = _Lark(r"""start: list
  382. list: | item "," list
  383. item : A
  384. A: "a"
  385. """)
  386. r = g.parse("")
  387. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  388. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  389. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  390. [list] = r.children
  391. self.assertSequenceEqual([item.data for item in list.children], ())
  392. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  393. def test_single_item_flatten_list(self):
  394. g = _Lark(r"""start: list
  395. list: | item "," list
  396. item : A
  397. A: "a"
  398. """)
  399. r = g.parse("a,")
  400. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  401. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  402. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  403. [list] = r.children
  404. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  405. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  406. def test_multiple_item_flatten_list(self):
  407. g = _Lark(r"""start: list
  408. #list: | item "," list
  409. item : A
  410. A: "a"
  411. """)
  412. r = g.parse("a,a,")
  413. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  414. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  415. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  416. [list] = r.children
  417. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  418. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  419. def test_recurse_flatten(self):
  420. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  421. g = _Lark(r"""start: a | start a
  422. a : A
  423. A : "a" """)
  424. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  425. # STree data structures, which uses recursion).
  426. g.parse("a" * (sys.getrecursionlimit() // 4))
  427. def test_token_collision(self):
  428. g = _Lark(r"""start: "Hello" NAME
  429. NAME: /\w/+
  430. %ignore " "
  431. """)
  432. x = g.parse('Hello World')
  433. self.assertSequenceEqual(x.children, ['World'])
  434. x = g.parse('Hello HelloWorld')
  435. self.assertSequenceEqual(x.children, ['HelloWorld'])
  436. def test_token_collision_WS(self):
  437. g = _Lark(r"""start: "Hello" NAME
  438. NAME: /\w/+
  439. %import common.WS
  440. %ignore WS
  441. """)
  442. x = g.parse('Hello World')
  443. self.assertSequenceEqual(x.children, ['World'])
  444. x = g.parse('Hello HelloWorld')
  445. self.assertSequenceEqual(x.children, ['HelloWorld'])
  446. @unittest.skipIf(LEXER is None, "Known bug with scanless parsing") # TODO
  447. def test_token_collision2(self):
  448. # NOTE: This test reveals a bug in token reconstruction in Scanless Earley
  449. # I probably need to re-write grammar transformation
  450. g = _Lark("""
  451. !start: "starts"
  452. %import common.LCASE_LETTER
  453. """)
  454. x = g.parse("starts")
  455. self.assertSequenceEqual(x.children, ['starts'])
  456. # def test_string_priority(self):
  457. # g = _Lark("""start: (A | /a?bb/)+
  458. # A: "a" """)
  459. # x = g.parse('abb')
  460. # self.assertEqual(len(x.children), 2)
  461. # # This parse raises an exception because the lexer will always try to consume
  462. # # "a" first and will never match the regular expression
  463. # # This behavior is subject to change!!
  464. # # Thie won't happen with ambiguity handling.
  465. # g = _Lark("""start: (A | /a?ab/)+
  466. # A: "a" """)
  467. # self.assertRaises(LexError, g.parse, 'aab')
  468. def test_undefined_rule(self):
  469. self.assertRaises(GrammarError, _Lark, """start: a""")
  470. def test_undefined_token(self):
  471. self.assertRaises(GrammarError, _Lark, """start: A""")
  472. def test_rule_collision(self):
  473. g = _Lark("""start: "a"+ "b"
  474. | "a"+ """)
  475. x = g.parse('aaaa')
  476. x = g.parse('aaaab')
  477. def test_rule_collision2(self):
  478. g = _Lark("""start: "a"* "b"
  479. | "a"+ """)
  480. x = g.parse('aaaa')
  481. x = g.parse('aaaab')
  482. x = g.parse('b')
  483. @unittest.skipIf(LEXER in (None, 'dynamic'), "Known bug with scanless parsing") # TODO
  484. def test_token_not_anon(self):
  485. """Tests that "a" is matched as A, rather than an anonymous token.
  486. That means that "a" is not filtered out, despite being an 'immediate string'.
  487. Whether or not this is the intuitive behavior, I'm not sure yet.
  488. Perhaps the right thing to do is report a collision (if such is relevant)
  489. -Erez
  490. """
  491. g = _Lark("""start: "a"
  492. A: "a" """)
  493. x = g.parse('a')
  494. self.assertEqual(len(x.children), 1, '"a" should not be considered anonymous')
  495. self.assertEqual(x.children[0].type, "A")
  496. g = _Lark("""start: /a/
  497. A: /a/ """)
  498. x = g.parse('a')
  499. self.assertEqual(len(x.children), 1, '/a/ should not be considered anonymous')
  500. self.assertEqual(x.children[0].type, "A")
  501. def test_maybe(self):
  502. g = _Lark("""start: ["a"] """)
  503. x = g.parse('a')
  504. x = g.parse('')
  505. def test_start(self):
  506. g = _Lark("""a: "a" a? """, start='a')
  507. x = g.parse('a')
  508. x = g.parse('aa')
  509. x = g.parse('aaa')
  510. def test_alias(self):
  511. g = _Lark("""start: "a" -> b """)
  512. x = g.parse('a')
  513. self.assertEqual(x.data, "b")
  514. def test_token_ebnf(self):
  515. g = _Lark("""start: A
  516. A: "a"* ("b"? "c".."e")+
  517. """)
  518. x = g.parse('abcde')
  519. x = g.parse('dd')
  520. def test_backslash(self):
  521. g = _Lark(r"""start: "\\" "a"
  522. """)
  523. x = g.parse(r'\a')
  524. g = _Lark(r"""start: /\\\\/ /a/
  525. """)
  526. x = g.parse(r'\a')
  527. def test_special_chars(self):
  528. g = _Lark(r"""start: "\n"
  529. """)
  530. x = g.parse('\n')
  531. g = _Lark(r"""start: /\n/
  532. """)
  533. x = g.parse('\n')
  534. def test_backslash2(self):
  535. g = _Lark(r"""start: "\"" "-"
  536. """)
  537. x = g.parse('"-')
  538. g = _Lark(r"""start: /\// /-/
  539. """)
  540. x = g.parse('/-')
  541. # def test_token_recurse(self):
  542. # g = _Lark("""start: A
  543. # A: B
  544. # B: A
  545. # """)
  546. def test_empty(self):
  547. # Fails an Earley implementation without special handling for empty rules,
  548. # or re-processing of already completed rules.
  549. g = _Lark(r"""start: _empty a "B"
  550. a: _empty "A"
  551. _empty:
  552. """)
  553. x = g.parse('AB')
  554. def test_lexer_token_limit(self):
  555. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  556. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  557. g = _Lark("""start: %s
  558. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  559. def test_float_without_lexer(self):
  560. g = _Lark("""start: ["+"|"-"] float
  561. float: digit* "." digit+ exp?
  562. | digit+ exp
  563. exp: ("e"|"E") ["+"|"-"] digit+
  564. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  565. """)
  566. g.parse("1.2")
  567. g.parse("-.2e9")
  568. g.parse("+2e-9")
  569. self.assertRaises(ParseError, g.parse, "+2e-9e")
  570. def test_keep_all_tokens(self):
  571. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  572. tree = l.parse('aaa')
  573. self.assertEqual(tree.children, ['a', 'a', 'a'])
  574. def test_token_flags(self):
  575. l = _Lark("""!start: "a"i+
  576. """
  577. )
  578. tree = l.parse('aA')
  579. self.assertEqual(tree.children, ['a', 'A'])
  580. l = _Lark("""!start: /a/i+
  581. """
  582. )
  583. tree = l.parse('aA')
  584. self.assertEqual(tree.children, ['a', 'A'])
  585. g = """!start: "a"i "a"
  586. """
  587. self.assertRaises(GrammarError, _Lark, g)
  588. g = """!start: /a/i /a/
  589. """
  590. self.assertRaises(GrammarError, _Lark, g)
  591. g = """start: NAME "," "a"
  592. NAME: /[a-z_]/i /[a-z0-9_]/i*
  593. """
  594. l = _Lark(g)
  595. tree = l.parse('ab,a')
  596. self.assertEqual(tree.children, ['ab'])
  597. tree = l.parse('AB,a')
  598. self.assertEqual(tree.children, ['AB'])
  599. def test_token_flags3(self):
  600. l = _Lark("""!start: ABC+
  601. ABC: "abc"i
  602. """
  603. )
  604. tree = l.parse('aBcAbC')
  605. self.assertEqual(tree.children, ['aBc', 'AbC'])
  606. def test_token_flags2(self):
  607. g = """!start: ("a"i | /a/ /b/?)+
  608. """
  609. l = _Lark(g)
  610. tree = l.parse('aA')
  611. self.assertEqual(tree.children, ['a', 'A'])
  612. def test_reduce_cycle(self):
  613. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  614. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  615. """
  616. l = _Lark("""
  617. term: A
  618. | term term
  619. A: "a"
  620. """, start='term')
  621. tree = l.parse("aa")
  622. self.assertEqual(len(tree.children), 2)
  623. @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority")
  624. def test_lexer_prioritization(self):
  625. "Tests effect of priority on result"
  626. grammar = """
  627. start: A B | AB
  628. A.2: "a"
  629. B: "b"
  630. AB: "ab"
  631. """
  632. l = _Lark(grammar)
  633. res = l.parse("ab")
  634. self.assertEqual(res.children, ['a', 'b'])
  635. self.assertNotEqual(res.children, ['ab'])
  636. grammar = """
  637. start: A B | AB
  638. A: "a"
  639. B: "b"
  640. AB.3: "ab"
  641. """
  642. l = _Lark(grammar)
  643. res = l.parse("ab")
  644. self.assertNotEqual(res.children, ['a', 'b'])
  645. self.assertEqual(res.children, ['ab'])
  646. def test_import(self):
  647. grammar = """
  648. start: NUMBER WORD
  649. %import common.NUMBER
  650. %import common.WORD
  651. %import common.WS
  652. %ignore WS
  653. """
  654. l = _Lark(grammar)
  655. x = l.parse('12 elephants')
  656. self.assertEqual(x.children, ['12', 'elephants'])
  657. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  658. def test_earley_prioritization(self):
  659. "Tests effect of priority on result"
  660. grammar = """
  661. start: a | b
  662. a.1: "a"
  663. b.2: "a"
  664. """
  665. # l = Lark(grammar, parser='earley', lexer='standard')
  666. l = _Lark(grammar)
  667. res = l.parse("a")
  668. self.assertEqual(res.children[0].data, 'b')
  669. grammar = """
  670. start: a | b
  671. a.2: "a"
  672. b.1: "a"
  673. """
  674. l = _Lark(grammar)
  675. # l = Lark(grammar, parser='earley', lexer='standard')
  676. res = l.parse("a")
  677. self.assertEqual(res.children[0].data, 'a')
  678. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  679. def test_earley_prioritization_sum(self):
  680. "Tests effect of priority on result"
  681. grammar = """
  682. start: ab_ b_ a_ | indirection
  683. indirection: a_ bb_ a_
  684. a_: "a"
  685. b_: "b"
  686. ab_: "ab"
  687. bb_.1: "bb"
  688. """
  689. l = _Lark(grammar, ambiguity='resolve__antiscore_sum')
  690. res = l.parse('abba')
  691. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  692. grammar = """
  693. start: ab_ b_ a_ | indirection
  694. indirection: a_ bb_ a_
  695. a_: "a"
  696. b_: "b"
  697. ab_.1: "ab"
  698. bb_: "bb"
  699. """
  700. l = Lark(grammar, parser='earley', ambiguity='resolve__antiscore_sum')
  701. res = l.parse('abba')
  702. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  703. grammar = """
  704. start: ab_ b_ a_ | indirection
  705. indirection: a_ bb_ a_
  706. a_.2: "a"
  707. b_.1: "b"
  708. ab_.3: "ab"
  709. bb_.3: "bb"
  710. """
  711. l = Lark(grammar, parser='earley', ambiguity='resolve__antiscore_sum')
  712. res = l.parse('abba')
  713. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  714. grammar = """
  715. start: ab_ b_ a_ | indirection
  716. indirection: a_ bb_ a_
  717. a_.1: "a"
  718. b_.1: "b"
  719. ab_.4: "ab"
  720. bb_.3: "bb"
  721. """
  722. l = Lark(grammar, parser='earley', ambiguity='resolve__antiscore_sum')
  723. res = l.parse('abba')
  724. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  725. def test_utf8(self):
  726. g = u"""start: a
  727. a: "±a"
  728. """
  729. l = _Lark(g)
  730. self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])]))
  731. g = u"""start: A
  732. A: "±a"
  733. """
  734. l = _Lark(g)
  735. self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a']))
  736. @unittest.skipIf(LEXER==None, "Scanless doesn't support regular expressions")
  737. def test_ignore(self):
  738. grammar = r"""
  739. COMMENT: /(!|(\/\/))[^\n]*/
  740. %ignore COMMENT
  741. %import common.WS -> _WS
  742. %import common.INT
  743. start: "INT"i _WS+ INT _WS*
  744. """
  745. parser = _Lark(grammar)
  746. tree = parser.parse("int 1 ! This is a comment\n")
  747. self.assertEqual(tree.children, ['1'])
  748. tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky!
  749. self.assertEqual(tree.children, ['1'])
  750. _NAME = "Test" + PARSER.capitalize() + (LEXER or 'Scanless').capitalize()
  751. _TestParser.__name__ = _NAME
  752. globals()[_NAME] = _TestParser
  753. # Note: You still have to import them in __main__ for the tests to run
  754. _TO_TEST = [
  755. ('standard', 'earley'),
  756. ('dynamic', 'earley'),
  757. ('standard', 'lalr'),
  758. ('contextual', 'lalr'),
  759. (None, 'earley'),
  760. ]
  761. for _LEXER, _PARSER in _TO_TEST:
  762. _make_parser_test(_LEXER, _PARSER)
  763. for _LEXER in (None, 'dynamic'):
  764. _make_full_earley_test(_LEXER)
  765. if __name__ == '__main__':
  766. unittest.main()