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.

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