This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 

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