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.

1217 lines
44 KiB

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