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.
 
 

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