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.

746 lines
25 KiB

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