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.

1355 lines
50 KiB

  1. """Parses and creates Grammar objects"""
  2. import hashlib
  3. import os.path
  4. import sys
  5. from collections import namedtuple
  6. from copy import copy, deepcopy
  7. from io import open
  8. import pkgutil
  9. from ast import literal_eval
  10. from numbers import Integral
  11. from .utils import bfs, Py36, logger, classify_bool, is_id_continue, is_id_start, bfs_all_unique, small_factors
  12. from .lexer import Token, TerminalDef, PatternStr, PatternRE
  13. from .parse_tree_builder import ParseTreeBuilder
  14. from .parser_frontends import ParsingFrontend
  15. from .common import LexerConf, ParserConf
  16. from .grammar import RuleOptions, Rule, Terminal, NonTerminal, Symbol
  17. from .utils import classify, suppress, dedup_list, Str
  18. from .exceptions import GrammarError, UnexpectedCharacters, UnexpectedToken, ParseError
  19. from .tree import Tree, SlottedTree as ST
  20. from .visitors import Transformer, Visitor, v_args, Transformer_InPlace, Transformer_NonRecursive
  21. inline_args = v_args(inline=True)
  22. __path__ = os.path.dirname(__file__)
  23. IMPORT_PATHS = ['grammars']
  24. EXT = '.lark'
  25. _RE_FLAGS = 'imslux'
  26. _EMPTY = Symbol('__empty__')
  27. _TERMINAL_NAMES = {
  28. '.' : 'DOT',
  29. ',' : 'COMMA',
  30. ':' : 'COLON',
  31. ';' : 'SEMICOLON',
  32. '+' : 'PLUS',
  33. '-' : 'MINUS',
  34. '*' : 'STAR',
  35. '/' : 'SLASH',
  36. '\\' : 'BACKSLASH',
  37. '|' : 'VBAR',
  38. '?' : 'QMARK',
  39. '!' : 'BANG',
  40. '@' : 'AT',
  41. '#' : 'HASH',
  42. '$' : 'DOLLAR',
  43. '%' : 'PERCENT',
  44. '^' : 'CIRCUMFLEX',
  45. '&' : 'AMPERSAND',
  46. '_' : 'UNDERSCORE',
  47. '<' : 'LESSTHAN',
  48. '>' : 'MORETHAN',
  49. '=' : 'EQUAL',
  50. '"' : 'DBLQUOTE',
  51. '\'' : 'QUOTE',
  52. '`' : 'BACKQUOTE',
  53. '~' : 'TILDE',
  54. '(' : 'LPAR',
  55. ')' : 'RPAR',
  56. '{' : 'LBRACE',
  57. '}' : 'RBRACE',
  58. '[' : 'LSQB',
  59. ']' : 'RSQB',
  60. '\n' : 'NEWLINE',
  61. '\r\n' : 'CRLF',
  62. '\t' : 'TAB',
  63. ' ' : 'SPACE',
  64. }
  65. # Grammar Parser
  66. TERMINALS = {
  67. '_LPAR': r'\(',
  68. '_RPAR': r'\)',
  69. '_LBRA': r'\[',
  70. '_RBRA': r'\]',
  71. '_LBRACE': r'\{',
  72. '_RBRACE': r'\}',
  73. 'OP': '[+*]|[?](?![a-z])',
  74. '_COLON': ':',
  75. '_COMMA': ',',
  76. '_OR': r'\|',
  77. '_DOT': r'\.(?!\.)',
  78. '_DOTDOT': r'\.\.',
  79. 'TILDE': '~',
  80. 'RULE': '!?[_?]?[a-z][_a-z0-9]*',
  81. 'TERMINAL': '_?[A-Z][_A-Z0-9]*',
  82. 'STRING': r'"(\\"|\\\\|[^"\n])*?"i?',
  83. 'REGEXP': r'/(?!/)(\\/|\\\\|[^/])*?/[%s]*' % _RE_FLAGS,
  84. '_NL': r'(\r?\n)+\s*',
  85. '_NL_OR': r'(\r?\n)+\s*\|',
  86. 'WS': r'[ \t]+',
  87. 'COMMENT': r'\s*//[^\n]*',
  88. 'BACKSLASH': r'\\[ ]*\n',
  89. '_TO': '->',
  90. '_IGNORE': r'%ignore',
  91. '_OVERRIDE': r'%override',
  92. '_DECLARE': r'%declare',
  93. '_EXTEND': r'%extend',
  94. '_IMPORT': r'%import',
  95. 'NUMBER': r'[+-]?\d+',
  96. }
  97. RULES = {
  98. 'start': ['_list'],
  99. '_list': ['_item', '_list _item'],
  100. '_item': ['rule', 'term', 'ignore', 'import', 'declare', 'override', 'extend', '_NL'],
  101. 'rule': ['RULE template_params _COLON expansions _NL',
  102. 'RULE template_params _DOT NUMBER _COLON expansions _NL'],
  103. 'template_params': ['_LBRACE _template_params _RBRACE',
  104. ''],
  105. '_template_params': ['RULE',
  106. '_template_params _COMMA RULE'],
  107. 'expansions': ['_expansions'],
  108. '_expansions': ['alias',
  109. '_expansions _OR alias',
  110. '_expansions _NL_OR alias'],
  111. '?alias': ['expansion _TO RULE', 'expansion'],
  112. 'expansion': ['_expansion'],
  113. '_expansion': ['', '_expansion expr'],
  114. '?expr': ['atom',
  115. 'atom OP',
  116. 'atom TILDE NUMBER',
  117. 'atom TILDE NUMBER _DOTDOT NUMBER',
  118. ],
  119. '?atom': ['_LPAR expansions _RPAR',
  120. 'maybe',
  121. 'value'],
  122. 'value': ['terminal',
  123. 'nonterminal',
  124. 'literal',
  125. 'range',
  126. 'template_usage'],
  127. 'terminal': ['TERMINAL'],
  128. 'nonterminal': ['RULE'],
  129. '?name': ['RULE', 'TERMINAL'],
  130. 'maybe': ['_LBRA expansions _RBRA'],
  131. 'range': ['STRING _DOTDOT STRING'],
  132. 'template_usage': ['RULE _LBRACE _template_args _RBRACE'],
  133. '_template_args': ['value',
  134. '_template_args _COMMA value'],
  135. 'term': ['TERMINAL _COLON expansions _NL',
  136. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  137. 'override': ['_OVERRIDE rule',
  138. '_OVERRIDE term'],
  139. 'extend': ['_EXTEND rule',
  140. '_EXTEND term'],
  141. 'ignore': ['_IGNORE expansions _NL'],
  142. 'declare': ['_DECLARE _declare_args _NL'],
  143. 'import': ['_IMPORT _import_path _NL',
  144. '_IMPORT _import_path _LPAR name_list _RPAR _NL',
  145. '_IMPORT _import_path _TO name _NL'],
  146. '_import_path': ['import_lib', 'import_rel'],
  147. 'import_lib': ['_import_args'],
  148. 'import_rel': ['_DOT _import_args'],
  149. '_import_args': ['name', '_import_args _DOT name'],
  150. 'name_list': ['_name_list'],
  151. '_name_list': ['name', '_name_list _COMMA name'],
  152. '_declare_args': ['name', '_declare_args name'],
  153. 'literal': ['REGEXP', 'STRING'],
  154. }
  155. # Value 5 keeps the number of states in the lalr parser somewhat minimal
  156. # It isn't optimal, but close to it. See PR #949
  157. SMALL_FACTOR_THRESHOLD = 5
  158. # The Threshold whether repeat via ~ are split up into different rules
  159. # 50 is chosen since it keeps the number of states low and therefore lalr analysis time low,
  160. # while not being to overaggressive and unnecessarily creating rules that might create shift/reduce conflicts.
  161. # (See PR #949)
  162. REPEAT_BREAK_THRESHOLD = 50
  163. @inline_args
  164. class EBNF_to_BNF(Transformer_InPlace):
  165. def __init__(self):
  166. self.new_rules = []
  167. self.rules_cache = {}
  168. self.prefix = 'anon'
  169. self.i = 0
  170. self.rule_options = None
  171. def _name_rule(self, inner):
  172. new_name = '__%s_%s_%d' % (self.prefix, inner, self.i)
  173. self.i += 1
  174. return new_name
  175. def _add_rule(self, key, name, expansions):
  176. t = NonTerminal(name)
  177. self.new_rules.append((name, expansions, self.rule_options))
  178. self.rules_cache[key] = t
  179. return t
  180. def _add_recurse_rule(self, type_, expr):
  181. try:
  182. return self.rules_cache[expr]
  183. except KeyError:
  184. new_name = self._name_rule(type_)
  185. t = NonTerminal(new_name)
  186. tree = ST('expansions', [
  187. ST('expansion', [expr]),
  188. ST('expansion', [t, expr])
  189. ])
  190. return self._add_rule(expr, new_name, tree)
  191. def _add_repeat_rule(self, a, b, target, atom):
  192. """Generate a rule that repeats target ``a`` times, and repeats atom ``b`` times.
  193. When called recursively (into target), it repeats atom for x(n) times, where:
  194. x(0) = 1
  195. x(n) = a(n) * x(n-1) + b
  196. Example rule when a=3, b=4:
  197. new_rule: target target target atom atom atom atom
  198. """
  199. key = (a, b, target, atom)
  200. try:
  201. return self.rules_cache[key]
  202. except KeyError:
  203. new_name = self._name_rule('repeat_a%d_b%d' % (a, b))
  204. tree = ST('expansions', [ST('expansion', [target] * a + [atom] * b)])
  205. return self._add_rule(key, new_name, tree)
  206. def _add_repeat_opt_rule(self, a, b, target, target_opt, atom):
  207. """Creates a rule that matches atom 0 to (a*n+b)-1 times.
  208. When target matches n times atom, and target_opt 0 to n-1 times target_opt,
  209. First we generate target * i followed by target_opt, for i from 0 to a-1
  210. These match 0 to n*a - 1 times atom
  211. Then we generate target * a followed by atom * i, for i from 0 to b-1
  212. These match n*a to n*a + b-1 times atom
  213. The created rule will not have any shift/reduce conflicts so that it can be used with lalr
  214. Example rule when a=3, b=4:
  215. new_rule: target_opt
  216. | target target_opt
  217. | target target target_opt
  218. | target target target
  219. | target target target atom
  220. | target target target atom atom
  221. | target target target atom atom atom
  222. """
  223. key = (a, b, target, atom, "opt")
  224. try:
  225. return self.rules_cache[key]
  226. except KeyError:
  227. new_name = self._name_rule('repeat_a%d_b%d_opt' % (a, b))
  228. tree = ST('expansions', [
  229. ST('expansion', [target]*i + [target_opt]) for i in range(a)
  230. ] + [
  231. ST('expansion', [target]*a + [atom]*i) for i in range(b)
  232. ])
  233. return self._add_rule(key, new_name, tree)
  234. def _generate_repeats(self, rule, mn, mx):
  235. """Generates a rule tree that repeats ``rule`` exactly between ``mn`` to ``mx`` times.
  236. """
  237. # For a small number of repeats, we can take the naive approach
  238. if mx < REPEAT_BREAK_THRESHOLD:
  239. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx + 1)])
  240. # For large repeat values, we break the repetition into sub-rules.
  241. # We treat ``rule~mn..mx`` as ``rule~mn rule~0..(diff=mx-mn)``.
  242. # We then use small_factors to split up mn and diff up into values [(a, b), ...]
  243. # This values are used with the help of _add_repeat_rule and _add_repeat_rule_opt
  244. # to generate a complete rule/expression that matches the corresponding number of repeats
  245. mn_target = rule
  246. for a, b in small_factors(mn, SMALL_FACTOR_THRESHOLD):
  247. mn_target = self._add_repeat_rule(a, b, mn_target, rule)
  248. if mx == mn:
  249. return mn_target
  250. diff = mx - mn + 1 # We add one because _add_repeat_opt_rule generates rules that match one less
  251. diff_factors = small_factors(diff, SMALL_FACTOR_THRESHOLD)
  252. diff_target = rule # Match rule 1 times
  253. diff_opt_target = ST('expansion', []) # match rule 0 times (e.g. up to 1 -1 times)
  254. for a, b in diff_factors[:-1]:
  255. diff_opt_target = self._add_repeat_opt_rule(a, b, diff_target, diff_opt_target, rule)
  256. diff_target = self._add_repeat_rule(a, b, diff_target, rule)
  257. a, b = diff_factors[-1]
  258. diff_opt_target = self._add_repeat_opt_rule(a, b, diff_target, diff_opt_target, rule)
  259. return ST('expansions', [ST('expansion', [mn_target] + [diff_opt_target])])
  260. def expr(self, rule, op, *args):
  261. if op.value == '?':
  262. empty = ST('expansion', [])
  263. return ST('expansions', [rule, empty])
  264. elif op.value == '+':
  265. # a : b c+ d
  266. # -->
  267. # a : b _c d
  268. # _c : _c c | c;
  269. return self._add_recurse_rule('plus', rule)
  270. elif op.value == '*':
  271. # a : b c* d
  272. # -->
  273. # a : b _c? d
  274. # _c : _c c | c;
  275. new_name = self._add_recurse_rule('star', rule)
  276. return ST('expansions', [new_name, ST('expansion', [])])
  277. elif op.value == '~':
  278. if len(args) == 1:
  279. mn = mx = int(args[0])
  280. else:
  281. mn, mx = map(int, args)
  282. if mx < mn or mn < 0:
  283. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  284. return self._generate_repeats(rule, mn, mx)
  285. assert False, op
  286. def maybe(self, rule):
  287. keep_all_tokens = self.rule_options and self.rule_options.keep_all_tokens
  288. def will_not_get_removed(sym):
  289. if isinstance(sym, NonTerminal):
  290. return not sym.name.startswith('_')
  291. if isinstance(sym, Terminal):
  292. return keep_all_tokens or not sym.filter_out
  293. assert False
  294. if any(rule.scan_values(will_not_get_removed)):
  295. empty = _EMPTY
  296. else:
  297. empty = ST('expansion', [])
  298. return ST('expansions', [rule, empty])
  299. class SimplifyRule_Visitor(Visitor):
  300. @staticmethod
  301. def _flatten(tree):
  302. while tree.expand_kids_by_data(tree.data):
  303. pass
  304. def expansion(self, tree):
  305. # rules_list unpacking
  306. # a : b (c|d) e
  307. # -->
  308. # a : b c e | b d e
  309. #
  310. # In AST terms:
  311. # expansion(b, expansions(c, d), e)
  312. # -->
  313. # expansions( expansion(b, c, e), expansion(b, d, e) )
  314. self._flatten(tree)
  315. for i, child in enumerate(tree.children):
  316. if isinstance(child, Tree) and child.data == 'expansions':
  317. tree.data = 'expansions'
  318. tree.children = [self.visit(ST('expansion', [option if i == j else other
  319. for j, other in enumerate(tree.children)]))
  320. for option in dedup_list(child.children)]
  321. self._flatten(tree)
  322. break
  323. def alias(self, tree):
  324. rule, alias_name = tree.children
  325. if rule.data == 'expansions':
  326. aliases = []
  327. for child in tree.children[0].children:
  328. aliases.append(ST('alias', [child, alias_name]))
  329. tree.data = 'expansions'
  330. tree.children = aliases
  331. def expansions(self, tree):
  332. self._flatten(tree)
  333. # Ensure all children are unique
  334. if len(set(tree.children)) != len(tree.children):
  335. tree.children = dedup_list(tree.children) # dedup is expensive, so try to minimize its use
  336. class RuleTreeToText(Transformer):
  337. def expansions(self, x):
  338. return x
  339. def expansion(self, symbols):
  340. return symbols, None
  341. def alias(self, x):
  342. (expansion, _alias), alias = x
  343. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  344. return expansion, alias.value
  345. class PrepareAnonTerminals(Transformer_InPlace):
  346. """Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them"""
  347. def __init__(self, terminals):
  348. self.terminals = terminals
  349. self.term_set = {td.name for td in self.terminals}
  350. self.term_reverse = {td.pattern: td for td in terminals}
  351. self.i = 0
  352. self.rule_options = None
  353. @inline_args
  354. def pattern(self, p):
  355. value = p.value
  356. if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags:
  357. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  358. term_name = None
  359. if isinstance(p, PatternStr):
  360. try:
  361. # If already defined, use the user-defined terminal name
  362. term_name = self.term_reverse[p].name
  363. except KeyError:
  364. # Try to assign an indicative anon-terminal name
  365. try:
  366. term_name = _TERMINAL_NAMES[value]
  367. except KeyError:
  368. if value and is_id_continue(value) and is_id_start(value[0]) and value.upper() not in self.term_set:
  369. term_name = value.upper()
  370. if term_name in self.term_set:
  371. term_name = None
  372. elif isinstance(p, PatternRE):
  373. if p in self.term_reverse: # Kind of a weird placement.name
  374. term_name = self.term_reverse[p].name
  375. else:
  376. assert False, p
  377. if term_name is None:
  378. term_name = '__ANON_%d' % self.i
  379. self.i += 1
  380. if term_name not in self.term_set:
  381. assert p not in self.term_reverse
  382. self.term_set.add(term_name)
  383. termdef = TerminalDef(term_name, p)
  384. self.term_reverse[p] = termdef
  385. self.terminals.append(termdef)
  386. filter_out = False if self.rule_options and self.rule_options.keep_all_tokens else isinstance(p, PatternStr)
  387. return Terminal(term_name, filter_out=filter_out)
  388. class _ReplaceSymbols(Transformer_InPlace):
  389. """Helper for ApplyTemplates"""
  390. def __init__(self):
  391. self.names = {}
  392. def value(self, c):
  393. if len(c) == 1 and isinstance(c[0], Token) and c[0].value in self.names:
  394. return self.names[c[0].value]
  395. return self.__default__('value', c, None)
  396. def template_usage(self, c):
  397. if c[0] in self.names:
  398. return self.__default__('template_usage', [self.names[c[0]].name] + c[1:], None)
  399. return self.__default__('template_usage', c, None)
  400. class ApplyTemplates(Transformer_InPlace):
  401. """Apply the templates, creating new rules that represent the used templates"""
  402. def __init__(self, rule_defs):
  403. self.rule_defs = rule_defs
  404. self.replacer = _ReplaceSymbols()
  405. self.created_templates = set()
  406. def template_usage(self, c):
  407. name = c[0]
  408. args = c[1:]
  409. result_name = "%s{%s}" % (name, ",".join(a.name for a in args))
  410. if result_name not in self.created_templates:
  411. self.created_templates.add(result_name)
  412. (_n, params, tree, options) ,= (t for t in self.rule_defs if t[0] == name)
  413. assert len(params) == len(args), args
  414. result_tree = deepcopy(tree)
  415. self.replacer.names = dict(zip(params, args))
  416. self.replacer.transform(result_tree)
  417. self.rule_defs.append((result_name, [], result_tree, deepcopy(options)))
  418. return NonTerminal(result_name)
  419. def _rfind(s, choices):
  420. return max(s.rfind(c) for c in choices)
  421. def eval_escaping(s):
  422. w = ''
  423. i = iter(s)
  424. for n in i:
  425. w += n
  426. if n == '\\':
  427. try:
  428. n2 = next(i)
  429. except StopIteration:
  430. raise GrammarError("Literal ended unexpectedly (bad escaping): `%r`" % s)
  431. if n2 == '\\':
  432. w += '\\\\'
  433. elif n2 not in 'Uuxnftr':
  434. w += '\\'
  435. w += n2
  436. w = w.replace('\\"', '"').replace("'", "\\'")
  437. to_eval = "u'''%s'''" % w
  438. try:
  439. s = literal_eval(to_eval)
  440. except SyntaxError as e:
  441. raise GrammarError(s, e)
  442. return s
  443. def _literal_to_pattern(literal):
  444. v = literal.value
  445. flag_start = _rfind(v, '/"')+1
  446. assert flag_start > 0
  447. flags = v[flag_start:]
  448. assert all(f in _RE_FLAGS for f in flags), flags
  449. if literal.type == 'STRING' and '\n' in v:
  450. raise GrammarError('You cannot put newlines in string literals')
  451. if literal.type == 'REGEXP' and '\n' in v and 'x' not in flags:
  452. raise GrammarError('You can only use newlines in regular expressions '
  453. 'with the `x` (verbose) flag')
  454. v = v[:flag_start]
  455. assert v[0] == v[-1] and v[0] in '"/'
  456. x = v[1:-1]
  457. s = eval_escaping(x)
  458. if s == "":
  459. raise GrammarError("Empty terminals are not allowed (%s)" % literal)
  460. if literal.type == 'STRING':
  461. s = s.replace('\\\\', '\\')
  462. return PatternStr(s, flags, raw=literal.value)
  463. elif literal.type == 'REGEXP':
  464. return PatternRE(s, flags, raw=literal.value)
  465. else:
  466. assert False, 'Invariant failed: literal.type not in ["STRING", "REGEXP"]'
  467. @inline_args
  468. class PrepareLiterals(Transformer_InPlace):
  469. def literal(self, literal):
  470. return ST('pattern', [_literal_to_pattern(literal)])
  471. def range(self, start, end):
  472. assert start.type == end.type == 'STRING'
  473. start = start.value[1:-1]
  474. end = end.value[1:-1]
  475. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1
  476. regexp = '[%s-%s]' % (start, end)
  477. return ST('pattern', [PatternRE(regexp)])
  478. def _make_joined_pattern(regexp, flags_set):
  479. # In Python 3.6, a new syntax for flags was introduced, that allows us to restrict the scope
  480. # of flags to a specific regexp group. We are already using it in `lexer.Pattern._get_flags`
  481. # However, for prior Python versions, we still need to use global flags, so we have to make sure
  482. # that there are no flag collisions when we merge several terminals.
  483. flags = ()
  484. if not Py36:
  485. if len(flags_set) > 1:
  486. raise GrammarError("Lark doesn't support joining terminals with conflicting flags in python <3.6!")
  487. elif len(flags_set) == 1:
  488. flags ,= flags_set
  489. return PatternRE(regexp, flags)
  490. class TerminalTreeToPattern(Transformer_NonRecursive):
  491. def pattern(self, ps):
  492. p ,= ps
  493. return p
  494. def expansion(self, items):
  495. assert items
  496. if len(items) == 1:
  497. return items[0]
  498. pattern = ''.join(i.to_regexp() for i in items)
  499. return _make_joined_pattern(pattern, {i.flags for i in items})
  500. def expansions(self, exps):
  501. if len(exps) == 1:
  502. return exps[0]
  503. # Do a bit of sorting to make sure that the longest option is returned
  504. # (Python's re module otherwise prefers just 'l' when given (l|ll) and both could match)
  505. exps.sort(key=lambda x: (-x.max_width, -x.min_width, -len(x.value)))
  506. pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps))
  507. return _make_joined_pattern(pattern, {i.flags for i in exps})
  508. def expr(self, args):
  509. inner, op = args[:2]
  510. if op == '~':
  511. if len(args) == 3:
  512. op = "{%d}" % int(args[2])
  513. else:
  514. mn, mx = map(int, args[2:])
  515. if mx < mn:
  516. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  517. op = "{%d,%d}" % (mn, mx)
  518. else:
  519. assert len(args) == 2
  520. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  521. def maybe(self, expr):
  522. return self.expr(expr + ['?'])
  523. def alias(self, t):
  524. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  525. def value(self, v):
  526. return v[0]
  527. class PrepareSymbols(Transformer_InPlace):
  528. def value(self, v):
  529. v ,= v
  530. if isinstance(v, Tree):
  531. return v
  532. elif v.type == 'RULE':
  533. return NonTerminal(Str(v.value))
  534. elif v.type == 'TERMINAL':
  535. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  536. assert False
  537. def nr_deepcopy_tree(t):
  538. """Deepcopy tree `t` without recursion"""
  539. return Transformer_NonRecursive(False).transform(t)
  540. class Grammar:
  541. def __init__(self, rule_defs, term_defs, ignore):
  542. self.term_defs = term_defs
  543. self.rule_defs = rule_defs
  544. self.ignore = ignore
  545. def compile(self, start, terminals_to_keep):
  546. # We change the trees in-place (to support huge grammars)
  547. # So deepcopy allows calling compile more than once.
  548. term_defs = [(n, (nr_deepcopy_tree(t), p)) for n, (t, p) in self.term_defs]
  549. rule_defs = [(n, p, nr_deepcopy_tree(t), o) for n, p, t, o in self.rule_defs]
  550. # ===================
  551. # Compile Terminals
  552. # ===================
  553. # Convert terminal-trees to strings/regexps
  554. for name, (term_tree, priority) in term_defs:
  555. if term_tree is None: # Terminal added through %declare
  556. continue
  557. expansions = list(term_tree.find_data('expansion'))
  558. if len(expansions) == 1 and not expansions[0].children:
  559. raise GrammarError("Terminals cannot be empty (%s)" % name)
  560. transformer = PrepareLiterals() * TerminalTreeToPattern()
  561. terminals = [TerminalDef(name, transformer.transform(term_tree), priority)
  562. for name, (term_tree, priority) in term_defs if term_tree]
  563. # =================
  564. # Compile Rules
  565. # =================
  566. # 1. Pre-process terminals
  567. anon_tokens_transf = PrepareAnonTerminals(terminals)
  568. transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals
  569. # 2. Inline Templates
  570. transformer *= ApplyTemplates(rule_defs)
  571. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  572. ebnf_to_bnf = EBNF_to_BNF()
  573. rules = []
  574. i = 0
  575. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  576. name, params, rule_tree, options = rule_defs[i]
  577. i += 1
  578. if len(params) != 0: # Dont transform templates
  579. continue
  580. rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  581. ebnf_to_bnf.rule_options = rule_options
  582. ebnf_to_bnf.prefix = name
  583. anon_tokens_transf.rule_options = rule_options
  584. tree = transformer.transform(rule_tree)
  585. res = ebnf_to_bnf.transform(tree)
  586. rules.append((name, res, options))
  587. rules += ebnf_to_bnf.new_rules
  588. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  589. # 4. Compile tree to Rule objects
  590. rule_tree_to_text = RuleTreeToText()
  591. simplify_rule = SimplifyRule_Visitor()
  592. compiled_rules = []
  593. for rule_content in rules:
  594. name, tree, options = rule_content
  595. simplify_rule.visit(tree)
  596. expansions = rule_tree_to_text.transform(tree)
  597. for i, (expansion, alias) in enumerate(expansions):
  598. if alias and name.startswith('_'):
  599. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)"% (name, alias))
  600. empty_indices = [x==_EMPTY for x in expansion]
  601. if any(empty_indices):
  602. exp_options = copy(options) or RuleOptions()
  603. exp_options.empty_indices = empty_indices
  604. expansion = [x for x in expansion if x!=_EMPTY]
  605. else:
  606. exp_options = options
  607. for sym in expansion:
  608. assert isinstance(sym, Symbol)
  609. if sym.is_term and exp_options and exp_options.keep_all_tokens:
  610. sym.filter_out = False
  611. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  612. compiled_rules.append(rule)
  613. # Remove duplicates of empty rules, throw error for non-empty duplicates
  614. if len(set(compiled_rules)) != len(compiled_rules):
  615. duplicates = classify(compiled_rules, lambda x: x)
  616. for dups in duplicates.values():
  617. if len(dups) > 1:
  618. if dups[0].expansion:
  619. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  620. % ''.join('\n * %s' % i for i in dups))
  621. # Empty rule; assert all other attributes are equal
  622. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  623. # Remove duplicates
  624. compiled_rules = list(set(compiled_rules))
  625. # Filter out unused rules
  626. while True:
  627. c = len(compiled_rules)
  628. used_rules = {s for r in compiled_rules
  629. for s in r.expansion
  630. if isinstance(s, NonTerminal)
  631. and s != r.origin}
  632. used_rules |= {NonTerminal(s) for s in start}
  633. compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules)
  634. for r in unused:
  635. logger.debug("Unused rule: %s", r)
  636. if len(compiled_rules) == c:
  637. break
  638. # Filter out unused terminals
  639. if terminals_to_keep != '*':
  640. used_terms = {t.name for r in compiled_rules
  641. for t in r.expansion
  642. if isinstance(t, Terminal)}
  643. terminals, unused = classify_bool(terminals, lambda t: t.name in used_terms or t.name in self.ignore or t.name in terminals_to_keep)
  644. if unused:
  645. logger.debug("Unused terminals: %s", [t.name for t in unused])
  646. return terminals, compiled_rules, self.ignore
  647. PackageResource = namedtuple('PackageResource', 'pkg_name path')
  648. class FromPackageLoader(object):
  649. """
  650. Provides a simple way of creating custom import loaders that load from packages via ``pkgutil.get_data`` instead of using `open`.
  651. This allows them to be compatible even from within zip files.
  652. Relative imports are handled, so you can just freely use them.
  653. pkg_name: The name of the package. You can probably provide `__name__` most of the time
  654. search_paths: All the path that will be search on absolute imports.
  655. """
  656. def __init__(self, pkg_name, search_paths=("", )):
  657. self.pkg_name = pkg_name
  658. self.search_paths = search_paths
  659. def __repr__(self):
  660. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.search_paths)
  661. def __call__(self, base_path, grammar_path):
  662. if base_path is None:
  663. to_try = self.search_paths
  664. else:
  665. # Check whether or not the importing grammar was loaded by this module.
  666. if not isinstance(base_path, PackageResource) or base_path.pkg_name != self.pkg_name:
  667. # Technically false, but FileNotFound doesn't exist in python2.7, and this message should never reach the end user anyway
  668. raise IOError()
  669. to_try = [base_path.path]
  670. for path in to_try:
  671. full_path = os.path.join(path, grammar_path)
  672. try:
  673. text = pkgutil.get_data(self.pkg_name, full_path)
  674. except IOError:
  675. continue
  676. else:
  677. return PackageResource(self.pkg_name, full_path), text.decode()
  678. raise IOError()
  679. stdlib_loader = FromPackageLoader('lark', IMPORT_PATHS)
  680. def resolve_term_references(term_dict):
  681. # TODO Solve with transitive closure (maybe)
  682. while True:
  683. changed = False
  684. for name, token_tree in term_dict.items():
  685. if token_tree is None: # Terminal added through %declare
  686. continue
  687. for exp in token_tree.find_data('value'):
  688. item ,= exp.children
  689. if isinstance(item, Token):
  690. if item.type == 'RULE':
  691. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  692. if item.type == 'TERMINAL':
  693. try:
  694. term_value = term_dict[item]
  695. except KeyError:
  696. raise GrammarError("Terminal used but not defined: %s" % item)
  697. assert term_value is not None
  698. exp.children[0] = term_value
  699. changed = True
  700. if not changed:
  701. break
  702. for name, term in term_dict.items():
  703. if term: # Not just declared
  704. for child in term.children:
  705. ids = [id(x) for x in child.iter_subtrees()]
  706. if id(term) in ids:
  707. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  708. def options_from_rule(name, params, *x):
  709. if len(x) > 1:
  710. priority, expansions = x
  711. priority = int(priority)
  712. else:
  713. expansions ,= x
  714. priority = None
  715. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  716. keep_all_tokens = name.startswith('!')
  717. name = name.lstrip('!')
  718. expand1 = name.startswith('?')
  719. name = name.lstrip('?')
  720. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  721. template_source=(name if params else None))
  722. def symbols_from_strcase(expansion):
  723. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  724. @inline_args
  725. class PrepareGrammar(Transformer_InPlace):
  726. def terminal(self, name):
  727. return name
  728. def nonterminal(self, name):
  729. return name
  730. def _find_used_symbols(tree):
  731. assert tree.data == 'expansions'
  732. return {t for x in tree.find_data('expansion')
  733. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  734. def _get_parser():
  735. try:
  736. return _get_parser.cache
  737. except AttributeError:
  738. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  739. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  740. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o)
  741. for r, _p, xs, o in rules for i, x in enumerate(xs)]
  742. callback = ParseTreeBuilder(rules, ST).create_callback()
  743. import re
  744. lexer_conf = LexerConf(terminals, re, ['WS', 'COMMENT', 'BACKSLASH'])
  745. parser_conf = ParserConf(rules, callback, ['start'])
  746. lexer_conf.lexer_type = 'standard'
  747. parser_conf.parser_type = 'lalr'
  748. _get_parser.cache = ParsingFrontend(lexer_conf, parser_conf, None)
  749. return _get_parser.cache
  750. GRAMMAR_ERRORS = [
  751. ('Incorrect type of value', ['a: 1\n']),
  752. ('Unclosed parenthesis', ['a: (\n']),
  753. ('Unmatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']),
  754. ('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']),
  755. ('Illegal name for rules or terminals', ['Aa:\n']),
  756. ('Alias expects lowercase name', ['a: -> "a"\n']),
  757. ('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']),
  758. ('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']),
  759. ('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']),
  760. ('Terminal names cannot contain dots', ['A.B\n']),
  761. ('Expecting rule or terminal definition', ['"a"\n']),
  762. ('%import expects a name', ['%import "a"\n']),
  763. ('%ignore expects a value', ['%ignore %import\n']),
  764. ]
  765. def _translate_parser_exception(parse, e):
  766. error = e.match_examples(parse, GRAMMAR_ERRORS, use_accepts=True)
  767. if error:
  768. return error
  769. elif 'STRING' in e.expected:
  770. return "Expecting a value"
  771. def _parse_grammar(text, name, start='start'):
  772. try:
  773. tree = _get_parser().parse(text + '\n', start)
  774. except UnexpectedCharacters as e:
  775. context = e.get_context(text)
  776. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  777. (e.line, e.column, name, context))
  778. except UnexpectedToken as e:
  779. context = e.get_context(text)
  780. error = _translate_parser_exception(_get_parser().parse, e)
  781. if error:
  782. raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  783. raise
  784. return PrepareGrammar().transform(tree)
  785. def _error_repr(error):
  786. if isinstance(error, UnexpectedToken):
  787. error2 = _translate_parser_exception(_get_parser().parse, error)
  788. if error2:
  789. return error2
  790. expected = ', '.join(error.accepts or error.expected)
  791. return "Unexpected token %r. Expected one of: {%s}" % (str(error.token), expected)
  792. else:
  793. return str(error)
  794. def _search_interactive_parser(interactive_parser, predicate):
  795. def expand(node):
  796. path, p = node
  797. for choice in p.choices():
  798. t = Token(choice, '')
  799. try:
  800. new_p = p.feed_token(t)
  801. except ParseError: # Illegal
  802. pass
  803. else:
  804. yield path + (choice,), new_p
  805. for path, p in bfs_all_unique([((), interactive_parser)], expand):
  806. if predicate(p):
  807. return path, p
  808. def find_grammar_errors(text, start='start'):
  809. errors = []
  810. def on_error(e):
  811. errors.append((e, _error_repr(e)))
  812. # recover to a new line
  813. token_path, _ = _search_interactive_parser(e.interactive_parser.as_immutable(), lambda p: '_NL' in p.choices())
  814. for token_type in token_path:
  815. e.interactive_parser.feed_token(Token(token_type, ''))
  816. e.interactive_parser.feed_token(Token('_NL', '\n'))
  817. return True
  818. _tree = _get_parser().parse(text + '\n', start, on_error=on_error)
  819. errors_by_line = classify(errors, lambda e: e[0].line)
  820. errors = [el[0] for el in errors_by_line.values()] # already sorted
  821. for e in errors:
  822. e[0].interactive_parser = None
  823. return errors
  824. def _get_mangle(prefix, aliases, base_mangle=None):
  825. def mangle(s):
  826. if s in aliases:
  827. s = aliases[s]
  828. else:
  829. if s[0] == '_':
  830. s = '_%s__%s' % (prefix, s[1:])
  831. else:
  832. s = '%s__%s' % (prefix, s)
  833. if base_mangle is not None:
  834. s = base_mangle(s)
  835. return s
  836. return mangle
  837. def _mangle_exp(exp, mangle):
  838. if mangle is None:
  839. return exp
  840. exp = deepcopy(exp) # TODO: is this needed
  841. for t in exp.iter_subtrees():
  842. for i, c in enumerate(t.children):
  843. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  844. t.children[i] = Token(c.type, mangle(c.value))
  845. return exp
  846. class GrammarBuilder:
  847. def __init__(self, global_keep_all_tokens=False, import_paths=None, used_files=None):
  848. self.global_keep_all_tokens = global_keep_all_tokens
  849. self.import_paths = import_paths or []
  850. self.used_files = used_files or {}
  851. self._definitions = {}
  852. self._ignore_names = []
  853. def _is_term(self, name):
  854. # Imported terminals are of the form `Path__to__Grammar__file__TERMINAL_NAME`
  855. # Only the last part is the actual name, and the rest might contain mixed case
  856. return name.rpartition('__')[-1].isupper()
  857. def _grammar_error(self, msg, *names):
  858. args = {}
  859. for i, name in enumerate(names, start=1):
  860. postfix = '' if i == 1 else str(i)
  861. args['name' + postfix] = name
  862. args['type' + postfix] = lowercase_type = ("rule", "terminal")[self._is_term(name)]
  863. args['Type' + postfix] = lowercase_type.title()
  864. raise GrammarError(msg.format(**args))
  865. def _check_options(self, name, options):
  866. if self._is_term(name):
  867. if options is None:
  868. options = 1
  869. # if we don't use Integral here, we run into python2.7/python3 problems with long vs int
  870. elif not isinstance(options, Integral):
  871. raise GrammarError("Terminal require a single int as 'options' (e.g. priority), got %s" % (type(options),))
  872. else:
  873. if options is None:
  874. options = RuleOptions()
  875. elif not isinstance(options, RuleOptions):
  876. raise GrammarError("Rules require a RuleOptions instance as 'options'")
  877. if self.global_keep_all_tokens:
  878. options.keep_all_tokens = True
  879. return options
  880. def _define(self, name, exp, params=(), options=None, override=False):
  881. if name in self._definitions:
  882. if not override:
  883. self._grammar_error("{Type} '{name}' defined more than once", name)
  884. elif override:
  885. self._grammar_error("Cannot override a nonexisting {type} {name}", name)
  886. if name.startswith('__'):
  887. self._grammar_error('Names starting with double-underscore are reserved (Error at {name})', name)
  888. self._definitions[name] = (params, exp, self._check_options(name, options))
  889. def _extend(self, name, exp, params=(), options=None):
  890. if name not in self._definitions:
  891. self._grammar_error("Can't extend {type} {name} as it wasn't defined before", name)
  892. if tuple(params) != tuple(self._definitions[name][0]):
  893. self._grammar_error("Cannot extend {type} with different parameters: {name}", name)
  894. # TODO: think about what to do with 'options'
  895. base = self._definitions[name][1]
  896. assert isinstance(base, Tree) and base.data == 'expansions'
  897. base.children.insert(0, exp)
  898. def _ignore(self, exp_or_name):
  899. if isinstance(exp_or_name, str):
  900. self._ignore_names.append(exp_or_name)
  901. else:
  902. assert isinstance(exp_or_name, Tree)
  903. t = exp_or_name
  904. if t.data == 'expansions' and len(t.children) == 1:
  905. t2 ,= t.children
  906. if t2.data=='expansion' and len(t2.children) == 1:
  907. item ,= t2.children
  908. if item.data == 'value':
  909. item ,= item.children
  910. if isinstance(item, Token) and item.type == 'TERMINAL':
  911. self._ignore_names.append(item.value)
  912. return
  913. name = '__IGNORE_%d'% len(self._ignore_names)
  914. self._ignore_names.append(name)
  915. self._definitions[name] = ((), t, 1)
  916. def _declare(self, *names):
  917. for name in names:
  918. self._define(name, None)
  919. def _unpack_import(self, stmt, grammar_name):
  920. if len(stmt.children) > 1:
  921. path_node, arg1 = stmt.children
  922. else:
  923. path_node, = stmt.children
  924. arg1 = None
  925. if isinstance(arg1, Tree): # Multi import
  926. dotted_path = tuple(path_node.children)
  927. names = arg1.children
  928. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  929. else: # Single import
  930. dotted_path = tuple(path_node.children[:-1])
  931. if not dotted_path:
  932. name ,= path_node.children
  933. raise GrammarError("Nothing was imported from grammar `%s`" % name)
  934. name = path_node.children[-1] # Get name from dotted path
  935. aliases = {name.value: (arg1 or name).value} # Aliases if exist
  936. if path_node.data == 'import_lib': # Import from library
  937. base_path = None
  938. else: # Relative import
  939. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  940. try:
  941. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  942. except AttributeError:
  943. base_file = None
  944. else:
  945. base_file = grammar_name # Import relative to grammar file path if external grammar file
  946. if base_file:
  947. if isinstance(base_file, PackageResource):
  948. base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
  949. else:
  950. base_path = os.path.split(base_file)[0]
  951. else:
  952. base_path = os.path.abspath(os.path.curdir)
  953. return dotted_path, base_path, aliases
  954. def _unpack_definition(self, tree, mangle):
  955. if tree.data == 'rule':
  956. name, params, exp, opts = options_from_rule(*tree.children)
  957. else:
  958. name = tree.children[0].value
  959. params = () # TODO terminal templates
  960. opts = int(tree.children[1]) if len(tree.children) == 3 else 1 # priority
  961. exp = tree.children[-1]
  962. if mangle is not None:
  963. params = tuple(mangle(p) for p in params)
  964. name = mangle(name)
  965. exp = _mangle_exp(exp, mangle)
  966. return name, exp, params, opts
  967. def load_grammar(self, grammar_text, grammar_name="<?>", mangle=None):
  968. tree = _parse_grammar(grammar_text, grammar_name)
  969. imports = {}
  970. for stmt in tree.children:
  971. if stmt.data == 'import':
  972. dotted_path, base_path, aliases = self._unpack_import(stmt, grammar_name)
  973. try:
  974. import_base_path, import_aliases = imports[dotted_path]
  975. assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
  976. import_aliases.update(aliases)
  977. except KeyError:
  978. imports[dotted_path] = base_path, aliases
  979. for dotted_path, (base_path, aliases) in imports.items():
  980. self.do_import(dotted_path, base_path, aliases, mangle)
  981. for stmt in tree.children:
  982. if stmt.data in ('term', 'rule'):
  983. self._define(*self._unpack_definition(stmt, mangle))
  984. elif stmt.data == 'override':
  985. r ,= stmt.children
  986. self._define(*self._unpack_definition(r, mangle), override=True)
  987. elif stmt.data == 'extend':
  988. r ,= stmt.children
  989. self._extend(*self._unpack_definition(r, mangle))
  990. elif stmt.data == 'ignore':
  991. # if mangle is not None, we shouldn't apply ignore, since we aren't in a toplevel grammar
  992. if mangle is None:
  993. self._ignore(*stmt.children)
  994. elif stmt.data == 'declare':
  995. names = [t.value for t in stmt.children]
  996. if mangle is None:
  997. self._declare(*names)
  998. else:
  999. self._declare(*map(mangle, names))
  1000. elif stmt.data == 'import':
  1001. pass
  1002. else:
  1003. assert False, stmt
  1004. term_defs = { name: exp
  1005. for name, (_params, exp, _options) in self._definitions.items()
  1006. if self._is_term(name)
  1007. }
  1008. resolve_term_references(term_defs)
  1009. def _remove_unused(self, used):
  1010. def rule_dependencies(symbol):
  1011. if self._is_term(symbol):
  1012. return []
  1013. try:
  1014. params, tree,_ = self._definitions[symbol]
  1015. except KeyError:
  1016. return []
  1017. return _find_used_symbols(tree) - set(params)
  1018. _used = set(bfs(used, rule_dependencies))
  1019. self._definitions = {k: v for k, v in self._definitions.items() if k in _used}
  1020. def do_import(self, dotted_path, base_path, aliases, base_mangle=None):
  1021. assert dotted_path
  1022. mangle = _get_mangle('__'.join(dotted_path), aliases, base_mangle)
  1023. grammar_path = os.path.join(*dotted_path) + EXT
  1024. to_try = self.import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
  1025. for source in to_try:
  1026. try:
  1027. if callable(source):
  1028. joined_path, text = source(base_path, grammar_path)
  1029. else:
  1030. joined_path = os.path.join(source, grammar_path)
  1031. with open(joined_path, encoding='utf8') as f:
  1032. text = f.read()
  1033. except IOError:
  1034. continue
  1035. else:
  1036. h = hashlib.md5(text.encode('utf8')).hexdigest()
  1037. if self.used_files.get(joined_path, h) != h:
  1038. raise RuntimeError("Grammar file was changed during importing")
  1039. self.used_files[joined_path] = h
  1040. gb = GrammarBuilder(self.global_keep_all_tokens, self.import_paths, self.used_files)
  1041. gb.load_grammar(text, joined_path, mangle)
  1042. gb._remove_unused(map(mangle, aliases))
  1043. for name in gb._definitions:
  1044. if name in self._definitions:
  1045. raise GrammarError("Cannot import '%s' from '%s': Symbol already defined." % (name, grammar_path))
  1046. self._definitions.update(**gb._definitions)
  1047. break
  1048. else:
  1049. # Search failed. Make Python throw a nice error.
  1050. open(grammar_path, encoding='utf8')
  1051. assert False, "Couldn't import grammar %s, but a corresponding file was found at a place where lark doesn't search for it" % (dotted_path,)
  1052. def validate(self):
  1053. for name, (params, exp, _options) in self._definitions.items():
  1054. for i, p in enumerate(params):
  1055. if p in self._definitions:
  1056. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  1057. if p in params[:i]:
  1058. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  1059. if exp is None: # Remaining checks don't apply to abstract rules/terminals
  1060. continue
  1061. for temp in exp.find_data('template_usage'):
  1062. sym = temp.children[0]
  1063. args = temp.children[1:]
  1064. if sym not in params:
  1065. if sym not in self._definitions:
  1066. self._grammar_error("Template '%s' used but not defined (in {type} {name})" % sym, name)
  1067. if len(args) != len(self._definitions[sym][0]):
  1068. expected, actual = len(self._definitions[sym][0]), len(args)
  1069. self._grammar_error("Wrong number of template arguments used for {name} "
  1070. "(expected %s, got %s) (in {type2} {name2})" % (expected, actual), sym, name)
  1071. for sym in _find_used_symbols(exp):
  1072. if sym not in self._definitions and sym not in params:
  1073. self._grammar_error("{Type} '{name}' used but not defined (in {type2} {name2})", sym, name)
  1074. if not set(self._definitions).issuperset(self._ignore_names):
  1075. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(self._ignore_names) - set(self._definitions)))
  1076. def build(self):
  1077. self.validate()
  1078. rule_defs = []
  1079. term_defs = []
  1080. for name, (params, exp, options) in self._definitions.items():
  1081. if self._is_term(name):
  1082. assert len(params) == 0
  1083. term_defs.append((name, (exp, options)))
  1084. else:
  1085. rule_defs.append((name, params, exp, options))
  1086. # resolve_term_references(term_defs)
  1087. return Grammar(rule_defs, term_defs, self._ignore_names)
  1088. def verify_used_files(file_hashes):
  1089. for path, old in file_hashes.items():
  1090. text = None
  1091. if isinstance(path, str) and os.path.exists(path):
  1092. with open(path, encoding='utf8') as f:
  1093. text = f.read()
  1094. elif isinstance(path, PackageResource):
  1095. with suppress(IOError):
  1096. text = pkgutil.get_data(*path).decode('utf-8')
  1097. if text is None: # We don't know how to load the path. ignore it.
  1098. continue
  1099. current = hashlib.md5(text.encode()).hexdigest()
  1100. if old != current:
  1101. logger.info("File %r changed, rebuilding Parser" % path)
  1102. return False
  1103. return True
  1104. def list_grammar_imports(grammar, import_paths=[]):
  1105. "Returns a list of paths to the lark grammars imported by the given grammar (recursively)"
  1106. builder = GrammarBuilder(False, import_paths)
  1107. builder.load_grammar(grammar, '<string>')
  1108. return list(builder.used_files.keys())
  1109. def load_grammar(grammar, source, import_paths, global_keep_all_tokens):
  1110. builder = GrammarBuilder(global_keep_all_tokens, import_paths)
  1111. builder.load_grammar(grammar, source)
  1112. return builder.build(), builder.used_files