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.

1054 lines
39 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 .utils import bfs, eval_escaping, Py36, logger, classify_bool, is_id_continue, isalpha
  8. from .lexer import Token, TerminalDef, PatternStr, PatternRE
  9. from .parse_tree_builder import ParseTreeBuilder
  10. from .parser_frontends import LALR_TraditionalLexer
  11. from .common import LexerConf, ParserConf
  12. from .grammar import RuleOptions, Rule, Terminal, NonTerminal, Symbol
  13. from .utils import classify, suppress, dedup_list, Str
  14. from .exceptions import GrammarError, UnexpectedCharacters, UnexpectedToken
  15. from .tree import Tree, SlottedTree as ST
  16. from .visitors import Transformer, Visitor, v_args, Transformer_InPlace, Transformer_NonRecursive
  17. inline_args = v_args(inline=True)
  18. __path__ = os.path.dirname(__file__)
  19. IMPORT_PATHS = ['grammars']
  20. EXT = '.lark'
  21. _RE_FLAGS = 'imslux'
  22. _EMPTY = Symbol('__empty__')
  23. _TERMINAL_NAMES = {
  24. '.' : 'DOT',
  25. ',' : 'COMMA',
  26. ':' : 'COLON',
  27. ';' : 'SEMICOLON',
  28. '+' : 'PLUS',
  29. '-' : 'MINUS',
  30. '*' : 'STAR',
  31. '/' : 'SLASH',
  32. '\\' : 'BACKSLASH',
  33. '|' : 'VBAR',
  34. '?' : 'QMARK',
  35. '!' : 'BANG',
  36. '@' : 'AT',
  37. '#' : 'HASH',
  38. '$' : 'DOLLAR',
  39. '%' : 'PERCENT',
  40. '^' : 'CIRCUMFLEX',
  41. '&' : 'AMPERSAND',
  42. '_' : 'UNDERSCORE',
  43. '<' : 'LESSTHAN',
  44. '>' : 'MORETHAN',
  45. '=' : 'EQUAL',
  46. '"' : 'DBLQUOTE',
  47. '\'' : 'QUOTE',
  48. '`' : 'BACKQUOTE',
  49. '~' : 'TILDE',
  50. '(' : 'LPAR',
  51. ')' : 'RPAR',
  52. '{' : 'LBRACE',
  53. '}' : 'RBRACE',
  54. '[' : 'LSQB',
  55. ']' : 'RSQB',
  56. '\n' : 'NEWLINE',
  57. '\r\n' : 'CRLF',
  58. '\t' : 'TAB',
  59. ' ' : 'SPACE',
  60. }
  61. # Grammar Parser
  62. TERMINALS = {
  63. '_LPAR': r'\(',
  64. '_RPAR': r'\)',
  65. '_LBRA': r'\[',
  66. '_RBRA': r'\]',
  67. '_LBRACE': r'\{',
  68. '_RBRACE': r'\}',
  69. 'OP': '[+*]|[?](?![a-z])',
  70. '_COLON': ':',
  71. '_COMMA': ',',
  72. '_OR': r'\|',
  73. '_DOT': r'\.(?!\.)',
  74. '_DOTDOT': r'\.\.',
  75. 'TILDE': '~',
  76. 'RULE': '!?[_?]?[a-z][_a-z0-9]*',
  77. 'TERMINAL': '_?[A-Z][_A-Z0-9]*',
  78. 'STRING': r'"(\\"|\\\\|[^"\n])*?"i?',
  79. 'REGEXP': r'/(?!/)(\\/|\\\\|[^/])*?/[%s]*' % _RE_FLAGS,
  80. '_NL': r'(\r?\n)+\s*',
  81. 'WS': r'[ \t]+',
  82. 'COMMENT': r'\s*//[^\n]*',
  83. '_TO': '->',
  84. '_IGNORE': r'%ignore',
  85. '_DECLARE': r'%declare',
  86. '_IMPORT': r'%import',
  87. 'NUMBER': r'[+-]?\d+',
  88. }
  89. RULES = {
  90. 'start': ['_list'],
  91. '_list': ['_item', '_list _item'],
  92. '_item': ['rule', 'term', 'statement', '_NL'],
  93. 'rule': ['RULE template_params _COLON expansions _NL',
  94. 'RULE template_params _DOT NUMBER _COLON expansions _NL'],
  95. 'template_params': ['_LBRACE _template_params _RBRACE',
  96. ''],
  97. '_template_params': ['RULE',
  98. '_template_params _COMMA RULE'],
  99. 'expansions': ['alias',
  100. 'expansions _OR alias',
  101. 'expansions _NL _OR alias'],
  102. '?alias': ['expansion _TO RULE', 'expansion'],
  103. 'expansion': ['_expansion'],
  104. '_expansion': ['', '_expansion expr'],
  105. '?expr': ['atom',
  106. 'atom OP',
  107. 'atom TILDE NUMBER',
  108. 'atom TILDE NUMBER _DOTDOT NUMBER',
  109. ],
  110. '?atom': ['_LPAR expansions _RPAR',
  111. 'maybe',
  112. 'value'],
  113. 'value': ['terminal',
  114. 'nonterminal',
  115. 'literal',
  116. 'range',
  117. 'template_usage'],
  118. 'terminal': ['TERMINAL'],
  119. 'nonterminal': ['RULE'],
  120. '?name': ['RULE', 'TERMINAL'],
  121. 'maybe': ['_LBRA expansions _RBRA'],
  122. 'range': ['STRING _DOTDOT STRING'],
  123. 'template_usage': ['RULE _LBRACE _template_args _RBRACE'],
  124. '_template_args': ['value',
  125. '_template_args _COMMA value'],
  126. 'term': ['TERMINAL _COLON expansions _NL',
  127. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  128. 'statement': ['ignore', 'import', 'declare'],
  129. 'ignore': ['_IGNORE expansions _NL'],
  130. 'declare': ['_DECLARE _declare_args _NL'],
  131. 'import': ['_IMPORT _import_path _NL',
  132. '_IMPORT _import_path _LPAR name_list _RPAR _NL',
  133. '_IMPORT _import_path _TO name _NL'],
  134. '_import_path': ['import_lib', 'import_rel'],
  135. 'import_lib': ['_import_args'],
  136. 'import_rel': ['_DOT _import_args'],
  137. '_import_args': ['name', '_import_args _DOT name'],
  138. 'name_list': ['_name_list'],
  139. '_name_list': ['name', '_name_list _COMMA name'],
  140. '_declare_args': ['name', '_declare_args name'],
  141. 'literal': ['REGEXP', 'STRING'],
  142. }
  143. @inline_args
  144. class EBNF_to_BNF(Transformer_InPlace):
  145. def __init__(self):
  146. self.new_rules = []
  147. self.rules_by_expr = {}
  148. self.prefix = 'anon'
  149. self.i = 0
  150. self.rule_options = None
  151. def _add_recurse_rule(self, type_, expr):
  152. if expr in self.rules_by_expr:
  153. return self.rules_by_expr[expr]
  154. new_name = '__%s_%s_%d' % (self.prefix, type_, self.i)
  155. self.i += 1
  156. t = NonTerminal(new_name)
  157. tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])])
  158. self.new_rules.append((new_name, tree, self.rule_options))
  159. self.rules_by_expr[expr] = t
  160. return t
  161. def expr(self, rule, op, *args):
  162. if op.value == '?':
  163. empty = ST('expansion', [])
  164. return ST('expansions', [rule, empty])
  165. elif op.value == '+':
  166. # a : b c+ d
  167. # -->
  168. # a : b _c d
  169. # _c : _c c | c;
  170. return self._add_recurse_rule('plus', rule)
  171. elif op.value == '*':
  172. # a : b c* d
  173. # -->
  174. # a : b _c? d
  175. # _c : _c c | c;
  176. new_name = self._add_recurse_rule('star', rule)
  177. return ST('expansions', [new_name, ST('expansion', [])])
  178. elif op.value == '~':
  179. if len(args) == 1:
  180. mn = mx = int(args[0])
  181. else:
  182. mn, mx = map(int, args)
  183. if mx < mn or mn < 0:
  184. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  185. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)])
  186. assert False, op
  187. def maybe(self, rule):
  188. keep_all_tokens = self.rule_options and self.rule_options.keep_all_tokens
  189. def will_not_get_removed(sym):
  190. if isinstance(sym, NonTerminal):
  191. return not sym.name.startswith('_')
  192. if isinstance(sym, Terminal):
  193. return keep_all_tokens or not sym.filter_out
  194. assert False
  195. if any(rule.scan_values(will_not_get_removed)):
  196. empty = _EMPTY
  197. else:
  198. empty = ST('expansion', [])
  199. return ST('expansions', [rule, empty])
  200. class SimplifyRule_Visitor(Visitor):
  201. @staticmethod
  202. def _flatten(tree):
  203. while True:
  204. to_expand = [i for i, child in enumerate(tree.children)
  205. if isinstance(child, Tree) and child.data == tree.data]
  206. if not to_expand:
  207. break
  208. tree.expand_kids_by_index(*to_expand)
  209. def expansion(self, tree):
  210. # rules_list unpacking
  211. # a : b (c|d) e
  212. # -->
  213. # a : b c e | b d e
  214. #
  215. # In AST terms:
  216. # expansion(b, expansions(c, d), e)
  217. # -->
  218. # expansions( expansion(b, c, e), expansion(b, d, e) )
  219. self._flatten(tree)
  220. for i, child in enumerate(tree.children):
  221. if isinstance(child, Tree) and child.data == 'expansions':
  222. tree.data = 'expansions'
  223. tree.children = [self.visit(ST('expansion', [option if i==j else other
  224. for j, other in enumerate(tree.children)]))
  225. for option in dedup_list(child.children)]
  226. self._flatten(tree)
  227. break
  228. def alias(self, tree):
  229. rule, alias_name = tree.children
  230. if rule.data == 'expansions':
  231. aliases = []
  232. for child in tree.children[0].children:
  233. aliases.append(ST('alias', [child, alias_name]))
  234. tree.data = 'expansions'
  235. tree.children = aliases
  236. def expansions(self, tree):
  237. self._flatten(tree)
  238. # Ensure all children are unique
  239. if len(set(tree.children)) != len(tree.children):
  240. tree.children = dedup_list(tree.children) # dedup is expensive, so try to minimize its use
  241. class RuleTreeToText(Transformer):
  242. def expansions(self, x):
  243. return x
  244. def expansion(self, symbols):
  245. return symbols, None
  246. def alias(self, x):
  247. (expansion, _alias), alias = x
  248. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  249. return expansion, alias.value
  250. @inline_args
  251. class CanonizeTree(Transformer_InPlace):
  252. def tokenmods(self, *args):
  253. if len(args) == 1:
  254. return list(args)
  255. tokenmods, value = args
  256. return tokenmods + [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 isalpha(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 _literal_to_pattern(literal):
  334. v = literal.value
  335. flag_start = _rfind(v, '/"')+1
  336. assert flag_start > 0
  337. flags = v[flag_start:]
  338. assert all(f in _RE_FLAGS for f in flags), flags
  339. if literal.type == 'STRING' and '\n' in v:
  340. raise GrammarError('You cannot put newlines in string literals')
  341. if literal.type == 'REGEXP' and '\n' in v and 'x' not in flags:
  342. raise GrammarError('You can only use newlines in regular expressions '
  343. 'with the `x` (verbose) flag')
  344. v = v[:flag_start]
  345. assert v[0] == v[-1] and v[0] in '"/'
  346. x = v[1:-1]
  347. s = eval_escaping(x)
  348. if literal.type == 'STRING':
  349. s = s.replace('\\\\', '\\')
  350. return PatternStr(s, flags)
  351. elif literal.type == 'REGEXP':
  352. return PatternRE(s, flags)
  353. else:
  354. assert False, 'Invariant failed: literal.type not in ["STRING", "REGEXP"]'
  355. @inline_args
  356. class PrepareLiterals(Transformer_InPlace):
  357. def literal(self, literal):
  358. return ST('pattern', [_literal_to_pattern(literal)])
  359. def range(self, start, end):
  360. assert start.type == end.type == 'STRING'
  361. start = start.value[1:-1]
  362. end = end.value[1:-1]
  363. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1, (start, end, len(eval_escaping(start)), len(eval_escaping(end)))
  364. regexp = '[%s-%s]' % (start, end)
  365. return ST('pattern', [PatternRE(regexp)])
  366. def _make_joined_pattern(regexp, flags_set):
  367. # In Python 3.6, a new syntax for flags was introduced, that allows us to restrict the scope
  368. # of flags to a specific regexp group. We are already using it in `lexer.Pattern._get_flags`
  369. # However, for prior Python versions, we still need to use global flags, so we have to make sure
  370. # that there are no flag collisions when we merge several terminals.
  371. flags = ()
  372. if not Py36:
  373. if len(flags_set) > 1:
  374. raise GrammarError("Lark doesn't support joining terminals with conflicting flags in python <3.6!")
  375. elif len(flags_set) == 1:
  376. flags ,= flags_set
  377. return PatternRE(regexp, flags)
  378. class TerminalTreeToPattern(Transformer):
  379. def pattern(self, ps):
  380. p ,= ps
  381. return p
  382. def expansion(self, items):
  383. assert items
  384. if len(items) == 1:
  385. return items[0]
  386. pattern = ''.join(i.to_regexp() for i in items)
  387. return _make_joined_pattern(pattern, {i.flags for i in items})
  388. def expansions(self, exps):
  389. if len(exps) == 1:
  390. return exps[0]
  391. pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps))
  392. return _make_joined_pattern(pattern, {i.flags for i in exps})
  393. def expr(self, args):
  394. inner, op = args[:2]
  395. if op == '~':
  396. if len(args) == 3:
  397. op = "{%d}" % int(args[2])
  398. else:
  399. mn, mx = map(int, args[2:])
  400. if mx < mn:
  401. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  402. op = "{%d,%d}" % (mn, mx)
  403. else:
  404. assert len(args) == 2
  405. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  406. def maybe(self, expr):
  407. return self.expr(expr + ['?'])
  408. def alias(self, t):
  409. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  410. def value(self, v):
  411. return v[0]
  412. class PrepareSymbols(Transformer_InPlace):
  413. def value(self, v):
  414. v ,= v
  415. if isinstance(v, Tree):
  416. return v
  417. elif v.type == 'RULE':
  418. return NonTerminal(Str(v.value))
  419. elif v.type == 'TERMINAL':
  420. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  421. assert False
  422. def _choice_of_rules(rules):
  423. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  424. def nr_deepcopy_tree(t):
  425. "Deepcopy tree `t` without recursion"
  426. return Transformer_NonRecursive(False).transform(t)
  427. class Grammar:
  428. def __init__(self, rule_defs, term_defs, ignore):
  429. self.term_defs = term_defs
  430. self.rule_defs = rule_defs
  431. self.ignore = ignore
  432. def compile(self, start, terminals_to_keep):
  433. # We change the trees in-place (to support huge grammars)
  434. # So deepcopy allows calling compile more than once.
  435. term_defs = deepcopy(list(self.term_defs))
  436. rule_defs = [(n,p,nr_deepcopy_tree(t),o) for n,p,t,o in self.rule_defs]
  437. # ===================
  438. # Compile Terminals
  439. # ===================
  440. # Convert terminal-trees to strings/regexps
  441. for name, (term_tree, priority) in term_defs:
  442. if term_tree is None: # Terminal added through %declare
  443. continue
  444. expansions = list(term_tree.find_data('expansion'))
  445. if len(expansions) == 1 and not expansions[0].children:
  446. raise GrammarError("Terminals cannot be empty (%s)" % name)
  447. transformer = PrepareLiterals() * TerminalTreeToPattern()
  448. terminals = [TerminalDef(name, transformer.transform( term_tree ), priority)
  449. for name, (term_tree, priority) in term_defs if term_tree]
  450. # =================
  451. # Compile Rules
  452. # =================
  453. # 1. Pre-process terminals
  454. anon_tokens_transf = PrepareAnonTerminals(terminals)
  455. transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals
  456. # 2. Inline Templates
  457. transformer *= ApplyTemplates(rule_defs)
  458. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  459. ebnf_to_bnf = EBNF_to_BNF()
  460. rules = []
  461. i = 0
  462. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  463. name, params, rule_tree, options = rule_defs[i]
  464. i += 1
  465. if len(params) != 0: # Dont transform templates
  466. continue
  467. rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  468. ebnf_to_bnf.rule_options = rule_options
  469. ebnf_to_bnf.prefix = name
  470. anon_tokens_transf.rule_options = rule_options
  471. tree = transformer.transform(rule_tree)
  472. res = ebnf_to_bnf.transform(tree)
  473. rules.append((name, res, options))
  474. rules += ebnf_to_bnf.new_rules
  475. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  476. # 4. Compile tree to Rule objects
  477. rule_tree_to_text = RuleTreeToText()
  478. simplify_rule = SimplifyRule_Visitor()
  479. compiled_rules = []
  480. for rule_content in rules:
  481. name, tree, options = rule_content
  482. simplify_rule.visit(tree)
  483. expansions = rule_tree_to_text.transform(tree)
  484. for i, (expansion, alias) in enumerate(expansions):
  485. if alias and name.startswith('_'):
  486. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)" % (name, alias))
  487. empty_indices = [x==_EMPTY for x in expansion]
  488. if any(empty_indices):
  489. exp_options = copy(options) or RuleOptions()
  490. exp_options.empty_indices = empty_indices
  491. expansion = [x for x in expansion if x!=_EMPTY]
  492. else:
  493. exp_options = options
  494. assert all(isinstance(x, Symbol) for x in expansion), expansion
  495. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  496. compiled_rules.append(rule)
  497. # Remove duplicates of empty rules, throw error for non-empty duplicates
  498. if len(set(compiled_rules)) != len(compiled_rules):
  499. duplicates = classify(compiled_rules, lambda x: x)
  500. for dups in duplicates.values():
  501. if len(dups) > 1:
  502. if dups[0].expansion:
  503. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  504. % ''.join('\n * %s' % i for i in dups))
  505. # Empty rule; assert all other attributes are equal
  506. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  507. # Remove duplicates
  508. compiled_rules = list(set(compiled_rules))
  509. # Filter out unused rules
  510. while True:
  511. c = len(compiled_rules)
  512. used_rules = {s for r in compiled_rules
  513. for s in r.expansion
  514. if isinstance(s, NonTerminal)
  515. and s != r.origin}
  516. used_rules |= {NonTerminal(s) for s in start}
  517. compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules)
  518. for r in unused:
  519. logger.debug("Unused rule: %s", r)
  520. if len(compiled_rules) == c:
  521. break
  522. # Filter out unused terminals
  523. used_terms = {t.name for r in compiled_rules
  524. for t in r.expansion
  525. if isinstance(t, Terminal)}
  526. 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)
  527. if unused:
  528. logger.debug("Unused terminals: %s", [t.name for t in unused])
  529. return terminals, compiled_rules, self.ignore
  530. class PackageResource(object):
  531. """
  532. Represents a path inside a Package. Used by `FromPackageLoader`
  533. """
  534. def __init__(self, pkg_name, path):
  535. self.pkg_name = pkg_name
  536. self.path = path
  537. def __str__(self):
  538. return "<%s: %s>" % (self.pkg_name, self.path)
  539. def __repr__(self):
  540. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.path)
  541. class FromPackageLoader(object):
  542. """
  543. Provides a simple way of creating custom import loaders that load from packages via ``pkgutil.get_data`` instead of using `open`.
  544. This allows them to be compatible even from within zip files.
  545. Relative imports are handled, so you can just freely use them.
  546. pkg_name: The name of the package. You can probably provide `__name__` most of the time
  547. search_paths: All the path that will be search on absolute imports.
  548. """
  549. def __init__(self, pkg_name, search_paths=("", )):
  550. self.pkg_name = pkg_name
  551. self.search_paths = search_paths
  552. def __repr__(self):
  553. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.search_paths)
  554. def __call__(self, base_path, grammar_path):
  555. if base_path is None:
  556. to_try = self.search_paths
  557. else:
  558. # Check whether or not the importing grammar was loaded by this module.
  559. if not isinstance(base_path, PackageResource) or base_path.pkg_name != self.pkg_name:
  560. # Technically false, but FileNotFound doesn't exist in python2.7, and this message should never reach the end user anyway
  561. raise IOError()
  562. to_try = [base_path.path]
  563. for path in to_try:
  564. full_path = os.path.join(path, grammar_path)
  565. try:
  566. text = pkgutil.get_data(self.pkg_name, full_path)
  567. except IOError:
  568. continue
  569. else:
  570. return PackageResource(self.pkg_name, full_path), text.decode()
  571. raise IOError()
  572. stdlib_loader = FromPackageLoader('lark', IMPORT_PATHS)
  573. _imported_grammars = {}
  574. def import_from_grammar_into_namespace(grammar, namespace, aliases):
  575. """Returns all rules and terminals of grammar, prepended
  576. with a 'namespace' prefix, except for those which are aliased.
  577. """
  578. imported_terms = dict(grammar.term_defs)
  579. imported_rules = {n:(n,p,deepcopy(t),o) for n,p,t,o in grammar.rule_defs}
  580. term_defs = []
  581. rule_defs = []
  582. def rule_dependencies(symbol):
  583. if symbol.type != 'RULE':
  584. return []
  585. try:
  586. _, params, tree,_ = imported_rules[symbol]
  587. except KeyError:
  588. raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace))
  589. return _find_used_symbols(tree) - set(params)
  590. def get_namespace_name(name, params):
  591. if params is not None:
  592. try:
  593. return params[name]
  594. except KeyError:
  595. pass
  596. try:
  597. return aliases[name].value
  598. except KeyError:
  599. if name[0] == '_':
  600. return '_%s__%s' % (namespace, name[1:])
  601. return '%s__%s' % (namespace, name)
  602. to_import = list(bfs(aliases, rule_dependencies))
  603. for symbol in to_import:
  604. if symbol.type == 'TERMINAL':
  605. term_defs.append([get_namespace_name(symbol, None), imported_terms[symbol]])
  606. else:
  607. assert symbol.type == 'RULE'
  608. _, params, tree, options = imported_rules[symbol]
  609. params_map = {p: ('%s__%s' if p[0]!='_' else '_%s__%s' ) % (namespace, p) for p in params}
  610. for t in tree.iter_subtrees():
  611. for i, c in enumerate(t.children):
  612. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  613. t.children[i] = Token(c.type, get_namespace_name(c, params_map))
  614. params = [params_map[p] for p in params] # We can not rely on ordered dictionaries
  615. rule_defs.append((get_namespace_name(symbol, params_map), params, tree, options))
  616. return term_defs, rule_defs
  617. def resolve_term_references(term_defs):
  618. # TODO Solve with transitive closure (maybe)
  619. term_dict = {k:t for k, (t,_p) in term_defs}
  620. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  621. while True:
  622. changed = False
  623. for name, (token_tree, _p) in term_defs:
  624. if token_tree is None: # Terminal added through %declare
  625. continue
  626. for exp in token_tree.find_data('value'):
  627. item ,= exp.children
  628. if isinstance(item, Token):
  629. if item.type == 'RULE':
  630. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  631. if item.type == 'TERMINAL':
  632. term_value = term_dict[item]
  633. assert term_value is not None
  634. exp.children[0] = term_value
  635. changed = True
  636. if not changed:
  637. break
  638. for name, term in term_dict.items():
  639. if term: # Not just declared
  640. for child in term.children:
  641. ids = [id(x) for x in child.iter_subtrees()]
  642. if id(term) in ids:
  643. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  644. def options_from_rule(name, params, *x):
  645. if len(x) > 1:
  646. priority, expansions = x
  647. priority = int(priority)
  648. else:
  649. expansions ,= x
  650. priority = None
  651. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  652. keep_all_tokens = name.startswith('!')
  653. name = name.lstrip('!')
  654. expand1 = name.startswith('?')
  655. name = name.lstrip('?')
  656. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  657. template_source=(name if params else None))
  658. def symbols_from_strcase(expansion):
  659. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  660. @inline_args
  661. class PrepareGrammar(Transformer_InPlace):
  662. def terminal(self, name):
  663. return name
  664. def nonterminal(self, name):
  665. return name
  666. def _find_used_symbols(tree):
  667. assert tree.data == 'expansions'
  668. return {t for x in tree.find_data('expansion')
  669. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  670. class GrammarLoader:
  671. ERRORS = [
  672. ('Unclosed parenthesis', ['a: (\n']),
  673. ('Umatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']),
  674. ('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']),
  675. ('Illegal name for rules or terminals', ['Aa:\n']),
  676. ('Alias expects lowercase name', ['a: -> "a"\n']),
  677. ('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']),
  678. ('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']),
  679. ('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']),
  680. ('Terminal names cannot contain dots', ['A.B\n']),
  681. ('%import expects a name', ['%import "a"\n']),
  682. ('%ignore expects a value', ['%ignore %import\n']),
  683. ]
  684. def __init__(self, global_keep_all_tokens):
  685. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  686. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  687. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o) for r, _p, xs, o in rules for i, x in enumerate(xs)]
  688. callback = ParseTreeBuilder(rules, ST).create_callback()
  689. import re
  690. lexer_conf = LexerConf(terminals, re, ['WS', 'COMMENT'])
  691. parser_conf = ParserConf(rules, callback, ['start'])
  692. self.parser = LALR_TraditionalLexer(lexer_conf, parser_conf)
  693. self.canonize_tree = CanonizeTree()
  694. self.global_keep_all_tokens = global_keep_all_tokens
  695. def import_grammar(self, grammar_path, base_path=None, import_paths=[]):
  696. if grammar_path not in _imported_grammars:
  697. # import_paths take priority over base_path since they should handle relative imports and ignore everything else.
  698. to_try = import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
  699. for source in to_try:
  700. try:
  701. if callable(source):
  702. joined_path, text = source(base_path, grammar_path)
  703. else:
  704. joined_path = os.path.join(source, grammar_path)
  705. with open(joined_path, encoding='utf8') as f:
  706. text = f.read()
  707. except IOError:
  708. continue
  709. else:
  710. grammar = self.load_grammar(text, joined_path, import_paths)
  711. _imported_grammars[grammar_path] = grammar
  712. break
  713. else:
  714. # Search failed. Make Python throw a nice error.
  715. open(grammar_path, encoding='utf8')
  716. assert False
  717. return _imported_grammars[grammar_path]
  718. def load_grammar(self, grammar_text, grammar_name='<?>', import_paths=[]):
  719. "Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
  720. try:
  721. tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
  722. except UnexpectedCharacters as e:
  723. context = e.get_context(grammar_text)
  724. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  725. (e.line, e.column, grammar_name, context))
  726. except UnexpectedToken as e:
  727. context = e.get_context(grammar_text)
  728. error = e.match_examples(self.parser.parse, self.ERRORS, use_accepts=True)
  729. if error:
  730. raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  731. elif 'STRING' in e.expected:
  732. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  733. raise
  734. tree = PrepareGrammar().transform(tree)
  735. # Extract grammar items
  736. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  737. term_defs = defs.pop('term', [])
  738. rule_defs = defs.pop('rule', [])
  739. statements = defs.pop('statement', [])
  740. assert not defs
  741. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  742. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  743. rule_defs = [options_from_rule(*x) for x in rule_defs]
  744. # Execute statements
  745. ignore, imports = [], {}
  746. for (stmt,) in statements:
  747. if stmt.data == 'ignore':
  748. t ,= stmt.children
  749. ignore.append(t)
  750. elif stmt.data == 'import':
  751. if len(stmt.children) > 1:
  752. path_node, arg1 = stmt.children
  753. else:
  754. path_node ,= stmt.children
  755. arg1 = None
  756. if isinstance(arg1, Tree): # Multi import
  757. dotted_path = tuple(path_node.children)
  758. names = arg1.children
  759. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  760. else: # Single import
  761. dotted_path = tuple(path_node.children[:-1])
  762. name = path_node.children[-1] # Get name from dotted path
  763. aliases = {name: arg1 or name} # Aliases if exist
  764. if path_node.data == 'import_lib': # Import from library
  765. base_path = None
  766. else: # Relative import
  767. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  768. try:
  769. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  770. except AttributeError:
  771. base_file = None
  772. else:
  773. base_file = grammar_name # Import relative to grammar file path if external grammar file
  774. if base_file:
  775. if isinstance(base_file, PackageResource):
  776. base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
  777. else:
  778. base_path = os.path.split(base_file)[0]
  779. else:
  780. base_path = os.path.abspath(os.path.curdir)
  781. try:
  782. import_base_path, import_aliases = imports[dotted_path]
  783. assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
  784. import_aliases.update(aliases)
  785. except KeyError:
  786. imports[dotted_path] = base_path, aliases
  787. elif stmt.data == 'declare':
  788. for t in stmt.children:
  789. term_defs.append([t.value, (None, None)])
  790. else:
  791. assert False, stmt
  792. # import grammars
  793. for dotted_path, (base_path, aliases) in imports.items():
  794. grammar_path = os.path.join(*dotted_path) + EXT
  795. g = self.import_grammar(grammar_path, base_path=base_path, import_paths=import_paths)
  796. new_td, new_rd = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases)
  797. term_defs += new_td
  798. rule_defs += new_rd
  799. # Verify correctness 1
  800. for name, _ in term_defs:
  801. if name.startswith('__'):
  802. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  803. # Handle ignore tokens
  804. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  805. # inability to handle duplicate terminals (two names, one value)
  806. ignore_names = []
  807. for t in ignore:
  808. if t.data=='expansions' and len(t.children) == 1:
  809. t2 ,= t.children
  810. if t2.data=='expansion' and len(t2.children) == 1:
  811. item ,= t2.children
  812. if item.data == 'value':
  813. item ,= item.children
  814. if isinstance(item, Token) and item.type == 'TERMINAL':
  815. ignore_names.append(item.value)
  816. continue
  817. name = '__IGNORE_%d'% len(ignore_names)
  818. ignore_names.append(name)
  819. term_defs.append((name, (t, 1)))
  820. # Verify correctness 2
  821. terminal_names = set()
  822. for name, _ in term_defs:
  823. if name in terminal_names:
  824. raise GrammarError("Terminal '%s' defined more than once" % name)
  825. terminal_names.add(name)
  826. if set(ignore_names) > terminal_names:
  827. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names))
  828. resolve_term_references(term_defs)
  829. rules = rule_defs
  830. rule_names = {}
  831. for name, params, _x, option in rules:
  832. # We can't just simply not throw away the tokens later, we need option.keep_all_tokens to correctly generate maybe_placeholders
  833. if self.global_keep_all_tokens:
  834. option.keep_all_tokens = True
  835. if name.startswith('__'):
  836. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  837. if name in rule_names:
  838. raise GrammarError("Rule '%s' defined more than once" % name)
  839. rule_names[name] = len(params)
  840. for name, params , expansions, _o in rules:
  841. for i, p in enumerate(params):
  842. if p in rule_names:
  843. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  844. if p in params[:i]:
  845. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  846. for temp in expansions.find_data('template_usage'):
  847. sym = temp.children[0]
  848. args = temp.children[1:]
  849. if sym not in params:
  850. if sym not in rule_names:
  851. raise GrammarError("Template '%s' used but not defined (in rule %s)" % (sym, name))
  852. if len(args) != rule_names[sym]:
  853. raise GrammarError("Wrong number of template arguments used for %s "
  854. "(expected %s, got %s) (in rule %s)"%(sym, rule_names[sym], len(args), name))
  855. for sym in _find_used_symbols(expansions):
  856. if sym.type == 'TERMINAL':
  857. if sym not in terminal_names:
  858. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  859. else:
  860. if sym not in rule_names and sym not in params:
  861. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  862. return Grammar(rules, term_defs, ignore_names)
  863. def load_grammar(grammar, source, import_paths, global_keep_all_tokens):
  864. return GrammarLoader(global_keep_all_tokens).load_grammar(grammar, source, import_paths)