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.

1304 lines
48 KiB

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