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.

1435 lines
55 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. import pkgutil
  7. from ast import literal_eval
  8. from .utils import bfs, Py36, logger, classify_bool, is_id_continue, is_id_start
  9. from .lexer import Token, TerminalDef, PatternStr, PatternRE
  10. from .parse_tree_builder import ParseTreeBuilder
  11. from .parser_frontends import ParsingFrontend
  12. from .common import LexerConf, ParserConf
  13. from .grammar import RuleOptions, Rule, Terminal, NonTerminal, Symbol
  14. from .utils import classify, suppress, dedup_list, Str
  15. from .exceptions import GrammarError, UnexpectedCharacters, UnexpectedToken
  16. from .tree import Tree, SlottedTree as ST
  17. from .visitors import Transformer, Visitor, v_args, Transformer_InPlace, Transformer_NonRecursive
  18. inline_args = v_args(inline=True)
  19. __path__ = os.path.dirname(__file__)
  20. IMPORT_PATHS = ['grammars']
  21. EXT = '.lark'
  22. _RE_FLAGS = 'imslux'
  23. _EMPTY = Symbol('__empty__')
  24. _TERMINAL_NAMES = {
  25. '.' : 'DOT',
  26. ',' : 'COMMA',
  27. ':' : 'COLON',
  28. ';' : 'SEMICOLON',
  29. '+' : 'PLUS',
  30. '-' : 'MINUS',
  31. '*' : 'STAR',
  32. '/' : 'SLASH',
  33. '\\' : 'BACKSLASH',
  34. '|' : 'VBAR',
  35. '?' : 'QMARK',
  36. '!' : 'BANG',
  37. '@' : 'AT',
  38. '#' : 'HASH',
  39. '$' : 'DOLLAR',
  40. '%' : 'PERCENT',
  41. '^' : 'CIRCUMFLEX',
  42. '&' : 'AMPERSAND',
  43. '_' : 'UNDERSCORE',
  44. '<' : 'LESSTHAN',
  45. '>' : 'MORETHAN',
  46. '=' : 'EQUAL',
  47. '"' : 'DBLQUOTE',
  48. '\'' : 'QUOTE',
  49. '`' : 'BACKQUOTE',
  50. '~' : 'TILDE',
  51. '(' : 'LPAR',
  52. ')' : 'RPAR',
  53. '{' : 'LBRACE',
  54. '}' : 'RBRACE',
  55. '[' : 'LSQB',
  56. ']' : 'RSQB',
  57. '\n' : 'NEWLINE',
  58. '\r\n' : 'CRLF',
  59. '\t' : 'TAB',
  60. ' ' : 'SPACE',
  61. }
  62. # Grammar Parser
  63. TERMINALS = {
  64. '_LPAR': r'\(',
  65. '_RPAR': r'\)',
  66. '_LBRA': r'\[',
  67. '_RBRA': r'\]',
  68. '_LBRACE': r'\{',
  69. '_RBRACE': r'\}',
  70. 'OP': '[+*]|[?](?![a-z])',
  71. '_COLON': ':',
  72. '_COMMA': ',',
  73. '_OR': r'\|',
  74. '_DOT': r'\.(?!\.)',
  75. '_DOTDOT': r'\.\.',
  76. 'TILDE': '~',
  77. 'RULE': '!?[_?]?[a-z][_a-z0-9]*',
  78. 'TERMINAL': '_?[A-Z][_A-Z0-9]*',
  79. 'STRING': r'"(\\"|\\\\|[^"\n])*?"i?',
  80. 'REGEXP': r'/(?!/)(\\/|\\\\|[^/])*?/[%s]*' % _RE_FLAGS,
  81. '_NL': r'(\r?\n)+\s*',
  82. 'WS': r'[ \t]+',
  83. 'COMMENT': r'\s*//[^\n]*',
  84. '_TO': '->',
  85. '_IGNORE': r'%ignore',
  86. '_OVERRIDE': r'%override',
  87. '_DECLARE': r'%declare',
  88. '_EXTEND': r'%extend',
  89. '_IMPORT': r'%import',
  90. 'NUMBER': r'[+-]?\d+',
  91. }
  92. RULES = {
  93. 'start': ['_list'],
  94. '_list': ['_item', '_list _item'],
  95. '_item': ['rule', 'term', 'statement', '_NL'],
  96. 'rule': ['RULE template_params _COLON expansions _NL',
  97. 'RULE template_params _DOT NUMBER _COLON expansions _NL'],
  98. 'template_params': ['_LBRACE _template_params _RBRACE',
  99. ''],
  100. '_template_params': ['RULE',
  101. '_template_params _COMMA RULE'],
  102. 'expansions': ['alias',
  103. 'expansions _OR alias',
  104. 'expansions _NL _OR alias'],
  105. '?alias': ['expansion _TO RULE', 'expansion'],
  106. 'expansion': ['_expansion'],
  107. '_expansion': ['', '_expansion expr'],
  108. '?expr': ['atom',
  109. 'atom OP',
  110. 'atom TILDE NUMBER',
  111. 'atom TILDE NUMBER _DOTDOT NUMBER',
  112. ],
  113. '?atom': ['_LPAR expansions _RPAR',
  114. 'maybe',
  115. 'value'],
  116. 'value': ['terminal',
  117. 'nonterminal',
  118. 'literal',
  119. 'range',
  120. 'template_usage'],
  121. 'terminal': ['TERMINAL'],
  122. 'nonterminal': ['RULE'],
  123. '?name': ['RULE', 'TERMINAL'],
  124. 'maybe': ['_LBRA expansions _RBRA'],
  125. 'range': ['STRING _DOTDOT STRING'],
  126. 'template_usage': ['RULE _LBRACE _template_args _RBRACE'],
  127. '_template_args': ['value',
  128. '_template_args _COMMA value'],
  129. 'term': ['TERMINAL _COLON expansions _NL',
  130. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  131. 'statement': ['ignore', 'import', 'declare', 'override', 'extend'],
  132. 'override': ['_OVERRIDE rule',
  133. '_OVERRIDE term'],
  134. 'extend': ['_EXTEND rule',
  135. '_EXTEND term'],
  136. 'ignore': ['_IGNORE expansions _NL'],
  137. 'declare': ['_DECLARE _declare_args _NL'],
  138. 'import': ['_IMPORT _import_path _NL',
  139. '_IMPORT _import_path _LPAR name_list _RPAR _NL',
  140. '_IMPORT _import_path _TO name _NL'],
  141. '_import_path': ['import_lib', 'import_rel'],
  142. 'import_lib': ['_import_args'],
  143. 'import_rel': ['_DOT _import_args'],
  144. '_import_args': ['name', '_import_args _DOT name'],
  145. 'name_list': ['_name_list'],
  146. '_name_list': ['name', '_name_list _COMMA name'],
  147. '_declare_args': ['name', '_declare_args name'],
  148. 'literal': ['REGEXP', 'STRING'],
  149. }
  150. @inline_args
  151. class EBNF_to_BNF(Transformer_InPlace):
  152. def __init__(self):
  153. self.new_rules = []
  154. self.rules_by_expr = {}
  155. self.prefix = 'anon'
  156. self.i = 0
  157. self.rule_options = None
  158. def _add_recurse_rule(self, type_, expr):
  159. if expr in self.rules_by_expr:
  160. return self.rules_by_expr[expr]
  161. new_name = '__%s_%s_%d' % (self.prefix, type_, self.i)
  162. self.i += 1
  163. t = NonTerminal(new_name)
  164. tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])])
  165. self.new_rules.append((new_name, tree, self.rule_options))
  166. self.rules_by_expr[expr] = t
  167. return t
  168. def expr(self, rule, op, *args):
  169. if op.value == '?':
  170. empty = ST('expansion', [])
  171. return ST('expansions', [rule, empty])
  172. elif op.value == '+':
  173. # a : b c+ d
  174. # -->
  175. # a : b _c d
  176. # _c : _c c | c;
  177. return self._add_recurse_rule('plus', rule)
  178. elif op.value == '*':
  179. # a : b c* d
  180. # -->
  181. # a : b _c? d
  182. # _c : _c c | c;
  183. new_name = self._add_recurse_rule('star', rule)
  184. return ST('expansions', [new_name, ST('expansion', [])])
  185. elif op.value == '~':
  186. if len(args) == 1:
  187. mn = mx = int(args[0])
  188. else:
  189. mn, mx = map(int, args)
  190. if mx < mn or mn < 0:
  191. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  192. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)])
  193. assert False, op
  194. def maybe(self, rule):
  195. keep_all_tokens = self.rule_options and self.rule_options.keep_all_tokens
  196. def will_not_get_removed(sym):
  197. if isinstance(sym, NonTerminal):
  198. return not sym.name.startswith('_')
  199. if isinstance(sym, Terminal):
  200. return keep_all_tokens or not sym.filter_out
  201. assert False
  202. if any(rule.scan_values(will_not_get_removed)):
  203. empty = _EMPTY
  204. else:
  205. empty = ST('expansion', [])
  206. return ST('expansions', [rule, empty])
  207. class SimplifyRule_Visitor(Visitor):
  208. @staticmethod
  209. def _flatten(tree):
  210. while True:
  211. to_expand = [i for i, child in enumerate(tree.children)
  212. if isinstance(child, Tree) and child.data == tree.data]
  213. if not to_expand:
  214. break
  215. tree.expand_kids_by_index(*to_expand)
  216. def expansion(self, tree):
  217. # rules_list unpacking
  218. # a : b (c|d) e
  219. # -->
  220. # a : b c e | b d e
  221. #
  222. # In AST terms:
  223. # expansion(b, expansions(c, d), e)
  224. # -->
  225. # expansions( expansion(b, c, e), expansion(b, d, e) )
  226. self._flatten(tree)
  227. for i, child in enumerate(tree.children):
  228. if isinstance(child, Tree) and child.data == 'expansions':
  229. tree.data = 'expansions'
  230. tree.children = [self.visit(ST('expansion', [option if i == j else other
  231. for j, other in enumerate(tree.children)]))
  232. for option in dedup_list(child.children)]
  233. self._flatten(tree)
  234. break
  235. def alias(self, tree):
  236. rule, alias_name = tree.children
  237. if rule.data == 'expansions':
  238. aliases = []
  239. for child in tree.children[0].children:
  240. aliases.append(ST('alias', [child, alias_name]))
  241. tree.data = 'expansions'
  242. tree.children = aliases
  243. def expansions(self, tree):
  244. self._flatten(tree)
  245. # Ensure all children are unique
  246. if len(set(tree.children)) != len(tree.children):
  247. tree.children = dedup_list(tree.children) # dedup is expensive, so try to minimize its use
  248. class RuleTreeToText(Transformer):
  249. def expansions(self, x):
  250. return x
  251. def expansion(self, symbols):
  252. return symbols, None
  253. def alias(self, x):
  254. (expansion, _alias), alias = x
  255. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  256. return expansion, alias.value
  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. self.rule_options = None
  265. @inline_args
  266. def pattern(self, p):
  267. value = p.value
  268. if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags:
  269. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  270. term_name = None
  271. if isinstance(p, PatternStr):
  272. try:
  273. # If already defined, use the user-defined terminal name
  274. term_name = self.term_reverse[p].name
  275. except KeyError:
  276. # Try to assign an indicative anon-terminal name
  277. try:
  278. term_name = _TERMINAL_NAMES[value]
  279. except KeyError:
  280. if is_id_continue(value) and is_id_start(value[0]) and value.upper() not in self.term_set:
  281. term_name = value.upper()
  282. if term_name in self.term_set:
  283. term_name = None
  284. elif isinstance(p, PatternRE):
  285. if p in self.term_reverse: # Kind of a weird placement.name
  286. term_name = self.term_reverse[p].name
  287. else:
  288. assert False, p
  289. if term_name is None:
  290. term_name = '__ANON_%d' % self.i
  291. self.i += 1
  292. if term_name not in self.term_set:
  293. assert p not in self.term_reverse
  294. self.term_set.add(term_name)
  295. termdef = TerminalDef(term_name, p)
  296. self.term_reverse[p] = termdef
  297. self.terminals.append(termdef)
  298. filter_out = False if self.rule_options and self.rule_options.keep_all_tokens else isinstance(p, PatternStr)
  299. return Terminal(term_name, filter_out=filter_out)
  300. class _ReplaceSymbols(Transformer_InPlace):
  301. """Helper for ApplyTemplates"""
  302. def __init__(self):
  303. self.names = {}
  304. def value(self, c):
  305. if len(c) == 1 and isinstance(c[0], Token) and c[0].value in self.names:
  306. return self.names[c[0].value]
  307. return self.__default__('value', c, None)
  308. def template_usage(self, c):
  309. if c[0] in self.names:
  310. return self.__default__('template_usage', [self.names[c[0]].name] + c[1:], None)
  311. return self.__default__('template_usage', c, None)
  312. class ApplyTemplates(Transformer_InPlace):
  313. """Apply the templates, creating new rules that represent the used templates"""
  314. def __init__(self, rule_defs):
  315. self.rule_defs = rule_defs
  316. self.replacer = _ReplaceSymbols()
  317. self.created_templates = set()
  318. def template_usage(self, c):
  319. name = c[0]
  320. args = c[1:]
  321. result_name = "%s{%s}" % (name, ",".join(a.name for a in args))
  322. if result_name not in self.created_templates:
  323. self.created_templates.add(result_name)
  324. (_n, params, tree, options) ,= (t for t in self.rule_defs if t[0] == name)
  325. assert len(params) == len(args), args
  326. result_tree = deepcopy(tree)
  327. self.replacer.names = dict(zip(params, args))
  328. self.replacer.transform(result_tree)
  329. self.rule_defs.append((result_name, [], result_tree, deepcopy(options)))
  330. return NonTerminal(result_name)
  331. def _rfind(s, choices):
  332. return max(s.rfind(c) for c in choices)
  333. def eval_escaping(s):
  334. w = ''
  335. i = iter(s)
  336. for n in i:
  337. w += n
  338. if n == '\\':
  339. try:
  340. n2 = next(i)
  341. except StopIteration:
  342. raise GrammarError("Literal ended unexpectedly (bad escaping): `%r`" % s)
  343. if n2 == '\\':
  344. w += '\\\\'
  345. elif n2 not in 'uxnftr':
  346. w += '\\'
  347. w += n2
  348. w = w.replace('\\"', '"').replace("'", "\\'")
  349. to_eval = "u'''%s'''" % w
  350. try:
  351. s = literal_eval(to_eval)
  352. except SyntaxError as e:
  353. raise GrammarError(s, e)
  354. return s
  355. def _literal_to_pattern(literal):
  356. v = literal.value
  357. flag_start = _rfind(v, '/"')+1
  358. assert flag_start > 0
  359. flags = v[flag_start:]
  360. assert all(f in _RE_FLAGS for f in flags), flags
  361. if literal.type == 'STRING' and '\n' in v:
  362. raise GrammarError('You cannot put newlines in string literals')
  363. if literal.type == 'REGEXP' and '\n' in v and 'x' not in flags:
  364. raise GrammarError('You can only use newlines in regular expressions '
  365. 'with the `x` (verbose) flag')
  366. v = v[:flag_start]
  367. assert v[0] == v[-1] and v[0] in '"/'
  368. x = v[1:-1]
  369. s = eval_escaping(x)
  370. if literal.type == 'STRING':
  371. s = s.replace('\\\\', '\\')
  372. return PatternStr(s, flags, raw=literal.value)
  373. elif literal.type == 'REGEXP':
  374. return PatternRE(s, flags, raw=literal.value)
  375. else:
  376. assert False, 'Invariant failed: literal.type not in ["STRING", "REGEXP"]'
  377. @inline_args
  378. class PrepareLiterals(Transformer_InPlace):
  379. def literal(self, literal):
  380. return ST('pattern', [_literal_to_pattern(literal)])
  381. def range(self, start, end):
  382. assert start.type == end.type == 'STRING'
  383. start = start.value[1:-1]
  384. end = end.value[1:-1]
  385. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1
  386. regexp = '[%s-%s]' % (start, end)
  387. return ST('pattern', [PatternRE(regexp)])
  388. def _make_joined_pattern(regexp, flags_set):
  389. # In Python 3.6, a new syntax for flags was introduced, that allows us to restrict the scope
  390. # of flags to a specific regexp group. We are already using it in `lexer.Pattern._get_flags`
  391. # However, for prior Python versions, we still need to use global flags, so we have to make sure
  392. # that there are no flag collisions when we merge several terminals.
  393. flags = ()
  394. if not Py36:
  395. if len(flags_set) > 1:
  396. raise GrammarError("Lark doesn't support joining terminals with conflicting flags in python <3.6!")
  397. elif len(flags_set) == 1:
  398. flags ,= flags_set
  399. return PatternRE(regexp, flags)
  400. class TerminalTreeToPattern(Transformer):
  401. def pattern(self, ps):
  402. p ,= ps
  403. return p
  404. def expansion(self, items):
  405. assert items
  406. if len(items) == 1:
  407. return items[0]
  408. pattern = ''.join(i.to_regexp() for i in items)
  409. return _make_joined_pattern(pattern, {i.flags for i in items})
  410. def expansions(self, exps):
  411. if len(exps) == 1:
  412. return exps[0]
  413. pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps))
  414. return _make_joined_pattern(pattern, {i.flags for i in exps})
  415. def expr(self, args):
  416. inner, op = args[:2]
  417. if op == '~':
  418. if len(args) == 3:
  419. op = "{%d}" % int(args[2])
  420. else:
  421. mn, mx = map(int, args[2:])
  422. if mx < mn:
  423. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  424. op = "{%d,%d}" % (mn, mx)
  425. else:
  426. assert len(args) == 2
  427. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  428. def maybe(self, expr):
  429. return self.expr(expr + ['?'])
  430. def alias(self, t):
  431. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  432. def value(self, v):
  433. return v[0]
  434. class PrepareSymbols(Transformer_InPlace):
  435. def value(self, v):
  436. v ,= v
  437. if isinstance(v, Tree):
  438. return v
  439. elif v.type == 'RULE':
  440. return NonTerminal(Str(v.value))
  441. elif v.type == 'TERMINAL':
  442. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  443. assert False
  444. def _choice_of_rules(rules):
  445. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  446. def nr_deepcopy_tree(t):
  447. """Deepcopy tree `t` without recursion"""
  448. return Transformer_NonRecursive(False).transform(t)
  449. class Grammar:
  450. def __init__(self, rule_defs, term_defs, ignore):
  451. self.term_defs = term_defs
  452. self.rule_defs = rule_defs
  453. self.ignore = ignore
  454. def compile(self, start, terminals_to_keep):
  455. # We change the trees in-place (to support huge grammars)
  456. # So deepcopy allows calling compile more than once.
  457. term_defs = deepcopy(list(self.term_defs))
  458. rule_defs = [(n,p,nr_deepcopy_tree(t),o) for n,p,t,o in self.rule_defs]
  459. # ===================
  460. # Compile Terminals
  461. # ===================
  462. # Convert terminal-trees to strings/regexps
  463. for name, (term_tree, priority) in term_defs:
  464. if term_tree is None: # Terminal added through %declare
  465. continue
  466. expansions = list(term_tree.find_data('expansion'))
  467. if len(expansions) == 1 and not expansions[0].children:
  468. raise GrammarError("Terminals cannot be empty (%s)" % name)
  469. transformer = PrepareLiterals() * TerminalTreeToPattern()
  470. terminals = [TerminalDef(name, transformer.transform(term_tree), priority)
  471. for name, (term_tree, priority) in term_defs if term_tree]
  472. # =================
  473. # Compile Rules
  474. # =================
  475. # 1. Pre-process terminals
  476. anon_tokens_transf = PrepareAnonTerminals(terminals)
  477. transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals
  478. # 2. Inline Templates
  479. transformer *= ApplyTemplates(rule_defs)
  480. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  481. ebnf_to_bnf = EBNF_to_BNF()
  482. rules = []
  483. i = 0
  484. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  485. name, params, rule_tree, options = rule_defs[i]
  486. i += 1
  487. if len(params) != 0: # Dont transform templates
  488. continue
  489. rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  490. ebnf_to_bnf.rule_options = rule_options
  491. ebnf_to_bnf.prefix = name
  492. anon_tokens_transf.rule_options = rule_options
  493. tree = transformer.transform(rule_tree)
  494. res = ebnf_to_bnf.transform(tree)
  495. rules.append((name, res, options))
  496. rules += ebnf_to_bnf.new_rules
  497. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  498. # 4. Compile tree to Rule objects
  499. rule_tree_to_text = RuleTreeToText()
  500. simplify_rule = SimplifyRule_Visitor()
  501. compiled_rules = []
  502. for rule_content in rules:
  503. name, tree, options = rule_content
  504. simplify_rule.visit(tree)
  505. expansions = rule_tree_to_text.transform(tree)
  506. for i, (expansion, alias) in enumerate(expansions):
  507. if alias and name.startswith('_'):
  508. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)"% (name, alias))
  509. empty_indices = [x==_EMPTY for x in expansion]
  510. if any(empty_indices):
  511. exp_options = copy(options) or RuleOptions()
  512. exp_options.empty_indices = empty_indices
  513. expansion = [x for x in expansion if x!=_EMPTY]
  514. else:
  515. exp_options = options
  516. assert all(isinstance(x, Symbol) for x in expansion), expansion
  517. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  518. compiled_rules.append(rule)
  519. # Remove duplicates of empty rules, throw error for non-empty duplicates
  520. if len(set(compiled_rules)) != len(compiled_rules):
  521. duplicates = classify(compiled_rules, lambda x: x)
  522. for dups in duplicates.values():
  523. if len(dups) > 1:
  524. if dups[0].expansion:
  525. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  526. % ''.join('\n * %s' % i for i in dups))
  527. # Empty rule; assert all other attributes are equal
  528. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  529. # Remove duplicates
  530. compiled_rules = list(set(compiled_rules))
  531. # Filter out unused rules
  532. while True:
  533. c = len(compiled_rules)
  534. used_rules = {s for r in compiled_rules
  535. for s in r.expansion
  536. if isinstance(s, NonTerminal)
  537. and s != r.origin}
  538. used_rules |= {NonTerminal(s) for s in start}
  539. compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules)
  540. for r in unused:
  541. logger.debug("Unused rule: %s", r)
  542. if len(compiled_rules) == c:
  543. break
  544. # Filter out unused terminals
  545. used_terms = {t.name for r in compiled_rules
  546. for t in r.expansion
  547. if isinstance(t, Terminal)}
  548. terminals, unused = classify_bool(terminals, lambda t: t.name in used_terms or t.name in self.ignore or t.name in terminals_to_keep)
  549. if unused:
  550. logger.debug("Unused terminals: %s", [t.name for t in unused])
  551. return terminals, compiled_rules, self.ignore
  552. class PackageResource(object):
  553. """
  554. Represents a path inside a Package. Used by `FromPackageLoader`
  555. """
  556. def __init__(self, pkg_name, path):
  557. self.pkg_name = pkg_name
  558. self.path = path
  559. def __str__(self):
  560. return "<%s: %s>" % (self.pkg_name, self.path)
  561. def __repr__(self):
  562. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.path)
  563. class FromPackageLoader(object):
  564. """
  565. Provides a simple way of creating custom import loaders that load from packages via ``pkgutil.get_data`` instead of using `open`.
  566. This allows them to be compatible even from within zip files.
  567. Relative imports are handled, so you can just freely use them.
  568. pkg_name: The name of the package. You can probably provide `__name__` most of the time
  569. search_paths: All the path that will be search on absolute imports.
  570. """
  571. def __init__(self, pkg_name, search_paths=("", )):
  572. self.pkg_name = pkg_name
  573. self.search_paths = search_paths
  574. def __repr__(self):
  575. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.search_paths)
  576. def __call__(self, base_path, grammar_path):
  577. if base_path is None:
  578. to_try = self.search_paths
  579. else:
  580. # Check whether or not the importing grammar was loaded by this module.
  581. if not isinstance(base_path, PackageResource) or base_path.pkg_name != self.pkg_name:
  582. # Technically false, but FileNotFound doesn't exist in python2.7, and this message should never reach the end user anyway
  583. raise IOError()
  584. to_try = [base_path.path]
  585. for path in to_try:
  586. full_path = os.path.join(path, grammar_path)
  587. try:
  588. text = pkgutil.get_data(self.pkg_name, full_path)
  589. except IOError:
  590. continue
  591. else:
  592. return PackageResource(self.pkg_name, full_path), text.decode()
  593. raise IOError()
  594. stdlib_loader = FromPackageLoader('lark', IMPORT_PATHS)
  595. _imported_grammars = {}
  596. def import_from_grammar_into_namespace(grammar, namespace, aliases):
  597. """Returns all rules and terminals of grammar, prepended
  598. with a 'namespace' prefix, except for those which are aliased.
  599. """
  600. imported_terms = {n: (deepcopy(e), p) for n, (e, p) in grammar.term_defs}
  601. imported_rules = {n: (n, p, deepcopy(t), o) for n, p, t, o in grammar.rule_defs}
  602. term_defs = []
  603. rule_defs = []
  604. def rule_dependencies(symbol):
  605. if symbol.type != 'RULE':
  606. return []
  607. try:
  608. _, params, tree,_ = imported_rules[symbol]
  609. except KeyError:
  610. raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace))
  611. return _find_used_symbols(tree) - set(params)
  612. def get_namespace_name(name, params):
  613. if params is not None:
  614. try:
  615. return params[name]
  616. except KeyError:
  617. pass
  618. try:
  619. return aliases[name].value
  620. except KeyError:
  621. if name[0] == '_':
  622. return '_%s__%s' % (namespace, name[1:])
  623. return '%s__%s' % (namespace, name)
  624. to_import = list(bfs(aliases, rule_dependencies))
  625. for symbol in to_import:
  626. if symbol.type == 'TERMINAL':
  627. term_defs.append([get_namespace_name(symbol, None), imported_terms[symbol]])
  628. else:
  629. assert symbol.type == 'RULE'
  630. _, params, tree, options = imported_rules[symbol]
  631. params_map = {p: ('%s__%s' if p[0]!='_' else '_%s__%s') % (namespace, p) for p in params}
  632. for t in tree.iter_subtrees():
  633. for i, c in enumerate(t.children):
  634. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  635. t.children[i] = Token(c.type, get_namespace_name(c, params_map))
  636. params = [params_map[p] for p in params] # We can not rely on ordered dictionaries
  637. rule_defs.append((get_namespace_name(symbol, params_map), params, tree, options))
  638. return term_defs, rule_defs
  639. def resolve_term_references(term_defs):
  640. # TODO Solve with transitive closure (maybe)
  641. term_dict = {k:t for k, (t,_p) in term_defs}
  642. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  643. while True:
  644. changed = False
  645. for name, (token_tree, _p) in term_defs:
  646. if token_tree is None: # Terminal added through %declare
  647. continue
  648. for exp in token_tree.find_data('value'):
  649. item ,= exp.children
  650. if isinstance(item, Token):
  651. if item.type == 'RULE':
  652. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  653. if item.type == 'TERMINAL':
  654. term_value = term_dict[item]
  655. assert term_value is not None
  656. exp.children[0] = term_value
  657. changed = True
  658. if not changed:
  659. break
  660. for name, term in term_dict.items():
  661. if term: # Not just declared
  662. for child in term.children:
  663. ids = [id(x) for x in child.iter_subtrees()]
  664. if id(term) in ids:
  665. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  666. def options_from_rule(name, params, *x):
  667. if len(x) > 1:
  668. priority, expansions = x
  669. priority = int(priority)
  670. else:
  671. expansions ,= x
  672. priority = None
  673. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  674. keep_all_tokens = name.startswith('!')
  675. name = name.lstrip('!')
  676. expand1 = name.startswith('?')
  677. name = name.lstrip('?')
  678. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  679. template_source=(name if params else None))
  680. def symbols_from_strcase(expansion):
  681. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  682. @inline_args
  683. class PrepareGrammar(Transformer_InPlace):
  684. def terminal(self, name):
  685. return name
  686. def nonterminal(self, name):
  687. return name
  688. def _find_used_symbols(tree):
  689. assert tree.data == 'expansions'
  690. return {t for x in tree.find_data('expansion')
  691. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  692. def extend_expansions(tree, new):
  693. assert isinstance(tree, Tree) and tree.data == 'expansions'
  694. assert isinstance(new, Tree) and new.data == 'expansions'
  695. while len(tree.children) == 2:
  696. assert isinstance(tree.children[0], Tree) and tree.children[0].data == 'expansions', tree
  697. tree = tree.children[0]
  698. tree.children.insert(0, new)
  699. def _grammar_parser():
  700. try:
  701. return _grammar_parser.cache
  702. except AttributeError:
  703. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  704. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  705. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o)
  706. for r, _p, xs, o in rules for i, x in enumerate(xs)]
  707. callback = ParseTreeBuilder(rules, ST).create_callback()
  708. import re
  709. lexer_conf = LexerConf(terminals, re, ['WS', 'COMMENT'])
  710. parser_conf = ParserConf(rules, callback, ['start'])
  711. lexer_conf.lexer_type = 'standard'
  712. parser_conf.parser_type = 'lalr'
  713. _grammar_parser.cache = ParsingFrontend(lexer_conf, parser_conf, {})
  714. return _grammar_parser.cache
  715. GRAMMAR_ERRORS = [
  716. ('Unclosed parenthesis', ['a: (\n']),
  717. ('Unmatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']),
  718. ('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']),
  719. ('Illegal name for rules or terminals', ['Aa:\n']),
  720. ('Alias expects lowercase name', ['a: -> "a"\n']),
  721. ('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']),
  722. ('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']),
  723. ('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']),
  724. ('Terminal names cannot contain dots', ['A.B\n']),
  725. ('%import expects a name', ['%import "a"\n']),
  726. ('%ignore expects a value', ['%ignore %import\n']),
  727. ]
  728. def _parse_grammar(text, name, start='start'):
  729. try:
  730. return PrepareGrammar().transform(_grammar_parser().parse(text + '\n', start))
  731. except UnexpectedCharacters as e:
  732. context = e.get_context(text)
  733. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  734. (e.line, e.column, name, context))
  735. except UnexpectedToken as e:
  736. context = e.get_context(text)
  737. error = e.match_examples(_grammar_parser().parse, GRAMMAR_ERRORS, use_accepts=True)
  738. if error:
  739. raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  740. elif 'STRING' in e.expected:
  741. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  742. raise
  743. class GrammarLoader:
  744. def __init__(self, global_keep_all_tokens=False):
  745. self.global_keep_all_tokens = global_keep_all_tokens
  746. def import_grammar(self, grammar_path, base_path=None, import_paths=[]):
  747. if grammar_path not in _imported_grammars:
  748. # import_paths take priority over base_path since they should handle relative imports and ignore everything else.
  749. to_try = import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
  750. for source in to_try:
  751. try:
  752. if callable(source):
  753. joined_path, text = source(base_path, grammar_path)
  754. else:
  755. joined_path = os.path.join(source, grammar_path)
  756. with open(joined_path, encoding='utf8') as f:
  757. text = f.read()
  758. except IOError:
  759. continue
  760. else:
  761. grammar = self.load_grammar(text, joined_path, import_paths)
  762. _imported_grammars[grammar_path] = grammar
  763. break
  764. else:
  765. # Search failed. Make Python throw a nice error.
  766. open(grammar_path, encoding='utf8')
  767. assert False
  768. return _imported_grammars[grammar_path]
  769. def load_grammar(self, grammar_text, grammar_name='<?>', import_paths=[]):
  770. """Parse grammar_text, verify, and create Grammar object. Display nice messages on error."""
  771. tree = _parse_grammar(grammar_text+'\n', grammar_name)
  772. # tree = PrepareGrammar().transform(tree)
  773. # Extract grammar items
  774. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  775. term_defs = defs.pop('term', [])
  776. rule_defs = defs.pop('rule', [])
  777. statements = defs.pop('statement', [])
  778. assert not defs
  779. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  780. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  781. rule_defs = [options_from_rule(*x) for x in rule_defs]
  782. # Execute statements
  783. ignore, imports = [], {}
  784. overriding_rules = []
  785. overriding_terms = []
  786. extend_rules = []
  787. extend_terms = []
  788. for (stmt,) in statements:
  789. if stmt.data == 'ignore':
  790. t ,= stmt.children
  791. ignore.append(t)
  792. elif stmt.data == 'import':
  793. if len(stmt.children) > 1:
  794. path_node, arg1 = stmt.children
  795. else:
  796. path_node ,= stmt.children
  797. arg1 = None
  798. if isinstance(arg1, Tree): # Multi import
  799. dotted_path = tuple(path_node.children)
  800. names = arg1.children
  801. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  802. else: # Single import
  803. dotted_path = tuple(path_node.children[:-1])
  804. name = path_node.children[-1] # Get name from dotted path
  805. aliases = {name: arg1 or name} # Aliases if exist
  806. if path_node.data == 'import_lib': # Import from library
  807. base_path = None
  808. else: # Relative import
  809. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  810. try:
  811. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  812. except AttributeError:
  813. base_file = None
  814. else:
  815. base_file = grammar_name # Import relative to grammar file path if external grammar file
  816. if base_file:
  817. if isinstance(base_file, PackageResource):
  818. base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
  819. else:
  820. base_path = os.path.split(base_file)[0]
  821. else:
  822. base_path = os.path.abspath(os.path.curdir)
  823. try:
  824. import_base_path, import_aliases = imports[dotted_path]
  825. assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
  826. import_aliases.update(aliases)
  827. except KeyError:
  828. imports[dotted_path] = base_path, aliases
  829. elif stmt.data == 'declare':
  830. for t in stmt.children:
  831. term_defs.append([t.value, (None, None)])
  832. elif stmt.data == 'override':
  833. r ,= stmt.children
  834. if r.data == 'rule':
  835. overriding_rules.append(options_from_rule(*r.children))
  836. else:
  837. if len(r.children) == 2:
  838. overriding_terms.append((r.children[0].value, (r.children[1], 1)))
  839. else:
  840. overriding_terms.append((r.children[0].value, (r.children[2], int(r.children[1]))))
  841. elif stmt.data == 'extend':
  842. r ,= stmt.children
  843. if r.data == 'rule':
  844. extend_rules.append(options_from_rule(*r.children))
  845. else:
  846. if len(r.children) == 2:
  847. extend_terms.append((r.children[0].value, (r.children[1], 1)))
  848. else:
  849. extend_terms.append((r.children[0].value, (r.children[2], int(r.children[1]))))
  850. else:
  851. assert False, stmt
  852. # import grammars
  853. for dotted_path, (base_path, aliases) in imports.items():
  854. grammar_path = os.path.join(*dotted_path) + EXT
  855. g = self.import_grammar(grammar_path, base_path=base_path, import_paths=import_paths)
  856. new_td, new_rd = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases)
  857. term_defs += new_td
  858. rule_defs += new_rd
  859. # replace rules by overridding rules, according to name
  860. for r in overriding_rules:
  861. name = r[0]
  862. # remove overridden rule from rule_defs
  863. overridden, rule_defs = classify_bool(rule_defs, lambda r: r[0] == name) # FIXME inefficient
  864. if not overridden:
  865. raise GrammarError("Cannot override a nonexisting rule: %s" % name)
  866. rule_defs.append(r)
  867. # Same for terminals
  868. for t in overriding_terms:
  869. name = t[0]
  870. # remove overridden rule from rule_defs
  871. overridden, term_defs = classify_bool(term_defs, lambda t: t[0] == name) # FIXME inefficient
  872. if not overridden:
  873. raise GrammarError("Cannot override a nonexisting terminal: %s" % name)
  874. term_defs.append(t)
  875. # Extend the definition of rules by adding new entries to the `expansions` node
  876. for r in extend_rules:
  877. name = r[0]
  878. # remove overridden rule from rule_defs
  879. for old in rule_defs:
  880. if old[0] == name:
  881. if len(old[1]) != len(r[1]):
  882. raise GrammarError("Cannot extend templates with different parameters: %s" % name)
  883. extend_expansions(old[2], r[2])
  884. break
  885. else:
  886. raise GrammarError("Can't extend rule %s as it wasn't defined before" % name)
  887. # Same for terminals
  888. for name, (e, _) in extend_terms:
  889. for old in term_defs:
  890. if old[0] == name:
  891. extend_expansions(old[1][0], e)
  892. break
  893. else:
  894. raise GrammarError("Can't extend terminal %s as it wasn't defined before" % name)
  895. ## Handle terminals
  896. # Verify correctness 1
  897. for name, _ in term_defs:
  898. if name.startswith('__'):
  899. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  900. # Handle ignore tokens
  901. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  902. # inability to handle duplicate terminals (two names, one value)
  903. ignore_names = []
  904. for t in ignore:
  905. if t.data=='expansions' and len(t.children) == 1:
  906. t2 ,= t.children
  907. if t2.data=='expansion' and len(t2.children) == 1:
  908. item ,= t2.children
  909. if item.data == 'value':
  910. item ,= item.children
  911. if isinstance(item, Token) and item.type == 'TERMINAL':
  912. ignore_names.append(item.value)
  913. continue
  914. name = '__IGNORE_%d'% len(ignore_names)
  915. ignore_names.append(name)
  916. term_defs.append((name, (t, 1)))
  917. # Verify correctness 2
  918. terminal_names = set()
  919. for name, _ in term_defs:
  920. if name in terminal_names:
  921. raise GrammarError("Terminal '%s' defined more than once" % name)
  922. terminal_names.add(name)
  923. if set(ignore_names) > terminal_names:
  924. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names))
  925. resolve_term_references(term_defs)
  926. ## Handle rules
  927. rule_names = {}
  928. for name, params, _x, option in rule_defs:
  929. # We can't just simply not throw away the tokens later, we need option.keep_all_tokens to correctly generate maybe_placeholders
  930. if self.global_keep_all_tokens:
  931. option.keep_all_tokens = True
  932. if name.startswith('__'):
  933. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  934. if name in rule_names:
  935. raise GrammarError("Rule '%s' defined more than once" % name)
  936. rule_names[name] = len(params)
  937. for name, params , expansions, _o in rule_defs:
  938. for i, p in enumerate(params):
  939. if p in rule_names:
  940. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  941. if p in params[:i]:
  942. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  943. for temp in expansions.find_data('template_usage'):
  944. sym = temp.children[0]
  945. args = temp.children[1:]
  946. if sym not in params:
  947. if sym not in rule_names:
  948. raise GrammarError("Template '%s' used but not defined (in rule %s)" % (sym, name))
  949. if len(args) != rule_names[sym]:
  950. raise GrammarError("Wrong number of template arguments used for %s "
  951. "(expected %s, got %s) (in rule %s)" % (sym, rule_names[sym], len(args), name))
  952. for sym in _find_used_symbols(expansions):
  953. if sym.type == 'TERMINAL':
  954. if sym not in terminal_names:
  955. raise GrammarError("Terminal '%s' used but not defined (in rule %s)" % (sym, name))
  956. else:
  957. if sym not in rule_names and sym not in params:
  958. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  959. return Grammar(rule_defs, term_defs, ignore_names)
  960. class GrammarBuilder:
  961. def __init__(self, global_keep_all_tokens=False, import_paths=None):
  962. self.global_keep_all_tokens = global_keep_all_tokens
  963. self.import_paths = import_paths or []
  964. self._definitions = {}
  965. self._ignore_names = []
  966. def _is_term(self, name):
  967. return name.isupper()
  968. def _grammar_error(self, msg, *names):
  969. args = {}
  970. for i, name in enumerate(names, start=1):
  971. postfix = '' if i == 1 else str(i)
  972. args['name'+ postfix] = name
  973. args['type' + postfix] = lowercase_type = ("rule", "terminal")[self._is_term(name)]
  974. args['Type' + postfix] = lowercase_type.title()
  975. raise GrammarError(msg.format(**args))
  976. def _check_options(self, name, options):
  977. if self._is_term(name):
  978. if options is None:
  979. options = 1
  980. elif not isinstance(options, int):
  981. raise GrammarError("Terminal require a single int as 'options' (e.g. priority)")
  982. else:
  983. if options is None:
  984. options = RuleOptions()
  985. elif not isinstance(options, RuleOptions):
  986. raise GrammarError("Rules require a RuleOptions instance as 'options'")
  987. if self.global_keep_all_tokens:
  988. options.keep_all_tokens = True
  989. return options
  990. def _define(self, name, exp, params=(), options=None, override=False):
  991. if (name in self._definitions) ^ override:
  992. if override:
  993. self._grammar_error("Cannot override a nonexisting {type} {name}", name)
  994. else:
  995. self._grammar_error("{Type} '{name}' defined more than once", name)
  996. if name.startswith('__'):
  997. self._grammar_error('Names starting with double-underscore are reserved (Error at {name})', name)
  998. self._definitions[name] = (params, exp, self._check_options(name, options))
  999. def _extend(self, name, exp, params=(), options=None):
  1000. if name not in self._definitions:
  1001. self._grammar_error("Can't extend {type} {name} as it wasn't defined before", name)
  1002. if tuple(params) != tuple(self._definitions[name][0]):
  1003. self._grammar_error("Cannot extend {type} with different parameters: {name}", name)
  1004. # TODO: think about what to do with 'options'
  1005. old_expansions = self._definitions[name][1]
  1006. extend_expansions(old_expansions, exp)
  1007. def _ignore(self, exp_or_name):
  1008. if isinstance(exp_or_name, str):
  1009. self._ignore_names.append(exp_or_name)
  1010. else:
  1011. assert isinstance(exp_or_name, Tree)
  1012. t = exp_or_name
  1013. if t.data == 'expansions' and len(t.children) == 1:
  1014. t2 ,= t.children
  1015. if t2.data=='expansion' and len(t2.children) == 1:
  1016. item ,= t2.children
  1017. if item.data == 'value':
  1018. item ,= item.children
  1019. if isinstance(item, Token) and item.type == 'TERMINAL':
  1020. self._ignore_names.append(item.value)
  1021. return
  1022. name = '__IGNORE_%d'% len(self._ignore_names)
  1023. self._ignore_names.append(name)
  1024. self._definitions[name] = ((), t, 1)
  1025. def _declare(self, *names):
  1026. for name in names:
  1027. self._define(name, None)
  1028. def _mangle_exp(self, exp, mangle):
  1029. if mangle is None:
  1030. return exp
  1031. exp = deepcopy(exp) # TODO: is this needed
  1032. for t in exp.iter_subtrees():
  1033. for i, c in enumerate(t.children):
  1034. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  1035. t.children[i] = Token(c.type, mangle(c.value))
  1036. return exp
  1037. def _unpack_definition(self, tree, mangle):
  1038. if tree.data == 'rule':
  1039. name, params, exp, opts = options_from_rule(*tree.children)
  1040. else:
  1041. name = tree.children[0].value
  1042. params = ()
  1043. opts = int(tree.children[1]) if len(tree.children) == 3 else 1 # priority
  1044. exp = tree.children[-1]
  1045. if mangle is not None:
  1046. params = tuple(mangle(p) for p in params)
  1047. name = mangle(name)
  1048. exp = self._mangle_exp(exp, mangle)
  1049. return name, exp, params, opts
  1050. def _unpack_import(self, stmt, grammar_name):
  1051. if len(stmt.children) > 1:
  1052. path_node, arg1 = stmt.children
  1053. else:
  1054. path_node, = stmt.children
  1055. arg1 = None
  1056. if isinstance(arg1, Tree): # Multi import
  1057. dotted_path = tuple(path_node.children)
  1058. names = arg1.children
  1059. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  1060. else: # Single import
  1061. dotted_path = tuple(path_node.children[:-1])
  1062. name = path_node.children[-1] # Get name from dotted path
  1063. aliases = {name.value: (arg1 or name).value} # Aliases if exist
  1064. if path_node.data == 'import_lib': # Import from library
  1065. base_path = None
  1066. else: # Relative import
  1067. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  1068. try:
  1069. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  1070. except AttributeError:
  1071. base_file = None
  1072. else:
  1073. base_file = grammar_name # Import relative to grammar file path if external grammar file
  1074. if base_file:
  1075. if isinstance(base_file, PackageResource):
  1076. base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
  1077. else:
  1078. base_path = os.path.split(base_file)[0]
  1079. else:
  1080. base_path = os.path.abspath(os.path.curdir)
  1081. return dotted_path, base_path, aliases
  1082. def load_grammar(self, grammar_text, grammar_name="<?>", mangle=None):
  1083. tree = _parse_grammar(grammar_text, grammar_name)
  1084. imports = {} # imports are collect over the whole file to prevent duplications
  1085. actions = [] # Some statements need to be delayed (override and extend) till after imports are handled
  1086. for stmt in tree.children:
  1087. if stmt.data in ('term', 'rule'):
  1088. self._define(*self._unpack_definition(stmt, mangle))
  1089. continue
  1090. assert stmt.data == 'statement', stmt.data
  1091. stmt ,= stmt.children
  1092. if stmt.data == 'import':
  1093. dotted_path, base_path, aliases = self._unpack_import(stmt, grammar_name)
  1094. try:
  1095. import_base_path, import_aliases = imports[dotted_path]
  1096. assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
  1097. import_aliases.update(aliases)
  1098. except KeyError:
  1099. imports[dotted_path] = base_path, aliases
  1100. elif stmt.data == 'ignore':
  1101. # if mangle is not None, we shouldn't apply ignore, since we aren't in a toplevel grammar
  1102. if mangle is None:
  1103. self._ignore(*stmt.children)
  1104. elif stmt.data == 'declare':
  1105. if mangle is None:
  1106. self._declare(*(t.value for t in stmt.children))
  1107. else:
  1108. self._declare(*(mangle(t.value) for t in stmt.children))
  1109. elif stmt.data == 'override':
  1110. r ,= stmt.children
  1111. actions.append((self._define, self._unpack_definition(r, mangle) + (True,)))
  1112. elif stmt.data == 'extend':
  1113. r ,= stmt.children
  1114. actions.append((self._extend, self._unpack_definition(r, mangle)))
  1115. else:
  1116. assert False, stmt
  1117. for dotted_path, (base_path, aliases) in imports.items():
  1118. self.do_import(dotted_path, base_path, aliases, mangle)
  1119. for f, args in actions:
  1120. f(*args)
  1121. def do_import(self, dotted_path, base_path, aliases, base_mangle=None):
  1122. mangle = self.get_mangle('__'.join(dotted_path), aliases, base_mangle)
  1123. grammar_path = os.path.join(*dotted_path) + EXT
  1124. to_try = self.import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
  1125. for source in to_try:
  1126. try:
  1127. if callable(source):
  1128. joined_path, text = source(base_path, grammar_path)
  1129. else:
  1130. joined_path = os.path.join(source, grammar_path)
  1131. with open(joined_path, encoding='utf8') as f:
  1132. text = f.read()
  1133. except IOError:
  1134. continue
  1135. else:
  1136. self.load_grammar(text, joined_path, mangle)
  1137. break
  1138. else:
  1139. # Search failed. Make Python throw a nice error.
  1140. open(grammar_path, encoding='utf8')
  1141. assert False, "Couldn't import grammar %s, but a corresponding file was found at a place where lark doesn't search for it" % (dotted_path,)
  1142. def get_mangle(self, prefix, aliases, base_mangle=None):
  1143. prefixes = (prefix, prefix.upper())
  1144. def mangle(s):
  1145. if s in aliases:
  1146. s = aliases[s]
  1147. else:
  1148. ns = prefixes[self._is_term(s)]
  1149. if s[0] == '_':
  1150. s = '_%s__%s' % (ns, s[1:])
  1151. else:
  1152. s = '%s__%s' % (ns, s)
  1153. if base_mangle is not None:
  1154. s = base_mangle(s)
  1155. return s
  1156. return mangle
  1157. def check(self):
  1158. for name, (params, exp, options) in self._definitions.items():
  1159. if self._is_term(name):
  1160. assert isinstance(options, int)
  1161. for i, p in enumerate(params):
  1162. if p in self._definitions:
  1163. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  1164. if p in params[:i]:
  1165. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  1166. if exp is None: # Remaining checks don't work for abstract rules/terminals
  1167. continue
  1168. for temp in exp.find_data('template_usage'):
  1169. sym = temp.children[0]
  1170. args = temp.children[1:]
  1171. if sym not in params:
  1172. if sym not in self._definitions:
  1173. self._grammar_error("Template '%s' used but not defined (in {type} {name})" % sym, name)
  1174. if len(args) != len(self._definitions[sym][0]):
  1175. expected, actual = len(self._definitions[sym][0]), len(args)
  1176. self._grammar_error("Wrong number of template arguments used for {name} "
  1177. "(expected %s, got %s) (in {type2} {name2})" % (expected, actual), sym, name)
  1178. for sym in _find_used_symbols(exp):
  1179. if sym not in self._definitions and sym not in params:
  1180. self._grammar_error("{Type} '{name}' used but not defined (in {type2} {name2})", sym, name)
  1181. if not set(self._definitions).issuperset(self._ignore_names):
  1182. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(self._ignore_names) - set(self._definitions)))
  1183. def build(self):
  1184. self.check()
  1185. rule_defs = []
  1186. term_defs = []
  1187. for name, (params, exp, options) in self._definitions.items():
  1188. if self._is_term(name):
  1189. assert len(params) == 0
  1190. term_defs.append((name, (exp, options)))
  1191. else:
  1192. rule_defs.append((name, params, exp, options))
  1193. resolve_term_references(term_defs)
  1194. return Grammar(rule_defs, term_defs, self._ignore_names)
  1195. def load_grammar(grammar, source, import_paths, global_keep_all_tokens):
  1196. builder = GrammarBuilder(global_keep_all_tokens, import_paths)
  1197. builder.load_grammar(grammar, source)
  1198. return builder.build()
  1199. # return GrammarLoader(global_keep_all_tokens).load_grammar(grammar, source, import_paths)