Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions explain_my_code/adapters/treesitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,10 +283,33 @@ def lower(self, ts_node: TSNode) -> list[Node]:
)
node.extend(self.synth_children(ts_node, kind))
if node_type not in self.LEAVES:
# Grammars without an `else_clause` (Java) put the else body straight in the
# `alternative` field. It gets the ELSE node JavaScript and C++ already have,
# so the walkthrough and the metrics see the same shape in every language.
alternative = _field(ts_node, "alternative") if kind is Kind.BRANCH else None
for child in self.recurse_into(ts_node, kind):
node.extend(self.lower(child))
lowered = self.lower(child)
if (
alternative is not None
and child == alternative
and child.type not in {"else_clause", "if_statement"}
):
lowered = [self._synthetic_else(ts_node, child, lowered)]
node.extend(lowered)
return [node]

def _synthetic_else(self, if_node: TSNode, alternative: TSNode, body: list[Node]) -> Node:
keyword = next((c for c in if_node.children if c.type == "else"), alternative)
start_row, start_col = keyword.start_point
body_row, body_col = alternative.start_point
if body_row > start_row:
span = Span(start_row + 1, start_col, body_row, 10_000)
else:
span = Span(start_row + 1, start_col, body_row + 1, max(body_col, start_col + 1))
node = Node(kind=Kind.ELSE, span=span, name="else", meta=self.meta_else(alternative))
node.extend(body)
return node

def synth_children(self, ts_node: TSNode, kind: Kind) -> list[Node]:
"""IR children with no 1:1 grammar node: parameters, mostly.

Expand Down Expand Up @@ -343,6 +366,12 @@ def span_for(self, ts_node: TSNode, kind: Kind) -> Span:

def kind_for(self, ts_node: TSNode) -> Kind | None:
node_type = ts_node.type
if node_type == "else_clause" and any(
c.type == "if_statement" for c in ts_node.named_children
):
# `else if` is one step of the chain, not an `else` holding a new `if`: let
# the inner `if` (marked `is_elif`) stand for it, as in Python and Java.
return None
if node_type in self.LITERAL_TYPES:
return Kind.LITERAL
kind = self.KINDS.get(node_type)
Expand Down Expand Up @@ -448,13 +477,26 @@ def _meta_branch(self, ts_node: TSNode) -> dict[str, Any]:
is_guard = len(statements) == 1 and statements[0].type in {
"return_statement", "break_statement", "continue_statement", "throw_statement",
}
# `is_elif` marks the `if` that IS an else branch, as the Python adapter does:
# inside an `else_clause` (JS, C++) or straight in the `alternative` field (Java).
parent = ts_node.parent
is_elif = parent is not None and (
parent.type == "else_clause"
or (parent.type == "if_statement" and _field(parent, "alternative") == ts_node)
)
return {
"condition": condition.strip("()"),
"has_else": alternative is not None,
"is_elif": alternative is not None and alternative.type == "if_statement",
"is_elif": is_elif,
# Tree-sitter nests the rest of an if/else chain under the `if` it continues;
# Python lays it out beside it. The metrics need to know which.
"continues_parent": is_elif,
"is_guard": is_guard,
}

def meta_else(self, ts_node: TSNode) -> dict[str, Any]:
return {"continues_parent": True}

def _meta_while(self, ts_node: TSNode) -> dict[str, Any]:
condition = _field_text(ts_node, "condition", 56).strip("()")
return {
Expand Down
67 changes: 58 additions & 9 deletions explain_my_code/analysis/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,18 +100,30 @@ def cyclomatic_of(node: Node) -> int:

A short-circuiting `a and b and c` contributes two, not one. Each operand after the
first is its own branch at runtime.

For a function, functions nested inside it are scored separately and left out. For
the whole file every decision counts.
"""
total = 1
for current in node.walk():
if current is not node and current.kind in CALLABLE_KINDS:
continue # nested functions are scored separately
own_body_only = node.kind in CALLABLE_KINDS
stack = list(node.children)
while stack:
current = stack.pop()
if own_body_only and current.kind in CALLABLE_KINDS:
continue
if current.kind is Kind.BOOLOP:
total += max(1, int(current.meta.get("operand_count", 2)) - 1)
elif current.kind in DECISION_KINDS:
total += 1
stack.extend(current.children)
return total


def _continues_chain(node: Node) -> bool:
"""`else` and `else if`: the rest of a decision that has already been counted."""
return node.kind is Kind.ELSE or bool(node.kind is Kind.BRANCH and node.meta.get("is_elif"))


def cognitive_of(node: Node) -> int:
"""SonarSource cognitive complexity: how hard the flow is to hold in your head.

Expand All @@ -129,9 +141,12 @@ def visit(current: Node, nesting: int) -> None:
increment = 0
deeper = nesting
if child.kind in NESTING_KINDS:
# `else if` is a continuation of one decision, not a fresh nesting level.
if child.meta.get("is_elif"):
if _continues_chain(child):
# `else` / `else if` add one, with no nesting penalty, and their body
# sits one level inside the chain's `if`. Tree-sitter hangs them under
# that `if`, which already added the level; Python puts them beside it.
increment = 1
deeper = nesting if child.meta.get("continues_parent") else nesting + 1
else:
increment = 1 + nesting
deeper = nesting + 1
Expand All @@ -145,16 +160,21 @@ def visit(current: Node, nesting: int) -> None:


def max_nesting_of(node: Node) -> int:
"""Deepest block nesting. For a function, nested functions are measured on their own."""
deepest = 0
own_body_only = node.kind in CALLABLE_KINDS

def visit(current: Node, depth: int) -> None:
nonlocal deepest
deepest = max(deepest, depth)
for child in current.children:
if child.kind in CALLABLE_KINDS:
visit(child, 0)
if not own_body_only:
visit(child, 0)
elif child.kind in NESTING_KINDS:
visit(child, depth + 1)
# An `else` / `else if` is at the same depth as the `if` it continues.
nested_in_chain = _continues_chain(child) and child.meta.get("continues_parent")
visit(child, depth if nested_in_chain else depth + 1)
else:
visit(child, depth)

Expand Down Expand Up @@ -289,18 +309,47 @@ def to_dict(self) -> dict[str, Any]:
}


def _comment_only_lines(comments: list[Node], raw_lines: list[str]) -> set[int]:
"""Lines with nothing but comments and whitespace on them.

`x = 1 # one` is a code line that also carries a comment: it counts towards both
the comment lines and the code lines, not only the comments.
"""
segments: dict[int, list[tuple[int, int]]] = {}
for node in comments:
span = node.span
for line in range(span.start_line, min(span.end_line, len(raw_lines)) + 1):
start = span.start_col if line == span.start_line else 0
end = span.end_col if line == span.end_line else len(raw_lines[line - 1])
segments.setdefault(line, []).append((start, end))
only: set[int] = set()
for line, parts in segments.items():
text = raw_lines[line - 1]
rest, cursor = [], 0
for start, end in sorted(parts):
rest.append(text[cursor:start])
cursor = max(cursor, end)
rest.append(text[cursor:])
# A blank line inside a block comment is already counted as blank.
if text.strip() and not "".join(rest).strip():
only.add(line)
return only


def file_metrics(root: Node, source: str) -> FileMetrics:
raw_lines = source.splitlines()
blank = sum(1 for line in raw_lines if not line.strip())
comments = list(root.find(Kind.COMMENT))
comment_lines = {
line
for node in root.find(Kind.COMMENT)
for node in comments
for line in range(node.span.start_line, node.span.end_line + 1)
}
comment_only = _comment_only_lines(comments, raw_lines)
functions = [n for n in root.walk() if n.kind in CALLABLE_KINDS]
return FileMetrics(
lines=len(raw_lines),
code_lines=max(len(raw_lines) - blank - len(comment_lines), 0),
code_lines=max(len(raw_lines) - blank - len(comment_only), 0),
comment_lines=len(comment_lines),
blank_lines=blank,
cyclomatic=cyclomatic_of(root),
Expand Down
81 changes: 81 additions & 0 deletions tests/test_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,87 @@ def shallow(x):
assert function(analysis, "shallow").max_nesting == 0


CHAIN_SHAPES = {
"loop-if-else": {
"python": "def f(xs):\n for x in xs:\n if x:\n a()\n else:\n b()\n",
"javascript": "function f(xs) {\n for (const x of xs) {\n if (x) {\n a();\n } else {\n b();\n }\n }\n}\n",
"java": "class A {\n void f(int[] xs) {\n for (int x : xs) {\n if (x > 0) {\n a();\n } else {\n b();\n }\n }\n }\n}\n",
"cpp": "void f(std::vector<int> xs) {\n for (int x : xs) {\n if (x) {\n a();\n } else {\n b();\n }\n }\n}\n",
},
"if-inside-elif": {
"python": "def f(a, b, c):\n if a:\n x()\n elif b:\n if c:\n y()\n",
"javascript": "function f(a, b, c) {\n if (a) {\n x();\n } else if (b) {\n if (c) {\n y();\n }\n }\n}\n",
"java": "class A {\n void f(boolean a, boolean b, boolean c) {\n if (a) {\n x();\n } else if (b) {\n if (c) {\n y();\n }\n }\n }\n}\n",
"cpp": "void f(bool a, bool b, bool c) {\n if (a) {\n x();\n } else if (b) {\n if (c) {\n y();\n }\n }\n}\n",
},
"five-arm-chain": {
"python": "def f(n):\n if n == 1:\n return 1\n elif n == 2:\n return 2\n elif n == 3:\n return 3\n elif n == 4:\n return 4\n else:\n return 5\n",
"javascript": "function f(n) {\n if (n === 1) { return 1; }\n else if (n === 2) { return 2; }\n else if (n === 3) { return 3; }\n else if (n === 4) { return 4; }\n else { return 5; }\n}\n",
"java": "class A {\n int f(int n) {\n if (n == 1) { return 1; }\n else if (n == 2) { return 2; }\n else if (n == 3) { return 3; }\n else if (n == 4) { return 4; }\n else { return 5; }\n }\n}\n",
"cpp": "int f(int n) {\n if (n == 1) { return 1; }\n else if (n == 2) { return 2; }\n else if (n == 3) { return 3; }\n else if (n == 4) { return 4; }\n else { return 5; }\n}\n",
},
"nested-if-in-else-block": {
"javascript": "function f(a, c) {\n if (a) {\n x();\n } else {\n y();\n if (c) {\n z();\n }\n }\n}\n",
"java": "class A {\n void f(boolean a, boolean c) {\n if (a) {\n x();\n } else {\n y();\n if (c) {\n z();\n }\n }\n }\n}\n",
"cpp": "void f(bool a, bool c) {\n if (a) {\n x();\n } else {\n y();\n if (c) {\n z();\n }\n }\n}\n",
"python": "def f(a, c):\n if a:\n x()\n else:\n y()\n if c:\n z()\n",
},
}

#: (cyclomatic, cognitive, max nesting), per SonarSource's rules for cognitive: `else`
#: and `else if` add one with no nesting penalty, and their bodies are nested one level.
CHAIN_EXPECTED = {
"loop-if-else": (3, 4, 2),
"if-inside-elif": (4, 4, 2),
"five-arm-chain": (5, 5, 1),
"nested-if-in-else-block": (3, 4, 2),
}


@pytest.mark.parametrize("shape", list(CHAIN_SHAPES))
@pytest.mark.parametrize("language", ["python", "javascript", "java", "cpp"])
def test_if_else_chains_score_the_same_in_every_language(shape, language):
"""Tree-sitter nests `else` / `else if` under the `if` they continue, so each arm
used to count as a deeper level: a five-arm JS chain scored cognitive 36 and
nesting 8 where the same Python scores 5 and 1."""
measured = function(analyze(CHAIN_SHAPES[shape][language], Language(language)), "f")
assert (measured.cyclomatic, measured.cognitive, measured.max_nesting) == CHAIN_EXPECTED[shape]


def test_nested_functions_are_scored_on_their_own():
analysis = analyze("""
def outer(rows):
def inner(row):
for cell in row:
for part in cell:
if part:
return part
return inner
""")
outer, inner = function(analysis, "outer"), function(analysis, "inner")
assert (outer.cyclomatic, outer.max_nesting) == (1, 0)
assert (inner.cyclomatic, inner.max_nesting) == (4, 3)
assert analysis.metrics.cyclomatic == 4, "the file total still counts every decision"


@pytest.mark.parametrize(
"language,source,code_lines",
[
(Language.PYTHON, "x = 1 # one\ny = 2 # two\n# a note\n", 2),
(Language.JAVASCRIPT, "const x = 1; // one\n/* a\n\n note */\nconst y = 2;\n", 2),
(Language.CPP, "int x = 1; /* one */\n// a note\nint y = /* two */ 2;\n", 2),
],
ids=["python", "javascript", "cpp"],
)
def test_lines_with_trailing_comments_are_still_code(language, source, code_lines):
assert analyze(source, language).metrics.code_lines == code_lines


def test_java_else_gets_explained():
result = explain(CHAIN_SHAPES["nested-if-in-else-block"]["java"], language=Language.JAVA)
assert any(line.kind.value == "else" and line.line == 5 for line in result.lines)


def test_maintainability_index_is_bounded():
assert maintainability_index(0, 1, 0) == 100.0
assert 0.0 <= maintainability_index(90_000, 400, 5000) <= 100.0
Expand Down
Loading