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.
 
 

582 line
21 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 _make_parser_test(LEXER, PARSER):
  96. def _Lark(grammar, **kwargs):
  97. return Lark(grammar, lexer=LEXER, parser=PARSER, **kwargs)
  98. class _TestParser(unittest.TestCase):
  99. def test_basic1(self):
  100. g = _Lark("""start: a+ b a* "b" a*
  101. b: "b"
  102. a: "a"
  103. """)
  104. r = g.parse('aaabaab')
  105. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  106. r = g.parse('aaabaaba')
  107. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  108. self.assertRaises(ParseError, g.parse, 'aaabaa')
  109. def test_basic2(self):
  110. # Multiple parsers and colliding tokens
  111. g = _Lark("""start: B A
  112. B: "12"
  113. A: "1" """)
  114. g2 = _Lark("""start: B A
  115. B: "12"
  116. A: "2" """)
  117. x = g.parse('121')
  118. assert x.data == 'start' and x.children == ['12', '1'], x
  119. x = g2.parse('122')
  120. assert x.data == 'start' and x.children == ['12', '2'], x
  121. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  122. def test_stringio_bytes(self):
  123. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  124. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  125. def test_stringio_unicode(self):
  126. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  127. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  128. def test_unicode(self):
  129. g = _Lark(u"""start: UNIA UNIB UNIA
  130. UNIA: /\xa3/
  131. UNIB: /\u0101/
  132. """)
  133. g.parse(u'\xa3\u0101\u00a3')
  134. @unittest.skipIf(LEXER is None, "Regexps >1 not supported with scanless parsing")
  135. def test_unicode2(self):
  136. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  137. UNIA: /\xa3/
  138. UNIB: "a\u0101b\ "
  139. UNIC: /a?\u0101c\n/
  140. """)
  141. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  142. def test_unicode3(self):
  143. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  144. UNIA: /\xa3/
  145. UNIB: "\u0101"
  146. UNIC: /\u0203/ /\n/
  147. """)
  148. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  149. def test_stack_for_ebnf(self):
  150. """Verify that stack depth isn't an issue for EBNF grammars"""
  151. g = _Lark(r"""start: a+
  152. a : "a" """)
  153. g.parse("a" * (sys.getrecursionlimit()*2 ))
  154. def test_expand1_lists_with_one_item(self):
  155. g = _Lark(r"""start: list
  156. ?list: item+
  157. item : A
  158. A: "a"
  159. """)
  160. r = g.parse("a")
  161. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  162. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  163. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  164. self.assertEqual(len(r.children), 1)
  165. def test_expand1_lists_with_one_item_2(self):
  166. g = _Lark(r"""start: list
  167. ?list: item+ "!"
  168. item : A
  169. A: "a"
  170. """)
  171. r = g.parse("a!")
  172. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  173. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  174. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  175. self.assertEqual(len(r.children), 1)
  176. def test_dont_expand1_lists_with_multiple_items(self):
  177. g = _Lark(r"""start: list
  178. ?list: item+
  179. item : A
  180. A: "a"
  181. """)
  182. r = g.parse("aa")
  183. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  184. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  185. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  186. self.assertEqual(len(r.children), 1)
  187. # Sanity check: verify that 'list' contains the two 'item's we've given it
  188. [list] = r.children
  189. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  190. def test_dont_expand1_lists_with_multiple_items_2(self):
  191. g = _Lark(r"""start: list
  192. ?list: item+ "!"
  193. item : A
  194. A: "a"
  195. """)
  196. r = g.parse("aa!")
  197. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  198. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  199. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  200. self.assertEqual(len(r.children), 1)
  201. # Sanity check: verify that 'list' contains the two 'item's we've given it
  202. [list] = r.children
  203. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  204. def test_empty_expand1_list(self):
  205. g = _Lark(r"""start: list
  206. ?list: item*
  207. item : A
  208. A: "a"
  209. """)
  210. r = g.parse("")
  211. # 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
  212. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  213. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  214. self.assertEqual(len(r.children), 1)
  215. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  216. [list] = r.children
  217. self.assertSequenceEqual([item.data for item in list.children], ())
  218. def test_empty_expand1_list_2(self):
  219. g = _Lark(r"""start: list
  220. ?list: item* "!"?
  221. item : A
  222. A: "a"
  223. """)
  224. r = g.parse("")
  225. # 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
  226. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  227. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  228. self.assertEqual(len(r.children), 1)
  229. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  230. [list] = r.children
  231. self.assertSequenceEqual([item.data for item in list.children], ())
  232. def test_empty_flatten_list(self):
  233. g = _Lark(r"""start: list
  234. list: | item "," list
  235. item : A
  236. A: "a"
  237. """)
  238. r = g.parse("")
  239. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  240. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  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. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  245. def test_single_item_flatten_list(self):
  246. g = _Lark(r"""start: list
  247. list: | item "," list
  248. item : A
  249. A: "a"
  250. """)
  251. r = g.parse("a,")
  252. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  253. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  254. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  255. [list] = r.children
  256. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  257. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  258. def test_multiple_item_flatten_list(self):
  259. g = _Lark(r"""start: list
  260. #list: | item "," list
  261. item : A
  262. A: "a"
  263. """)
  264. r = g.parse("a,a,")
  265. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  266. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  267. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  268. [list] = r.children
  269. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  270. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  271. def test_recurse_flatten(self):
  272. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  273. g = _Lark(r"""start: a | start a
  274. a : A
  275. A : "a" """)
  276. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  277. # STree data structures, which uses recursion).
  278. g.parse("a" * (sys.getrecursionlimit() // 4))
  279. def test_token_collision(self):
  280. g = _Lark("""start: "Hello" NAME
  281. NAME: /\w/+
  282. %ignore " "
  283. """)
  284. x = g.parse('Hello World')
  285. self.assertSequenceEqual(x.children, ['World'])
  286. x = g.parse('Hello HelloWorld')
  287. self.assertSequenceEqual(x.children, ['HelloWorld'])
  288. # def test_string_priority(self):
  289. # g = _Lark("""start: (A | /a?bb/)+
  290. # A: "a" """)
  291. # x = g.parse('abb')
  292. # self.assertEqual(len(x.children), 2)
  293. # # This parse raises an exception because the lexer will always try to consume
  294. # # "a" first and will never match the regular expression
  295. # # This behavior is subject to change!!
  296. # # Thie won't happen with ambiguity handling.
  297. # g = _Lark("""start: (A | /a?ab/)+
  298. # A: "a" """)
  299. # self.assertRaises(LexError, g.parse, 'aab')
  300. def test_undefined_rule(self):
  301. self.assertRaises(GrammarError, _Lark, """start: a""")
  302. def test_undefined_token(self):
  303. self.assertRaises(GrammarError, _Lark, """start: A""")
  304. def test_rule_collision(self):
  305. g = _Lark("""start: "a"+ "b"
  306. | "a"+ """)
  307. x = g.parse('aaaa')
  308. x = g.parse('aaaab')
  309. def test_rule_collision2(self):
  310. g = _Lark("""start: "a"* "b"
  311. | "a"+ """)
  312. x = g.parse('aaaa')
  313. x = g.parse('aaaab')
  314. x = g.parse('b')
  315. @unittest.skipIf(LEXER is None, "Regexps >1 not supported with scanless parsing")
  316. def test_regex_embed(self):
  317. g = _Lark("""start: A B C
  318. A: /a/
  319. B: /${A}b/
  320. C: /${B}c/
  321. """)
  322. x = g.parse('aababc')
  323. def test_token_embed(self):
  324. g = _Lark("""start: A B C
  325. A: "a"
  326. B: A "b"
  327. C: B "c"
  328. """)
  329. x = g.parse('aababc')
  330. def test_token_not_anon(self):
  331. """Tests that "a" is matched as A, rather than an anonymous token.
  332. That means that "a" is not filtered out, despite being an 'immediate string'.
  333. Whether or not this is the intuitive behavior, I'm not sure yet.
  334. Perhaps the right thing to do is report a collision (if such is relevant)
  335. -Erez
  336. """
  337. g = _Lark("""start: "a"
  338. A: "a" """)
  339. x = g.parse('a')
  340. self.assertEqual(len(x.children), 1, '"a" should not be considered anonymous')
  341. self.assertEqual(x.children[0].type, "A")
  342. g = _Lark("""start: /a/
  343. A: /a/ """)
  344. x = g.parse('a')
  345. self.assertEqual(len(x.children), 1, '/a/ should not be considered anonymous')
  346. self.assertEqual(x.children[0].type, "A")
  347. def test_maybe(self):
  348. g = _Lark("""start: ["a"] """)
  349. x = g.parse('a')
  350. x = g.parse('')
  351. def test_start(self):
  352. g = _Lark("""a: "a" a? """, start='a')
  353. x = g.parse('a')
  354. x = g.parse('aa')
  355. x = g.parse('aaa')
  356. def test_alias(self):
  357. g = _Lark("""start: "a" -> b """)
  358. x = g.parse('a')
  359. self.assertEqual(x.data, "b")
  360. def test_token_ebnf(self):
  361. g = _Lark("""start: A
  362. A: "a"* ("b"? "c".."e")+
  363. """)
  364. x = g.parse('abcde')
  365. x = g.parse('dd')
  366. def test_backslash(self):
  367. g = _Lark(r"""start: "\\" "a"
  368. """)
  369. x = g.parse(r'\a')
  370. g = _Lark(r"""start: /\\\\/ /a/
  371. """)
  372. x = g.parse(r'\a')
  373. def test_special_chars(self):
  374. g = _Lark(r"""start: "\n"
  375. """)
  376. x = g.parse('\n')
  377. g = _Lark(r"""start: /\n/
  378. """)
  379. x = g.parse('\n')
  380. def test_backslash2(self):
  381. g = _Lark(r"""start: "\"" "-"
  382. """)
  383. x = g.parse('"-')
  384. g = _Lark(r"""start: /\// /-/
  385. """)
  386. x = g.parse('/-')
  387. # def test_token_recurse(self):
  388. # g = _Lark("""start: A
  389. # A: B
  390. # B: A
  391. # """)
  392. def test_empty(self):
  393. # Fails an Earley implementation without special handling for empty rules,
  394. # or re-processing of already completed rules.
  395. g = _Lark(r"""start: _empty a "B"
  396. a: _empty "A"
  397. _empty:
  398. """)
  399. x = g.parse('AB')
  400. def test_lexer_token_limit(self):
  401. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  402. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  403. g = _Lark("""start: %s
  404. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  405. def test_float_without_lexer(self):
  406. g = _Lark("""start: ["+"|"-"] float
  407. float: digit* "." digit+ exp?
  408. | digit+ exp
  409. exp: ("e"|"E") ["+"|"-"] digit+
  410. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  411. """)
  412. g.parse("1.2")
  413. g.parse("-.2e9")
  414. g.parse("+2e-9")
  415. self.assertRaises(ParseError, g.parse, "+2e-9e")
  416. def test_token_flags(self):
  417. l = _Lark("""!start: "a"i+
  418. """
  419. )
  420. tree = l.parse('aA')
  421. self.assertEqual(tree.children, ['a', 'A'])
  422. l = _Lark("""!start: /a/i+
  423. """
  424. )
  425. tree = l.parse('aA')
  426. self.assertEqual(tree.children, ['a', 'A'])
  427. g = """!start: "a"i "a"
  428. """
  429. self.assertRaises(GrammarError, _Lark, g)
  430. g = """!start: /a/i /a/
  431. """
  432. self.assertRaises(GrammarError, _Lark, g)
  433. g = """start: NAME "," "a"
  434. NAME: /[a-z_]/i /[a-z0-9_]/i*
  435. """
  436. l = _Lark(g)
  437. tree = l.parse('ab,a')
  438. self.assertEqual(tree.children, ['ab'])
  439. tree = l.parse('AB,a')
  440. self.assertEqual(tree.children, ['AB'])
  441. def test_token_flags2(self):
  442. g = """!start: ("a"i | /a/ /b/?)+
  443. """
  444. l = _Lark(g)
  445. tree = l.parse('aA')
  446. self.assertEqual(tree.children, ['a', 'A'])
  447. _NAME = "Test" + PARSER.capitalize() + (LEXER or 'Scanless').capitalize()
  448. _TestParser.__name__ = _NAME
  449. globals()[_NAME] = _TestParser
  450. _TO_TEST = [
  451. ('standard', 'earley'),
  452. ('standard', 'lalr'),
  453. ('contextual', 'lalr'),
  454. (None, 'earley'),
  455. ]
  456. for LEXER, PARSER in _TO_TEST:
  457. _make_parser_test(LEXER, PARSER)
  458. if __name__ == '__main__':
  459. unittest.main()