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.

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