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.

1105 lines
40 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. '_IMPORT': r'%import',
  89. 'NUMBER': r'[+-]?\d+',
  90. }
  91. RULES = {
  92. 'start': ['_list'],
  93. '_list': ['_item', '_list _item'],
  94. '_item': ['rule', 'term', 'statement', '_NL'],
  95. 'rule': ['RULE template_params _COLON expansions _NL',
  96. 'RULE template_params _DOT NUMBER _COLON expansions _NL'],
  97. 'template_params': ['_LBRACE _template_params _RBRACE',
  98. ''],
  99. '_template_params': ['RULE',
  100. '_template_params _COMMA RULE'],
  101. 'expansions': ['alias',
  102. 'expansions _OR alias',
  103. 'expansions _NL _OR alias'],
  104. '?alias': ['expansion _TO RULE', 'expansion'],
  105. 'expansion': ['_expansion'],
  106. '_expansion': ['', '_expansion expr'],
  107. '?expr': ['atom',
  108. 'atom OP',
  109. 'atom TILDE NUMBER',
  110. 'atom TILDE NUMBER _DOTDOT NUMBER',
  111. ],
  112. '?atom': ['_LPAR expansions _RPAR',
  113. 'maybe',
  114. 'value'],
  115. 'value': ['terminal',
  116. 'nonterminal',
  117. 'literal',
  118. 'range',
  119. 'template_usage'],
  120. 'terminal': ['TERMINAL'],
  121. 'nonterminal': ['RULE'],
  122. '?name': ['RULE', 'TERMINAL'],
  123. 'maybe': ['_LBRA expansions _RBRA'],
  124. 'range': ['STRING _DOTDOT STRING'],
  125. 'template_usage': ['RULE _LBRACE _template_args _RBRACE'],
  126. '_template_args': ['value',
  127. '_template_args _COMMA value'],
  128. 'term': ['TERMINAL _COLON expansions _NL',
  129. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  130. 'statement': ['ignore', 'import', 'declare', 'override_rule'],
  131. 'override_rule': ['_OVERRIDE rule'],
  132. 'ignore': ['_IGNORE expansions _NL'],
  133. 'declare': ['_DECLARE _declare_args _NL'],
  134. 'import': ['_IMPORT _import_path _NL',
  135. '_IMPORT _import_path _LPAR name_list _RPAR _NL',
  136. '_IMPORT _import_path _TO name _NL'],
  137. '_import_path': ['import_lib', 'import_rel'],
  138. 'import_lib': ['_import_args'],
  139. 'import_rel': ['_DOT _import_args'],
  140. '_import_args': ['name', '_import_args _DOT name'],
  141. 'name_list': ['_name_list'],
  142. '_name_list': ['name', '_name_list _COMMA name'],
  143. '_declare_args': ['name', '_declare_args name'],
  144. 'literal': ['REGEXP', 'STRING'],
  145. }
  146. @inline_args
  147. class EBNF_to_BNF(Transformer_InPlace):
  148. def __init__(self):
  149. self.new_rules = []
  150. self.rules_by_expr = {}
  151. self.prefix = 'anon'
  152. self.i = 0
  153. self.rule_options = None
  154. def _add_recurse_rule(self, type_, expr):
  155. if expr in self.rules_by_expr:
  156. return self.rules_by_expr[expr]
  157. new_name = '__%s_%s_%d' % (self.prefix, type_, self.i)
  158. self.i += 1
  159. t = NonTerminal(new_name)
  160. tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])])
  161. self.new_rules.append((new_name, tree, self.rule_options))
  162. self.rules_by_expr[expr] = t
  163. return t
  164. def expr(self, rule, op, *args):
  165. if op.value == '?':
  166. empty = ST('expansion', [])
  167. return ST('expansions', [rule, empty])
  168. elif op.value == '+':
  169. # a : b c+ d
  170. # -->
  171. # a : b _c d
  172. # _c : _c c | c;
  173. return self._add_recurse_rule('plus', rule)
  174. elif op.value == '*':
  175. # a : b c* d
  176. # -->
  177. # a : b _c? d
  178. # _c : _c c | c;
  179. new_name = self._add_recurse_rule('star', rule)
  180. return ST('expansions', [new_name, ST('expansion', [])])
  181. elif op.value == '~':
  182. if len(args) == 1:
  183. mn = mx = int(args[0])
  184. else:
  185. mn, mx = map(int, args)
  186. if mx < mn or mn < 0:
  187. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
  188. return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)])
  189. assert False, op
  190. def maybe(self, rule):
  191. keep_all_tokens = self.rule_options and self.rule_options.keep_all_tokens
  192. def will_not_get_removed(sym):
  193. if isinstance(sym, NonTerminal):
  194. return not sym.name.startswith('_')
  195. if isinstance(sym, Terminal):
  196. return keep_all_tokens or not sym.filter_out
  197. assert False
  198. if any(rule.scan_values(will_not_get_removed)):
  199. empty = _EMPTY
  200. else:
  201. empty = ST('expansion', [])
  202. return ST('expansions', [rule, empty])
  203. class SimplifyRule_Visitor(Visitor):
  204. @staticmethod
  205. def _flatten(tree):
  206. while True:
  207. to_expand = [i for i, child in enumerate(tree.children)
  208. if isinstance(child, Tree) and child.data == tree.data]
  209. if not to_expand:
  210. break
  211. tree.expand_kids_by_index(*to_expand)
  212. def expansion(self, tree):
  213. # rules_list unpacking
  214. # a : b (c|d) e
  215. # -->
  216. # a : b c e | b d e
  217. #
  218. # In AST terms:
  219. # expansion(b, expansions(c, d), e)
  220. # -->
  221. # expansions( expansion(b, c, e), expansion(b, d, e) )
  222. self._flatten(tree)
  223. for i, child in enumerate(tree.children):
  224. if isinstance(child, Tree) and child.data == 'expansions':
  225. tree.data = 'expansions'
  226. tree.children = [self.visit(ST('expansion', [option if i == j else other
  227. for j, other in enumerate(tree.children)]))
  228. for option in dedup_list(child.children)]
  229. self._flatten(tree)
  230. break
  231. def alias(self, tree):
  232. rule, alias_name = tree.children
  233. if rule.data == 'expansions':
  234. aliases = []
  235. for child in tree.children[0].children:
  236. aliases.append(ST('alias', [child, alias_name]))
  237. tree.data = 'expansions'
  238. tree.children = aliases
  239. def expansions(self, tree):
  240. self._flatten(tree)
  241. # Ensure all children are unique
  242. if len(set(tree.children)) != len(tree.children):
  243. tree.children = dedup_list(tree.children) # dedup is expensive, so try to minimize its use
  244. class RuleTreeToText(Transformer):
  245. def expansions(self, x):
  246. return x
  247. def expansion(self, symbols):
  248. return symbols, None
  249. def alias(self, x):
  250. (expansion, _alias), alias = x
  251. assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
  252. return expansion, alias.value
  253. @inline_args
  254. class CanonizeTree(Transformer_InPlace):
  255. def tokenmods(self, *args):
  256. if len(args) == 1:
  257. return list(args)
  258. tokenmods, value = args
  259. return tokenmods + [value]
  260. class PrepareAnonTerminals(Transformer_InPlace):
  261. """Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them"""
  262. def __init__(self, terminals):
  263. self.terminals = terminals
  264. self.term_set = {td.name for td in self.terminals}
  265. self.term_reverse = {td.pattern: td for td in terminals}
  266. self.i = 0
  267. self.rule_options = None
  268. @inline_args
  269. def pattern(self, p):
  270. value = p.value
  271. if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags:
  272. raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
  273. term_name = None
  274. if isinstance(p, PatternStr):
  275. try:
  276. # If already defined, use the user-defined terminal name
  277. term_name = self.term_reverse[p].name
  278. except KeyError:
  279. # Try to assign an indicative anon-terminal name
  280. try:
  281. term_name = _TERMINAL_NAMES[value]
  282. except KeyError:
  283. if is_id_continue(value) and is_id_start(value[0]) and value.upper() not in self.term_set:
  284. term_name = value.upper()
  285. if term_name in self.term_set:
  286. term_name = None
  287. elif isinstance(p, PatternRE):
  288. if p in self.term_reverse: # Kind of a weird placement.name
  289. term_name = self.term_reverse[p].name
  290. else:
  291. assert False, p
  292. if term_name is None:
  293. term_name = '__ANON_%d' % self.i
  294. self.i += 1
  295. if term_name not in self.term_set:
  296. assert p not in self.term_reverse
  297. self.term_set.add(term_name)
  298. termdef = TerminalDef(term_name, p)
  299. self.term_reverse[p] = termdef
  300. self.terminals.append(termdef)
  301. filter_out = False if self.rule_options and self.rule_options.keep_all_tokens else isinstance(p, PatternStr)
  302. return Terminal(term_name, filter_out=filter_out)
  303. class _ReplaceSymbols(Transformer_InPlace):
  304. """Helper for ApplyTemplates"""
  305. def __init__(self):
  306. self.names = {}
  307. def value(self, c):
  308. if len(c) == 1 and isinstance(c[0], Token) and c[0].value in self.names:
  309. return self.names[c[0].value]
  310. return self.__default__('value', c, None)
  311. def template_usage(self, c):
  312. if c[0] in self.names:
  313. return self.__default__('template_usage', [self.names[c[0]].name] + c[1:], None)
  314. return self.__default__('template_usage', c, None)
  315. class ApplyTemplates(Transformer_InPlace):
  316. """Apply the templates, creating new rules that represent the used templates"""
  317. def __init__(self, rule_defs):
  318. self.rule_defs = rule_defs
  319. self.replacer = _ReplaceSymbols()
  320. self.created_templates = set()
  321. def template_usage(self, c):
  322. name = c[0]
  323. args = c[1:]
  324. result_name = "%s{%s}" % (name, ",".join(a.name for a in args))
  325. if result_name not in self.created_templates:
  326. self.created_templates.add(result_name)
  327. (_n, params, tree, options) ,= (t for t in self.rule_defs if t[0] == name)
  328. assert len(params) == len(args), args
  329. result_tree = deepcopy(tree)
  330. self.replacer.names = dict(zip(params, args))
  331. self.replacer.transform(result_tree)
  332. self.rule_defs.append((result_name, [], result_tree, deepcopy(options)))
  333. return NonTerminal(result_name)
  334. def _rfind(s, choices):
  335. return max(s.rfind(c) for c in choices)
  336. def eval_escaping(s):
  337. w = ''
  338. i = iter(s)
  339. for n in i:
  340. w += n
  341. if n == '\\':
  342. try:
  343. n2 = next(i)
  344. except StopIteration:
  345. raise GrammarError("Literal ended unexpectedly (bad escaping): `%r`" % s)
  346. if n2 == '\\':
  347. w += '\\\\'
  348. elif n2 not in 'uxnftr':
  349. w += '\\'
  350. w += n2
  351. w = w.replace('\\"', '"').replace("'", "\\'")
  352. to_eval = "u'''%s'''" % w
  353. try:
  354. s = literal_eval(to_eval)
  355. except SyntaxError as e:
  356. raise GrammarError(s, e)
  357. return s
  358. def _literal_to_pattern(literal):
  359. v = literal.value
  360. flag_start = _rfind(v, '/"')+1
  361. assert flag_start > 0
  362. flags = v[flag_start:]
  363. assert all(f in _RE_FLAGS for f in flags), flags
  364. if literal.type == 'STRING' and '\n' in v:
  365. raise GrammarError('You cannot put newlines in string literals')
  366. if literal.type == 'REGEXP' and '\n' in v and 'x' not in flags:
  367. raise GrammarError('You can only use newlines in regular expressions '
  368. 'with the `x` (verbose) flag')
  369. v = v[:flag_start]
  370. assert v[0] == v[-1] and v[0] in '"/'
  371. x = v[1:-1]
  372. s = eval_escaping(x)
  373. if literal.type == 'STRING':
  374. s = s.replace('\\\\', '\\')
  375. return PatternStr(s, flags, raw=literal.value)
  376. elif literal.type == 'REGEXP':
  377. return PatternRE(s, flags, raw=literal.value)
  378. else:
  379. assert False, 'Invariant failed: literal.type not in ["STRING", "REGEXP"]'
  380. @inline_args
  381. class PrepareLiterals(Transformer_InPlace):
  382. def literal(self, literal):
  383. return ST('pattern', [_literal_to_pattern(literal)])
  384. def range(self, start, end):
  385. assert start.type == end.type == 'STRING'
  386. start = start.value[1:-1]
  387. end = end.value[1:-1]
  388. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1
  389. regexp = '[%s-%s]' % (start, end)
  390. return ST('pattern', [PatternRE(regexp)])
  391. def _make_joined_pattern(regexp, flags_set):
  392. # In Python 3.6, a new syntax for flags was introduced, that allows us to restrict the scope
  393. # of flags to a specific regexp group. We are already using it in `lexer.Pattern._get_flags`
  394. # However, for prior Python versions, we still need to use global flags, so we have to make sure
  395. # that there are no flag collisions when we merge several terminals.
  396. flags = ()
  397. if not Py36:
  398. if len(flags_set) > 1:
  399. raise GrammarError("Lark doesn't support joining terminals with conflicting flags in python <3.6!")
  400. elif len(flags_set) == 1:
  401. flags ,= flags_set
  402. return PatternRE(regexp, flags)
  403. class TerminalTreeToPattern(Transformer):
  404. def pattern(self, ps):
  405. p ,= ps
  406. return p
  407. def expansion(self, items):
  408. assert items
  409. if len(items) == 1:
  410. return items[0]
  411. pattern = ''.join(i.to_regexp() for i in items)
  412. return _make_joined_pattern(pattern, {i.flags for i in items})
  413. def expansions(self, exps):
  414. if len(exps) == 1:
  415. return exps[0]
  416. pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps))
  417. return _make_joined_pattern(pattern, {i.flags for i in exps})
  418. def expr(self, args):
  419. inner, op = args[:2]
  420. if op == '~':
  421. if len(args) == 3:
  422. op = "{%d}" % int(args[2])
  423. else:
  424. mn, mx = map(int, args[2:])
  425. if mx < mn:
  426. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  427. op = "{%d,%d}" % (mn, mx)
  428. else:
  429. assert len(args) == 2
  430. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  431. def maybe(self, expr):
  432. return self.expr(expr + ['?'])
  433. def alias(self, t):
  434. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  435. def value(self, v):
  436. return v[0]
  437. class PrepareSymbols(Transformer_InPlace):
  438. def value(self, v):
  439. v ,= v
  440. if isinstance(v, Tree):
  441. return v
  442. elif v.type == 'RULE':
  443. return NonTerminal(Str(v.value))
  444. elif v.type == 'TERMINAL':
  445. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  446. assert False
  447. def _choice_of_rules(rules):
  448. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  449. def nr_deepcopy_tree(t):
  450. """Deepcopy tree `t` without recursion"""
  451. return Transformer_NonRecursive(False).transform(t)
  452. class Grammar:
  453. def __init__(self, rule_defs, term_defs, ignore):
  454. self.term_defs = term_defs
  455. self.rule_defs = rule_defs
  456. self.ignore = ignore
  457. def compile(self, start, terminals_to_keep):
  458. # We change the trees in-place (to support huge grammars)
  459. # So deepcopy allows calling compile more than once.
  460. term_defs = deepcopy(list(self.term_defs))
  461. rule_defs = [(n,p,nr_deepcopy_tree(t),o) for n,p,t,o in self.rule_defs]
  462. # ===================
  463. # Compile Terminals
  464. # ===================
  465. # Convert terminal-trees to strings/regexps
  466. for name, (term_tree, priority) in term_defs:
  467. if term_tree is None: # Terminal added through %declare
  468. continue
  469. expansions = list(term_tree.find_data('expansion'))
  470. if len(expansions) == 1 and not expansions[0].children:
  471. raise GrammarError("Terminals cannot be empty (%s)" % name)
  472. transformer = PrepareLiterals() * TerminalTreeToPattern()
  473. terminals = [TerminalDef(name, transformer.transform(term_tree), priority)
  474. for name, (term_tree, priority) in term_defs if term_tree]
  475. # =================
  476. # Compile Rules
  477. # =================
  478. # 1. Pre-process terminals
  479. anon_tokens_transf = PrepareAnonTerminals(terminals)
  480. transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals
  481. # 2. Inline Templates
  482. transformer *= ApplyTemplates(rule_defs)
  483. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  484. ebnf_to_bnf = EBNF_to_BNF()
  485. rules = []
  486. i = 0
  487. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  488. name, params, rule_tree, options = rule_defs[i]
  489. i += 1
  490. if len(params) != 0: # Dont transform templates
  491. continue
  492. rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  493. ebnf_to_bnf.rule_options = rule_options
  494. ebnf_to_bnf.prefix = name
  495. anon_tokens_transf.rule_options = rule_options
  496. tree = transformer.transform(rule_tree)
  497. res = ebnf_to_bnf.transform(tree)
  498. rules.append((name, res, options))
  499. rules += ebnf_to_bnf.new_rules
  500. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  501. # 4. Compile tree to Rule objects
  502. rule_tree_to_text = RuleTreeToText()
  503. simplify_rule = SimplifyRule_Visitor()
  504. compiled_rules = []
  505. for rule_content in rules:
  506. name, tree, options = rule_content
  507. simplify_rule.visit(tree)
  508. expansions = rule_tree_to_text.transform(tree)
  509. for i, (expansion, alias) in enumerate(expansions):
  510. if alias and name.startswith('_'):
  511. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)"% (name, alias))
  512. empty_indices = [x==_EMPTY for x in expansion]
  513. if any(empty_indices):
  514. exp_options = copy(options) or RuleOptions()
  515. exp_options.empty_indices = empty_indices
  516. expansion = [x for x in expansion if x!=_EMPTY]
  517. else:
  518. exp_options = options
  519. assert all(isinstance(x, Symbol) for x in expansion), expansion
  520. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  521. compiled_rules.append(rule)
  522. # Remove duplicates of empty rules, throw error for non-empty duplicates
  523. if len(set(compiled_rules)) != len(compiled_rules):
  524. duplicates = classify(compiled_rules, lambda x: x)
  525. for dups in duplicates.values():
  526. if len(dups) > 1:
  527. if dups[0].expansion:
  528. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  529. % ''.join('\n * %s' % i for i in dups))
  530. # Empty rule; assert all other attributes are equal
  531. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  532. # Remove duplicates
  533. compiled_rules = list(set(compiled_rules))
  534. # Filter out unused rules
  535. while True:
  536. c = len(compiled_rules)
  537. used_rules = {s for r in compiled_rules
  538. for s in r.expansion
  539. if isinstance(s, NonTerminal)
  540. and s != r.origin}
  541. used_rules |= {NonTerminal(s) for s in start}
  542. compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules)
  543. for r in unused:
  544. logger.debug("Unused rule: %s", r)
  545. if len(compiled_rules) == c:
  546. break
  547. # Filter out unused terminals
  548. used_terms = {t.name for r in compiled_rules
  549. for t in r.expansion
  550. if isinstance(t, Terminal)}
  551. 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)
  552. if unused:
  553. logger.debug("Unused terminals: %s", [t.name for t in unused])
  554. return terminals, compiled_rules, self.ignore
  555. class PackageResource(object):
  556. """
  557. Represents a path inside a Package. Used by `FromPackageLoader`
  558. """
  559. def __init__(self, pkg_name, path):
  560. self.pkg_name = pkg_name
  561. self.path = path
  562. def __str__(self):
  563. return "<%s: %s>" % (self.pkg_name, self.path)
  564. def __repr__(self):
  565. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.path)
  566. class FromPackageLoader(object):
  567. """
  568. Provides a simple way of creating custom import loaders that load from packages via ``pkgutil.get_data`` instead of using `open`.
  569. This allows them to be compatible even from within zip files.
  570. Relative imports are handled, so you can just freely use them.
  571. pkg_name: The name of the package. You can probably provide `__name__` most of the time
  572. search_paths: All the path that will be search on absolute imports.
  573. """
  574. def __init__(self, pkg_name, search_paths=("", )):
  575. self.pkg_name = pkg_name
  576. self.search_paths = search_paths
  577. def __repr__(self):
  578. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.search_paths)
  579. def __call__(self, base_path, grammar_path):
  580. if base_path is None:
  581. to_try = self.search_paths
  582. else:
  583. # Check whether or not the importing grammar was loaded by this module.
  584. if not isinstance(base_path, PackageResource) or base_path.pkg_name != self.pkg_name:
  585. # Technically false, but FileNotFound doesn't exist in python2.7, and this message should never reach the end user anyway
  586. raise IOError()
  587. to_try = [base_path.path]
  588. for path in to_try:
  589. full_path = os.path.join(path, grammar_path)
  590. try:
  591. text = pkgutil.get_data(self.pkg_name, full_path)
  592. except IOError:
  593. continue
  594. else:
  595. return PackageResource(self.pkg_name, full_path), text.decode()
  596. raise IOError()
  597. stdlib_loader = FromPackageLoader('lark', IMPORT_PATHS)
  598. _imported_grammars = {}
  599. def import_from_grammar_into_namespace(grammar, namespace, aliases):
  600. """Returns all rules and terminals of grammar, prepended
  601. with a 'namespace' prefix, except for those which are aliased.
  602. """
  603. imported_terms = dict(grammar.term_defs)
  604. imported_rules = {n:(n,p,deepcopy(t),o) for n,p,t,o in grammar.rule_defs}
  605. term_defs = []
  606. rule_defs = []
  607. def rule_dependencies(symbol):
  608. if symbol.type != 'RULE':
  609. return []
  610. try:
  611. _, params, tree,_ = imported_rules[symbol]
  612. except KeyError:
  613. raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace))
  614. return _find_used_symbols(tree) - set(params)
  615. def get_namespace_name(name, params):
  616. if params is not None:
  617. try:
  618. return params[name]
  619. except KeyError:
  620. pass
  621. try:
  622. return aliases[name].value
  623. except KeyError:
  624. if name[0] == '_':
  625. return '_%s__%s' % (namespace, name[1:])
  626. return '%s__%s' % (namespace, name)
  627. to_import = list(bfs(aliases, rule_dependencies))
  628. for symbol in to_import:
  629. if symbol.type == 'TERMINAL':
  630. term_defs.append([get_namespace_name(symbol, None), imported_terms[symbol]])
  631. else:
  632. assert symbol.type == 'RULE'
  633. _, params, tree, options = imported_rules[symbol]
  634. params_map = {p: ('%s__%s' if p[0]!='_' else '_%s__%s') % (namespace, p) for p in params}
  635. for t in tree.iter_subtrees():
  636. for i, c in enumerate(t.children):
  637. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  638. t.children[i] = Token(c.type, get_namespace_name(c, params_map))
  639. params = [params_map[p] for p in params] # We can not rely on ordered dictionaries
  640. rule_defs.append((get_namespace_name(symbol, params_map), params, tree, options))
  641. return term_defs, rule_defs
  642. def resolve_term_references(term_defs):
  643. # TODO Solve with transitive closure (maybe)
  644. term_dict = {k:t for k, (t,_p) in term_defs}
  645. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  646. while True:
  647. changed = False
  648. for name, (token_tree, _p) in term_defs:
  649. if token_tree is None: # Terminal added through %declare
  650. continue
  651. for exp in token_tree.find_data('value'):
  652. item ,= exp.children
  653. if isinstance(item, Token):
  654. if item.type == 'RULE':
  655. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  656. if item.type == 'TERMINAL':
  657. term_value = term_dict[item]
  658. assert term_value is not None
  659. exp.children[0] = term_value
  660. changed = True
  661. if not changed:
  662. break
  663. for name, term in term_dict.items():
  664. if term: # Not just declared
  665. for child in term.children:
  666. ids = [id(x) for x in child.iter_subtrees()]
  667. if id(term) in ids:
  668. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  669. def options_from_rule(name, params, *x):
  670. if len(x) > 1:
  671. priority, expansions = x
  672. priority = int(priority)
  673. else:
  674. expansions ,= x
  675. priority = None
  676. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  677. keep_all_tokens = name.startswith('!')
  678. name = name.lstrip('!')
  679. expand1 = name.startswith('?')
  680. name = name.lstrip('?')
  681. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  682. template_source=(name if params else None))
  683. def symbols_from_strcase(expansion):
  684. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  685. @inline_args
  686. class PrepareGrammar(Transformer_InPlace):
  687. def terminal(self, name):
  688. return name
  689. def nonterminal(self, name):
  690. return name
  691. def _find_used_symbols(tree):
  692. assert tree.data == 'expansions'
  693. return {t for x in tree.find_data('expansion')
  694. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  695. class GrammarLoader:
  696. ERRORS = [
  697. ('Unclosed parenthesis', ['a: (\n']),
  698. ('Unmatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']),
  699. ('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']),
  700. ('Illegal name for rules or terminals', ['Aa:\n']),
  701. ('Alias expects lowercase name', ['a: -> "a"\n']),
  702. ('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']),
  703. ('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']),
  704. ('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']),
  705. ('Terminal names cannot contain dots', ['A.B\n']),
  706. ('%import expects a name', ['%import "a"\n']),
  707. ('%ignore expects a value', ['%ignore %import\n']),
  708. ]
  709. def __init__(self, global_keep_all_tokens):
  710. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  711. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  712. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o)
  713. for r, _p, xs, o in rules for i, x in enumerate(xs)]
  714. callback = ParseTreeBuilder(rules, ST).create_callback()
  715. import re
  716. lexer_conf = LexerConf(terminals, re, ['WS', 'COMMENT'])
  717. parser_conf = ParserConf(rules, callback, ['start'])
  718. lexer_conf.lexer_type = 'standard'
  719. parser_conf.parser_type = 'lalr'
  720. self.parser = ParsingFrontend(lexer_conf, parser_conf, {})
  721. self.canonize_tree = CanonizeTree()
  722. self.global_keep_all_tokens = global_keep_all_tokens
  723. def import_grammar(self, grammar_path, base_path=None, import_paths=[]):
  724. if grammar_path not in _imported_grammars:
  725. # import_paths take priority over base_path since they should handle relative imports and ignore everything else.
  726. to_try = import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
  727. for source in to_try:
  728. try:
  729. if callable(source):
  730. joined_path, text = source(base_path, grammar_path)
  731. else:
  732. joined_path = os.path.join(source, grammar_path)
  733. with open(joined_path, encoding='utf8') as f:
  734. text = f.read()
  735. except IOError:
  736. continue
  737. else:
  738. grammar = self.load_grammar(text, joined_path, import_paths)
  739. _imported_grammars[grammar_path] = grammar
  740. break
  741. else:
  742. # Search failed. Make Python throw a nice error.
  743. open(grammar_path, encoding='utf8')
  744. assert False
  745. return _imported_grammars[grammar_path]
  746. def load_grammar(self, grammar_text, grammar_name='<?>', import_paths=[]):
  747. """Parse grammar_text, verify, and create Grammar object. Display nice messages on error."""
  748. try:
  749. tree = self.canonize_tree.transform(self.parser.parse(grammar_text+'\n'))
  750. except UnexpectedCharacters as e:
  751. context = e.get_context(grammar_text)
  752. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  753. (e.line, e.column, grammar_name, context))
  754. except UnexpectedToken as e:
  755. context = e.get_context(grammar_text)
  756. error = e.match_examples(self.parser.parse, self.ERRORS, use_accepts=True)
  757. if error:
  758. raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  759. elif 'STRING' in e.expected:
  760. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  761. raise
  762. tree = PrepareGrammar().transform(tree)
  763. # Extract grammar items
  764. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  765. term_defs = defs.pop('term', [])
  766. rule_defs = defs.pop('rule', [])
  767. statements = defs.pop('statement', [])
  768. assert not defs
  769. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  770. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  771. rule_defs = [options_from_rule(*x) for x in rule_defs]
  772. # Execute statements
  773. ignore, imports = [], {}
  774. overriding_rules = []
  775. for (stmt,) in statements:
  776. if stmt.data == 'ignore':
  777. t ,= stmt.children
  778. ignore.append(t)
  779. elif stmt.data == 'import':
  780. if len(stmt.children) > 1:
  781. path_node, arg1 = stmt.children
  782. else:
  783. path_node ,= stmt.children
  784. arg1 = None
  785. if isinstance(arg1, Tree): # Multi import
  786. dotted_path = tuple(path_node.children)
  787. names = arg1.children
  788. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  789. else: # Single import
  790. dotted_path = tuple(path_node.children[:-1])
  791. name = path_node.children[-1] # Get name from dotted path
  792. aliases = {name: arg1 or name} # Aliases if exist
  793. if path_node.data == 'import_lib': # Import from library
  794. base_path = None
  795. else: # Relative import
  796. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  797. try:
  798. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  799. except AttributeError:
  800. base_file = None
  801. else:
  802. base_file = grammar_name # Import relative to grammar file path if external grammar file
  803. if base_file:
  804. if isinstance(base_file, PackageResource):
  805. base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
  806. else:
  807. base_path = os.path.split(base_file)[0]
  808. else:
  809. base_path = os.path.abspath(os.path.curdir)
  810. try:
  811. import_base_path, import_aliases = imports[dotted_path]
  812. assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
  813. import_aliases.update(aliases)
  814. except KeyError:
  815. imports[dotted_path] = base_path, aliases
  816. elif stmt.data == 'declare':
  817. for t in stmt.children:
  818. term_defs.append([t.value, (None, None)])
  819. elif stmt.data == 'override_rule':
  820. r ,= stmt.children
  821. overriding_rules.append(options_from_rule(*r.children))
  822. else:
  823. assert False, stmt
  824. # import grammars
  825. for dotted_path, (base_path, aliases) in imports.items():
  826. grammar_path = os.path.join(*dotted_path) + EXT
  827. g = self.import_grammar(grammar_path, base_path=base_path, import_paths=import_paths)
  828. new_td, new_rd = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases)
  829. term_defs += new_td
  830. rule_defs += new_rd
  831. # replace rules by overridding rules, according to name
  832. for r in overriding_rules:
  833. name = r[0]
  834. # remove overridden rule from rule_defs
  835. overridden, rule_defs = classify_bool(rule_defs, lambda r: r[0] == name) # FIXME inefficient
  836. if not overridden:
  837. raise GrammarError("Cannot override a nonexisting rule: %s" % name)
  838. rule_defs.append(r)
  839. ## Handle terminals
  840. # Verify correctness 1
  841. for name, _ in term_defs:
  842. if name.startswith('__'):
  843. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  844. # Handle ignore tokens
  845. # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's
  846. # inability to handle duplicate terminals (two names, one value)
  847. ignore_names = []
  848. for t in ignore:
  849. if t.data=='expansions' and len(t.children) == 1:
  850. t2 ,= t.children
  851. if t2.data=='expansion' and len(t2.children) == 1:
  852. item ,= t2.children
  853. if item.data == 'value':
  854. item ,= item.children
  855. if isinstance(item, Token) and item.type == 'TERMINAL':
  856. ignore_names.append(item.value)
  857. continue
  858. name = '__IGNORE_%d'% len(ignore_names)
  859. ignore_names.append(name)
  860. term_defs.append((name, (t, 1)))
  861. # Verify correctness 2
  862. terminal_names = set()
  863. for name, _ in term_defs:
  864. if name in terminal_names:
  865. raise GrammarError("Terminal '%s' defined more than once" % name)
  866. terminal_names.add(name)
  867. if set(ignore_names) > terminal_names:
  868. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names))
  869. resolve_term_references(term_defs)
  870. ## Handle rules
  871. rule_names = {}
  872. for name, params, _x, option in rule_defs:
  873. # We can't just simply not throw away the tokens later, we need option.keep_all_tokens to correctly generate maybe_placeholders
  874. if self.global_keep_all_tokens:
  875. option.keep_all_tokens = True
  876. if name.startswith('__'):
  877. raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name)
  878. if name in rule_names:
  879. raise GrammarError("Rule '%s' defined more than once" % name)
  880. rule_names[name] = len(params)
  881. for name, params , expansions, _o in rule_defs:
  882. for i, p in enumerate(params):
  883. if p in rule_names:
  884. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  885. if p in params[:i]:
  886. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  887. for temp in expansions.find_data('template_usage'):
  888. sym = temp.children[0]
  889. args = temp.children[1:]
  890. if sym not in params:
  891. if sym not in rule_names:
  892. raise GrammarError("Template '%s' used but not defined (in rule %s)" % (sym, name))
  893. if len(args) != rule_names[sym]:
  894. raise GrammarError("Wrong number of template arguments used for %s "
  895. "(expected %s, got %s) (in rule %s)" % (sym, rule_names[sym], len(args), name))
  896. for sym in _find_used_symbols(expansions):
  897. if sym.type == 'TERMINAL':
  898. if sym not in terminal_names:
  899. raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name))
  900. else:
  901. if sym not in rule_names and sym not in params:
  902. raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name))
  903. return Grammar(rule_defs, term_defs, ignore_names)
  904. def load_grammar(grammar, source, import_paths, global_keep_all_tokens):
  905. return GrammarLoader(global_keep_all_tokens).load_grammar(grammar, source, import_paths)