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.

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