"""Complexity and nesting of one Rust function body, from tokens (no parser). complexity = 1 + decision points. A decision point is: an `if` (so `else if` and `if let` count once), a `while`, a `for` loop, a `loop`, a `&&`, a `||` (only when it follows an operand, so `&&x` and `|| body` do not count), a `?`, and every `match` arm after the first one of its match. A guard `if` in an arm counts as an `if`. Nested `fn` items are measured on their own and left out of the function that contains them; closures are part of their function. nesting = the deepest chain of blocks inside the body (the body itself is depth 0): the block of an `if`, `else`, `while`, `for`, `loop`, `match`, `unsafe`, `async`, a closure `{ }` and a bare block each add one. A match arm block `=> { }`, a struct literal or pattern `Foo { }` and a macro `name! { }` add nothing. """ NOT_OPERAND = frozenset( "if else match while for loop in return let mut ref move as break continue where fn use pub impl dyn unsafe async " "static const type struct enum trait mod".split()) def _kind_after(toks, i): """What the `{` at `i` opens when no `if/while/for/match` is waiting for it: count, arm or other.""" prev = toks[i - 1] if prev.text == ">" and i >= 2 and toks[i - 2].text == "=" and toks[i - 2].pos + 1 == prev.pos: return "arm" if prev.text == "!" or (prev.kind == "ident" and prev.text[0].isupper()): return "other" return "count" def _after_operand(toks, i): """True when the token before `i` ends an operand, so a `&&` or `||` at `i` is a boolean operator.""" if i == 0: return False prev = toks[i - 1] if prev.kind in ("number", "string", "char") or prev.text in (")", "]", "?"): return True return prev.kind == "ident" and prev.text not in NOT_OPERAND class _Walk: def __init__(self, toks): self.toks = toks self.points = self.arms = self.matches = 0 self.paren = self.depth = self.deepest = 0 self.pending = [] # paren depth of each `if/while/for/match` still waiting for its block self.stack = [] # kind of each open brace self.skip_to = -1 def visit(self, i): tok = self.toks[i] if i <= self.skip_to: return if tok.kind == "ident": self.keyword(i, tok.text) elif tok.kind == "punct": self.punct(i, tok.text) def keyword(self, i, text): if text == "match": self.matches += 1 elif text == "loop": self.points += 1 elif text == "for" and self.toks[i + 1].text == "<": return elif text in ("if", "while", "for"): self.points += 1 if text in ("if", "while", "for", "match"): self.pending.append(self.paren) def punct(self, i, text): if text in "([": self.paren += 1 elif text in ")]": self.paren -= 1 self.drop_pending(self.paren + 1) elif text == ";": self.drop_pending(self.paren) elif text == "?": self.points += 1 elif text in ("{", "}"): self.brace(i, text) elif text in ("&", "|", "="): self.operator(i, text) def drop_pending(self, floor): """Forget the `if/while/for/match` that can no longer get a block: those at `floor` or deeper.""" while self.pending and self.pending[-1] >= floor: self.pending.pop() def brace(self, i, text): if text == "}": if self.stack and self.stack.pop() == "count": self.depth -= 1 return if self.pending and self.pending[-1] == self.paren: self.pending.pop() kind = "count" else: kind = _kind_after(self.toks, i) self.stack.append(kind) if kind == "count": self.depth += 1 self.deepest = max(self.deepest, self.depth) def operator(self, i, text): nxt = self.toks[i + 1] if i + 1 < len(self.toks) else None if text == "=": self.arms += 1 if nxt is not None and nxt.text == ">" and nxt.pos == self.toks[i].pos + 1 else 0 elif nxt is not None and nxt.text == text and nxt.pos == self.toks[i].pos + 1: self.skip_to = i + 1 self.points += 1 if _after_operand(self.toks, i) else 0 def metrics(toks, lo, hi, skips): """(complexity, nesting) of toks[lo:hi], leaving out the (first, last) token spans in `skips`.""" walk = _Walk(toks) skips = sorted(skips) i, at = lo, 0 while i < hi: if at < len(skips) and i == skips[at][0]: i, at = skips[at][1] + 1, at + 1 continue walk.visit(i) i += 1 return 1 + walk.points + max(0, walk.arms - walk.matches), walk.deepest