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.

955 lines
35 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
  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, Transformer_NonRecursive
  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. '_LBRACE': r'\{',
  67. '_RBRACE': r'\}',
  68. 'OP': '[+*]|[?](?![a-z])',
  69. '_COLON': ':',
  70. '_COMMA': ',',
  71. '_OR': r'\|',
  72. '_DOT': r'\.(?!\.)',
  73. '_DOTDOT': r'\.\.',
  74. 'TILDE': '~',
  75. 'RULE': '!?[_?]?[a-z][_a-z0-9]*',
  76. 'TERMINAL': '_?[A-Z][_A-Z0-9]*',
  77. 'STRING': r'"(\\"|\\\\|[^"\n])*?"i?',
  78. 'REGEXP': r'/(?!/)(\\/|\\\\|[^/\n])*?/[%s]*' % _RE_FLAGS,
  79. '_NL': r'(\r?\n)+\s*',
  80. 'WS': r'[ \t]+',
  81. 'COMMENT': r'\s*//[^\n]*',
  82. '_TO': '->',
  83. '_IGNORE': r'%ignore',
  84. '_DECLARE': r'%declare',
  85. '_IMPORT': r'%import',
  86. 'NUMBER': r'[+-]?\d+',
  87. }
  88. RULES = {
  89. 'start': ['_list'],
  90. '_list': ['_item', '_list _item'],
  91. '_item': ['rule', 'term', 'statement', '_NL'],
  92. 'rule': ['RULE template_params _COLON expansions _NL',
  93. 'RULE template_params _DOT NUMBER _COLON expansions _NL'],
  94. 'template_params': ['_LBRACE _template_params _RBRACE',
  95. ''],
  96. '_template_params': ['RULE',
  97. '_template_params _COMMA RULE'],
  98. 'expansions': ['alias',
  99. 'expansions _OR alias',
  100. 'expansions _NL _OR alias'],
  101. '?alias': ['expansion _TO RULE', 'expansion'],
  102. 'expansion': ['_expansion'],
  103. '_expansion': ['', '_expansion expr'],
  104. '?expr': ['atom',
  105. 'atom OP',
  106. 'atom TILDE NUMBER',
  107. 'atom TILDE NUMBER _DOTDOT NUMBER',
  108. ],
  109. '?atom': ['_LPAR expansions _RPAR',
  110. 'maybe',
  111. 'value'],
  112. 'value': ['terminal',
  113. 'nonterminal',
  114. 'literal',
  115. 'range',
  116. 'template_usage'],
  117. 'terminal': ['TERMINAL'],
  118. 'nonterminal': ['RULE'],
  119. '?name': ['RULE', 'TERMINAL'],
  120. 'maybe': ['_LBRA expansions _RBRA'],
  121. 'range': ['STRING _DOTDOT STRING'],
  122. 'template_usage': ['RULE _LBRACE _template_args _RBRACE'],
  123. '_template_args': ['value',
  124. '_template_args _COMMA value'],
  125. 'term': ['TERMINAL _COLON expansions _NL',
  126. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  127. 'statement': ['ignore', 'import', 'declare'],
  128. 'ignore': ['_IGNORE expansions _NL'],
  129. 'declare': ['_DECLARE _declare_args _NL'],
  130. 'import': ['_IMPORT _import_path _NL',
  131. '_IMPORT _import_path _LPAR name_list _RPAR _NL',
  132. '_IMPORT _import_path _TO name _NL'],
  133. '_import_path': ['import_lib', 'import_rel'],
  134. 'import_lib': ['_import_args'],
  135. 'import_rel': ['_DOT _import_args'],
  136. '_import_args': ['name', '_import_args _DOT name'],
  137. 'name_list': ['_name_list'],
  138. '_name_list': ['name', '_name_list _COMMA name'],
  139. '_declare_args': ['name', '_declare_args name'],
  140. 'literal': ['REGEXP', 'STRING'],
  141. }
  142. @inline_args
  143. class EBNF_to_BNF(Transformer_InPlace):
  144. def __init__(self):
  145. self.new_rules = []
  146. self.rules_by_expr = {}
  147. self.prefix = 'anon'
  148. self.i = 0
  149. self.rule_options = None
  150. def _add_recurse_rule(self, type_, expr):
  151. if expr in self.rules_by_expr:
  152. return self.rules_by_expr[expr]
  153. new_name = '__%s_%s_%d' % (self.prefix, type_, self.i)
  154. self.i += 1
  155. t = NonTerminal(new_name)
  156. tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])])
  157. self.new_rules.append((new_name, tree, self.rule_options))
  158. self.rules_by_expr[expr] = t
  159. return t
  160. def expr(self, rule, op, *args):
  161. if op.value == '?':
  162. empty = ST('expansion', [])
  163. return ST('expansions', [rule, empty])
  164. elif op.value == '+':
  165. # a : b c+ d
  166. # -->
  167. # a : b _c d
  168. # _c : _c c | c;
  169. return self._add_recurse_rule('plus', rule)
  170. elif op.value == '*':
  171. # a : b c* d
  172. # -->
  173. # a : b _c? d
  174. # _c : _c c | c;
  175. new_name = self._add_recurse_rule('star', rule)
  176. return ST('expansions', [new_name, ST('expansion', [])])
  177. elif op.value == '~':
  178. if len(args) == 1:
  179. mn = mx = int(args[0])
  180. else:
  181. mn, mx = map(int, args)
  182. if mx < mn or mn < 0:
  183. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  184. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)])
  185. assert False, op
  186. def maybe(self, rule):
  187. keep_all_tokens = self.rule_options and self.rule_options.keep_all_tokens
  188. def will_not_get_removed(sym):
  189. if isinstance(sym, NonTerminal):
  190. return not sym.name.startswith('_')
  191. if isinstance(sym, Terminal):
  192. return keep_all_tokens or not sym.filter_out
  193. assert False
  194. if any(rule.scan_values(will_not_get_removed)):
  195. empty = _EMPTY
  196. else:
  197. empty = ST('expansion', [])
  198. return ST('expansions', [rule, empty])
  199. class SimplifyRule_Visitor(Visitor):
  200. @staticmethod
  201. def _flatten(tree):
  202. while True:
  203. to_expand = [i for i, child in enumerate(tree.children)
  204. if isinstance(child, Tree) and child.data == tree.data]
  205. if not to_expand:
  206. break
  207. tree.expand_kids_by_index(*to_expand)
  208. def expansion(self, tree):
  209. # rules_list unpacking
  210. # a : b (c|d) e
  211. # -->
  212. # a : b c e | b d e
  213. #
  214. # In AST terms:
  215. # expansion(b, expansions(c, d), e)
  216. # -->
  217. # expansions( expansion(b, c, e), expansion(b, d, e) )
  218. self._flatten(tree)
  219. for i, child in enumerate(tree.children):
  220. if isinstance(child, Tree) and child.data == 'expansions':
  221. tree.data = 'expansions'
  222. tree.children = [self.visit(ST('expansion', [option if i==j else other
  223. for j, other in enumerate(tree.children)]))
  224. for option in dedup_list(child.children)]
  225. self._flatten(tree)
  226. break
  227. def alias(self, tree):
  228. rule, alias_name = tree.children
  229. if rule.data == 'expansions':
  230. aliases = []
  231. for child in tree.children[0].children:
  232. aliases.append(ST('alias', [child, alias_name]))
  233. tree.data = 'expansions'
  234. tree.children = aliases
  235. def expansions(self, tree):
  236. self._flatten(tree)
  237. # Ensure all children are unique
  238. if len(set(tree.children)) != len(tree.children):
  239. tree.children = dedup_list(tree.children) # dedup is expensive, so try to minimize its use
  240. class RuleTreeToText(Transformer):
  241. def expansions(self, x):
  242. return x
  243. def expansion(self, symbols):
  244. return symbols, None
  245. def alias(self, x):
  246. (expansion, _alias), alias = x
  247. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  248. return expansion, alias.value
  249. @inline_args
  250. class CanonizeTree(Transformer_InPlace):
  251. def tokenmods(self, *args):
  252. if len(args) == 1:
  253. return list(args)
  254. tokenmods, value = args
  255. return tokenmods + [value]
  256. class PrepareAnonTerminals(Transformer_InPlace):
  257. "Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them"
  258. def __init__(self, terminals):
  259. self.terminals = terminals
  260. self.term_set = {td.name for td in self.terminals}
  261. self.term_reverse = {td.pattern: td for td in terminals}
  262. self.i = 0
  263. self.rule_options = None
  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. filter_out = False if self.rule_options and self.rule_options.keep_all_tokens else isinstance(p, PatternStr)
  300. return Terminal(term_name, filter_out=filter_out)
  301. class _ReplaceSymbols(Transformer_InPlace):
  302. " Helper for ApplyTemplates "
  303. def __init__(self):
  304. self.names = {}
  305. def value(self, c):
  306. if len(c) == 1 and isinstance(c[0], Token) and c[0].value in self.names:
  307. return self.names[c[0].value]
  308. return self.__default__('value', c, None)
  309. def template_usage(self, c):
  310. if c[0] in self.names:
  311. return self.__default__('template_usage', [self.names[c[0]].name] + c[1:], None)
  312. return self.__default__('template_usage', c, None)
  313. class ApplyTemplates(Transformer_InPlace):
  314. " Apply the templates, creating new rules that represent the used templates "
  315. def __init__(self, rule_defs):
  316. self.rule_defs = rule_defs
  317. self.replacer = _ReplaceSymbols()
  318. self.created_templates = set()
  319. def template_usage(self, c):
  320. name = c[0]
  321. args = c[1:]
  322. result_name = "%s{%s}" % (name, ",".join(a.name for a in args))
  323. if result_name not in self.created_templates:
  324. self.created_templates.add(result_name)
  325. (_n, params, tree, options) ,= (t for t in self.rule_defs if t[0] == name)
  326. assert len(params) == len(args), args
  327. result_tree = deepcopy(tree)
  328. self.replacer.names = dict(zip(params, args))
  329. self.replacer.transform(result_tree)
  330. self.rule_defs.append((result_name, [], result_tree, deepcopy(options)))
  331. return NonTerminal(result_name)
  332. def _rfind(s, choices):
  333. return max(s.rfind(c) for c in choices)
  334. def _literal_to_pattern(literal):
  335. v = literal.value
  336. flag_start = _rfind(v, '/"')+1
  337. assert flag_start > 0
  338. flags = v[flag_start:]
  339. assert all(f in _RE_FLAGS for f in flags), flags
  340. v = v[:flag_start]
  341. assert v[0] == v[-1] and v[0] in '"/'
  342. x = v[1:-1]
  343. s = eval_escaping(x)
  344. if literal.type == 'STRING':
  345. s = s.replace('\\\\', '\\')
  346. return { 'STRING': PatternStr,
  347. 'REGEXP': PatternRE }[literal.type](s, flags)
  348. @inline_args
  349. class PrepareLiterals(Transformer_InPlace):
  350. def literal(self, literal):
  351. return ST('pattern', [_literal_to_pattern(literal)])
  352. def range(self, start, end):
  353. assert start.type == end.type == 'STRING'
  354. start = start.value[1:-1]
  355. end = end.value[1:-1]
  356. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1, (start, end, len(eval_escaping(start)), len(eval_escaping(end)))
  357. regexp = '[%s-%s]' % (start, end)
  358. return ST('pattern', [PatternRE(regexp)])
  359. class TerminalTreeToPattern(Transformer):
  360. def pattern(self, ps):
  361. p ,= ps
  362. return p
  363. def expansion(self, items):
  364. assert items
  365. if len(items) == 1:
  366. return items[0]
  367. if len({i.flags for i in items}) > 1:
  368. raise GrammarError("Lark doesn't support joining terminals with conflicting flags!")
  369. return PatternRE(''.join(i.to_regexp() for i in items), items[0].flags if items else ())
  370. def expansions(self, exps):
  371. if len(exps) == 1:
  372. return exps[0]
  373. if len({i.flags for i in exps}) > 1:
  374. raise GrammarError("Lark doesn't support joining terminals with conflicting flags!")
  375. return PatternRE('(?:%s)' % ('|'.join(i.to_regexp() for i in exps)), exps[0].flags)
  376. def expr(self, args):
  377. inner, op = args[:2]
  378. if op == '~':
  379. if len(args) == 3:
  380. op = "{%d}" % int(args[2])
  381. else:
  382. mn, mx = map(int, args[2:])
  383. if mx < mn:
  384. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  385. op = "{%d,%d}" % (mn, mx)
  386. else:
  387. assert len(args) == 2
  388. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  389. def maybe(self, expr):
  390. return self.expr(expr + ['?'])
  391. def alias(self, t):
  392. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  393. def value(self, v):
  394. return v[0]
  395. class PrepareSymbols(Transformer_InPlace):
  396. def value(self, v):
  397. v ,= v
  398. if isinstance(v, Tree):
  399. return v
  400. elif v.type == 'RULE':
  401. return NonTerminal(Str(v.value))
  402. elif v.type == 'TERMINAL':
  403. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  404. assert False
  405. def _choice_of_rules(rules):
  406. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  407. def nr_deepcopy_tree(t):
  408. "Deepcopy tree `t` without recursion"
  409. return Transformer_NonRecursive(False).transform(t)
  410. class Grammar:
  411. def __init__(self, rule_defs, term_defs, ignore):
  412. self.term_defs = term_defs
  413. self.rule_defs = rule_defs
  414. self.ignore = ignore
  415. def compile(self, start):
  416. # We change the trees in-place (to support huge grammars)
  417. # So deepcopy allows calling compile more than once.
  418. term_defs = deepcopy(list(self.term_defs))
  419. rule_defs = [(n,p,nr_deepcopy_tree(t),o) for n,p,t,o in self.rule_defs]
  420. # ===================
  421. # Compile Terminals
  422. # ===================
  423. # Convert terminal-trees to strings/regexps
  424. for name, (term_tree, priority) in term_defs:
  425. if term_tree is None: # Terminal added through %declare
  426. continue
  427. expansions = list(term_tree.find_data('expansion'))
  428. if len(expansions) == 1 and not expansions[0].children:
  429. raise GrammarError("Terminals cannot be empty (%s)" % name)
  430. transformer = PrepareLiterals() * TerminalTreeToPattern()
  431. terminals = [TerminalDef(name, transformer.transform( term_tree ), priority)
  432. for name, (term_tree, priority) in term_defs if term_tree]
  433. # =================
  434. # Compile Rules
  435. # =================
  436. # 1. Pre-process terminals
  437. anon_tokens_transf = PrepareAnonTerminals(terminals)
  438. transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals
  439. # 2. Inline Templates
  440. transformer *= ApplyTemplates(rule_defs)
  441. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  442. ebnf_to_bnf = EBNF_to_BNF()
  443. rules = []
  444. i = 0
  445. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  446. name, params, rule_tree, options = rule_defs[i]
  447. i += 1
  448. if len(params) != 0: # Dont transform templates
  449. continue
  450. rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  451. ebnf_to_bnf.rule_options = rule_options
  452. ebnf_to_bnf.prefix = name
  453. anon_tokens_transf.rule_options = rule_options
  454. tree = transformer.transform(rule_tree)
  455. res = ebnf_to_bnf.transform(tree)
  456. rules.append((name, res, options))
  457. rules += ebnf_to_bnf.new_rules
  458. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  459. # 4. Compile tree to Rule objects
  460. rule_tree_to_text = RuleTreeToText()
  461. simplify_rule = SimplifyRule_Visitor()
  462. compiled_rules = []
  463. for rule_content in rules:
  464. name, tree, options = rule_content
  465. simplify_rule.visit(tree)
  466. expansions = rule_tree_to_text.transform(tree)
  467. for i, (expansion, alias) in enumerate(expansions):
  468. if alias and name.startswith('_'):
  469. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)" % (name, alias))
  470. empty_indices = [x==_EMPTY for x in expansion]
  471. if any(empty_indices):
  472. exp_options = copy(options) or RuleOptions()
  473. exp_options.empty_indices = empty_indices
  474. expansion = [x for x in expansion if x!=_EMPTY]
  475. else:
  476. exp_options = options
  477. assert all(isinstance(x, Symbol) for x in expansion), expansion
  478. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  479. compiled_rules.append(rule)
  480. # Remove duplicates of empty rules, throw error for non-empty duplicates
  481. if len(set(compiled_rules)) != len(compiled_rules):
  482. duplicates = classify(compiled_rules, lambda x: x)
  483. for dups in duplicates.values():
  484. if len(dups) > 1:
  485. if dups[0].expansion:
  486. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  487. % ''.join('\n * %s' % i for i in dups))
  488. # Empty rule; assert all other attributes are equal
  489. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  490. # Remove duplicates
  491. compiled_rules = list(set(compiled_rules))
  492. # Filter out unused rules
  493. while True:
  494. c = len(compiled_rules)
  495. used_rules = {s for r in compiled_rules
  496. for s in r.expansion
  497. if isinstance(s, NonTerminal)
  498. and s != r.origin}
  499. used_rules |= {NonTerminal(s) for s in start}
  500. compiled_rules = [r for r in compiled_rules if r.origin in used_rules]
  501. if len(compiled_rules) == c:
  502. break
  503. # Filter out unused terminals
  504. used_terms = {t.name for r in compiled_rules
  505. for t in r.expansion
  506. if isinstance(t, Terminal)}
  507. terminals = [t for t in terminals if t.name in used_terms or t.name in self.ignore]
  508. return terminals, compiled_rules, self.ignore
  509. _imported_grammars = {}
  510. def import_grammar(grammar_path, re_, base_paths=[]):
  511. if grammar_path not in _imported_grammars:
  512. import_paths = base_paths + IMPORT_PATHS
  513. for import_path in import_paths:
  514. with suppress(IOError):
  515. joined_path = os.path.join(import_path, grammar_path)
  516. with open(joined_path, encoding='utf8') as f:
  517. text = f.read()
  518. grammar = load_grammar(text, joined_path, re_)
  519. _imported_grammars[grammar_path] = grammar
  520. break
  521. else:
  522. open(grammar_path, encoding='utf8')
  523. assert False
  524. return _imported_grammars[grammar_path]
  525. def import_from_grammar_into_namespace(grammar, namespace, aliases):
  526. """Returns all rules and terminals of grammar, prepended
  527. with a 'namespace' prefix, except for those which are aliased.
  528. """
  529. imported_terms = dict(grammar.term_defs)
  530. imported_rules = {n:(n,p,deepcopy(t),o) for n,p,t,o in grammar.rule_defs}
  531. term_defs = []
  532. rule_defs = []
  533. def rule_dependencies(symbol):
  534. if symbol.type != 'RULE':
  535. return []
  536. try:
  537. _, params, tree,_ = imported_rules[symbol]
  538. except KeyError:
  539. raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace))
  540. return _find_used_symbols(tree) - set(params)
  541. def get_namespace_name(name, params):
  542. if params is not None:
  543. try:
  544. return params[name]
  545. except KeyError:
  546. pass
  547. try:
  548. return aliases[name].value
  549. except KeyError:
  550. if name[0] == '_':
  551. return '_%s__%s' % (namespace, name[1:])
  552. return '%s__%s' % (namespace, name)
  553. to_import = list(bfs(aliases, rule_dependencies))
  554. for symbol in to_import:
  555. if symbol.type == 'TERMINAL':
  556. term_defs.append([get_namespace_name(symbol, None), imported_terms[symbol]])
  557. else:
  558. assert symbol.type == 'RULE'
  559. _, params, tree, options = imported_rules[symbol]
  560. params_map = {p: ('%s__%s' if p[0]!='_' else '_%s__%s' ) % (namespace, p) for p in params}
  561. for t in tree.iter_subtrees():
  562. for i, c in enumerate(t.children):
  563. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  564. t.children[i] = Token(c.type, get_namespace_name(c, params_map))
  565. params = [params_map[p] for p in params] # We can not rely on ordered dictionaries
  566. rule_defs.append((get_namespace_name(symbol, params_map), params, tree, options))
  567. return term_defs, rule_defs
  568. def resolve_term_references(term_defs):
  569. # TODO Solve with transitive closure (maybe)
  570. term_dict = {k:t for k, (t,_p) in term_defs}
  571. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  572. while True:
  573. changed = False
  574. for name, (token_tree, _p) in term_defs:
  575. if token_tree is None: # Terminal added through %declare
  576. continue
  577. for exp in token_tree.find_data('value'):
  578. item ,= exp.children
  579. if isinstance(item, Token):
  580. if item.type == 'RULE':
  581. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  582. if item.type == 'TERMINAL':
  583. term_value = term_dict[item]
  584. assert term_value is not None
  585. exp.children[0] = term_value
  586. changed = True
  587. if not changed:
  588. break
  589. for name, term in term_dict.items():
  590. if term: # Not just declared
  591. for child in term.children:
  592. ids = [id(x) for x in child.iter_subtrees()]
  593. if id(term) in ids:
  594. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  595. def options_from_rule(name, params, *x):
  596. if len(x) > 1:
  597. priority, expansions = x
  598. priority = int(priority)
  599. else:
  600. expansions ,= x
  601. priority = None
  602. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  603. keep_all_tokens = name.startswith('!')
  604. name = name.lstrip('!')
  605. expand1 = name.startswith('?')
  606. name = name.lstrip('?')
  607. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  608. template_source=(name if params else None))
  609. def symbols_from_strcase(expansion):
  610. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  611. @inline_args
  612. class PrepareGrammar(Transformer_InPlace):
  613. def terminal(self, name):
  614. return name
  615. def nonterminal(self, name):
  616. return name
  617. def _find_used_symbols(tree):
  618. assert tree.data == 'expansions'
  619. return {t for x in tree.find_data('expansion')
  620. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  621. class GrammarLoader:
  622. def __init__(self, re_):
  623. self.re = re_
  624. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  625. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  626. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o) for r, _p, xs, o in rules for i, x in enumerate(xs)]
  627. callback = ParseTreeBuilder(rules, ST).create_callback()
  628. lexer_conf = LexerConf(terminals, ['WS', 'COMMENT'])
  629. parser_conf = ParserConf(rules, callback, ['start'])
  630. self.parser = LALR_TraditionalLexer(lexer_conf, parser_conf, re_)
  631. self.canonize_tree = CanonizeTree()
  632. def load_grammar(self, grammar_text, grammar_name='<?>'):
  633. "Parse grammar_text, verify, and create Grammar object. Display nice messages on error."
  634. try:
  635. tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') )
  636. except UnexpectedCharacters as e:
  637. context = e.get_context(grammar_text)
  638. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  639. (e.line, e.column, grammar_name, context))
  640. except UnexpectedToken as e:
  641. context = e.get_context(grammar_text)
  642. error = e.match_examples(self.parser.parse, {
  643. 'Unclosed parenthesis': ['a: (\n'],
  644. 'Umatched closing parenthesis': ['a: )\n', 'a: [)\n', 'a: (]\n'],
  645. 'Expecting rule or terminal definition (missing colon)': ['a\n', 'a->\n', 'A->\n', 'a A\n'],
  646. 'Alias expects lowercase name': ['a: -> "a"\n'],
  647. 'Unexpected colon': ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n'],
  648. 'Misplaced operator': ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n'],
  649. 'Expecting option ("|") or a new rule or terminal definition': ['a:a\n()\n'],
  650. '%import expects a name': ['%import "a"\n'],
  651. '%ignore expects a value': ['%ignore %import\n'],
  652. })
  653. if error:
  654. raise GrammarError("%s at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  655. elif 'STRING' in e.expected:
  656. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  657. raise
  658. tree = PrepareGrammar().transform(tree)
  659. # Extract grammar items
  660. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  661. term_defs = defs.pop('term', [])
  662. rule_defs = defs.pop('rule', [])
  663. statements = defs.pop('statement', [])
  664. assert not defs
  665. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  666. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  667. rule_defs = [options_from_rule(*x) for x in rule_defs]
  668. # Execute statements
  669. ignore, imports = [], {}
  670. for (stmt,) in statements:
  671. if stmt.data == 'ignore':
  672. t ,= stmt.children
  673. ignore.append(t)
  674. elif stmt.data == 'import':
  675. if len(stmt.children) > 1:
  676. path_node, arg1 = stmt.children
  677. else:
  678. path_node, = stmt.children
  679. arg1 = None
  680. if isinstance(arg1, Tree): # Multi import
  681. dotted_path = tuple(path_node.children)
  682. names = arg1.children
  683. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  684. else: # Single import
  685. dotted_path = tuple(path_node.children[:-1])
  686. name = path_node.children[-1] # Get name from dotted path
  687. aliases = {name: arg1 or name} # Aliases if exist
  688. if path_node.data == 'import_lib': # Import from library
  689. base_paths = []
  690. else: # Relative import
  691. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  692. try:
  693. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  694. except AttributeError:
  695. base_file = None
  696. else:
  697. base_file = grammar_name # Import relative to grammar file path if external grammar file
  698. if base_file:
  699. base_paths = [os.path.split(base_file)[0]]
  700. else:
  701. base_paths = [os.path.abspath(os.path.curdir)]
  702. try:
  703. import_base_paths, import_aliases = imports[dotted_path]
  704. assert base_paths == import_base_paths, 'Inconsistent base_paths for %s.' % '.'.join(dotted_path)
  705. import_aliases.update(aliases)
  706. except KeyError:
  707. imports[dotted_path] = base_paths, aliases
  708. elif stmt.data == 'declare':
  709. for t in stmt.children:
  710. term_defs.append([t.value, (None, None)])
  711. else:
  712. assert False, stmt
  713. # import grammars
  714. for dotted_path, (base_paths, aliases) in imports.items():
  715. grammar_path = os.path.join(*dotted_path) + EXT
  716. g = import_grammar(grammar_path, self.re, base_paths=base_paths)
  717. new_td, new_rd = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases)
  718. term_defs += new_td
  719. rule_defs += new_rd
  720. # Verify correctness 1
  721. for name, _ in term_defs:
  722. if name.startswith('__'):
  723. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  724. # Handle ignore tokens
  725. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  726. # inability to handle duplicate terminals (two names, one value)
  727. ignore_names = []
  728. for t in ignore:
  729. if t.data=='expansions' and len(t.children) == 1:
  730. t2 ,= t.children
  731. if t2.data=='expansion' and len(t2.children) == 1:
  732. item ,= t2.children
  733. if item.data == 'value':
  734. item ,= item.children
  735. if isinstance(item, Token) and item.type == 'TERMINAL':
  736. ignore_names.append(item.value)
  737. continue
  738. name = '__IGNORE_%d'% len(ignore_names)
  739. ignore_names.append(name)
  740. term_defs.append((name, (t, 1)))
  741. # Verify correctness 2
  742. terminal_names = set()
  743. for name, _ in term_defs:
  744. if name in terminal_names:
  745. raise GrammarError("Terminal '%s' defined more than once" % name)
  746. terminal_names.add(name)
  747. if set(ignore_names) > terminal_names:
  748. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names))
  749. resolve_term_references(term_defs)
  750. rules = rule_defs
  751. rule_names = {}
  752. for name, params, _x, _o in rules:
  753. if name.startswith('__'):
  754. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  755. if name in rule_names:
  756. raise GrammarError("Rule '%s' defined more than once" % name)
  757. rule_names[name] = len(params)
  758. for name, params , expansions, _o in rules:
  759. for i, p in enumerate(params):
  760. if p in rule_names:
  761. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  762. if p in params[:i]:
  763. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  764. for temp in expansions.find_data('template_usage'):
  765. sym = temp.children[0]
  766. args = temp.children[1:]
  767. if sym not in params:
  768. if sym not in rule_names:
  769. raise GrammarError("Template '%s' used but not defined (in rule %s)" % (sym, name))
  770. if len(args) != rule_names[sym]:
  771. raise GrammarError("Wrong number of template arguments used for %s "
  772. "(expected %s, got %s) (in rule %s)"%(sym, rule_names[sym], len(args), name))
  773. for sym in _find_used_symbols(expansions):
  774. if sym.type == 'TERMINAL':
  775. if sym not in terminal_names:
  776. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  777. else:
  778. if sym not in rule_names and sym not in params:
  779. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  780. return Grammar(rules, term_defs, ignore_names)
  781. def load_grammar(grammar, source, re_):
  782. return GrammarLoader(re_).load_grammar(grammar, source)