This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1356 Zeilen
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. if sym is _EMPTY:
  294. return False
  295. assert False, sym
  296. empty = ST('expansion', [_EMPTY] * len(list(rule.scan_values(will_not_get_removed))))
  297. return ST('expansions', [rule, empty])
  298. class SimplifyRule_Visitor(Visitor):
  299. @staticmethod
  300. def _flatten(tree):
  301. while tree.expand_kids_by_data(tree.data):
  302. pass
  303. def expansion(self, tree):
  304. # rules_list unpacking
  305. # a : b (c|d) e
  306. # -->
  307. # a : b c e | b d e
  308. #
  309. # In AST terms:
  310. # expansion(b, expansions(c, d), e)
  311. # -->
  312. # expansions( expansion(b, c, e), expansion(b, d, e) )
  313. self._flatten(tree)
  314. for i, child in enumerate(tree.children):
  315. if isinstance(child, Tree) and child.data == 'expansions':
  316. tree.data = 'expansions'
  317. tree.children = [self.visit(ST('expansion', [option if i == j else other
  318. for j, other in enumerate(tree.children)]))
  319. for option in dedup_list(child.children)]
  320. self._flatten(tree)
  321. break
  322. def alias(self, tree):
  323. rule, alias_name = tree.children
  324. if rule.data == 'expansions':
  325. aliases = []
  326. for child in tree.children[0].children:
  327. aliases.append(ST('alias', [child, alias_name]))
  328. tree.data = 'expansions'
  329. tree.children = aliases
  330. def expansions(self, tree):
  331. self._flatten(tree)
  332. # Ensure all children are unique
  333. if len(set(tree.children)) != len(tree.children):
  334. tree.children = dedup_list(tree.children) # dedup is expensive, so try to minimize its use
  335. class RuleTreeToText(Transformer):
  336. def expansions(self, x):
  337. return x
  338. def expansion(self, symbols):
  339. return symbols, None
  340. def alias(self, x):
  341. (expansion, _alias), alias = x
  342. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  343. return expansion, alias.value
  344. class PrepareAnonTerminals(Transformer_InPlace):
  345. """Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them"""
  346. def __init__(self, terminals):
  347. self.terminals = terminals
  348. self.term_set = {td.name for td in self.terminals}
  349. self.term_reverse = {td.pattern: td for td in terminals}
  350. self.i = 0
  351. self.rule_options = None
  352. @inline_args
  353. def pattern(self, p):
  354. value = p.value
  355. if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags:
  356. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  357. term_name = None
  358. if isinstance(p, PatternStr):
  359. try:
  360. # If already defined, use the user-defined terminal name
  361. term_name = self.term_reverse[p].name
  362. except KeyError:
  363. # Try to assign an indicative anon-terminal name
  364. try:
  365. term_name = _TERMINAL_NAMES[value]
  366. except KeyError:
  367. if value and is_id_continue(value) and is_id_start(value[0]) and value.upper() not in self.term_set:
  368. term_name = value.upper()
  369. if term_name in self.term_set:
  370. term_name = None
  371. elif isinstance(p, PatternRE):
  372. if p in self.term_reverse: # Kind of a weird placement.name
  373. term_name = self.term_reverse[p].name
  374. else:
  375. assert False, p
  376. if term_name is None:
  377. term_name = '__ANON_%d' % self.i
  378. self.i += 1
  379. if term_name not in self.term_set:
  380. assert p not in self.term_reverse
  381. self.term_set.add(term_name)
  382. termdef = TerminalDef(term_name, p)
  383. self.term_reverse[p] = termdef
  384. self.terminals.append(termdef)
  385. filter_out = False if self.rule_options and self.rule_options.keep_all_tokens else isinstance(p, PatternStr)
  386. return Terminal(term_name, filter_out=filter_out)
  387. class _ReplaceSymbols(Transformer_InPlace):
  388. """Helper for ApplyTemplates"""
  389. def __init__(self):
  390. self.names = {}
  391. def value(self, c):
  392. if len(c) == 1 and isinstance(c[0], Token) and c[0].value in self.names:
  393. return self.names[c[0].value]
  394. return self.__default__('value', c, None)
  395. def template_usage(self, c):
  396. if c[0] in self.names:
  397. return self.__default__('template_usage', [self.names[c[0]].name] + c[1:], None)
  398. return self.__default__('template_usage', c, None)
  399. class ApplyTemplates(Transformer_InPlace):
  400. """Apply the templates, creating new rules that represent the used templates"""
  401. def __init__(self, rule_defs):
  402. self.rule_defs = rule_defs
  403. self.replacer = _ReplaceSymbols()
  404. self.created_templates = set()
  405. def template_usage(self, c):
  406. name = c[0]
  407. args = c[1:]
  408. result_name = "%s{%s}" % (name, ",".join(a.name for a in args))
  409. if result_name not in self.created_templates:
  410. self.created_templates.add(result_name)
  411. (_n, params, tree, options) ,= (t for t in self.rule_defs if t[0] == name)
  412. assert len(params) == len(args), args
  413. result_tree = deepcopy(tree)
  414. self.replacer.names = dict(zip(params, args))
  415. self.replacer.transform(result_tree)
  416. self.rule_defs.append((result_name, [], result_tree, deepcopy(options)))
  417. return NonTerminal(result_name)
  418. def _rfind(s, choices):
  419. return max(s.rfind(c) for c in choices)
  420. def eval_escaping(s):
  421. w = ''
  422. i = iter(s)
  423. for n in i:
  424. w += n
  425. if n == '\\':
  426. try:
  427. n2 = next(i)
  428. except StopIteration:
  429. raise GrammarError("Literal ended unexpectedly (bad escaping): `%r`" % s)
  430. if n2 == '\\':
  431. w += '\\\\'
  432. elif n2 not in 'Uuxnftr':
  433. w += '\\'
  434. w += n2
  435. w = w.replace('\\"', '"').replace("'", "\\'")
  436. to_eval = "u'''%s'''" % w
  437. try:
  438. s = literal_eval(to_eval)
  439. except SyntaxError as e:
  440. raise GrammarError(s, e)
  441. return s
  442. def _literal_to_pattern(literal):
  443. v = literal.value
  444. flag_start = _rfind(v, '/"')+1
  445. assert flag_start > 0
  446. flags = v[flag_start:]
  447. assert all(f in _RE_FLAGS for f in flags), flags
  448. if literal.type == 'STRING' and '\n' in v:
  449. raise GrammarError('You cannot put newlines in string literals')
  450. if literal.type == 'REGEXP' and '\n' in v and 'x' not in flags:
  451. raise GrammarError('You can only use newlines in regular expressions '
  452. 'with the `x` (verbose) flag')
  453. v = v[:flag_start]
  454. assert v[0] == v[-1] and v[0] in '"/'
  455. x = v[1:-1]
  456. s = eval_escaping(x)
  457. if s == "":
  458. raise GrammarError("Empty terminals are not allowed (%s)" % literal)
  459. if literal.type == 'STRING':
  460. s = s.replace('\\\\', '\\')
  461. return PatternStr(s, flags, raw=literal.value)
  462. elif literal.type == 'REGEXP':
  463. return PatternRE(s, flags, raw=literal.value)
  464. else:
  465. assert False, 'Invariant failed: literal.type not in ["STRING", "REGEXP"]'
  466. @inline_args
  467. class PrepareLiterals(Transformer_InPlace):
  468. def literal(self, literal):
  469. return ST('pattern', [_literal_to_pattern(literal)])
  470. def range(self, start, end):
  471. assert start.type == end.type == 'STRING'
  472. start = start.value[1:-1]
  473. end = end.value[1:-1]
  474. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1
  475. regexp = '[%s-%s]' % (start, end)
  476. return ST('pattern', [PatternRE(regexp)])
  477. def _make_joined_pattern(regexp, flags_set):
  478. return PatternRE(regexp, ())
  479. class TerminalTreeToPattern(Transformer_NonRecursive):
  480. def pattern(self, ps):
  481. p ,= ps
  482. return p
  483. def expansion(self, items):
  484. assert items
  485. if len(items) == 1:
  486. return items[0]
  487. pattern = ''.join(i.to_regexp() for i in items)
  488. return _make_joined_pattern(pattern, {i.flags for i in items})
  489. def expansions(self, exps):
  490. if len(exps) == 1:
  491. return exps[0]
  492. # Do a bit of sorting to make sure that the longest option is returned
  493. # (Python's re module otherwise prefers just 'l' when given (l|ll) and both could match)
  494. exps.sort(key=lambda x: (-x.max_width, -x.min_width, -len(x.value)))
  495. pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps))
  496. return _make_joined_pattern(pattern, {i.flags for i in exps})
  497. def expr(self, args):
  498. inner, op = args[:2]
  499. if op == '~':
  500. if len(args) == 3:
  501. op = "{%d}" % int(args[2])
  502. else:
  503. mn, mx = map(int, args[2:])
  504. if mx < mn:
  505. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  506. op = "{%d,%d}" % (mn, mx)
  507. else:
  508. assert len(args) == 2
  509. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  510. def maybe(self, expr):
  511. return self.expr(expr + ['?'])
  512. def alias(self, t):
  513. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  514. def value(self, v):
  515. return v[0]
  516. class PrepareSymbols(Transformer_InPlace):
  517. def value(self, v):
  518. v ,= v
  519. if isinstance(v, Tree):
  520. return v
  521. elif v.type == 'RULE':
  522. return NonTerminal(str(v.value))
  523. elif v.type == 'TERMINAL':
  524. return Terminal(str(v.value), filter_out=v.startswith('_'))
  525. assert False
  526. def nr_deepcopy_tree(t):
  527. """Deepcopy tree `t` without recursion"""
  528. return Transformer_NonRecursive(False).transform(t)
  529. class Grammar:
  530. term_defs: List[Tuple[str, Tuple[Tree, int]]]
  531. rule_defs: List[Tuple[str, Tuple[str, ...], Tree, RuleOptions]]
  532. ignore: List[str]
  533. def __init__(self, rule_defs: List[Tuple[str, Tuple[str, ...], Tree, RuleOptions]], term_defs: List[Tuple[str, Tuple[Tree, int]]], ignore: List[str]) -> None:
  534. self.term_defs = term_defs
  535. self.rule_defs = rule_defs
  536. self.ignore = ignore
  537. def compile(self, start, terminals_to_keep):
  538. # We change the trees in-place (to support huge grammars)
  539. # So deepcopy allows calling compile more than once.
  540. term_defs = [(n, (nr_deepcopy_tree(t), p)) for n, (t, p) in self.term_defs]
  541. rule_defs = [(n, p, nr_deepcopy_tree(t), o) for n, p, t, o in self.rule_defs]
  542. # ===================
  543. # Compile Terminals
  544. # ===================
  545. # Convert terminal-trees to strings/regexps
  546. for name, (term_tree, priority) in term_defs:
  547. if term_tree is None: # Terminal added through %declare
  548. continue
  549. expansions = list(term_tree.find_data('expansion'))
  550. if len(expansions) == 1 and not expansions[0].children:
  551. raise GrammarError("Terminals cannot be empty (%s)" % name)
  552. transformer = PrepareLiterals() * TerminalTreeToPattern()
  553. terminals = [TerminalDef(name, transformer.transform(term_tree), priority)
  554. for name, (term_tree, priority) in term_defs if term_tree]
  555. # =================
  556. # Compile Rules
  557. # =================
  558. # 1. Pre-process terminals
  559. anon_tokens_transf = PrepareAnonTerminals(terminals)
  560. transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals
  561. # 2. Inline Templates
  562. transformer *= ApplyTemplates(rule_defs)
  563. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  564. ebnf_to_bnf = EBNF_to_BNF()
  565. rules = []
  566. i = 0
  567. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  568. name, params, rule_tree, options = rule_defs[i]
  569. i += 1
  570. if len(params) != 0: # Dont transform templates
  571. continue
  572. rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  573. ebnf_to_bnf.rule_options = rule_options
  574. ebnf_to_bnf.prefix = name
  575. anon_tokens_transf.rule_options = rule_options
  576. tree = transformer.transform(rule_tree)
  577. res = ebnf_to_bnf.transform(tree)
  578. rules.append((name, res, options))
  579. rules += ebnf_to_bnf.new_rules
  580. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  581. # 4. Compile tree to Rule objects
  582. rule_tree_to_text = RuleTreeToText()
  583. simplify_rule = SimplifyRule_Visitor()
  584. compiled_rules = []
  585. for rule_content in rules:
  586. name, tree, options = rule_content
  587. simplify_rule.visit(tree)
  588. expansions = rule_tree_to_text.transform(tree)
  589. for i, (expansion, alias) in enumerate(expansions):
  590. if alias and name.startswith('_'):
  591. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)"% (name, alias))
  592. empty_indices = [x==_EMPTY for x in expansion]
  593. if any(empty_indices):
  594. exp_options = copy(options) or RuleOptions()
  595. exp_options.empty_indices = empty_indices
  596. expansion = [x for x in expansion if x!=_EMPTY]
  597. else:
  598. exp_options = options
  599. for sym in expansion:
  600. assert isinstance(sym, Symbol)
  601. if sym.is_term and exp_options and exp_options.keep_all_tokens:
  602. sym.filter_out = False
  603. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  604. compiled_rules.append(rule)
  605. # Remove duplicates of empty rules, throw error for non-empty duplicates
  606. if len(set(compiled_rules)) != len(compiled_rules):
  607. duplicates = classify(compiled_rules, lambda x: x)
  608. for dups in duplicates.values():
  609. if len(dups) > 1:
  610. if dups[0].expansion:
  611. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  612. % ''.join('\n * %s' % i for i in dups))
  613. # Empty rule; assert all other attributes are equal
  614. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  615. # Remove duplicates
  616. compiled_rules = list(set(compiled_rules))
  617. # Filter out unused rules
  618. while True:
  619. c = len(compiled_rules)
  620. used_rules = {s for r in compiled_rules
  621. for s in r.expansion
  622. if isinstance(s, NonTerminal)
  623. and s != r.origin}
  624. used_rules |= {NonTerminal(s) for s in start}
  625. compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules)
  626. for r in unused:
  627. logger.debug("Unused rule: %s", r)
  628. if len(compiled_rules) == c:
  629. break
  630. # Filter out unused terminals
  631. if terminals_to_keep != '*':
  632. used_terms = {t.name for r in compiled_rules
  633. for t in r.expansion
  634. if isinstance(t, Terminal)}
  635. 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)
  636. if unused:
  637. logger.debug("Unused terminals: %s", [t.name for t in unused])
  638. return terminals, compiled_rules, self.ignore
  639. PackageResource = namedtuple('PackageResource', 'pkg_name path')
  640. class FromPackageLoader:
  641. """
  642. Provides a simple way of creating custom import loaders that load from packages via ``pkgutil.get_data`` instead of using `open`.
  643. This allows them to be compatible even from within zip files.
  644. Relative imports are handled, so you can just freely use them.
  645. pkg_name: The name of the package. You can probably provide `__name__` most of the time
  646. search_paths: All the path that will be search on absolute imports.
  647. """
  648. pkg_name: str
  649. search_paths: Tuple[str, ...]
  650. def __init__(self, pkg_name: str, search_paths: Tuple[str, ...]=("", )) -> None:
  651. self.pkg_name = pkg_name
  652. self.search_paths = search_paths
  653. def __repr__(self):
  654. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.search_paths)
  655. def __call__(self, base_path: Union[None, str, PackageResource], grammar_path: str) -> Tuple[PackageResource, str]:
  656. if base_path is None:
  657. to_try = self.search_paths
  658. else:
  659. # Check whether or not the importing grammar was loaded by this module.
  660. if not isinstance(base_path, PackageResource) or base_path.pkg_name != self.pkg_name:
  661. # Technically false, but FileNotFound doesn't exist in python2.7, and this message should never reach the end user anyway
  662. raise IOError()
  663. to_try = [base_path.path]
  664. for path in to_try:
  665. full_path = os.path.join(path, grammar_path)
  666. try:
  667. text = pkgutil.get_data(self.pkg_name, full_path)
  668. except IOError:
  669. continue
  670. else:
  671. return PackageResource(self.pkg_name, full_path), text.decode()
  672. raise IOError()
  673. stdlib_loader = FromPackageLoader('lark', IMPORT_PATHS)
  674. def resolve_term_references(term_dict):
  675. # TODO Solve with transitive closure (maybe)
  676. while True:
  677. changed = False
  678. for name, token_tree in term_dict.items():
  679. if token_tree is None: # Terminal added through %declare
  680. continue
  681. for exp in token_tree.find_data('value'):
  682. item ,= exp.children
  683. if isinstance(item, Token):
  684. if item.type == 'RULE':
  685. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  686. if item.type == 'TERMINAL':
  687. try:
  688. term_value = term_dict[item]
  689. except KeyError:
  690. raise GrammarError("Terminal used but not defined: %s" % item)
  691. assert term_value is not None
  692. exp.children[0] = term_value
  693. changed = True
  694. if not changed:
  695. break
  696. for name, term in term_dict.items():
  697. if term: # Not just declared
  698. for child in term.children:
  699. ids = [id(x) for x in child.iter_subtrees()]
  700. if id(term) in ids:
  701. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  702. def options_from_rule(name, params, *x):
  703. if len(x) > 1:
  704. priority, expansions = x
  705. priority = int(priority)
  706. else:
  707. expansions ,= x
  708. priority = None
  709. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  710. keep_all_tokens = name.startswith('!')
  711. name = name.lstrip('!')
  712. expand1 = name.startswith('?')
  713. name = name.lstrip('?')
  714. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  715. template_source=(name if params else None))
  716. def symbols_from_strcase(expansion):
  717. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  718. @inline_args
  719. class PrepareGrammar(Transformer_InPlace):
  720. def terminal(self, name):
  721. return name
  722. def nonterminal(self, name):
  723. return name
  724. def _find_used_symbols(tree):
  725. assert tree.data == 'expansions'
  726. return {t for x in tree.find_data('expansion')
  727. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  728. def _get_parser():
  729. try:
  730. return _get_parser.cache
  731. except AttributeError:
  732. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  733. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  734. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o)
  735. for r, _p, xs, o in rules for i, x in enumerate(xs)]
  736. callback = ParseTreeBuilder(rules, ST).create_callback()
  737. import re
  738. lexer_conf = LexerConf(terminals, re, ['WS', 'COMMENT', 'BACKSLASH'])
  739. parser_conf = ParserConf(rules, callback, ['start'])
  740. lexer_conf.lexer_type = 'basic'
  741. parser_conf.parser_type = 'lalr'
  742. _get_parser.cache = ParsingFrontend(lexer_conf, parser_conf, None)
  743. return _get_parser.cache
  744. GRAMMAR_ERRORS = [
  745. ('Incorrect type of value', ['a: 1\n']),
  746. ('Unclosed parenthesis', ['a: (\n']),
  747. ('Unmatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']),
  748. ('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']),
  749. ('Illegal name for rules or terminals', ['Aa:\n']),
  750. ('Alias expects lowercase name', ['a: -> "a"\n']),
  751. ('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']),
  752. ('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']),
  753. ('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']),
  754. ('Terminal names cannot contain dots', ['A.B\n']),
  755. ('Expecting rule or terminal definition', ['"a"\n']),
  756. ('%import expects a name', ['%import "a"\n']),
  757. ('%ignore expects a value', ['%ignore %import\n']),
  758. ]
  759. def _translate_parser_exception(parse, e):
  760. error = e.match_examples(parse, GRAMMAR_ERRORS, use_accepts=True)
  761. if error:
  762. return error
  763. elif 'STRING' in e.expected:
  764. return "Expecting a value"
  765. def _parse_grammar(text, name, start='start'):
  766. try:
  767. tree = _get_parser().parse(text + '\n', start)
  768. except UnexpectedCharacters as e:
  769. context = e.get_context(text)
  770. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  771. (e.line, e.column, name, context))
  772. except UnexpectedToken as e:
  773. context = e.get_context(text)
  774. error = _translate_parser_exception(_get_parser().parse, e)
  775. if error:
  776. raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  777. raise
  778. return PrepareGrammar().transform(tree)
  779. def _error_repr(error):
  780. if isinstance(error, UnexpectedToken):
  781. error2 = _translate_parser_exception(_get_parser().parse, error)
  782. if error2:
  783. return error2
  784. expected = ', '.join(error.accepts or error.expected)
  785. return "Unexpected token %r. Expected one of: {%s}" % (str(error.token), expected)
  786. else:
  787. return str(error)
  788. def _search_interactive_parser(interactive_parser, predicate):
  789. def expand(node):
  790. path, p = node
  791. for choice in p.choices():
  792. t = Token(choice, '')
  793. try:
  794. new_p = p.feed_token(t)
  795. except ParseError: # Illegal
  796. pass
  797. else:
  798. yield path + (choice,), new_p
  799. for path, p in bfs_all_unique([((), interactive_parser)], expand):
  800. if predicate(p):
  801. return path, p
  802. def find_grammar_errors(text: str, start: str='start') -> List[Tuple[UnexpectedInput, str]]:
  803. errors = []
  804. def on_error(e):
  805. errors.append((e, _error_repr(e)))
  806. # recover to a new line
  807. token_path, _ = _search_interactive_parser(e.interactive_parser.as_immutable(), lambda p: '_NL' in p.choices())
  808. for token_type in token_path:
  809. e.interactive_parser.feed_token(Token(token_type, ''))
  810. e.interactive_parser.feed_token(Token('_NL', '\n'))
  811. return True
  812. _tree = _get_parser().parse(text + '\n', start, on_error=on_error)
  813. errors_by_line = classify(errors, lambda e: e[0].line)
  814. errors = [el[0] for el in errors_by_line.values()] # already sorted
  815. for e in errors:
  816. e[0].interactive_parser = None
  817. return errors
  818. def _get_mangle(prefix, aliases, base_mangle=None):
  819. def mangle(s):
  820. if s in aliases:
  821. s = aliases[s]
  822. else:
  823. if s[0] == '_':
  824. s = '_%s__%s' % (prefix, s[1:])
  825. else:
  826. s = '%s__%s' % (prefix, s)
  827. if base_mangle is not None:
  828. s = base_mangle(s)
  829. return s
  830. return mangle
  831. def _mangle_exp(exp, mangle):
  832. if mangle is None:
  833. return exp
  834. exp = deepcopy(exp) # TODO: is this needed
  835. for t in exp.iter_subtrees():
  836. for i, c in enumerate(t.children):
  837. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  838. t.children[i] = Token(c.type, mangle(c.value))
  839. return exp
  840. class GrammarBuilder:
  841. global_keep_all_tokens: bool
  842. import_paths: List[Union[str, Callable]]
  843. used_files: Dict[str, str]
  844. 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:
  845. self.global_keep_all_tokens = global_keep_all_tokens
  846. self.import_paths = import_paths or []
  847. self.used_files = used_files or {}
  848. self._definitions = {}
  849. self._ignore_names = []
  850. def _is_term(self, name):
  851. # Imported terminals are of the form `Path__to__Grammar__file__TERMINAL_NAME`
  852. # Only the last part is the actual name, and the rest might contain mixed case
  853. return name.rpartition('__')[-1].isupper()
  854. def _grammar_error(self, msg, *names):
  855. args = {}
  856. for i, name in enumerate(names, start=1):
  857. postfix = '' if i == 1 else str(i)
  858. args['name' + postfix] = name
  859. args['type' + postfix] = lowercase_type = ("rule", "terminal")[self._is_term(name)]
  860. args['Type' + postfix] = lowercase_type.title()
  861. raise GrammarError(msg.format(**args))
  862. def _check_options(self, name, options):
  863. if self._is_term(name):
  864. if options is None:
  865. options = 1
  866. elif not isinstance(options, int):
  867. raise GrammarError("Terminal require a single int as 'options' (e.g. priority), got %s" % (type(options),))
  868. else:
  869. if options is None:
  870. options = RuleOptions()
  871. elif not isinstance(options, RuleOptions):
  872. raise GrammarError("Rules require a RuleOptions instance as 'options'")
  873. if self.global_keep_all_tokens:
  874. options.keep_all_tokens = True
  875. return options
  876. def _define(self, name, exp, params=(), options=None, override=False):
  877. if name in self._definitions:
  878. if not override:
  879. self._grammar_error("{Type} '{name}' defined more than once", name)
  880. elif override:
  881. self._grammar_error("Cannot override a nonexisting {type} {name}", name)
  882. if name.startswith('__'):
  883. self._grammar_error('Names starting with double-underscore are reserved (Error at {name})', name)
  884. self._definitions[name] = (params, exp, self._check_options(name, options))
  885. def _extend(self, name, exp, params=(), options=None):
  886. if name not in self._definitions:
  887. self._grammar_error("Can't extend {type} {name} as it wasn't defined before", name)
  888. if tuple(params) != tuple(self._definitions[name][0]):
  889. self._grammar_error("Cannot extend {type} with different parameters: {name}", name)
  890. # TODO: think about what to do with 'options'
  891. base = self._definitions[name][1]
  892. assert isinstance(base, Tree) and base.data == 'expansions'
  893. base.children.insert(0, exp)
  894. def _ignore(self, exp_or_name):
  895. if isinstance(exp_or_name, str):
  896. self._ignore_names.append(exp_or_name)
  897. else:
  898. assert isinstance(exp_or_name, Tree)
  899. t = exp_or_name
  900. if t.data == 'expansions' and len(t.children) == 1:
  901. t2 ,= t.children
  902. if t2.data=='expansion' and len(t2.children) == 1:
  903. item ,= t2.children
  904. if item.data == 'value':
  905. item ,= item.children
  906. if isinstance(item, Token) and item.type == 'TERMINAL':
  907. self._ignore_names.append(item.value)
  908. return
  909. name = '__IGNORE_%d'% len(self._ignore_names)
  910. self._ignore_names.append(name)
  911. self._definitions[name] = ((), t, TOKEN_DEFAULT_PRIORITY)
  912. def _declare(self, *names):
  913. for name in names:
  914. self._define(name, None)
  915. def _unpack_import(self, stmt, grammar_name):
  916. if len(stmt.children) > 1:
  917. path_node, arg1 = stmt.children
  918. else:
  919. path_node, = stmt.children
  920. arg1 = None
  921. if isinstance(arg1, Tree): # Multi import
  922. dotted_path = tuple(path_node.children)
  923. names = arg1.children
  924. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  925. else: # Single import
  926. dotted_path = tuple(path_node.children[:-1])
  927. if not dotted_path:
  928. name ,= path_node.children
  929. raise GrammarError("Nothing was imported from grammar `%s`" % name)
  930. name = path_node.children[-1] # Get name from dotted path
  931. aliases = {name.value: (arg1 or name).value} # Aliases if exist
  932. if path_node.data == 'import_lib': # Import from library
  933. base_path = None
  934. else: # Relative import
  935. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  936. try:
  937. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  938. except AttributeError:
  939. base_file = None
  940. else:
  941. base_file = grammar_name # Import relative to grammar file path if external grammar file
  942. if base_file:
  943. if isinstance(base_file, PackageResource):
  944. base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
  945. else:
  946. base_path = os.path.split(base_file)[0]
  947. else:
  948. base_path = os.path.abspath(os.path.curdir)
  949. return dotted_path, base_path, aliases
  950. def _unpack_definition(self, tree, mangle):
  951. if tree.data == 'rule':
  952. name, params, exp, opts = options_from_rule(*tree.children)
  953. else:
  954. name = tree.children[0].value
  955. params = () # TODO terminal templates
  956. opts = int(tree.children[1]) if len(tree.children) == 3 else TOKEN_DEFAULT_PRIORITY # priority
  957. exp = tree.children[-1]
  958. if mangle is not None:
  959. params = tuple(mangle(p) for p in params)
  960. name = mangle(name)
  961. exp = _mangle_exp(exp, mangle)
  962. return name, exp, params, opts
  963. def load_grammar(self, grammar_text: str, grammar_name: str="<?>", mangle: Optional[Callable[[str], str]]=None) -> None:
  964. tree = _parse_grammar(grammar_text, grammar_name)
  965. imports = {}
  966. for stmt in tree.children:
  967. if stmt.data == 'import':
  968. dotted_path, base_path, aliases = self._unpack_import(stmt, grammar_name)
  969. try:
  970. import_base_path, import_aliases = imports[dotted_path]
  971. assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
  972. import_aliases.update(aliases)
  973. except KeyError:
  974. imports[dotted_path] = base_path, aliases
  975. for dotted_path, (base_path, aliases) in imports.items():
  976. self.do_import(dotted_path, base_path, aliases, mangle)
  977. for stmt in tree.children:
  978. if stmt.data in ('term', 'rule'):
  979. self._define(*self._unpack_definition(stmt, mangle))
  980. elif stmt.data == 'override':
  981. r ,= stmt.children
  982. self._define(*self._unpack_definition(r, mangle), override=True)
  983. elif stmt.data == 'extend':
  984. r ,= stmt.children
  985. self._extend(*self._unpack_definition(r, mangle))
  986. elif stmt.data == 'ignore':
  987. # if mangle is not None, we shouldn't apply ignore, since we aren't in a toplevel grammar
  988. if mangle is None:
  989. self._ignore(*stmt.children)
  990. elif stmt.data == 'declare':
  991. names = [t.value for t in stmt.children]
  992. if mangle is None:
  993. self._declare(*names)
  994. else:
  995. self._declare(*map(mangle, names))
  996. elif stmt.data == 'import':
  997. pass
  998. else:
  999. assert False, stmt
  1000. term_defs = { name: exp
  1001. for name, (_params, exp, _options) in self._definitions.items()
  1002. if self._is_term(name)
  1003. }
  1004. resolve_term_references(term_defs)
  1005. def _remove_unused(self, used):
  1006. def rule_dependencies(symbol):
  1007. if self._is_term(symbol):
  1008. return []
  1009. try:
  1010. params, tree,_ = self._definitions[symbol]
  1011. except KeyError:
  1012. return []
  1013. return _find_used_symbols(tree) - set(params)
  1014. _used = set(bfs(used, rule_dependencies))
  1015. self._definitions = {k: v for k, v in self._definitions.items() if k in _used}
  1016. def do_import(self, dotted_path: Tuple[str, ...], base_path: Optional[str], aliases: Dict[str, str], base_mangle: Optional[Callable[[str], str]]=None) -> None:
  1017. assert dotted_path
  1018. mangle = _get_mangle('__'.join(dotted_path), aliases, base_mangle)
  1019. grammar_path = os.path.join(*dotted_path) + EXT
  1020. to_try = self.import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
  1021. for source in to_try:
  1022. try:
  1023. if callable(source):
  1024. joined_path, text = source(base_path, grammar_path)
  1025. else:
  1026. joined_path = os.path.join(source, grammar_path)
  1027. with open(joined_path, encoding='utf8') as f:
  1028. text = f.read()
  1029. except IOError:
  1030. continue
  1031. else:
  1032. h = hashlib.md5(text.encode('utf8')).hexdigest()
  1033. if self.used_files.get(joined_path, h) != h:
  1034. raise RuntimeError("Grammar file was changed during importing")
  1035. self.used_files[joined_path] = h
  1036. gb = GrammarBuilder(self.global_keep_all_tokens, self.import_paths, self.used_files)
  1037. gb.load_grammar(text, joined_path, mangle)
  1038. gb._remove_unused(map(mangle, aliases))
  1039. for name in gb._definitions:
  1040. if name in self._definitions:
  1041. raise GrammarError("Cannot import '%s' from '%s': Symbol already defined." % (name, grammar_path))
  1042. self._definitions.update(**gb._definitions)
  1043. break
  1044. else:
  1045. # Search failed. Make Python throw a nice error.
  1046. open(grammar_path, encoding='utf8')
  1047. 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,)
  1048. def validate(self) -> None:
  1049. for name, (params, exp, _options) in self._definitions.items():
  1050. for i, p in enumerate(params):
  1051. if p in self._definitions:
  1052. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  1053. if p in params[:i]:
  1054. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  1055. if exp is None: # Remaining checks don't apply to abstract rules/terminals
  1056. continue
  1057. for temp in exp.find_data('template_usage'):
  1058. sym = temp.children[0]
  1059. args = temp.children[1:]
  1060. if sym not in params:
  1061. if sym not in self._definitions:
  1062. self._grammar_error("Template '%s' used but not defined (in {type} {name})" % sym, name)
  1063. if len(args) != len(self._definitions[sym][0]):
  1064. expected, actual = len(self._definitions[sym][0]), len(args)
  1065. self._grammar_error("Wrong number of template arguments used for {name} "
  1066. "(expected %s, got %s) (in {type2} {name2})" % (expected, actual), sym, name)
  1067. for sym in _find_used_symbols(exp):
  1068. if sym not in self._definitions and sym not in params:
  1069. self._grammar_error("{Type} '{name}' used but not defined (in {type2} {name2})", sym, name)
  1070. if not set(self._definitions).issuperset(self._ignore_names):
  1071. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(self._ignore_names) - set(self._definitions)))
  1072. def build(self) -> Grammar:
  1073. self.validate()
  1074. rule_defs = []
  1075. term_defs = []
  1076. for name, (params, exp, options) in self._definitions.items():
  1077. if self._is_term(name):
  1078. assert len(params) == 0
  1079. term_defs.append((name, (exp, options)))
  1080. else:
  1081. rule_defs.append((name, params, exp, options))
  1082. # resolve_term_references(term_defs)
  1083. return Grammar(rule_defs, term_defs, self._ignore_names)
  1084. def verify_used_files(file_hashes):
  1085. for path, old in file_hashes.items():
  1086. text = None
  1087. if isinstance(path, str) and os.path.exists(path):
  1088. with open(path, encoding='utf8') as f:
  1089. text = f.read()
  1090. elif isinstance(path, PackageResource):
  1091. with suppress(IOError):
  1092. text = pkgutil.get_data(*path).decode('utf-8')
  1093. if text is None: # We don't know how to load the path. ignore it.
  1094. continue
  1095. current = hashlib.md5(text.encode()).hexdigest()
  1096. if old != current:
  1097. logger.info("File %r changed, rebuilding Parser" % path)
  1098. return False
  1099. return True
  1100. def list_grammar_imports(grammar, import_paths=[]):
  1101. "Returns a list of paths to the lark grammars imported by the given grammar (recursively)"
  1102. builder = GrammarBuilder(False, import_paths)
  1103. builder.load_grammar(grammar, '<string>')
  1104. return list(builder.used_files.keys())
  1105. def load_grammar(grammar, source, import_paths, global_keep_all_tokens):
  1106. builder = GrammarBuilder(global_keep_all_tokens, import_paths)
  1107. builder.load_grammar(grammar, source)
  1108. return builder.build(), builder.used_files