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.

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