load_grammar.py 53 KB

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