3333import com .github .javaparser .ast .CompilationUnit ;
3434import com .github .javaparser .ast .ImportDeclaration ;
3535import com .github .javaparser .ast .PackageDeclaration ;
36+ import com .github .javaparser .ast .body .ClassOrInterfaceDeclaration ;
37+ import com .github .javaparser .ast .body .EnumDeclaration ;
38+ import com .github .javaparser .ast .body .RecordDeclaration ;
3639import com .github .javaparser .ast .type .ClassOrInterfaceType ;
3740import com .github .javaparser .ast .visitor .VoidVisitorAdapter ;
3841
@@ -77,7 +80,13 @@ public String apply(String rawUnix) throws Exception {
7780 existingImportsBySimple .put (simple , fqn );
7881 }
7982
80- // 3. Walk the AST to find outermost fully-qualified type nodes
83+ // 3. Collect type names declared in this file (top-level + nested)
84+ Set <String > declaredTypeNames = new LinkedHashSet <>();
85+ cu .findAll (ClassOrInterfaceDeclaration .class ).forEach (c -> declaredTypeNames .add (c .getNameAsString ()));
86+ cu .findAll (EnumDeclaration .class ).forEach (c -> declaredTypeNames .add (c .getNameAsString ()));
87+ cu .findAll (RecordDeclaration .class ).forEach (c -> declaredTypeNames .add (c .getNameAsString ()));
88+
89+ // 4. Walk the AST to find outermost fully-qualified type nodes
8190 Map <String , Set <String >> simpleToFqns = new LinkedHashMap <>();
8291 List <QualifiedTypeRef > qualifiedRefs = new ArrayList <>();
8392
@@ -87,7 +96,7 @@ public String apply(String rawUnix) throws Exception {
8796 return rawUnix ;
8897 }
8998
90- // 4 . Determine which FQNs are safe to shorten
99+ // 5 . Determine which FQNs are safe to shorten
91100 Set <String > safeToShorten = new LinkedHashSet <>();
92101 for (Map .Entry <String , Set <String >> entry : simpleToFqns .entrySet ()) {
93102 String simple = entry .getKey ();
@@ -100,14 +109,18 @@ public String apply(String rawUnix) throws Exception {
100109 if (existing != null && !existing .equals (fqn )) {
101110 continue ;
102111 }
112+ // Skip if simple name clashes with a type declared in this file
113+ if (declaredTypeNames .contains (simple )) {
114+ continue ;
115+ }
103116 safeToShorten .add (fqn );
104117 }
105118
106119 if (safeToShorten .isEmpty ()) {
107120 return rawUnix ;
108121 }
109122
110- // 5 . Convert line/column positions to string offsets and replace
123+ // 6 . Convert line/column positions to string offsets and replace
111124 // Build line-start offset table
112125 int [] lineOffsets = buildLineOffsets (rawUnix );
113126
@@ -134,7 +147,7 @@ public String apply(String rawUnix) throws Exception {
134147 sb .delete (removal [0 ], removal [1 ]);
135148 }
136149
137- // 6 . Add missing imports
150+ // 7 . Add missing imports
138151 Set <String > newImports = new TreeSet <>();
139152 for (String fqn : safeToShorten ) {
140153 if (fqn .startsWith ("java.lang." ) && fqn .indexOf ('.' , 10 ) == -1 ) {
0 commit comments