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.

1959 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 DualBytesLark:
  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. NOTE: Not currently used, but left here for future debugging.
  467. """
  468. def __init__(self, g, *args, **kwargs):
  469. self.text_lexer = Lark(g, *args, use_bytes=False, **kwargs)
  470. g = self.text_lexer.grammar_source.lower()
  471. if '\\u' in g or not isascii(g):
  472. # Bytes re can't deal with uniode escapes
  473. self.bytes_lark = None
  474. else:
  475. # Everything here should work, so use `use_bytes='force'`
  476. self.bytes_lark = Lark(self.text_lexer.grammar_source, *args, use_bytes='force', **kwargs)
  477. def parse(self, text, start=None):
  478. # TODO: Easy workaround, more complex checks would be beneficial
  479. if not isascii(text) or self.bytes_lark is None:
  480. return self.text_lexer.parse(text, start)
  481. try:
  482. rv = self.text_lexer.parse(text, start)
  483. except Exception as e:
  484. try:
  485. self.bytes_lark.parse(text.encode(), start)
  486. except Exception as be:
  487. assert type(e) == type(be), "Parser with and without `use_bytes` raise different exceptions"
  488. raise e
  489. assert False, "Parser without `use_bytes` raises exception, with doesn't"
  490. try:
  491. bv = self.bytes_lark.parse(text.encode(), start)
  492. except Exception as be:
  493. assert False, "Parser without `use_bytes` doesn't raise an exception, with does"
  494. _tree_structure_check(rv, bv)
  495. return rv
  496. @classmethod
  497. def open(cls, grammar_filename, rel_to=None, **options):
  498. if rel_to:
  499. basepath = os.path.dirname(rel_to)
  500. grammar_filename = os.path.join(basepath, grammar_filename)
  501. with open(grammar_filename, encoding='utf8') as f:
  502. return cls(f, **options)
  503. def save(self,f):
  504. self.text_lexer.save(f)
  505. if self.bytes_lark is not None:
  506. self.bytes_lark.save(f)
  507. def load(self,f):
  508. self.text_lexer = self.text_lexer.load(f)
  509. if self.bytes_lark is not None:
  510. self.bytes_lark.load(f)
  511. def _make_parser_test(LEXER, PARSER):
  512. lexer_class_or_name = CustomLexer if LEXER == 'custom' else LEXER
  513. def _Lark(grammar, **kwargs):
  514. return Lark(grammar, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  515. def _Lark_open(gfilename, **kwargs):
  516. return Lark.open(gfilename, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs)
  517. class _TestParser(unittest.TestCase):
  518. def test_basic1(self):
  519. g = _Lark("""start: a+ b a* "b" a*
  520. b: "b"
  521. a: "a"
  522. """)
  523. r = g.parse('aaabaab')
  524. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' )
  525. r = g.parse('aaabaaba')
  526. self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' )
  527. self.assertRaises(ParseError, g.parse, 'aaabaa')
  528. def test_basic2(self):
  529. # Multiple parsers and colliding tokens
  530. g = _Lark("""start: B A
  531. B: "12"
  532. A: "1" """)
  533. g2 = _Lark("""start: B A
  534. B: "12"
  535. A: "2" """)
  536. x = g.parse('121')
  537. assert x.data == 'start' and x.children == ['12', '1'], x
  538. x = g2.parse('122')
  539. assert x.data == 'start' and x.children == ['12', '2'], x
  540. @unittest.skipIf(cStringIO is None, "cStringIO not available")
  541. def test_stringio_bytes(self):
  542. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  543. _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  544. def test_stringio_unicode(self):
  545. """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object"""
  546. _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" '))
  547. def test_unicode(self):
  548. g = _Lark(u"""start: UNIA UNIB UNIA
  549. UNIA: /\xa3/
  550. UNIB: /\u0101/
  551. """)
  552. g.parse(u'\xa3\u0101\u00a3')
  553. def test_unicode2(self):
  554. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  555. UNIA: /\xa3/
  556. UNIB: "a\u0101b\ "
  557. UNIC: /a?\u0101c\n/
  558. """)
  559. g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n')
  560. def test_unicode3(self):
  561. g = _Lark(r"""start: UNIA UNIB UNIA UNIC
  562. UNIA: /\xa3/
  563. UNIB: "\u0101"
  564. UNIC: /\u0203/ /\n/
  565. """)
  566. g.parse(u'\xa3\u0101\u00a3\u0203\n')
  567. def test_hex_escape(self):
  568. g = _Lark(r"""start: A B C
  569. A: "\x01"
  570. B: /\x02/
  571. C: "\xABCD"
  572. """)
  573. g.parse('\x01\x02\xABCD')
  574. def test_unicode_literal_range_escape(self):
  575. g = _Lark(r"""start: A+
  576. A: "\u0061".."\u0063"
  577. """)
  578. g.parse('abc')
  579. def test_hex_literal_range_escape(self):
  580. g = _Lark(r"""start: A+
  581. A: "\x01".."\x03"
  582. """)
  583. g.parse('\x01\x02\x03')
  584. @unittest.skipIf(sys.version_info[:2]==(2, 7), "bytes parser isn't perfect in Python2.7, exceptions don't work correctly")
  585. def test_bytes_utf8(self):
  586. g = r"""
  587. start: BOM? char+
  588. BOM: "\xef\xbb\xbf"
  589. char: CHAR1 | CHAR2 | CHAR3 | CHAR4
  590. CONTINUATION_BYTE: "\x80" .. "\xbf"
  591. CHAR1: "\x00" .. "\x7f"
  592. CHAR2: "\xc0" .. "\xdf" CONTINUATION_BYTE
  593. CHAR3: "\xe0" .. "\xef" CONTINUATION_BYTE CONTINUATION_BYTE
  594. CHAR4: "\xf0" .. "\xf7" CONTINUATION_BYTE CONTINUATION_BYTE CONTINUATION_BYTE
  595. """
  596. g = _Lark(g, use_bytes=True)
  597. s = u"🔣 地? gurīn".encode('utf-8')
  598. self.assertEqual(len(g.parse(s).children), 10)
  599. for enc, j in [("sjis", u"地球の絵はグリーンでグッド? Chikyuu no e wa guriin de guddo"),
  600. ("sjis", u"売春婦"),
  601. ("euc-jp", u"乂鵬鵠")]:
  602. s = j.encode(enc)
  603. self.assertRaises(UnexpectedCharacters, g.parse, s)
  604. @unittest.skipIf(PARSER == 'cyk', "Takes forever")
  605. def test_stack_for_ebnf(self):
  606. """Verify that stack depth isn't an issue for EBNF grammars"""
  607. g = _Lark(r"""start: a+
  608. a : "a" """)
  609. g.parse("a" * (sys.getrecursionlimit()*2 ))
  610. def test_expand1_lists_with_one_item(self):
  611. g = _Lark(r"""start: list
  612. ?list: item+
  613. item : A
  614. A: "a"
  615. """)
  616. r = g.parse("a")
  617. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  618. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  619. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  620. self.assertEqual(len(r.children), 1)
  621. def test_expand1_lists_with_one_item_2(self):
  622. g = _Lark(r"""start: list
  623. ?list: item+ "!"
  624. item : A
  625. A: "a"
  626. """)
  627. r = g.parse("a!")
  628. # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item'
  629. self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',))
  630. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  631. self.assertEqual(len(r.children), 1)
  632. def test_dont_expand1_lists_with_multiple_items(self):
  633. g = _Lark(r"""start: list
  634. ?list: item+
  635. item : A
  636. A: "a"
  637. """)
  638. r = g.parse("aa")
  639. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  640. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  641. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  642. self.assertEqual(len(r.children), 1)
  643. # Sanity check: verify that 'list' contains the two 'item's we've given it
  644. [list] = r.children
  645. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  646. def test_dont_expand1_lists_with_multiple_items_2(self):
  647. g = _Lark(r"""start: list
  648. ?list: item+ "!"
  649. item : A
  650. A: "a"
  651. """)
  652. r = g.parse("aa!")
  653. # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded
  654. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  655. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  656. self.assertEqual(len(r.children), 1)
  657. # Sanity check: verify that 'list' contains the two 'item's we've given it
  658. [list] = r.children
  659. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  660. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  661. def test_empty_expand1_list(self):
  662. g = _Lark(r"""start: list
  663. ?list: item*
  664. item : A
  665. A: "a"
  666. """)
  667. r = g.parse("")
  668. # 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
  669. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  670. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  671. self.assertEqual(len(r.children), 1)
  672. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  673. [list] = r.children
  674. self.assertSequenceEqual([item.data for item in list.children], ())
  675. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  676. def test_empty_expand1_list_2(self):
  677. g = _Lark(r"""start: list
  678. ?list: item* "!"?
  679. item : A
  680. A: "a"
  681. """)
  682. r = g.parse("")
  683. # 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
  684. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  685. # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule
  686. self.assertEqual(len(r.children), 1)
  687. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  688. [list] = r.children
  689. self.assertSequenceEqual([item.data for item in list.children], ())
  690. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  691. def test_empty_flatten_list(self):
  692. g = _Lark(r"""start: list
  693. list: | item "," list
  694. item : A
  695. A: "a"
  696. """)
  697. r = g.parse("")
  698. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  699. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  700. # Sanity check: verify that 'list' contains no 'item's as we've given it none
  701. [list] = r.children
  702. self.assertSequenceEqual([item.data for item in list.children], ())
  703. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  704. def test_single_item_flatten_list(self):
  705. g = _Lark(r"""start: list
  706. list: | item "," list
  707. item : A
  708. A: "a"
  709. """)
  710. r = g.parse("a,")
  711. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  712. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  713. # Sanity check: verify that 'list' contains exactly the one 'item' we've given it
  714. [list] = r.children
  715. self.assertSequenceEqual([item.data for item in list.children], ('item',))
  716. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  717. def test_multiple_item_flatten_list(self):
  718. g = _Lark(r"""start: list
  719. #list: | item "," list
  720. item : A
  721. A: "a"
  722. """)
  723. r = g.parse("a,a,")
  724. # Because 'list' is a flatten rule it's top-level element should *never* be expanded
  725. self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',))
  726. # Sanity check: verify that 'list' contains exactly the two 'item's we've given it
  727. [list] = r.children
  728. self.assertSequenceEqual([item.data for item in list.children], ('item', 'item'))
  729. @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)")
  730. def test_recurse_flatten(self):
  731. """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening."""
  732. g = _Lark(r"""start: a | start a
  733. a : A
  734. A : "a" """)
  735. # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built
  736. # STree data structures, which uses recursion).
  737. g.parse("a" * (sys.getrecursionlimit() // 4))
  738. def test_token_collision(self):
  739. g = _Lark(r"""start: "Hello" NAME
  740. NAME: /\w/+
  741. %ignore " "
  742. """)
  743. x = g.parse('Hello World')
  744. self.assertSequenceEqual(x.children, ['World'])
  745. x = g.parse('Hello HelloWorld')
  746. self.assertSequenceEqual(x.children, ['HelloWorld'])
  747. def test_token_collision_WS(self):
  748. g = _Lark(r"""start: "Hello" NAME
  749. NAME: /\w/+
  750. %import common.WS
  751. %ignore WS
  752. """)
  753. x = g.parse('Hello World')
  754. self.assertSequenceEqual(x.children, ['World'])
  755. x = g.parse('Hello HelloWorld')
  756. self.assertSequenceEqual(x.children, ['HelloWorld'])
  757. def test_token_collision2(self):
  758. g = _Lark("""
  759. !start: "starts"
  760. %import common.LCASE_LETTER
  761. """)
  762. x = g.parse("starts")
  763. self.assertSequenceEqual(x.children, ['starts'])
  764. def test_templates(self):
  765. g = _Lark(r"""
  766. start: "[" sep{NUMBER, ","} "]"
  767. sep{item, delim}: item (delim item)*
  768. NUMBER: /\d+/
  769. %ignore " "
  770. """)
  771. x = g.parse("[1, 2, 3, 4]")
  772. self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])])
  773. x = g.parse("[1]")
  774. self.assertSequenceEqual(x.children, [Tree('sep', ['1'])])
  775. def test_templates_recursion(self):
  776. g = _Lark(r"""
  777. start: "[" _sep{NUMBER, ","} "]"
  778. _sep{item, delim}: item | _sep{item, delim} delim item
  779. NUMBER: /\d+/
  780. %ignore " "
  781. """)
  782. x = g.parse("[1, 2, 3, 4]")
  783. self.assertSequenceEqual(x.children, ['1', '2', '3', '4'])
  784. x = g.parse("[1]")
  785. self.assertSequenceEqual(x.children, ['1'])
  786. def test_templates_import(self):
  787. g = _Lark_open("test_templates_import.lark", rel_to=__file__)
  788. x = g.parse("[1, 2, 3, 4]")
  789. self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])])
  790. x = g.parse("[1]")
  791. self.assertSequenceEqual(x.children, [Tree('sep', ['1'])])
  792. def test_templates_alias(self):
  793. g = _Lark(r"""
  794. start: expr{"C"}
  795. expr{t}: "A" t
  796. | "B" t -> b
  797. """)
  798. x = g.parse("AC")
  799. self.assertSequenceEqual(x.children, [Tree('expr', [])])
  800. x = g.parse("BC")
  801. self.assertSequenceEqual(x.children, [Tree('b', [])])
  802. def test_templates_modifiers(self):
  803. g = _Lark(r"""
  804. start: expr{"B"}
  805. !expr{t}: "A" t
  806. """)
  807. x = g.parse("AB")
  808. self.assertSequenceEqual(x.children, [Tree('expr', ["A", "B"])])
  809. g = _Lark(r"""
  810. start: _expr{"B"}
  811. !_expr{t}: "A" t
  812. """)
  813. x = g.parse("AB")
  814. self.assertSequenceEqual(x.children, ["A", "B"])
  815. g = _Lark(r"""
  816. start: expr{b}
  817. b: "B"
  818. ?expr{t}: "A" t
  819. """)
  820. x = g.parse("AB")
  821. self.assertSequenceEqual(x.children, [Tree('b',[])])
  822. def test_templates_templates(self):
  823. g = _Lark('''start: a{b}
  824. a{t}: t{"a"}
  825. b{x}: x''')
  826. x = g.parse('a')
  827. self.assertSequenceEqual(x.children, [Tree('a', [Tree('b',[])])])
  828. def test_g_regex_flags(self):
  829. g = _Lark("""
  830. start: "a" /b+/ C
  831. C: "C" | D
  832. D: "D" E
  833. E: "e"
  834. """, g_regex_flags=re.I)
  835. x1 = g.parse("ABBc")
  836. x2 = g.parse("abdE")
  837. # def test_string_priority(self):
  838. # g = _Lark("""start: (A | /a?bb/)+
  839. # A: "a" """)
  840. # x = g.parse('abb')
  841. # self.assertEqual(len(x.children), 2)
  842. # # This parse raises an exception because the lexer will always try to consume
  843. # # "a" first and will never match the regular expression
  844. # # This behavior is subject to change!!
  845. # # Thie won't happen with ambiguity handling.
  846. # g = _Lark("""start: (A | /a?ab/)+
  847. # A: "a" """)
  848. # self.assertRaises(LexError, g.parse, 'aab')
  849. def test_undefined_rule(self):
  850. self.assertRaises(GrammarError, _Lark, """start: a""")
  851. def test_undefined_token(self):
  852. self.assertRaises(GrammarError, _Lark, """start: A""")
  853. def test_rule_collision(self):
  854. g = _Lark("""start: "a"+ "b"
  855. | "a"+ """)
  856. x = g.parse('aaaa')
  857. x = g.parse('aaaab')
  858. def test_rule_collision2(self):
  859. g = _Lark("""start: "a"* "b"
  860. | "a"+ """)
  861. x = g.parse('aaaa')
  862. x = g.parse('aaaab')
  863. x = g.parse('b')
  864. def test_token_not_anon(self):
  865. """Tests that "a" is matched as an anonymous token, and not A.
  866. """
  867. g = _Lark("""start: "a"
  868. A: "a" """)
  869. x = g.parse('a')
  870. self.assertEqual(len(x.children), 0, '"a" should be considered anonymous')
  871. g = _Lark("""start: "a" A
  872. A: "a" """)
  873. x = g.parse('aa')
  874. self.assertEqual(len(x.children), 1, 'only "a" should be considered anonymous')
  875. self.assertEqual(x.children[0].type, "A")
  876. g = _Lark("""start: /a/
  877. A: /a/ """)
  878. x = g.parse('a')
  879. self.assertEqual(len(x.children), 1)
  880. self.assertEqual(x.children[0].type, "A", "A isn't associated with /a/")
  881. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  882. def test_maybe(self):
  883. g = _Lark("""start: ["a"] """)
  884. x = g.parse('a')
  885. x = g.parse('')
  886. def test_start(self):
  887. g = _Lark("""a: "a" a? """, start='a')
  888. x = g.parse('a')
  889. x = g.parse('aa')
  890. x = g.parse('aaa')
  891. def test_alias(self):
  892. g = _Lark("""start: "a" -> b """)
  893. x = g.parse('a')
  894. self.assertEqual(x.data, "b")
  895. def test_token_ebnf(self):
  896. g = _Lark("""start: A
  897. A: "a"* ("b"? "c".."e")+
  898. """)
  899. x = g.parse('abcde')
  900. x = g.parse('dd')
  901. def test_backslash(self):
  902. g = _Lark(r"""start: "\\" "a"
  903. """)
  904. x = g.parse(r'\a')
  905. g = _Lark(r"""start: /\\/ /a/
  906. """)
  907. x = g.parse(r'\a')
  908. def test_backslash2(self):
  909. g = _Lark(r"""start: "\"" "-"
  910. """)
  911. x = g.parse('"-')
  912. g = _Lark(r"""start: /\// /-/
  913. """)
  914. x = g.parse('/-')
  915. def test_special_chars(self):
  916. g = _Lark(r"""start: "\n"
  917. """)
  918. x = g.parse('\n')
  919. g = _Lark(r"""start: /\n/
  920. """)
  921. x = g.parse('\n')
  922. # def test_token_recurse(self):
  923. # g = _Lark("""start: A
  924. # A: B
  925. # B: A
  926. # """)
  927. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  928. def test_empty(self):
  929. # Fails an Earley implementation without special handling for empty rules,
  930. # or re-processing of already completed rules.
  931. g = _Lark(r"""start: _empty a "B"
  932. a: _empty "A"
  933. _empty:
  934. """)
  935. x = g.parse('AB')
  936. def test_regex_quote(self):
  937. g = r"""
  938. start: SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING
  939. SINGLE_QUOTED_STRING : /'[^']*'/
  940. DOUBLE_QUOTED_STRING : /"[^"]*"/
  941. """
  942. g = _Lark(g)
  943. self.assertEqual( g.parse('"hello"').children, ['"hello"'])
  944. self.assertEqual( g.parse("'hello'").children, ["'hello'"])
  945. @unittest.skipIf(not Py36, "Required re syntax only exists in python3.6+")
  946. def test_join_regex_flags(self):
  947. g = r"""
  948. start: A
  949. A: B C
  950. B: /./s
  951. C: /./
  952. """
  953. g = _Lark(g)
  954. self.assertEqual(g.parse(" ").children,[" "])
  955. self.assertEqual(g.parse("\n ").children,["\n "])
  956. self.assertRaises(UnexpectedCharacters, g.parse, "\n\n")
  957. g = r"""
  958. start: A
  959. A: B | C
  960. B: "b"i
  961. C: "c"
  962. """
  963. g = _Lark(g)
  964. self.assertEqual(g.parse("b").children,["b"])
  965. self.assertEqual(g.parse("B").children,["B"])
  966. self.assertEqual(g.parse("c").children,["c"])
  967. self.assertRaises(UnexpectedCharacters, g.parse, "C")
  968. def test_lexer_token_limit(self):
  969. "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation"
  970. tokens = {'A%d'%i:'"%d"'%i for i in range(300)}
  971. g = _Lark("""start: %s
  972. %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items())))
  973. def test_float_without_lexer(self):
  974. expected_error = UnexpectedCharacters if LEXER.startswith('dynamic') else UnexpectedToken
  975. if PARSER == 'cyk':
  976. expected_error = ParseError
  977. g = _Lark("""start: ["+"|"-"] float
  978. float: digit* "." digit+ exp?
  979. | digit+ exp
  980. exp: ("e"|"E") ["+"|"-"] digit+
  981. digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"
  982. """)
  983. g.parse("1.2")
  984. g.parse("-.2e9")
  985. g.parse("+2e-9")
  986. self.assertRaises( expected_error, g.parse, "+2e-9e")
  987. def test_keep_all_tokens(self):
  988. l = _Lark("""start: "a"+ """, keep_all_tokens=True)
  989. tree = l.parse('aaa')
  990. self.assertEqual(tree.children, ['a', 'a', 'a'])
  991. def test_token_flags(self):
  992. l = _Lark("""!start: "a"i+
  993. """
  994. )
  995. tree = l.parse('aA')
  996. self.assertEqual(tree.children, ['a', 'A'])
  997. l = _Lark("""!start: /a/i+
  998. """
  999. )
  1000. tree = l.parse('aA')
  1001. self.assertEqual(tree.children, ['a', 'A'])
  1002. # g = """!start: "a"i "a"
  1003. # """
  1004. # self.assertRaises(GrammarError, _Lark, g)
  1005. # g = """!start: /a/i /a/
  1006. # """
  1007. # self.assertRaises(GrammarError, _Lark, g)
  1008. g = """start: NAME "," "a"
  1009. NAME: /[a-z_]/i /[a-z0-9_]/i*
  1010. """
  1011. l = _Lark(g)
  1012. tree = l.parse('ab,a')
  1013. self.assertEqual(tree.children, ['ab'])
  1014. tree = l.parse('AB,a')
  1015. self.assertEqual(tree.children, ['AB'])
  1016. def test_token_flags3(self):
  1017. l = _Lark("""!start: ABC+
  1018. ABC: "abc"i
  1019. """
  1020. )
  1021. tree = l.parse('aBcAbC')
  1022. self.assertEqual(tree.children, ['aBc', 'AbC'])
  1023. def test_token_flags2(self):
  1024. g = """!start: ("a"i | /a/ /b/?)+
  1025. """
  1026. l = _Lark(g)
  1027. tree = l.parse('aA')
  1028. self.assertEqual(tree.children, ['a', 'A'])
  1029. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1030. def test_twice_empty(self):
  1031. g = """!start: ("A"?)?
  1032. """
  1033. l = _Lark(g)
  1034. tree = l.parse('A')
  1035. self.assertEqual(tree.children, ['A'])
  1036. tree = l.parse('')
  1037. self.assertEqual(tree.children, [])
  1038. def test_undefined_ignore(self):
  1039. g = """!start: "A"
  1040. %ignore B
  1041. """
  1042. self.assertRaises( GrammarError, _Lark, g)
  1043. def test_alias_in_terminal(self):
  1044. g = """start: TERM
  1045. TERM: "a" -> alias
  1046. """
  1047. self.assertRaises( GrammarError, _Lark, g)
  1048. def test_line_and_column(self):
  1049. g = r"""!start: "A" bc "D"
  1050. !bc: "B\nC"
  1051. """
  1052. l = _Lark(g)
  1053. a, bc, d = l.parse("AB\nCD").children
  1054. self.assertEqual(a.line, 1)
  1055. self.assertEqual(a.column, 1)
  1056. bc ,= bc.children
  1057. self.assertEqual(bc.line, 1)
  1058. self.assertEqual(bc.column, 2)
  1059. self.assertEqual(d.line, 2)
  1060. self.assertEqual(d.column, 2)
  1061. if LEXER != 'dynamic':
  1062. self.assertEqual(a.end_line, 1)
  1063. self.assertEqual(a.end_column, 2)
  1064. self.assertEqual(bc.end_line, 2)
  1065. self.assertEqual(bc.end_column, 2)
  1066. self.assertEqual(d.end_line, 2)
  1067. self.assertEqual(d.end_column, 3)
  1068. def test_reduce_cycle(self):
  1069. """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state.
  1070. It seems that the correct solution is to explicitely distinguish finalization in the reduce() function.
  1071. """
  1072. l = _Lark("""
  1073. term: A
  1074. | term term
  1075. A: "a"
  1076. """, start='term')
  1077. tree = l.parse("aa")
  1078. self.assertEqual(len(tree.children), 2)
  1079. @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority")
  1080. def test_lexer_prioritization(self):
  1081. "Tests effect of priority on result"
  1082. grammar = """
  1083. start: A B | AB
  1084. A.2: "a"
  1085. B: "b"
  1086. AB: "ab"
  1087. """
  1088. l = _Lark(grammar)
  1089. res = l.parse("ab")
  1090. self.assertEqual(res.children, ['a', 'b'])
  1091. self.assertNotEqual(res.children, ['ab'])
  1092. grammar = """
  1093. start: A B | AB
  1094. A: "a"
  1095. B: "b"
  1096. AB.3: "ab"
  1097. """
  1098. l = _Lark(grammar)
  1099. res = l.parse("ab")
  1100. self.assertNotEqual(res.children, ['a', 'b'])
  1101. self.assertEqual(res.children, ['ab'])
  1102. grammar = """
  1103. start: A B | AB
  1104. A: "a"
  1105. B.-20: "b"
  1106. AB.-10: "ab"
  1107. """
  1108. l = _Lark(grammar)
  1109. res = l.parse("ab")
  1110. self.assertEqual(res.children, ['a', 'b'])
  1111. grammar = """
  1112. start: A B | AB
  1113. A.-99999999999999999999999: "a"
  1114. B: "b"
  1115. AB: "ab"
  1116. """
  1117. l = _Lark(grammar)
  1118. res = l.parse("ab")
  1119. self.assertEqual(res.children, ['ab'])
  1120. def test_import(self):
  1121. grammar = """
  1122. start: NUMBER WORD
  1123. %import common.NUMBER
  1124. %import common.WORD
  1125. %import common.WS
  1126. %ignore WS
  1127. """
  1128. l = _Lark(grammar)
  1129. x = l.parse('12 elephants')
  1130. self.assertEqual(x.children, ['12', 'elephants'])
  1131. def test_import_rename(self):
  1132. grammar = """
  1133. start: N W
  1134. %import common.NUMBER -> N
  1135. %import common.WORD -> W
  1136. %import common.WS
  1137. %ignore WS
  1138. """
  1139. l = _Lark(grammar)
  1140. x = l.parse('12 elephants')
  1141. self.assertEqual(x.children, ['12', 'elephants'])
  1142. def test_relative_import(self):
  1143. l = _Lark_open('test_relative_import.lark', rel_to=__file__)
  1144. x = l.parse('12 lions')
  1145. self.assertEqual(x.children, ['12', 'lions'])
  1146. def test_relative_import_unicode(self):
  1147. l = _Lark_open('test_relative_import_unicode.lark', rel_to=__file__)
  1148. x = l.parse(u'Ø')
  1149. self.assertEqual(x.children, [u'Ø'])
  1150. def test_relative_import_rename(self):
  1151. l = _Lark_open('test_relative_import_rename.lark', rel_to=__file__)
  1152. x = l.parse('12 lions')
  1153. self.assertEqual(x.children, ['12', 'lions'])
  1154. def test_relative_rule_import(self):
  1155. l = _Lark_open('test_relative_rule_import.lark', rel_to=__file__)
  1156. x = l.parse('xaabby')
  1157. self.assertEqual(x.children, [
  1158. 'x',
  1159. Tree('expr', ['a', Tree('expr', ['a', 'b']), 'b']),
  1160. 'y'])
  1161. def test_relative_rule_import_drop_ignore(self):
  1162. # %ignore rules are dropped on import
  1163. l = _Lark_open('test_relative_rule_import_drop_ignore.lark',
  1164. rel_to=__file__)
  1165. self.assertRaises((ParseError, UnexpectedInput),
  1166. l.parse, 'xa abby')
  1167. def test_relative_rule_import_subrule(self):
  1168. l = _Lark_open('test_relative_rule_import_subrule.lark',
  1169. rel_to=__file__)
  1170. x = l.parse('xaabby')
  1171. self.assertEqual(x.children, [
  1172. 'x',
  1173. Tree('startab', [
  1174. Tree('grammars__ab__expr', [
  1175. 'a', Tree('grammars__ab__expr', ['a', 'b']), 'b',
  1176. ]),
  1177. ]),
  1178. 'y'])
  1179. def test_relative_rule_import_subrule_no_conflict(self):
  1180. l = _Lark_open(
  1181. 'test_relative_rule_import_subrule_no_conflict.lark',
  1182. rel_to=__file__)
  1183. x = l.parse('xaby')
  1184. self.assertEqual(x.children, [Tree('expr', [
  1185. 'x',
  1186. Tree('startab', [
  1187. Tree('grammars__ab__expr', ['a', 'b']),
  1188. ]),
  1189. 'y'])])
  1190. self.assertRaises((ParseError, UnexpectedInput),
  1191. l.parse, 'xaxabyby')
  1192. def test_relative_rule_import_rename(self):
  1193. l = _Lark_open('test_relative_rule_import_rename.lark',
  1194. rel_to=__file__)
  1195. x = l.parse('xaabby')
  1196. self.assertEqual(x.children, [
  1197. 'x',
  1198. Tree('ab', ['a', Tree('ab', ['a', 'b']), 'b']),
  1199. 'y'])
  1200. def test_multi_import(self):
  1201. grammar = """
  1202. start: NUMBER WORD
  1203. %import common (NUMBER, WORD, WS)
  1204. %ignore WS
  1205. """
  1206. l = _Lark(grammar)
  1207. x = l.parse('12 toucans')
  1208. self.assertEqual(x.children, ['12', 'toucans'])
  1209. def test_relative_multi_import(self):
  1210. l = _Lark_open("test_relative_multi_import.lark", rel_to=__file__)
  1211. x = l.parse('12 capybaras')
  1212. self.assertEqual(x.children, ['12', 'capybaras'])
  1213. def test_relative_import_preserves_leading_underscore(self):
  1214. l = _Lark_open("test_relative_import_preserves_leading_underscore.lark", rel_to=__file__)
  1215. x = l.parse('Ax')
  1216. self.assertEqual(next(x.find_data('c')).children, ['A'])
  1217. def test_relative_import_of_nested_grammar(self):
  1218. l = _Lark_open("grammars/test_relative_import_of_nested_grammar.lark", rel_to=__file__)
  1219. x = l.parse('N')
  1220. self.assertEqual(next(x.find_data('rule_to_import')).children, ['N'])
  1221. def test_relative_import_rules_dependencies_imported_only_once(self):
  1222. l = _Lark_open("test_relative_import_rules_dependencies_imported_only_once.lark", rel_to=__file__)
  1223. x = l.parse('AAA')
  1224. self.assertEqual(next(x.find_data('a')).children, ['A'])
  1225. self.assertEqual(next(x.find_data('b')).children, ['A'])
  1226. self.assertEqual(next(x.find_data('d')).children, ['A'])
  1227. def test_import_errors(self):
  1228. grammar = """
  1229. start: NUMBER WORD
  1230. %import .grammars.bad_test.NUMBER
  1231. """
  1232. self.assertRaises(IOError, _Lark, grammar)
  1233. grammar = """
  1234. start: NUMBER WORD
  1235. %import bad_test.NUMBER
  1236. """
  1237. self.assertRaises(IOError, _Lark, grammar)
  1238. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  1239. def test_earley_prioritization(self):
  1240. "Tests effect of priority on result"
  1241. grammar = """
  1242. start: a | b
  1243. a.1: "a"
  1244. b.2: "a"
  1245. """
  1246. # l = Lark(grammar, parser='earley', lexer='standard')
  1247. l = _Lark(grammar)
  1248. res = l.parse("a")
  1249. self.assertEqual(res.children[0].data, 'b')
  1250. grammar = """
  1251. start: a | b
  1252. a.2: "a"
  1253. b.1: "a"
  1254. """
  1255. l = _Lark(grammar)
  1256. # l = Lark(grammar, parser='earley', lexer='standard')
  1257. res = l.parse("a")
  1258. self.assertEqual(res.children[0].data, 'a')
  1259. @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules")
  1260. def test_earley_prioritization_sum(self):
  1261. "Tests effect of priority on result"
  1262. grammar = """
  1263. start: ab_ b_ a_ | indirection
  1264. indirection: a_ bb_ a_
  1265. a_: "a"
  1266. b_: "b"
  1267. ab_: "ab"
  1268. bb_.1: "bb"
  1269. """
  1270. l = Lark(grammar, priority="invert")
  1271. res = l.parse('abba')
  1272. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1273. grammar = """
  1274. start: ab_ b_ a_ | indirection
  1275. indirection: a_ bb_ a_
  1276. a_: "a"
  1277. b_: "b"
  1278. ab_.1: "ab"
  1279. bb_: "bb"
  1280. """
  1281. l = Lark(grammar, priority="invert")
  1282. res = l.parse('abba')
  1283. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1284. grammar = """
  1285. start: ab_ b_ a_ | indirection
  1286. indirection: a_ bb_ a_
  1287. a_.2: "a"
  1288. b_.1: "b"
  1289. ab_.3: "ab"
  1290. bb_.3: "bb"
  1291. """
  1292. l = Lark(grammar, priority="invert")
  1293. res = l.parse('abba')
  1294. self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_')
  1295. grammar = """
  1296. start: ab_ b_ a_ | indirection
  1297. indirection: a_ bb_ a_
  1298. a_.1: "a"
  1299. b_.1: "b"
  1300. ab_.4: "ab"
  1301. bb_.3: "bb"
  1302. """
  1303. l = Lark(grammar, priority="invert")
  1304. res = l.parse('abba')
  1305. self.assertEqual(''.join(child.data for child in res.children), 'indirection')
  1306. def test_utf8(self):
  1307. g = u"""start: a
  1308. a: "±a"
  1309. """
  1310. l = _Lark(g)
  1311. self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])]))
  1312. g = u"""start: A
  1313. A: "±a"
  1314. """
  1315. l = _Lark(g)
  1316. self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a']))
  1317. @unittest.skipIf(PARSER == 'cyk', "No empty rules")
  1318. def test_ignore(self):
  1319. grammar = r"""
  1320. COMMENT: /(!|(\/\/))[^\n]*/
  1321. %ignore COMMENT
  1322. %import common.WS -> _WS
  1323. %import common.INT
  1324. start: "INT"i _WS+ INT _WS*
  1325. """
  1326. parser = _Lark(grammar)
  1327. tree = parser.parse("int 1 ! This is a comment\n")
  1328. self.assertEqual(tree.children, ['1'])
  1329. tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky!
  1330. self.assertEqual(tree.children, ['1'])
  1331. parser = _Lark(r"""
  1332. start : "a"*
  1333. %ignore "b"
  1334. """)
  1335. tree = parser.parse("bb")
  1336. self.assertEqual(tree.children, [])
  1337. def test_regex_escaping(self):
  1338. g = _Lark("start: /[ab]/")
  1339. g.parse('a')
  1340. g.parse('b')
  1341. self.assertRaises( UnexpectedInput, g.parse, 'c')
  1342. _Lark(r'start: /\w/').parse('a')
  1343. g = _Lark(r'start: /\\w/')
  1344. self.assertRaises( UnexpectedInput, g.parse, 'a')
  1345. g.parse(r'\w')
  1346. _Lark(r'start: /\[/').parse('[')
  1347. _Lark(r'start: /\//').parse('/')
  1348. _Lark(r'start: /\\/').parse('\\')
  1349. _Lark(r'start: /\[ab]/').parse('[ab]')
  1350. _Lark(r'start: /\\[ab]/').parse('\\a')
  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. _Lark(r'start: "\\\t"').parse('\\\t')
  1357. def test_ranged_repeat_rules(self):
  1358. g = u"""!start: "A"~3
  1359. """
  1360. l = _Lark(g)
  1361. self.assertEqual(l.parse(u'AAA'), Tree('start', ["A", "A", "A"]))
  1362. self.assertRaises(ParseError, l.parse, u'AA')
  1363. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1364. g = u"""!start: "A"~0..2
  1365. """
  1366. if PARSER != 'cyk': # XXX CYK currently doesn't support empty grammars
  1367. l = _Lark(g)
  1368. self.assertEqual(l.parse(u''), Tree('start', []))
  1369. self.assertEqual(l.parse(u'A'), Tree('start', ['A']))
  1370. self.assertEqual(l.parse(u'AA'), Tree('start', ['A', 'A']))
  1371. self.assertRaises((UnexpectedToken, UnexpectedInput), l.parse, u'AAA')
  1372. g = u"""!start: "A"~3..2
  1373. """
  1374. self.assertRaises(GrammarError, _Lark, g)
  1375. g = u"""!start: "A"~2..3 "B"~2
  1376. """
  1377. l = _Lark(g)
  1378. self.assertEqual(l.parse(u'AABB'), Tree('start', ['A', 'A', 'B', 'B']))
  1379. self.assertEqual(l.parse(u'AAABB'), Tree('start', ['A', 'A', 'A', 'B', 'B']))
  1380. self.assertRaises(ParseError, l.parse, u'AAAB')
  1381. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1382. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1383. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1384. def test_ranged_repeat_terms(self):
  1385. g = u"""!start: AAA
  1386. AAA: "A"~3
  1387. """
  1388. l = _Lark(g)
  1389. self.assertEqual(l.parse(u'AAA'), Tree('start', ["AAA"]))
  1390. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AA')
  1391. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA')
  1392. g = u"""!start: AABB CC
  1393. AABB: "A"~0..2 "B"~2
  1394. CC: "C"~1..2
  1395. """
  1396. l = _Lark(g)
  1397. self.assertEqual(l.parse(u'AABBCC'), Tree('start', ['AABB', 'CC']))
  1398. self.assertEqual(l.parse(u'BBC'), Tree('start', ['BB', 'C']))
  1399. self.assertEqual(l.parse(u'ABBCC'), Tree('start', ['ABB', 'CC']))
  1400. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAB')
  1401. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB')
  1402. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB')
  1403. self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB')
  1404. @unittest.skipIf(PARSER=='earley', "Priority not handled correctly right now") # TODO XXX
  1405. def test_priority_vs_embedded(self):
  1406. g = """
  1407. A.2: "a"
  1408. WORD: ("a".."z")+
  1409. start: (A | WORD)+
  1410. """
  1411. l = _Lark(g)
  1412. t = l.parse('abc')
  1413. self.assertEqual(t.children, ['a', 'bc'])
  1414. self.assertEqual(t.children[0].type, 'A')
  1415. def test_line_counting(self):
  1416. p = _Lark("start: /[^x]+/")
  1417. text = 'hello\nworld'
  1418. t = p.parse(text)
  1419. tok = t.children[0]
  1420. self.assertEqual(tok, text)
  1421. self.assertEqual(tok.line, 1)
  1422. self.assertEqual(tok.column, 1)
  1423. if _LEXER != 'dynamic':
  1424. self.assertEqual(tok.end_line, 2)
  1425. self.assertEqual(tok.end_column, 6)
  1426. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1427. def test_empty_end(self):
  1428. p = _Lark("""
  1429. start: b c d
  1430. b: "B"
  1431. c: | "C"
  1432. d: | "D"
  1433. """)
  1434. res = p.parse('B')
  1435. self.assertEqual(len(res.children), 3)
  1436. @unittest.skipIf(PARSER=='cyk', "Empty rules")
  1437. def test_maybe_placeholders(self):
  1438. # Anonymous tokens shouldn't count
  1439. p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1440. self.assertEqual(p.parse("").children, [])
  1441. # All invisible constructs shouldn't count
  1442. p = _Lark("""start: [A] ["b"] [_c] ["e" "f" _c]
  1443. A: "a"
  1444. _c: "c" """, maybe_placeholders=True)
  1445. self.assertEqual(p.parse("").children, [None])
  1446. self.assertEqual(p.parse("c").children, [None])
  1447. self.assertEqual(p.parse("aefc").children, ['a'])
  1448. # ? shouldn't apply
  1449. p = _Lark("""!start: ["a"] "b"? ["c"] """, maybe_placeholders=True)
  1450. self.assertEqual(p.parse("").children, [None, None])
  1451. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1452. p = _Lark("""!start: ["a"] ["b"] ["c"] """, maybe_placeholders=True)
  1453. self.assertEqual(p.parse("").children, [None, None, None])
  1454. self.assertEqual(p.parse("a").children, ['a', None, None])
  1455. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1456. self.assertEqual(p.parse("c").children, [None, None, 'c'])
  1457. self.assertEqual(p.parse("ab").children, ['a', 'b', None])
  1458. self.assertEqual(p.parse("ac").children, ['a', None, 'c'])
  1459. self.assertEqual(p.parse("bc").children, [None, 'b', 'c'])
  1460. self.assertEqual(p.parse("abc").children, ['a', 'b', 'c'])
  1461. p = _Lark("""!start: (["a"] "b" ["c"])+ """, maybe_placeholders=True)
  1462. self.assertEqual(p.parse("b").children, [None, 'b', None])
  1463. self.assertEqual(p.parse("bb").children, [None, 'b', None, None, 'b', None])
  1464. self.assertEqual(p.parse("abbc").children, ['a', 'b', None, None, 'b', 'c'])
  1465. self.assertEqual(p.parse("babbcabcb").children,
  1466. [None, 'b', None,
  1467. 'a', 'b', None,
  1468. None, 'b', 'c',
  1469. 'a', 'b', 'c',
  1470. None, 'b', None])
  1471. p = _Lark("""!start: ["a"] ["c"] "b"+ ["a"] ["d"] """, maybe_placeholders=True)
  1472. self.assertEqual(p.parse("bb").children, [None, None, 'b', 'b', None, None])
  1473. self.assertEqual(p.parse("bd").children, [None, None, 'b', None, 'd'])
  1474. self.assertEqual(p.parse("abba").children, ['a', None, 'b', 'b', 'a', None])
  1475. self.assertEqual(p.parse("cbbbb").children, [None, 'c', 'b', 'b', 'b', 'b', None, None])
  1476. def test_escaped_string(self):
  1477. "Tests common.ESCAPED_STRING"
  1478. grammar = r"""
  1479. start: ESCAPED_STRING+
  1480. %import common (WS_INLINE, ESCAPED_STRING)
  1481. %ignore WS_INLINE
  1482. """
  1483. parser = _Lark(grammar)
  1484. parser.parse(r'"\\" "b" "c"')
  1485. parser.parse(r'"That" "And a \"b"')
  1486. def test_meddling_unused(self):
  1487. "Unless 'unused' is removed, LALR analysis will fail on reduce-reduce collision"
  1488. grammar = """
  1489. start: EKS* x
  1490. x: EKS
  1491. unused: x*
  1492. EKS: "x"
  1493. """
  1494. parser = _Lark(grammar)
  1495. @unittest.skipIf(PARSER!='lalr' or LEXER=='custom', "Serialize currently only works for LALR parsers without custom lexers (though it should be easy to extend)")
  1496. def test_serialize(self):
  1497. grammar = """
  1498. start: _ANY b "C"
  1499. _ANY: /./
  1500. b: "B"
  1501. """
  1502. parser = _Lark(grammar)
  1503. s = BytesIO()
  1504. parser.save(s)
  1505. s.seek(0)
  1506. parser2 = Lark.load(s)
  1507. self.assertEqual(parser2.parse('ABC'), Tree('start', [Tree('b', [])]) )
  1508. def test_multi_start(self):
  1509. parser = _Lark('''
  1510. a: "x" "a"?
  1511. b: "x" "b"?
  1512. ''', start=['a', 'b'])
  1513. self.assertEqual(parser.parse('xa', 'a'), Tree('a', []))
  1514. self.assertEqual(parser.parse('xb', 'b'), Tree('b', []))
  1515. def test_lexer_detect_newline_tokens(self):
  1516. # Detect newlines in regular tokens
  1517. g = _Lark(r"""start: "go" tail*
  1518. !tail : SA "@" | SB "@" | SC "@" | SD "@"
  1519. SA : "a" /\n/
  1520. SB : /b./s
  1521. SC : "c" /[^a-z]/
  1522. SD : "d" /\s/
  1523. """)
  1524. a,b,c,d = [x.children[1] for x in g.parse('goa\n@b\n@c\n@d\n@').children]
  1525. self.assertEqual(a.line, 2)
  1526. self.assertEqual(b.line, 3)
  1527. self.assertEqual(c.line, 4)
  1528. self.assertEqual(d.line, 5)
  1529. # Detect newlines in ignored tokens
  1530. for re in ['/\\n/', '/[^a-z]/', '/\\s/']:
  1531. g = _Lark('''!start: "a" "a"
  1532. %ignore {}'''.format(re))
  1533. a, b = g.parse('a\na').children
  1534. self.assertEqual(a.line, 1)
  1535. self.assertEqual(b.line, 2)
  1536. @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.')
  1537. def test_unicode_class(self):
  1538. "Tests that character classes from the `regex` module work correctly."
  1539. g = _Lark(r"""?start: NAME
  1540. NAME: ID_START ID_CONTINUE*
  1541. ID_START: /[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_]+/
  1542. ID_CONTINUE: ID_START | /[\p{Mn}\p{Mc}\p{Nd}\p{Pc}]+/""", regex=True)
  1543. self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்')
  1544. @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.')
  1545. def test_unicode_word(self):
  1546. "Tests that a persistent bug in the `re` module works when `regex` is enabled."
  1547. g = _Lark(r"""?start: NAME
  1548. NAME: /[\w]+/
  1549. """, regex=True)
  1550. self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்')
  1551. _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize()
  1552. _TestParser.__name__ = _NAME
  1553. _TestParser.__qualname__ = "tests.test_parser." + _NAME
  1554. globals()[_NAME] = _TestParser
  1555. # Note: You still have to import them in __main__ for the tests to run
  1556. _TO_TEST = [
  1557. ('standard', 'earley'),
  1558. ('standard', 'cyk'),
  1559. ('dynamic', 'earley'),
  1560. ('dynamic_complete', 'earley'),
  1561. ('standard', 'lalr'),
  1562. ('contextual', 'lalr'),
  1563. ('custom', 'lalr'),
  1564. # (None, 'earley'),
  1565. ]
  1566. for _LEXER, _PARSER in _TO_TEST:
  1567. _make_parser_test(_LEXER, _PARSER)
  1568. for _LEXER in ('dynamic', 'dynamic_complete'):
  1569. _make_full_earley_test(_LEXER)
  1570. if __name__ == '__main__':
  1571. unittest.main()