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.

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