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.

692 lines
23 KiB

  1. "Parses and creates Grammar objects"
  2. import os.path
  3. from itertools import chain
  4. import re
  5. from ast import literal_eval
  6. from copy import deepcopy
  7. from .lexer import Token, UnexpectedInput
  8. from .parse_tree_builder import ParseTreeBuilder
  9. from .parser_frontends import LALR
  10. from .parsers.lalr_parser import UnexpectedToken
  11. from .common import is_terminal, GrammarError, LexerConf, ParserConf, PatternStr, PatternRE, TokenDef
  12. from .grammar import RuleOptions, Rule, Terminal, NonTerminal, Symbol
  13. from .utils import classify, suppress
  14. from .tree import Tree, Transformer, InlineTransformer, Visitor, SlottedTree as ST
  15. __path__ = os.path.dirname(__file__)
  16. IMPORT_PATHS = [os.path.join(__path__, 'grammars')]
  17. _RE_FLAGS = 'imslux'
  18. _TERMINAL_NAMES = {
  19. '.' : 'DOT',
  20. ',' : 'COMMA',
  21. ':' : 'COLON',
  22. ';' : 'SEMICOLON',
  23. '+' : 'PLUS',
  24. '-' : 'MINUS',
  25. '*' : 'STAR',
  26. '/' : 'SLASH',
  27. '\\' : 'BACKSLASH',
  28. '|' : 'VBAR',
  29. '?' : 'QMARK',
  30. '!' : 'BANG',
  31. '@' : 'AT',
  32. '#' : 'HASH',
  33. '$' : 'DOLLAR',
  34. '%' : 'PERCENT',
  35. '^' : 'CIRCUMFLEX',
  36. '&' : 'AMPERSAND',
  37. '_' : 'UNDERSCORE',
  38. '<' : 'LESSTHAN',
  39. '>' : 'MORETHAN',
  40. '=' : 'EQUAL',
  41. '"' : 'DBLQUOTE',
  42. '\'' : 'QUOTE',
  43. '`' : 'BACKQUOTE',
  44. '~' : 'TILDE',
  45. '(' : 'LPAR',
  46. ')' : 'RPAR',
  47. '{' : 'LBRACE',
  48. '}' : 'RBRACE',
  49. '[' : 'LSQB',
  50. ']' : 'RSQB',
  51. '\n' : 'NEWLINE',
  52. '\r\n' : 'CRLF',
  53. '\t' : 'TAB',
  54. ' ' : 'SPACE',
  55. }
  56. # Grammar Parser
  57. TERMINALS = {
  58. '_LPAR': r'\(',
  59. '_RPAR': r'\)',
  60. '_LBRA': r'\[',
  61. '_RBRA': r'\]',
  62. 'OP': '[+*][?]?|[?](?![a-z])',
  63. '_COLON': ':',
  64. '_OR': r'\|',
  65. '_DOT': r'\.',
  66. 'TILDE': '~',
  67. 'RULE': '!?[_?]?[a-z][_a-z0-9]*',
  68. 'TERMINAL': '_?[A-Z][_A-Z0-9]*',
  69. 'STRING': r'"(\\"|\\\\|[^"\n])*?"i?',
  70. 'REGEXP': r'/(?!/)(\\/|\\\\|[^/\n])*?/[%s]*' % _RE_FLAGS,
  71. '_NL': r'(\r?\n)+\s*',
  72. 'WS': r'[ \t]+',
  73. 'COMMENT': r'//[^\n]*',
  74. '_TO': '->',
  75. '_IGNORE': r'%ignore',
  76. '_DECLARE': r'%declare',
  77. '_IMPORT': r'%import',
  78. 'NUMBER': r'\d+',
  79. }
  80. RULES = {
  81. 'start': ['_list'],
  82. '_list': ['_item', '_list _item'],
  83. '_item': ['rule', 'token', 'statement', '_NL'],
  84. 'rule': ['RULE _COLON expansions _NL',
  85. 'RULE _DOT NUMBER _COLON expansions _NL'],
  86. 'expansions': ['alias',
  87. 'expansions _OR alias',
  88. 'expansions _NL _OR alias'],
  89. '?alias': ['expansion _TO RULE', 'expansion'],
  90. 'expansion': ['_expansion'],
  91. '_expansion': ['', '_expansion expr'],
  92. '?expr': ['atom',
  93. 'atom OP',
  94. 'atom TILDE NUMBER',
  95. 'atom TILDE NUMBER _DOT _DOT NUMBER',
  96. ],
  97. '?atom': ['_LPAR expansions _RPAR',
  98. 'maybe',
  99. 'value'],
  100. 'value': ['terminal',
  101. 'nonterminal',
  102. 'literal',
  103. 'range'],
  104. 'terminal': ['TERMINAL'],
  105. 'nonterminal': ['RULE'],
  106. '?name': ['RULE', 'TERMINAL'],
  107. 'maybe': ['_LBRA expansions _RBRA'],
  108. 'range': ['STRING _DOT _DOT STRING'],
  109. 'token': ['TERMINAL _COLON expansions _NL',
  110. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  111. 'statement': ['ignore', 'import', 'declare'],
  112. 'ignore': ['_IGNORE expansions _NL'],
  113. 'declare': ['_DECLARE _declare_args _NL'],
  114. 'import': ['_IMPORT import_args _NL',
  115. '_IMPORT import_args _TO TERMINAL _NL'],
  116. 'import_args': ['_import_args'],
  117. '_import_args': ['name', '_import_args _DOT name'],
  118. '_declare_args': ['name', '_declare_args name'],
  119. 'literal': ['REGEXP', 'STRING'],
  120. }
  121. class EBNF_to_BNF(InlineTransformer):
  122. def __init__(self):
  123. self.new_rules = []
  124. self.rules_by_expr = {}
  125. self.prefix = 'anon'
  126. self.i = 0
  127. self.rule_options = None
  128. def _add_recurse_rule(self, type_, expr):
  129. if expr in self.rules_by_expr:
  130. return self.rules_by_expr[expr]
  131. new_name = '__%s_%s_%d' % (self.prefix, type_, self.i)
  132. self.i += 1
  133. t = NonTerminal(Token('RULE', new_name, -1))
  134. tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])])
  135. self.new_rules.append((new_name, tree, self.rule_options))
  136. self.rules_by_expr[expr] = t
  137. return t
  138. def expr(self, rule, op, *args):
  139. if op.value == '?':
  140. return ST('expansions', [rule, ST('expansion', [])])
  141. elif op.value == '+':
  142. # a : b c+ d
  143. # -->
  144. # a : b _c d
  145. # _c : _c c | c;
  146. return self._add_recurse_rule('plus', rule)
  147. elif op.value == '*':
  148. # a : b c* d
  149. # -->
  150. # a : b _c? d
  151. # _c : _c c | c;
  152. new_name = self._add_recurse_rule('star', rule)
  153. return ST('expansions', [new_name, ST('expansion', [])])
  154. elif op.value == '~':
  155. if len(args) == 1:
  156. mn = mx = int(args[0])
  157. else:
  158. mn, mx = map(int, args)
  159. if mx < mn:
  160. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  161. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)])
  162. assert False, op
  163. class SimplifyRule_Visitor(Visitor):
  164. @staticmethod
  165. def _flatten(tree):
  166. while True:
  167. to_expand = [i for i, child in enumerate(tree.children)
  168. if isinstance(child, Tree) and child.data == tree.data]
  169. if not to_expand:
  170. break
  171. tree.expand_kids_by_index(*to_expand)
  172. def expansion(self, tree):
  173. # rules_list unpacking
  174. # a : b (c|d) e
  175. # -->
  176. # a : b c e | b d e
  177. #
  178. # In AST terms:
  179. # expansion(b, expansions(c, d), e)
  180. # -->
  181. # expansions( expansion(b, c, e), expansion(b, d, e) )
  182. while True:
  183. self._flatten(tree)
  184. for i, child in enumerate(tree.children):
  185. if isinstance(child, Tree) and child.data == 'expansions':
  186. tree.data = 'expansions'
  187. tree.children = [self.visit(ST('expansion', [option if i==j else other
  188. for j, other in enumerate(tree.children)]))
  189. for option in set(child.children)]
  190. break
  191. else:
  192. break
  193. def alias(self, tree):
  194. rule, alias_name = tree.children
  195. if rule.data == 'expansions':
  196. aliases = []
  197. for child in tree.children[0].children:
  198. aliases.append(ST('alias', [child, alias_name]))
  199. tree.data = 'expansions'
  200. tree.children = aliases
  201. def expansions(self, tree):
  202. self._flatten(tree)
  203. tree.children = list(set(tree.children))
  204. class RuleTreeToText(Transformer):
  205. def expansions(self, x):
  206. return x
  207. def expansion(self, symbols):
  208. return symbols, None
  209. def alias(self, x):
  210. (expansion, _alias), alias = x
  211. assert _alias is None, (alias, expansion, '-', _alias)
  212. return expansion, alias.value
  213. class CanonizeTree(InlineTransformer):
  214. def maybe(self, expr):
  215. return ST('expr', [expr, Token('OP', '?', -1)])
  216. def tokenmods(self, *args):
  217. if len(args) == 1:
  218. return list(args)
  219. tokenmods, value = args
  220. return tokenmods + [value]
  221. class PrepareAnonTerminals(InlineTransformer):
  222. "Create a unique list of anonymous tokens. Attempt to give meaningful names to them when we add them"
  223. def __init__(self, tokens):
  224. self.tokens = tokens
  225. self.token_set = {td.name for td in self.tokens}
  226. self.token_reverse = {td.pattern: td for td in tokens}
  227. self.i = 0
  228. def pattern(self, p):
  229. value = p.value
  230. if p in self.token_reverse and p.flags != self.token_reverse[p].pattern.flags:
  231. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  232. token_name = None
  233. if isinstance(p, PatternStr):
  234. try:
  235. # If already defined, use the user-defined token name
  236. token_name = self.token_reverse[p].name
  237. except KeyError:
  238. # Try to assign an indicative anon-token name
  239. try:
  240. token_name = _TERMINAL_NAMES[value]
  241. except KeyError:
  242. if value.isalnum() and value[0].isalpha() and value.upper() not in self.token_set:
  243. with suppress(UnicodeEncodeError):
  244. value.upper().encode('ascii') # Make sure we don't have unicode in our token names
  245. token_name = value.upper()
  246. elif isinstance(p, PatternRE):
  247. if p in self.token_reverse: # Kind of a wierd placement.name
  248. token_name = self.token_reverse[p].name
  249. else:
  250. assert False, p
  251. if token_name is None:
  252. token_name = '__ANON_%d' % self.i
  253. self.i += 1
  254. if token_name not in self.token_set:
  255. assert p not in self.token_reverse
  256. self.token_set.add(token_name)
  257. tokendef = TokenDef(token_name, p)
  258. self.token_reverse[p] = tokendef
  259. self.tokens.append(tokendef)
  260. return Terminal(Token('TERMINAL', token_name, -1), filter_out=isinstance(p, PatternStr))
  261. def _rfind(s, choices):
  262. return max(s.rfind(c) for c in choices)
  263. def _fix_escaping(s):
  264. w = ''
  265. i = iter(s)
  266. for n in i:
  267. w += n
  268. if n == '\\':
  269. n2 = next(i)
  270. if n2 == '\\':
  271. w += '\\\\'
  272. elif n2 not in 'unftr':
  273. w += '\\'
  274. w += n2
  275. w = w.replace('\\"', '"').replace("'", "\\'")
  276. to_eval = "u'''%s'''" % w
  277. try:
  278. s = literal_eval(to_eval)
  279. except SyntaxError as e:
  280. raise ValueError(s, e)
  281. return s
  282. def _literal_to_pattern(literal):
  283. v = literal.value
  284. flag_start = _rfind(v, '/"')+1
  285. assert flag_start > 0
  286. flags = v[flag_start:]
  287. assert all(f in _RE_FLAGS for f in flags), flags
  288. v = v[:flag_start]
  289. assert v[0] == v[-1] and v[0] in '"/'
  290. x = v[1:-1]
  291. s = _fix_escaping(x)
  292. if literal.type == 'STRING':
  293. s = s.replace('\\\\', '\\')
  294. return { 'STRING': PatternStr,
  295. 'REGEXP': PatternRE }[literal.type](s, flags)
  296. class PrepareLiterals(InlineTransformer):
  297. def literal(self, literal):
  298. return ST('pattern', [_literal_to_pattern(literal)])
  299. def range(self, start, end):
  300. assert start.type == end.type == 'STRING'
  301. start = start.value[1:-1]
  302. end = end.value[1:-1]
  303. assert len(start) == len(end) == 1, (start, end, len(start), len(end))
  304. regexp = '[%s-%s]' % (start, end)
  305. return ST('pattern', [PatternRE(regexp)])
  306. class TokenTreeToPattern(Transformer):
  307. def pattern(self, ps):
  308. p ,= ps
  309. return p
  310. def expansion(self, items):
  311. assert items
  312. if len(items) == 1:
  313. return items[0]
  314. if len({i.flags for i in items}) > 1:
  315. raise GrammarError("Lark doesn't support joining tokens with conflicting flags!")
  316. return PatternRE(''.join(i.to_regexp() for i in items), items[0].flags if items else ())
  317. def expansions(self, exps):
  318. if len(exps) == 1:
  319. return exps[0]
  320. if len({i.flags for i in exps}) > 1:
  321. raise GrammarError("Lark doesn't support joining tokens with conflicting flags!")
  322. return PatternRE('(?:%s)' % ('|'.join(i.to_regexp() for i in exps)), exps[0].flags)
  323. def expr(self, args):
  324. inner, op = args[:2]
  325. if op == '~':
  326. if len(args) == 3:
  327. op = "{%d}" % int(args[2])
  328. else:
  329. mn, mx = map(int, args[2:])
  330. if mx < mn:
  331. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  332. op = "{%d,%d}" % (mn, mx)
  333. else:
  334. assert len(args) == 2
  335. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  336. def alias(self, t):
  337. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  338. def value(self, v):
  339. return v[0]
  340. class PrepareSymbols(Transformer):
  341. def value(self, v):
  342. v ,= v
  343. if isinstance(v, Tree):
  344. return v
  345. elif v.type == 'RULE':
  346. return NonTerminal(v.value)
  347. elif v.type == 'TERMINAL':
  348. return Terminal(v.value, filter_out=v.startswith('_'))
  349. assert False
  350. def _choice_of_rules(rules):
  351. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  352. class Grammar:
  353. def __init__(self, rule_defs, token_defs, ignore):
  354. self.token_defs = token_defs
  355. self.rule_defs = rule_defs
  356. self.ignore = ignore
  357. def compile(self):
  358. token_defs = list(self.token_defs)
  359. rule_defs = self.rule_defs
  360. # =================
  361. # Compile Tokens
  362. # =================
  363. # Convert token-trees to strings/regexps
  364. transformer = PrepareLiterals() * TokenTreeToPattern()
  365. for name, (token_tree, priority) in token_defs:
  366. if token_tree is None: # Terminal added through %declare
  367. continue
  368. expansions = list(token_tree.find_data('expansion'))
  369. if len(expansions) == 1 and not expansions[0].children:
  370. raise GrammarError("Terminals cannot be empty (%s)" % name)
  371. tokens = [TokenDef(name, transformer.transform(token_tree), priority)
  372. for name, (token_tree, priority) in token_defs if token_tree]
  373. # =================
  374. # Compile Rules
  375. # =================
  376. # 1. Pre-process terminals
  377. transformer = PrepareLiterals() * PrepareSymbols() * PrepareAnonTerminals(tokens) # Adds to tokens
  378. # 2. Convert EBNF to BNF (and apply step 1)
  379. ebnf_to_bnf = EBNF_to_BNF()
  380. rules = []
  381. for name, rule_tree, options in rule_defs:
  382. ebnf_to_bnf.rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  383. tree = transformer.transform(rule_tree)
  384. rules.append((name, ebnf_to_bnf.transform(tree), options))
  385. rules += ebnf_to_bnf.new_rules
  386. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  387. # 3. Compile tree to Rule objects
  388. rule_tree_to_text = RuleTreeToText()
  389. simplify_rule = SimplifyRule_Visitor()
  390. compiled_rules = []
  391. for name, tree, options in rules:
  392. simplify_rule.visit(tree)
  393. expansions = rule_tree_to_text.transform(tree)
  394. for expansion, alias in expansions:
  395. if alias and name.startswith('_'):
  396. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)" % (name, alias))
  397. assert all(isinstance(x, Symbol) for x in expansion), expansion
  398. rule = Rule(NonTerminal(name), expansion, alias, options)
  399. compiled_rules.append(rule)
  400. return tokens, compiled_rules, self.ignore
  401. _imported_grammars = {}
  402. def import_grammar(grammar_path):
  403. if grammar_path not in _imported_grammars:
  404. for import_path in IMPORT_PATHS:
  405. with open(os.path.join(import_path, grammar_path)) as f:
  406. text = f.read()
  407. grammar = load_grammar(text, grammar_path)
  408. _imported_grammars[grammar_path] = grammar
  409. return _imported_grammars[grammar_path]
  410. def resolve_token_references(token_defs):
  411. # TODO Cycles detection
  412. # TODO Solve with transitive closure (maybe)
  413. token_dict = {k:t for k, (t,_p) in token_defs}
  414. assert len(token_dict) == len(token_defs), "Same name defined twice?"
  415. while True:
  416. changed = False
  417. for name, (token_tree, _p) in token_defs:
  418. if token_tree is None: # Terminal added through %declare
  419. continue
  420. for exp in token_tree.find_data('value'):
  421. item ,= exp.children
  422. if isinstance(item, Token):
  423. if item.type == 'RULE':
  424. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  425. if item.type == 'TERMINAL':
  426. exp.children[0] = token_dict[item]
  427. changed = True
  428. if not changed:
  429. break
  430. def options_from_rule(name, *x):
  431. if len(x) > 1:
  432. priority, expansions = x
  433. priority = int(priority)
  434. else:
  435. expansions ,= x
  436. priority = None
  437. keep_all_tokens = name.startswith('!')
  438. name = name.lstrip('!')
  439. expand1 = name.startswith('?')
  440. name = name.lstrip('?')
  441. return name, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority)
  442. def symbols_from_strcase(expansion):
  443. return [Terminal(x, filter_out=x.startswith('_')) if is_terminal(x) else NonTerminal(x) for x in expansion]
  444. class PrepareGrammar(InlineTransformer):
  445. def terminal(self, name):
  446. return name
  447. def nonterminal(self, name):
  448. return name
  449. class GrammarLoader:
  450. def __init__(self):
  451. tokens = [TokenDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  452. rules = [options_from_rule(name, x) for name, x in RULES.items()]
  453. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), None, o) for r, xs, o in rules for x in xs]
  454. callback = ParseTreeBuilder(rules, ST).create_callback()
  455. lexer_conf = LexerConf(tokens, ['WS', 'COMMENT'])
  456. parser_conf = ParserConf(rules, callback, 'start')
  457. self.parser = LALR(lexer_conf, parser_conf)
  458. self.canonize_tree = CanonizeTree()
  459. def load_grammar(self, grammar_text, name='<?>'):
  460. "Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
  461. try:
  462. tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
  463. except UnexpectedInput as e:
  464. raise GrammarError("Unexpected input %r at line %d column %d in %s" % (e.context, e.line, e.column, name))
  465. except UnexpectedToken as e:
  466. context = e.get_context(grammar_text)
  467. error = e.match_examples(self.parser.parse, {
  468. 'Unclosed parenthesis': ['a: (\n'],
  469. 'Umatched closing parenthesis': ['a: )\n', 'a: [)\n', 'a: (]\n'],
  470. 'Expecting rule or token definition (missing colon)': ['a\n', 'a->\n', 'A->\n', 'a A\n'],
  471. 'Alias expects lowercase name': ['a: -> "a"\n'],
  472. 'Unexpected colon': ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n'],
  473. 'Misplaced operator': ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n'],
  474. 'Expecting option ("|") or a new rule or token definition': ['a:a\n()\n'],
  475. '%import expects a name': ['%import "a"\n'],
  476. '%ignore expects a value': ['%ignore %import\n'],
  477. })
  478. if error:
  479. raise GrammarError("%s at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  480. elif 'STRING' in e.expected:
  481. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  482. raise
  483. tree = PrepareGrammar().transform(tree)
  484. # Extract grammar items
  485. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  486. token_defs = defs.pop('token', [])
  487. rule_defs = defs.pop('rule', [])
  488. statements = defs.pop('statement', [])
  489. assert not defs
  490. token_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in token_defs]
  491. token_defs = [(name.value, (t, int(p))) for name, p, t in token_defs]
  492. # Execute statements
  493. ignore = []
  494. declared = []
  495. for (stmt,) in statements:
  496. if stmt.data == 'ignore':
  497. t ,= stmt.children
  498. ignore.append(t)
  499. elif stmt.data == 'import':
  500. dotted_path = stmt.children[0].children
  501. name = stmt.children[1] if len(stmt.children)>1 else dotted_path[-1]
  502. grammar_path = os.path.join(*dotted_path[:-1]) + '.lark'
  503. g = import_grammar(grammar_path)
  504. token_options = dict(g.token_defs)[dotted_path[-1]]
  505. assert isinstance(token_options, tuple) and len(token_options)==2
  506. token_defs.append([name.value, token_options])
  507. elif stmt.data == 'declare':
  508. for t in stmt.children:
  509. token_defs.append([t.value, (None, None)])
  510. else:
  511. assert False, stmt
  512. # Verify correctness 1
  513. for name, _ in token_defs:
  514. if name.startswith('__'):
  515. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  516. # Handle ignore tokens
  517. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  518. # inability to handle duplicate tokens (two names, one value)
  519. ignore_names = []
  520. for t in ignore:
  521. if t.data=='expansions' and len(t.children) == 1:
  522. t2 ,= t.children
  523. if t2.data=='expansion' and len(t2.children) == 1:
  524. item ,= t2.children
  525. if item.data == 'value':
  526. item ,= item.children
  527. if isinstance(item, Token) and item.type == 'TERMINAL':
  528. ignore_names.append(item.value)
  529. continue
  530. name = '__IGNORE_%d'% len(ignore_names)
  531. ignore_names.append(name)
  532. token_defs.append((name, (t, 0)))
  533. # Verify correctness 2
  534. token_names = set()
  535. for name, _ in token_defs:
  536. if name in token_names:
  537. raise GrammarError("Token '%s' defined more than once" % name)
  538. token_names.add(name)
  539. if set(ignore_names) > token_names:
  540. raise GrammarError("Tokens %s were marked to ignore but were not defined!" % (set(ignore_names) - token_names))
  541. # Resolve token references
  542. resolve_token_references(token_defs)
  543. rules = [options_from_rule(*x) for x in rule_defs]
  544. rule_names = set()
  545. for name, _x, _o in rules:
  546. if name.startswith('__'):
  547. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  548. if name in rule_names:
  549. raise GrammarError("Rule '%s' defined more than once" % name)
  550. rule_names.add(name)
  551. for name, expansions, _o in rules:
  552. used_symbols = {t for x in expansions.find_data('expansion')
  553. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  554. for sym in used_symbols:
  555. if is_terminal(sym):
  556. if sym not in token_names:
  557. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  558. else:
  559. if sym not in rule_names:
  560. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  561. # TODO don't include unused tokens, they can only cause trouble!
  562. return Grammar(rules, token_defs, ignore_names)
  563. load_grammar = GrammarLoader().load_grammar