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.

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