Skip to content

Commit

Permalink
Prepare for a change to JCTree.getQualifiedIdentifier
Browse files Browse the repository at this point in the history
openjdk/jdk@a917fb3

Fixes: #898
PiperOrigin-RevId: 512685971
  • Loading branch information
cushon authored and google-java-format Team committed Feb 28, 2023
1 parent 64f98ed commit f74c55d
Showing 1 changed file with 13 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCImport;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
Expand Down Expand Up @@ -293,9 +292,7 @@ private static RangeMap<Integer, String> buildReplacements(
}

private static String getSimpleName(JCImport importTree) {
return importTree.getQualifiedIdentifier() instanceof JCIdent
? ((JCIdent) importTree.getQualifiedIdentifier()).getName().toString()
: ((JCFieldAccess) importTree.getQualifiedIdentifier()).getIdentifier().toString();
return getQualifiedIdentifier(importTree).getIdentifier().toString();
}

private static boolean isUnused(
Expand All @@ -304,18 +301,15 @@ private static boolean isUnused(
Multimap<String, Range<Integer>> usedInJavadoc,
JCImport importTree,
String simpleName) {
String qualifier =
((JCFieldAccess) importTree.getQualifiedIdentifier()).getExpression().toString();
JCFieldAccess qualifiedIdentifier = getQualifiedIdentifier(importTree);
String qualifier = qualifiedIdentifier.getExpression().toString();
if (qualifier.equals("java.lang")) {
return true;
}
if (unit.getPackageName() != null && unit.getPackageName().toString().equals(qualifier)) {
return true;
}
if (importTree.getQualifiedIdentifier() instanceof JCFieldAccess
&& ((JCFieldAccess) importTree.getQualifiedIdentifier())
.getIdentifier()
.contentEquals("*")) {
if (qualifiedIdentifier.getIdentifier().contentEquals("*")) {
return false;
}

Expand All @@ -328,6 +322,15 @@ private static boolean isUnused(
return true;
}

private static JCFieldAccess getQualifiedIdentifier(JCImport importTree) {
// Use reflection because the return type is JCTree in some versions and JCFieldAccess in others
try {
return (JCFieldAccess) JCImport.class.getMethod("getQualifiedIdentifier").invoke(importTree);
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}

/** Applies the replacements to the given source, and re-format any edited javadoc. */
private static String applyReplacements(String source, RangeMap<Integer, String> replacements) {
// save non-empty fixed ranges for reformatting after fixes are applied
Expand Down

0 comments on commit f74c55d

Please sign in to comment.