"""Edits a function or impl chunk needs when it moves one module down: visibility and `super::` / `self::` paths.""" import re from .items import CLOSE, OPEN, _keyword, _skip_attrs, _skip_visibility, significant from .lexer import tokenize VIS = "pub(super) " INCLUDE = re.compile(r'(include_(?:str|bytes)!\(\s*")(?=[^/])') def _is_double_colon(sig, k): return k >= 1 and sig[k].text == ":" and sig[k - 1].text == ":" def _restricted_visibility_edits(sig): """`pub(super)` and `pub(self)` name a scope relative to the module; one level down they need `pub(in ...)`.""" edits = [] for k, tok in enumerate(sig[:-3]): if tok.text == "pub" and sig[k + 1].text == "(" and sig[k + 3].text == ")": inner = sig[k + 2] replacement = {"super": "in super::super", "self": "in super"}.get(inner.text) if replacement: edits.append((inner.start, len(inner.text), replacement)) return edits def _path_edits(sig): """(position, length, replacement) for every path that starts with `super` or `self` (not after `::`).""" edits = [] for k, tok in enumerate(sig[:-2]): follows_path = k >= 2 and _is_double_colon(sig, k - 1) if tok.kind != "ident" or follows_path or not _is_double_colon(sig, k + 2): continue if tok.text == "super": edits.append((tok.start, 5, "super::super")) elif tok.text == "self": edits.append((tok.start, 4, "super")) return edits def _assoc_item_starts(sig): """Indexes in `sig` where an associated item of an impl body (brace depth 1) begins.""" starts, depth = [], 0 for k, tok in enumerate(sig): depth += (tok.text in OPEN) - (tok.text in CLOSE) if k > 0 and sig[k - 1].text in ("{", "}", ";") and depth == 1 and tok.text != "}": starts.append(k) return starts def _assoc_visibility_edits(sig): """`pub(super)` before every private fn or const of an inherent impl body.""" edits = [] for k in _assoc_item_starts(sig): first = _skip_attrs(sig, k) if first < len(sig) and sig[first].text != "pub" and _keyword(sig, first)[0] in ("fn", "const"): edits.append((sig[first].start, 0, VIS)) return edits def _fn_visibility_edits(sig): """`pub(super)` for a free fn that has no visibility.""" first = _skip_attrs(sig, 0) if sig[first].text == "pub" or _keyword(sig, first)[0] != "fn": return [] return [(sig[first].start, 0, VIS)] def apply_edits(text, edits): for pos, length, replacement in sorted(edits, reverse=True): text = text[:pos] + replacement + text[pos + length:] return text def retarget(chunk, kind, inherent): """The chunk (one fn or impl, from its leading comments on) as it must read inside a child module.""" sig = significant(tokenize(chunk)) edits = _path_edits(sig) + _restricted_visibility_edits(sig) if kind == "fn": edits += _fn_visibility_edits(sig) elif inherent: edits += _assoc_visibility_edits(sig) return INCLUDE.sub(lambda m: m.group(1) + "../", apply_edits(chunk, edits))