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.

1126 lines
41 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 numbers import Integral
  9. from .utils import bfs, Py36, logger, classify_bool, is_id_continue, is_id_start
  10. from .lexer import Token, TerminalDef, PatternStr, PatternRE
  11. from .parse_tree_builder import ParseTreeBuilder
  12. from .parser_frontends import ParsingFrontend
  13. from .common import LexerConf, ParserConf
  14. from .grammar import RuleOptions, Rule, Terminal, NonTerminal, Symbol
  15. from .utils import classify, suppress, dedup_list, Str
  16. from .exceptions import GrammarError, UnexpectedCharacters, UnexpectedToken
  17. from .tree import Tree, SlottedTree as ST
  18. from .visitors import Transformer, Visitor, v_args, Transformer_InPlace, Transformer_NonRecursive
  19. inline_args = v_args(inline=True)
  20. __path__ = os.path.dirname(__file__)
  21. IMPORT_PATHS = ['grammars']
  22. EXT = '.lark'
  23. _RE_FLAGS = 'imslux'
  24. _EMPTY = Symbol('__empty__')
  25. _TERMINAL_NAMES = {
  26. '.' : 'DOT',
  27. ',' : 'COMMA',
  28. ':' : 'COLON',
  29. ';' : 'SEMICOLON',
  30. '+' : 'PLUS',
  31. '-' : 'MINUS',
  32. '*' : 'STAR',
  33. '/' : 'SLASH',
  34. '\\' : 'BACKSLASH',
  35. '|' : 'VBAR',
  36. '?' : 'QMARK',
  37. '!' : 'BANG',
  38. '@' : 'AT',
  39. '#' : 'HASH',
  40. '$' : 'DOLLAR',
  41. '%' : 'PERCENT',
  42. '^' : 'CIRCUMFLEX',
  43. '&' : 'AMPERSAND',
  44. '_' : 'UNDERSCORE',
  45. '<' : 'LESSTHAN',
  46. '>' : 'MORETHAN',
  47. '=' : 'EQUAL',
  48. '"' : 'DBLQUOTE',
  49. '\'' : 'QUOTE',
  50. '`' : 'BACKQUOTE',
  51. '~' : 'TILDE',
  52. '(' : 'LPAR',
  53. ')' : 'RPAR',
  54. '{' : 'LBRACE',
  55. '}' : 'RBRACE',
  56. '[' : 'LSQB',
  57. ']' : 'RSQB',
  58. '\n' : 'NEWLINE',
  59. '\r\n' : 'CRLF',
  60. '\t' : 'TAB',
  61. ' ' : 'SPACE',
  62. }
  63. # Grammar Parser
  64. TERMINALS = {
  65. '_LPAR': r'\(',
  66. '_RPAR': r'\)',
  67. '_LBRA': r'\[',
  68. '_RBRA': r'\]',
  69. '_LBRACE': r'\{',
  70. '_RBRACE': r'\}',
  71. 'OP': '[+*]|[?](?![a-z])',
  72. '_COLON': ':',
  73. '_COMMA': ',',
  74. '_OR': r'\|',
  75. '_DOT': r'\.(?!\.)',
  76. '_DOTDOT': r'\.\.',
  77. 'TILDE': '~',
  78. 'RULE': '!?[_?]?[a-z][_a-z0-9]*',
  79. 'TERMINAL': '_?[A-Z][_A-Z0-9]*',
  80. 'STRING': r'"(\\"|\\\\|[^"\n])*?"i?',
  81. 'REGEXP': r'/(?!/)(\\/|\\\\|[^/])*?/[%s]*' % _RE_FLAGS,
  82. '_NL': r'(\r?\n)+\s*',
  83. 'WS': r'[ \t]+',
  84. 'COMMENT': r'\s*//[^\n]*',
  85. '_TO': '->',
  86. '_IGNORE': r'%ignore',
  87. '_OVERRIDE': r'%override',
  88. '_DECLARE': r'%declare',
  89. '_EXTEND': r'%extend',
  90. '_IMPORT': r'%import',
  91. 'NUMBER': r'[+-]?\d+',
  92. }
  93. RULES = {
  94. 'start': ['_list'],
  95. '_list': ['_item', '_list _item'],
  96. '_item': ['rule', 'term', 'ignore', 'import', 'declare', 'override', 'extend', '_NL'],
  97. 'rule': ['RULE template_params _COLON expansions _NL',
  98. 'RULE template_params _DOT NUMBER _COLON expansions _NL'],
  99. 'template_params': ['_LBRACE _template_params _RBRACE',
  100. ''],
  101. '_template_params': ['RULE',
  102. '_template_params _COMMA RULE'],
  103. 'expansions': ['alias',
  104. 'expansions _OR alias',
  105. 'expansions _NL _OR alias'],
  106. '?alias': ['expansion _TO RULE', 'expansion'],
  107. 'expansion': ['_expansion'],
  108. '_expansion': ['', '_expansion expr'],
  109. '?expr': ['atom',
  110. 'atom OP',
  111. 'atom TILDE NUMBER',
  112. 'atom TILDE NUMBER _DOTDOT NUMBER',
  113. ],
  114. '?atom': ['_LPAR expansions _RPAR',
  115. 'maybe',
  116. 'value'],
  117. 'value': ['terminal',
  118. 'nonterminal',
  119. 'literal',
  120. 'range',
  121. 'template_usage'],
  122. 'terminal': ['TERMINAL'],
  123. 'nonterminal': ['RULE'],
  124. '?name': ['RULE', 'TERMINAL'],
  125. 'maybe': ['_LBRA expansions _RBRA'],
  126. 'range': ['STRING _DOTDOT STRING'],
  127. 'template_usage': ['RULE _LBRACE _template_args _RBRACE'],
  128. '_template_args': ['value',
  129. '_template_args _COMMA value'],
  130. 'term': ['TERMINAL _COLON expansions _NL',
  131. 'TERMINAL _DOT NUMBER _COLON expansions _NL'],
  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 nr_deepcopy_tree(t):
  445. """Deepcopy tree `t` without recursion"""
  446. return Transformer_NonRecursive(False).transform(t)
  447. class Grammar:
  448. def __init__(self, rule_defs, term_defs, ignore):
  449. self.term_defs = term_defs
  450. self.rule_defs = rule_defs
  451. self.ignore = ignore
  452. def compile(self, start, terminals_to_keep):
  453. # We change the trees in-place (to support huge grammars)
  454. # So deepcopy allows calling compile more than once.
  455. term_defs = deepcopy(list(self.term_defs))
  456. rule_defs = [(n,p,nr_deepcopy_tree(t),o) for n,p,t,o in self.rule_defs]
  457. # ===================
  458. # Compile Terminals
  459. # ===================
  460. # Convert terminal-trees to strings/regexps
  461. for name, (term_tree, priority) in term_defs:
  462. if term_tree is None: # Terminal added through %declare
  463. continue
  464. expansions = list(term_tree.find_data('expansion'))
  465. if len(expansions) == 1 and not expansions[0].children:
  466. raise GrammarError("Terminals cannot be empty (%s)" % name)
  467. transformer = PrepareLiterals() * TerminalTreeToPattern()
  468. terminals = [TerminalDef(name, transformer.transform(term_tree), priority)
  469. for name, (term_tree, priority) in term_defs if term_tree]
  470. # =================
  471. # Compile Rules
  472. # =================
  473. # 1. Pre-process terminals
  474. anon_tokens_transf = PrepareAnonTerminals(terminals)
  475. transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals
  476. # 2. Inline Templates
  477. transformer *= ApplyTemplates(rule_defs)
  478. # 3. Convert EBNF to BNF (and apply step 1 & 2)
  479. ebnf_to_bnf = EBNF_to_BNF()
  480. rules = []
  481. i = 0
  482. while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
  483. name, params, rule_tree, options = rule_defs[i]
  484. i += 1
  485. if len(params) != 0: # Dont transform templates
  486. continue
  487. rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
  488. ebnf_to_bnf.rule_options = rule_options
  489. ebnf_to_bnf.prefix = name
  490. anon_tokens_transf.rule_options = rule_options
  491. tree = transformer.transform(rule_tree)
  492. res = ebnf_to_bnf.transform(tree)
  493. rules.append((name, res, options))
  494. rules += ebnf_to_bnf.new_rules
  495. assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
  496. # 4. Compile tree to Rule objects
  497. rule_tree_to_text = RuleTreeToText()
  498. simplify_rule = SimplifyRule_Visitor()
  499. compiled_rules = []
  500. for rule_content in rules:
  501. name, tree, options = rule_content
  502. simplify_rule.visit(tree)
  503. expansions = rule_tree_to_text.transform(tree)
  504. for i, (expansion, alias) in enumerate(expansions):
  505. if alias and name.startswith('_'):
  506. raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)"% (name, alias))
  507. empty_indices = [x==_EMPTY for x in expansion]
  508. if any(empty_indices):
  509. exp_options = copy(options) or RuleOptions()
  510. exp_options.empty_indices = empty_indices
  511. expansion = [x for x in expansion if x!=_EMPTY]
  512. else:
  513. exp_options = options
  514. assert all(isinstance(x, Symbol) for x in expansion), expansion
  515. rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
  516. compiled_rules.append(rule)
  517. # Remove duplicates of empty rules, throw error for non-empty duplicates
  518. if len(set(compiled_rules)) != len(compiled_rules):
  519. duplicates = classify(compiled_rules, lambda x: x)
  520. for dups in duplicates.values():
  521. if len(dups) > 1:
  522. if dups[0].expansion:
  523. raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
  524. % ''.join('\n * %s' % i for i in dups))
  525. # Empty rule; assert all other attributes are equal
  526. assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
  527. # Remove duplicates
  528. compiled_rules = list(set(compiled_rules))
  529. # Filter out unused rules
  530. while True:
  531. c = len(compiled_rules)
  532. used_rules = {s for r in compiled_rules
  533. for s in r.expansion
  534. if isinstance(s, NonTerminal)
  535. and s != r.origin}
  536. used_rules |= {NonTerminal(s) for s in start}
  537. compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules)
  538. for r in unused:
  539. logger.debug("Unused rule: %s", r)
  540. if len(compiled_rules) == c:
  541. break
  542. # Filter out unused terminals
  543. used_terms = {t.name for r in compiled_rules
  544. for t in r.expansion
  545. if isinstance(t, Terminal)}
  546. 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)
  547. if unused:
  548. logger.debug("Unused terminals: %s", [t.name for t in unused])
  549. return terminals, compiled_rules, self.ignore
  550. class PackageResource(object):
  551. """
  552. Represents a path inside a Package. Used by `FromPackageLoader`
  553. """
  554. def __init__(self, pkg_name, path):
  555. self.pkg_name = pkg_name
  556. self.path = path
  557. def __str__(self):
  558. return "<%s: %s>" % (self.pkg_name, self.path)
  559. def __repr__(self):
  560. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.path)
  561. class FromPackageLoader(object):
  562. """
  563. Provides a simple way of creating custom import loaders that load from packages via ``pkgutil.get_data`` instead of using `open`.
  564. This allows them to be compatible even from within zip files.
  565. Relative imports are handled, so you can just freely use them.
  566. pkg_name: The name of the package. You can probably provide `__name__` most of the time
  567. search_paths: All the path that will be search on absolute imports.
  568. """
  569. def __init__(self, pkg_name, search_paths=("", )):
  570. self.pkg_name = pkg_name
  571. self.search_paths = search_paths
  572. def __repr__(self):
  573. return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.search_paths)
  574. def __call__(self, base_path, grammar_path):
  575. if base_path is None:
  576. to_try = self.search_paths
  577. else:
  578. # Check whether or not the importing grammar was loaded by this module.
  579. if not isinstance(base_path, PackageResource) or base_path.pkg_name != self.pkg_name:
  580. # Technically false, but FileNotFound doesn't exist in python2.7, and this message should never reach the end user anyway
  581. raise IOError()
  582. to_try = [base_path.path]
  583. for path in to_try:
  584. full_path = os.path.join(path, grammar_path)
  585. try:
  586. text = pkgutil.get_data(self.pkg_name, full_path)
  587. except IOError:
  588. continue
  589. else:
  590. return PackageResource(self.pkg_name, full_path), text.decode()
  591. raise IOError()
  592. stdlib_loader = FromPackageLoader('lark', IMPORT_PATHS)
  593. def resolve_term_references(term_defs):
  594. # TODO Solve with transitive closure (maybe)
  595. term_dict = {k:t for k, (t,_p) in term_defs}
  596. assert len(term_dict) == len(term_defs), "Same name defined twice?"
  597. while True:
  598. changed = False
  599. for name, (token_tree, _p) in term_defs:
  600. if token_tree is None: # Terminal added through %declare
  601. continue
  602. for exp in token_tree.find_data('value'):
  603. item ,= exp.children
  604. if isinstance(item, Token):
  605. if item.type == 'RULE':
  606. raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
  607. if item.type == 'TERMINAL':
  608. term_value = term_dict[item]
  609. assert term_value is not None
  610. exp.children[0] = term_value
  611. changed = True
  612. if not changed:
  613. break
  614. for name, term in term_dict.items():
  615. if term: # Not just declared
  616. for child in term.children:
  617. ids = [id(x) for x in child.iter_subtrees()]
  618. if id(term) in ids:
  619. raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
  620. def options_from_rule(name, params, *x):
  621. if len(x) > 1:
  622. priority, expansions = x
  623. priority = int(priority)
  624. else:
  625. expansions ,= x
  626. priority = None
  627. params = [t.value for t in params.children] if params is not None else [] # For the grammar parser
  628. keep_all_tokens = name.startswith('!')
  629. name = name.lstrip('!')
  630. expand1 = name.startswith('?')
  631. name = name.lstrip('?')
  632. return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
  633. template_source=(name if params else None))
  634. def symbols_from_strcase(expansion):
  635. return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion]
  636. @inline_args
  637. class PrepareGrammar(Transformer_InPlace):
  638. def terminal(self, name):
  639. return name
  640. def nonterminal(self, name):
  641. return name
  642. def _find_used_symbols(tree):
  643. assert tree.data == 'expansions'
  644. return {t for x in tree.find_data('expansion')
  645. for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))}
  646. def _get_parser():
  647. try:
  648. return _get_parser.cache
  649. except AttributeError:
  650. terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
  651. rules = [options_from_rule(name, None, x) for name, x in RULES.items()]
  652. rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o)
  653. for r, _p, xs, o in rules for i, x in enumerate(xs)]
  654. callback = ParseTreeBuilder(rules, ST).create_callback()
  655. import re
  656. lexer_conf = LexerConf(terminals, re, ['WS', 'COMMENT'])
  657. parser_conf = ParserConf(rules, callback, ['start'])
  658. lexer_conf.lexer_type = 'standard'
  659. parser_conf.parser_type = 'lalr'
  660. _get_parser.cache = ParsingFrontend(lexer_conf, parser_conf, {})
  661. return _get_parser.cache
  662. GRAMMAR_ERRORS = [
  663. ('Unclosed parenthesis', ['a: (\n']),
  664. ('Unmatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']),
  665. ('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']),
  666. ('Illegal name for rules or terminals', ['Aa:\n']),
  667. ('Alias expects lowercase name', ['a: -> "a"\n']),
  668. ('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']),
  669. ('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']),
  670. ('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']),
  671. ('Terminal names cannot contain dots', ['A.B\n']),
  672. ('%import expects a name', ['%import "a"\n']),
  673. ('%ignore expects a value', ['%ignore %import\n']),
  674. ]
  675. def _parse_grammar(text, name, start='start'):
  676. try:
  677. tree = _get_parser().parse(text + '\n', start)
  678. except UnexpectedCharacters as e:
  679. context = e.get_context(text)
  680. raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
  681. (e.line, e.column, name, context))
  682. except UnexpectedToken as e:
  683. context = e.get_context(text)
  684. error = e.match_examples(_get_parser().parse, GRAMMAR_ERRORS, use_accepts=True)
  685. if error:
  686. raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context))
  687. elif 'STRING' in e.expected:
  688. raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context))
  689. raise
  690. return PrepareGrammar().transform(tree)
  691. class GrammarBuilder:
  692. def __init__(self, global_keep_all_tokens=False, import_paths=None):
  693. self.global_keep_all_tokens = global_keep_all_tokens
  694. self.import_paths = import_paths or []
  695. self._definitions = {}
  696. self._ignore_names = []
  697. def _is_term(self, name):
  698. # Imported terminals are of the form `Path__to__Grammar__file__TERMINAL_NAME`
  699. # Only the last part is the actual name, and the rest might contain mixed case
  700. return name.rpartition('__')[-1].isupper()
  701. def _grammar_error(self, msg, *names):
  702. args = {}
  703. for i, name in enumerate(names, start=1):
  704. postfix = '' if i == 1 else str(i)
  705. args['name' + postfix] = name
  706. args['type' + postfix] = lowercase_type = ("rule", "terminal")[self._is_term(name)]
  707. args['Type' + postfix] = lowercase_type.title()
  708. raise GrammarError(msg.format(**args))
  709. def _check_options(self, name, options):
  710. if self._is_term(name):
  711. if options is None:
  712. options = 1
  713. # if we don't use Integral here, we run into python2.7/python3 problems with long vs int
  714. elif not isinstance(options, Integral):
  715. raise GrammarError("Terminal require a single int as 'options' (e.g. priority), got %s" % (type(options),))
  716. else:
  717. if options is None:
  718. options = RuleOptions()
  719. elif not isinstance(options, RuleOptions):
  720. raise GrammarError("Rules require a RuleOptions instance as 'options'")
  721. if self.global_keep_all_tokens:
  722. options.keep_all_tokens = True
  723. return options
  724. def _define(self, name, exp, params=(), options=None, override=False):
  725. if (name in self._definitions) ^ override:
  726. if override:
  727. self._grammar_error("Cannot override a nonexisting {type} {name}", name)
  728. else:
  729. self._grammar_error("{Type} '{name}' defined more than once", name)
  730. if name.startswith('__'):
  731. self._grammar_error('Names starting with double-underscore are reserved (Error at {name})', name)
  732. self._definitions[name] = (params, exp, self._check_options(name, options))
  733. def _extend(self, name, exp, params=(), options=None):
  734. if name not in self._definitions:
  735. self._grammar_error("Can't extend {type} {name} as it wasn't defined before", name)
  736. if tuple(params) != tuple(self._definitions[name][0]):
  737. self._grammar_error("Cannot extend {type} with different parameters: {name}", name)
  738. # TODO: think about what to do with 'options'
  739. base = self._definitions[name][1]
  740. while len(base.children) == 2:
  741. assert isinstance(base.children[0], Tree) and base.children[0].data == 'expansions', base
  742. base = base.children[0]
  743. base.children.insert(0, exp)
  744. def _ignore(self, exp_or_name):
  745. if isinstance(exp_or_name, str):
  746. self._ignore_names.append(exp_or_name)
  747. else:
  748. assert isinstance(exp_or_name, Tree)
  749. t = exp_or_name
  750. if t.data == 'expansions' and len(t.children) == 1:
  751. t2 ,= t.children
  752. if t2.data=='expansion' and len(t2.children) == 1:
  753. item ,= t2.children
  754. if item.data == 'value':
  755. item ,= item.children
  756. if isinstance(item, Token) and item.type == 'TERMINAL':
  757. self._ignore_names.append(item.value)
  758. return
  759. name = '__IGNORE_%d'% len(self._ignore_names)
  760. self._ignore_names.append(name)
  761. self._definitions[name] = ((), t, 1)
  762. def _declare(self, *names):
  763. for name in names:
  764. self._define(name, None)
  765. def _mangle_exp(self, exp, mangle):
  766. if mangle is None:
  767. return exp
  768. exp = deepcopy(exp) # TODO: is this needed
  769. for t in exp.iter_subtrees():
  770. for i, c in enumerate(t.children):
  771. if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'):
  772. t.children[i] = Token(c.type, mangle(c.value))
  773. return exp
  774. def _unpack_definition(self, tree, mangle):
  775. if tree.data == 'rule':
  776. name, params, exp, opts = options_from_rule(*tree.children)
  777. else:
  778. name = tree.children[0].value
  779. params = () # TODO terminal templates
  780. opts = int(tree.children[1]) if len(tree.children) == 3 else 1 # priority
  781. exp = tree.children[-1]
  782. if mangle is not None:
  783. params = tuple(mangle(p) for p in params)
  784. name = mangle(name)
  785. exp = self._mangle_exp(exp, mangle)
  786. return name, exp, params, opts
  787. def _unpack_import(self, stmt, grammar_name):
  788. if len(stmt.children) > 1:
  789. path_node, arg1 = stmt.children
  790. else:
  791. path_node, = stmt.children
  792. arg1 = None
  793. if isinstance(arg1, Tree): # Multi import
  794. dotted_path = tuple(path_node.children)
  795. names = arg1.children
  796. aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
  797. else: # Single import
  798. dotted_path = tuple(path_node.children[:-1])
  799. name = path_node.children[-1] # Get name from dotted path
  800. aliases = {name.value: (arg1 or name).value} # Aliases if exist
  801. if path_node.data == 'import_lib': # Import from library
  802. base_path = None
  803. else: # Relative import
  804. if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
  805. try:
  806. base_file = os.path.abspath(sys.modules['__main__'].__file__)
  807. except AttributeError:
  808. base_file = None
  809. else:
  810. base_file = grammar_name # Import relative to grammar file path if external grammar file
  811. if base_file:
  812. if isinstance(base_file, PackageResource):
  813. base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
  814. else:
  815. base_path = os.path.split(base_file)[0]
  816. else:
  817. base_path = os.path.abspath(os.path.curdir)
  818. return dotted_path, base_path, aliases
  819. def load_grammar(self, grammar_text, grammar_name="<?>", mangle=None):
  820. tree = _parse_grammar(grammar_text, grammar_name)
  821. imports = {} # imports are collect over the whole file to prevent duplications
  822. for stmt in tree.children:
  823. if stmt.data == 'import':
  824. dotted_path, base_path, aliases = self._unpack_import(stmt, grammar_name)
  825. try:
  826. import_base_path, import_aliases = imports[dotted_path]
  827. assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
  828. import_aliases.update(aliases)
  829. except KeyError:
  830. imports[dotted_path] = base_path, aliases
  831. for dotted_path, (base_path, aliases) in imports.items():
  832. self.do_import(dotted_path, base_path, aliases, mangle)
  833. for stmt in tree.children:
  834. if stmt.data in ('term', 'rule'):
  835. self._define(*self._unpack_definition(stmt, mangle))
  836. elif stmt.data == 'override':
  837. r ,= stmt.children
  838. self._define(*self._unpack_definition(r, mangle), override=True)
  839. elif stmt.data == 'extend':
  840. r ,= stmt.children
  841. self._extend(*self._unpack_definition(r, mangle))
  842. elif stmt.data == 'ignore':
  843. # if mangle is not None, we shouldn't apply ignore, since we aren't in a toplevel grammar
  844. if mangle is None:
  845. self._ignore(*stmt.children)
  846. elif stmt.data == 'declare':
  847. names = [t.value for t in stmt.children]
  848. if mangle is None:
  849. self._declare(*names)
  850. else:
  851. self._declare(*map(mangle, names))
  852. elif stmt.data == 'import':
  853. pass
  854. else:
  855. assert False, stmt
  856. def do_import(self, dotted_path, base_path, aliases, base_mangle=None):
  857. mangle = self.get_mangle('__'.join(dotted_path), aliases, base_mangle)
  858. grammar_path = os.path.join(*dotted_path) + EXT
  859. to_try = self.import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
  860. for source in to_try:
  861. try:
  862. if callable(source):
  863. joined_path, text = source(base_path, grammar_path)
  864. else:
  865. joined_path = os.path.join(source, grammar_path)
  866. with open(joined_path, encoding='utf8') as f:
  867. text = f.read()
  868. except IOError:
  869. continue
  870. else:
  871. self.load_grammar(text, joined_path, mangle)
  872. break
  873. else:
  874. # Search failed. Make Python throw a nice error.
  875. open(grammar_path, encoding='utf8')
  876. 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,)
  877. def get_mangle(self, prefix, aliases, base_mangle=None):
  878. def mangle(s):
  879. if s in aliases:
  880. s = aliases[s]
  881. else:
  882. if s[0] == '_':
  883. s = '_%s__%s' % (prefix, s[1:])
  884. else:
  885. s = '%s__%s' % (prefix, s)
  886. if base_mangle is not None:
  887. s = base_mangle(s)
  888. return s
  889. return mangle
  890. def check(self):
  891. for name, (params, exp, options) in self._definitions.items():
  892. for i, p in enumerate(params):
  893. if p in self._definitions:
  894. raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
  895. if p in params[:i]:
  896. raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
  897. if exp is None: # Remaining checks don't work for abstract rules/terminals
  898. continue
  899. for temp in exp.find_data('template_usage'):
  900. sym = temp.children[0]
  901. args = temp.children[1:]
  902. if sym not in params:
  903. if sym not in self._definitions:
  904. self._grammar_error("Template '%s' used but not defined (in {type} {name})" % sym, name)
  905. if len(args) != len(self._definitions[sym][0]):
  906. expected, actual = len(self._definitions[sym][0]), len(args)
  907. self._grammar_error("Wrong number of template arguments used for {name} "
  908. "(expected %s, got %s) (in {type2} {name2})" % (expected, actual), sym, name)
  909. for sym in _find_used_symbols(exp):
  910. if sym not in self._definitions and sym not in params:
  911. self._grammar_error("{Type} '{name}' used but not defined (in {type2} {name2})", sym, name)
  912. if not set(self._definitions).issuperset(self._ignore_names):
  913. raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(self._ignore_names) - set(self._definitions)))
  914. def build(self):
  915. self.check()
  916. rule_defs = []
  917. term_defs = []
  918. for name, (params, exp, options) in self._definitions.items():
  919. if self._is_term(name):
  920. assert len(params) == 0
  921. term_defs.append((name, (exp, options)))
  922. else:
  923. rule_defs.append((name, params, exp, options))
  924. resolve_term_references(term_defs)
  925. return Grammar(rule_defs, term_defs, self._ignore_names)
  926. def load_grammar(grammar, source, import_paths, global_keep_all_tokens):
  927. builder = GrammarBuilder(global_keep_all_tokens, import_paths)
  928. builder.load_grammar(grammar, source)
  929. return builder.build()