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.

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