Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(health): count TSX style objects and data props as markup, not code (#4760)

Raghav Chamadiyad03d52a4ee0c
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
index 2e4ed41f4..a331be826 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
@@ -3,7 +3,7 @@
A function that does too much. We flag when **all three** conditions
hold:
-- NLOC ≥ 70 (the function is long)
+- NLOC ≥ 70, JSX markup lines excluded (the function is long)
- CCN ≥ 9 (it has many decision paths)
- the enclosing file is *central* — see the centrality gate below.
@@ -72,13 +72,18 @@ class BrainMethodDetector:
out: list[BiomarkerResult] = []
for fn in ctx.all_functions:
judged = judged_ccn(fn)
- severity = self.severity_for(judged, fn.nloc)
+ # JSX markup lines are layout, as in large_method.
+ code_lines = fn.nloc - fn.markup_nloc
+ severity = self.severity_for(judged, code_lines)
if severity is None:
continue
details = {"ccn": fn.ccn, "nloc": fn.nloc, "max_nesting": fn.max_nesting}
+ if fn.markup_nloc:
+ details["markup_nloc"] = fn.markup_nloc
# Severity was judged on the dispatch-flat number, so the reason
# leads with it — the raw one stays in ``details["ccn"]``.
- reason = f"Brain Method: {fn.name} is {fn.nloc} lines, CCN {judged}"
+ besides = f" besides {fn.markup_nloc} of JSX markup" if fn.markup_nloc else ""
+ reason = f"Brain Method: {fn.name} is {code_lines} lines{besides}, CCN {judged}"
if judged != fn.ccn:
details["judged_ccn"] = judged
reason += f" ({fn.ccn} counting every arm of its dispatch)"
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/markup.py b/packages/core/src/repowise/core/analysis/health/complexity/markup.py
index 267f77f51..94d5cd8b5 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/markup.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/markup.py
@@ -1,4 +1,9 @@
-"""Lines of a JSX file that hold only markup: tags, attributes and text, no expression."""
+"""Lines of a JSX file that hold only markup: tags, attributes and text, no logic.
+
+An attribute value of plain data (``style={{ color: "red" }}``, ``title={label}``)
+is markup too, and so is a component's ``const`` data literal used only there.
+A call, an operator, a function or control flow keeps a line code.
+"""
from __future__ import annotations
@@ -12,22 +17,140 @@ if TYPE_CHECKING:
#: Grammars that parse JSX; a ``.ts`` file reads with ``typescript`` and has none.
_JSX_GRAMMARS = frozenset({"tsx", "javascript"})
-#: The ``{...}`` slot inside markup; what it holds is code again.
+#: The ``{...}`` slot inside markup; what it holds is code again unless it is data.
_EXPRESSION_SLOT = "jsx_expression"
+#: Nodes a plain data value is built from: literals, references, objects, arrays.
+_DATA_KINDS = frozenset(
+ {
+ "string",
+ "string_fragment",
+ "escape_sequence",
+ "template_string",
+ "template_substitution",
+ "number",
+ "true",
+ "false",
+ "null",
+ "undefined",
+ "identifier",
+ "property_identifier",
+ "shorthand_property_identifier",
+ "member_expression",
+ "object",
+ "pair",
+ "array",
+ "spread_element",
+ "parenthesized_expression",
+ }
+)
+#: ``x as const`` / ``x satisfies T``: only the value is data, the type is skipped.
+_TYPED_VALUE = frozenset({"as_expression", "satisfies_expression"})
+
+
+def _is_data(node: Node) -> bool:
+ """True when *node* holds no call, operator, function or control flow.
+
+ Nested JSX counts as data here: its own ``{...}`` slots are judged on their own.
+ """
+ stack = list(node.named_children)
+ while stack:
+ child = stack.pop()
+ kind = child.type
+ if kind.startswith("jsx_") or "comment" in kind:
+ continue
+ if kind in _TYPED_VALUE:
+ stack.extend(child.named_children[:1])
+ elif kind in _DATA_KINDS or (
+ kind == "unary_expression" and child.children[0].type == "-"
+ ):
+ stack.extend(child.named_children)
+ else:
+ return False
+ return True
+
+
+def _is_data_slot(node: Node) -> bool:
+ """An attribute's ``{...}`` value that is plain data."""
+ parent = node.parent
+ return parent is not None and parent.type == "jsx_attribute" and _is_data(node)
+
+
+def _in_data_slot(node: Node, scope: Node) -> bool:
+ """*node* sits in a data attribute value below *scope*."""
+ slot = node.parent
+ while slot is not None and slot != scope and slot.type != _EXPRESSION_SLOT:
+ slot = slot.parent
+ return slot is not None and slot != scope and _is_data_slot(slot)
+
+
+def _used_only_in_data_slots(name: Node, scope: Node) -> bool:
+ """Every other mention of *name* in *scope* sits in a data attribute value."""
+ text = name.text
+ uses = 0
+ stack = [scope]
+ while stack:
+ node = stack.pop()
+ if node.type not in ("identifier", "shorthand_property_identifier"):
+ stack.extend(node.children)
+ elif node != name and node.text == text:
+ if not _in_data_slot(node, scope):
+ return False
+ uses += 1
+ return uses > 0
+
+
+def _data_literal_name(node: Node) -> Node | None:
+ """The name of ``const X = {...}`` / ``[...]`` of plain data in a block, else ``None``."""
+ declarators = node.named_children
+ if node.children[0].type != "const" or len(declarators) != 1:
+ return None
+ name = declarators[0].child_by_field_name("name")
+ value = declarators[0].child_by_field_name("value")
+ if name is None or value is None or name.type != "identifier":
+ return None
+ literal = value.named_children[0] if value.type in _TYPED_VALUE else value
+ return name if literal.type in ("object", "array") and _is_data(literal) else None
+
+
+def _data_declarations(root: Node) -> set[tuple[int, int]]:
+ """Byte spans of ``const X = {...}`` in a function body, X used only as attribute data."""
+ spans: set[tuple[int, int]] = set()
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ stack.extend(node.named_children)
+ scope = node.parent
+ if node.type != "lexical_declaration" or scope is None or scope.type != "statement_block":
+ continue
+ name = _data_literal_name(node)
+ if name is not None and _used_only_in_data_slots(name, scope):
+ spans.add((node.start_byte, node.end_byte))
+ return spans
+
+
+def _opens_markup(node: Node, in_markup: bool, data_decls: set[tuple[int, int]]) -> bool:
+ """Whether *node*'s tokens are markup, given its parent's state."""
+ kind = node.type
+ if kind == _EXPRESSION_SLOT:
+ return in_markup and _is_data_slot(node)
+ if kind.startswith("jsx_"):
+ return True
+ if kind == "lexical_declaration" and (node.start_byte, node.end_byte) in data_decls:
+ return True
+ return in_markup
def _token_rows(root: Node) -> tuple[set[int], set[int]]:
"""Rows holding a markup token and rows holding a code token, comments skipped."""
markup: set[int] = set()
code: set[int] = set()
+ data_decls = _data_declarations(root)
stack: list[tuple[Node, bool]] = [(root, False)]
while stack:
node, in_markup = stack.pop()
- kind = node.type
- if "comment" in kind:
+ if "comment" in node.type:
continue
- if kind.startswith("jsx_"):
- in_markup = kind != _EXPRESSION_SLOT
+ in_markup = _opens_markup(node, in_markup, data_decls)
if node.children:
stack.extend((child, in_markup) for child in node.children)
elif node.start_byte < node.end_byte:
diff --git a/tests/unit/health/test_method_size_accuracy.py b/tests/unit/health/test_method_size_accuracy.py
index a2d977e1c..a07331513 100644
--- a/tests/unit/health/test_method_size_accuracy.py
+++ b/tests/unit/health/test_method_size_accuracy.py
@@ -4,6 +4,8 @@ from __future__ import annotations
from dataclasses import replace
+import pytest
+
from repowise.core.analysis.health.biomarkers import FileContext
from repowise.core.analysis.health.biomarkers.brain_method import BrainMethodDetector
from repowise.core.analysis.health.biomarkers.complex_method import ComplexMethodDetector
@@ -115,3 +117,135 @@ def test_logic_lines_inside_jsx_still_count_as_code() -> None:
[panel] = [fn for fn in fcx.functions if fn.name == "Panel"]
# ``<h2>{label}</h2>`` holds an expression, so it is code.
assert panel.nloc - panel.markup_nloc >= 6
+
+
+def _code_rows(component: str, name: str = "Card") -> FunctionComplexity:
+ fcx = walk_file("src/Card.tsx", "typescript", component.encode())
+ [fn] = [fn for fn in fcx.functions if fn.name == name]
+ return fn
+
+
+_STYLE_PAIRS = "\n".join(f' prop{i}: "value-{i}",' for i in range(70))
+_SPANS = "\n".join(
+ f' <span\n className="cell-{i}"\n style={{{{ opacity: 0.5 }}}}\n'
+ f' title={{label}}\n />'
+ for i in range(20)
+)
+_STYLED = f"""export function Card({{ label, open }}: Props) {{
+ if (!open) {{
+ return null;
+ }}
+ const tone = label ? "on" : "off";
+ if (tone === "on") {{
+ console.log(tone);
+ }}
+ return (
+ <div
+ style={{{{
+{_STYLE_PAIRS}
+ }}}}
+ >
+{_SPANS}
+ </div>
+ );
+}}
+"""
+
+
+def test_literal_style_objects_and_data_props_are_markup() -> None:
+ card = _code_rows(_STYLED)
+ # The function line, the guards, the const, the return and its parens.
+ assert card.nloc - card.markup_nloc <= 12
+ assert LargeMethodDetector().detect(_ctx(card, path="src/Card.tsx")) == []
+
+
+def test_a_prop_with_a_call_or_a_condition_stays_code() -> None:
+ card = _code_rows(
+ """export function Card({ label, wide }: Props) {
+ return (
+ <div
+ className="card"
+ title={format(label)}
+ style={{
+ width: wide ? 320 : 260,
+ }}
+ onClick={() => {
+ track(label);
+ }}
+ />
+ );
+}
+"""
+ )
+ # Only ``<div``, ``className`` and ``/>`` are markup.
+ assert card.markup_nloc == 3
+
+
+def test_a_const_data_literal_used_only_as_a_prop_is_markup() -> None:
+ card = _code_rows(
+ """export function Card({ label }: Props) {
+ const box = {
+ padding: 4,
+ color: "red",
+ };
+ return <div style={box}>{label}</div>;
+}
+"""
+ )
+ # The four lines of ``box`` are markup; the return line holds ``{label}``.
+ assert card.markup_nloc == 4
+
+
[email protected]("cast", ["as Palette", "satisfies Palette"])
+def test_a_typed_const_data_literal_used_only_as_a_prop_is_markup(cast: str) -> None:
+ card = _code_rows(
+ f"""export function Card({{ label }}: Props) {{
+ const box = {{
+ padding: 4,
+ color: "red",
+ }} {cast};
+ return <div style={{box}}>{{label}}</div>;
+}}
+"""
+ )
+ assert card.markup_nloc == 4
+
+
+def test_a_const_data_literal_read_by_logic_stays_code() -> None:
+ card = _code_rows(
+ """export function Card({ kind }: Props) {
+ const labels = {
+ a: "Alpha",
+ b: "Beta",
+ };
+ return <div title={labels.a}>{labels[kind]}</div>;
+}
+"""
+ )
+ assert card.markup_nloc == 0
+
+
+def test_brain_method_does_not_count_jsx_markup_lines() -> None:
+ # 100 lines, 40 of them markup: 60 lines of code is under brain_method's 70.
+ assert BrainMethodDetector().detect(_central(_fn(nloc=100, ccn=12, markup_nloc=40))) == []
+ [finding] = BrainMethodDetector().detect(_central(_fn(nloc=120, ccn=12, markup_nloc=40)))
+ assert finding.reason == (
+ "Brain Method: tokenize is 80 lines besides 40 of JSX markup, CCN 12, "
+ "in a file imported by 10 others"
+ )
+ assert finding.details["markup_nloc"] == 40
+
+
+def test_jsx_files_and_as_const_literals_read_the_same() -> None:
+ component = """export function Card({ label }) {
+ const box = {
+ margin: -1,
+ } as const;
+ return <div style={box}>{label}</div>;
+}
+"""
+ assert _code_rows(component).markup_nloc == 3
+ plain = component.replace(" as const", "")
+ fcx = walk_file("src/Card.jsx", "javascript", plain.encode())
+ [card] = [fn for fn in fcx.functions if fn.name == "Card"]
+ assert card.markup_nloc == 3