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.

1957 lines
67 KiB

  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import
  3. import re
  4. import unittest
  5. import logging
  6. import os
  7. import sys
  8. from copy import copy, deepcopy
  9. from lark.utils import Py36, isascii
  10. from lark import Token
  11. try:
  12. from cStringIO import StringIO as cStringIO
  13. except ImportError:
  14. # Available only in Python 2.x, 3.x only has io.StringIO from below
  15. cStringIO = None
  16. from io import (
  17. StringIO as uStringIO,
  18. BytesIO,
  19. open,
  20. )
  21. logging.basicConfig(level=logging.INFO)
  22. try:
  23. import regex
  24. except ImportError:
  25. regex = None
  26. from lark.lark import Lark
  27. from lark.exceptions import GrammarError, ParseError, UnexpectedToken, UnexpectedInput, UnexpectedCharacters
  28. from lark.tree import Tree
  29. from lark.visitors import Transformer, Transformer_InPlace, v_args
  30. from lark.grammar import Rule
  31. from lark.lexer import TerminalDef, Lexer, TraditionalLexer
  32. __path__ = os.path.dirname(__file__)
  33. def _read(n, *args):
  34. with open(os.path.join(__path__, n), *args) as f:
  35. return f.read()
  36. class TestParsers(unittest.TestCase):
  37. def test_big_list(self):
  38. Lark(r"""
  39. start: {}
  40. """.format(
  41. "|".join(['"%s"'%i for i in range(250)])
  42. ))
  43. def test_same_ast(self):
  44. "Tests that Earley and LALR parsers produce equal trees"
  45. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  46. name_list: NAME | name_list "," NAME
  47. NAME: /\w+/ """, parser='lalr')
  48. l = g.parse('(a,b,c,*x)')
  49. g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")"
  50. name_list: NAME | name_list "," NAME
  51. NAME: /\w/+ """)
  52. l2 = g.parse('(a,b,c,*x)')
  53. assert l == l2, '%s != %s' % (l.pretty(), l2.pretty())
  54. def test_infinite_recurse(self):
  55. g = """start: a
  56. a: a | "a"
  57. """
  58. self.assertRaises(GrammarError, Lark, g, parser='lalr')
  59. # TODO: should it? shouldn't it?
  60. # l = Lark(g, parser='earley', lexer='dynamic')
  61. # self.assertRaises(ParseError, l.parse, 'a')
  62. def test_propagate_positions(self):
  63. g = Lark("""start: a
  64. a: "a"
  65. """, propagate_positions=True)
  66. r = g.parse('a')
  67. self.assertEqual( r.children[0].meta.line, 1 )
  68. g = Lark("""start: x
  69. x: a
  70. a: "a"
  71. """, propagate_positions=True)
  72. r = g.parse('a')
  73. self.assertEqual( r.children[0].meta.line, 1 )
  74. def test_expand1(self):
  75. g = Lark("""start: a
  76. ?a: b
  77. b: "x"
  78. """)
  79. r = g.parse('x')
  80. self.assertEqual( r.children[0].data, "b" )
  81. g = Lark("""start: a
  82. ?a: b -> c
  83. b: "x"
  84. """)
  85. r = g.parse('x')
  86. self.assertEqual( r.children[0].data, "c" )
  87. g = Lark("""start: a
  88. ?a: B -> c
  89. B: "x"
  90. """)
  91. self.assertEqual( r.children[0].data, "c" )
  92. g = Lark("""start: a
  93. ?a: b b -> c
  94. b: "x"
  95. """)
  96. r = g.parse('xx')
  97. self.assertEqual( r.children[0].data, "c" )
  98. def test_comment_in_rule_definition(self):
  99. g = Lark("""start: a
  100. a: "a"
  101. // A comment
  102. // Another comment
  103. | "b"
  104. // Still more
  105. c: "unrelated"
  106. """)
  107. r = g.parse('b')
  108. self.assertEqual( r.children[0].data, "a" )
  109. def test_visit_tokens(self):
  110. class T(Transformer):
  111. def a(self, children):
  112. return children[0] + "!"
  113. def A(self, tok):
  114. return tok.update(value=tok.upper())
  115. # Test regular
  116. g = """start: a
  117. a : A
  118. A: "x"
  119. """
  120. p = Lark(g, parser='lalr')
  121. r = T(False).transform(p.parse("x"))
  122. self.assertEqual( r.children, ["x!"] )
  123. r = T().transform(p.parse("x"))
  124. self.assertEqual( r.children, ["X!"] )
  125. # Test internal transformer
  126. p = Lark(g, parser='lalr', transformer=T())
  127. r = p.parse("x")
  128. self.assertEqual( r.children, ["X!"] )
  129. def test_vargs_meta(self):
  130. @v_args(meta=True)
  131. class T1(Transformer):
  132. def a(self, children, meta):
  133. assert not children
  134. return meta.line
  135. def start(self, children, meta):
  136. return children
  137. @v_args(meta=True, inline=True)
  138. class T2(Transformer):
  139. def a(self, meta):
  140. return meta.line
  141. def start(self, meta, *res):
  142. return list(res)
  143. for T in (T1, T2):
  144. for internal in [False, True]:
  145. try:
  146. g = Lark(r"""start: a+
  147. a : "x" _NL?
  148. _NL: /\n/+
  149. """, parser='lalr', transformer=T() if internal else None, propagate_positions=True)
  150. except NotImplementedError:
  151. assert internal
  152. continue
  153. res = g.parse("xx\nx\nxxx\n\n\nxx")
  154. assert not internal
  155. res = T().transform(res)
  156. self.assertEqual(res, [1, 1, 2, 3, 3, 3, 6, 6])
  157. def test_vargs_tree(self):
  158. tree = Lark('''
  159. start: a a a
  160. !a: "A"
  161. ''').parse('AAA')
  162. tree_copy = deepcopy(tree)
  163. @v_args(tree=True)
  164. class T(Transformer):
  165. def a(self, tree):
  166. return 1
  167. def start(self, tree):
  168. return tree.children
  169. res = T().transform(tree)
  170. self.assertEqual(res, [1, 1, 1])
  171. self.assertEqual(tree, tree_copy)
  172. def test_embedded_transformer(self):
  173. class T(Transformer):
  174. def a(self, children):
  175. return "<a>"
  176. def b(self, children):
  177. return "<b>"
  178. def c(self, children):
  179. return "<c>"
  180. # Test regular
  181. g = Lark("""start: a
  182. a : "x"
  183. """, parser='lalr')
  184. r = T().transform(g.parse("x"))
  185. self.assertEqual( r.children, ["<a>"] )
  186. g = Lark("""start: a
  187. a : "x"
  188. """, parser='lalr', transformer=T())
  189. r = g.parse("x")
  190. self.assertEqual( r.children, ["<a>"] )
  191. # Test Expand1
  192. g = Lark("""start: a
  193. ?a : b
  194. b : "x"
  195. """, parser='lalr')
  196. r = T().transform(g.parse("x"))
  197. self.assertEqual( r.children, ["<b>"] )
  198. g = Lark("""start: a
  199. ?a : b
  200. b : "x"
  201. """, parser='lalr', transformer=T())
  202. r = g.parse("x")
  203. self.assertEqual( r.children, ["<b>"] )
  204. # Test Expand1 -> Alias
  205. g = Lark("""start: a
  206. ?a : b b -> c
  207. b : "x"
  208. """, parser='lalr')
  209. r = T().transform(g.parse("xx"))
  210. self.assertEqual( r.children, ["<c>"] )
  211. g = Lark("""start: a
  212. ?a : b b -> c
  213. b : "x"
  214. """, parser='lalr', transformer=T())
  215. r = g.parse("xx")
  216. self.assertEqual( r.children, ["<c>"] )
  217. def test_embedded_transformer_inplace(self):
  218. @v_args(tree=True)
  219. class T1(Transformer_InPlace):
  220. def a(self, tree):
  221. assert isinstance(tree, Tree), tree
  222. tree.children.append("tested")
  223. return tree
  224. def b(self, tree):
  225. return Tree(tree.data, tree.children + ['tested2'])
  226. @v_args(tree=True)
  227. class T2(Transformer):
  228. def a(self, tree):
  229. assert isinstance(tree, Tree), tree
  230. tree.children.append("tested")
  231. return tree
  232. def b(self, tree):
  233. return Tree(tree.data, tree.children + ['tested2'])
  234. class T3(Transformer):
  235. @v_args(tree=True)
  236. def a(self, tree):
  237. assert isinstance(tree, Tree)
  238. tree.children.append("tested")
  239. return tree
  240. @v_args(tree=True)
  241. def b(self, tree):
  242. return Tree(tree.data, tree.children + ['tested2'])
  243. for t in [T1(), T2(), T3()]:
  244. for internal in [False, True]:
  245. g = Lark("""start: a b
  246. a : "x"
  247. b : "y"
  248. """, parser='lalr', transformer=t if internal else None)
  249. r = g.parse("xy")
  250. if not internal:
  251. r = t.transform(r)
  252. a, b = r.children
  253. self.assertEqual(a.children, ["tested"])
  254. self.assertEqual(b.children, ["tested2"])
  255. def test_alias(self):
  256. Lark("""start: ["a"] "b" ["c"] "e" ["f"] ["g"] ["h"] "x" -> d """)
  257. def _make_full_earley_test(LEXER):
  258. def _Lark(grammar, **kwargs):
  259. return Lark(grammar, lexer=LEXER, parser='earley', propagate_positions=True, **kwargs)
  260. class _TestFullEarley(unittest.TestCase):
  261. def test_anon(self):
  262. # Fails an Earley implementation without special handling for empty rules,
  263. # or re-processing of already completed rules.
  264. g = Lark(r"""start: B
  265. B: ("ab"|/[^b]/)+
  266. """, lexer=LEXER)
  267. self.assertEqual( g.parse('abc').children[0], 'abc')
  268. def test_earley(self):
  269. g = Lark("""start: A "b" c
  270. A: "a"+
  271. c: "abc"
  272. """, parser="earley", lexer=LEXER)
  273. x = g.parse('aaaababc')
  274. def test_earley2(self):
  275. grammar = """
  276. start: statement+
  277. statement: "r"
  278. | "c" /[a-z]/+
  279. %ignore " "
  280. """
  281. program = """c b r"""
  282. l = Lark(grammar, parser='earley', lexer=LEXER)
  283. l.parse(program)
  284. @unittest.skipIf(LEXER=='dynamic', "Only relevant for the dynamic_complete parser")
  285. def test_earley3(self):
  286. """Tests prioritization and disambiguation for pseudo-terminals (there should be only one result)
  287. By default, `+` should immitate regexp greedy-matching
  288. """
  289. grammar = """
  290. start: A A
  291. A: "a"+
  292. """
  293. l = Lark(grammar, parser='earley', lexer=LEXER)
  294. res = l.parse("aaa")
  295. self.assertEqual(set(res.children), {'aa', 'a'})
  296. # XXX TODO fix Earley to maintain correct order
  297. # i.e. terminals it imitate greedy search for terminals, but lazy search for rules
  298. # self.assertEqual(res.children, ['aa', 'a'])
  299. def test_earley4(self):
  300. grammar = """
  301. start: A A?
  302. A: "a"+
  303. """
  304. l = Lark(grammar, parser='earley', lexer=LEXER)
  305. res = l.parse("aaa")
  306. assert set(res.children) == {'aa', 'a'} or res.children == ['aaa']
  307. # XXX TODO fix Earley to maintain correct order
  308. # i.e. terminals it imitate greedy search for terminals, but lazy search for rules
  309. # self.assertEqual(res.children, ['aaa'])
  310. def test_earley_repeating_empty(self):
  311. # This was a sneaky bug!
  312. grammar = """
  313. !start: "a" empty empty "b"
  314. empty: empty2
  315. empty2:
  316. """
  317. parser = Lark(grammar, parser='earley', lexer=LEXER)
  318. res = parser.parse('ab')
  319. empty_tree = Tree('empty', [Tree('empty2', [])])
  320. self.assertSequenceEqual(res.children, ['a', empty_tree, empty_tree, 'b'])
  321. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  322. def test_earley_explicit_ambiguity(self):
  323. # This was a sneaky bug!
  324. grammar = """
  325. start: a b | ab
  326. a: "a"
  327. b: "b"
  328. ab: "ab"
  329. """
  330. parser = Lark(grammar, parser='earley', lexer=LEXER, ambiguity='explicit')
  331. ambig_tree = parser.parse('ab')
  332. self.assertEqual( ambig_tree.data, '_ambig')
  333. self.assertEqual( len(ambig_tree.children), 2)
  334. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  335. def test_ambiguity1(self):
  336. grammar = """
  337. start: cd+ "e"
  338. !cd: "c"
  339. | "d"
  340. | "cd"
  341. """
  342. l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER)
  343. ambig_tree = l.parse('cde')
  344. assert ambig_tree.data == '_ambig', ambig_tree
  345. assert len(ambig_tree.children) == 2
  346. @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer")
  347. def test_ambiguity2(self):
  348. grammar = """
  349. ANY: /[a-zA-Z0-9 ]+/
  350. a.2: "A" b+
  351. b.2: "B"
  352. c: ANY
  353. start: (a|c)*
  354. """
  355. l = Lark(grammar, parser='earley', lexer=LEXER)
  356. res = l.parse('ABX')
  357. expected = Tree('start', [
  358. Tree('a', [
  359. Tree('b', [])
  360. ]),
  361. Tree('c', [
  362. 'X'
  363. ])
  364. ])
  365. self.assertEqual(res, expected)
  366. def test_fruitflies_ambig(self):
  367. grammar = """
  368. start: noun verb noun -> simple
  369. | noun verb "like" noun -> comparative
  370. noun: adj? NOUN
  371. verb: VERB
  372. adj: ADJ
  373. NOUN: "flies" | "bananas" | "fruit"
  374. VERB: "like" | "flies"
  375. ADJ: "fruit"
  376. %import common.WS
  377. %ignore WS
  378. """
  379. parser = Lark(grammar, ambiguity='explicit', lexer=LEXER)
  380. tree = parser.parse('fruit flies like bananas')
  381. expected = Tree('_ambig', [
  382. Tree('comparative', [
  383. Tree('noun', ['fruit']),
  384. Tree('verb', ['flies']),
  385. Tree('noun', ['bananas'])
  386. ]),
  387. Tree('simple', [
  388. Tree('noun', [Tree('adj', ['fruit']), 'flies']),
  389. Tree('verb', ['like']),
  390. Tree('noun', ['bananas'])
  391. ])
  392. ])
  393. # self.assertEqual(tree, expected)
  394. self.assertEqual(tree.data, expected.data)
  395. self.assertEqual(set(tree.children), set(expected.children))
  396. @unittest.skipIf(LEXER!='dynamic_complete', "Only relevant for the dynamic_complete parser")
  397. def test_explicit_ambiguity2(self):
  398. grammar = r"""
  399. start: NAME+
  400. NAME: /\w+/
  401. %ignore " "
  402. """
  403. text = """cat"""
  404. parser = _Lark(grammar, start='start', ambiguity='explicit')
  405. tree = parser.parse(text)
  406. self.assertEqual(tree.data, '_ambig')
  407. combinations = {tuple(str(s) for s in t.children) for t in tree.children}
  408. self.assertEqual(combinations, {
  409. ('cat',),
  410. ('ca', 't'),
  411. ('c', 'at'),
  412. ('c', 'a' ,'t')
  413. })
  414. def test_term_ambig_resolve(self):
  415. grammar = r"""
  416. !start: NAME+
  417. NAME: /\w+/
  418. %ignore " "
  419. """
  420. text = """foo bar"""
  421. parser = Lark(grammar)
  422. tree = parser.parse(text)
  423. self.assertEqual(tree.children, ['foo', 'bar'])
  424. # @unittest.skipIf(LEXER=='dynamic', "Not implemented in Dynamic Earley yet") # TODO
  425. # def test_not_all_derivations(self):
  426. # grammar = """
  427. # start: cd+ "e"
  428. # !cd: "c"
  429. # | "d"
  430. # | "cd"
  431. # """
  432. # l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER, earley__all_derivations=False)
  433. # x = l.parse('cde')
  434. # assert x.data != '_ambig', x
  435. # assert len(x.children) == 1
  436. _NAME = "TestFullEarley" + LEXER.capitalize()
  437. _TestFullEarley.__name__ = _NAME
  438. globals()[_NAME] = _TestFullEarley
  439. class CustomLexer(Lexer):
  440. """
  441. Purpose of this custom lexer is to test the integration,
  442. so it uses the traditionalparser as implementation without custom lexing behaviour.
  443. """
  444. def __init__(self, lexer_conf):
  445. self.lexer = TraditionalLexer(copy(lexer_conf))
  446. def lex(self, *args, **kwargs):
  447. return self.lexer.lex(*args, **kwargs)
  448. def _tree_structure_check(a, b):
  449. """
  450. Checks that both Tree objects have the same structure, without checking their values.
  451. """
  452. assert a.data == b.data and len(a.children) == len(b.children)
  453. for ca,cb in zip(a.children, b.children):
  454. assert type(ca) == type(cb)
  455. if isinstance(ca, Tree):
  456. _tree_structure_check(ca, cb)
  457. elif isinstance(ca, Token):
  458. assert ca.type == cb.type
  459. else:
  460. assert ca == cb
  461. class DualLark:
  462. """
  463. A helper class that wraps both a normal parser, and a parser for bytes.
  464. It automatically transforms `.parse` calls for both lexer, returning the value from the text lexer
  465. It always checks that both produce the same output/error
  466. """
  467. def __init__(self, g, *args, **kwargs):
  468. self.text_lexer = Lark(g, *args, use_bytes=False, **kwargs)
  469. g = self.text_lexer.grammar_source.lower()
  470. if '\\u' in g or not isascii(g):
  471. # Bytes re can't deal with uniode escapes
  472. self.bytes_lark = None
  473. else:
  474. # Everything here should work, so use `use_bytes='force'`
  475. self.bytes_lark = Lark(self.text_lexer.grammar_source, *args, use_bytes='force', **kwargs)
  476. def parse(self, text, start=None):
  477. # TODO: Easy workaround, more complex checks would be beneficial
  478. if not isascii(text) or self.bytes_lark is None:
  479. return self.text_lexer.parse(text, start)
  480. try:
  481. rv = self.text_lexer.parse(text, start)
  482. except Exception as e:
  483. try:
  484. self.bytes_lark.parse(text.encode(), start)
  485. except Exception as be:
  486. assert type(e) == type(be), "Parser with and without `use_bytes` raise different exceptions"
  487. raise e
  488. assert False, "Parser without `use_bytes` raises exception, with doesn't"
  489. try:
  490. bv = self.bytes_lark.parse(text.encode(), start)
  491. except Exception as be:
  492. assert False, "Parser without `use_bytes` doesn't raise an exception, with does"
  493. _tree_structure_check(rv, bv)
  494. return rv
  495. @classmethod
  496. def open(cls, grammar_filename, rel_to=None, **options):
  497. if rel_to:
  498. basepath = os.path.dirname(rel_to)
  499. grammar_filename = os.path.join(basepath, grammar_filename)
  500. with open(grammar_filename, encoding='utf8') as f:
  501. return cls(f, **options)
  502. def save(self,f):
  503. self.text_lexer.save(f)
  504. if self.bytes_lark is not None:
  505. self.bytes_lark.save(f)
  506. def load(self,f):
  507. self.text_lexer = self.text_lexer.load(f)
  508. if self.bytes_lark is not None:
  509. self.bytes_lark.load(f)
  510. def _make_parser_test(LEXER, PARSER):
  511. lexer_class_or_name = CustomLexer if LEXER == 'custom' else LEXER
  512. def _Lark(grammar, **kwargs):
  513. return DualLark(grammar, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  514. def _Lark_open(gfilename, **kwargs):
  515. return DualLark.open(gfilename, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  516. class _TestParser(unittest.TestCase):
  517. def test_basic1(self):
  518. g = _Lark("""start: a+ b a* "b" a*
  519. b: "b"
  520. a: "a"
  521. """)
  522. r = g.parse('aaabaab')
  523. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  524. r = g.parse('aaabaaba')
  525. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  526. self.assertRaises(ParseError, g.parse, 'aaabaa')
  527. def test_basic2(self):
  528. # Multiple parsers and colliding tokens
  529. g = _Lark("""start: B A
  530. B: "12"
  531. A: "1" """)
  532. g2 = _Lark("""start: B A
  533. B: "12"
  534. A: "2" """)
  535. x = g.parse('121')
  536. assert x.data == 'start' and x.children == ['12', '1'], x
  537. x = g2.parse('122')
  538. assert x.data == 'start' and x.children == ['12', '2'], x
  539. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  540. def test_stringio_bytes(self):
  541. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  542. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  543. def test_stringio_unicode(self):
  544. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  545. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  546. def test_unicode(self):
  547. g = _Lark(u"""start: UNIA UNIB UNIA
  548. UNIA: /\xa3/
  549. UNIB: /\u0101/
  550. """)
  551. g.parse(u'\xa3\u0101\u00a3')
  552. def test_unicode2(self):
  553. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  554. UNIA: /\xa3/
  555. UNIB: "a\u0101b\ "
  556. UNIC: /a?\u0101c\n/
  557. """)
  558. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  559. def test_unicode3(self):
  560. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  561. UNIA: /\xa3/
  562. UNIB: "\u0101"
  563. UNIC: /\u0203/ /\n/
  564. """)
  565. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  566. def test_hex_escape(self):
  567. g = _Lark(r"""start: A B C
  568. A: "\x01"
  569. B: /\x02/
  570. C: "\xABCD"
  571. """)
  572. g.parse('\x01\x02\xABCD')
  573. def test_unicode_literal_range_escape(self):
  574. g = _Lark(r"""start: A+
  575. A: "\u0061".."\u0063"
  576. """)
  577. g.parse('abc')
  578. def test_hex_literal_range_escape(self):
  579. g = _Lark(r"""start: A+
  580. A: "\x01".."\x03"
  581. """)
  582. g.parse('\x01\x02\x03')
  583. @unittest.skipIf(sys.version_info[:2]==(2, 7), "bytes parser isn't perfect in Python2.7, exceptions don't work correctly")
  584. def test_bytes_utf8(self):
  585. g = r"""
  586. start: BOM? char+
  587. BOM: "\xef\xbb\xbf"
  588. char: CHAR1 | CHAR2 | CHAR3 | CHAR4
  589. CONTINUATION_BYTE: "\x80" .. "\xbf"
  590. CHAR1: "\x00" .. "\x7f"
  591. CHAR2: "\xc0" .. "\xdf" CONTINUATION_BYTE
  592. CHAR3: "\xe0" .. "\xef" CONTINUATION_BYTE CONTINUATION_BYTE
  593. CHAR4: "\xf0" .. "\xf7" CONTINUATION_BYTE CONTINUATION_BYTE CONTINUATION_BYTE
  594. """
  595. g = _Lark(g)
  596. s = u"🔣 地? gurīn".encode('utf-8')
  597. self.assertEqual(len(g.bytes_lark.parse(s).children), 10)
  598. for enc, j in [("sjis", u"地球の絵はグリーンでグッド? Chikyuu no e wa guriin de guddo"),
  599. ("sjis", u"売春婦"),
  600. ("euc-jp", u"乂鵬鵠")]:
  601. s = j.encode(enc)
  602. self.assertRaises(UnexpectedCharacters, g.bytes_lark.parse, s)
  603. @unittest.skipIf(PARSER == 'cyk', "Takes forever")
  604. def test_stack_for_ebnf(self):
  605. """Verify that stack depth isn't an issue for EBNF grammars"""
  606. g = _Lark(r"""start: a+
  607. a : "a" """)
  608. g.parse("a" * (sys.getrecursionlimit()*2 ))
  609. def test_expand1_lists_with_one_item(self):
  610. g = _Lark(r"""start: list
  611. ?list: item+
  612. item : A
  613. A: "a"
  614. """)
  615. r = g.parse("a")
  616. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  617. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  618. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  619. self.assertEqual(len(r.children), 1)
  620. def test_expand1_lists_with_one_item_2(self):
  621. g = _Lark(r"""start: list
  622. ?list: item+ "!"
  623. item : A
  624. A: "a"
  625. """)
  626. r = g.parse("a!")
  627. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  628. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  629. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  630. self.assertEqual(len(r.children), 1)
  631. def test_dont_expand1_lists_with_multiple_items(self):
  632. g = _Lark(r"""start: list
  633. ?list: item+
  634. item : A
  635. A: "a"
  636. """)
  637. r = g.parse("aa")
  638. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  639. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  640. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  641. self.assertEqual(len(r.children), 1)
  642. # Sanity check: verify that 'list' contains the two 'item's we've given it
  643. [list] = r.children
  644. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  645. def test_dont_expand1_lists_with_multiple_items_2(self):
  646. g = _Lark(r"""start: list
  647. ?list: item+ "!"
  648. item : A
  649. A: "a"
  650. """)
  651. r = g.parse("aa!")
  652. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  653. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  654. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  655. self.assertEqual(len(r.children), 1)
  656. # Sanity check: verify that 'list' contains the two 'item's we've given it
  657. [list] = r.children
  658. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  659. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  660. def test_empty_expand1_list(self):
  661. g = _Lark(r"""start: list
  662. ?list: item*
  663. item : A
  664. A: "a"
  665. """)
  666. r = g.parse("")
  667. # 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
  668. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  669. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  670. self.assertEqual(len(r.children), 1)
  671. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  672. [list] = r.children
  673. self.assertSequenceEqual([item.data for item in list.children], ())
  674. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  675. def test_empty_expand1_list_2(self):
  676. g = _Lark(r"""start: list
  677. ?list: item* "!"?
  678. item : A
  679. A: "a"
  680. """)
  681. r = g.parse("")
  682. # 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
  683. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  684. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  685. self.assertEqual(len(r.children), 1)
  686. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  687. [list] = r.children
  688. self.assertSequenceEqual([item.data for item in list.children], ())
  689. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  690. def test_empty_flatten_list(self):
  691. g = _Lark(r"""start: list
  692. list: | item "," list
  693. item : A
  694. A: "a"
  695. """)
  696. r = g.parse("")
  697. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  698. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  699. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  700. [list] = r.children
  701. self.assertSequenceEqual([item.data for item in list.children], ())
  702. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  703. def test_single_item_flatten_list(self):
  704. g = _Lark(r"""start: list
  705. list: | item "," list
  706. item : A
  707. A: "a"
  708. """)
  709. r = g.parse("a,")
  710. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  711. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  712. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  713. [list] = r.children
  714. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  715. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  716. def test_multiple_item_flatten_list(self):
  717. g = _Lark(r"""start: list
  718. #list: | item "," list
  719. item : A
  720. A: "a"
  721. """)
  722. r = g.parse("a,a,")
  723. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  724. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  725. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  726. [list] = r.children
  727. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  728. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  729. def test_recurse_flatten(self):
  730. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  731. g = _Lark(r"""start: a | start a
  732. a : A
  733. A : "a" """)
  734. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  735. # STree data structures, which uses recursion).
  736. g.parse("a" * (sys.getrecursionlimit() // 4))
  737. def test_token_collision(self):
  738. g = _Lark(r"""start: "Hello" NAME
  739. NAME: /\w/+
  740. %ignore " "
  741. """)
  742. x = g.parse('Hello World')
  743. self.assertSequenceEqual(x.children, ['World'])
  744. x = g.parse('Hello HelloWorld')
  745. self.assertSequenceEqual(x.children, ['HelloWorld'])
  746. def test_token_collision_WS(self):
  747. g = _Lark(r"""start: "Hello" NAME
  748. NAME: /\w/+
  749. %import common.WS
  750. %ignore WS
  751. """)
  752. x = g.parse('Hello World')
  753. self.assertSequenceEqual(x.children, ['World'])
  754. x = g.parse('Hello HelloWorld')
  755. self.assertSequenceEqual(x.children, ['HelloWorld'])
  756. def test_token_collision2(self):
  757. g = _Lark("""
  758. !start: "starts"
  759. %import common.LCASE_LETTER
  760. """)
  761. x = g.parse("starts")
  762. self.assertSequenceEqual(x.children, ['starts'])
  763. def test_templates(self):
  764. g = _Lark(r"""
  765. start: "[" sep{NUMBER, ","} "]"
  766. sep{item, delim}: item (delim item)*
  767. NUMBER: /\d+/
  768. %ignore " "
  769. """)
  770. x = g.parse("[1, 2, 3, 4]")
  771. self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])])
  772. x = g.parse("[1]")
  773. self.assertSequenceEqual(x.children, [Tree('sep', ['1'])])
  774. def test_templates_recursion(self):
  775. g = _Lark(r"""
  776. start: "[" _sep{NUMBER, ","} "]"
  777. _sep{item, delim}: item | _sep{item, delim} delim item
  778. NUMBER: /\d+/
  779. %ignore " "
  780. """)
  781. x = g.parse("[1, 2, 3, 4]")
  782. self.assertSequenceEqual(x.children, ['1', '2', '3', '4'])
  783. x = g.parse("[1]")
  784. self.assertSequenceEqual(x.children, ['1'])
  785. def test_templates_import(self):
  786. g = _Lark_open("test_templates_import.lark", rel_to=__file__)
  787. x = g.parse("[1, 2, 3, 4]")
  788. self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])])
  789. x = g.parse("[1]")
  790. self.assertSequenceEqual(x.children, [Tree('sep', ['1'])])
  791. def test_templates_alias(self):
  792. g = _Lark(r"""
  793. start: expr{"C"}
  794. expr{t}: "A" t
  795. | "B" t -> b
  796. """)
  797. x = g.parse("AC")
  798. self.assertSequenceEqual(x.children, [Tree('expr', [])])
  799. x = g.parse("BC")
  800. self.assertSequenceEqual(x.children, [Tree('b', [])])
  801. def test_templates_modifiers(self):
  802. g = _Lark(r"""
  803. start: expr{"B"}
  804. !expr{t}: "A" t
  805. """)
  806. x = g.parse("AB")
  807. self.assertSequenceEqual(x.children, [Tree('expr', ["A", "B"])])
  808. g = _Lark(r"""
  809. start: _expr{"B"}
  810. !_expr{t}: "A" t
  811. """)
  812. x = g.parse("AB")
  813. self.assertSequenceEqual(x.children, ["A", "B"])
  814. g = _Lark(r"""
  815. start: expr{b}
  816. b: "B"
  817. ?expr{t}: "A" t
  818. """)
  819. x = g.parse("AB")
  820. self.assertSequenceEqual(x.children, [Tree('b',[])])
  821. def test_templates_templates(self):
  822. g = _Lark('''start: a{b}
  823. a{t}: t{"a"}
  824. b{x}: x''')
  825. x = g.parse('a')
  826. self.assertSequenceEqual(x.children, [Tree('a', [Tree('b',[])])])
  827. def test_g_regex_flags(self):
  828. g = _Lark("""
  829. start: "a" /b+/ C
  830. C: "C" | D
  831. D: "D" E
  832. E: "e"
  833. """, g_regex_flags=re.I)
  834. x1 = g.parse("ABBc")
  835. x2 = g.parse("abdE")
  836. # def test_string_priority(self):
  837. # g = _Lark("""start: (A | /a?bb/)+
  838. # A: "a" """)
  839. # x = g.parse('abb')
  840. # self.assertEqual(len(x.children), 2)
  841. # # This parse raises an exception because the lexer will always try to consume
  842. # # "a" first and will never match the regular expression
  843. # # This behavior is subject to change!!
  844. # # Thie won't happen with ambiguity handling.
  845. # g = _Lark("""start: (A | /a?ab/)+
  846. # A: "a" """)
  847. # self.assertRaises(LexError, g.parse, 'aab')
  848. def test_undefined_rule(self):
  849. self.assertRaises(GrammarError, _Lark, """start: a""")
  850. def test_undefined_token(self):
  851. self.assertRaises(GrammarError, _Lark, """start: A""")
  852. def test_rule_collision(self):
  853. g = _Lark("""start: "a"+ "b"
  854. | "a"+ """)
  855. x = g.parse('aaaa')
  856. x = g.parse('aaaab')
  857. def test_rule_collision2(self):
  858. g = _Lark("""start: "a"* "b"
  859. | "a"+ """)
  860. x = g.parse('aaaa')
  861. x = g.parse('aaaab')
  862. x = g.parse('b')
  863. def test_token_not_anon(self):
  864. """Tests that "a" is matched as an anonymous token, and not A.
  865. """
  866. g = _Lark("""start: "a"
  867. A: "a" """)
  868. x = g.parse('a')
  869. self.assertEqual(len(x.children), 0, '"a" should be considered anonymous')
  870. g = _Lark("""start: "a" A
  871. A: "a" """)
  872. x = g.parse('aa')
  873. self.assertEqual(len(x.children), 1, 'only "a" should be considered anonymous')
  874. self.assertEqual(x.children[0].type, "A")
  875. g = _Lark("""start: /a/
  876. A: /a/ """)
  877. x = g.parse('a')
  878. self.assertEqual(len(x.children), 1)
  879. self.assertEqual(x.children[0].type, "A", "A isn't associated with /a/")
  880. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  881. def test_maybe(self):
  882. g = _Lark("""start: ["a"] """)
  883. x = g.parse('a')
  884. x = g.parse('')
  885. def test_start(self):
  886. g = _Lark("""a: "a" a? """, start='a')
  887. x = g.parse('a')
  888. x = g.parse('aa')
  889. x = g.parse('aaa')
  890. def test_alias(self):
  891. g = _Lark("""start: "a" -> b """)
  892. x = g.parse('a')
  893. self.assertEqual(x.data, "b")
  894. def test_token_ebnf(self):
  895. g = _Lark("""start: A
  896. A: "a"* ("b"? "c".."e")+
  897. """)
  898. x = g.parse('abcde')
  899. x = g.parse('dd')
  900. def test_backslash(self):
  901. g = _Lark(r"""start: "\\" "a"
  902. """)
  903. x = g.parse(r'\a')
  904. g = _Lark(r"""start: /\\/ /a/
  905. """)
  906. x = g.parse(r'\a')
  907. def test_backslash2(self):
  908. g = _Lark(r"""start: "\"" "-"
  909. """)
  910. x = g.parse('"-')
  911. g = _Lark(r"""start: /\// /-/
  912. """)
  913. x = g.parse('/-')
  914. def test_special_chars(self):
  915. g = _Lark(r"""start: "\n"
  916. """)
  917. x = g.parse('\n')
  918. g = _Lark(r"""start: /\n/
  919. """)
  920. x = g.parse('\n')
  921. # def test_token_recurse(self):
  922. # g = _Lark("""start: A
  923. # A: B
  924. # B: A
  925. # """)
  926. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  927. def test_empty(self):
  928. # Fails an Earley implementation without special handling for empty rules,
  929. # or re-processing of already completed rules.
  930. g = _Lark(r"""start: _empty a "B"
  931. a: _empty "A"
  932. _empty:
  933. """)
  934. x = g.parse('AB')
  935. def test_regex_quote(self):
  936. g = r"""
  937. start: SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING
  938. SINGLE_QUOTED_STRING : /'[^']*'/
  939. DOUBLE_QUOTED_STRING : /"[^"]*"/
  940. """
  941. g = _Lark(g)
  942. self.assertEqual( g.parse('"hello"').children, ['"hello"'])
  943. self.assertEqual( g.parse("'hello'").children, ["'hello'"])
  944. @unittest.skipIf(not Py36, "Required re syntax only exists in python3.6+")
  945. def test_join_regex_flags(self):
  946. g = r"""
  947. start: A
  948. A: B C
  949. B: /./s
  950. C: /./
  951. """
  952. g = _Lark(g)
  953. self.assertEqual(g.parse(" ").children,[" "])
  954. self.assertEqual(g.parse("\n ").children,["\n "])
  955. self.assertRaises(UnexpectedCharacters, g.parse, "\n\n")
  956. g = r"""
  957. start: A
  958. A: B | C
  959. B: "b"i
  960. C: "c"
  961. """
  962. g = _Lark(g)
  963. self.assertEqual(g.parse("b").children,["b"])
  964. self.assertEqual(g.parse("B").children,["B"])
  965. self.assertEqual(g.parse("c").children,["c"])
  966. self.assertRaises(UnexpectedCharacters, g.parse, "C")
  967. def test_lexer_token_limit(self):
  968. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  969. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  970. g = _Lark("""start: %s
  971. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  972. def test_float_without_lexer(self):
  973. expected_error = UnexpectedCharacters if LEXER.startswith('dynamic') else UnexpectedToken
  974. if PARSER == 'cyk':
  975. expected_error = ParseError
  976. g = _Lark("""start: ["+"|"-"] float
  977. float: digit* "." digit+ exp?
  978. | digit+ exp
  979. exp: ("e"|"E") ["+"|"-"] digit+
  980. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  981. """)
  982. g.parse("1.2")
  983. g.parse("-.2e9")
  984. g.parse("+2e-9")
  985. self.assertRaises( expected_error, g.parse, "+2e-9e")
  986. def test_keep_all_tokens(self):
  987. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  988. tree = l.parse('aaa')
  989. self.assertEqual(tree.children, ['a', 'a', 'a'])
  990. def test_token_flags(self):
  991. l = _Lark("""!start: "a"i+
  992. """
  993. )
  994. tree = l.parse('aA')
  995. self.assertEqual(tree.children, ['a', 'A'])
  996. l = _Lark("""!start: /a/i+
  997. """
  998. )
  999. tree = l.parse('aA')
  1000. self.assertEqual(tree.children, ['a', 'A'])
  1001. # g = """!start: "a"i "a"
  1002. # """
  1003. # self.assertRaises(GrammarError, _Lark, g)
  1004. # g = """!start: /a/i /a/
  1005. # """
  1006. # self.assertRaises(GrammarError, _Lark, g)
  1007. g = """start: NAME "," "a"
  1008. NAME: /[a-z_]/i /[a-z0-9_]/i*
  1009. """
  1010. l = _Lark(g)
  1011. tree = l.parse('ab,a')
  1012. self.assertEqual(tree.children, ['ab'])
  1013. tree = l.parse('AB,a')
  1014. self.assertEqual(tree.children, ['AB'])
  1015. def test_token_flags3(self):
  1016. l = _Lark("""!start: ABC+
  1017. ABC: "abc"i
  1018. """
  1019. )
  1020. tree = l.parse('aBcAbC')
  1021. self.assertEqual(tree.children, ['aBc', 'AbC'])
  1022. def test_token_flags2(self):
  1023. g = """!start: ("a"i | /a/ /b/?)+
  1024. """
  1025. l = _Lark(g)
  1026. tree = l.parse('aA')
  1027. self.assertEqual(tree.children, ['a', 'A'])
  1028. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1029. def test_twice_empty(self):
  1030. g = """!start: ("A"?)?
  1031. """
  1032. l = _Lark(g)
  1033. tree = l.parse('A')
  1034. self.assertEqual(tree.children, ['A'])
  1035. tree = l.parse('')
  1036. self.assertEqual(tree.children, [])
  1037. def test_undefined_ignore(self):
  1038. g = """!start: "A"
  1039. %ignore B
  1040. """
  1041. self.assertRaises( GrammarError, _Lark, g)
  1042. def test_alias_in_terminal(self):
  1043. g = """start: TERM
  1044. TERM: "a" -> alias
  1045. """
  1046. self.assertRaises( GrammarError, _Lark, g)
  1047. def test_line_and_column(self):
  1048. g = r"""!start: "A" bc "D"
  1049. !bc: "B\nC"
  1050. """
  1051. l = _Lark(g)
  1052. a, bc, d = l.parse("AB\nCD").children
  1053. self.assertEqual(a.line, 1)
  1054. self.assertEqual(a.column, 1)
  1055. bc ,= bc.children
  1056. self.assertEqual(bc.line, 1)
  1057. self.assertEqual(bc.column, 2)
  1058. self.assertEqual(d.line, 2)
  1059. self.assertEqual(d.column, 2)
  1060. if LEXER != 'dynamic':
  1061. self.assertEqual(a.end_line, 1)
  1062. self.assertEqual(a.end_column, 2)
  1063. self.assertEqual(bc.end_line, 2)
  1064. self.assertEqual(bc.end_column, 2)
  1065. self.assertEqual(d.end_line, 2)
  1066. self.assertEqual(d.end_column, 3)
  1067. def test_reduce_cycle(self):
  1068. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  1069. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  1070. """
  1071. l = _Lark("""
  1072. term: A
  1073. | term term
  1074. A: "a"
  1075. """, start='term')
  1076. tree = l.parse("aa")
  1077. self.assertEqual(len(tree.children), 2)
  1078. @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority")
  1079. def test_lexer_prioritization(self):
  1080. "Tests effect of priority on result"
  1081. grammar = """
  1082. start: A B | AB
  1083. A.2: "a"
  1084. B: "b"
  1085. AB: "ab"
  1086. """
  1087. l = _Lark(grammar)
  1088. res = l.parse("ab")
  1089. self.assertEqual(res.children, ['a', 'b'])
  1090. self.assertNotEqual(res.children, ['ab'])
  1091. grammar = """
  1092. start: A B | AB
  1093. A: "a"
  1094. B: "b"
  1095. AB.3: "ab"
  1096. """
  1097. l = _Lark(grammar)
  1098. res = l.parse("ab")
  1099. self.assertNotEqual(res.children, ['a', 'b'])
  1100. self.assertEqual(res.children, ['ab'])
  1101. grammar = """
  1102. start: A B | AB
  1103. A: "a"
  1104. B.-20: "b"
  1105. AB.-10: "ab"
  1106. """
  1107. l = _Lark(grammar)
  1108. res = l.parse("ab")
  1109. self.assertEqual(res.children, ['a', 'b'])
  1110. grammar = """
  1111. start: A B | AB
  1112. A.-99999999999999999999999: "a"
  1113. B: "b"
  1114. AB: "ab"
  1115. """
  1116. l = _Lark(grammar)
  1117. res = l.parse("ab")
  1118. self.assertEqual(res.children, ['ab'])
  1119. def test_import(self):
  1120. grammar = """
  1121. start: NUMBER WORD
  1122. %import common.NUMBER
  1123. %import common.WORD
  1124. %import common.WS
  1125. %ignore WS
  1126. """
  1127. l = _Lark(grammar)
  1128. x = l.parse('12 elephants')
  1129. self.assertEqual(x.children, ['12', 'elephants'])
  1130. def test_import_rename(self):
  1131. grammar = """
  1132. start: N W
  1133. %import common.NUMBER -> N
  1134. %import common.WORD -> W
  1135. %import common.WS
  1136. %ignore WS
  1137. """
  1138. l = _Lark(grammar)
  1139. x = l.parse('12 elephants')
  1140. self.assertEqual(x.children, ['12', 'elephants'])
  1141. def test_relative_import(self):
  1142. l = _Lark_open('test_relative_import.lark', rel_to=__file__)
  1143. x = l.parse('12 lions')
  1144. self.assertEqual(x.children, ['12', 'lions'])
  1145. def test_relative_import_unicode(self):
  1146. l = _Lark_open('test_relative_import_unicode.lark', rel_to=__file__)
  1147. x = l.parse(u'Ø')
  1148. self.assertEqual(x.children, [u'Ø'])
  1149. def test_relative_import_rename(self):
  1150. l = _Lark_open('test_relative_import_rename.lark', rel_to=__file__)
  1151. x = l.parse('12 lions')
  1152. self.assertEqual(x.children, ['12', 'lions'])
  1153. def test_relative_rule_import(self):
  1154. l = _Lark_open('test_relative_rule_import.lark', rel_to=__file__)
  1155. x = l.parse('xaabby')
  1156. self.assertEqual(x.children, [
  1157. 'x',
  1158. Tree('expr', ['a', Tree('expr', ['a', 'b']), 'b']),
  1159. 'y'])
  1160. def test_relative_rule_import_drop_ignore(self):
  1161. # %ignore rules are dropped on import
  1162. l = _Lark_open('test_relative_rule_import_drop_ignore.lark',
  1163. rel_to=__file__)
  1164. self.assertRaises((ParseError, UnexpectedInput),
  1165. l.parse, 'xa abby')
  1166. def test_relative_rule_import_subrule(self):
  1167. l = _Lark_open('test_relative_rule_import_subrule.lark',
  1168. rel_to=__file__)
  1169. x = l.parse('xaabby')
  1170. self.assertEqual(x.children, [
  1171. 'x',
  1172. Tree('startab', [
  1173. Tree('grammars__ab__expr', [
  1174. 'a', Tree('grammars__ab__expr', ['a', 'b']), 'b',
  1175. ]),
  1176. ]),
  1177. 'y'])
  1178. def test_relative_rule_import_subrule_no_conflict(self):
  1179. l = _Lark_open(
  1180. 'test_relative_rule_import_subrule_no_conflict.lark',
  1181. rel_to=__file__)
  1182. x = l.parse('xaby')
  1183. self.assertEqual(x.children, [Tree('expr', [
  1184. 'x',
  1185. Tree('startab', [
  1186. Tree('grammars__ab__expr', ['a', 'b']),
  1187. ]),
  1188. 'y'])])
  1189. self.assertRaises((ParseError, UnexpectedInput),
  1190. l.parse, 'xaxabyby')
  1191. def test_relative_rule_import_rename(self):
  1192. l = _Lark_open('test_relative_rule_import_rename.lark',
  1193. rel_to=__file__)
  1194. x = l.parse('xaabby')
  1195. self.assertEqual(x.children, [
  1196. 'x',
  1197. Tree('ab', ['a', Tree('ab', ['a', 'b']), 'b']),
  1198. 'y'])
  1199. def test_multi_import(self):
  1200. grammar = """
  1201. start: NUMBER WORD
  1202. %import common (NUMBER, WORD, WS)
  1203. %ignore WS
  1204. """
  1205. l = _Lark(grammar)
  1206. x = l.parse('12 toucans')
  1207. self.assertEqual(x.children, ['12', 'toucans'])
  1208. def test_relative_multi_import(self):
  1209. l = _Lark_open("test_relative_multi_import.lark", rel_to=__file__)
  1210. x = l.parse('12 capybaras')
  1211. self.assertEqual(x.children, ['12', 'capybaras'])
  1212. def test_relative_import_preserves_leading_underscore(self):
  1213. l = _Lark_open("test_relative_import_preserves_leading_underscore.lark", rel_to=__file__)
  1214. x = l.parse('Ax')
  1215. self.assertEqual(next(x.find_data('c')).children, ['A'])
  1216. def test_relative_import_of_nested_grammar(self):
  1217. l = _Lark_open("grammars/test_relative_import_of_nested_grammar.lark", rel_to=__file__)
  1218. x = l.parse('N')
  1219. self.assertEqual(next(x.find_data('rule_to_import')).children, ['N'])
  1220. def test_relative_import_rules_dependencies_imported_only_once(self):
  1221. l = _Lark_open("test_relative_import_rules_dependencies_imported_only_once.lark", rel_to=__file__)
  1222. x = l.parse('AAA')
  1223. self.assertEqual(next(x.find_data('a')).children, ['A'])
  1224. self.assertEqual(next(x.find_data('b')).children, ['A'])
  1225. self.assertEqual(next(x.find_data('d')).children, ['A'])
  1226. def test_import_errors(self):
  1227. grammar = """
  1228. start: NUMBER WORD
  1229. %import .grammars.bad_test.NUMBER
  1230. """
  1231. self.assertRaises(IOError, _Lark, grammar)
  1232. grammar = """
  1233. start: NUMBER WORD
  1234. %import bad_test.NUMBER
  1235. """
  1236. self.assertRaises(IOError, _Lark, grammar)
  1237. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  1238. def test_earley_prioritization(self):
  1239. "Tests effect of priority on result"
  1240. grammar = """
  1241. start: a | b
  1242. a.1: "a"
  1243. b.2: "a"
  1244. """
  1245. # l = Lark(grammar, parser='earley', lexer='standard')
  1246. l = _Lark(grammar)
  1247. res = l.parse("a")
  1248. self.assertEqual(res.children[0].data, 'b')
  1249. grammar = """
  1250. start: a | b
  1251. a.2: "a"
  1252. b.1: "a"
  1253. """
  1254. l = _Lark(grammar)
  1255. # l = Lark(grammar, parser='earley', lexer='standard')
  1256. res = l.parse("a")
  1257. self.assertEqual(res.children[0].data, 'a')
  1258. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  1259. def test_earley_prioritization_sum(self):
  1260. "Tests effect of priority on result"
  1261. grammar = """
  1262. start: ab_ b_ a_ | indirection
  1263. indirection: a_ bb_ a_
  1264. a_: "a"
  1265. b_: "b"
  1266. ab_: "ab"
  1267. bb_.1: "bb"
  1268. """
  1269. l = Lark(grammar, priority="invert")
  1270. res = l.parse('abba')
  1271. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1272. grammar = """
  1273. start: ab_ b_ a_ | indirection
  1274. indirection: a_ bb_ a_
  1275. a_: "a"
  1276. b_: "b"
  1277. ab_.1: "ab"
  1278. bb_: "bb"
  1279. """
  1280. l = Lark(grammar, priority="invert")
  1281. res = l.parse('abba')
  1282. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1283. grammar = """
  1284. start: ab_ b_ a_ | indirection
  1285. indirection: a_ bb_ a_
  1286. a_.2: "a"
  1287. b_.1: "b"
  1288. ab_.3: "ab"
  1289. bb_.3: "bb"
  1290. """
  1291. l = Lark(grammar, priority="invert")
  1292. res = l.parse('abba')
  1293. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1294. grammar = """
  1295. start: ab_ b_ a_ | indirection
  1296. indirection: a_ bb_ a_
  1297. a_.1: "a"
  1298. b_.1: "b"
  1299. ab_.4: "ab"
  1300. bb_.3: "bb"
  1301. """
  1302. l = Lark(grammar, priority="invert")
  1303. res = l.parse('abba')
  1304. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1305. def test_utf8(self):
  1306. g = u"""start: a
  1307. a: "±a"
  1308. """
  1309. l = _Lark(g)
  1310. self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])]))
  1311. g = u"""start: A
  1312. A: "±a"
  1313. """
  1314. l = _Lark(g)
  1315. self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a']))
  1316. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1317. def test_ignore(self):
  1318. grammar = r"""
  1319. COMMENT: /(!|(\/\/))[^\n]*/
  1320. %ignore COMMENT
  1321. %import common.WS -> _WS
  1322. %import common.INT
  1323. start: "INT"i _WS+ INT _WS*
  1324. """
  1325. parser = _Lark(grammar)
  1326. tree = parser.parse("int 1 ! This is a comment\n")
  1327. self.assertEqual(tree.children, ['1'])
  1328. tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky!
  1329. self.assertEqual(tree.children, ['1'])
  1330. parser = _Lark(r"""
  1331. start : "a"*
  1332. %ignore "b"
  1333. """)
  1334. tree = parser.parse("bb")
  1335. self.assertEqual(tree.children, [])
  1336. def test_regex_escaping(self):
  1337. g = _Lark("start: /[ab]/")
  1338. g.parse('a')
  1339. g.parse('b')
  1340. self.assertRaises( UnexpectedInput, g.parse, 'c')
  1341. _Lark(r'start: /\w/').parse('a')
  1342. g = _Lark(r'start: /\\w/')
  1343. self.assertRaises( UnexpectedInput, g.parse, 'a')
  1344. g.parse(r'\w')
  1345. _Lark(r'start: /\[/').parse('[')
  1346. _Lark(r'start: /\//').parse('/')
  1347. _Lark(r'start: /\\/').parse('\\')
  1348. _Lark(r'start: /\[ab]/').parse('[ab]')
  1349. _Lark(r'start: /\\[ab]/').parse('\\a')
  1350. _Lark(r'start: /\t/').parse('\t')
  1351. _Lark(r'start: /\\t/').parse('\\t')
  1352. _Lark(r'start: /\\\t/').parse('\\\t')
  1353. _Lark(r'start: "\t"').parse('\t')
  1354. _Lark(r'start: "\\t"').parse('\\t')
  1355. _Lark(r'start: "\\\t"').parse('\\\t')
  1356. def test_ranged_repeat_rules(self):
  1357. g = u"""!start: "A"~3
  1358. """
  1359. l = _Lark(g)
  1360. self.assertEqual(l.parse(u'AAA'), Tree('start', ["A", "A", "A"]))
  1361. self.assertRaises(ParseError, l.parse, u'AA')
  1362. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1363. g = u"""!start: "A"~0..2
  1364. """
  1365. if PARSER != 'cyk': # XXX CYK currently doesn't support empty grammars
  1366. l = _Lark(g)
  1367. self.assertEqual(l.parse(u''), Tree('start', []))
  1368. self.assertEqual(l.parse(u'A'), Tree('start', ['A']))
  1369. self.assertEqual(l.parse(u'AA'), Tree('start', ['A', 'A']))
  1370. self.assertRaises((UnexpectedToken, UnexpectedInput), l.parse, u'AAA')
  1371. g = u"""!start: "A"~3..2
  1372. """
  1373. self.assertRaises(GrammarError, _Lark, g)
  1374. g = u"""!start: "A"~2..3 "B"~2
  1375. """
  1376. l = _Lark(g)
  1377. self.assertEqual(l.parse(u'AABB'), Tree('start', ['A', 'A', 'B', 'B']))
  1378. self.assertEqual(l.parse(u'AAABB'), Tree('start', ['A', 'A', 'A', 'B', 'B']))
  1379. self.assertRaises(ParseError, l.parse, u'AAAB')
  1380. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1381. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1382. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1383. def test_ranged_repeat_terms(self):
  1384. g = u"""!start: AAA
  1385. AAA: "A"~3
  1386. """
  1387. l = _Lark(g)
  1388. self.assertEqual(l.parse(u'AAA'), Tree('start', ["AAA"]))
  1389. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AA')
  1390. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1391. g = u"""!start: AABB CC
  1392. AABB: "A"~0..2 "B"~2
  1393. CC: "C"~1..2
  1394. """
  1395. l = _Lark(g)
  1396. self.assertEqual(l.parse(u'AABBCC'), Tree('start', ['AABB', 'CC']))
  1397. self.assertEqual(l.parse(u'BBC'), Tree('start', ['BB', 'C']))
  1398. self.assertEqual(l.parse(u'ABBCC'), Tree('start', ['ABB', 'CC']))
  1399. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAB')
  1400. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1401. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1402. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1403. @unittest.skipIf(PARSER=='earley', "Priority not handled correctly right now") # TODO XXX
  1404. def test_priority_vs_embedded(self):
  1405. g = """
  1406. A.2: "a"
  1407. WORD: ("a".."z")+
  1408. start: (A | WORD)+
  1409. """
  1410. l = _Lark(g)
  1411. t = l.parse('abc')
  1412. self.assertEqual(t.children, ['a', 'bc'])
  1413. self.assertEqual(t.children[0].type, 'A')
  1414. def test_line_counting(self):
  1415. p = _Lark("start: /[^x]+/")
  1416. text = 'hello\nworld'
  1417. t = p.parse(text)
  1418. tok = t.children[0]
  1419. self.assertEqual(tok, text)
  1420. self.assertEqual(tok.line, 1)
  1421. self.assertEqual(tok.column, 1)
  1422. if _LEXER != 'dynamic':
  1423. self.assertEqual(tok.end_line, 2)
  1424. self.assertEqual(tok.end_column, 6)
  1425. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1426. def test_empty_end(self):
  1427. p = _Lark("""
  1428. start: b c d
  1429. b: "B"
  1430. c: | "C"
  1431. d: | "D"
  1432. """)
  1433. res = p.parse('B')
  1434. self.assertEqual(len(res.children), 3)
  1435. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1436. def test_maybe_placeholders(self):
  1437. # Anonymous tokens shouldn't count
  1438. p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1439. self.assertEqual(p.parse("").children, [])
  1440. # All invisible constructs shouldn't count
  1441. p = _Lark("""start: [A] ["b"] [_c] ["e" "f" _c]
  1442. A: "a"
  1443. _c: "c" """, maybe_placeholders=True)
  1444. self.assertEqual(p.parse("").children, [None])
  1445. self.assertEqual(p.parse("c").children, [None])
  1446. self.assertEqual(p.parse("aefc").children, ['a'])
  1447. # ? shouldn't apply
  1448. p = _Lark("""!start: ["a"] "b"? ["c"] """, maybe_placeholders=True)
  1449. self.assertEqual(p.parse("").children, [None, None])
  1450. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1451. p = _Lark("""!start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1452. self.assertEqual(p.parse("").children, [None, None, None])
  1453. self.assertEqual(p.parse("a").children, ['a', None, None])
  1454. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1455. self.assertEqual(p.parse("c").children, [None, None, 'c'])
  1456. self.assertEqual(p.parse("ab").children, ['a', 'b', None])
  1457. self.assertEqual(p.parse("ac").children, ['a', None, 'c'])
  1458. self.assertEqual(p.parse("bc").children, [None, 'b', 'c'])
  1459. self.assertEqual(p.parse("abc").children, ['a', 'b', 'c'])
  1460. p = _Lark("""!start: (["a"] "b" ["c"])+ """, maybe_placeholders=True)
  1461. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1462. self.assertEqual(p.parse("bb").children, [None, 'b', None, None, 'b', None])
  1463. self.assertEqual(p.parse("abbc").children, ['a', 'b', None, None, 'b', 'c'])
  1464. self.assertEqual(p.parse("babbcabcb").children,
  1465. [None, 'b', None,
  1466. 'a', 'b', None,
  1467. None, 'b', 'c',
  1468. 'a', 'b', 'c',
  1469. None, 'b', None])
  1470. p = _Lark("""!start: ["a"] ["c"] "b"+ ["a"] ["d"] """, maybe_placeholders=True)
  1471. self.assertEqual(p.parse("bb").children, [None, None, 'b', 'b', None, None])
  1472. self.assertEqual(p.parse("bd").children, [None, None, 'b', None, 'd'])
  1473. self.assertEqual(p.parse("abba").children, ['a', None, 'b', 'b', 'a', None])
  1474. self.assertEqual(p.parse("cbbbb").children, [None, 'c', 'b', 'b', 'b', 'b', None, None])
  1475. def test_escaped_string(self):
  1476. "Tests common.ESCAPED_STRING"
  1477. grammar = r"""
  1478. start: ESCAPED_STRING+
  1479. %import common (WS_INLINE, ESCAPED_STRING)
  1480. %ignore WS_INLINE
  1481. """
  1482. parser = _Lark(grammar)
  1483. parser.parse(r'"\\" "b" "c"')
  1484. parser.parse(r'"That" "And a \"b"')
  1485. def test_meddling_unused(self):
  1486. "Unless 'unused' is removed, LALR analysis will fail on reduce-reduce collision"
  1487. grammar = """
  1488. start: EKS* x
  1489. x: EKS
  1490. unused: x*
  1491. EKS: "x"
  1492. """
  1493. parser = _Lark(grammar)
  1494. @unittest.skipIf(PARSER!='lalr' or LEXER=='custom', "Serialize currently only works for LALR parsers without custom lexers (though it should be easy to extend)")
  1495. def test_serialize(self):
  1496. grammar = """
  1497. start: _ANY b "C"
  1498. _ANY: /./
  1499. b: "B"
  1500. """
  1501. parser = _Lark(grammar)
  1502. s = BytesIO()
  1503. parser.save(s)
  1504. s.seek(0)
  1505. parser2 = Lark.load(s)
  1506. self.assertEqual(parser2.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1507. def test_multi_start(self):
  1508. parser = _Lark('''
  1509. a: "x" "a"?
  1510. b: "x" "b"?
  1511. ''', start=['a', 'b'])
  1512. self.assertEqual(parser.parse('xa', 'a'), Tree('a', []))
  1513. self.assertEqual(parser.parse('xb', 'b'), Tree('b', []))
  1514. def test_lexer_detect_newline_tokens(self):
  1515. # Detect newlines in regular tokens
  1516. g = _Lark(r"""start: "go" tail*
  1517. !tail : SA "@" | SB "@" | SC "@" | SD "@"
  1518. SA : "a" /\n/
  1519. SB : /b./s
  1520. SC : "c" /[^a-z]/
  1521. SD : "d" /\s/
  1522. """)
  1523. a,b,c,d = [x.children[1] for x in g.parse('goa\n@b\n@c\n@d\n@').children]
  1524. self.assertEqual(a.line, 2)
  1525. self.assertEqual(b.line, 3)
  1526. self.assertEqual(c.line, 4)
  1527. self.assertEqual(d.line, 5)
  1528. # Detect newlines in ignored tokens
  1529. for re in ['/\\n/', '/[^a-z]/', '/\\s/']:
  1530. g = _Lark('''!start: "a" "a"
  1531. %ignore {}'''.format(re))
  1532. a, b = g.parse('a\na').children
  1533. self.assertEqual(a.line, 1)
  1534. self.assertEqual(b.line, 2)
  1535. @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.')
  1536. def test_unicode_class(self):
  1537. "Tests that character classes from the `regex` module work correctly."
  1538. g = _Lark(r"""?start: NAME
  1539. NAME: ID_START ID_CONTINUE*
  1540. ID_START: /[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_]+/
  1541. ID_CONTINUE: ID_START | /[\p{Mn}\p{Mc}\p{Nd}\p{Pc}]+/""", regex=True)
  1542. self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்')
  1543. @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.')
  1544. def test_unicode_word(self):
  1545. "Tests that a persistent bug in the `re` module works when `regex` is enabled."
  1546. g = _Lark(r"""?start: NAME
  1547. NAME: /[\w]+/
  1548. """, regex=True)
  1549. self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்')
  1550. _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize()
  1551. _TestParser.__name__ = _NAME
  1552. _TestParser.__qualname__ = "tests.test_parser." + _NAME
  1553. globals()[_NAME] = _TestParser
  1554. # Note: You still have to import them in __main__ for the tests to run
  1555. _TO_TEST = [
  1556. ('standard', 'earley'),
  1557. ('standard', 'cyk'),
  1558. ('dynamic', 'earley'),
  1559. ('dynamic_complete', 'earley'),
  1560. ('standard', 'lalr'),
  1561. ('contextual', 'lalr'),
  1562. ('custom', 'lalr'),
  1563. # (None, 'earley'),
  1564. ]
  1565. for _LEXER, _PARSER in _TO_TEST:
  1566. _make_parser_test(_LEXER, _PARSER)
  1567. for _LEXER in ('dynamic', 'dynamic_complete'):
  1568. _make_full_earley_test(_LEXER)
  1569. if __name__ == '__main__':
  1570. unittest.main()