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.

427 lines
16 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. __path__ = os.path.dirname(__file__)
  20. def _read(n, *args):
  21. with open(os.path.join(__path__, n), *args) as f:
  22. return f.read()
  23. class TestParsers(unittest.TestCase):
  24. def test_same_ast(self):
  25. "Tests that Earley and LALR parsers produce equal trees"
  26. g = Lark("""start: "(" name_list ("," "*" NAME)? ")"
  27. name_list: NAME | name_list "," NAME
  28. NAME: /\w+/ """, parser='lalr')
  29. l = g.parse('(a,b,c,*x)')
  30. g = Lark("""start: "(" name_list ("," "*" NAME)? ")"
  31. name_list: NAME | name_list "," NAME
  32. NAME: /\w+/ """)
  33. l2 = g.parse('(a,b,c,*x)')
  34. assert l == l2, '%s != %s' % (l.pretty(), l2.pretty())
  35. def test_earley_nolex(self):
  36. g = Lark("""start: A "b" c
  37. A: "a"+
  38. c: "abc"
  39. """, parser="earley", lexer=None)
  40. x = g.parse('aaaababc')
  41. class TestEarley(unittest.TestCase):
  42. pass
  43. def _make_parser_test(LEXER, PARSER):
  44. def _Lark(grammar, **kwargs):
  45. return Lark(grammar, lexer=LEXER, parser=PARSER, **kwargs)
  46. class _TestParser(unittest.TestCase):
  47. def test_basic1(self):
  48. g = _Lark("""start: a+ b a* "b" a*
  49. b: "b"
  50. a: "a"
  51. """)
  52. r = g.parse('aaabaab')
  53. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  54. r = g.parse('aaabaaba')
  55. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  56. self.assertRaises(ParseError, g.parse, 'aaabaa')
  57. def test_basic2(self):
  58. # Multiple parsers and colliding tokens
  59. g = _Lark("""start: B A
  60. B: "12"
  61. A: "1" """)
  62. g2 = _Lark("""start: B A
  63. B: "12"
  64. A: "2" """)
  65. x = g.parse('121')
  66. assert x.data == 'start' and x.children == ['12', '1'], x
  67. x = g2.parse('122')
  68. assert x.data == 'start' and x.children == ['12', '2'], x
  69. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  70. def test_stringio_bytes(self):
  71. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  72. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  73. def test_stringio_unicode(self):
  74. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  75. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  76. def test_unicode(self):
  77. g = _Lark(u"""start: UNIA UNIB UNIA
  78. UNIA: /\xa3/
  79. UNIB: /\u0101/
  80. """)
  81. g.parse(u'\xa3\u0101\u00a3')
  82. def test_unicode2(self):
  83. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  84. UNIA: /\xa3/
  85. UNIB: "a\u0101b\ "
  86. UNIC: /a?\u0101c\n/
  87. """)
  88. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  89. def test_recurse_expansion(self):
  90. """Verify that stack depth doesn't get exceeded on recursive rules marked for expansion."""
  91. g = _Lark(r"""start: a | start a
  92. a : "a" """)
  93. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  94. # STree data structures, which uses recursion).
  95. g.parse("a" * (sys.getrecursionlimit() // 4))
  96. def test_expand1_lists_with_one_item(self):
  97. g = _Lark(r"""start: list
  98. ?list: item+
  99. item : A
  100. A: "a"
  101. """)
  102. r = g.parse("a")
  103. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  104. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  105. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  106. self.assertEqual(len(r.children), 1)
  107. def test_expand1_lists_with_one_item_2(self):
  108. g = _Lark(r"""start: list
  109. ?list: item+ "!"
  110. item : A
  111. A: "a"
  112. """)
  113. r = g.parse("a!")
  114. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  115. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  116. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  117. self.assertEqual(len(r.children), 1)
  118. def test_dont_expand1_lists_with_multiple_items(self):
  119. g = _Lark(r"""start: list
  120. ?list: item+
  121. item : A
  122. A: "a"
  123. """)
  124. r = g.parse("aa")
  125. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  126. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  127. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  128. self.assertEqual(len(r.children), 1)
  129. # Sanity check: verify that 'list' contains the two 'item's we've given it
  130. [list] = r.children
  131. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  132. def test_dont_expand1_lists_with_multiple_items_2(self):
  133. g = _Lark(r"""start: list
  134. ?list: item+ "!"
  135. item : A
  136. A: "a"
  137. """)
  138. r = g.parse("aa!")
  139. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  140. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  141. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  142. self.assertEqual(len(r.children), 1)
  143. # Sanity check: verify that 'list' contains the two 'item's we've given it
  144. [list] = r.children
  145. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  146. def test_empty_expand1_list(self):
  147. g = _Lark(r"""start: list
  148. ?list: item*
  149. item : A
  150. A: "a"
  151. """)
  152. r = g.parse("")
  153. # 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
  154. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  155. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  156. self.assertEqual(len(r.children), 1)
  157. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  158. [list] = r.children
  159. self.assertSequenceEqual([item.data for item in list.children], ())
  160. def test_empty_expand1_list_2(self):
  161. g = _Lark(r"""start: list
  162. ?list: item* "!"?
  163. item : A
  164. A: "a"
  165. """)
  166. r = g.parse("")
  167. # 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
  168. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  169. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  170. self.assertEqual(len(r.children), 1)
  171. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  172. [list] = r.children
  173. self.assertSequenceEqual([item.data for item in list.children], ())
  174. def test_empty_flatten_list(self):
  175. g = _Lark(r"""start: list
  176. list: | item "," list
  177. item : A
  178. A: "a"
  179. """)
  180. r = g.parse("")
  181. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  182. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  183. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  184. [list] = r.children
  185. self.assertSequenceEqual([item.data for item in list.children], ())
  186. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  187. def test_single_item_flatten_list(self):
  188. g = _Lark(r"""start: list
  189. list: | item "," list
  190. item : A
  191. A: "a"
  192. """)
  193. r = g.parse("a,")
  194. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  195. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  196. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  197. [list] = r.children
  198. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  199. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  200. def test_multiple_item_flatten_list(self):
  201. g = _Lark(r"""start: list
  202. #list: | item "," list
  203. item : A
  204. A: "a"
  205. """)
  206. r = g.parse("a,a,")
  207. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  208. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  209. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  210. [list] = r.children
  211. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  212. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  213. def test_recurse_flatten(self):
  214. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  215. g = _Lark(r"""start: a | start a
  216. a : A
  217. A : "a" """)
  218. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  219. # STree data structures, which uses recursion).
  220. g.parse("a" * (sys.getrecursionlimit() // 4))
  221. def test_token_collision(self):
  222. g = _Lark("""start: "Hello" NAME
  223. NAME: /\w+/
  224. %ignore " "
  225. """)
  226. x = g.parse('Hello World')
  227. self.assertSequenceEqual(x.children, ['World'])
  228. x = g.parse('Hello HelloWorld')
  229. self.assertSequenceEqual(x.children, ['HelloWorld'])
  230. # def test_string_priority(self):
  231. # g = _Lark("""start: (A | /a?bb/)+
  232. # A: "a" """)
  233. # x = g.parse('abb')
  234. # self.assertEqual(len(x.children), 2)
  235. # # This parse raises an exception because the lexer will always try to consume
  236. # # "a" first and will never match the regular expression
  237. # # This behavior is subject to change!!
  238. # # Thie won't happen with ambiguity handling.
  239. # g = _Lark("""start: (A | /a?ab/)+
  240. # A: "a" """)
  241. # self.assertRaises(LexError, g.parse, 'aab')
  242. def test_undefined_rule(self):
  243. self.assertRaises(GrammarError, _Lark, """start: a""")
  244. def test_undefined_token(self):
  245. self.assertRaises(GrammarError, _Lark, """start: A""")
  246. def test_rule_collision(self):
  247. g = _Lark("""start: "a"+ "b"
  248. | "a"+ """)
  249. x = g.parse('aaaa')
  250. x = g.parse('aaaab')
  251. def test_rule_collision2(self):
  252. g = _Lark("""start: "a"* "b"
  253. | "a"+ """)
  254. x = g.parse('aaaa')
  255. x = g.parse('aaaab')
  256. x = g.parse('b')
  257. def test_regex_embed(self):
  258. g = _Lark("""start: A B C
  259. A: /a/
  260. B: /${A}b/
  261. C: /${B}c/
  262. """)
  263. x = g.parse('aababc')
  264. def test_token_embed(self):
  265. g = _Lark("""start: A B C
  266. A: "a"
  267. B: A "b"
  268. C: B "c"
  269. """)
  270. x = g.parse('aababc')
  271. def test_token_not_anon(self):
  272. """Tests that "a" is matched as A, rather than an anonymous token.
  273. That means that "a" is not filtered out, despite being an 'immediate string'.
  274. Whether or not this is the intuitive behavior, I'm not sure yet.
  275. Perhaps the right thing to do is report a collision (if such is relevant)
  276. -Erez
  277. """
  278. g = _Lark("""start: "a"
  279. A: "a" """)
  280. x = g.parse('a')
  281. self.assertEqual(len(x.children), 1, '"a" should not be considered anonymous')
  282. self.assertEqual(x.children[0].type, "A")
  283. g = _Lark("""start: /a/
  284. A: /a/ """)
  285. x = g.parse('a')
  286. self.assertEqual(len(x.children), 1, '/a/ should not be considered anonymous')
  287. self.assertEqual(x.children[0].type, "A")
  288. def test_maybe(self):
  289. g = _Lark("""start: ["a"] """)
  290. x = g.parse('a')
  291. x = g.parse('')
  292. def test_start(self):
  293. g = _Lark("""a: "a" a? """, start='a')
  294. x = g.parse('a')
  295. x = g.parse('aa')
  296. x = g.parse('aaa')
  297. def test_alias(self):
  298. g = _Lark("""start: "a" -> b """)
  299. x = g.parse('a')
  300. self.assertEqual(x.data, "b")
  301. def test_token_ebnf(self):
  302. g = _Lark("""start: A
  303. A: "a"* ("b"? "c".."e")+
  304. """)
  305. x = g.parse('abcde')
  306. x = g.parse('dd')
  307. # def test_token_recurse(self):
  308. # g = _Lark("""start: A
  309. # A: B
  310. # B: A
  311. # """)
  312. def test_lexer_token_limit(self):
  313. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  314. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  315. g = _Lark("""start: %s
  316. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  317. def test_float_without_lexer(self):
  318. g = _Lark("""start: ["+"|"-"] float
  319. float: digit* "." digit+ exp?
  320. | digit+ exp
  321. exp: ("e"|"E") ["+"|"-"] digit+
  322. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  323. """)
  324. g.parse("1.2")
  325. g.parse("-.2e9")
  326. g.parse("+2e-9")
  327. self.assertRaises(ParseError, g.parse, "+2e-9e")
  328. _NAME = "Test" + PARSER.capitalize() + (LEXER or 'None').capitalize()
  329. _TestParser.__name__ = _NAME
  330. globals()[_NAME] = _TestParser
  331. _TO_TEST = [
  332. ('standard', 'earley'),
  333. ('standard', 'lalr'),
  334. ('contextual', 'lalr'),
  335. ]
  336. for LEXER, PARSER in _TO_TEST:
  337. _make_parser_test(LEXER, PARSER)
  338. if __name__ == '__main__':
  339. unittest.main()