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.

1222 lines
44 KiB

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