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.

1357 lines
50 KiB

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