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.

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