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.

872 lines
31 KiB

  1. "Parses and creates Grammar objects"
  2. import os.path
  3. import sys
  4. from copy import copy, deepcopy
  5. from io import open
  6. from .utils import bfs, eval_escaping
  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, END
  12. from .utils import classify, suppress, dedup_list, Str
  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. '_DOTDOT': 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'\s*//[^\n]*',
  80. '_TO': '->',
  81. '_IGNORE': r'%ignore',
  82. '_DECLARE': r'%declare',
  83. '_IMPORT': r'%import',
  84. <<<<<<< HEAD
  85. 'NUMBER': r'[+-]?\d+',
  86. =======
  87. 'NUMBER': r'\d+',
  88. '_END': r'\$',
  89. >>>>>>> end_symbol
  90. }
  91. RULES = {
  92. 'start': ['_list'],
  93. '_list': ['_item', '_list _item'],
  94. '_item': ['rule', 'term', 'statement', '_NL'],
  95. 'rule': ['RULE _COLON expansions _NL',
  96. 'RULE _DOT NUMBER _COLON expansions _NL'],
  97. 'expansions': ['alias',
  98. 'expansions _OR alias',
  99. 'expansions _NL _OR alias'],
  100. '?alias': ['expansion _TO RULE', 'expansion'],
  101. 'expansion': ['_expansion'],
  102. '_expansion': ['', '_expansion expr'],
  103. '?expr': ['atom',
  104. 'atom OP',
  105. 'atom TILDE NUMBER',
  106. 'atom TILDE NUMBER _DOTDOT NUMBER',
  107. ],
  108. '?atom': ['_LPAR expansions _RPAR',
  109. 'maybe',
  110. 'value'],
  111. 'value': ['terminal',
  112. 'nonterminal',
  113. 'literal',
  114. 'range',
  115. 'end'],
  116. 'terminal': ['TERMINAL'],
  117. 'nonterminal': ['RULE'],
  118. '?name': ['RULE', 'TERMINAL'],
  119. 'maybe': ['_LBRA expansions _RBRA'],
  120. <<<<<<< HEAD
  121. 'range': ['STRING _DOTDOT STRING'],
  122. =======
  123. 'range': ['STRING _DOT _DOT STRING'],
  124. 'end': ['_END'],
  125. >>>>>>> end_symbol
  126. 'term': ['TERMINAL _COLON expansions _NL',
  127. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  128. 'statement': ['ignore', 'import', 'declare'],
  129. 'ignore': ['_IGNORE expansions _NL'],
  130. 'declare': ['_DECLARE _declare_args _NL'],
  131. 'import': ['_IMPORT _import_path _NL',
  132. '_IMPORT _import_path _LPAR name_list _RPAR _NL',
  133. '_IMPORT _import_path _TO name _NL'],
  134. '_import_path': ['import_lib', 'import_rel'],
  135. 'import_lib': ['_import_args'],
  136. 'import_rel': ['_DOT _import_args'],
  137. '_import_args': ['name', '_import_args _DOT name'],
  138. 'name_list': ['_name_list'],
  139. '_name_list': ['name', '_name_list _COMMA name'],
  140. '_declare_args': ['name', '_declare_args name'],
  141. 'literal': ['REGEXP', 'STRING'],
  142. }
  143. @inline_args
  144. class EBNF_to_BNF(Transformer_InPlace):
  145. def __init__(self):
  146. self.new_rules = []
  147. self.rules_by_expr = {}
  148. self.prefix = 'anon'
  149. self.i = 0
  150. self.rule_options = None
  151. def _add_recurse_rule(self, type_, expr):
  152. if expr in self.rules_by_expr:
  153. return self.rules_by_expr[expr]
  154. new_name = '__%s_%s_%d' % (self.prefix, type_, self.i)
  155. self.i += 1
  156. t = NonTerminal(new_name)
  157. tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])])
  158. self.new_rules.append((new_name, tree, self.rule_options))
  159. self.rules_by_expr[expr] = t
  160. return t
  161. def expr(self, rule, op, *args):
  162. if op.value == '?':
  163. empty = ST('expansion', [])
  164. return ST('expansions', [rule, empty])
  165. elif op.value == '+':
  166. # a : b c+ d
  167. # -->
  168. # a : b _c d
  169. # _c : _c c | c;
  170. return self._add_recurse_rule('plus', rule)
  171. elif op.value == '*':
  172. # a : b c* d
  173. # -->
  174. # a : b _c? d
  175. # _c : _c c | c;
  176. new_name = self._add_recurse_rule('star', rule)
  177. return ST('expansions', [new_name, ST('expansion', [])])
  178. elif op.value == '~':
  179. if len(args) == 1:
  180. mn = mx = int(args[0])
  181. else:
  182. mn, mx = map(int, args)
  183. if mx < mn or mn < 0:
  184. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  185. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)])
  186. assert False, op
  187. def maybe(self, rule):
  188. keep_all_tokens = self.rule_options and self.rule_options.keep_all_tokens
  189. def will_not_get_removed(sym):
  190. if isinstance(sym, NonTerminal):
  191. return not sym.name.startswith('_')
  192. if isinstance(sym, Terminal):
  193. return keep_all_tokens or not sym.filter_out
  194. assert False
  195. if any(rule.scan_values(will_not_get_removed)):
  196. empty = _EMPTY
  197. else:
  198. empty = ST('expansion', [])
  199. return ST('expansions', [rule, empty])
  200. class SimplifyRule_Visitor(Visitor):
  201. @staticmethod
  202. def _flatten(tree):
  203. while True:
  204. to_expand = [i for i, child in enumerate(tree.children)
  205. if isinstance(child, Tree) and child.data == tree.data]
  206. if not to_expand:
  207. break
  208. tree.expand_kids_by_index(*to_expand)
  209. def expansion(self, tree):
  210. # rules_list unpacking
  211. # a : b (c|d) e
  212. # -->
  213. # a : b c e | b d e
  214. #
  215. # In AST terms:
  216. # expansion(b, expansions(c, d), e)
  217. # -->
  218. # expansions( expansion(b, c, e), expansion(b, d, e) )
  219. self._flatten(tree)
  220. for i, child in enumerate(tree.children):
  221. if isinstance(child, Tree) and child.data == 'expansions':
  222. tree.data = 'expansions'
  223. tree.children = [self.visit(ST('expansion', [option if i==j else other
  224. for j, other in enumerate(tree.children)]))
  225. for option in dedup_list(child.children)]
  226. self._flatten(tree)
  227. break
  228. def alias(self, tree):
  229. rule, alias_name = tree.children
  230. if rule.data == 'expansions':
  231. aliases = []
  232. for child in tree.children[0].children:
  233. aliases.append(ST('alias', [child, alias_name]))
  234. tree.data = 'expansions'
  235. tree.children = aliases
  236. def expansions(self, tree):
  237. self._flatten(tree)
  238. tree.children = dedup_list(tree.children)
  239. class RuleTreeToText(Transformer):
  240. def expansions(self, x):
  241. return x
  242. def expansion(self, symbols):
  243. return symbols, None
  244. def alias(self, x):
  245. (expansion, _alias), alias = x
  246. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  247. return expansion, alias.value
  248. @inline_args
  249. class CanonizeTree(Transformer_InPlace):
  250. def tokenmods(self, *args):
  251. if len(args) == 1:
  252. return list(args)
  253. tokenmods, value = args
  254. return tokenmods + [value]
  255. def end(self):
  256. return Token('TERMINAL', END)
  257. class PrepareAnonTerminals(Transformer_InPlace):
  258. "Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them"
  259. def __init__(self, terminals):
  260. self.terminals = terminals
  261. self.term_set = {td.name for td in self.terminals}
  262. self.term_reverse = {td.pattern: td for td in terminals}
  263. self.i = 0
  264. @inline_args
  265. def pattern(self, p):
  266. value = p.value
  267. if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags:
  268. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  269. term_name = None
  270. if isinstance(p, PatternStr):
  271. try:
  272. # If already defined, use the user-defined terminal name
  273. term_name = self.term_reverse[p].name
  274. except KeyError:
  275. # Try to assign an indicative anon-terminal name
  276. try:
  277. term_name = _TERMINAL_NAMES[value]
  278. except KeyError:
  279. if value.isalnum() and value[0].isalpha() and value.upper() not in self.term_set:
  280. with suppress(UnicodeEncodeError):
  281. value.upper().encode('ascii') # Make sure we don't have unicode in our terminal names
  282. term_name = value.upper()
  283. if term_name in self.term_set:
  284. term_name = None
  285. elif isinstance(p, PatternRE):
  286. if p in self.term_reverse: # Kind of a wierd placement.name
  287. term_name = self.term_reverse[p].name
  288. else:
  289. assert False, p
  290. if term_name is None:
  291. term_name = '__ANON_%d' % self.i
  292. self.i += 1
  293. if term_name not in self.term_set:
  294. assert p not in self.term_reverse
  295. self.term_set.add(term_name)
  296. termdef = TerminalDef(term_name, p)
  297. self.term_reverse[p] = termdef
  298. self.terminals.append(termdef)
  299. return Terminal(term_name, filter_out=isinstance(p, PatternStr))
  300. def _rfind(s, choices):
  301. return max(s.rfind(c) for c in choices)
  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 = eval_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(eval_escaping(start)) == len(eval_escaping(end)) == 1, (start, end, len(eval_escaping(start)), len(eval_escaping(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 maybe(self, expr):
  358. return self.expr(expr + ['?'])
  359. def alias(self, t):
  360. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  361. def value(self, v):
  362. return v[0]
  363. class PrepareSymbols(Transformer_InPlace):
  364. def value(self, v):
  365. v ,= v
  366. if isinstance(v, Tree):
  367. return v
  368. elif v.type == 'RULE':
  369. return NonTerminal(Str(v.value))
  370. elif v.type == 'TERMINAL':
  371. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  372. assert False
  373. def _choice_of_rules(rules):
  374. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  375. class Grammar:
  376. def __init__(self, rule_defs, term_defs, ignore):
  377. self.term_defs = term_defs
  378. self.rule_defs = rule_defs
  379. self.ignore = ignore
  380. def compile(self, start):
  381. # We change the trees in-place (to support huge grammars)
  382. # So deepcopy allows calling compile more than once.
  383. term_defs = deepcopy(list(self.term_defs))
  384. rule_defs = deepcopy(self.rule_defs)
  385. # ===================
  386. # Compile Terminals
  387. # ===================
  388. # Convert terminal-trees to strings/regexps
  389. for name, (term_tree, priority) in term_defs:
  390. if term_tree is None: # Terminal added through %declare
  391. continue
  392. expansions = list(term_tree.find_data('expansion'))
  393. if len(expansions) == 1 and not expansions[0].children:
  394. raise GrammarError("Terminals cannot be empty (%s)" % name)
  395. transformer = PrepareLiterals() * TerminalTreeToPattern()
  396. terminals = [TerminalDef(name, transformer.transform( term_tree ), priority)
  397. for name, (term_tree, priority) in term_defs if term_tree]
  398. # =================
  399. # Compile Rules
  400. # =================
  401. # 1. Pre-process terminals
  402. transformer = PrepareLiterals() * PrepareSymbols() * PrepareAnonTerminals(terminals) # Adds to terminals
  403. # 2. Convert EBNF to BNF (and apply step 1)
  404. ebnf_to_bnf = EBNF_to_BNF()
  405. rules = []
  406. for name, rule_tree, options in rule_defs:
  407. ebnf_to_bnf.rule_options = RuleOptions(keep_all_tokens=True) if options.keep_all_tokens else None
  408. ebnf_to_bnf.prefix = name
  409. tree = transformer.transform(rule_tree)
  410. res = ebnf_to_bnf.transform(tree)
  411. rules.append((name, res, options))
  412. rules += ebnf_to_bnf.new_rules
  413. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  414. # 3. Compile tree to Rule objects
  415. rule_tree_to_text = RuleTreeToText()
  416. simplify_rule = SimplifyRule_Visitor()
  417. compiled_rules = []
  418. for rule_content in rules:
  419. name, tree, options = rule_content
  420. simplify_rule.visit(tree)
  421. expansions = rule_tree_to_text.transform(tree)
  422. for i, (expansion, alias) in enumerate(expansions):
  423. if alias and name.startswith('_'):
  424. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)" % (name, alias))
  425. empty_indices = [x==_EMPTY for x in expansion]
  426. if any(empty_indices):
  427. exp_options = copy(options) or RuleOptions()
  428. exp_options.empty_indices = empty_indices
  429. expansion = [x for x in expansion if x!=_EMPTY]
  430. else:
  431. exp_options = options
  432. assert all(isinstance(x, Symbol) for x in expansion), expansion
  433. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  434. compiled_rules.append(rule)
  435. # Remove duplicates of empty rules, throw error for non-empty duplicates
  436. if len(set(compiled_rules)) != len(compiled_rules):
  437. duplicates = classify(compiled_rules, lambda x: x)
  438. for dups in duplicates.values():
  439. if len(dups) > 1:
  440. if dups[0].expansion:
  441. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  442. % ''.join('\n * %s' % i for i in dups))
  443. # Empty rule; assert all other attributes are equal
  444. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  445. # Remove duplicates
  446. compiled_rules = list(set(compiled_rules))
  447. # Filter out unused rules
  448. while True:
  449. c = len(compiled_rules)
  450. used_rules = {s for r in compiled_rules
  451. for s in r.expansion
  452. if isinstance(s, NonTerminal)
  453. and s != r.origin}
  454. used_rules |= {NonTerminal(s) for s in start}
  455. compiled_rules = [r for r in compiled_rules if r.origin in used_rules]
  456. if len(compiled_rules) == c:
  457. break
  458. # Filter out unused terminals
  459. used_terms = {t.name for r in compiled_rules
  460. for t in r.expansion
  461. if isinstance(t, Terminal)}
  462. terminals = [t for t in terminals if t.name in used_terms or t.name in self.ignore]
  463. return terminals, compiled_rules, self.ignore
  464. _imported_grammars = {}
  465. def import_grammar(grammar_path, base_paths=[]):
  466. if grammar_path not in _imported_grammars:
  467. import_paths = base_paths + IMPORT_PATHS
  468. for import_path in import_paths:
  469. with suppress(IOError):
  470. joined_path = os.path.join(import_path, grammar_path)
  471. with open(joined_path, encoding='utf8') as f:
  472. text = f.read()
  473. grammar = load_grammar(text, joined_path)
  474. _imported_grammars[grammar_path] = grammar
  475. break
  476. else:
  477. open(grammar_path, encoding='utf8')
  478. assert False
  479. return _imported_grammars[grammar_path]
  480. def import_from_grammar_into_namespace(grammar, namespace, aliases):
  481. """Returns all rules and terminals of grammar, prepended
  482. with a 'namespace' prefix, except for those which are aliased.
  483. """
  484. imported_terms = dict(grammar.term_defs)
  485. imported_rules = {n:(n,deepcopy(t),o) for n,t,o in grammar.rule_defs}
  486. term_defs = []
  487. rule_defs = []
  488. def rule_dependencies(symbol):
  489. if symbol.type != 'RULE':
  490. return []
  491. try:
  492. _, tree, _ = imported_rules[symbol]
  493. except KeyError:
  494. raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace))
  495. return _find_used_symbols(tree)
  496. def get_namespace_name(name):
  497. try:
  498. return aliases[name].value
  499. except KeyError:
  500. if name[0] == '_':
  501. return '_%s__%s' % (namespace, name[1:])
  502. return '%s__%s' % (namespace, name)
  503. to_import = list(bfs(aliases, rule_dependencies))
  504. for symbol in to_import:
  505. if symbol.type == 'TERMINAL':
  506. term_defs.append([get_namespace_name(symbol), imported_terms[symbol]])
  507. else:
  508. assert symbol.type == 'RULE'
  509. rule = imported_rules[symbol]
  510. for t in rule[1].iter_subtrees():
  511. for i, c in enumerate(t.children):
  512. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  513. t.children[i] = Token(c.type, get_namespace_name(c))
  514. rule_defs.append((get_namespace_name(symbol), rule[1], rule[2]))
  515. return term_defs, rule_defs
  516. def resolve_term_references(term_defs):
  517. # TODO Solve with transitive closure (maybe)
  518. term_dict = {k:t for k, (t,_p) in term_defs}
  519. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  520. while True:
  521. changed = False
  522. for name, (token_tree, _p) in term_defs:
  523. if token_tree is None: # Terminal added through %declare
  524. continue
  525. for exp in token_tree.find_data('value'):
  526. item ,= exp.children
  527. if isinstance(item, Token):
  528. if item.type == 'RULE':
  529. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  530. if item.type == 'TERMINAL':
  531. term_value = term_dict[item]
  532. assert term_value is not None
  533. exp.children[0] = term_value
  534. changed = True
  535. if not changed:
  536. break
  537. for name, term in term_dict.items():
  538. if term: # Not just declared
  539. for child in term.children:
  540. ids = [id(x) for x in child.iter_subtrees()]
  541. if id(term) in ids:
  542. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  543. def options_from_rule(name, *x):
  544. if len(x) > 1:
  545. priority, expansions = x
  546. priority = int(priority)
  547. else:
  548. expansions ,= x
  549. priority = None
  550. keep_all_tokens = name.startswith('!')
  551. name = name.lstrip('!')
  552. expand1 = name.startswith('?')
  553. name = name.lstrip('?')
  554. return name, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority)
  555. def symbols_from_strcase(expansion):
  556. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  557. @inline_args
  558. class PrepareGrammar(Transformer_InPlace):
  559. def terminal(self, name):
  560. return name
  561. def nonterminal(self, name):
  562. return name
  563. def _find_used_symbols(tree):
  564. assert tree.data == 'expansions'
  565. return {t for x in tree.find_data('expansion')
  566. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  567. class GrammarLoader:
  568. def __init__(self):
  569. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  570. rules = [options_from_rule(name, x) for name, x in RULES.items()]
  571. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o) for r, xs, o in rules for i, x in enumerate(xs)]
  572. callback = ParseTreeBuilder(rules, ST).create_callback()
  573. lexer_conf = LexerConf(terminals, ['WS', 'COMMENT'])
  574. parser_conf = ParserConf(rules, callback, ['start'])
  575. self.parser = LALR_TraditionalLexer(lexer_conf, parser_conf)
  576. self.canonize_tree = CanonizeTree()
  577. def load_grammar(self, grammar_text, grammar_name='<?>'):
  578. "Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
  579. try:
  580. tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
  581. except UnexpectedCharacters as e:
  582. context = e.get_context(grammar_text)
  583. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  584. (e.line, e.column, grammar_name, context))
  585. except UnexpectedToken as e:
  586. context = e.get_context(grammar_text)
  587. error = e.match_examples(self.parser.parse, {
  588. 'Unclosed parenthesis': ['a: (\n'],
  589. 'Umatched closing parenthesis': ['a: )\n', 'a: [)\n', 'a: (]\n'],
  590. 'Expecting rule or terminal definition (missing colon)': ['a\n', 'a->\n', 'A->\n', 'a A\n'],
  591. 'Alias expects lowercase name': ['a: -> "a"\n'],
  592. 'Unexpected colon': ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n'],
  593. 'Misplaced operator': ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n'],
  594. 'Expecting option ("|") or a new rule or terminal definition': ['a:a\n()\n'],
  595. '%import expects a name': ['%import "a"\n'],
  596. '%ignore expects a value': ['%ignore %import\n'],
  597. })
  598. if error:
  599. raise GrammarError("%s at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  600. elif 'STRING' in e.expected:
  601. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  602. raise
  603. tree = PrepareGrammar().transform(tree)
  604. # Extract grammar items
  605. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  606. term_defs = defs.pop('term', [])
  607. rule_defs = defs.pop('rule', [])
  608. statements = defs.pop('statement', [])
  609. assert not defs
  610. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  611. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  612. term_defs.append((END, (None, 0)))
  613. rule_defs = [options_from_rule(*x) for x in rule_defs]
  614. # Execute statements
  615. ignore, imports = [], {}
  616. for (stmt,) in statements:
  617. if stmt.data == 'ignore':
  618. t ,= stmt.children
  619. ignore.append(t)
  620. elif stmt.data == 'import':
  621. if len(stmt.children) > 1:
  622. path_node, arg1 = stmt.children
  623. else:
  624. path_node, = stmt.children
  625. arg1 = None
  626. if isinstance(arg1, Tree): # Multi import
  627. dotted_path = tuple(path_node.children)
  628. names = arg1.children
  629. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  630. else: # Single import
  631. dotted_path = tuple(path_node.children[:-1])
  632. name = path_node.children[-1] # Get name from dotted path
  633. aliases = {name: arg1 or name} # Aliases if exist
  634. if path_node.data == 'import_lib': # Import from library
  635. base_paths = []
  636. else: # Relative import
  637. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  638. try:
  639. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  640. except AttributeError:
  641. base_file = None
  642. else:
  643. base_file = grammar_name # Import relative to grammar file path if external grammar file
  644. if base_file:
  645. base_paths = [os.path.split(base_file)[0]]
  646. else:
  647. base_paths = [os.path.abspath(os.path.curdir)]
  648. try:
  649. import_base_paths, import_aliases = imports[dotted_path]
  650. assert base_paths == import_base_paths, 'Inconsistent base_paths for %s.' % '.'.join(dotted_path)
  651. import_aliases.update(aliases)
  652. except KeyError:
  653. imports[dotted_path] = base_paths, aliases
  654. elif stmt.data == 'declare':
  655. for t in stmt.children:
  656. term_defs.append([t.value, (None, None)])
  657. else:
  658. assert False, stmt
  659. # import grammars
  660. for dotted_path, (base_paths, aliases) in imports.items():
  661. grammar_path = os.path.join(*dotted_path) + EXT
  662. g = import_grammar(grammar_path, base_paths=base_paths)
  663. new_td, new_rd = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases)
  664. term_defs += new_td
  665. rule_defs += new_rd
  666. # Verify correctness 1
  667. for name, _ in term_defs:
  668. if name.startswith('__'):
  669. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  670. # Handle ignore tokens
  671. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  672. # inability to handle duplicate terminals (two names, one value)
  673. ignore_names = []
  674. for t in ignore:
  675. if t.data=='expansions' and len(t.children) == 1:
  676. t2 ,= t.children
  677. if t2.data=='expansion' and len(t2.children) == 1:
  678. item ,= t2.children
  679. if item.data == 'value':
  680. item ,= item.children
  681. if isinstance(item, Token) and item.type == 'TERMINAL':
  682. ignore_names.append(item.value)
  683. continue
  684. name = '__IGNORE_%d'% len(ignore_names)
  685. ignore_names.append(name)
  686. term_defs.append((name, (t, 1)))
  687. # Verify correctness 2
  688. terminal_names = set()
  689. for name, _ in term_defs:
  690. if name in terminal_names:
  691. raise GrammarError("Terminal '%s' defined more than once" % name)
  692. terminal_names.add(name)
  693. if set(ignore_names) - terminal_names:
  694. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names))
  695. resolve_term_references(term_defs)
  696. rules = rule_defs
  697. rule_names = set()
  698. for name, _x, _o in rules:
  699. if name.startswith('__'):
  700. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  701. if name in rule_names:
  702. raise GrammarError("Rule '%s' defined more than once" % name)
  703. rule_names.add(name)
  704. for name, expansions, _o in rules:
  705. for sym in _find_used_symbols(expansions):
  706. if sym.type == 'TERMINAL':
  707. if sym not in terminal_names:
  708. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  709. else:
  710. if sym not in rule_names:
  711. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  712. return Grammar(rules, term_defs, ignore_names)
  713. load_grammar = GrammarLoader().load_grammar