|
| 1 | +/* |
| 2 | + * Copyright 2023-2025 DiffPlug |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.diffplug.spotless.glue.java.parser; |
| 17 | + |
| 18 | +import static java.util.stream.Collectors.joining; |
| 19 | +import static java.util.stream.Collectors.toMap; |
| 20 | + |
| 21 | +import java.io.File; |
| 22 | +import java.io.IOException; |
| 23 | +import java.util.ArrayList; |
| 24 | +import java.util.Collection; |
| 25 | +import java.util.Comparator; |
| 26 | +import java.util.List; |
| 27 | +import java.util.Map; |
| 28 | +import java.util.Optional; |
| 29 | +import java.util.Set; |
| 30 | +import java.util.TreeSet; |
| 31 | +import java.util.function.Function; |
| 32 | +import java.util.regex.Pattern; |
| 33 | +import javassist.ClassPool; |
| 34 | + |
| 35 | +import com.github.javaparser.JavaParser; |
| 36 | +import com.github.javaparser.ast.CompilationUnit; |
| 37 | +import com.github.javaparser.ast.ImportDeclaration; |
| 38 | +import com.github.javaparser.ast.Node; |
| 39 | +import com.github.javaparser.ast.expr.AnnotationExpr; |
| 40 | +import com.github.javaparser.ast.expr.MarkerAnnotationExpr; |
| 41 | +import com.github.javaparser.ast.expr.MethodCallExpr; |
| 42 | +import com.github.javaparser.ast.expr.NormalAnnotationExpr; |
| 43 | +import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; |
| 44 | +import com.github.javaparser.ast.type.ClassOrInterfaceType; |
| 45 | +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; |
| 46 | +import com.github.javaparser.resolution.SymbolResolver; |
| 47 | +import com.github.javaparser.resolution.UnsolvedSymbolException; |
| 48 | +import com.github.javaparser.resolution.declarations.ResolvedAnnotationDeclaration; |
| 49 | +import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration; |
| 50 | +import com.github.javaparser.resolution.types.ResolvedType; |
| 51 | +import com.github.javaparser.symbolsolver.JavaSymbolSolver; |
| 52 | +import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; |
| 53 | +import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver; |
| 54 | +import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; |
| 55 | +import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; |
| 56 | + |
| 57 | +import com.diffplug.spotless.FormatterFunc; |
| 58 | +import com.diffplug.spotless.LineEnding; |
| 59 | +import com.diffplug.spotless.Lint; |
| 60 | + |
| 61 | +public class ExpandWildcardsFormatterFunc implements FormatterFunc.NeedsFile { |
| 62 | + |
| 63 | + private final JavaParser parser; |
| 64 | + static { |
| 65 | + // If ClassPool is allowed to cache class files, it does not free the file-lock |
| 66 | + ClassPool.cacheOpenedJarFile = false; |
| 67 | + } |
| 68 | + |
| 69 | + public ExpandWildcardsFormatterFunc(Collection<File> typeSolverClasspath) throws IOException { |
| 70 | + this.parser = new JavaParser(); |
| 71 | + |
| 72 | + CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver(); |
| 73 | + combinedTypeSolver.add(new ReflectionTypeSolver()); |
| 74 | + for (File element : typeSolverClasspath) { |
| 75 | + if (element.isFile()) { |
| 76 | + combinedTypeSolver.add(new JarTypeSolver(element)); |
| 77 | + } else if (element.isDirectory()) { |
| 78 | + combinedTypeSolver.add(new JavaParserTypeSolver(element)); |
| 79 | + } // gracefully ignore non-existing src-directories |
| 80 | + } |
| 81 | + |
| 82 | + SymbolResolver symbolSolver = new JavaSymbolSolver(combinedTypeSolver); |
| 83 | + parser.getParserConfiguration().setSymbolResolver(symbolSolver); |
| 84 | + } |
| 85 | + |
| 86 | + @Override |
| 87 | + public String applyWithFile(String rawUnix, File file) throws Exception { |
| 88 | + Optional<CompilationUnit> parseResult = parser.parse(rawUnix).getResult(); |
| 89 | + if (parseResult.isEmpty()) { |
| 90 | + return rawUnix; |
| 91 | + } |
| 92 | + CompilationUnit cu = parseResult.get(); |
| 93 | + Map<ImportDeclaration, Set<ImportDeclaration>> importMap = findWildcardImports(cu) |
| 94 | + .stream() |
| 95 | + .collect(toMap(Function.identity(), |
| 96 | + t -> new TreeSet<>(Comparator.comparing(ImportDeclaration::getNameAsString)))); |
| 97 | + if (importMap.isEmpty()) { |
| 98 | + // No wildcards found => do not change anything |
| 99 | + return rawUnix; |
| 100 | + } |
| 101 | + |
| 102 | + cu.accept(new CollectImportedTypesVisitor(), importMap); |
| 103 | + for (var entry : importMap.entrySet()) { |
| 104 | + String pattern = Pattern.quote(LineEnding.toUnix(entry.getKey().toString())); |
| 105 | + String replacement = entry.getValue().stream().map(ImportDeclaration::toString).collect(joining()); |
| 106 | + rawUnix = rawUnix.replaceAll(pattern, replacement); |
| 107 | + } |
| 108 | + |
| 109 | + return rawUnix; |
| 110 | + } |
| 111 | + |
| 112 | + private List<ImportDeclaration> findWildcardImports(CompilationUnit cu) { |
| 113 | + List<ImportDeclaration> wildcardImports = new ArrayList<>(); |
| 114 | + for (ImportDeclaration importDeclaration : cu.getImports()) { |
| 115 | + if (importDeclaration.isAsterisk()) { |
| 116 | + wildcardImports.add(importDeclaration); |
| 117 | + } |
| 118 | + } |
| 119 | + return wildcardImports; |
| 120 | + } |
| 121 | + |
| 122 | + private static final class CollectImportedTypesVisitor |
| 123 | + extends VoidVisitorAdapter<Map<ImportDeclaration, Set<ImportDeclaration>>> { |
| 124 | + |
| 125 | + @Override |
| 126 | + public void visit(final ClassOrInterfaceType n, |
| 127 | + final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { |
| 128 | + // default imports |
| 129 | + ResolvedType resolvedType = wrapUnsolvedSymbolException(n, ClassOrInterfaceType::resolve); |
| 130 | + if (resolvedType.isReference()) { |
| 131 | + matchTypeName(importMap, resolvedType.asReferenceType().getQualifiedName(), false); |
| 132 | + } |
| 133 | + super.visit(n, importMap); |
| 134 | + } |
| 135 | + |
| 136 | + private void matchTypeName(Map<ImportDeclaration, Set<ImportDeclaration>> importMap, String qualifiedName, |
| 137 | + boolean isStatic) { |
| 138 | + int lastDot = qualifiedName.lastIndexOf('.'); |
| 139 | + if (lastDot < 0) { |
| 140 | + return; |
| 141 | + } |
| 142 | + |
| 143 | + String packageName = qualifiedName.substring(0, lastDot); |
| 144 | + for (var entry : importMap.entrySet()) { |
| 145 | + if (entry.getKey().isStatic() == isStatic |
| 146 | + && packageName.equals(entry.getKey().getName().asString())) { |
| 147 | + entry.getValue().add(new ImportDeclaration(qualifiedName, isStatic, false)); |
| 148 | + break; |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + @Override |
| 154 | + public void visit(final MarkerAnnotationExpr n, |
| 155 | + final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { |
| 156 | + visitAnnotation(n, importMap); |
| 157 | + super.visit(n, importMap); |
| 158 | + } |
| 159 | + |
| 160 | + @Override |
| 161 | + public void visit(final SingleMemberAnnotationExpr n, |
| 162 | + final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { |
| 163 | + visitAnnotation(n, importMap); |
| 164 | + super.visit(n, importMap); |
| 165 | + } |
| 166 | + |
| 167 | + @Override |
| 168 | + public void visit(final NormalAnnotationExpr n, |
| 169 | + final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { |
| 170 | + visitAnnotation(n, importMap); |
| 171 | + super.visit(n, importMap); |
| 172 | + } |
| 173 | + |
| 174 | + private void visitAnnotation(final AnnotationExpr n, |
| 175 | + final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { |
| 176 | + ResolvedAnnotationDeclaration resolvedType = wrapUnsolvedSymbolException(n, AnnotationExpr::resolve); |
| 177 | + matchTypeName(importMap, resolvedType.getQualifiedName(), false); |
| 178 | + } |
| 179 | + |
| 180 | + @Override |
| 181 | + public void visit(final MethodCallExpr n, final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { |
| 182 | + // static imports |
| 183 | + ResolvedMethodDeclaration resolved = wrapUnsolvedSymbolException(n, MethodCallExpr::resolve); |
| 184 | + if (resolved.isStatic()) { |
| 185 | + matchTypeName(importMap, resolved.getQualifiedName(), true); |
| 186 | + } |
| 187 | + super.visit(n, importMap); |
| 188 | + } |
| 189 | + |
| 190 | + private static <T extends Node, R> R wrapUnsolvedSymbolException(T node, Function<T, R> func) { |
| 191 | + try { |
| 192 | + return func.apply(node); |
| 193 | + } catch (UnsolvedSymbolException ex) { |
| 194 | + if (node.getBegin().isPresent() && node.getEnd().isPresent()) { |
| 195 | + throw Lint.atLineRange(node.getBegin().get().line, node.getEnd().get().line, "UnsolvedSymbolException", ex.getMessage()).shortcut(); |
| 196 | + } |
| 197 | + if (node.getBegin().isPresent()) { |
| 198 | + throw Lint.atLine(node.getBegin().get().line, "UnsolvedSymbolException", ex.getMessage()).shortcut(); |
| 199 | + } else if (node.getEnd().isPresent()) { |
| 200 | + throw Lint.atLine(node.getEnd().get().line, "UnsolvedSymbolException", ex.getMessage()).shortcut(); |
| 201 | + } else { |
| 202 | + throw Lint.atUndefinedLine("UnsolvedSymbolException", ex.getMessage()).shortcut(); |
| 203 | + } |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + } |
| 208 | + |
| 209 | +} |
0 commit comments