"""Cut one long inherent `impl` block into several `impl` blocks of the same type, between its associated items.""" import re from .items import parse_items, significant from .lexer import tokenize DOC_LINE = re.compile(r"^\s*(///|#\[\s*doc\b)") def _header_end(chunk): """(index of the opening `{` of the impl body, index of its closing `}`) in `chunk`, or None.""" sig = significant(tokenize(chunk)) keyword = next((k for k, t in enumerate(sig) if t.text == "impl"), None) if keyword is None: return None depth, opening = 0, None for tok in sig[keyword:]: depth += (tok.text in "([") - (tok.text in ")]") if tok.text == "{" and depth == 0: opening = tok.start break return (opening, sig[-1].start) if opening is not None and sig[-1].text == "}" else None def _without_docs(header): return "\n".join(row for row in header.split("\n") if not DOC_LINE.match(row)) def _line_count(text): return text.count("\n") + 1 def _pack(items, body, target): """Consecutive associated items packed into parts of about `target` lines.""" parts, current = [], [] for item in items: if current and _line_count(body[current[0].start:item.end]) > target: parts.append(current) current = [] current.append(item) return parts + ([current] if current else []) def split_impl(chunk, target): """The impl blocks that replace `chunk`: one when it is short or has fewer than two associated items.""" bounds = _header_end(chunk) if bounds is None or _line_count(chunk) <= target: return [chunk] opening, closing = bounds header, body = chunk[:opening + 1], chunk[opening + 1:closing] parts = _pack(parse_items(body), body, target) if len(parts) < 2: return [chunk] blocks = [] for n, part in enumerate(parts): end = len(body) if n == len(parts) - 1 else part[-1].end text = header if n == 0 else _without_docs(header) blocks.append(text + body[0 if n == 0 else part[0].start:end].rstrip() + "\n}") return blocks