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.

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