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.

1362 lines
50 KiB

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