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.

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