use of com.sun.source.tree.ImportTree in project error-prone by google.
the class WildcardImport method matchCompilationUnit.
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
ImmutableList<ImportTree> wildcardImports = getWildcardImports(tree.getImports());
if (wildcardImports.isEmpty()) {
return NO_MATCH;
}
// Find all of the types that need to be imported.
Set<TypeToImport> typesToImport = ImportCollector.collect((JCCompilationUnit) tree);
Fix fix = createFix(wildcardImports, typesToImport, state);
if (fix.isEmpty()) {
return NO_MATCH;
}
return describeMatch(wildcardImports.get(0), fix);
}
use of com.sun.source.tree.ImportTree in project error-prone by google.
the class RemoveUnusedImports method matchCompilationUnit.
@Override
public Description matchCompilationUnit(CompilationUnitTree compilationUnitTree, VisitorState state) {
final ImmutableSetMultimap<ImportTree, Symbol> importedSymbols = getImportedSymbols(compilationUnitTree, state);
if (importedSymbols.isEmpty()) {
return NO_MATCH;
}
final Set<ImportTree> unusedImports = new HashSet<>(importedSymbols.keySet());
new TreeSymbolScanner(JavacTrees.instance(state.context), state.getTypes()).scan(compilationUnitTree, new SymbolSink() {
@Override
public boolean keepScanning() {
return !unusedImports.isEmpty();
}
@Override
public void accept(Symbol symbol) {
unusedImports.removeAll(importedSymbols.inverse().get(symbol));
}
});
if (unusedImports.isEmpty()) {
return NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
for (ImportTree unusedImport : unusedImports) {
fixBuilder.delete(unusedImport);
}
return describeMatch(unusedImports.iterator().next(), fixBuilder.build());
}
use of com.sun.source.tree.ImportTree in project meghanada-server by mopemope.
the class TreeAnalyzer method analyzeImports.
private static void analyzeImports(CompilationUnitTree cut, Source src, EndPosTable endPosTable) {
CachedASMReflector cachedASMReflector = CachedASMReflector.getInstance();
long firstLine = 0;
for (ImportTree imp : cut.getImports()) {
JCTree.JCImport jcImport = (JCTree.JCImport) imp;
int startPos = jcImport.getPreferredPosition();
int endPos = jcImport.getEndPosition(endPosTable);
Range range = Range.create(src, startPos + 1, endPos);
firstLine = range.begin.line;
String importClass = imp.getQualifiedIdentifier().toString();
String simpleName = ClassNameUtils.getSimpleName(importClass);
if (imp.isStatic()) {
// TODO static asterisk
Tree tree = imp.getQualifiedIdentifier();
if (tree instanceof JCTree.JCFieldAccess) {
JCTree.JCFieldAccess fieldAccess = (JCTree.JCFieldAccess) tree;
com.sun.tools.javac.util.Name name = fieldAccess.getIdentifier();
JCTree.JCExpression expression = fieldAccess.getExpression();
String methodName = name.toString();
String decClazz = expression.toString();
src.addStaticImport(methodName, decClazz);
} else {
log.warn("Not impl");
}
} else {
if (simpleName.equals("*")) {
// wild
for (String s : cachedASMReflector.getPackageClasses(importClass).values()) {
src.addImport(s);
}
} else {
src.addImport(importClass);
}
}
}
src.setClassStartLine(firstLine);
}
use of com.sun.source.tree.ImportTree in project robolectric by robolectric.
the class ImplementsValidator method captureJavadoc.
private void captureJavadoc(TypeElement elem) {
List<String> imports = new ArrayList<>();
try {
List<? extends ImportTree> importLines = Trees.instance(env).getPath(elem).getCompilationUnit().getImports();
for (ImportTree importLine : importLines) {
imports.add(importLine.getQualifiedIdentifier().toString());
}
} catch (IllegalArgumentException e) {
// Trees relies on javac APIs and is not available in all annotation processing
// implementations
}
List<TypeElement> enclosedTypes = ElementFilter.typesIn(elem.getEnclosedElements());
for (TypeElement enclosedType : enclosedTypes) {
imports.add(enclosedType.getQualifiedName().toString());
}
Elements elementUtils = env.getElementUtils();
modelBuilder.documentType(elem, elementUtils.getDocComment(elem), imports);
for (Element memberElement : ElementFilter.methodsIn(elem.getEnclosedElements())) {
try {
ExecutableElement methodElement = (ExecutableElement) memberElement;
Implementation implementation = memberElement.getAnnotation(Implementation.class);
DocumentedMethod documentedMethod = new DocumentedMethod(memberElement.toString());
for (Modifier modifier : memberElement.getModifiers()) {
documentedMethod.modifiers.add(modifier.toString());
}
documentedMethod.isImplementation = implementation != null;
if (implementation != null) {
documentedMethod.minSdk = sdkOrNull(implementation.minSdk());
documentedMethod.maxSdk = sdkOrNull(implementation.maxSdk());
}
for (VariableElement variableElement : methodElement.getParameters()) {
documentedMethod.params.add(variableElement.toString());
}
documentedMethod.returnType = methodElement.getReturnType().toString();
for (TypeMirror typeMirror : methodElement.getThrownTypes()) {
documentedMethod.exceptions.add(typeMirror.toString());
}
String docMd = elementUtils.getDocComment(methodElement);
if (docMd != null) {
documentedMethod.setDocumentation(docMd);
}
modelBuilder.documentMethod(elem, documentedMethod);
} catch (Exception e) {
throw new RuntimeException("failed to capture javadoc for " + elem + "." + memberElement, e);
}
}
}
use of com.sun.source.tree.ImportTree in project error-prone by google.
the class FindIdentifiers method findAllIdents.
/**
* Finds the set of all bare variable identifiers in scope at the current location. Identifiers
* are ordered by ascending distance/scope count from the current location to match shadowing
* rules. That is, if two variables with the same simple names appear in the set, the one that
* appears first in iteration order is the one you get if you use the bare name in the source
* code.
*
* <p>We do not report variables that would require a qualfied access. We also do not handle
* wildcard imports.
*/
public static LinkedHashSet<VarSymbol> findAllIdents(VisitorState state) {
ImmutableSet.Builder<VarSymbol> result = new ImmutableSet.Builder<>();
Tree prev = state.getPath().getLeaf();
for (Tree curr : state.getPath().getParentPath()) {
switch(curr.getKind()) {
case BLOCK:
for (StatementTree stmt : ((BlockTree) curr).getStatements()) {
if (stmt.equals(prev)) {
break;
}
addIfVariable(stmt, result);
}
break;
case METHOD:
for (VariableTree param : ((MethodTree) curr).getParameters()) {
result.add(ASTHelpers.getSymbol(param));
}
break;
case CATCH:
result.add(ASTHelpers.getSymbol(((CatchTree) curr).getParameter()));
break;
case CLASS:
case INTERFACE:
case ENUM:
case ANNOTATION_TYPE:
// field is referred to by qualified name, but we don't support that.
for (Tree member : ((ClassTree) curr).getMembers()) {
if (member.equals(prev)) {
break;
}
addIfVariable(member, result);
}
// Collect inherited fields.
Type classType = ASTHelpers.getType(curr);
List<Type> classTypeClosure = state.getTypes().closure(classType);
List<Type> superTypes = classTypeClosure.size() <= 1 ? Collections.emptyList() : classTypeClosure.subList(1, classTypeClosure.size());
for (Type type : superTypes) {
Scope scope = type.tsym.members();
ImmutableList.Builder<VarSymbol> varsList = ImmutableList.builder();
for (Symbol var : scope.getSymbols(VarSymbol.class::isInstance)) {
varsList.add((VarSymbol) var);
}
result.addAll(varsList.build().reverse());
}
break;
case FOR_LOOP:
addAllIfVariable(((ForLoopTree) curr).getInitializer(), result);
break;
case ENHANCED_FOR_LOOP:
result.add(ASTHelpers.getSymbol(((EnhancedForLoopTree) curr).getVariable()));
break;
case TRY:
TryTree tryTree = (TryTree) curr;
boolean inResources = false;
for (Tree resource : tryTree.getResources()) {
if (resource.equals(prev)) {
inResources = true;
break;
}
}
if (inResources) {
// Case 1: we're in one of the resource declarations
for (Tree resource : tryTree.getResources()) {
if (resource.equals(prev)) {
break;
}
addIfVariable(resource, result);
}
} else if (tryTree.getBlock().equals(prev)) {
// Case 2: We're in the block (not a catch or finally)
addAllIfVariable(tryTree.getResources(), result);
}
break;
case COMPILATION_UNIT:
for (ImportTree importTree : ((CompilationUnitTree) curr).getImports()) {
if (importTree.isStatic() && importTree.getQualifiedIdentifier().getKind() == Kind.MEMBER_SELECT) {
MemberSelectTree memberSelectTree = (MemberSelectTree) importTree.getQualifiedIdentifier();
Scope scope = state.getTypes().membersClosure(ASTHelpers.getType(memberSelectTree.getExpression()), /* skipInterface= */
false);
for (Symbol var : scope.getSymbols(sym -> sym instanceof VarSymbol && sym.getSimpleName().equals(memberSelectTree.getIdentifier()))) {
result.add((VarSymbol) var);
}
}
}
break;
default:
// other node types don't introduce variables
break;
}
prev = curr;
}
// TODO(eaftan): switch out collector for ImmutableSet.toImmutableSet()
return result.build().stream().filter(var -> isVisible(var, state.getPath())).collect(Collectors.toCollection(LinkedHashSet::new));
}
Aggregations