This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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