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.

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