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.

803 lines
28 KiB

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