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(java): record package-private access instead of public (#2771)
Raghav Chamadiya9ec2367f9f3f
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.pyindex d5bf2fd1d..2ca5dbdb9 100644--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py@@ -4,8 +4,8 @@ Most languages can determine visibility from a symbol's name + modifiertext alone (the ``visibility_fn`` shape). Some cannot, because the answerdepends on surrounding AST context — C/C++ ``public:`` / ``private:``access specifier siblings, ``static`` storage class at file scope and-``__declspec(dllexport)`` attributes; C#'s no-modifier default, which-differs by enclosing declaration; TS/JS export position; Rust's+``__declspec(dllexport)`` attributes; the C# and Java no-modifier+defaults, which differ by enclosing declaration; TS/JS export position; Rust'strait items, which may not write a modifier of their own. Each has a``refine_*_visibility`` the parser calls after the generic``visibility_fn``.@@ -59,12 +59,20 @@ def rust_visibility(_name: str, mods: list[str]) -> str:def java_visibility(_name: str, mods: list[str]) -> str:+ """Java visibility; no access keyword is package-private, recorded ``internal``.++ That default is the top-level type one. Interface members and enum+ constructors default differently, which ``refine_java_visibility``+ corrects from the AST.+ """combined = " ".join(mods).lower()if "private" in combined:return "private"if "protected" in combined:return "protected"- return "public"+ if "public" in combined:+ return "public"+ return "internal"def public_by_default(_name: str, _mods: list[str]) -> str:@@ -376,6 +384,41 @@ def refine_csharp_visibility(def_node: Node, current_visibility: str) -> str:return current_visibility+# ---------------------------------------------------------------------------+# Java node-aware visibility refinement+# ---------------------------------------------------------------------------++_JAVA_ACCESS_KEYWORDS = ("private", "protected", "public")++# Members of these bodies are implicitly public (JLS 9.4, 9.5, 9.6).+_JAVA_PUBLIC_BODIES = frozenset({"interface_body", "annotation_type_body"})+++def refine_java_visibility(def_node: Node) -> str:+ """Give a Java declaration the access it writes, else its scope's default.++ Read from the AST because the query's modifier-less pattern matches first+ and the parser keeps the first match, so ``private class X`` reaches+ ``java_visibility`` with no modifier text at all. With no access keyword a+ declaration is package-private, except that interface and annotation+ members are public and an enum constructor is private.+ """+ modifiers = next((c for c in def_node.children if c.type == "modifiers"), None)+ if modifiers is not None:+ written = {c.type for c in modifiers.children}+ for keyword in _JAVA_ACCESS_KEYWORDS:+ if keyword in written:+ return keyword+ body = def_node.parent+ if body is None:+ return "internal"+ if body.type in _JAVA_PUBLIC_BODIES:+ return "public"+ if def_node.type == "constructor_declaration" and body.type == "enum_body_declarations":+ return "private"+ return "internal"++# ---------------------------------------------------------------------------# Rust node-aware visibility refinement# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 418804f07..19e0ce3cd 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -64,6 +64,7 @@ from .extractors.synthetic_symbols import extract_synthetic_symbolsfrom .extractors.visibility import (refine_cpp_visibility,refine_csharp_visibility,+ refine_java_visibility,refine_rust_visibility,refine_ts_visibility,ts_deferred_export_names,@@ -828,6 +829,10 @@ def _refine_visibility(# it, which the modifier-text fn cannot see.if language == "csharp":return refine_csharp_visibility(def_node, visibility), False+ # Java: no access keyword means package-private, except inside an+ # interface or annotation body, which the modifier-text fn cannot see.+ if language == "java":+ return refine_java_visibility(def_node), False# TS/JS: a top-level declaration is only public when exported —# inline, via ``export { x }`` lists, or ``export default x``.if language in _TS_JS_LANGUAGES:diff --git a/tests/unit/dead_code/test_unused_exports.py b/tests/unit/dead_code/test_unused_exports.pyindex 9d117bffc..57bf827fe 100644--- a/tests/unit/dead_code/test_unused_exports.py+++ b/tests/unit/dead_code/test_unused_exports.py@@ -315,3 +315,79 @@ def test_unused_export_rust_impl_non_importable():names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}assert "MyStruct" not in names+++def test_java_package_private_class_is_not_an_unused_export():+ """A modifier-less Java class is package-private, not public API.++ Shaped on gson's ``@JsonAdapter(Deserializer.class)`` test class: the+ nested class has no importer and never could, and must not be reported+ as a public symbol. A public class with no importer still is.+ """+ from datetime import datetime++ from repowise.core.ingestion.models import FileInfo+ from repowise.core.ingestion.parser import ASTParser++ path = "src/main/java/com/example/Holder.java"+ src = b"""+package com.example;+public class Holder {+ @JsonAdapter(Deserializer.class) DummyClass f4;+ static class Deserializer implements JsonDeserializer<DummyClass> {}+}+public class Unused {}+"""+ info = FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language="java",+ size_bytes=len(src),+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ symbols = [+ {+ "name": s.name,+ "kind": s.kind,+ "visibility": s.visibility,+ "parent_name": s.parent_name,+ "decorators": [],+ "start_line": s.start_line,+ "end_line": s.end_line,+ }+ for s in ASTParser().parse_file(info, src).symbols+ ]+ g = _build_graph(+ nodes={+ path: {+ "language": "java",+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": len(symbols),+ "symbols": symbols,+ },+ "src/main/java/com/example/Main.java": {+ "language": "java",+ "is_entry_point": True,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 0,+ "symbols": [],+ },+ },+ edges=[("src/main/java/com/example/Main.java", path, {"imported_names": ["Holder"]})],+ )++ report = DeadCodeAnalyzer(g, git_meta_map={}).analyze(+ {"detect_unreachable_files": False, "detect_zombie_packages": False}+ )++ unused = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}+ assert "Deserializer" not in unused+ assert "Unused" in unuseddiff --git a/tests/unit/ingestion/test_java_visibility_defaults.py b/tests/unit/ingestion/test_java_visibility_defaults.pynew file mode 100644index 000000000..34ef14ca2--- /dev/null+++ b/tests/unit/ingestion/test_java_visibility_defaults.py@@ -0,0 +1,137 @@+"""A Java declaration with no access keyword takes its enclosing scope's default.++No access keyword means package-private, recorded ``internal``, except that+interface and annotation members are implicitly public and an enum+constructor is implicitly private. ``refine_java_visibility`` reads the+declaration's own ``modifiers`` node and its enclosing body.+"""++from __future__ import annotations++from datetime import datetime++from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParser++_PARSER = ASTParser()+++def _symbols(src: str, path: str = "src/p/Thing.java") -> list[tuple[str, str, str]]:+ info = FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language="java",+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ parsed = _PARSER.parse_file(info, src.encode("utf-8"))+ return [(s.kind, s.name, s.visibility) for s in parsed.symbols]+++def _visibility(src: str) -> dict[str, str]:+ return {name: vis for _, name, vis in _symbols(src)}+++def test_unmodified_top_level_types_are_package_private() -> None:+ src = """+package p;+class Helper {}+interface Port {}+enum Mode { A, B }+record Pair(int a, int b) {}+public class Api {}+"""+ syms = _symbols(src)+ assert ("class", "Helper", "internal") in syms+ assert ("interface", "Port", "internal") in syms+ assert ("enum", "Mode", "internal") in syms+ assert ("class", "Pair", "internal") in syms+ assert ("class", "Api", "public") in syms+++def test_unmodified_class_members_are_package_private() -> None:+ src = """+public class Outer {+ static class Deserializer {}+ void run() {}+ static final void helper() {}+ @Override void annotated() {}+}+"""+ vis = _visibility(src)+ assert vis["Deserializer"] == "internal"+ assert vis["run"] == "internal"+ assert vis["helper"] == "internal"+ assert vis["annotated"] == "internal"+++def test_explicit_access_keywords_win() -> None:+ src = """+public class Outer {+ @Deprecated private static class Hidden {}+ private class Inner { public void open() {} }+ protected void guarded() {}+ public void exposed() {}+}+"""+ vis = _visibility(src)+ # The modifier-less query pattern matches first and used to drop the+ # captured ``private`` of a class declaration.+ assert vis["Hidden"] == "private"+ assert vis["Inner"] == "private"+ assert vis["open"] == "public"+ assert vis["guarded"] == "protected"+ assert vis["exposed"] == "public"+++def test_interface_and_annotation_members_are_public() -> None:+ src = """+interface Repo {+ void save();+ default void flush() {}+ static void create() {}+ class Nested {}+ private void secret() {}+}+@interface Marker {+ class Holder {}+}+"""+ vis = _visibility(src)+ assert vis["save"] == "public"+ assert vis["flush"] == "public"+ assert vis["create"] == "public"+ assert vis["Nested"] == "public"+ assert vis["secret"] == "private"+ assert vis["Holder"] == "public"+++def test_enum_constructor_is_private_and_enum_methods_package_private() -> None:+ src = """+public enum Color {+ RED, GREEN;+ void paint() {}+ Color() {}+}+"""+ syms = _symbols(src)+ assert ("enum", "Color", "public") in syms+ assert ("method", "Color", "private") in syms+ assert ("method", "paint", "internal") in syms+++def test_record_body_is_package_private_and_accessors_stay_public() -> None:+ src = """+record Point(int x, int y) {+ void shift() {}+}+"""+ vis = _visibility(src)+ assert vis["shift"] == "internal"+ assert vis["x"] == "public"+ assert vis["y"] == "public"