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.

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