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.

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