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.

624 lines
22 KiB

  1. from __future__ import absolute_import
  2. import unittest
  3. import logging
  4. import os
  5. import sys
  6. try:
  7. from cStringIO import StringIO as cStringIO
  8. except ImportError:
  9. # Available only in Python 2.x, 3.x only has io.StringIO from below
  10. cStringIO = None
  11. from io import (
  12. StringIO as uStringIO,
  13. open,
  14. )
  15. logging.basicConfig(level=logging.INFO)
  16. from lark.lark import Lark
  17. from lark.common import GrammarError, ParseError
  18. from lark.lexer import LexError
  19. from lark.tree import Tree
  20. __path__ = os.path.dirname(__file__)
  21. def _read(n, *args):
  22. with open(os.path.join(__path__, n), *args) as f:
  23. return f.read()
  24. class TestParsers(unittest.TestCase):
  25. def test_same_ast(self):
  26. "Tests that Earley and LALR parsers produce equal trees"
  27. g = Lark("""start: "(" name_list ("," "*" NAME)? ")"
  28. name_list: NAME | name_list "," NAME
  29. NAME: /\w+/ """, parser='lalr')
  30. l = g.parse('(a,b,c,*x)')
  31. g = Lark("""start: "(" name_list ("," "*" NAME)? ")"
  32. name_list: NAME | name_list "," NAME
  33. NAME: /\w/+ """)
  34. l2 = g.parse('(a,b,c,*x)')
  35. assert l == l2, '%s != %s' % (l.pretty(), l2.pretty())
  36. def test_infinite_recurse(self):
  37. g = """start: a
  38. a: a | "a"
  39. """
  40. self.assertRaises(GrammarError, Lark, g, parser='lalr')
  41. l = Lark(g, parser='earley')
  42. self.assertRaises(ParseError, l.parse, 'a')
  43. class TestEarley(unittest.TestCase):
  44. def test_anon_in_scanless(self):
  45. # Fails an Earley implementation without special handling for empty rules,
  46. # or re-processing of already completed rules.
  47. g = Lark(r"""start: B
  48. B: ("ab"|/[^b]/)*
  49. """, lexer=None)
  50. self.assertEqual( g.parse('abc').children[0], 'abc')
  51. def test_earley_scanless(self):
  52. g = Lark("""start: A "b" c
  53. A: "a"+
  54. c: "abc"
  55. """, parser="earley", lexer=None)
  56. x = g.parse('aaaababc')
  57. def test_earley_scanless2(self):
  58. grammar = """
  59. start: statement+
  60. statement: "r"
  61. | "c" /[a-z]/+
  62. %ignore " "
  63. """
  64. program = """c b r"""
  65. l = Lark(grammar, parser='earley', lexer=None)
  66. l.parse(program)
  67. def test_earley_scanless3(self):
  68. "Tests prioritization and disambiguation for pseudo-terminals (there should be only one result)"
  69. grammar = """
  70. start: A A
  71. A: "a"+
  72. """
  73. l = Lark(grammar, parser='earley', lexer=None)
  74. res = l.parse("aaa")
  75. self.assertEqual(res.children, ['aa', 'a'])
  76. def test_earley_scanless4(self):
  77. grammar = """
  78. start: A A?
  79. A: "a"+
  80. """
  81. l = Lark(grammar, parser='earley', lexer=None)
  82. res = l.parse("aaa")
  83. self.assertEqual(res.children, ['aaa'])
  84. def test_earley_repeating_empty(self):
  85. # This was a sneaky bug!
  86. grammar = """
  87. !start: "a" empty empty "b"
  88. empty: empty2
  89. empty2:
  90. """
  91. parser = Lark(grammar, parser='earley', lexer=None)
  92. res = parser.parse('ab')
  93. empty_tree = Tree('empty', [Tree('empty2', [])])
  94. self.assertSequenceEqual(res.children, ['a', empty_tree, empty_tree, 'b'])
  95. def test_earley_explicit_ambiguity(self):
  96. # This was a sneaky bug!
  97. grammar = """
  98. start: a b | ab
  99. a: "a"
  100. b: "b"
  101. ab: "ab"
  102. """
  103. parser = Lark(grammar, parser='earley', lexer=None, ambiguity='explicit')
  104. res = parser.parse('ab')
  105. self.assertEqual( res.data, '_ambig')
  106. self.assertEqual( len(res.children), 2)
  107. def _make_parser_test(LEXER, PARSER):
  108. def _Lark(grammar, **kwargs):
  109. return Lark(grammar, lexer=LEXER, parser=PARSER, **kwargs)
  110. class _TestParser(unittest.TestCase):
  111. def test_basic1(self):
  112. g = _Lark("""start: a+ b a* "b" a*
  113. b: "b"
  114. a: "a"
  115. """)
  116. r = g.parse('aaabaab')
  117. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  118. r = g.parse('aaabaaba')
  119. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  120. self.assertRaises(ParseError, g.parse, 'aaabaa')
  121. def test_basic2(self):
  122. # Multiple parsers and colliding tokens
  123. g = _Lark("""start: B A
  124. B: "12"
  125. A: "1" """)
  126. g2 = _Lark("""start: B A
  127. B: "12"
  128. A: "2" """)
  129. x = g.parse('121')
  130. assert x.data == 'start' and x.children == ['12', '1'], x
  131. x = g2.parse('122')
  132. assert x.data == 'start' and x.children == ['12', '2'], x
  133. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  134. def test_stringio_bytes(self):
  135. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  136. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  137. def test_stringio_unicode(self):
  138. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  139. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  140. def test_unicode(self):
  141. g = _Lark(u"""start: UNIA UNIB UNIA
  142. UNIA: /\xa3/
  143. UNIB: /\u0101/
  144. """)
  145. g.parse(u'\xa3\u0101\u00a3')
  146. @unittest.skipIf(LEXER is None, "Regexps >1 not supported with scanless parsing")
  147. def test_unicode2(self):
  148. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  149. UNIA: /\xa3/
  150. UNIB: "a\u0101b\ "
  151. UNIC: /a?\u0101c\n/
  152. """)
  153. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  154. def test_unicode3(self):
  155. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  156. UNIA: /\xa3/
  157. UNIB: "\u0101"
  158. UNIC: /\u0203/ /\n/
  159. """)
  160. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  161. def test_stack_for_ebnf(self):
  162. """Verify that stack depth isn't an issue for EBNF grammars"""
  163. g = _Lark(r"""start: a+
  164. a : "a" """)
  165. g.parse("a" * (sys.getrecursionlimit()*2 ))
  166. def test_expand1_lists_with_one_item(self):
  167. g = _Lark(r"""start: list
  168. ?list: item+
  169. item : A
  170. A: "a"
  171. """)
  172. r = g.parse("a")
  173. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  174. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  175. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  176. self.assertEqual(len(r.children), 1)
  177. def test_expand1_lists_with_one_item_2(self):
  178. g = _Lark(r"""start: list
  179. ?list: item+ "!"
  180. item : A
  181. A: "a"
  182. """)
  183. r = g.parse("a!")
  184. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  185. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  186. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  187. self.assertEqual(len(r.children), 1)
  188. def test_dont_expand1_lists_with_multiple_items(self):
  189. g = _Lark(r"""start: list
  190. ?list: item+
  191. item : A
  192. A: "a"
  193. """)
  194. r = g.parse("aa")
  195. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  196. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  197. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  198. self.assertEqual(len(r.children), 1)
  199. # Sanity check: verify that 'list' contains the two 'item's we've given it
  200. [list] = r.children
  201. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  202. def test_dont_expand1_lists_with_multiple_items_2(self):
  203. g = _Lark(r"""start: list
  204. ?list: item+ "!"
  205. item : A
  206. A: "a"
  207. """)
  208. r = g.parse("aa!")
  209. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  210. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  211. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  212. self.assertEqual(len(r.children), 1)
  213. # Sanity check: verify that 'list' contains the two 'item's we've given it
  214. [list] = r.children
  215. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  216. def test_empty_expand1_list(self):
  217. g = _Lark(r"""start: list
  218. ?list: item*
  219. item : A
  220. A: "a"
  221. """)
  222. r = g.parse("")
  223. # 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
  224. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  225. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  226. self.assertEqual(len(r.children), 1)
  227. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  228. [list] = r.children
  229. self.assertSequenceEqual([item.data for item in list.children], ())
  230. def test_empty_expand1_list_2(self):
  231. g = _Lark(r"""start: list
  232. ?list: item* "!"?
  233. item : A
  234. A: "a"
  235. """)
  236. r = g.parse("")
  237. # 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
  238. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  239. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  240. self.assertEqual(len(r.children), 1)
  241. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  242. [list] = r.children
  243. self.assertSequenceEqual([item.data for item in list.children], ())
  244. def test_empty_flatten_list(self):
  245. g = _Lark(r"""start: list
  246. list: | item "," list
  247. item : A
  248. A: "a"
  249. """)
  250. r = g.parse("")
  251. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  252. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  253. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  254. [list] = r.children
  255. self.assertSequenceEqual([item.data for item in list.children], ())
  256. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  257. def test_single_item_flatten_list(self):
  258. g = _Lark(r"""start: list
  259. list: | item "," list
  260. item : A
  261. A: "a"
  262. """)
  263. r = g.parse("a,")
  264. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  265. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  266. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  267. [list] = r.children
  268. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  269. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  270. def test_multiple_item_flatten_list(self):
  271. g = _Lark(r"""start: list
  272. #list: | item "," list
  273. item : A
  274. A: "a"
  275. """)
  276. r = g.parse("a,a,")
  277. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  278. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  279. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  280. [list] = r.children
  281. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  282. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  283. def test_recurse_flatten(self):
  284. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  285. g = _Lark(r"""start: a | start a
  286. a : A
  287. A : "a" """)
  288. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  289. # STree data structures, which uses recursion).
  290. g.parse("a" * (sys.getrecursionlimit() // 4))
  291. def test_token_collision(self):
  292. g = _Lark("""start: "Hello" NAME
  293. NAME: /\w/+
  294. %ignore " "
  295. """)
  296. x = g.parse('Hello World')
  297. self.assertSequenceEqual(x.children, ['World'])
  298. x = g.parse('Hello HelloWorld')
  299. self.assertSequenceEqual(x.children, ['HelloWorld'])
  300. # def test_string_priority(self):
  301. # g = _Lark("""start: (A | /a?bb/)+
  302. # A: "a" """)
  303. # x = g.parse('abb')
  304. # self.assertEqual(len(x.children), 2)
  305. # # This parse raises an exception because the lexer will always try to consume
  306. # # "a" first and will never match the regular expression
  307. # # This behavior is subject to change!!
  308. # # Thie won't happen with ambiguity handling.
  309. # g = _Lark("""start: (A | /a?ab/)+
  310. # A: "a" """)
  311. # self.assertRaises(LexError, g.parse, 'aab')
  312. def test_undefined_rule(self):
  313. self.assertRaises(GrammarError, _Lark, """start: a""")
  314. def test_undefined_token(self):
  315. self.assertRaises(GrammarError, _Lark, """start: A""")
  316. def test_rule_collision(self):
  317. g = _Lark("""start: "a"+ "b"
  318. | "a"+ """)
  319. x = g.parse('aaaa')
  320. x = g.parse('aaaab')
  321. def test_rule_collision2(self):
  322. g = _Lark("""start: "a"* "b"
  323. | "a"+ """)
  324. x = g.parse('aaaa')
  325. x = g.parse('aaaab')
  326. x = g.parse('b')
  327. @unittest.skipIf(LEXER is None, "Regexps >1 not supported with scanless parsing")
  328. def test_regex_embed(self):
  329. g = _Lark("""start: A B C
  330. A: /a/
  331. B: /${A}b/
  332. C: /${B}c/
  333. """)
  334. x = g.parse('aababc')
  335. def test_token_embed(self):
  336. g = _Lark("""start: A B C
  337. A: "a"
  338. B: A "b"
  339. C: B "c"
  340. """)
  341. x = g.parse('aababc')
  342. @unittest.skipIf(LEXER is None, "Known bug with scanless parsing") # TODO
  343. def test_token_not_anon(self):
  344. """Tests that "a" is matched as A, rather than an anonymous token.
  345. That means that "a" is not filtered out, despite being an 'immediate string'.
  346. Whether or not this is the intuitive behavior, I'm not sure yet.
  347. Perhaps the right thing to do is report a collision (if such is relevant)
  348. -Erez
  349. """
  350. g = _Lark("""start: "a"
  351. A: "a" """)
  352. x = g.parse('a')
  353. self.assertEqual(len(x.children), 1, '"a" should not be considered anonymous')
  354. self.assertEqual(x.children[0].type, "A")
  355. g = _Lark("""start: /a/
  356. A: /a/ """)
  357. x = g.parse('a')
  358. self.assertEqual(len(x.children), 1, '/a/ should not be considered anonymous')
  359. self.assertEqual(x.children[0].type, "A")
  360. def test_maybe(self):
  361. g = _Lark("""start: ["a"] """)
  362. x = g.parse('a')
  363. x = g.parse('')
  364. def test_start(self):
  365. g = _Lark("""a: "a" a? """, start='a')
  366. x = g.parse('a')
  367. x = g.parse('aa')
  368. x = g.parse('aaa')
  369. def test_alias(self):
  370. g = _Lark("""start: "a" -> b """)
  371. x = g.parse('a')
  372. self.assertEqual(x.data, "b")
  373. def test_token_ebnf(self):
  374. g = _Lark("""start: A
  375. A: "a"* ("b"? "c".."e")+
  376. """)
  377. x = g.parse('abcde')
  378. x = g.parse('dd')
  379. def test_backslash(self):
  380. g = _Lark(r"""start: "\\" "a"
  381. """)
  382. x = g.parse(r'\a')
  383. g = _Lark(r"""start: /\\\\/ /a/
  384. """)
  385. x = g.parse(r'\a')
  386. def test_special_chars(self):
  387. g = _Lark(r"""start: "\n"
  388. """)
  389. x = g.parse('\n')
  390. g = _Lark(r"""start: /\n/
  391. """)
  392. x = g.parse('\n')
  393. def test_backslash2(self):
  394. g = _Lark(r"""start: "\"" "-"
  395. """)
  396. x = g.parse('"-')
  397. g = _Lark(r"""start: /\// /-/
  398. """)
  399. x = g.parse('/-')
  400. # def test_token_recurse(self):
  401. # g = _Lark("""start: A
  402. # A: B
  403. # B: A
  404. # """)
  405. def test_empty(self):
  406. # Fails an Earley implementation without special handling for empty rules,
  407. # or re-processing of already completed rules.
  408. g = _Lark(r"""start: _empty a "B"
  409. a: _empty "A"
  410. _empty:
  411. """)
  412. x = g.parse('AB')
  413. def test_lexer_token_limit(self):
  414. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  415. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  416. g = _Lark("""start: %s
  417. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  418. def test_float_without_lexer(self):
  419. g = _Lark("""start: ["+"|"-"] float
  420. float: digit* "." digit+ exp?
  421. | digit+ exp
  422. exp: ("e"|"E") ["+"|"-"] digit+
  423. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  424. """)
  425. g.parse("1.2")
  426. g.parse("-.2e9")
  427. g.parse("+2e-9")
  428. self.assertRaises(ParseError, g.parse, "+2e-9e")
  429. def test_token_flags(self):
  430. l = _Lark("""!start: "a"i+
  431. """
  432. )
  433. tree = l.parse('aA')
  434. self.assertEqual(tree.children, ['a', 'A'])
  435. l = _Lark("""!start: /a/i+
  436. """
  437. )
  438. tree = l.parse('aA')
  439. self.assertEqual(tree.children, ['a', 'A'])
  440. g = """!start: "a"i "a"
  441. """
  442. self.assertRaises(GrammarError, _Lark, g)
  443. g = """!start: /a/i /a/
  444. """
  445. self.assertRaises(GrammarError, _Lark, g)
  446. g = """start: NAME "," "a"
  447. NAME: /[a-z_]/i /[a-z0-9_]/i*
  448. """
  449. l = _Lark(g)
  450. tree = l.parse('ab,a')
  451. self.assertEqual(tree.children, ['ab'])
  452. tree = l.parse('AB,a')
  453. self.assertEqual(tree.children, ['AB'])
  454. def test_token_flags3(self):
  455. l = _Lark("""!start: ABC+
  456. ABC: "abc"i
  457. """
  458. )
  459. tree = l.parse('aBcAbC')
  460. self.assertEqual(tree.children, ['aBc', 'AbC'])
  461. def test_token_flags2(self):
  462. g = """!start: ("a"i | /a/ /b/?)+
  463. """
  464. l = _Lark(g)
  465. tree = l.parse('aA')
  466. self.assertEqual(tree.children, ['a', 'A'])
  467. def test_reduce_cycle(self):
  468. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  469. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  470. """
  471. l = _Lark("""
  472. term: A
  473. | term term
  474. A: "a"
  475. """, start='term')
  476. tree = l.parse("aa")
  477. self.assertEqual(len(tree.children), 2)
  478. _NAME = "Test" + PARSER.capitalize() + (LEXER or 'Scanless').capitalize()
  479. _TestParser.__name__ = _NAME
  480. globals()[_NAME] = _TestParser
  481. _TO_TEST = [
  482. ('standard', 'earley'),
  483. ('standard', 'lalr'),
  484. ('contextual', 'lalr'),
  485. (None, 'earley'),
  486. ]
  487. for LEXER, PARSER in _TO_TEST:
  488. _make_parser_test(LEXER, PARSER)
  489. if __name__ == '__main__':
  490. unittest.main()