"""Rust functions of a source text: qualified key, span and the five measures (see rmetrics for the rules). A function runs from its `fn` keyword to the closing brace of its body, so its line count is signature plus body. Its key is the chain of enclosing `impl`/`trait`/`mod`/`fn` names and its own name (`Type::method`, `Trait for Type::method`, `helper::inner`); a repeated key gets `#2`, `#3` in order of appearance. """ import pathlib import re import sys from collections import namedtuple sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "dev")) from rustsplit.lexer import tokenize # noqa: E402 from . import model, rmetrics # noqa: E402 Tok = namedtuple("Tok", "kind text line pos") ITEMS = ("impl", "trait", "mod") SKIP_IDENTS = frozenset(("dyn", "mut", "const", "unsafe", "for", "impl")) def significant(text): """Tokens without whitespace and comments, each with its 1-based line and character position.""" out, line = [], 1 for tok in tokenize(text): if tok.kind not in ("ws", "comment"): out.append(Tok(tok.kind, tok.text, line, tok.start)) line += tok.text.count("\n") return out def _punct(tok): return tok.text if tok.kind == "punct" else "" def _paren_delta(tok): """+1 for `(` and `[`, -1 for `)` and `]`, else 0.""" text = _punct(tok) return 1 if text and text in "([" else (-1 if text and text in ")]" else 0) def _header_end(toks, j): """Index of the first `{` or `;` at bracket depth 0 from `j` on: (index, text); (None, "") when there is none.""" depth = 0 for k in range(j, len(toks)): depth += _paren_delta(toks[k]) if depth == 0 and _punct(toks[k]) in ("{", ";"): return k, toks[k].text return None, "" def body_start(toks, j): """Index of the `{` that opens the body of the fn whose name is before `j`; None for a declaration ending in `;`.""" end, text = _header_end(toks, j) return end if text == "{" else None def _item_position(toks, i): """An `impl`/`trait`/`mod` keyword starts an item (not `-> impl Trait` or `x: impl Fn()`).""" if i == 0: return True prev = toks[i - 1] modifier = prev.kind == "ident" and prev.text in ("unsafe", "pub", "default") return prev.text in (";", "}", "{", "]", ")") or modifier def _is_arrow(toks, j): return j > 0 and toks[j].text == ">" and toks[j - 1].text == "-" and toks[j - 1].pos + 1 == toks[j].pos def _angle(toks, j): """+1 for `<`, -1 for a closing `>` (not the one of `->`), else 0.""" if toks[j].text == "<": return 1 return -1 if toks[j].text == ">" and not _is_arrow(toks, j) else 0 def _skip_generics(hdr): """Index after the leading `<...>` of an impl header (0 when there is none).""" if not hdr or hdr[0].text != "<": return 0 depth = 0 for j in range(len(hdr)): depth += _angle(hdr, j) if depth == 0: return j + 1 return len(hdr) def _last_ident(tokens): """The last identifier of a path or type at angle depth 0, before any `where`.""" depth, found = 0, "_" for j, tok in enumerate(tokens): depth += _angle(tokens, j) if tok.kind == "ident" and tok.text == "where": break if tok.kind == "ident" and depth == 0 and tok.text not in SKIP_IDENTS: found = tok.text return found def _impl_label(hdr): hdr = hdr[_skip_generics(hdr):] depth = 0 for j, tok in enumerate(hdr): depth += _angle(hdr, j) if tok.kind == "ident" and tok.text == "for" and depth == 0: return f"{_last_ident(hdr[:j])} for {_last_ident(hdr[j + 1:])}" return _last_ident(hdr) def item_header(toks, i): """(label, index of the opening brace) of an `impl`/`trait`/`mod` item at `i`; None when it has no body.""" brace, text = _header_end(toks, i + 1) if text != "{": return None hdr = toks[i + 1:brace] if toks[i].text == "impl": return _impl_label(hdr), brace return next((t.text for t in hdr if t.kind == "ident"), "_"), brace def _open_bracket(toks, j): depth = 0 for k in range(j, -1, -1): depth += 1 if toks[k].text == "]" else (-1 if toks[k].text == "[" else 0) if depth == 0: return k return -1 def _list_start(toks, j): """Index of the `(` that opens the parameter list after the fn name (past generics `<...>`); None without one.""" depth = 0 for k in range(j, len(toks)): depth += _angle(toks, k) if depth == 0 and _punct(toks[k]) == "(": return k if depth == 0 and _punct(toks[k]) in ("{", ";"): return None return None def _depth_step(toks, k): """+1 for an opening `( [ { <`, -1 for the closing one (not the `>` of `->`), else 0.""" text = _punct(toks[k]) if text and text in "([{": return 1 return -1 if text and text in ")]}" else _angle(toks, k) def param_count(toks, j): """Parameters of the fn whose name is before `j`, `self` included: the non-empty comma-separated parts.""" start = _list_start(toks, j) if start is None: return 0 depth, count, part = 1, 0, False for k in range(start + 1, len(toks)): depth += _depth_step(toks, k) if depth == 0: break if depth == 1 and _punct(toks[k]) == ",": count, part = count + part, False else: part = True return count + part def _is_test_attr(attr): return "cfg(" in attr and re.search(r"\btest\b", attr) is not None and "not(test" not in attr def has_test_cfg(toks, i): """True when the item at `i` carries a `#[cfg(...test...)]` attribute.""" j = i - 1 while j >= 0 and toks[j].text == "pub": j -= 1 while j >= 0 and toks[j].text == "]": k = _open_bracket(toks, j) if k < 1 or toks[k - 1].text != "#": return False if _is_test_attr("".join(t.text for t in toks[k:j + 1])): return True j = k - 2 return False class _Rec: def __init__(self, name, key, start, body): self.name, self.key, self.start, self.body = name, key, start, body self.test, self.params = False, 0 self.end = -1 self.children = [] class _Frame: def __init__(self, label, rec, test): self.label, self.rec, self.test = label, rec, test class _Scanner: def __init__(self, toks): self.toks, self.stack, self.recs = toks, [], [] self.fn_at, self.item_at, self.counts = {}, {}, {} def run(self): for i, tok in enumerate(self.toks): if tok.kind == "ident": self.on_ident(i, tok.text) elif tok.text == "{" and tok.kind == "punct": self.push(i) elif tok.text == "}" and tok.kind == "punct": self.pop(i) return self.recs def on_ident(self, i, text): if text == "fn": self.on_fn(i) elif text in ITEMS and _item_position(self.toks, i): self.on_item(i) def on_fn(self, i): if i + 1 >= len(self.toks) or self.toks[i + 1].kind != "ident": return body = body_start(self.toks, i + 2) if body is None: return name = self.toks[i + 1].text key = "::".join([f.label for f in self.stack if f.label] + [name]) self.counts[key] = self.counts.get(key, 0) + 1 key += f"#{self.counts[key]}" if self.counts[key] > 1 else "" rec = _Rec(name, key, i, body) rec.test = any(f.test for f in self.stack) rec.params = param_count(self.toks, i + 2) self.fn_at[body] = rec def on_item(self, i): header = item_header(self.toks, i) if header: label, brace = header self.item_at[brace] = (label, self.toks[i].text == "mod" and has_test_cfg(self.toks, i)) def push(self, i): rec = self.fn_at.pop(i, None) label, test = self.item_at.pop(i, (None, False)) self.stack.append(_Frame(rec.name if rec else label, rec, test)) def pop(self, i): if not self.stack: return frame = self.stack.pop() if frame.rec is None: return frame.rec.end = i self.recs.append(frame.rec) outer = next((f for f in reversed(self.stack) if f.rec), None) if outer is not None: outer.rec.children.append((frame.rec.start, i)) def scan(text, wide): """[Fn] of a Rust source text; `wide` is the set of line numbers wider than the limit.""" toks = significant(text) result = [] for rec in _Scanner(toks).run(): complexity, nesting = rmetrics.metrics(toks, rec.body + 1, rec.end, rec.children) first, last = toks[rec.start].line, toks[rec.end].line result.append(model.Fn(rec.key, first, last, last - first + 1, complexity, nesting, model.count_wide(wide, first, last), rec.test, rec.params)) return sorted(result, key=lambda fn: fn.start)