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.

703 lines
24 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
  13. from .tree import Tree, SlottedTree as ST
  14. from .transformers import Transformer, Transformer_Children, Transformer_ChildrenInline, Visitor
  15. __path__ = os.path.dirname(__file__)
  16. IMPORT_PATHS = [os.path.join(__path__, 'grammars')]
  17. _RE_FLAGS = 'imslux'
  18. _TOKEN_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. TOKENS = {
  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. 'TOKEN': '_?[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. '_IMPORT': r'%import',
  77. 'NUMBER': r'\d+',
  78. }
  79. RULES = {
  80. 'start': ['_list'],
  81. '_list': ['_item', '_list _item'],
  82. '_item': ['rule', 'token', 'statement', '_NL'],
  83. 'rule': ['RULE _COLON expansions _NL',
  84. 'RULE _DOT NUMBER _COLON expansions _NL'],
  85. 'expansions': ['alias',
  86. 'expansions _OR alias',
  87. 'expansions _NL _OR alias'],
  88. '?alias': ['expansion _TO RULE', 'expansion'],
  89. 'expansion': ['_expansion'],
  90. '_expansion': ['', '_expansion expr'],
  91. '?expr': ['atom',
  92. 'atom OP',
  93. 'atom TILDE NUMBER',
  94. 'atom TILDE NUMBER _DOT _DOT NUMBER',
  95. ],
  96. '?atom': ['_LPAR expansions _RPAR',
  97. 'maybe',
  98. 'name',
  99. 'literal',
  100. 'range'],
  101. '?name': ['RULE', 'TOKEN'],
  102. 'maybe': ['_LBRA expansions _RBRA'],
  103. 'range': ['STRING _DOT _DOT STRING'],
  104. 'token': ['TOKEN _COLON expansions _NL',
  105. 'TOKEN _DOT NUMBER _COLON expansions _NL'],
  106. 'statement': ['ignore', 'import'],
  107. 'ignore': ['_IGNORE expansions _NL'],
  108. 'import': ['_IMPORT import_args _NL',
  109. '_IMPORT import_args _TO TOKEN'],
  110. 'import_args': ['_import_args'],
  111. '_import_args': ['name', '_import_args _DOT name'],
  112. 'literal': ['REGEXP', 'STRING'],
  113. }
  114. class EBNF_to_BNF(Transformer_ChildrenInline):
  115. def __init__(self):
  116. self.new_rules = []
  117. self.rules_by_expr = {}
  118. self.prefix = 'anon'
  119. self.i = 0
  120. self.rule_options = None
  121. def _add_recurse_rule(self, type_, expr):
  122. if expr in self.rules_by_expr:
  123. return self.rules_by_expr[expr]
  124. new_name = '__%s_%s_%d' % (self.prefix, type_, self.i)
  125. self.i += 1
  126. t = Token('RULE', new_name, -1)
  127. tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])])
  128. self.new_rules.append((new_name, tree, self.rule_options))
  129. self.rules_by_expr[expr] = t
  130. return t
  131. def expr(self, rule, op, *args):
  132. if op.value == '?':
  133. return ST('expansions', [rule, ST('expansion', [])])
  134. elif op.value == '+':
  135. # a : b c+ d
  136. # -->
  137. # a : b _c d
  138. # _c : _c c | c;
  139. return self._add_recurse_rule('plus', rule)
  140. elif op.value == '*':
  141. # a : b c* d
  142. # -->
  143. # a : b _c? d
  144. # _c : _c c | c;
  145. new_name = self._add_recurse_rule('star', rule)
  146. return ST('expansions', [new_name, ST('expansion', [])])
  147. elif op.value == '~':
  148. if len(args) == 1:
  149. mn = mx = int(args[0])
  150. else:
  151. mn, mx = map(int, args)
  152. if mx < mn:
  153. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  154. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)])
  155. assert False, op
  156. class SimplifyRule_Visitor(Visitor):
  157. @staticmethod
  158. def _flatten(tree):
  159. while True:
  160. to_expand = [i for i, child in enumerate(tree.children)
  161. if isinstance(child, Tree) and child.data == tree.data]
  162. if not to_expand:
  163. break
  164. tree.expand_kids_by_index(*to_expand)
  165. def expansion(self, tree):
  166. # rules_list unpacking
  167. # a : b (c|d) e
  168. # -->
  169. # a : b c e | b d e
  170. #
  171. # In AST terms:
  172. # expansion(b, expansions(c, d), e)
  173. # -->
  174. # expansions( expansion(b, c, e), expansion(b, d, e) )
  175. self._flatten(tree)
  176. for i, child in enumerate(tree.children):
  177. if isinstance(child, Tree) and child.data == 'expansions':
  178. tree.data = 'expansions'
  179. tree.children = [self.visit(ST('expansion', [option if i==j else other
  180. for j, other in enumerate(tree.children)]))
  181. for option in set(child.children)]
  182. break
  183. def alias(self, tree):
  184. rule, alias_name = tree.children
  185. if rule.data == 'expansions':
  186. aliases = []
  187. for child in tree.children[0].children:
  188. aliases.append(ST('alias', [child, alias_name]))
  189. tree.data = 'expansions'
  190. tree.children = aliases
  191. def expansions(self, tree):
  192. self._flatten(tree)
  193. tree.children = list(set(tree.children))
  194. class RuleTreeToText(Transformer_Children):
  195. def expansions(self, x):
  196. return x
  197. def expansion(self, symbols):
  198. return [sym.value for sym in symbols], None
  199. def alias(self, x):
  200. (expansion, _alias), alias = x
  201. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  202. return expansion, alias.value
  203. class CanonizeTree(Transformer_ChildrenInline):
  204. def maybe(self, expr):
  205. return ST('expr', [expr, Token('OP', '?', -1)])
  206. def tokenmods(self, *args):
  207. if len(args) == 1:
  208. return list(args)
  209. tokenmods, value = args
  210. return tokenmods + [value]
  211. class ExtractAnonTokens(Transformer_ChildrenInline):
  212. "Create a unique list of anonymous tokens. Attempt to give meaningful names to them when we add them"
  213. def __init__(self, tokens):
  214. self.tokens = tokens
  215. self.token_set = {td.name for td in self.tokens}
  216. self.token_reverse = {td.pattern: td for td in tokens}
  217. self.i = 0
  218. def pattern(self, p):
  219. value = p.value
  220. if p in self.token_reverse and p.flags != self.token_reverse[p].pattern.flags:
  221. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  222. if isinstance(p, PatternStr):
  223. try:
  224. # If already defined, use the user-defined token name
  225. token_name = self.token_reverse[p].name
  226. except KeyError:
  227. # Try to assign an indicative anon-token name, otherwise use a numbered name
  228. try:
  229. token_name = _TOKEN_NAMES[value]
  230. except KeyError:
  231. if value.isalnum() and value[0].isalpha() and ('__'+value.upper()) not in self.token_set:
  232. token_name = '%s%d' % (value.upper(), self.i)
  233. try:
  234. # Make sure we don't have unicode in our token names
  235. token_name.encode('ascii')
  236. except UnicodeEncodeError:
  237. token_name = 'ANONSTR_%d' % self.i
  238. else:
  239. token_name = 'ANONSTR_%d' % self.i
  240. self.i += 1
  241. token_name = '__' + token_name
  242. elif isinstance(p, PatternRE):
  243. if p in self.token_reverse: # Kind of a wierd placement.name
  244. token_name = self.token_reverse[p].name
  245. else:
  246. token_name = 'ANONRE_%d' % self.i
  247. self.i += 1
  248. else:
  249. assert False, p
  250. if token_name not in self.token_set:
  251. assert p not in self.token_reverse
  252. self.token_set.add(token_name)
  253. tokendef = TokenDef(token_name, p)
  254. self.token_reverse[p] = tokendef
  255. self.tokens.append(tokendef)
  256. return Token('TOKEN', token_name, -1)
  257. def _rfind(s, choices):
  258. return max(s.rfind(c) for c in choices)
  259. def _fix_escaping(s):
  260. w = ''
  261. i = iter(s)
  262. for n in i:
  263. w += n
  264. if n == '\\':
  265. n2 = next(i)
  266. if n2 == '\\':
  267. w += '\\\\'
  268. elif n2 not in 'unftr':
  269. w += '\\'
  270. w += n2
  271. w = w.replace('\\"', '"').replace("'", "\\'")
  272. to_eval = "u'''%s'''" % w
  273. try:
  274. s = literal_eval(to_eval)
  275. except SyntaxError as e:
  276. raise ValueError(s, e)
  277. return s
  278. def _literal_to_pattern(literal):
  279. v = literal.value
  280. flag_start = _rfind(v, '/"')+1
  281. assert flag_start > 0
  282. flags = v[flag_start:]
  283. assert all(f in _RE_FLAGS for f in flags), flags
  284. v = v[:flag_start]
  285. assert v[0] == v[-1] and v[0] in '"/'
  286. x = v[1:-1]
  287. s = _fix_escaping(x)
  288. if v[0] == '"':
  289. s = s.replace('\\\\', '\\')
  290. return { 'STRING': PatternStr,
  291. 'REGEXP': PatternRE }[literal.type](s, flags)
  292. class PrepareLiterals(Transformer_ChildrenInline):
  293. def literal(self, literal):
  294. return ST('pattern', [_literal_to_pattern(literal)])
  295. def range(self, start, end):
  296. assert start.type == end.type == 'STRING'
  297. start = start.value[1:-1]
  298. end = end.value[1:-1]
  299. assert len(start) == len(end) == 1, (start, end, len(start), len(end))
  300. regexp = '[%s-%s]' % (start, end)
  301. return ST('pattern', [PatternRE(regexp)])
  302. class SplitLiterals(Transformer_ChildrenInline):
  303. def pattern(self, p):
  304. if isinstance(p, PatternStr) and len(p.value)>1:
  305. return ST('expansion', [ST('pattern', [PatternStr(ch, flags=p.flags)]) for ch in p.value])
  306. return ST('pattern', [p])
  307. class TokenTreeToPattern(Transformer_Children):
  308. def pattern(self, ps):
  309. p ,= ps
  310. return p
  311. def expansion(self, 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)
  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 _interleave(l, item):
  339. for e in l:
  340. yield e
  341. if isinstance(e, Tree):
  342. if e.data in ('literal', 'range'):
  343. yield item
  344. elif is_terminal(e):
  345. yield item
  346. def _choice_of_rules(rules):
  347. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  348. class Grammar:
  349. def __init__(self, rule_defs, token_defs, ignore):
  350. self.token_defs = token_defs
  351. self.rule_defs = rule_defs
  352. self.ignore = ignore
  353. def _prepare_scanless_grammar(self, start):
  354. # XXX Pretty hacky! There should be a better way to write this method..
  355. rule_defs = deepcopy(self.rule_defs)
  356. term_defs = self.token_defs
  357. # Implement the "%ignore" feature without a lexer..
  358. terms_to_ignore = {name:'__'+name for name in self.ignore}
  359. if terms_to_ignore:
  360. assert set(terms_to_ignore) <= {name for name, _t in term_defs}
  361. term_defs = [(terms_to_ignore.get(name,name),t) for name,t in term_defs]
  362. expr = Token('RULE', '__ignore')
  363. for r, tree, _o in rule_defs:
  364. for exp in tree.find_data('expansion'):
  365. exp.children = list(_interleave(exp.children, expr))
  366. if r == start:
  367. exp.children = [expr] + exp.children
  368. for exp in tree.find_data('expr'):
  369. exp.children[0] = ST('expansion', list(_interleave(exp.children[:1], expr)))
  370. _ignore_tree = ST('expr', [_choice_of_rules(terms_to_ignore.values()), Token('OP', '?')])
  371. rule_defs.append(('__ignore', _ignore_tree, None))
  372. # Convert all tokens to rules
  373. new_terminal_names = {name: '__token_'+name for name, _t in term_defs}
  374. for name, tree, options in rule_defs:
  375. for exp in chain( tree.find_data('expansion'), tree.find_data('expr') ):
  376. for i, sym in enumerate(exp.children):
  377. if sym in new_terminal_names:
  378. exp.children[i] = Token(sym.type, new_terminal_names[sym])
  379. for name, (tree, priority) in term_defs: # TODO transfer priority to rule?
  380. if any(tree.find_data('alias')):
  381. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  382. if name.startswith('_'):
  383. options = RuleOptions(filter_out=True, priority=-priority)
  384. else:
  385. options = RuleOptions(keep_all_tokens=True, create_token=name, priority=-priority)
  386. name = new_terminal_names[name]
  387. inner_name = name + '_inner'
  388. rule_defs.append((name, _choice_of_rules([inner_name]), None))
  389. rule_defs.append((inner_name, tree, options))
  390. return [], rule_defs
  391. def compile(self, lexer=False, start=None):
  392. if not lexer:
  393. token_defs, rule_defs = self._prepare_scanless_grammar(start)
  394. else:
  395. token_defs = list(self.token_defs)
  396. rule_defs = self.rule_defs
  397. # =================
  398. # Compile Tokens
  399. # =================
  400. # Convert token-trees to strings/regexps
  401. transformer = PrepareLiterals() * TokenTreeToPattern()
  402. tokens = [TokenDef(name, transformer.transform(token_tree), priority)
  403. for name, (token_tree, priority) in token_defs]
  404. # =================
  405. # Compile Rules
  406. # =================
  407. # 1. Pre-process terminals
  408. transformer = PrepareLiterals()
  409. if not lexer:
  410. transformer *= SplitLiterals()
  411. transformer *= ExtractAnonTokens(tokens) # Adds to tokens
  412. # 2. Convert EBNF to BNF (and apply step 1)
  413. ebnf_to_bnf = EBNF_to_BNF()
  414. rules = []
  415. for name, rule_tree, options in rule_defs:
  416. ebnf_to_bnf.rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  417. tree = transformer.transform(rule_tree)
  418. rules.append((name, ebnf_to_bnf.transform(tree), options))
  419. rules += ebnf_to_bnf.new_rules
  420. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  421. # 3. Compile tree to Rule objects
  422. rule_tree_to_text = RuleTreeToText()
  423. simplify_rule = SimplifyRule_Visitor()
  424. compiled_rules = []
  425. for name, tree, options in rules:
  426. simplify_rule.visit(tree)
  427. expansions = rule_tree_to_text.transform(tree)
  428. for expansion, alias in expansions:
  429. if alias and name.startswith('_'):
  430. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)" % (name, alias))
  431. rule = Rule(name, expansion, alias, options)
  432. compiled_rules.append(rule)
  433. return tokens, compiled_rules, self.ignore
  434. _imported_grammars = {}
  435. def import_grammar(grammar_path):
  436. if grammar_path not in _imported_grammars:
  437. for import_path in IMPORT_PATHS:
  438. with open(os.path.join(import_path, grammar_path)) as f:
  439. text = f.read()
  440. grammar = load_grammar(text, grammar_path)
  441. _imported_grammars[grammar_path] = grammar
  442. return _imported_grammars[grammar_path]
  443. def resolve_token_references(token_defs):
  444. # TODO Cycles detection
  445. # TODO Solve with transitive closure (maybe)
  446. token_dict = {k:t for k, (t,_p) in token_defs}
  447. assert len(token_dict) == len(token_defs), "Same name defined twice?"
  448. while True:
  449. changed = False
  450. for name, (token_tree, _p) in token_defs:
  451. for exp in chain(token_tree.find_data('expansion'), token_tree.find_data('expr')):
  452. for i, item in enumerate(exp.children):
  453. if isinstance(item, Token):
  454. if item.type == 'RULE':
  455. raise GrammarError("Rules aren't allowed inside tokens (%s in %s)" % (item, name))
  456. if item.type == 'TOKEN':
  457. exp.children[i] = token_dict[item]
  458. changed = True
  459. if not changed:
  460. break
  461. def options_from_rule(name, *x):
  462. if len(x) > 1:
  463. priority, expansions = x
  464. priority = int(priority)
  465. else:
  466. expansions ,= x
  467. priority = None
  468. keep_all_tokens = name.startswith('!')
  469. name = name.lstrip('!')
  470. expand1 = name.startswith('?')
  471. name = name.lstrip('?')
  472. return name, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority)
  473. class GrammarLoader:
  474. def __init__(self):
  475. tokens = [TokenDef(name, PatternRE(value)) for name, value in TOKENS.items()]
  476. rules = [options_from_rule(name, x) for name, x in RULES.items()]
  477. rules = [Rule(r, x.split(), None, o) for r, xs, o in rules for x in xs]
  478. callback = ParseTreeBuilder(rules, ST).create_callback()
  479. lexer_conf = LexerConf(tokens, ['WS', 'COMMENT'])
  480. parser_conf = ParserConf(rules, callback, 'start')
  481. self.parser = LALR(lexer_conf, parser_conf)
  482. self.canonize_tree = CanonizeTree()
  483. def load_grammar(self, grammar_text, name='<?>'):
  484. "Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
  485. try:
  486. tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
  487. except UnexpectedInput as e:
  488. raise GrammarError("Unexpected input %r at line %d column %d in %s" % (e.context, e.line, e.column, name))
  489. except UnexpectedToken as e:
  490. if e.expected == ['_COLON']:
  491. raise GrammarError("Missing colon at line %s column %s" % (e.line, e.column))
  492. elif e.expected == ['RULE']:
  493. raise GrammarError("Missing alias at line %s column %s" % (e.line, e.column))
  494. elif 'STRING' in e.expected:
  495. raise GrammarError("Expecting a value at line %s column %s" % (e.line, e.column))
  496. elif e.expected == ['_OR']:
  497. raise GrammarError("Newline without starting a new option (Expecting '|') at line %s column %s" % (e.line, e.column))
  498. raise
  499. # Extract grammar items
  500. token_defs = [c.children for c in tree.children if c.data=='token']
  501. rule_defs = [c.children for c in tree.children if c.data=='rule']
  502. statements = [c.children for c in tree.children if c.data=='statement']
  503. assert len(token_defs) + len(rule_defs) + len(statements) == len(tree.children)
  504. token_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in token_defs]
  505. token_defs = [(name.value, (t, int(p))) for name, p, t in token_defs]
  506. # Execute statements
  507. ignore = []
  508. for (stmt,) in statements:
  509. if stmt.data == 'ignore':
  510. t ,= stmt.children
  511. ignore.append(t)
  512. elif stmt.data == 'import':
  513. dotted_path = stmt.children[0].children
  514. name = stmt.children[1] if len(stmt.children)>1 else dotted_path[-1]
  515. grammar_path = os.path.join(*dotted_path[:-1]) + '.g'
  516. g = import_grammar(grammar_path)
  517. token_options = dict(g.token_defs)[dotted_path[-1]]
  518. assert isinstance(token_options, tuple) and len(token_options)==2
  519. token_defs.append([name.value, token_options])
  520. else:
  521. assert False, stmt
  522. # Verify correctness 1
  523. for name, _ in token_defs:
  524. if name.startswith('__'):
  525. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  526. # Handle ignore tokens
  527. # XXX A slightly hacky solution. Recognition of %ignore TOKEN as separate comes from the lexer's
  528. # inability to handle duplicate tokens (two names, one value)
  529. ignore_names = []
  530. for t in ignore:
  531. if t.data=='expansions' and len(t.children) == 1:
  532. t2 ,= t.children
  533. if t2.data=='expansion' and len(t2.children) == 1:
  534. item ,= t2.children
  535. if isinstance(item, Token) and item.type == 'TOKEN':
  536. ignore_names.append(item.value)
  537. continue
  538. name = '__IGNORE_%d'% len(ignore_names)
  539. ignore_names.append(name)
  540. token_defs.append((name, (t, 0)))
  541. # Verify correctness 2
  542. token_names = set()
  543. for name, _ in token_defs:
  544. if name in token_names:
  545. raise GrammarError("Token '%s' defined more than once" % name)
  546. token_names.add(name)
  547. if set(ignore_names) > token_names:
  548. raise GrammarError("Tokens %s were marked to ignore but were not defined!" % (set(ignore_names) - token_names))
  549. # Resolve token references
  550. resolve_token_references(token_defs)
  551. rules = [options_from_rule(*x) for x in rule_defs]
  552. rule_names = set()
  553. for name, _x, _o in rules:
  554. if name.startswith('__'):
  555. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  556. if name in rule_names:
  557. raise GrammarError("Rule '%s' defined more than once" % name)
  558. rule_names.add(name)
  559. for name, expansions, _o in rules:
  560. used_symbols = {t for x in expansions.find_data('expansion')
  561. for t in x.scan_values(lambda t: t.type in ('RULE', 'TOKEN'))}
  562. for sym in used_symbols:
  563. if is_terminal(sym):
  564. if sym not in token_names:
  565. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  566. else:
  567. if sym not in rule_names:
  568. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  569. # TODO don't include unused tokens, they can only cause trouble!
  570. return Grammar(rules, token_defs, ignore_names)
  571. load_grammar = GrammarLoader().load_grammar