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.

980 lines
36 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', 'template', 'term', 'statement', '_NL'],
  92. 'template': ['RULE _LBRACE template_params _RBRACE _COLON expansions _NL',
  93. 'RULE _LBRACE template_params _RBRACE _DOT NUMBER _COLON expansions _NL'],
  94. 'template_params': ['_template_params'],
  95. '_template_params': ['RULE',
  96. '_template_params _COMMA RULE'],
  97. 'rule': ['RULE _COLON expansions _NL',
  98. 'RULE _DOT NUMBER _COLON expansions _NL'],
  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. tree.children = dedup_list(tree.children)
  239. class RuleTreeToText(Transformer):
  240. def expansions(self, x):
  241. return x
  242. def expansion(self, symbols):
  243. return symbols, None
  244. def alias(self, x):
  245. (expansion, _alias), alias = x
  246. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  247. return expansion, alias.value
  248. @inline_args
  249. class CanonizeTree(Transformer_InPlace):
  250. def tokenmods(self, *args):
  251. if len(args) == 1:
  252. return list(args)
  253. tokenmods, value = args
  254. return tokenmods + [value]
  255. class PrepareAnonTerminals(Transformer_InPlace):
  256. "Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them"
  257. def __init__(self, terminals):
  258. self.terminals = terminals
  259. self.term_set = {td.name for td in self.terminals}
  260. self.term_reverse = {td.pattern: td for td in terminals}
  261. self.i = 0
  262. @inline_args
  263. def pattern(self, p):
  264. value = p.value
  265. if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags:
  266. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  267. term_name = None
  268. if isinstance(p, PatternStr):
  269. try:
  270. # If already defined, use the user-defined terminal name
  271. term_name = self.term_reverse[p].name
  272. except KeyError:
  273. # Try to assign an indicative anon-terminal name
  274. try:
  275. term_name = _TERMINAL_NAMES[value]
  276. except KeyError:
  277. if value.isalnum() and value[0].isalpha() and value.upper() not in self.term_set:
  278. with suppress(UnicodeEncodeError):
  279. value.upper().encode('ascii') # Make sure we don't have unicode in our terminal names
  280. term_name = value.upper()
  281. if term_name in self.term_set:
  282. term_name = None
  283. elif isinstance(p, PatternRE):
  284. if p in self.term_reverse: # Kind of a wierd placement.name
  285. term_name = self.term_reverse[p].name
  286. else:
  287. assert False, p
  288. if term_name is None:
  289. term_name = '__ANON_%d' % self.i
  290. self.i += 1
  291. if term_name not in self.term_set:
  292. assert p not in self.term_reverse
  293. self.term_set.add(term_name)
  294. termdef = TerminalDef(term_name, p)
  295. self.term_reverse[p] = termdef
  296. self.terminals.append(termdef)
  297. return Terminal(term_name, filter_out=isinstance(p, PatternStr))
  298. class _ReplaceSymbols(Transformer_InPlace):
  299. " Helper for ApplyTemplates "
  300. def __init__(self):
  301. super(_ReplaceSymbols, self).__init__()
  302. self.names = {}
  303. def value(self, c):
  304. if len(c) == 1 and isinstance(c[0], Token) and c[0].type == 'RULE' and c[0].value in self.names:
  305. return self.names[c[0].value]
  306. return self.__default__('value', c, None)
  307. class ApplyTemplates(Transformer_InPlace):
  308. " Apply the templates, creating new rules that represent the used templates "
  309. def __init__(self, temp_defs, rule_defs):
  310. super(ApplyTemplates, self).__init__()
  311. self.temp_defs = temp_defs
  312. self.rule_defs = rule_defs
  313. self.replacer = _ReplaceSymbols()
  314. self.created_templates = set()
  315. def _get_template_name(self, name, args):
  316. return "_%s{%s}" % (name, ",".join(a.name for a in args))
  317. def template_usage(self, c):
  318. name = c[0]
  319. args = c[1:]
  320. result_name = self._get_template_name(name.value, args)
  321. if result_name not in self.created_templates:
  322. self.created_templates.add(result_name)
  323. (_n, params, tree, options) ,= (t for t in self.temp_defs if t[0] == name)
  324. assert len(params) == len(args), args
  325. result_tree = deepcopy(tree)
  326. self.replacer.names = dict(zip(params, args))
  327. self.replacer.transform(result_tree)
  328. self.rule_defs.append((result_name, result_tree, deepcopy(options)))
  329. return NonTerminal(result_name)
  330. def _rfind(s, choices):
  331. return max(s.rfind(c) for c in choices)
  332. def _literal_to_pattern(literal):
  333. v = literal.value
  334. flag_start = _rfind(v, '/"')+1
  335. assert flag_start > 0
  336. flags = v[flag_start:]
  337. assert all(f in _RE_FLAGS for f in flags), flags
  338. v = v[:flag_start]
  339. assert v[0] == v[-1] and v[0] in '"/'
  340. x = v[1:-1]
  341. s = eval_escaping(x)
  342. if literal.type == 'STRING':
  343. s = s.replace('\\\\', '\\')
  344. return { 'STRING': PatternStr,
  345. 'REGEXP': PatternRE }[literal.type](s, flags)
  346. @inline_args
  347. class PrepareLiterals(Transformer_InPlace):
  348. def literal(self, literal):
  349. return ST('pattern', [_literal_to_pattern(literal)])
  350. def range(self, start, end):
  351. assert start.type == end.type == 'STRING'
  352. start = start.value[1:-1]
  353. end = end.value[1:-1]
  354. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1, (start, end, len(eval_escaping(start)), len(eval_escaping(end)))
  355. regexp = '[%s-%s]' % (start, end)
  356. return ST('pattern', [PatternRE(regexp)])
  357. class TerminalTreeToPattern(Transformer):
  358. def pattern(self, ps):
  359. p ,= ps
  360. return p
  361. def expansion(self, items):
  362. assert items
  363. if len(items) == 1:
  364. return items[0]
  365. if len({i.flags for i in items}) > 1:
  366. raise GrammarError("Lark doesn't support joining terminals with conflicting flags!")
  367. return PatternRE(''.join(i.to_regexp() for i in items), items[0].flags if items else ())
  368. def expansions(self, exps):
  369. if len(exps) == 1:
  370. return exps[0]
  371. if len({i.flags for i in exps}) > 1:
  372. raise GrammarError("Lark doesn't support joining terminals with conflicting flags!")
  373. return PatternRE('(?:%s)' % ('|'.join(i.to_regexp() for i in exps)), exps[0].flags)
  374. def expr(self, args):
  375. inner, op = args[:2]
  376. if op == '~':
  377. if len(args) == 3:
  378. op = "{%d}" % int(args[2])
  379. else:
  380. mn, mx = map(int, args[2:])
  381. if mx < mn:
  382. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  383. op = "{%d,%d}" % (mn, mx)
  384. else:
  385. assert len(args) == 2
  386. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  387. def maybe(self, expr):
  388. return self.expr(expr + ['?'])
  389. def alias(self, t):
  390. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  391. def value(self, v):
  392. return v[0]
  393. class PrepareSymbols(Transformer_InPlace):
  394. def value(self, v):
  395. v ,= v
  396. if isinstance(v, Tree):
  397. return v
  398. elif v.type == 'RULE':
  399. return NonTerminal(Str(v.value))
  400. elif v.type == 'TERMINAL':
  401. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  402. assert False
  403. def _choice_of_rules(rules):
  404. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  405. class Grammar:
  406. def __init__(self, rule_defs, term_defs, temp_defs, ignore):
  407. self.term_defs = term_defs
  408. self.rule_defs = rule_defs
  409. self.temp_defs = temp_defs
  410. self.ignore = ignore
  411. def compile(self, start):
  412. # We change the trees in-place (to support huge grammars)
  413. # So deepcopy allows calling compile more than once.
  414. term_defs = deepcopy(list(self.term_defs))
  415. rule_defs = deepcopy(self.rule_defs)
  416. temp_defs = deepcopy(self.temp_defs)
  417. # ===================
  418. # Compile Terminals
  419. # ===================
  420. # Convert terminal-trees to strings/regexps
  421. for name, (term_tree, priority) in term_defs:
  422. if term_tree is None: # Terminal added through %declare
  423. continue
  424. expansions = list(term_tree.find_data('expansion'))
  425. if len(expansions) == 1 and not expansions[0].children:
  426. raise GrammarError("Terminals cannot be empty (%s)" % name)
  427. transformer = PrepareLiterals() * TerminalTreeToPattern()
  428. terminals = [TerminalDef(name, transformer.transform( term_tree ), priority)
  429. for name, (term_tree, priority) in term_defs if term_tree]
  430. # =================
  431. # Compile Rules
  432. # =================
  433. # 1. Pre-process terminals
  434. transformer = PrepareLiterals() * PrepareSymbols() * PrepareAnonTerminals(terminals) # Adds to terminals
  435. # 2. Inline Templates
  436. transformer *= ApplyTemplates(temp_defs, rule_defs)
  437. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  438. ebnf_to_bnf = EBNF_to_BNF()
  439. rules = []
  440. i = 0
  441. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  442. name, rule_tree, options = rule_defs[i]
  443. ebnf_to_bnf.rule_options = RuleOptions(keep_all_tokens=True) if options.keep_all_tokens else None
  444. ebnf_to_bnf.prefix = name
  445. tree = transformer.transform(rule_tree)
  446. res = ebnf_to_bnf.transform(tree)
  447. rules.append((name, res, options))
  448. i += 1
  449. rules += ebnf_to_bnf.new_rules
  450. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  451. # 4. Compile tree to Rule objects
  452. rule_tree_to_text = RuleTreeToText()
  453. simplify_rule = SimplifyRule_Visitor()
  454. compiled_rules = []
  455. for rule_content in rules:
  456. name, tree, options = rule_content
  457. simplify_rule.visit(tree)
  458. expansions = rule_tree_to_text.transform(tree)
  459. for i, (expansion, alias) in enumerate(expansions):
  460. if alias and name.startswith('_'):
  461. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)" % (name, alias))
  462. empty_indices = [x==_EMPTY for x in expansion]
  463. if any(empty_indices):
  464. exp_options = copy(options) or RuleOptions()
  465. exp_options.empty_indices = empty_indices
  466. expansion = [x for x in expansion if x!=_EMPTY]
  467. else:
  468. exp_options = options
  469. assert all(isinstance(x, Symbol) for x in expansion), expansion
  470. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  471. compiled_rules.append(rule)
  472. # Remove duplicates of empty rules, throw error for non-empty duplicates
  473. if len(set(compiled_rules)) != len(compiled_rules):
  474. duplicates = classify(compiled_rules, lambda x: x)
  475. for dups in duplicates.values():
  476. if len(dups) > 1:
  477. if dups[0].expansion:
  478. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  479. % ''.join('\n * %s' % i for i in dups))
  480. # Empty rule; assert all other attributes are equal
  481. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  482. # Remove duplicates
  483. compiled_rules = list(set(compiled_rules))
  484. # Filter out unused rules
  485. while True:
  486. c = len(compiled_rules)
  487. used_rules = {s for r in compiled_rules
  488. for s in r.expansion
  489. if isinstance(s, NonTerminal)
  490. and s != r.origin}
  491. used_rules |= {NonTerminal(s) for s in start}
  492. compiled_rules = [r for r in compiled_rules if r.origin in used_rules]
  493. if len(compiled_rules) == c:
  494. break
  495. # Filter out unused terminals
  496. used_terms = {t.name for r in compiled_rules
  497. for t in r.expansion
  498. if isinstance(t, Terminal)}
  499. terminals = [t for t in terminals if t.name in used_terms or t.name in self.ignore]
  500. return terminals, compiled_rules, self.ignore
  501. _imported_grammars = {}
  502. def import_grammar(grammar_path, base_paths=[]):
  503. if grammar_path not in _imported_grammars:
  504. import_paths = base_paths + IMPORT_PATHS
  505. for import_path in import_paths:
  506. with suppress(IOError):
  507. joined_path = os.path.join(import_path, grammar_path)
  508. with open(joined_path, encoding='utf8') as f:
  509. text = f.read()
  510. grammar = load_grammar(text, joined_path)
  511. _imported_grammars[grammar_path] = grammar
  512. break
  513. else:
  514. open(grammar_path, encoding='utf8')
  515. assert False
  516. return _imported_grammars[grammar_path]
  517. def import_from_grammar_into_namespace(grammar, namespace, aliases):
  518. """Returns all rules and terminals of grammar, prepended
  519. with a 'namespace' prefix, except for those which are aliased.
  520. """
  521. imported_terms = dict(grammar.term_defs)
  522. imported_rules = {n:(n,deepcopy(t),o) for n,t,o in grammar.rule_defs}
  523. imported_temps = {n:(n,p,deepcopy(t),o) for n,p,t,o in grammar.temp_defs}
  524. term_defs = []
  525. rule_defs = []
  526. temp_defs = []
  527. def rule_dependencies(symbol):
  528. if symbol.type != 'RULE':
  529. return []
  530. if symbol in imported_rules:
  531. return _find_used_symbols(imported_rules[symbol][1])
  532. elif symbol in imported_temps:
  533. return _find_used_symbols(imported_temps[symbol][2]) - set(imported_temps[symbol][1])
  534. else:
  535. raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace))
  536. def get_namespace_name(name):
  537. try:
  538. return aliases[name].value
  539. except KeyError:
  540. if name[0] == '_':
  541. return '_%s__%s' % (namespace, name[1:])
  542. return '%s__%s' % (namespace, name)
  543. to_import = list(bfs(aliases, rule_dependencies))
  544. for symbol in to_import:
  545. if symbol.type == 'TERMINAL':
  546. term_defs.append([get_namespace_name(symbol), imported_terms[symbol]])
  547. else:
  548. assert symbol.type == 'RULE'
  549. if symbol in imported_rules:
  550. rule = imported_rules[symbol]
  551. for t in rule[1].iter_subtrees():
  552. for i, c in enumerate(t.children):
  553. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  554. t.children[i] = Token(c.type, get_namespace_name(c))
  555. rule_defs.append((get_namespace_name(symbol), rule[1], rule[2]))
  556. else:
  557. temp = imported_temps[symbol]
  558. for t in temp[2].iter_subtrees():
  559. for i, c in enumerate(t.children):
  560. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  561. t.children[i] = Token(c.type, get_namespace_name(c))
  562. params = [('%s__%s' if p[0]!='_' else '_%s__%s' ) % (namespace, p) for p in temp[1]]
  563. temp_defs.append((get_namespace_name(symbol), params, temp[2], temp[3]))
  564. return term_defs, rule_defs, temp_defs
  565. def resolve_term_references(term_defs):
  566. # TODO Solve with transitive closure (maybe)
  567. term_dict = {k:t for k, (t,_p) in term_defs}
  568. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  569. while True:
  570. changed = False
  571. for name, (token_tree, _p) in term_defs:
  572. if token_tree is None: # Terminal added through %declare
  573. continue
  574. for exp in token_tree.find_data('value'):
  575. item ,= exp.children
  576. if isinstance(item, Token):
  577. if item.type == 'RULE':
  578. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  579. if item.type == 'TERMINAL':
  580. term_value = term_dict[item]
  581. assert term_value is not None
  582. exp.children[0] = term_value
  583. changed = True
  584. if not changed:
  585. break
  586. for name, term in term_dict.items():
  587. if term: # Not just declared
  588. for child in term.children:
  589. ids = [id(x) for x in child.iter_subtrees()]
  590. if id(term) in ids:
  591. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  592. def options_from_rule(name, *x):
  593. if len(x) > 1:
  594. priority, expansions = x
  595. priority = int(priority)
  596. else:
  597. expansions ,= x
  598. priority = None
  599. keep_all_tokens = name.startswith('!')
  600. name = name.lstrip('!')
  601. expand1 = name.startswith('?')
  602. name = name.lstrip('?')
  603. return name, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority)
  604. def options_from_template(name, params, *x):
  605. if len(x) > 1:
  606. priority, expansions = x
  607. priority = int(priority)
  608. else:
  609. expansions ,= x
  610. priority = None
  611. params = [t.value for t in params.children]
  612. keep_all_tokens = name.startswith('!')
  613. name = name.lstrip('!')
  614. expand1 = name.startswith('?')
  615. name = name.lstrip('?')
  616. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority)
  617. def symbols_from_strcase(expansion):
  618. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  619. @inline_args
  620. class PrepareGrammar(Transformer_InPlace):
  621. def terminal(self, name):
  622. return name
  623. def nonterminal(self, name):
  624. return name
  625. def _find_used_symbols(tree):
  626. assert tree.data == 'expansions'
  627. return {t for x in tree.find_data('expansion')
  628. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  629. class GrammarLoader:
  630. def __init__(self):
  631. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  632. rules = [options_from_rule(name, x) for name, x in RULES.items()]
  633. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o) for r, xs, o in rules for i, x in enumerate(xs)]
  634. callback = ParseTreeBuilder(rules, ST).create_callback()
  635. lexer_conf = LexerConf(terminals, ['WS', 'COMMENT'])
  636. parser_conf = ParserConf(rules, callback, ['start'])
  637. self.parser = LALR_TraditionalLexer(lexer_conf, parser_conf)
  638. self.canonize_tree = CanonizeTree()
  639. def load_grammar(self, grammar_text, grammar_name='<?>'):
  640. "Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
  641. try:
  642. tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
  643. except UnexpectedCharacters as e:
  644. context = e.get_context(grammar_text)
  645. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  646. (e.line, e.column, grammar_name, context))
  647. except UnexpectedToken as e:
  648. context = e.get_context(grammar_text)
  649. error = e.match_examples(self.parser.parse, {
  650. 'Unclosed parenthesis': ['a: (\n'],
  651. 'Umatched closing parenthesis': ['a: )\n', 'a: [)\n', 'a: (]\n'],
  652. 'Expecting rule or terminal definition (missing colon)': ['a\n', 'a->\n', 'A->\n', 'a A\n'],
  653. 'Alias expects lowercase name': ['a: -> "a"\n'],
  654. 'Unexpected colon': ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n'],
  655. 'Misplaced operator': ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n'],
  656. 'Expecting option ("|") or a new rule or terminal definition': ['a:a\n()\n'],
  657. '%import expects a name': ['%import "a"\n'],
  658. '%ignore expects a value': ['%ignore %import\n'],
  659. })
  660. if error:
  661. raise GrammarError("%s at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  662. elif 'STRING' in e.expected:
  663. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  664. raise
  665. tree = PrepareGrammar().transform(tree)
  666. # Extract grammar items
  667. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  668. term_defs = defs.pop('term', [])
  669. rule_defs = defs.pop('rule', [])
  670. temp_defs = defs.pop('template', [])
  671. statements = defs.pop('statement', [])
  672. assert not defs
  673. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  674. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  675. rule_defs = [options_from_rule(*x) for x in rule_defs]
  676. temp_defs = [options_from_template(*x) for x in temp_defs]
  677. # Execute statements
  678. ignore, imports = [], {}
  679. for (stmt,) in statements:
  680. if stmt.data == 'ignore':
  681. t ,= stmt.children
  682. ignore.append(t)
  683. elif stmt.data == 'import':
  684. if len(stmt.children) > 1:
  685. path_node, arg1 = stmt.children
  686. else:
  687. path_node, = stmt.children
  688. arg1 = None
  689. if isinstance(arg1, Tree): # Multi import
  690. dotted_path = tuple(path_node.children)
  691. names = arg1.children
  692. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  693. else: # Single import
  694. dotted_path = tuple(path_node.children[:-1])
  695. name = path_node.children[-1] # Get name from dotted path
  696. aliases = {name: arg1 or name} # Aliases if exist
  697. if path_node.data == 'import_lib': # Import from library
  698. base_paths = []
  699. else: # Relative import
  700. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  701. try:
  702. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  703. except AttributeError:
  704. base_file = None
  705. else:
  706. base_file = grammar_name # Import relative to grammar file path if external grammar file
  707. if base_file:
  708. base_paths = [os.path.split(base_file)[0]]
  709. else:
  710. base_paths = [os.path.abspath(os.path.curdir)]
  711. try:
  712. import_base_paths, import_aliases = imports[dotted_path]
  713. assert base_paths == import_base_paths, 'Inconsistent base_paths for %s.' % '.'.join(dotted_path)
  714. import_aliases.update(aliases)
  715. except KeyError:
  716. imports[dotted_path] = base_paths, aliases
  717. elif stmt.data == 'declare':
  718. for t in stmt.children:
  719. term_defs.append([t.value, (None, None)])
  720. else:
  721. assert False, stmt
  722. # import grammars
  723. for dotted_path, (base_paths, aliases) in imports.items():
  724. grammar_path = os.path.join(*dotted_path) + EXT
  725. g = import_grammar(grammar_path, base_paths=base_paths)
  726. new_td, new_rd, new_tp = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases)
  727. term_defs += new_td
  728. rule_defs += new_rd
  729. temp_defs += new_tp
  730. # Verify correctness 1
  731. for name, _ in term_defs:
  732. if name.startswith('__'):
  733. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  734. # Handle ignore tokens
  735. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  736. # inability to handle duplicate terminals (two names, one value)
  737. ignore_names = []
  738. for t in ignore:
  739. if t.data=='expansions' and len(t.children) == 1:
  740. t2 ,= t.children
  741. if t2.data=='expansion' and len(t2.children) == 1:
  742. item ,= t2.children
  743. if item.data == 'value':
  744. item ,= item.children
  745. if isinstance(item, Token) and item.type == 'TERMINAL':
  746. ignore_names.append(item.value)
  747. continue
  748. name = '__IGNORE_%d'% len(ignore_names)
  749. ignore_names.append(name)
  750. term_defs.append((name, (t, 1)))
  751. # Verify correctness 2
  752. terminal_names = set()
  753. for name, _ in term_defs:
  754. if name in terminal_names:
  755. raise GrammarError("Terminal '%s' defined more than once" % name)
  756. terminal_names.add(name)
  757. if set(ignore_names) > terminal_names:
  758. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names))
  759. resolve_term_references(term_defs)
  760. rules = rule_defs
  761. rule_names = set()
  762. for name, _x, _o in rules:
  763. if name.startswith('__'):
  764. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  765. if name in rule_names:
  766. raise GrammarError("Rule '%s' defined more than once" % name)
  767. rule_names.add(name)
  768. temp_names = set()
  769. for name, _p, _x, _o in temp_defs:
  770. if name.startswith('__'):
  771. raise GrammarError('Names starting with double-underscore are reserved (Error at %s (template))' % name)
  772. if name.startswith('_'): # TODO: rethink this decision (not the error msg)
  773. raise GrammarError('Templates are always inline, they should not start with a underscore (Error ar %s)' % name)
  774. if name in temp_names:
  775. raise GrammarError("Template '%s' defined more than once" % name)
  776. temp_names.add(name)
  777. if name in rule_names:
  778. raise GrammarError("Template '%s' conflicts with rule of same name" % name)
  779. for name, expansions, _o in rules:
  780. for sym in _find_used_symbols(expansions):
  781. if sym.type == 'TERMINAL':
  782. if sym not in terminal_names:
  783. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  784. else:
  785. if sym not in rule_names and sym not in temp_names: # TODO: check that sym is actually used as template
  786. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  787. for name, params, expansions, _o in temp_defs:
  788. for i, p in enumerate(params):
  789. if p in rule_names:
  790. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  791. if p in temp_names:
  792. raise GrammarError("Template Parameter conflicts with template %s (in template %s)" % (p, name))
  793. if p in params[:i]:
  794. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  795. for sym in _find_used_symbols(expansions):
  796. if sym.type == 'TERMINAL':
  797. if sym not in terminal_names:
  798. raise GrammarError("Token '%s' used but not defined (in template %s)" % (sym, name))
  799. else:
  800. if sym not in rule_names and sym not in temp_names and sym not in params:
  801. raise GrammarError("Rule '%s' used but not defined (in template %s)" % (sym, name))
  802. # TODO: check that sym is actually used as template
  803. # TODO: number of template arguments matches requirement
  804. return Grammar(rules, term_defs, temp_defs, ignore_names)
  805. load_grammar = GrammarLoader().load_grammar