use of org.eclipse.jdt.core.dom.AnnotationTypeDeclaration in project che by eclipse.
the class SuppressWarningsSubProcessor method addSuppressWarningsProposalIfPossible.
/**
* Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance).
*
* @param cu the compilation unit
* @param node the node on which to add a SuppressWarning token
* @param warningToken the warning token to add
* @param relevance the proposal's relevance
* @param proposals collector to which the proposal should be added
* @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal
*
* @since 3.6
*/
private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) {
ChildListPropertyDescriptor property;
String name;
boolean isLocalVariable = false;
switch(node.getNodeType()) {
case ASTNode.SINGLE_VARIABLE_DECLARATION:
property = SingleVariableDeclaration.MODIFIERS2_PROPERTY;
name = ((SingleVariableDeclaration) node).getName().getIdentifier();
isLocalVariable = true;
break;
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
property = VariableDeclarationStatement.MODIFIERS2_PROPERTY;
name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments());
isLocalVariable = true;
break;
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
property = VariableDeclarationExpression.MODIFIERS2_PROPERTY;
name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments());
isLocalVariable = true;
break;
case ASTNode.TYPE_DECLARATION:
property = TypeDeclaration.MODIFIERS2_PROPERTY;
name = ((TypeDeclaration) node).getName().getIdentifier();
break;
case ASTNode.ANNOTATION_TYPE_DECLARATION:
property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY;
name = ((AnnotationTypeDeclaration) node).getName().getIdentifier();
break;
case ASTNode.ENUM_DECLARATION:
property = EnumDeclaration.MODIFIERS2_PROPERTY;
name = ((EnumDeclaration) node).getName().getIdentifier();
break;
case ASTNode.FIELD_DECLARATION:
property = FieldDeclaration.MODIFIERS2_PROPERTY;
name = getFirstFragmentName(((FieldDeclaration) node).fragments());
break;
// case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations
case ASTNode.METHOD_DECLARATION:
property = MethodDeclaration.MODIFIERS2_PROPERTY;
//$NON-NLS-1$
name = ((MethodDeclaration) node).getName().getIdentifier() + "()";
break;
case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY;
//$NON-NLS-1$
name = ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + "()";
break;
case ASTNode.ENUM_CONSTANT_DECLARATION:
property = EnumConstantDeclaration.MODIFIERS2_PROPERTY;
name = ((EnumConstantDeclaration) node).getName().getIdentifier();
break;
default:
return relevance;
}
String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) });
ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance);
proposals.add(proposal);
return isLocalVariable ? relevance - 1 : 0;
}
use of org.eclipse.jdt.core.dom.AnnotationTypeDeclaration in project buck by facebook.
the class JavaFileParser method extractFeaturesFromJavaCode.
public JavaFileFeatures extractFeaturesFromJavaCode(String code) {
// For now, we will harcode this. Ultimately, we probably want to make this configurable via
// .buckconfig. For example, the Buck project itself is diligent about disallowing wildcard
// imports, but the one exception is the Java code generated via Thrift in src-gen.
final boolean shouldThrowForUnsupportedWildcardImport = false;
final AtomicBoolean isPoisonedByUnsupportedWildcardImport = new AtomicBoolean(false);
final CompilationUnit compilationUnit = makeCompilationUnitFromSource(code);
final ImmutableSortedSet.Builder<String> providedSymbols = ImmutableSortedSet.naturalOrder();
final ImmutableSortedSet.Builder<String> requiredSymbols = ImmutableSortedSet.naturalOrder();
final ImmutableSortedSet.Builder<String> exportedSymbols = ImmutableSortedSet.naturalOrder();
final ImmutableSortedSet.Builder<String> requiredSymbolsFromExplicitImports = ImmutableSortedSet.naturalOrder();
compilationUnit.accept(new ASTVisitor() {
@Nullable
private String packageName;
/** Maps simple name to fully-qualified name. */
private Map<String, String> simpleImportedTypes = new HashMap<>();
/**
* Maps wildcard import prefixes, such as {@code "java.util"} to the types in the respective
* package if a wildcard import such as {@code import java.util.*} is used.
*/
private Map<String, ImmutableSet<String>> wildcardImports = new HashMap<>();
@Override
public boolean visit(PackageDeclaration node) {
Preconditions.checkState(packageName == null, "There should be at most one package declaration");
packageName = node.getName().getFullyQualifiedName();
return false;
}
// providedSymbols
@Override
public boolean visit(TypeDeclaration node) {
// Local classes can be declared inside of methods. Skip over these.
if (node.getParent() instanceof TypeDeclarationStatement) {
return true;
}
String fullyQualifiedName = getFullyQualifiedTypeName(node);
if (fullyQualifiedName != null) {
providedSymbols.add(fullyQualifiedName);
}
@SuppressWarnings("unchecked") List<Type> interfaceTypes = node.superInterfaceTypes();
for (Type interfaceType : interfaceTypes) {
tryAddType(interfaceType, DependencyType.EXPORTED);
}
Type superclassType = node.getSuperclassType();
if (superclassType != null) {
tryAddType(superclassType, DependencyType.EXPORTED);
}
return true;
}
@Override
public boolean visit(EnumDeclaration node) {
String fullyQualifiedName = getFullyQualifiedTypeName(node);
if (fullyQualifiedName != null) {
providedSymbols.add(fullyQualifiedName);
}
return true;
}
@Override
public boolean visit(AnnotationTypeDeclaration node) {
String fullyQualifiedName = getFullyQualifiedTypeName(node);
if (fullyQualifiedName != null) {
providedSymbols.add(fullyQualifiedName);
}
return true;
}
// requiredSymbols
/**
* Uses heuristics to try to figure out what type of QualifiedName this is. Returns a non-null
* value if this is believed to be a reference that qualifies as a "required symbol"
* relationship.
*/
@Override
public boolean visit(QualifiedName node) {
QualifiedName ancestor = findMostQualifiedAncestor(node);
ASTNode parent = ancestor.getParent();
if (!(parent instanceof PackageDeclaration) && !(parent instanceof ImportDeclaration)) {
String symbol = ancestor.getFullyQualifiedName();
// lookup.
if (CharMatcher.javaUpperCase().matches(symbol.charAt(0))) {
addTypeFromDotDelimitedSequence(symbol, DependencyType.REQUIRED);
}
}
return false;
}
/**
* @param expr could be "Example", "Example.field", "com.example.Example". Note it could also
* be a built-in type, such as "java.lang.Integer", in which case it will not be added to
* the set of required symbols.
*/
private void addTypeFromDotDelimitedSequence(String expr, DependencyType dependencyType) {
// check it against JAVA_LANG_TYPES.
if (startsWithUppercaseChar(expr)) {
int index = expr.indexOf('.');
if (index >= 0) {
String leftmostComponent = expr.substring(0, index);
if (JAVA_LANG_TYPES.contains(leftmostComponent)) {
return;
}
}
}
expr = qualifyWithPackageNameIfNecessary(expr);
addSymbol(expr, dependencyType);
}
@Override
public boolean visit(ImportDeclaration node) {
String fullyQualifiedName = node.getName().getFullyQualifiedName();
// third-party code. As such, we will tolerate these for some of the common cases.
if (node.isOnDemand()) {
ImmutableSet<String> value = SUPPORTED_WILDCARD_IMPORTS.get(fullyQualifiedName);
if (value != null) {
wildcardImports.put(fullyQualifiedName, value);
return false;
} else if (shouldThrowForUnsupportedWildcardImport) {
throw new RuntimeException(String.format("Use of wildcard 'import %s.*' makes it impossible to statically determine " + "required symbols in this file. Please enumerate explicit imports.", fullyQualifiedName));
} else {
isPoisonedByUnsupportedWildcardImport.set(true);
return false;
}
}
// Only worry about the dependency on the enclosing type.
Optional<String> simpleName = getSimpleNameFromFullyQualifiedName(fullyQualifiedName);
if (simpleName.isPresent()) {
String name = simpleName.get();
int index = fullyQualifiedName.indexOf("." + name);
String enclosingType = fullyQualifiedName.substring(0, index + name.length() + 1);
requiredSymbolsFromExplicitImports.add(enclosingType);
simpleImportedTypes.put(name, enclosingType);
} else {
LOG.warn("Suspicious import lacks obvious enclosing type: %s", fullyQualifiedName);
// The one example we have seen of this in the wild is
// "org.whispersystems.curve25519.java.curve_sigs". In practice, we still need to add it
// as a required symbol in this case.
requiredSymbols.add(fullyQualifiedName);
}
return false;
}
@Override
public boolean visit(MethodInvocation node) {
if (node.getExpression() == null) {
return true;
}
String receiver = node.getExpression().toString();
if (looksLikeAType(receiver)) {
addTypeFromDotDelimitedSequence(receiver, DependencyType.REQUIRED);
}
return true;
}
/** An annotation on a member with zero arguments. */
@Override
public boolean visit(MarkerAnnotation node) {
DependencyType dependencyType = findDependencyTypeForAnnotation(node);
addSimpleTypeName(node.getTypeName(), dependencyType);
return true;
}
/** An annotation on a member with named arguments. */
@Override
public boolean visit(NormalAnnotation node) {
DependencyType dependencyType = findDependencyTypeForAnnotation(node);
addSimpleTypeName(node.getTypeName(), dependencyType);
return true;
}
/** An annotation on a member with a single, unnamed argument. */
@Override
public boolean visit(SingleMemberAnnotation node) {
DependencyType dependencyType = findDependencyTypeForAnnotation(node);
addSimpleTypeName(node.getTypeName(), dependencyType);
return true;
}
private DependencyType findDependencyTypeForAnnotation(Annotation annotation) {
ASTNode parentNode = annotation.getParent();
if (parentNode == null) {
return DependencyType.REQUIRED;
}
if (parentNode instanceof BodyDeclaration) {
// Note that BodyDeclaration is an abstract class. Its subclasses are things like
// FieldDeclaration and MethodDeclaration. We want to be sure that an annotation on any
// non-private declaration is considered an exported symbol.
BodyDeclaration declaration = (BodyDeclaration) parentNode;
int modifiers = declaration.getModifiers();
if ((modifiers & Modifier.PRIVATE) == 0) {
return DependencyType.EXPORTED;
}
}
return DependencyType.REQUIRED;
}
@Override
public boolean visit(SimpleType node) {
// This method is responsible for finding the overwhelming majority of the required symbols
// in the AST.
tryAddType(node, DependencyType.REQUIRED);
return true;
}
// exportedSymbols
@Override
public boolean visit(MethodDeclaration node) {
// Types from private method signatures need not be exported.
if ((node.getModifiers() & Modifier.PRIVATE) != 0) {
return true;
}
Type returnType = node.getReturnType2();
if (returnType != null) {
tryAddType(returnType, DependencyType.EXPORTED);
}
@SuppressWarnings("unchecked") List<SingleVariableDeclaration> params = node.parameters();
for (SingleVariableDeclaration decl : params) {
tryAddType(decl.getType(), DependencyType.EXPORTED);
}
@SuppressWarnings("unchecked") List<Type> exceptions = node.thrownExceptionTypes();
for (Type exception : exceptions) {
tryAddType(exception, DependencyType.EXPORTED);
}
return true;
}
@Override
public boolean visit(FieldDeclaration node) {
// Types from private fields need not be exported.
if ((node.getModifiers() & Modifier.PRIVATE) == 0) {
tryAddType(node.getType(), DependencyType.EXPORTED);
}
return true;
}
private void tryAddType(Type type, DependencyType dependencyType) {
if (type.isSimpleType()) {
SimpleType simpleType = (SimpleType) type;
Name simpleTypeName = simpleType.getName();
String simpleName = simpleTypeName.toString();
// rather than simply required.
if (!CharMatcher.javaUpperCase().matchesAllOf(simpleName) || (dependencyType == DependencyType.EXPORTED && simpleImportedTypes.containsKey(simpleName))) {
addSimpleTypeName(simpleTypeName, dependencyType);
}
} else if (type.isArrayType()) {
ArrayType arrayType = (ArrayType) type;
tryAddType(arrayType.getElementType(), dependencyType);
} else if (type.isParameterizedType()) {
ParameterizedType parameterizedType = (ParameterizedType) type;
tryAddType(parameterizedType.getType(), dependencyType);
@SuppressWarnings("unchecked") List<Type> argTypes = parameterizedType.typeArguments();
for (Type argType : argTypes) {
tryAddType(argType, dependencyType);
}
}
}
private void addSimpleTypeName(Name simpleTypeName, DependencyType dependencyType) {
String simpleName = simpleTypeName.toString();
if (JAVA_LANG_TYPES.contains(simpleName)) {
return;
}
String fullyQualifiedNameForSimpleName = simpleImportedTypes.get(simpleName);
if (fullyQualifiedNameForSimpleName != null) {
// May need to promote from required to exported in this case.
if (dependencyType == DependencyType.EXPORTED) {
addSymbol(fullyQualifiedNameForSimpleName, DependencyType.EXPORTED);
}
return;
}
// the iterator most of the time.
if (!wildcardImports.isEmpty()) {
for (Map.Entry<String, ImmutableSet<String>> entry : wildcardImports.entrySet()) {
Set<String> types = entry.getValue();
if (types.contains(simpleName)) {
String packageName = entry.getKey();
addSymbol(packageName + "." + simpleName, dependencyType);
return;
}
}
}
String symbol = simpleTypeName.getFullyQualifiedName();
symbol = qualifyWithPackageNameIfNecessary(symbol);
addSymbol(symbol, dependencyType);
}
private void addSymbol(String symbol, DependencyType dependencyType) {
((dependencyType == DependencyType.REQUIRED) ? requiredSymbols : exportedSymbols).add(symbol);
}
private String qualifyWithPackageNameIfNecessary(String symbol) {
if (!startsWithUppercaseChar(symbol)) {
return symbol;
}
// If the symbol starts with a capital letter, then we assume that it is a reference to
// a type in the same package.
int index = symbol.indexOf('.');
if (index >= 0) {
symbol = symbol.substring(0, index);
}
if (packageName != null) {
symbol = packageName + "." + symbol;
}
return symbol;
}
});
// TODO(bolinfest): Special treatment for exportedSymbols when poisoned by wildcard import.
ImmutableSortedSet<String> totalExportedSymbols = exportedSymbols.build();
// If we were poisoned by an unsupported wildcard import, then we should rely exclusively on
// the explicit imports to determine the required symbols.
Set<String> totalRequiredSymbols = new HashSet<>();
if (isPoisonedByUnsupportedWildcardImport.get()) {
totalRequiredSymbols.addAll(requiredSymbolsFromExplicitImports.build());
} else {
totalRequiredSymbols.addAll(requiredSymbolsFromExplicitImports.build());
totalRequiredSymbols.addAll(requiredSymbols.build());
}
// Make sure that required and exported symbols are disjoint sets.
totalRequiredSymbols.removeAll(totalExportedSymbols);
return new JavaFileFeatures(providedSymbols.build(), ImmutableSortedSet.copyOf(totalRequiredSymbols), totalExportedSymbols);
}
use of org.eclipse.jdt.core.dom.AnnotationTypeDeclaration in project che by eclipse.
the class NewAnnotationMemberProposal method getRewrite.
@Override
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(fInvocationNode);
ASTNode typeDecl = astRoot.findDeclaringNode(fSenderBinding);
ASTNode newTypeDecl = null;
if (typeDecl != null) {
newTypeDecl = typeDecl;
} else {
astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
}
createImportRewrite(astRoot);
if (newTypeDecl instanceof AnnotationTypeDeclaration) {
AnnotationTypeDeclaration newAnnotationTypeDecl = (AnnotationTypeDeclaration) newTypeDecl;
ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
AnnotationTypeMemberDeclaration newStub = getStub(rewrite, newAnnotationTypeDecl);
List<BodyDeclaration> members = newAnnotationTypeDecl.bodyDeclarations();
int insertIndex = members.size();
ListRewrite listRewriter = rewrite.getListRewrite(newAnnotationTypeDecl, AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY);
listRewriter.insertAt(newStub, insertIndex, null);
return rewrite;
}
return null;
}
use of org.eclipse.jdt.core.dom.AnnotationTypeDeclaration in project che by eclipse.
the class TypeContextChecker method fillWithTypeStubs.
private static void fillWithTypeStubs(final StringBuffer bufBefore, final StringBuffer bufAfter, final int focalPosition, List<? extends BodyDeclaration> types) {
StringBuffer buf;
for (Iterator<? extends BodyDeclaration> iter = types.iterator(); iter.hasNext(); ) {
BodyDeclaration bodyDeclaration = iter.next();
if (!(bodyDeclaration instanceof AbstractTypeDeclaration)) {
//account for local classes:
if (!(bodyDeclaration instanceof MethodDeclaration))
continue;
int bodyStart = bodyDeclaration.getStartPosition();
int bodyEnd = bodyDeclaration.getStartPosition() + bodyDeclaration.getLength();
if (!(bodyStart < focalPosition && focalPosition < bodyEnd))
continue;
MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
buf = bufBefore;
appendModifiers(buf, methodDeclaration.modifiers());
appendTypeParameters(buf, methodDeclaration.typeParameters());
//$NON-NLS-1$
buf.append(" void ");
buf.append(methodDeclaration.getName().getIdentifier());
//$NON-NLS-1$
buf.append("(){\n");
Block body = methodDeclaration.getBody();
body.accept(new HierarchicalASTVisitor() {
@Override
public boolean visit(AbstractTypeDeclaration node) {
fillWithTypeStubs(bufBefore, bufAfter, focalPosition, Collections.singletonList(node));
return false;
}
@Override
public boolean visit(ClassInstanceCreation node) {
AnonymousClassDeclaration anonDecl = node.getAnonymousClassDeclaration();
if (anonDecl == null)
// could be in CIC parameter list
return true;
int anonStart = anonDecl.getStartPosition();
int anonEnd = anonDecl.getStartPosition() + anonDecl.getLength();
if (!(anonStart < focalPosition && focalPosition < anonEnd))
return false;
//$NON-NLS-1$
bufBefore.append(" new ");
bufBefore.append(node.getType().toString());
//$NON-NLS-1$
bufBefore.append("(){\n");
fillWithTypeStubs(bufBefore, bufAfter, focalPosition, anonDecl.bodyDeclarations());
//$NON-NLS-1$
bufAfter.append("};\n");
return false;
}
});
buf = bufAfter;
//$NON-NLS-1$
buf.append("}\n");
continue;
}
AbstractTypeDeclaration decl = (AbstractTypeDeclaration) bodyDeclaration;
buf = decl.getStartPosition() < focalPosition ? bufBefore : bufAfter;
appendModifiers(buf, decl.modifiers());
if (decl instanceof TypeDeclaration) {
TypeDeclaration type = (TypeDeclaration) decl;
//$NON-NLS-1$//$NON-NLS-2$
buf.append(type.isInterface() ? "interface " : "class ");
buf.append(type.getName().getIdentifier());
appendTypeParameters(buf, type.typeParameters());
if (type.getSuperclassType() != null) {
//$NON-NLS-1$
buf.append(" extends ");
buf.append(ASTNodes.asString(type.getSuperclassType()));
}
List<Type> superInterfaces = type.superInterfaceTypes();
appendSuperInterfaces(buf, superInterfaces);
} else if (decl instanceof AnnotationTypeDeclaration) {
AnnotationTypeDeclaration annotation = (AnnotationTypeDeclaration) decl;
//$NON-NLS-1$
buf.append("@interface ");
buf.append(annotation.getName().getIdentifier());
} else if (decl instanceof EnumDeclaration) {
EnumDeclaration enumDecl = (EnumDeclaration) decl;
//$NON-NLS-1$
buf.append("enum ");
buf.append(enumDecl.getName().getIdentifier());
List<Type> superInterfaces = enumDecl.superInterfaceTypes();
appendSuperInterfaces(buf, superInterfaces);
}
//$NON-NLS-1$
buf.append("{\n");
if (decl instanceof EnumDeclaration)
//$NON-NLS-1$
buf.append(";\n");
fillWithTypeStubs(bufBefore, bufAfter, focalPosition, decl.bodyDeclarations());
buf = decl.getStartPosition() + decl.getLength() < focalPosition ? bufBefore : bufAfter;
//$NON-NLS-1$
buf.append("}\n");
}
}
Aggregations