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.

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