Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(refactoring): preserve Java helper types and throws (#3882)
Pragalvae6c0ebb23ce8
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.pyindex 2ed0ff73c..12e8ec196 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py@@ -64,12 +64,38 @@ _CONDITIONAL_KINDS = frozenset({"switch_expression", "switch_statement"})_SCOPE_BOUNDARIES = frozenset({"lambda_expression", "class_body"})+class JavaDeclaredTypes(DeclaredTypes):+ """Java declarations, including explicit types implied by a ``var`` initializer."""++ def of(self, name: Node) -> str | None:+ declared = super().of(name)+ if declared is not None:+ return declared+ holder = name.parent+ while holder is not None and holder.type in self.wrapper_kinds:+ holder = holder.parent+ if holder is None or holder.type not in self.holder_kinds:+ return None+ typ = holder.child_by_field_name("type")+ if typ is None or node_text(typ) != "var":+ return None+ declarator = name.parent+ value = declarator.child_by_field_name("value") if declarator is not None else None+ if value is None:+ return None+ if value.type in {"object_creation_expression", "cast_expression"}:+ created = value.child_by_field_name("type")+ text = node_text(created) if created is not None else ""+ return text if text and "<>" not in text else None+ return None++class JavaDefUseDialect(BaseDefUseDialect):language = "java"member_access_kinds = frozenset({"field_access"})receiver_write_kinds = _ASSIGN_KINDS | _UPDATE_KINDS- declared_types = DeclaredTypes(- frozenset({"formal_parameter", "local_variable_declaration", "enhanced_for_statement"}),+ declared_types = JavaDeclaredTypes(+ frozenset({"formal_parameter", "local_variable_declaration", "enhanced_for_statement", "resource"}),frozenset({"variable_declarator"}),)keyword_kinds = frozenset() # Java has no keyword arguments.diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.pyindex 09975ab06..e79ccc0a1 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py@@ -700,6 +700,11 @@ def _render_fields(out_rebound=rebound,typed_host=fn_node is not Noneand fn_node.child_by_field_name("return_type") is not None,+ throws_clause=(+ next((child.text.decode() for child in fn_node.named_children if child.type == "throws"), None)+ if language == "java" and fn_node is not None+ else None+ ),))rendered = {diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.pyindex 053b0d16f..4eea33c62 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py@@ -45,6 +45,7 @@ JUDGMENT_REASONS = ("receiver_unbound","reshapes_class_surface","rewrites_dependent_imports",+ "type_unresolved","unclassified_refactoring_type",)@@ -138,10 +139,16 @@ def _extract_method_reasons(suggestion: RefactoringSuggestion, facts: dict[str,R1's dataflow gate proves the span behaviour-preserving before it is everoffered, and the blast radius is categorically local, so the only thing leftto check is that the detector itself was sure, that an awaiting span- has an async function to land in, and that the helper can share the- span's receiver (``extract_method._receiver_hazard``).+ has an async function to land in, that a typed helper signature has no+ unresolved slots, and that the helper can share the span's receiver+ (``extract_method._receiver_hazard``)."""plan = suggestion.plan or {}+ symbol = plan.get("new_symbol") or {}+ signature = symbol.get("signature_text") or ""+ slots = [*symbol.get("params", ()), *symbol.get("returns", ())]+ if "<type>" in signature and any(slot.get("type") is None for slot in slots):+ return ["type_unresolved"]if plan.get("needs_async") and plan.get("async_host") is False:return ["async_helper_unexpressible"]hazard = plan.get("receiver_hazard")diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/render.py b/packages/core/src/repowise/core/analysis/health/refactoring/render.pyindex 62dfebb52..923163486 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/render.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/render.py@@ -119,6 +119,7 @@ class HelperShape:out_written_before: bool = Falseout_rebound: bool = Falsetyped_host: bool = False+ throws_clause: str | None = Noneclass Rendered(NamedTuple):@@ -334,7 +335,8 @@ def _java_sig(s: HelperShape) -> str:out = _single_out(s)ret = _type(out, "java") if out else "void"static = "" if _method(s) else "static "- return f"private {static}{ret} {_name(s)}({_type_first(s, 'java')}) {{"+ throws = f" {s.throws_clause}" if s.throws_clause else ""+ return f"private {static}{ret} {_name(s)}({_type_first(s, 'java')}){throws} {{"def _java_call(s: HelperShape) -> str:diff --git a/tests/unit/health/test_extract_method_render.py b/tests/unit/health/test_extract_method_render.pyindex 3cefc9f09..e0409bd0e 100644--- a/tests/unit/health/test_extract_method_render.py+++ b/tests/unit/health/test_extract_method_render.py@@ -206,6 +206,92 @@ def test_each_language_writes_its_own_header_and_call(shape, sig, call):assert render(shape)[:2] == (sig, call)+def test_java_helper_copies_the_hosts_throws_clause():+ shape = _shape(+ "java",+ kind="function",+ returns=(),+ throws_clause="throws IOException, InterruptedException",+ )+ assert render(shape).signature == (+ "private static void loadTotals(T1 items, <type> limit) "+ "throws IOException, InterruptedException {"+ )+++def test_java_extraction_reads_throws_from_the_host():+ (fn,) = _functions("java", "java", "class C { void f() throws IOException, InterruptedException { } }")+ dialect = get_defuse_dialect("java")+ fields = em._render_fields(+ fn,+ Extraction(1, 1, (), (), slice_nloc=1, ccn_removed=1),+ dialect,+ "java",+ "helper",+ {"new_symbol": {"kind": "function", "receiver": None}},+ async_host=True,+ )+ assert fields["new_symbol"]["signature_text"] == (+ "private static void helper() throws IOException, InterruptedException {"+ )+++def test_java_try_resource_has_its_declared_type():+ (fn,) = _functions(+ "java",+ "java",+ "class C { void f() { try (Writer log = open()) { log.write(\"x\"); } } }",+ )+ definition = next(d for d in fn.def_use.definitions if d.var == "log")+ row = definition.line - 1+ name = fn.fn_node.descendant_for_point_range(+ (row, definition.column), (row, definition.column + len(definition.var))+ )+ assert get_defuse_dialect("java").declared_types.of(name) == "Writer"+++def test_java_var_new_expression_uses_the_created_type():+ (fn,) = _functions(+ "java",+ "java",+ "class C { void f() { var out = new HashMap<String, Object>(); } }",+ )+ definition = next(d for d in fn.def_use.definitions if d.var == "out")+ row = definition.line - 1+ name = fn.fn_node.descendant_for_point_range(+ (row, definition.column), (row, definition.column + len(definition.var))+ )+ assert get_defuse_dialect("java").declared_types.of(name) == "HashMap<String, Object>"+++def test_java_var_cast_initializer_uses_the_cast_type():+ (fn,) = _functions(+ "java",+ "java",+ "class C { void f() { var out = (Writer) open(); } }",+ )+ definition = next(d for d in fn.def_use.definitions if d.var == "out")+ row = definition.line - 1+ name = fn.fn_node.descendant_for_point_range(+ (row, definition.column), (row, definition.column + len(definition.var))+ )+ assert get_defuse_dialect("java").declared_types.of(name) == "Writer"+++def test_java_var_diamond_initializer_stays_unknown():+ (fn,) = _functions(+ "java",+ "java",+ "class C { void f() { var out = new HashMap<>(); } }",+ )+ definition = next(d for d in fn.def_use.definitions if d.var == "out")+ row = definition.line - 1+ name = fn.fn_node.descendant_for_point_range(+ (row, definition.column), (row, definition.column + len(definition.var))+ )+ assert get_defuse_dialect("java").declared_types.of(name) is None++def test_rust_borrows_a_value_the_host_reads_after_the_call():shape = _shape("rust",diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.pyindex c7b670fcb..3d7344deb 100644--- a/tests/unit/health/test_refactoring_extract_method.py+++ b/tests/unit/health/test_refactoring_extract_method.py@@ -655,6 +655,99 @@ def _detect_in(language: str, ext: str, src: str):return plans[0]+_URI_PARTS_JAVA = """+class UriParts {+ static Map<String, Object> parts(URI uri, Writer log) throws IOException {+ var out = new HashMap<String, Object>();+ String host = uri.getHost();+ String path = uri.getPath();+ String query = uri.getQuery();+ int port = uri.getPort();+ if (host == null) {+ throw new IllegalArgumentException("no host");+ }+ out.put("host", host);+ if (path != null) {+ out.put("path", path);+ int dot = path.lastIndexOf('.');+ if (dot >= 0) {+ out.put("extension", path.substring(dot + 1));+ log.write("extension\\n");+ }+ }+ if (port != -1) {+ out.put("port", port);+ log.write("port\\n");+ }+ if (query != null) {+ out.put("query", query);+ log.write("query\\n");+ }+ return out;+ }+}+"""+++def test_issue_3823_uri_parts_plan_has_known_type_and_checked_exception():+ plan = _detect_in("java", "java", _URI_PARTS_JAVA)++ assert plan.plan["new_symbol"]["signature_text"] == (+ "private static void extractedHelper(Writer log, HashMap<String, Object> out, "+ "String path, int port, String query) throws IOException {"+ )+++def test_java_extraction_inside_caught_io_exceptions_does_not_add_throws():+ import re++ src = _URI_PARTS_JAVA.replace(" throws IOException", "")+ src = re.sub(+ r'(?m)^(\s*)log\.write\((.*)\);$',+ r'\1try { log.write(\2); } catch (IOException e) { out.put("logError", e); }',+ src,+ )++ plan = _detect_in("java", "java", src)++ assert "throws IOException" not in plan.plan["new_symbol"]["signature_text"]+ assert "HashMap<String, Object> out" in plan.plan["new_symbol"]["signature_text"]+ span = plan.plan["span"]+ lifted = src.splitlines()[span["start"] - 1 : span["end"]]+ assert sum("catch (IOException e)" in line for line in lifted) == 3+++def test_issue_3823_try_resource_type_flows_through_detector():+ src = _URI_PARTS_JAVA.replace(+ "static Map<String, Object> parts(URI uri, Writer log) throws IOException {",+ "static Map<String, Object> parts(URI uri) {\n try (Writer log = open()) {",+ ).replace(+ "var out = new HashMap<String, Object>();",+ "Map<String, Object> out = new HashMap<>();",+ ).replace(+ " return out;\n }\n}",+ " return out;\n }\n }\n}",+ )+ plan = _detect_in("java", "java", src)++ assert "Writer log" in plan.plan["new_symbol"]["signature_text"]+ assert "<type>" not in plan.plan["new_symbol"]["signature_text"]+++def test_issue_3823_var_call_type_stays_judgment_at_detector_boundary():+ from repowise.core.analysis.health.refactoring.preconditions import classify_step++ src = _URI_PARTS_JAVA.replace(+ "var out = new HashMap<String, Object>();", "var out = createMap();"+ )+ plan = _detect_in("java", "java", src)+ applicability = classify_step(plan)++ assert "<type> out" in plan.plan["new_symbol"]["signature_text"]+ assert applicability.classification == "judgment"+ assert "type_unresolved" in applicability.reasons++def test_detector_emits_suggestion_for_flagged_function():findings = [_Finding("complex_method", "process", line_start=2, health_impact=1.5)]suggestions = ExtractMethodDetector().detect(_ctx(_PROCESS, findings))diff --git a/tests/unit/health/test_refactoring_preconditions.py b/tests/unit/health/test_refactoring_preconditions.pyindex 94258d243..4e8e9f434 100644--- a/tests/unit/health/test_refactoring_preconditions.py+++ b/tests/unit/health/test_refactoring_preconditions.py@@ -63,6 +63,25 @@ def test_a_proved_local_extraction_is_mechanical() -> None:assert applicability.reasons == ("dataflow_proved_local_extraction",)+def test_a_java_extraction_with_an_unresolved_parameter_is_a_judgment_call():+ applicability = classify_step(+ step(+ "extract_method",+ file_path="svc/Orders.java",+ blast_radius={"scope": "local"},+ plan={+ "new_symbol": {+ "params": [{"name": "value", "type": None}],+ "returns": [],+ "signature_text": "private static void helper(<type> value) {",+ }+ },+ )+ )+ assert applicability.classification == "judgment"+ assert applicability.reasons == ("type_unresolved",)++def test_an_unsure_detector_keeps_its_own_extraction_a_judgment_call() -> None:applicability = classify_step(step("extract_method", blast_radius={"scope": "local"}, confidence="medium")