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.

780 lines
27 KiB

  1. "Parses and creates Grammar objects"
  2. import os.path
  3. import sys
  4. from ast import literal_eval
  5. from copy import deepcopy
  6. from .utils import bfs
  7. from .lexer import Token, TerminalDef, PatternStr, PatternRE
  8. from .parse_tree_builder import ParseTreeBuilder
  9. from .parser_frontends import LALR_TraditionalLexer
  10. from .common import LexerConf, ParserConf
  11. from .grammar import RuleOptions, Rule, Terminal, NonTerminal, Symbol
  12. from .utils import classify, suppress
  13. from .exceptions import GrammarError, UnexpectedCharacters, UnexpectedToken
  14. from .tree import Tree, SlottedTree as ST
  15. from .visitors import Transformer, Visitor, v_args, Transformer_InPlace
  16. inline_args = v_args(inline=True)
  17. __path__ = os.path.dirname(__file__)
  18. IMPORT_PATHS = [os.path.join(__path__, 'grammars')]
  19. EXT = '.lark'
  20. _RE_FLAGS = 'imslux'
  21. _TERMINAL_NAMES = {
  22. '.' : 'DOT',
  23. ',' : 'COMMA',
  24. ':' : 'COLON',
  25. ';' : 'SEMICOLON',
  26. '+' : 'PLUS',
  27. '-' : 'MINUS',
  28. '*' : 'STAR',
  29. '/' : 'SLASH',
  30. '\\' : 'BACKSLASH',
  31. '|' : 'VBAR',
  32. '?' : 'QMARK',
  33. '!' : 'BANG',
  34. '@' : 'AT',
  35. '#' : 'HASH',
  36. '$' : 'DOLLAR',
  37. '%' : 'PERCENT',
  38. '^' : 'CIRCUMFLEX',
  39. '&' : 'AMPERSAND',
  40. '_' : 'UNDERSCORE',
  41. '<' : 'LESSTHAN',
  42. '>' : 'MORETHAN',
  43. '=' : 'EQUAL',
  44. '"' : 'DBLQUOTE',
  45. '\'' : 'QUOTE',
  46. '`' : 'BACKQUOTE',
  47. '~' : 'TILDE',
  48. '(' : 'LPAR',
  49. ')' : 'RPAR',
  50. '{' : 'LBRACE',
  51. '}' : 'RBRACE',
  52. '[' : 'LSQB',
  53. ']' : 'RSQB',
  54. '\n' : 'NEWLINE',
  55. '\r\n' : 'CRLF',
  56. '\t' : 'TAB',
  57. ' ' : 'SPACE',
  58. }
  59. # Grammar Parser
  60. TERMINALS = {
  61. '_LPAR': r'\(',
  62. '_RPAR': r'\)',
  63. '_LBRA': r'\[',
  64. '_RBRA': r'\]',
  65. 'OP': '[+*][?]?|[?](?![a-z])',
  66. '_COLON': ':',
  67. '_COMMA': ',',
  68. '_OR': r'\|',
  69. '_DOT': r'\.',
  70. 'TILDE': '~',
  71. 'RULE': '!?[_?]?[a-z][_a-z0-9]*',
  72. 'TERMINAL': '_?[A-Z][_A-Z0-9]*',
  73. 'STRING': r'"(\\"|\\\\|[^"\n])*?"i?',
  74. 'REGEXP': r'/(?!/)(\\/|\\\\|[^/\n])*?/[%s]*' % _RE_FLAGS,
  75. '_NL': r'(\r?\n)+\s*',
  76. 'WS': r'[ \t]+',
  77. 'COMMENT': r'//[^\n]*',
  78. '_TO': '->',
  79. '_IGNORE': r'%ignore',
  80. '_DECLARE': r'%declare',
  81. '_IMPORT': r'%import',
  82. 'NUMBER': r'\d+',
  83. }
  84. RULES = {
  85. 'start': ['_list'],
  86. '_list': ['_item', '_list _item'],
  87. '_item': ['rule', 'term', 'statement', '_NL'],
  88. 'rule': ['RULE _COLON expansions _NL',
  89. 'RULE _DOT NUMBER _COLON expansions _NL'],
  90. 'expansions': ['alias',
  91. 'expansions _OR alias',
  92. 'expansions _NL _OR alias'],
  93. '?alias': ['expansion _TO RULE', 'expansion'],
  94. 'expansion': ['_expansion'],
  95. '_expansion': ['', '_expansion expr'],
  96. '?expr': ['atom',
  97. 'atom OP',
  98. 'atom TILDE NUMBER',
  99. 'atom TILDE NUMBER _DOT _DOT NUMBER',
  100. ],
  101. '?atom': ['_LPAR expansions _RPAR',
  102. 'maybe',
  103. 'value'],
  104. 'value': ['terminal',
  105. 'nonterminal',
  106. 'literal',
  107. 'range'],
  108. 'terminal': ['TERMINAL'],
  109. 'nonterminal': ['RULE'],
  110. '?name': ['RULE', 'TERMINAL'],
  111. 'maybe': ['_LBRA expansions _RBRA'],
  112. 'range': ['STRING _DOT _DOT STRING'],
  113. 'term': ['TERMINAL _COLON expansions _NL',
  114. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  115. 'statement': ['ignore', 'import', 'declare'],
  116. 'ignore': ['_IGNORE expansions _NL'],
  117. 'declare': ['_DECLARE _declare_args _NL'],
  118. 'import': ['_IMPORT _import_path _NL',
  119. '_IMPORT _import_path _LPAR name_list _RPAR _NL',
  120. '_IMPORT _import_path _TO TERMINAL _NL'],
  121. '_import_path': ['import_lib', 'import_rel'],
  122. 'import_lib': ['_import_args'],
  123. 'import_rel': ['_DOT _import_args'],
  124. '_import_args': ['name', '_import_args _DOT name'],
  125. 'name_list': ['_name_list'],
  126. '_name_list': ['name', '_name_list _COMMA name'],
  127. '_declare_args': ['name', '_declare_args name'],
  128. 'literal': ['REGEXP', 'STRING'],
  129. }
  130. @inline_args
  131. class EBNF_to_BNF(Transformer_InPlace):
  132. def __init__(self):
  133. self.new_rules = []
  134. self.rules_by_expr = {}
  135. self.prefix = 'anon'
  136. self.i = 0
  137. self.rule_options = None
  138. def _add_recurse_rule(self, type_, expr):
  139. if expr in self.rules_by_expr:
  140. return self.rules_by_expr[expr]
  141. new_name = '__%s_%s_%d' % (self.prefix, type_, self.i)
  142. self.i += 1
  143. t = NonTerminal(new_name)
  144. tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])])
  145. self.new_rules.append((new_name, tree, self.rule_options))
  146. self.rules_by_expr[expr] = t
  147. return t
  148. def expr(self, rule, op, *args):
  149. if op.value == '?':
  150. return ST('expansions', [rule, ST('expansion', [])])
  151. elif op.value == '+':
  152. # a : b c+ d
  153. # -->
  154. # a : b _c d
  155. # _c : _c c | c;
  156. return self._add_recurse_rule('plus', rule)
  157. elif op.value == '*':
  158. # a : b c* d
  159. # -->
  160. # a : b _c? d
  161. # _c : _c c | c;
  162. new_name = self._add_recurse_rule('star', rule)
  163. return ST('expansions', [new_name, ST('expansion', [])])
  164. elif op.value == '~':
  165. if len(args) == 1:
  166. mn = mx = int(args[0])
  167. else:
  168. mn, mx = map(int, args)
  169. if mx < mn:
  170. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  171. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)])
  172. assert False, op
  173. class SimplifyRule_Visitor(Visitor):
  174. @staticmethod
  175. def _flatten(tree):
  176. while True:
  177. to_expand = [i for i, child in enumerate(tree.children)
  178. if isinstance(child, Tree) and child.data == tree.data]
  179. if not to_expand:
  180. break
  181. tree.expand_kids_by_index(*to_expand)
  182. def expansion(self, tree):
  183. # rules_list unpacking
  184. # a : b (c|d) e
  185. # -->
  186. # a : b c e | b d e
  187. #
  188. # In AST terms:
  189. # expansion(b, expansions(c, d), e)
  190. # -->
  191. # expansions( expansion(b, c, e), expansion(b, d, e) )
  192. self._flatten(tree)
  193. for i, child in enumerate(tree.children):
  194. if isinstance(child, Tree) and child.data == 'expansions':
  195. tree.data = 'expansions'
  196. tree.children = [self.visit(ST('expansion', [option if i==j else other
  197. for j, other in enumerate(tree.children)]))
  198. for option in set(child.children)]
  199. self._flatten(tree)
  200. break
  201. def alias(self, tree):
  202. rule, alias_name = tree.children
  203. if rule.data == 'expansions':
  204. aliases = []
  205. for child in tree.children[0].children:
  206. aliases.append(ST('alias', [child, alias_name]))
  207. tree.data = 'expansions'
  208. tree.children = aliases
  209. def expansions(self, tree):
  210. self._flatten(tree)
  211. tree.children = list(set(tree.children))
  212. class RuleTreeToText(Transformer):
  213. def expansions(self, x):
  214. return x
  215. def expansion(self, symbols):
  216. return symbols, None
  217. def alias(self, x):
  218. (expansion, _alias), alias = x
  219. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  220. return expansion, alias.value
  221. @inline_args
  222. class CanonizeTree(Transformer_InPlace):
  223. def maybe(self, expr):
  224. return ST('expr', [expr, Token('OP', '?', -1)])
  225. def tokenmods(self, *args):
  226. if len(args) == 1:
  227. return list(args)
  228. tokenmods, value = args
  229. return tokenmods + [value]
  230. class PrepareAnonTerminals(Transformer_InPlace):
  231. "Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them"
  232. def __init__(self, terminals):
  233. self.terminals = terminals
  234. self.term_set = {td.name for td in self.terminals}
  235. self.term_reverse = {td.pattern: td for td in terminals}
  236. self.i = 0
  237. @inline_args
  238. def pattern(self, p):
  239. value = p.value
  240. if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags:
  241. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  242. term_name = None
  243. if isinstance(p, PatternStr):
  244. try:
  245. # If already defined, use the user-defined terminal name
  246. term_name = self.term_reverse[p].name
  247. except KeyError:
  248. # Try to assign an indicative anon-terminal name
  249. try:
  250. term_name = _TERMINAL_NAMES[value]
  251. except KeyError:
  252. if value.isalnum() and value[0].isalpha() and value.upper() not in self.term_set:
  253. with suppress(UnicodeEncodeError):
  254. value.upper().encode('ascii') # Make sure we don't have unicode in our terminal names
  255. term_name = value.upper()
  256. if term_name in self.term_set:
  257. term_name = None
  258. elif isinstance(p, PatternRE):
  259. if p in self.term_reverse: # Kind of a wierd placement.name
  260. term_name = self.term_reverse[p].name
  261. else:
  262. assert False, p
  263. if term_name is None:
  264. term_name = '__ANON_%d' % self.i
  265. self.i += 1
  266. if term_name not in self.term_set:
  267. assert p not in self.term_reverse
  268. self.term_set.add(term_name)
  269. termdef = TerminalDef(term_name, p)
  270. self.term_reverse[p] = termdef
  271. self.terminals.append(termdef)
  272. return Terminal(term_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 TerminalTreeToPattern(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 terminals 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 terminals 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, term_defs, ignore):
  367. self.term_defs = term_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. term_defs = deepcopy(list(self.term_defs))
  374. rule_defs = deepcopy(self.rule_defs)
  375. # ===================
  376. # Compile Terminals
  377. # ===================
  378. # Convert terminal-trees to strings/regexps
  379. transformer = PrepareLiterals() * TerminalTreeToPattern()
  380. for name, (term_tree, priority) in term_defs:
  381. if term_tree is None: # Terminal added through %declare
  382. continue
  383. expansions = list(term_tree.find_data('expansion'))
  384. if len(expansions) == 1 and not expansions[0].children:
  385. raise GrammarError("Terminals cannot be empty (%s)" % name)
  386. terminals = [TerminalDef(name, transformer.transform(term_tree), priority)
  387. for name, (term_tree, priority) in term_defs if term_tree]
  388. # =================
  389. # Compile Rules
  390. # =================
  391. # 1. Pre-process terminals
  392. transformer = PrepareLiterals() * PrepareSymbols() * PrepareAnonTerminals(terminals) # Adds to terminals
  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 terminals, 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 import_from_grammar_into_namespace(grammar, namespace, aliases):
  432. imported_terms = dict(grammar.term_defs)
  433. imported_rules = {n:(n,t,o) for n,t,o in grammar.rule_defs}
  434. term_defs = []
  435. rule_defs = []
  436. def rule_dependencies(symbol):
  437. if symbol.type != 'RULE':
  438. return []
  439. _, tree, _ = imported_rules[symbol]
  440. return tree.scan_values(lambda x: x.type in ('RULE', 'TERMINAL'))
  441. def get_namespace_name(name):
  442. try:
  443. return aliases[name].value
  444. except KeyError:
  445. return '%s.%s' % (namespace, name)
  446. to_import = list(bfs(aliases, rule_dependencies))
  447. for symbol in to_import:
  448. if symbol.type == 'TERMINAL':
  449. term_defs.append([get_namespace_name(symbol), imported_terms[symbol]])
  450. else:
  451. assert symbol.type == 'RULE'
  452. rule = imported_rules[symbol]
  453. for t in rule[1].iter_subtrees():
  454. for i, c in enumerate(t.children):
  455. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  456. t.children[i] = Token(c.type, get_namespace_name(c))
  457. rule_defs.append((get_namespace_name(symbol), rule[1], rule[2]))
  458. return term_defs, rule_defs
  459. def resolve_term_references(term_defs):
  460. # TODO Cycles detection
  461. # TODO Solve with transitive closure (maybe)
  462. token_dict = {k:t for k, (t,_p) in term_defs}
  463. assert len(token_dict) == len(term_defs), "Same name defined twice?"
  464. while True:
  465. changed = False
  466. for name, (token_tree, _p) in term_defs:
  467. if token_tree is None: # Terminal added through %declare
  468. continue
  469. for exp in token_tree.find_data('value'):
  470. item ,= exp.children
  471. if isinstance(item, Token):
  472. if item.type == 'RULE':
  473. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  474. if item.type == 'TERMINAL':
  475. exp.children[0] = token_dict[item]
  476. changed = True
  477. if not changed:
  478. break
  479. def options_from_rule(name, *x):
  480. if len(x) > 1:
  481. priority, expansions = x
  482. priority = int(priority)
  483. else:
  484. expansions ,= x
  485. priority = None
  486. keep_all_tokens = name.startswith('!')
  487. name = name.lstrip('!')
  488. expand1 = name.startswith('?')
  489. name = name.lstrip('?')
  490. return name, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority)
  491. def symbols_from_strcase(expansion):
  492. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  493. @inline_args
  494. class PrepareGrammar(Transformer_InPlace):
  495. def terminal(self, name):
  496. return name
  497. def nonterminal(self, name):
  498. return name
  499. class GrammarLoader:
  500. def __init__(self):
  501. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  502. rules = [options_from_rule(name, x) for name, x in RULES.items()]
  503. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), None, o) for r, xs, o in rules for x in xs]
  504. callback = ParseTreeBuilder(rules, ST).create_callback()
  505. lexer_conf = LexerConf(terminals, ['WS', 'COMMENT'])
  506. parser_conf = ParserConf(rules, callback, 'start')
  507. self.parser = LALR_TraditionalLexer(lexer_conf, parser_conf)
  508. self.canonize_tree = CanonizeTree()
  509. def load_grammar(self, grammar_text, grammar_name='<?>'):
  510. "Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
  511. try:
  512. tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
  513. except UnexpectedCharacters as e:
  514. context = e.get_context(grammar_text)
  515. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  516. (e.line, e.column, grammar_name, context))
  517. except UnexpectedToken as e:
  518. context = e.get_context(grammar_text)
  519. error = e.match_examples(self.parser.parse, {
  520. 'Unclosed parenthesis': ['a: (\n'],
  521. 'Umatched closing parenthesis': ['a: )\n', 'a: [)\n', 'a: (]\n'],
  522. 'Expecting rule or terminal definition (missing colon)': ['a\n', 'a->\n', 'A->\n', 'a A\n'],
  523. 'Alias expects lowercase name': ['a: -> "a"\n'],
  524. 'Unexpected colon': ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n'],
  525. 'Misplaced operator': ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n'],
  526. 'Expecting option ("|") or a new rule or terminal definition': ['a:a\n()\n'],
  527. '%import expects a name': ['%import "a"\n'],
  528. '%ignore expects a value': ['%ignore %import\n'],
  529. })
  530. if error:
  531. raise GrammarError("%s at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  532. elif 'STRING' in e.expected:
  533. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  534. raise
  535. tree = PrepareGrammar().transform(tree)
  536. # Extract grammar items
  537. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  538. term_defs = defs.pop('term', [])
  539. rule_defs = defs.pop('rule', [])
  540. statements = defs.pop('statement', [])
  541. assert not defs
  542. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  543. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  544. rule_defs = [options_from_rule(*x) for x in rule_defs]
  545. # Execute statements
  546. ignore = []
  547. for (stmt,) in statements:
  548. if stmt.data == 'ignore':
  549. t ,= stmt.children
  550. ignore.append(t)
  551. elif stmt.data == 'import':
  552. if len(stmt.children) > 1:
  553. path_node, arg1 = stmt.children
  554. else:
  555. path_node ,= stmt.children
  556. arg1 = None
  557. if isinstance(arg1, Tree): # Multi import
  558. dotted_path = path_node.children
  559. names = arg1.children
  560. aliases = names # Can't have aliased multi import, so all aliases will be the same as names
  561. else: # Single import
  562. dotted_path = path_node.children[:-1]
  563. names = [path_node.children[-1]] # Get name from dotted path
  564. aliases = [arg1] if arg1 else names # Aliases if exist
  565. grammar_path = os.path.join(*dotted_path) + EXT
  566. if path_node.data == 'import_lib': # Import from library
  567. g = import_grammar(grammar_path)
  568. else: # Relative import
  569. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  570. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  571. else:
  572. base_file = grammar_name # Import relative to grammar file path if external grammar file
  573. base_path = os.path.split(base_file)[0]
  574. g = import_grammar(grammar_path, base_paths=[base_path])
  575. aliases_dict = dict(zip(names, aliases))
  576. new_td, new_rd = import_from_grammar_into_namespace(g, '.'.join(dotted_path), aliases_dict)
  577. term_defs += new_td
  578. rule_defs += new_rd
  579. elif stmt.data == 'declare':
  580. for t in stmt.children:
  581. term_defs.append([t.value, (None, None)])
  582. else:
  583. assert False, stmt
  584. # Verify correctness 1
  585. for name, _ in term_defs:
  586. if name.startswith('__'):
  587. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  588. # Handle ignore tokens
  589. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  590. # inability to handle duplicate terminals (two names, one value)
  591. ignore_names = []
  592. for t in ignore:
  593. if t.data=='expansions' and len(t.children) == 1:
  594. t2 ,= t.children
  595. if t2.data=='expansion' and len(t2.children) == 1:
  596. item ,= t2.children
  597. if item.data == 'value':
  598. item ,= item.children
  599. if isinstance(item, Token) and item.type == 'TERMINAL':
  600. ignore_names.append(item.value)
  601. continue
  602. name = '__IGNORE_%d'% len(ignore_names)
  603. ignore_names.append(name)
  604. term_defs.append((name, (t, 0)))
  605. # Verify correctness 2
  606. terminal_names = set()
  607. for name, _ in term_defs:
  608. if name in terminal_names:
  609. raise GrammarError("Terminal '%s' defined more than once" % name)
  610. terminal_names.add(name)
  611. if set(ignore_names) > terminal_names:
  612. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names))
  613. resolve_term_references(term_defs)
  614. rules = rule_defs
  615. rule_names = set()
  616. for name, _x, _o in rules:
  617. if name.startswith('__'):
  618. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  619. if name in rule_names:
  620. raise GrammarError("Rule '%s' defined more than once" % name)
  621. rule_names.add(name)
  622. for name, expansions, _o in rules:
  623. used_symbols = {t for x in expansions.find_data('expansion')
  624. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  625. for sym in used_symbols:
  626. if sym.type == 'TERMINAL':
  627. if sym not in terminal_names:
  628. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  629. else:
  630. if sym not in rule_names:
  631. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  632. # TODO don't include unused terminals, they can only cause trouble!
  633. return Grammar(rules, term_defs, ignore_names)
  634. load_grammar = GrammarLoader().load_grammar