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.

936 lines
34 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. from .utils import bfs, eval_escaping
  7. from .lexer import Token, TerminalDef, PatternStr, PatternRE
  8. from .parse_tree_builder import ParseTreeBuilder
  9. from .parser_frontends import LALR_TraditionalLexer
  10. from .common import LexerConf, ParserConf
  11. from .grammar import RuleOptions, Rule, Terminal, NonTerminal, Symbol
  12. from .utils import classify, suppress, dedup_list, Str
  13. from .exceptions import GrammarError, UnexpectedCharacters, UnexpectedToken
  14. from .tree import Tree, SlottedTree as ST
  15. from .visitors import Transformer, Visitor, v_args, Transformer_InPlace
  16. inline_args = v_args(inline=True)
  17. __path__ = os.path.dirname(__file__)
  18. IMPORT_PATHS = [os.path.join(__path__, 'grammars')]
  19. EXT = '.lark'
  20. _RE_FLAGS = 'imslux'
  21. _EMPTY = Symbol('__empty__')
  22. _TERMINAL_NAMES = {
  23. '.' : 'DOT',
  24. ',' : 'COMMA',
  25. ':' : 'COLON',
  26. ';' : 'SEMICOLON',
  27. '+' : 'PLUS',
  28. '-' : 'MINUS',
  29. '*' : 'STAR',
  30. '/' : 'SLASH',
  31. '\\' : 'BACKSLASH',
  32. '|' : 'VBAR',
  33. '?' : 'QMARK',
  34. '!' : 'BANG',
  35. '@' : 'AT',
  36. '#' : 'HASH',
  37. '$' : 'DOLLAR',
  38. '%' : 'PERCENT',
  39. '^' : 'CIRCUMFLEX',
  40. '&' : 'AMPERSAND',
  41. '_' : 'UNDERSCORE',
  42. '<' : 'LESSTHAN',
  43. '>' : 'MORETHAN',
  44. '=' : 'EQUAL',
  45. '"' : 'DBLQUOTE',
  46. '\'' : 'QUOTE',
  47. '`' : 'BACKQUOTE',
  48. '~' : 'TILDE',
  49. '(' : 'LPAR',
  50. ')' : 'RPAR',
  51. '{' : 'LBRACE',
  52. '}' : 'RBRACE',
  53. '[' : 'LSQB',
  54. ']' : 'RSQB',
  55. '\n' : 'NEWLINE',
  56. '\r\n' : 'CRLF',
  57. '\t' : 'TAB',
  58. ' ' : 'SPACE',
  59. }
  60. # Grammar Parser
  61. TERMINALS = {
  62. '_LPAR': r'\(',
  63. '_RPAR': r'\)',
  64. '_LBRA': r'\[',
  65. '_RBRA': r'\]',
  66. '_LBRACE': r'\{',
  67. '_RBRACE': r'\}',
  68. 'OP': '[+*]|[?](?![a-z])',
  69. '_COLON': ':',
  70. '_COMMA': ',',
  71. '_OR': r'\|',
  72. '_DOT': r'\.(?!\.)',
  73. '_DOTDOT': r'\.\.',
  74. 'TILDE': '~',
  75. 'RULE': '!?[_?]?[a-z][_a-z0-9]*',
  76. 'TERMINAL': '_?[A-Z][_A-Z0-9]*',
  77. 'STRING': r'"(\\"|\\\\|[^"\n])*?"i?',
  78. 'REGEXP': r'/(?!/)(\\/|\\\\|[^/\n])*?/[%s]*' % _RE_FLAGS,
  79. '_NL': r'(\r?\n)+\s*',
  80. 'WS': r'[ \t]+',
  81. 'COMMENT': r'\s*//[^\n]*',
  82. '_TO': '->',
  83. '_IGNORE': r'%ignore',
  84. '_DECLARE': r'%declare',
  85. '_IMPORT': r'%import',
  86. 'NUMBER': r'[+-]?\d+',
  87. }
  88. RULES = {
  89. 'start': ['_list'],
  90. '_list': ['_item', '_list _item'],
  91. '_item': ['rule', 'term', 'statement', '_NL'],
  92. 'rule': ['RULE template_params _COLON expansions _NL',
  93. 'RULE template_params _DOT NUMBER _COLON expansions _NL'],
  94. 'template_params': ['_LBRACE _template_params _RBRACE',
  95. ''],
  96. '_template_params': ['RULE',
  97. '_template_params _COMMA RULE'],
  98. 'expansions': ['alias',
  99. 'expansions _OR alias',
  100. 'expansions _NL _OR alias'],
  101. '?alias': ['expansion _TO RULE', 'expansion'],
  102. 'expansion': ['_expansion'],
  103. '_expansion': ['', '_expansion expr'],
  104. '?expr': ['atom',
  105. 'atom OP',
  106. 'atom TILDE NUMBER',
  107. 'atom TILDE NUMBER _DOTDOT NUMBER',
  108. ],
  109. '?atom': ['_LPAR expansions _RPAR',
  110. 'maybe',
  111. 'value'],
  112. 'value': ['terminal',
  113. 'nonterminal',
  114. 'literal',
  115. 'range',
  116. 'template_usage'],
  117. 'terminal': ['TERMINAL'],
  118. 'nonterminal': ['RULE'],
  119. '?name': ['RULE', 'TERMINAL'],
  120. 'maybe': ['_LBRA expansions _RBRA'],
  121. 'range': ['STRING _DOTDOT STRING'],
  122. 'template_usage': ['RULE _LBRACE _template_args _RBRACE'],
  123. '_template_args': ['value',
  124. '_template_args _COMMA value'],
  125. 'term': ['TERMINAL _COLON expansions _NL',
  126. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  127. 'statement': ['ignore', 'import', 'declare'],
  128. 'ignore': ['_IGNORE expansions _NL'],
  129. 'declare': ['_DECLARE _declare_args _NL'],
  130. 'import': ['_IMPORT _import_path _NL',
  131. '_IMPORT _import_path _LPAR name_list _RPAR _NL',
  132. '_IMPORT _import_path _TO name _NL'],
  133. '_import_path': ['import_lib', 'import_rel'],
  134. 'import_lib': ['_import_args'],
  135. 'import_rel': ['_DOT _import_args'],
  136. '_import_args': ['name', '_import_args _DOT name'],
  137. 'name_list': ['_name_list'],
  138. '_name_list': ['name', '_name_list _COMMA name'],
  139. '_declare_args': ['name', '_declare_args name'],
  140. 'literal': ['REGEXP', 'STRING'],
  141. }
  142. @inline_args
  143. class EBNF_to_BNF(Transformer_InPlace):
  144. def __init__(self):
  145. self.new_rules = []
  146. self.rules_by_expr = {}
  147. self.prefix = 'anon'
  148. self.i = 0
  149. self.rule_options = None
  150. def _add_recurse_rule(self, type_, expr):
  151. if expr in self.rules_by_expr:
  152. return self.rules_by_expr[expr]
  153. new_name = '__%s_%s_%d' % (self.prefix, type_, self.i)
  154. self.i += 1
  155. t = NonTerminal(new_name)
  156. tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])])
  157. self.new_rules.append((new_name, tree, self.rule_options))
  158. self.rules_by_expr[expr] = t
  159. return t
  160. def expr(self, rule, op, *args):
  161. if op.value == '?':
  162. empty = ST('expansion', [])
  163. return ST('expansions', [rule, empty])
  164. elif op.value == '+':
  165. # a : b c+ d
  166. # -->
  167. # a : b _c d
  168. # _c : _c c | c;
  169. return self._add_recurse_rule('plus', rule)
  170. elif op.value == '*':
  171. # a : b c* d
  172. # -->
  173. # a : b _c? d
  174. # _c : _c c | c;
  175. new_name = self._add_recurse_rule('star', rule)
  176. return ST('expansions', [new_name, ST('expansion', [])])
  177. elif op.value == '~':
  178. if len(args) == 1:
  179. mn = mx = int(args[0])
  180. else:
  181. mn, mx = map(int, args)
  182. if mx < mn or mn < 0:
  183. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  184. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)])
  185. assert False, op
  186. def maybe(self, rule):
  187. keep_all_tokens = self.rule_options and self.rule_options.keep_all_tokens
  188. def will_not_get_removed(sym):
  189. if isinstance(sym, NonTerminal):
  190. return not sym.name.startswith('_')
  191. if isinstance(sym, Terminal):
  192. return keep_all_tokens or not sym.filter_out
  193. assert False
  194. if any(rule.scan_values(will_not_get_removed)):
  195. empty = _EMPTY
  196. else:
  197. empty = ST('expansion', [])
  198. return ST('expansions', [rule, empty])
  199. class SimplifyRule_Visitor(Visitor):
  200. @staticmethod
  201. def _flatten(tree):
  202. while True:
  203. to_expand = [i for i, child in enumerate(tree.children)
  204. if isinstance(child, Tree) and child.data == tree.data]
  205. if not to_expand:
  206. break
  207. tree.expand_kids_by_index(*to_expand)
  208. def expansion(self, tree):
  209. # rules_list unpacking
  210. # a : b (c|d) e
  211. # -->
  212. # a : b c e | b d e
  213. #
  214. # In AST terms:
  215. # expansion(b, expansions(c, d), e)
  216. # -->
  217. # expansions( expansion(b, c, e), expansion(b, d, e) )
  218. self._flatten(tree)
  219. for i, child in enumerate(tree.children):
  220. if isinstance(child, Tree) and child.data == 'expansions':
  221. tree.data = 'expansions'
  222. tree.children = [self.visit(ST('expansion', [option if i==j else other
  223. for j, other in enumerate(tree.children)]))
  224. for option in dedup_list(child.children)]
  225. self._flatten(tree)
  226. break
  227. def alias(self, tree):
  228. rule, alias_name = tree.children
  229. if rule.data == 'expansions':
  230. aliases = []
  231. for child in tree.children[0].children:
  232. aliases.append(ST('alias', [child, alias_name]))
  233. tree.data = 'expansions'
  234. tree.children = aliases
  235. def expansions(self, tree):
  236. self._flatten(tree)
  237. tree.children = dedup_list(tree.children)
  238. class RuleTreeToText(Transformer):
  239. def expansions(self, x):
  240. return x
  241. def expansion(self, symbols):
  242. return symbols, None
  243. def alias(self, x):
  244. (expansion, _alias), alias = x
  245. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  246. return expansion, alias.value
  247. @inline_args
  248. class CanonizeTree(Transformer_InPlace):
  249. def tokenmods(self, *args):
  250. if len(args) == 1:
  251. return list(args)
  252. tokenmods, value = args
  253. return tokenmods + [value]
  254. class PrepareAnonTerminals(Transformer_InPlace):
  255. "Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them"
  256. def __init__(self, terminals):
  257. self.terminals = terminals
  258. self.term_set = {td.name for td in self.terminals}
  259. self.term_reverse = {td.pattern: td for td in terminals}
  260. self.i = 0
  261. @inline_args
  262. def pattern(self, p):
  263. value = p.value
  264. if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags:
  265. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  266. term_name = None
  267. if isinstance(p, PatternStr):
  268. try:
  269. # If already defined, use the user-defined terminal name
  270. term_name = self.term_reverse[p].name
  271. except KeyError:
  272. # Try to assign an indicative anon-terminal name
  273. try:
  274. term_name = _TERMINAL_NAMES[value]
  275. except KeyError:
  276. if value.isalnum() and value[0].isalpha() and value.upper() not in self.term_set:
  277. with suppress(UnicodeEncodeError):
  278. value.upper().encode('ascii') # Make sure we don't have unicode in our terminal names
  279. term_name = value.upper()
  280. if term_name in self.term_set:
  281. term_name = None
  282. elif isinstance(p, PatternRE):
  283. if p in self.term_reverse: # Kind of a wierd placement.name
  284. term_name = self.term_reverse[p].name
  285. else:
  286. assert False, p
  287. if term_name is None:
  288. term_name = '__ANON_%d' % self.i
  289. self.i += 1
  290. if term_name not in self.term_set:
  291. assert p not in self.term_reverse
  292. self.term_set.add(term_name)
  293. termdef = TerminalDef(term_name, p)
  294. self.term_reverse[p] = termdef
  295. self.terminals.append(termdef)
  296. return Terminal(term_name, filter_out=isinstance(p, PatternStr))
  297. class _ReplaceSymbols(Transformer_InPlace):
  298. " Helper for ApplyTemplates "
  299. def __init__(self):
  300. super(_ReplaceSymbols, self).__init__()
  301. self.names = {}
  302. def value(self, c):
  303. if len(c) == 1 and isinstance(c[0], Token) and c[0].type == 'RULE' and c[0].value in self.names:
  304. return self.names[c[0].value]
  305. return self.__default__('value', c, None)
  306. class ApplyTemplates(Transformer_InPlace):
  307. " Apply the templates, creating new rules that represent the used templates "
  308. def __init__(self, rule_defs):
  309. super(ApplyTemplates, self).__init__()
  310. self.rule_defs = rule_defs
  311. self.replacer = _ReplaceSymbols()
  312. self.created_templates = set()
  313. def template_usage(self, c):
  314. name = c[0]
  315. args = c[1:]
  316. result_name = "%s{%s}" % (name, ",".join(a.name for a in args))
  317. if result_name not in self.created_templates:
  318. self.created_templates.add(result_name)
  319. (_n, params, tree, options) ,= (t for t in self.rule_defs if t[0] == name)
  320. assert len(params) == len(args), args
  321. result_tree = deepcopy(tree)
  322. self.replacer.names = dict(zip(params, args))
  323. self.replacer.transform(result_tree)
  324. self.rule_defs.append((result_name, [], result_tree, deepcopy(options)))
  325. return NonTerminal(result_name)
  326. def _rfind(s, choices):
  327. return max(s.rfind(c) for c in choices)
  328. def _literal_to_pattern(literal):
  329. v = literal.value
  330. flag_start = _rfind(v, '/"')+1
  331. assert flag_start > 0
  332. flags = v[flag_start:]
  333. assert all(f in _RE_FLAGS for f in flags), flags
  334. v = v[:flag_start]
  335. assert v[0] == v[-1] and v[0] in '"/'
  336. x = v[1:-1]
  337. s = eval_escaping(x)
  338. if literal.type == 'STRING':
  339. s = s.replace('\\\\', '\\')
  340. return { 'STRING': PatternStr,
  341. 'REGEXP': PatternRE }[literal.type](s, flags)
  342. @inline_args
  343. class PrepareLiterals(Transformer_InPlace):
  344. def literal(self, literal):
  345. return ST('pattern', [_literal_to_pattern(literal)])
  346. def range(self, start, end):
  347. assert start.type == end.type == 'STRING'
  348. start = start.value[1:-1]
  349. end = end.value[1:-1]
  350. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1, (start, end, len(eval_escaping(start)), len(eval_escaping(end)))
  351. regexp = '[%s-%s]' % (start, end)
  352. return ST('pattern', [PatternRE(regexp)])
  353. class TerminalTreeToPattern(Transformer):
  354. def pattern(self, ps):
  355. p ,= ps
  356. return p
  357. def expansion(self, items):
  358. assert items
  359. if len(items) == 1:
  360. return items[0]
  361. if len({i.flags for i in items}) > 1:
  362. raise GrammarError("Lark doesn't support joining terminals with conflicting flags!")
  363. return PatternRE(''.join(i.to_regexp() for i in items), items[0].flags if items else ())
  364. def expansions(self, exps):
  365. if len(exps) == 1:
  366. return exps[0]
  367. if len({i.flags for i in exps}) > 1:
  368. raise GrammarError("Lark doesn't support joining terminals with conflicting flags!")
  369. return PatternRE('(?:%s)' % ('|'.join(i.to_regexp() for i in exps)), exps[0].flags)
  370. def expr(self, args):
  371. inner, op = args[:2]
  372. if op == '~':
  373. if len(args) == 3:
  374. op = "{%d}" % int(args[2])
  375. else:
  376. mn, mx = map(int, args[2:])
  377. if mx < mn:
  378. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  379. op = "{%d,%d}" % (mn, mx)
  380. else:
  381. assert len(args) == 2
  382. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  383. def maybe(self, expr):
  384. return self.expr(expr + ['?'])
  385. def alias(self, t):
  386. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  387. def value(self, v):
  388. return v[0]
  389. class PrepareSymbols(Transformer_InPlace):
  390. def value(self, v):
  391. v ,= v
  392. if isinstance(v, Tree):
  393. return v
  394. elif v.type == 'RULE':
  395. return NonTerminal(Str(v.value))
  396. elif v.type == 'TERMINAL':
  397. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  398. assert False
  399. def _choice_of_rules(rules):
  400. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  401. class Grammar:
  402. def __init__(self, rule_defs, term_defs, ignore):
  403. self.term_defs = term_defs
  404. self.rule_defs = rule_defs
  405. self.ignore = ignore
  406. def compile(self, start):
  407. # We change the trees in-place (to support huge grammars)
  408. # So deepcopy allows calling compile more than once.
  409. term_defs = deepcopy(list(self.term_defs))
  410. rule_defs = deepcopy(self.rule_defs)
  411. # ===================
  412. # Compile Terminals
  413. # ===================
  414. # Convert terminal-trees to strings/regexps
  415. for name, (term_tree, priority) in term_defs:
  416. if term_tree is None: # Terminal added through %declare
  417. continue
  418. expansions = list(term_tree.find_data('expansion'))
  419. if len(expansions) == 1 and not expansions[0].children:
  420. raise GrammarError("Terminals cannot be empty (%s)" % name)
  421. transformer = PrepareLiterals() * TerminalTreeToPattern()
  422. terminals = [TerminalDef(name, transformer.transform( term_tree ), priority)
  423. for name, (term_tree, priority) in term_defs if term_tree]
  424. # =================
  425. # Compile Rules
  426. # =================
  427. # 1. Pre-process terminals
  428. transformer = PrepareLiterals() * PrepareSymbols() * PrepareAnonTerminals(terminals) # Adds to terminals
  429. # 2. Inline Templates
  430. transformer *= ApplyTemplates(rule_defs)
  431. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  432. ebnf_to_bnf = EBNF_to_BNF()
  433. rules = []
  434. i = 0
  435. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  436. name, params, rule_tree, options = rule_defs[i]
  437. i += 1
  438. if len(params) != 0: # Dont transform templates
  439. continue
  440. ebnf_to_bnf.rule_options = RuleOptions(keep_all_tokens=True) if options.keep_all_tokens else None
  441. ebnf_to_bnf.prefix = name
  442. tree = transformer.transform(rule_tree)
  443. res = ebnf_to_bnf.transform(tree)
  444. rules.append((name, res, options))
  445. rules += ebnf_to_bnf.new_rules
  446. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  447. # 4. Compile tree to Rule objects
  448. rule_tree_to_text = RuleTreeToText()
  449. simplify_rule = SimplifyRule_Visitor()
  450. compiled_rules = []
  451. for rule_content in rules:
  452. name, tree, options = rule_content
  453. simplify_rule.visit(tree)
  454. expansions = rule_tree_to_text.transform(tree)
  455. for i, (expansion, alias) in enumerate(expansions):
  456. if alias and name.startswith('_'):
  457. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)" % (name, alias))
  458. empty_indices = [x==_EMPTY for x in expansion]
  459. if any(empty_indices):
  460. exp_options = copy(options) or RuleOptions()
  461. exp_options.empty_indices = empty_indices
  462. expansion = [x for x in expansion if x!=_EMPTY]
  463. else:
  464. exp_options = options
  465. assert all(isinstance(x, Symbol) for x in expansion), expansion
  466. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  467. compiled_rules.append(rule)
  468. # Remove duplicates of empty rules, throw error for non-empty duplicates
  469. if len(set(compiled_rules)) != len(compiled_rules):
  470. duplicates = classify(compiled_rules, lambda x: x)
  471. for dups in duplicates.values():
  472. if len(dups) > 1:
  473. if dups[0].expansion:
  474. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  475. % ''.join('\n * %s' % i for i in dups))
  476. # Empty rule; assert all other attributes are equal
  477. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  478. # Remove duplicates
  479. compiled_rules = list(set(compiled_rules))
  480. # Filter out unused rules
  481. while True:
  482. c = len(compiled_rules)
  483. used_rules = {s for r in compiled_rules
  484. for s in r.expansion
  485. if isinstance(s, NonTerminal)
  486. and s != r.origin}
  487. used_rules |= {NonTerminal(s) for s in start}
  488. compiled_rules = [r for r in compiled_rules if r.origin in used_rules]
  489. if len(compiled_rules) == c:
  490. break
  491. # Filter out unused terminals
  492. used_terms = {t.name for r in compiled_rules
  493. for t in r.expansion
  494. if isinstance(t, Terminal)}
  495. terminals = [t for t in terminals if t.name in used_terms or t.name in self.ignore]
  496. return terminals, compiled_rules, self.ignore
  497. _imported_grammars = {}
  498. def import_grammar(grammar_path, base_paths=[]):
  499. if grammar_path not in _imported_grammars:
  500. import_paths = base_paths + IMPORT_PATHS
  501. for import_path in import_paths:
  502. with suppress(IOError):
  503. joined_path = os.path.join(import_path, grammar_path)
  504. with open(joined_path, encoding='utf8') as f:
  505. text = f.read()
  506. grammar = load_grammar(text, joined_path)
  507. _imported_grammars[grammar_path] = grammar
  508. break
  509. else:
  510. open(grammar_path, encoding='utf8')
  511. assert False
  512. return _imported_grammars[grammar_path]
  513. def import_from_grammar_into_namespace(grammar, namespace, aliases):
  514. """Returns all rules and terminals of grammar, prepended
  515. with a 'namespace' prefix, except for those which are aliased.
  516. """
  517. imported_terms = dict(grammar.term_defs)
  518. imported_rules = {n:(n,p,deepcopy(t),o) for n,p,t,o in grammar.rule_defs}
  519. term_defs = []
  520. rule_defs = []
  521. def rule_dependencies(symbol):
  522. if symbol.type != 'RULE':
  523. return []
  524. try:
  525. _, params, tree,_ = imported_rules[symbol]
  526. except KeyError:
  527. raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace))
  528. return _find_used_symbols(tree) - set(params)
  529. def get_namespace_name(name, params):
  530. if params is not None:
  531. try:
  532. return params[name]
  533. except KeyError:
  534. pass
  535. try:
  536. return aliases[name].value
  537. except KeyError:
  538. if name[0] == '_':
  539. return '_%s__%s' % (namespace, name[1:])
  540. return '%s__%s' % (namespace, name)
  541. to_import = list(bfs(aliases, rule_dependencies))
  542. for symbol in to_import:
  543. if symbol.type == 'TERMINAL':
  544. term_defs.append([get_namespace_name(symbol, None), imported_terms[symbol]])
  545. else:
  546. assert symbol.type == 'RULE'
  547. _, params, tree, options = imported_rules[symbol]
  548. params_map = {p: ('%s__%s' if p[0]!='_' else '_%s__%s' ) % (namespace, p) for p in params}
  549. for t in tree.iter_subtrees():
  550. for i, c in enumerate(t.children):
  551. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  552. t.children[i] = Token(c.type, get_namespace_name(c, params_map))
  553. params = [params_map[p] for p in params] # We can not rely on ordered dictionaries
  554. rule_defs.append((get_namespace_name(symbol, params_map), params, tree, options))
  555. return term_defs, rule_defs
  556. def resolve_term_references(term_defs):
  557. # TODO Solve with transitive closure (maybe)
  558. term_dict = {k:t for k, (t,_p) in term_defs}
  559. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  560. while True:
  561. changed = False
  562. for name, (token_tree, _p) in term_defs:
  563. if token_tree is None: # Terminal added through %declare
  564. continue
  565. for exp in token_tree.find_data('value'):
  566. item ,= exp.children
  567. if isinstance(item, Token):
  568. if item.type == 'RULE':
  569. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  570. if item.type == 'TERMINAL':
  571. term_value = term_dict[item]
  572. assert term_value is not None
  573. exp.children[0] = term_value
  574. changed = True
  575. if not changed:
  576. break
  577. for name, term in term_dict.items():
  578. if term: # Not just declared
  579. for child in term.children:
  580. ids = [id(x) for x in child.iter_subtrees()]
  581. if id(term) in ids:
  582. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  583. def options_from_rule(name, params, *x):
  584. if len(x) > 1:
  585. priority, expansions = x
  586. priority = int(priority)
  587. else:
  588. expansions ,= x
  589. priority = None
  590. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  591. keep_all_tokens = name.startswith('!')
  592. name = name.lstrip('!')
  593. expand1 = name.startswith('?')
  594. name = name.lstrip('?')
  595. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  596. template_source=(name if params else None))
  597. def symbols_from_strcase(expansion):
  598. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  599. @inline_args
  600. class PrepareGrammar(Transformer_InPlace):
  601. def terminal(self, name):
  602. return name
  603. def nonterminal(self, name):
  604. return name
  605. def _find_used_symbols(tree):
  606. assert tree.data == 'expansions'
  607. return {t for x in tree.find_data('expansion')
  608. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  609. class GrammarLoader:
  610. def __init__(self):
  611. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  612. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  613. 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)]
  614. callback = ParseTreeBuilder(rules, ST).create_callback()
  615. lexer_conf = LexerConf(terminals, ['WS', 'COMMENT'])
  616. parser_conf = ParserConf(rules, callback, ['start'])
  617. self.parser = LALR_TraditionalLexer(lexer_conf, parser_conf)
  618. self.canonize_tree = CanonizeTree()
  619. def load_grammar(self, grammar_text, grammar_name='<?>'):
  620. "Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
  621. try:
  622. tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
  623. except UnexpectedCharacters as e:
  624. context = e.get_context(grammar_text)
  625. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  626. (e.line, e.column, grammar_name, context))
  627. except UnexpectedToken as e:
  628. context = e.get_context(grammar_text)
  629. error = e.match_examples(self.parser.parse, {
  630. 'Unclosed parenthesis': ['a: (\n'],
  631. 'Umatched closing parenthesis': ['a: )\n', 'a: [)\n', 'a: (]\n'],
  632. 'Expecting rule or terminal definition (missing colon)': ['a\n', 'a->\n', 'A->\n', 'a A\n'],
  633. 'Alias expects lowercase name': ['a: -> "a"\n'],
  634. 'Unexpected colon': ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n'],
  635. 'Misplaced operator': ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n'],
  636. 'Expecting option ("|") or a new rule or terminal definition': ['a:a\n()\n'],
  637. '%import expects a name': ['%import "a"\n'],
  638. '%ignore expects a value': ['%ignore %import\n'],
  639. })
  640. if error:
  641. raise GrammarError("%s at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  642. elif 'STRING' in e.expected:
  643. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  644. raise
  645. tree = PrepareGrammar().transform(tree)
  646. # Extract grammar items
  647. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  648. term_defs = defs.pop('term', [])
  649. rule_defs = defs.pop('rule', [])
  650. statements = defs.pop('statement', [])
  651. assert not defs
  652. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  653. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  654. rule_defs = [options_from_rule(*x) for x in rule_defs]
  655. # Execute statements
  656. ignore, imports = [], {}
  657. for (stmt,) in statements:
  658. if stmt.data == 'ignore':
  659. t ,= stmt.children
  660. ignore.append(t)
  661. elif stmt.data == 'import':
  662. if len(stmt.children) > 1:
  663. path_node, arg1 = stmt.children
  664. else:
  665. path_node, = stmt.children
  666. arg1 = None
  667. if isinstance(arg1, Tree): # Multi import
  668. dotted_path = tuple(path_node.children)
  669. names = arg1.children
  670. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  671. else: # Single import
  672. dotted_path = tuple(path_node.children[:-1])
  673. name = path_node.children[-1] # Get name from dotted path
  674. aliases = {name: arg1 or name} # Aliases if exist
  675. if path_node.data == 'import_lib': # Import from library
  676. base_paths = []
  677. else: # Relative import
  678. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  679. try:
  680. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  681. except AttributeError:
  682. base_file = None
  683. else:
  684. base_file = grammar_name # Import relative to grammar file path if external grammar file
  685. if base_file:
  686. base_paths = [os.path.split(base_file)[0]]
  687. else:
  688. base_paths = [os.path.abspath(os.path.curdir)]
  689. try:
  690. import_base_paths, import_aliases = imports[dotted_path]
  691. assert base_paths == import_base_paths, 'Inconsistent base_paths for %s.' % '.'.join(dotted_path)
  692. import_aliases.update(aliases)
  693. except KeyError:
  694. imports[dotted_path] = base_paths, aliases
  695. elif stmt.data == 'declare':
  696. for t in stmt.children:
  697. term_defs.append([t.value, (None, None)])
  698. else:
  699. assert False, stmt
  700. # import grammars
  701. for dotted_path, (base_paths, aliases) in imports.items():
  702. grammar_path = os.path.join(*dotted_path) + EXT
  703. g = import_grammar(grammar_path, base_paths=base_paths)
  704. new_td, new_rd = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases)
  705. term_defs += new_td
  706. rule_defs += new_rd
  707. # Verify correctness 1
  708. for name, _ in term_defs:
  709. if name.startswith('__'):
  710. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  711. # Handle ignore tokens
  712. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  713. # inability to handle duplicate terminals (two names, one value)
  714. ignore_names = []
  715. for t in ignore:
  716. if t.data=='expansions' and len(t.children) == 1:
  717. t2 ,= t.children
  718. if t2.data=='expansion' and len(t2.children) == 1:
  719. item ,= t2.children
  720. if item.data == 'value':
  721. item ,= item.children
  722. if isinstance(item, Token) and item.type == 'TERMINAL':
  723. ignore_names.append(item.value)
  724. continue
  725. name = '__IGNORE_%d'% len(ignore_names)
  726. ignore_names.append(name)
  727. term_defs.append((name, (t, 1)))
  728. # Verify correctness 2
  729. terminal_names = set()
  730. for name, _ in term_defs:
  731. if name in terminal_names:
  732. raise GrammarError("Terminal '%s' defined more than once" % name)
  733. terminal_names.add(name)
  734. if set(ignore_names) > terminal_names:
  735. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names))
  736. resolve_term_references(term_defs)
  737. rules = rule_defs
  738. rule_names = {}
  739. for name, params, _x, _o in rules:
  740. if name.startswith('__'):
  741. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  742. if name in rule_names:
  743. raise GrammarError("Rule '%s' defined more than once" % name)
  744. rule_names[name] = len(params)
  745. for name, params , expansions, _o in rules:
  746. for i, p in enumerate(params):
  747. if p in rule_names:
  748. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  749. if p in params[:i]:
  750. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  751. for temp in expansions.find_data('template_usage'):
  752. sym = temp.children[0]
  753. args = temp.children[1:]
  754. if sym not in rule_names:
  755. raise GrammarError("Template '%s' used but not defined (in rule %s)" % (sym, name))
  756. if len(args) != rule_names[sym]:
  757. raise GrammarError("Wrong number of template arguments used for %s "
  758. "(expected %s, got %s) (in rule %s)"%(sym, rule_names[sym], len(args), name))
  759. for sym in _find_used_symbols(expansions):
  760. if sym.type == 'TERMINAL':
  761. if sym not in terminal_names:
  762. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  763. else:
  764. if sym not in rule_names and sym not in params:
  765. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  766. return Grammar(rules, term_defs, ignore_names)
  767. load_grammar = GrammarLoader().load_grammar