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.

1056 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
  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 value.isalnum() and value[0].isalpha() and value.upper() not in self.term_set:
  281. with suppress(UnicodeEncodeError):
  282. value.upper().encode('ascii') # Make sure we don't have unicode in our terminal names
  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 _literal_to_pattern(literal):
  336. v = literal.value
  337. flag_start = _rfind(v, '/"')+1
  338. assert flag_start > 0
  339. flags = v[flag_start:]
  340. assert all(f in _RE_FLAGS for f in flags), flags
  341. if literal.type == 'STRING' and '\n' in v:
  342. raise GrammarError('You cannot put newlines in string literals')
  343. if literal.type == 'REGEXP' and '\n' in v and 'x' not in flags:
  344. raise GrammarError('You can only use newlines in regular expressions '
  345. 'with the `x` (verbose) flag')
  346. v = v[:flag_start]
  347. assert v[0] == v[-1] and v[0] in '"/'
  348. x = v[1:-1]
  349. s = eval_escaping(x)
  350. if literal.type == 'STRING':
  351. s = s.replace('\\\\', '\\')
  352. return PatternStr(s, flags)
  353. elif literal.type == 'REGEXP':
  354. return PatternRE(s, flags)
  355. else:
  356. assert False, 'Invariant failed: literal.type not in ["STRING", "REGEXP"]'
  357. @inline_args
  358. class PrepareLiterals(Transformer_InPlace):
  359. def literal(self, literal):
  360. return ST('pattern', [_literal_to_pattern(literal)])
  361. def range(self, start, end):
  362. assert start.type == end.type == 'STRING'
  363. start = start.value[1:-1]
  364. end = end.value[1:-1]
  365. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1, (start, end, len(eval_escaping(start)), len(eval_escaping(end)))
  366. regexp = '[%s-%s]' % (start, end)
  367. return ST('pattern', [PatternRE(regexp)])
  368. def _make_joined_pattern(regexp, flags_set):
  369. # In Python 3.6, a new syntax for flags was introduced, that allows us to restrict the scope
  370. # of flags to a specific regexp group. We are already using it in `lexer.Pattern._get_flags`
  371. # However, for prior Python versions, we still need to use global flags, so we have to make sure
  372. # that there are no flag collisions when we merge several terminals.
  373. flags = ()
  374. if not Py36:
  375. if len(flags_set) > 1:
  376. raise GrammarError("Lark doesn't support joining terminals with conflicting flags in python <3.6!")
  377. elif len(flags_set) == 1:
  378. flags ,= flags_set
  379. return PatternRE(regexp, flags)
  380. class TerminalTreeToPattern(Transformer):
  381. def pattern(self, ps):
  382. p ,= ps
  383. return p
  384. def expansion(self, items):
  385. assert items
  386. if len(items) == 1:
  387. return items[0]
  388. pattern = ''.join(i.to_regexp() for i in items)
  389. return _make_joined_pattern(pattern, {i.flags for i in items})
  390. def expansions(self, exps):
  391. if len(exps) == 1:
  392. return exps[0]
  393. pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps))
  394. return _make_joined_pattern(pattern, {i.flags for i in exps})
  395. def expr(self, args):
  396. inner, op = args[:2]
  397. if op == '~':
  398. if len(args) == 3:
  399. op = "{%d}" % int(args[2])
  400. else:
  401. mn, mx = map(int, args[2:])
  402. if mx < mn:
  403. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  404. op = "{%d,%d}" % (mn, mx)
  405. else:
  406. assert len(args) == 2
  407. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  408. def maybe(self, expr):
  409. return self.expr(expr + ['?'])
  410. def alias(self, t):
  411. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  412. def value(self, v):
  413. return v[0]
  414. class PrepareSymbols(Transformer_InPlace):
  415. def value(self, v):
  416. v ,= v
  417. if isinstance(v, Tree):
  418. return v
  419. elif v.type == 'RULE':
  420. return NonTerminal(Str(v.value))
  421. elif v.type == 'TERMINAL':
  422. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  423. assert False
  424. def _choice_of_rules(rules):
  425. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  426. def nr_deepcopy_tree(t):
  427. "Deepcopy tree `t` without recursion"
  428. return Transformer_NonRecursive(False).transform(t)
  429. class Grammar:
  430. def __init__(self, rule_defs, term_defs, ignore):
  431. self.term_defs = term_defs
  432. self.rule_defs = rule_defs
  433. self.ignore = ignore
  434. def compile(self, start, terminals_to_keep):
  435. # We change the trees in-place (to support huge grammars)
  436. # So deepcopy allows calling compile more than once.
  437. term_defs = deepcopy(list(self.term_defs))
  438. rule_defs = [(n,p,nr_deepcopy_tree(t),o) for n,p,t,o in self.rule_defs]
  439. # ===================
  440. # Compile Terminals
  441. # ===================
  442. # Convert terminal-trees to strings/regexps
  443. for name, (term_tree, priority) in term_defs:
  444. if term_tree is None: # Terminal added through %declare
  445. continue
  446. expansions = list(term_tree.find_data('expansion'))
  447. if len(expansions) == 1 and not expansions[0].children:
  448. raise GrammarError("Terminals cannot be empty (%s)" % name)
  449. transformer = PrepareLiterals() * TerminalTreeToPattern()
  450. terminals = [TerminalDef(name, transformer.transform( term_tree ), priority)
  451. for name, (term_tree, priority) in term_defs if term_tree]
  452. # =================
  453. # Compile Rules
  454. # =================
  455. # 1. Pre-process terminals
  456. anon_tokens_transf = PrepareAnonTerminals(terminals)
  457. transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals
  458. # 2. Inline Templates
  459. transformer *= ApplyTemplates(rule_defs)
  460. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  461. ebnf_to_bnf = EBNF_to_BNF()
  462. rules = []
  463. i = 0
  464. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  465. name, params, rule_tree, options = rule_defs[i]
  466. i += 1
  467. if len(params) != 0: # Dont transform templates
  468. continue
  469. rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  470. ebnf_to_bnf.rule_options = rule_options
  471. ebnf_to_bnf.prefix = name
  472. anon_tokens_transf.rule_options = rule_options
  473. tree = transformer.transform(rule_tree)
  474. res = ebnf_to_bnf.transform(tree)
  475. rules.append((name, res, options))
  476. rules += ebnf_to_bnf.new_rules
  477. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  478. # 4. Compile tree to Rule objects
  479. rule_tree_to_text = RuleTreeToText()
  480. simplify_rule = SimplifyRule_Visitor()
  481. compiled_rules = []
  482. for rule_content in rules:
  483. name, tree, options = rule_content
  484. simplify_rule.visit(tree)
  485. expansions = rule_tree_to_text.transform(tree)
  486. for i, (expansion, alias) in enumerate(expansions):
  487. if alias and name.startswith('_'):
  488. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)" % (name, alias))
  489. empty_indices = [x==_EMPTY for x in expansion]
  490. if any(empty_indices):
  491. exp_options = copy(options) or RuleOptions()
  492. exp_options.empty_indices = empty_indices
  493. expansion = [x for x in expansion if x!=_EMPTY]
  494. else:
  495. exp_options = options
  496. assert all(isinstance(x, Symbol) for x in expansion), expansion
  497. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  498. compiled_rules.append(rule)
  499. # Remove duplicates of empty rules, throw error for non-empty duplicates
  500. if len(set(compiled_rules)) != len(compiled_rules):
  501. duplicates = classify(compiled_rules, lambda x: x)
  502. for dups in duplicates.values():
  503. if len(dups) > 1:
  504. if dups[0].expansion:
  505. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  506. % ''.join('\n * %s' % i for i in dups))
  507. # Empty rule; assert all other attributes are equal
  508. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  509. # Remove duplicates
  510. compiled_rules = list(set(compiled_rules))
  511. # Filter out unused rules
  512. while True:
  513. c = len(compiled_rules)
  514. used_rules = {s for r in compiled_rules
  515. for s in r.expansion
  516. if isinstance(s, NonTerminal)
  517. and s != r.origin}
  518. used_rules |= {NonTerminal(s) for s in start}
  519. compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules)
  520. for r in unused:
  521. logger.debug("Unused rule: %s", r)
  522. if len(compiled_rules) == c:
  523. break
  524. # Filter out unused terminals
  525. used_terms = {t.name for r in compiled_rules
  526. for t in r.expansion
  527. if isinstance(t, Terminal)}
  528. 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)
  529. if unused:
  530. logger.debug("Unused terminals: %s", [t.name for t in unused])
  531. return terminals, compiled_rules, self.ignore
  532. class PackageResource(object):
  533. """
  534. Represents a path inside a Package. Used by `FromPackageLoader`
  535. """
  536. def __init__(self, pkg_name, path):
  537. self.pkg_name = pkg_name
  538. self.path = path
  539. def __str__(self):
  540. return "<%s: %s>" % (self.pkg_name, self.path)
  541. def __repr__(self):
  542. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.path)
  543. class FromPackageLoader(object):
  544. """
  545. Provides a simple way of creating custom import loaders that load from packages via ``pkgutil.get_data`` instead of using `open`.
  546. This allows them to be compatible even from within zip files.
  547. Relative imports are handled, so you can just freely use them.
  548. pkg_name: The name of the package. You can probably provide `__name__` most of the time
  549. search_paths: All the path that will be search on absolute imports.
  550. """
  551. def __init__(self, pkg_name, search_paths=("", )):
  552. self.pkg_name = pkg_name
  553. self.search_paths = search_paths
  554. def __repr__(self):
  555. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.search_paths)
  556. def __call__(self, base_path, grammar_path):
  557. if base_path is None:
  558. to_try = self.search_paths
  559. else:
  560. # Check whether or not the importing grammar was loaded by this module.
  561. if not isinstance(base_path, PackageResource) or base_path.pkg_name != self.pkg_name:
  562. # Technically false, but FileNotFound doesn't exist in python2.7, and this message should never reach the end user anyway
  563. raise IOError()
  564. to_try = [base_path.path]
  565. for path in to_try:
  566. full_path = os.path.join(path, grammar_path)
  567. try:
  568. text = pkgutil.get_data(self.pkg_name, full_path)
  569. except IOError:
  570. continue
  571. else:
  572. return PackageResource(self.pkg_name, full_path), text.decode()
  573. raise IOError()
  574. stdlib_loader = FromPackageLoader('lark', IMPORT_PATHS)
  575. _imported_grammars = {}
  576. def import_from_grammar_into_namespace(grammar, namespace, aliases):
  577. """Returns all rules and terminals of grammar, prepended
  578. with a 'namespace' prefix, except for those which are aliased.
  579. """
  580. imported_terms = dict(grammar.term_defs)
  581. imported_rules = {n:(n,p,deepcopy(t),o) for n,p,t,o in grammar.rule_defs}
  582. term_defs = []
  583. rule_defs = []
  584. def rule_dependencies(symbol):
  585. if symbol.type != 'RULE':
  586. return []
  587. try:
  588. _, params, tree,_ = imported_rules[symbol]
  589. except KeyError:
  590. raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace))
  591. return _find_used_symbols(tree) - set(params)
  592. def get_namespace_name(name, params):
  593. if params is not None:
  594. try:
  595. return params[name]
  596. except KeyError:
  597. pass
  598. try:
  599. return aliases[name].value
  600. except KeyError:
  601. if name[0] == '_':
  602. return '_%s__%s' % (namespace, name[1:])
  603. return '%s__%s' % (namespace, name)
  604. to_import = list(bfs(aliases, rule_dependencies))
  605. for symbol in to_import:
  606. if symbol.type == 'TERMINAL':
  607. term_defs.append([get_namespace_name(symbol, None), imported_terms[symbol]])
  608. else:
  609. assert symbol.type == 'RULE'
  610. _, params, tree, options = imported_rules[symbol]
  611. params_map = {p: ('%s__%s' if p[0]!='_' else '_%s__%s' ) % (namespace, p) for p in params}
  612. for t in tree.iter_subtrees():
  613. for i, c in enumerate(t.children):
  614. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  615. t.children[i] = Token(c.type, get_namespace_name(c, params_map))
  616. params = [params_map[p] for p in params] # We can not rely on ordered dictionaries
  617. rule_defs.append((get_namespace_name(symbol, params_map), params, tree, options))
  618. return term_defs, rule_defs
  619. def resolve_term_references(term_defs):
  620. # TODO Solve with transitive closure (maybe)
  621. term_dict = {k:t for k, (t,_p) in term_defs}
  622. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  623. while True:
  624. changed = False
  625. for name, (token_tree, _p) in term_defs:
  626. if token_tree is None: # Terminal added through %declare
  627. continue
  628. for exp in token_tree.find_data('value'):
  629. item ,= exp.children
  630. if isinstance(item, Token):
  631. if item.type == 'RULE':
  632. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  633. if item.type == 'TERMINAL':
  634. term_value = term_dict[item]
  635. assert term_value is not None
  636. exp.children[0] = term_value
  637. changed = True
  638. if not changed:
  639. break
  640. for name, term in term_dict.items():
  641. if term: # Not just declared
  642. for child in term.children:
  643. ids = [id(x) for x in child.iter_subtrees()]
  644. if id(term) in ids:
  645. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  646. def options_from_rule(name, params, *x):
  647. if len(x) > 1:
  648. priority, expansions = x
  649. priority = int(priority)
  650. else:
  651. expansions ,= x
  652. priority = None
  653. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  654. keep_all_tokens = name.startswith('!')
  655. name = name.lstrip('!')
  656. expand1 = name.startswith('?')
  657. name = name.lstrip('?')
  658. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  659. template_source=(name if params else None))
  660. def symbols_from_strcase(expansion):
  661. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  662. @inline_args
  663. class PrepareGrammar(Transformer_InPlace):
  664. def terminal(self, name):
  665. return name
  666. def nonterminal(self, name):
  667. return name
  668. def _find_used_symbols(tree):
  669. assert tree.data == 'expansions'
  670. return {t for x in tree.find_data('expansion')
  671. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  672. class GrammarLoader:
  673. ERRORS = [
  674. ('Unclosed parenthesis', ['a: (\n']),
  675. ('Umatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']),
  676. ('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']),
  677. ('Illegal name for rules or terminals', ['Aa:\n']),
  678. ('Alias expects lowercase name', ['a: -> "a"\n']),
  679. ('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']),
  680. ('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']),
  681. ('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']),
  682. ('Terminal names cannot contain dots', ['A.B\n']),
  683. ('%import expects a name', ['%import "a"\n']),
  684. ('%ignore expects a value', ['%ignore %import\n']),
  685. ]
  686. def __init__(self, global_keep_all_tokens):
  687. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  688. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  689. 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)]
  690. callback = ParseTreeBuilder(rules, ST).create_callback()
  691. import re
  692. lexer_conf = LexerConf(terminals, re, ['WS', 'COMMENT'])
  693. parser_conf = ParserConf(rules, callback, ['start'])
  694. self.parser = LALR_TraditionalLexer(lexer_conf, parser_conf)
  695. self.canonize_tree = CanonizeTree()
  696. self.global_keep_all_tokens = global_keep_all_tokens
  697. def import_grammar(self, grammar_path, base_path=None, import_paths=[]):
  698. if grammar_path not in _imported_grammars:
  699. # import_paths take priority over base_path since they should handle relative imports and ignore everything else.
  700. to_try = import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
  701. for source in to_try:
  702. try:
  703. if callable(source):
  704. joined_path, text = source(base_path, grammar_path)
  705. else:
  706. joined_path = os.path.join(source, grammar_path)
  707. with open(joined_path, encoding='utf8') as f:
  708. text = f.read()
  709. except IOError:
  710. continue
  711. else:
  712. grammar = self.load_grammar(text, joined_path, import_paths)
  713. _imported_grammars[grammar_path] = grammar
  714. break
  715. else:
  716. # Search failed. Make Python throw a nice error.
  717. open(grammar_path, encoding='utf8')
  718. assert False
  719. return _imported_grammars[grammar_path]
  720. def load_grammar(self, grammar_text, grammar_name='<?>', import_paths=[]):
  721. "Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
  722. try:
  723. tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
  724. except UnexpectedCharacters as e:
  725. context = e.get_context(grammar_text)
  726. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  727. (e.line, e.column, grammar_name, context))
  728. except UnexpectedToken as e:
  729. context = e.get_context(grammar_text)
  730. error = e.match_examples(self.parser.parse, self.ERRORS, use_accepts=True)
  731. if error:
  732. raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  733. elif 'STRING' in e.expected:
  734. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  735. raise
  736. tree = PrepareGrammar().transform(tree)
  737. # Extract grammar items
  738. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  739. term_defs = defs.pop('term', [])
  740. rule_defs = defs.pop('rule', [])
  741. statements = defs.pop('statement', [])
  742. assert not defs
  743. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  744. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  745. rule_defs = [options_from_rule(*x) for x in rule_defs]
  746. # Execute statements
  747. ignore, imports = [], {}
  748. for (stmt,) in statements:
  749. if stmt.data == 'ignore':
  750. t ,= stmt.children
  751. ignore.append(t)
  752. elif stmt.data == 'import':
  753. if len(stmt.children) > 1:
  754. path_node, arg1 = stmt.children
  755. else:
  756. path_node ,= stmt.children
  757. arg1 = None
  758. if isinstance(arg1, Tree): # Multi import
  759. dotted_path = tuple(path_node.children)
  760. names = arg1.children
  761. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  762. else: # Single import
  763. dotted_path = tuple(path_node.children[:-1])
  764. name = path_node.children[-1] # Get name from dotted path
  765. aliases = {name: arg1 or name} # Aliases if exist
  766. if path_node.data == 'import_lib': # Import from library
  767. base_path = None
  768. else: # Relative import
  769. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  770. try:
  771. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  772. except AttributeError:
  773. base_file = None
  774. else:
  775. base_file = grammar_name # Import relative to grammar file path if external grammar file
  776. if base_file:
  777. if isinstance(base_file, PackageResource):
  778. base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
  779. else:
  780. base_path = os.path.split(base_file)[0]
  781. else:
  782. base_path = os.path.abspath(os.path.curdir)
  783. try:
  784. import_base_path, import_aliases = imports[dotted_path]
  785. assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
  786. import_aliases.update(aliases)
  787. except KeyError:
  788. imports[dotted_path] = base_path, aliases
  789. elif stmt.data == 'declare':
  790. for t in stmt.children:
  791. term_defs.append([t.value, (None, None)])
  792. else:
  793. assert False, stmt
  794. # import grammars
  795. for dotted_path, (base_path, aliases) in imports.items():
  796. grammar_path = os.path.join(*dotted_path) + EXT
  797. g = self.import_grammar(grammar_path, base_path=base_path, import_paths=import_paths)
  798. new_td, new_rd = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases)
  799. term_defs += new_td
  800. rule_defs += new_rd
  801. # Verify correctness 1
  802. for name, _ in term_defs:
  803. if name.startswith('__'):
  804. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  805. # Handle ignore tokens
  806. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  807. # inability to handle duplicate terminals (two names, one value)
  808. ignore_names = []
  809. for t in ignore:
  810. if t.data=='expansions' and len(t.children) == 1:
  811. t2 ,= t.children
  812. if t2.data=='expansion' and len(t2.children) == 1:
  813. item ,= t2.children
  814. if item.data == 'value':
  815. item ,= item.children
  816. if isinstance(item, Token) and item.type == 'TERMINAL':
  817. ignore_names.append(item.value)
  818. continue
  819. name = '__IGNORE_%d'% len(ignore_names)
  820. ignore_names.append(name)
  821. term_defs.append((name, (t, 1)))
  822. # Verify correctness 2
  823. terminal_names = set()
  824. for name, _ in term_defs:
  825. if name in terminal_names:
  826. raise GrammarError("Terminal '%s' defined more than once" % name)
  827. terminal_names.add(name)
  828. if set(ignore_names) > terminal_names:
  829. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names))
  830. resolve_term_references(term_defs)
  831. rules = rule_defs
  832. rule_names = {}
  833. for name, params, _x, option in rules:
  834. # We can't just simply not throw away the tokens later, we need option.keep_all_tokens to correctly generate maybe_placeholders
  835. if self.global_keep_all_tokens:
  836. option.keep_all_tokens = True
  837. if name.startswith('__'):
  838. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  839. if name in rule_names:
  840. raise GrammarError("Rule '%s' defined more than once" % name)
  841. rule_names[name] = len(params)
  842. for name, params , expansions, _o in rules:
  843. for i, p in enumerate(params):
  844. if p in rule_names:
  845. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  846. if p in params[:i]:
  847. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  848. for temp in expansions.find_data('template_usage'):
  849. sym = temp.children[0]
  850. args = temp.children[1:]
  851. if sym not in params:
  852. if sym not in rule_names:
  853. raise GrammarError("Template '%s' used but not defined (in rule %s)" % (sym, name))
  854. if len(args) != rule_names[sym]:
  855. raise GrammarError("Wrong number of template arguments used for %s "
  856. "(expected %s, got %s) (in rule %s)"%(sym, rule_names[sym], len(args), name))
  857. for sym in _find_used_symbols(expansions):
  858. if sym.type == 'TERMINAL':
  859. if sym not in terminal_names:
  860. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  861. else:
  862. if sym not in rule_names and sym not in params:
  863. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  864. return Grammar(rules, term_defs, ignore_names)
  865. def load_grammar(grammar, source, import_paths, global_keep_all_tokens):
  866. return GrammarLoader(global_keep_all_tokens).load_grammar(grammar, source, import_paths)