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
  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 value.isalnum() and value[0].isalpha() and value.upper() not in self.term_set:
  284. with suppress(UnicodeEncodeError):
  285. value.upper().encode('ascii') # Make sure we don't have unicode in our terminal names
  286. term_name = value.upper()
  287. if term_name in self.term_set:
  288. term_name = None
  289. elif isinstance(p, PatternRE):
  290. if p in self.term_reverse: # Kind of a weird placement.name
  291. term_name = self.term_reverse[p].name
  292. else:
  293. assert False, p
  294. if term_name is None:
  295. term_name = '__ANON_%d' % self.i
  296. self.i += 1
  297. if term_name not in self.term_set:
  298. assert p not in self.term_reverse
  299. self.term_set.add(term_name)
  300. termdef = TerminalDef(term_name, p)
  301. self.term_reverse[p] = termdef
  302. self.terminals.append(termdef)
  303. filter_out = False if self.rule_options and self.rule_options.keep_all_tokens else isinstance(p, PatternStr)
  304. return Terminal(term_name, filter_out=filter_out)
  305. class _ReplaceSymbols(Transformer_InPlace):
  306. """Helper for ApplyTemplates"""
  307. def __init__(self):
  308. self.names = {}
  309. def value(self, c):
  310. if len(c) == 1 and isinstance(c[0], Token) and c[0].value in self.names:
  311. return self.names[c[0].value]
  312. return self.__default__('value', c, None)
  313. def template_usage(self, c):
  314. if c[0] in self.names:
  315. return self.__default__('template_usage', [self.names[c[0]].name] + c[1:], None)
  316. return self.__default__('template_usage', c, None)
  317. class ApplyTemplates(Transformer_InPlace):
  318. """Apply the templates, creating new rules that represent the used templates"""
  319. def __init__(self, rule_defs):
  320. self.rule_defs = rule_defs
  321. self.replacer = _ReplaceSymbols()
  322. self.created_templates = set()
  323. def template_usage(self, c):
  324. name = c[0]
  325. args = c[1:]
  326. result_name = "%s{%s}" % (name, ",".join(a.name for a in args))
  327. if result_name not in self.created_templates:
  328. self.created_templates.add(result_name)
  329. (_n, params, tree, options) ,= (t for t in self.rule_defs if t[0] == name)
  330. assert len(params) == len(args), args
  331. result_tree = deepcopy(tree)
  332. self.replacer.names = dict(zip(params, args))
  333. self.replacer.transform(result_tree)
  334. self.rule_defs.append((result_name, [], result_tree, deepcopy(options)))
  335. return NonTerminal(result_name)
  336. def _rfind(s, choices):
  337. return max(s.rfind(c) for c in choices)
  338. def eval_escaping(s):
  339. w = ''
  340. i = iter(s)
  341. for n in i:
  342. w += n
  343. if n == '\\':
  344. try:
  345. n2 = next(i)
  346. except StopIteration:
  347. raise GrammarError("Literal ended unexpectedly (bad escaping): `%r`" % s)
  348. if n2 == '\\':
  349. w += '\\\\'
  350. elif n2 not in 'uxnftr':
  351. w += '\\'
  352. w += n2
  353. w = w.replace('\\"', '"').replace("'", "\\'")
  354. to_eval = "u'''%s'''" % w
  355. try:
  356. s = literal_eval(to_eval)
  357. except SyntaxError as e:
  358. raise GrammarError(s, e)
  359. return s
  360. def _literal_to_pattern(literal):
  361. v = literal.value
  362. flag_start = _rfind(v, '/"')+1
  363. assert flag_start > 0
  364. flags = v[flag_start:]
  365. assert all(f in _RE_FLAGS for f in flags), flags
  366. if literal.type == 'STRING' and '\n' in v:
  367. raise GrammarError('You cannot put newlines in string literals')
  368. if literal.type == 'REGEXP' and '\n' in v and 'x' not in flags:
  369. raise GrammarError('You can only use newlines in regular expressions '
  370. 'with the `x` (verbose) flag')
  371. v = v[:flag_start]
  372. assert v[0] == v[-1] and v[0] in '"/'
  373. x = v[1:-1]
  374. s = eval_escaping(x)
  375. if literal.type == 'STRING':
  376. s = s.replace('\\\\', '\\')
  377. return PatternStr(s, flags, raw=literal.value)
  378. elif literal.type == 'REGEXP':
  379. return PatternRE(s, flags, raw=literal.value)
  380. else:
  381. assert False, 'Invariant failed: literal.type not in ["STRING", "REGEXP"]'
  382. @inline_args
  383. class PrepareLiterals(Transformer_InPlace):
  384. def literal(self, literal):
  385. return ST('pattern', [_literal_to_pattern(literal)])
  386. def range(self, start, end):
  387. assert start.type == end.type == 'STRING'
  388. start = start.value[1:-1]
  389. end = end.value[1:-1]
  390. assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1
  391. regexp = '[%s-%s]' % (start, end)
  392. return ST('pattern', [PatternRE(regexp)])
  393. def _make_joined_pattern(regexp, flags_set):
  394. # In Python 3.6, a new syntax for flags was introduced, that allows us to restrict the scope
  395. # of flags to a specific regexp group. We are already using it in `lexer.Pattern._get_flags`
  396. # However, for prior Python versions, we still need to use global flags, so we have to make sure
  397. # that there are no flag collisions when we merge several terminals.
  398. flags = ()
  399. if not Py36:
  400. if len(flags_set) > 1:
  401. raise GrammarError("Lark doesn't support joining terminals with conflicting flags in python <3.6!")
  402. elif len(flags_set) == 1:
  403. flags ,= flags_set
  404. return PatternRE(regexp, flags)
  405. class TerminalTreeToPattern(Transformer):
  406. def pattern(self, ps):
  407. p ,= ps
  408. return p
  409. def expansion(self, items):
  410. assert items
  411. if len(items) == 1:
  412. return items[0]
  413. pattern = ''.join(i.to_regexp() for i in items)
  414. return _make_joined_pattern(pattern, {i.flags for i in items})
  415. def expansions(self, exps):
  416. if len(exps) == 1:
  417. return exps[0]
  418. pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps))
  419. return _make_joined_pattern(pattern, {i.flags for i in exps})
  420. def expr(self, args):
  421. inner, op = args[:2]
  422. if op == '~':
  423. if len(args) == 3:
  424. op = "{%d}" % int(args[2])
  425. else:
  426. mn, mx = map(int, args[2:])
  427. if mx < mn:
  428. raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
  429. op = "{%d,%d}" % (mn, mx)
  430. else:
  431. assert len(args) == 2
  432. return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
  433. def maybe(self, expr):
  434. return self.expr(expr + ['?'])
  435. def alias(self, t):
  436. raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
  437. def value(self, v):
  438. return v[0]
  439. class PrepareSymbols(Transformer_InPlace):
  440. def value(self, v):
  441. v ,= v
  442. if isinstance(v, Tree):
  443. return v
  444. elif v.type == 'RULE':
  445. return NonTerminal(Str(v.value))
  446. elif v.type == 'TERMINAL':
  447. return Terminal(Str(v.value), filter_out=v.startswith('_'))
  448. assert False
  449. def _choice_of_rules(rules):
  450. return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules])
  451. def nr_deepcopy_tree(t):
  452. """Deepcopy tree `t` without recursion"""
  453. return Transformer_NonRecursive(False).transform(t)
  454. class Grammar:
  455. def __init__(self, rule_defs, term_defs, ignore):
  456. self.term_defs = term_defs
  457. self.rule_defs = rule_defs
  458. self.ignore = ignore
  459. def compile(self, start, terminals_to_keep):
  460. # We change the trees in-place (to support huge grammars)
  461. # So deepcopy allows calling compile more than once.
  462. term_defs = deepcopy(list(self.term_defs))
  463. rule_defs = [(n,p,nr_deepcopy_tree(t),o) for n,p,t,o in self.rule_defs]
  464. # ===================
  465. # Compile Terminals
  466. # ===================
  467. # Convert terminal-trees to strings/regexps
  468. for name, (term_tree, priority) in term_defs:
  469. if term_tree is None: # Terminal added through %declare
  470. continue
  471. expansions = list(term_tree.find_data('expansion'))
  472. if len(expansions) == 1 and not expansions[0].children:
  473. raise GrammarError("Terminals cannot be empty (%s)" % name)
  474. transformer = PrepareLiterals() * TerminalTreeToPattern()
  475. terminals = [TerminalDef(name, transformer.transform(term_tree), priority)
  476. for name, (term_tree, priority) in term_defs if term_tree]
  477. # =================
  478. # Compile Rules
  479. # =================
  480. # 1. Pre-process terminals
  481. anon_tokens_transf = PrepareAnonTerminals(terminals)
  482. transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals
  483. # 2. Inline Templates
  484. transformer *= ApplyTemplates(rule_defs)
  485. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  486. ebnf_to_bnf = EBNF_to_BNF()
  487. rules = []
  488. i = 0
  489. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  490. name, params, rule_tree, options = rule_defs[i]
  491. i += 1
  492. if len(params) != 0: # Dont transform templates
  493. continue
  494. rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  495. ebnf_to_bnf.rule_options = rule_options
  496. ebnf_to_bnf.prefix = name
  497. anon_tokens_transf.rule_options = rule_options
  498. tree = transformer.transform(rule_tree)
  499. res = ebnf_to_bnf.transform(tree)
  500. rules.append((name, res, options))
  501. rules += ebnf_to_bnf.new_rules
  502. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  503. # 4. Compile tree to Rule objects
  504. rule_tree_to_text = RuleTreeToText()
  505. simplify_rule = SimplifyRule_Visitor()
  506. compiled_rules = []
  507. for rule_content in rules:
  508. name, tree, options = rule_content
  509. simplify_rule.visit(tree)
  510. expansions = rule_tree_to_text.transform(tree)
  511. for i, (expansion, alias) in enumerate(expansions):
  512. if alias and name.startswith('_'):
  513. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)"% (name, alias))
  514. empty_indices = [x==_EMPTY for x in expansion]
  515. if any(empty_indices):
  516. exp_options = copy(options) or RuleOptions()
  517. exp_options.empty_indices = empty_indices
  518. expansion = [x for x in expansion if x!=_EMPTY]
  519. else:
  520. exp_options = options
  521. assert all(isinstance(x, Symbol) for x in expansion), expansion
  522. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  523. compiled_rules.append(rule)
  524. # Remove duplicates of empty rules, throw error for non-empty duplicates
  525. if len(set(compiled_rules)) != len(compiled_rules):
  526. duplicates = classify(compiled_rules, lambda x: x)
  527. for dups in duplicates.values():
  528. if len(dups) > 1:
  529. if dups[0].expansion:
  530. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  531. % ''.join('\n * %s' % i for i in dups))
  532. # Empty rule; assert all other attributes are equal
  533. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  534. # Remove duplicates
  535. compiled_rules = list(set(compiled_rules))
  536. # Filter out unused rules
  537. while True:
  538. c = len(compiled_rules)
  539. used_rules = {s for r in compiled_rules
  540. for s in r.expansion
  541. if isinstance(s, NonTerminal)
  542. and s != r.origin}
  543. used_rules |= {NonTerminal(s) for s in start}
  544. compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules)
  545. for r in unused:
  546. logger.debug("Unused rule: %s", r)
  547. if len(compiled_rules) == c:
  548. break
  549. # Filter out unused terminals
  550. used_terms = {t.name for r in compiled_rules
  551. for t in r.expansion
  552. if isinstance(t, Terminal)}
  553. 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)
  554. if unused:
  555. logger.debug("Unused terminals: %s", [t.name for t in unused])
  556. return terminals, compiled_rules, self.ignore
  557. class PackageResource(object):
  558. """
  559. Represents a path inside a Package. Used by `FromPackageLoader`
  560. """
  561. def __init__(self, pkg_name, path):
  562. self.pkg_name = pkg_name
  563. self.path = path
  564. def __str__(self):
  565. return "<%s: %s>" % (self.pkg_name, self.path)
  566. def __repr__(self):
  567. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.path)
  568. class FromPackageLoader(object):
  569. """
  570. Provides a simple way of creating custom import loaders that load from packages via ``pkgutil.get_data`` instead of using `open`.
  571. This allows them to be compatible even from within zip files.
  572. Relative imports are handled, so you can just freely use them.
  573. pkg_name: The name of the package. You can probably provide `__name__` most of the time
  574. search_paths: All the path that will be search on absolute imports.
  575. """
  576. def __init__(self, pkg_name, search_paths=("", )):
  577. self.pkg_name = pkg_name
  578. self.search_paths = search_paths
  579. def __repr__(self):
  580. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.search_paths)
  581. def __call__(self, base_path, grammar_path):
  582. if base_path is None:
  583. to_try = self.search_paths
  584. else:
  585. # Check whether or not the importing grammar was loaded by this module.
  586. if not isinstance(base_path, PackageResource) or base_path.pkg_name != self.pkg_name:
  587. # Technically false, but FileNotFound doesn't exist in python2.7, and this message should never reach the end user anyway
  588. raise IOError()
  589. to_try = [base_path.path]
  590. for path in to_try:
  591. full_path = os.path.join(path, grammar_path)
  592. try:
  593. text = pkgutil.get_data(self.pkg_name, full_path)
  594. except IOError:
  595. continue
  596. else:
  597. return PackageResource(self.pkg_name, full_path), text.decode()
  598. raise IOError()
  599. stdlib_loader = FromPackageLoader('lark', IMPORT_PATHS)
  600. _imported_grammars = {}
  601. def import_from_grammar_into_namespace(grammar, namespace, aliases):
  602. """Returns all rules and terminals of grammar, prepended
  603. with a 'namespace' prefix, except for those which are aliased.
  604. """
  605. imported_terms = dict(grammar.term_defs)
  606. imported_rules = {n:(n,p,deepcopy(t),o) for n,p,t,o in grammar.rule_defs}
  607. term_defs = []
  608. rule_defs = []
  609. def rule_dependencies(symbol):
  610. if symbol.type != 'RULE':
  611. return []
  612. try:
  613. _, params, tree,_ = imported_rules[symbol]
  614. except KeyError:
  615. raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace))
  616. return _find_used_symbols(tree) - set(params)
  617. def get_namespace_name(name, params):
  618. if params is not None:
  619. try:
  620. return params[name]
  621. except KeyError:
  622. pass
  623. try:
  624. return aliases[name].value
  625. except KeyError:
  626. if name[0] == '_':
  627. return '_%s__%s' % (namespace, name[1:])
  628. return '%s__%s' % (namespace, name)
  629. to_import = list(bfs(aliases, rule_dependencies))
  630. for symbol in to_import:
  631. if symbol.type == 'TERMINAL':
  632. term_defs.append([get_namespace_name(symbol, None), imported_terms[symbol]])
  633. else:
  634. assert symbol.type == 'RULE'
  635. _, params, tree, options = imported_rules[symbol]
  636. params_map = {p: ('%s__%s' if p[0]!='_' else '_%s__%s') % (namespace, p) for p in params}
  637. for t in tree.iter_subtrees():
  638. for i, c in enumerate(t.children):
  639. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  640. t.children[i] = Token(c.type, get_namespace_name(c, params_map))
  641. params = [params_map[p] for p in params] # We can not rely on ordered dictionaries
  642. rule_defs.append((get_namespace_name(symbol, params_map), params, tree, options))
  643. return term_defs, rule_defs
  644. def resolve_term_references(term_defs):
  645. # TODO Solve with transitive closure (maybe)
  646. term_dict = {k:t for k, (t,_p) in term_defs}
  647. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  648. while True:
  649. changed = False
  650. for name, (token_tree, _p) in term_defs:
  651. if token_tree is None: # Terminal added through %declare
  652. continue
  653. for exp in token_tree.find_data('value'):
  654. item ,= exp.children
  655. if isinstance(item, Token):
  656. if item.type == 'RULE':
  657. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  658. if item.type == 'TERMINAL':
  659. term_value = term_dict[item]
  660. assert term_value is not None
  661. exp.children[0] = term_value
  662. changed = True
  663. if not changed:
  664. break
  665. for name, term in term_dict.items():
  666. if term: # Not just declared
  667. for child in term.children:
  668. ids = [id(x) for x in child.iter_subtrees()]
  669. if id(term) in ids:
  670. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  671. def options_from_rule(name, params, *x):
  672. if len(x) > 1:
  673. priority, expansions = x
  674. priority = int(priority)
  675. else:
  676. expansions ,= x
  677. priority = None
  678. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  679. keep_all_tokens = name.startswith('!')
  680. name = name.lstrip('!')
  681. expand1 = name.startswith('?')
  682. name = name.lstrip('?')
  683. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  684. template_source=(name if params else None))
  685. def symbols_from_strcase(expansion):
  686. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  687. @inline_args
  688. class PrepareGrammar(Transformer_InPlace):
  689. def terminal(self, name):
  690. return name
  691. def nonterminal(self, name):
  692. return name
  693. def _find_used_symbols(tree):
  694. assert tree.data == 'expansions'
  695. return {t for x in tree.find_data('expansion')
  696. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  697. class GrammarLoader:
  698. ERRORS = [
  699. ('Unclosed parenthesis', ['a: (\n']),
  700. ('Unmatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']),
  701. ('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']),
  702. ('Illegal name for rules or terminals', ['Aa:\n']),
  703. ('Alias expects lowercase name', ['a: -> "a"\n']),
  704. ('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']),
  705. ('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']),
  706. ('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']),
  707. ('Terminal names cannot contain dots', ['A.B\n']),
  708. ('%import expects a name', ['%import "a"\n']),
  709. ('%ignore expects a value', ['%ignore %import\n']),
  710. ]
  711. def __init__(self, global_keep_all_tokens):
  712. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  713. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  714. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o)
  715. for r, _p, xs, o in rules for i, x in enumerate(xs)]
  716. callback = ParseTreeBuilder(rules, ST).create_callback()
  717. import re
  718. lexer_conf = LexerConf(terminals, re, ['WS', 'COMMENT'])
  719. parser_conf = ParserConf(rules, callback, ['start'])
  720. lexer_conf.lexer_type = 'standard'
  721. parser_conf.parser_type = 'lalr'
  722. self.parser = ParsingFrontend(lexer_conf, parser_conf, {})
  723. self.canonize_tree = CanonizeTree()
  724. self.global_keep_all_tokens = global_keep_all_tokens
  725. def import_grammar(self, grammar_path, base_path=None, import_paths=[]):
  726. if grammar_path not in _imported_grammars:
  727. # import_paths take priority over base_path since they should handle relative imports and ignore everything else.
  728. to_try = import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
  729. for source in to_try:
  730. try:
  731. if callable(source):
  732. joined_path, text = source(base_path, grammar_path)
  733. else:
  734. joined_path = os.path.join(source, grammar_path)
  735. with open(joined_path, encoding='utf8') as f:
  736. text = f.read()
  737. except IOError:
  738. continue
  739. else:
  740. grammar = self.load_grammar(text, joined_path, import_paths)
  741. _imported_grammars[grammar_path] = grammar
  742. break
  743. else:
  744. # Search failed. Make Python throw a nice error.
  745. open(grammar_path, encoding='utf8')
  746. assert False
  747. return _imported_grammars[grammar_path]
  748. def load_grammar(self, grammar_text, grammar_name='<?>', import_paths=[]):
  749. """Parse grammar_text, verify, and create Grammar object. Display nice messages on error."""
  750. try:
  751. tree = self.canonize_tree.transform(self.parser.parse(grammar_text+'\n'))
  752. except UnexpectedCharacters as e:
  753. context = e.get_context(grammar_text)
  754. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  755. (e.line, e.column, grammar_name, context))
  756. except UnexpectedToken as e:
  757. context = e.get_context(grammar_text)
  758. error = e.match_examples(self.parser.parse, self.ERRORS, use_accepts=True)
  759. if error:
  760. raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  761. elif 'STRING' in e.expected:
  762. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  763. raise
  764. tree = PrepareGrammar().transform(tree)
  765. # Extract grammar items
  766. defs = classify(tree.children, lambda c: c.data, lambda c: c.children)
  767. term_defs = defs.pop('term', [])
  768. rule_defs = defs.pop('rule', [])
  769. statements = defs.pop('statement', [])
  770. assert not defs
  771. term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs]
  772. term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs]
  773. rule_defs = [options_from_rule(*x) for x in rule_defs]
  774. # Execute statements
  775. ignore, imports = [], {}
  776. overriding_rules = []
  777. for (stmt,) in statements:
  778. if stmt.data == 'ignore':
  779. t ,= stmt.children
  780. ignore.append(t)
  781. elif stmt.data == 'import':
  782. if len(stmt.children) > 1:
  783. path_node, arg1 = stmt.children
  784. else:
  785. path_node ,= stmt.children
  786. arg1 = None
  787. if isinstance(arg1, Tree): # Multi import
  788. dotted_path = tuple(path_node.children)
  789. names = arg1.children
  790. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  791. else: # Single import
  792. dotted_path = tuple(path_node.children[:-1])
  793. name = path_node.children[-1] # Get name from dotted path
  794. aliases = {name: arg1 or name} # Aliases if exist
  795. if path_node.data == 'import_lib': # Import from library
  796. base_path = None
  797. else: # Relative import
  798. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  799. try:
  800. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  801. except AttributeError:
  802. base_file = None
  803. else:
  804. base_file = grammar_name # Import relative to grammar file path if external grammar file
  805. if base_file:
  806. if isinstance(base_file, PackageResource):
  807. base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
  808. else:
  809. base_path = os.path.split(base_file)[0]
  810. else:
  811. base_path = os.path.abspath(os.path.curdir)
  812. try:
  813. import_base_path, import_aliases = imports[dotted_path]
  814. assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
  815. import_aliases.update(aliases)
  816. except KeyError:
  817. imports[dotted_path] = base_path, aliases
  818. elif stmt.data == 'declare':
  819. for t in stmt.children:
  820. term_defs.append([t.value, (None, None)])
  821. elif stmt.data == 'override_rule':
  822. r ,= stmt.children
  823. overriding_rules.append(options_from_rule(*r.children))
  824. else:
  825. assert False, stmt
  826. # import grammars
  827. for dotted_path, (base_path, aliases) in imports.items():
  828. grammar_path = os.path.join(*dotted_path) + EXT
  829. g = self.import_grammar(grammar_path, base_path=base_path, import_paths=import_paths)
  830. new_td, new_rd = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases)
  831. term_defs += new_td
  832. rule_defs += new_rd
  833. for r in overriding_rules:
  834. name = r[0]
  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)