Search in sources :

Example 16 with IExtendedModifier

use of org.eclipse.jdt.core.dom.IExtendedModifier in project eclipse-pmd by acanda.

the class SuppressWarningsQuickFix method findExistingSuppressWarningsAnnotation.

private Annotation findExistingSuppressWarningsAnnotation(final List<IExtendedModifier> modifiers) {
    for (final IExtendedModifier modifier : modifiers) {
        if (modifier.isAnnotation()) {
            final Annotation annotation = (Annotation) modifier;
            final Name typeName = annotation.getTypeName();
            if (typeName.isSimpleName() && "SuppressWarnings".equals(typeName.getFullyQualifiedName()) || typeName.isQualifiedName() && "java.lang.SuppressWarnings".equals(typeName.getFullyQualifiedName())) {
                return annotation;
            }
        }
    }
    return null;
}
Also used : Annotation(org.eclipse.jdt.core.dom.Annotation) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) SingleMemberAnnotation(org.eclipse.jdt.core.dom.SingleMemberAnnotation) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name)

Example 17 with IExtendedModifier

use of org.eclipse.jdt.core.dom.IExtendedModifier in project eclipse.jdt.ls by eclipse.

the class RedundantNullnessTypeAnnotationsFilter method getNNBDAnnotation.

// based on org.eclipse.jdt.apt.core.internal.declaration.ASTBasedDeclarationImpl.getAnnotationInstancesFromAST()
private static /* @Nullable */
IAnnotationBinding getNNBDAnnotation(ASTNode astNode, String nonNullByDefaultName) {
    List<IExtendedModifier> extendsMods = null;
    switch(astNode.getNodeType()) {
        case ASTNode.COMPILATION_UNIT:
            {
                // special case: when reaching the root of the ast, check the package annotations.
                PackageDeclaration packageDeclaration = ((CompilationUnit) astNode).getPackage();
                if (packageDeclaration != null) {
                    IPackageBinding packageBinding = packageDeclaration.resolveBinding();
                    if (packageBinding != null) {
                        for (IAnnotationBinding annotationBinding : packageBinding.getAnnotations()) {
                            ITypeBinding annotationType = annotationBinding.getAnnotationType();
                            if (annotationType != null && annotationType.getQualifiedName().equals(nonNullByDefaultName)) {
                                return annotationBinding;
                            }
                        }
                    }
                }
                return null;
            }
        case ASTNode.TYPE_DECLARATION:
        case ASTNode.ANNOTATION_TYPE_DECLARATION:
        case ASTNode.ENUM_DECLARATION:
        case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
        case ASTNode.METHOD_DECLARATION:
        case ASTNode.FIELD_DECLARATION:
        case ASTNode.ENUM_CONSTANT_DECLARATION:
            extendsMods = ((BodyDeclaration) astNode).modifiers();
            break;
        case ASTNode.VARIABLE_DECLARATION_STATEMENT:
            extendsMods = ((VariableDeclarationStatement) astNode).modifiers();
            break;
        case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
            extendsMods = ((VariableDeclarationExpression) astNode).modifiers();
            break;
        case ASTNode.SINGLE_VARIABLE_DECLARATION:
            extendsMods = ((SingleVariableDeclaration) astNode).modifiers();
            break;
        case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
            final ASTNode parent = ((VariableDeclarationFragment) astNode).getParent();
            if (parent instanceof BodyDeclaration) {
                extendsMods = ((BodyDeclaration) parent).modifiers();
            }
            break;
        default:
            return null;
    }
    if (extendsMods != null) {
        for (IExtendedModifier extMod : extendsMods) {
            if (extMod.isAnnotation()) {
                Annotation annotation = (Annotation) extMod;
                IAnnotationBinding annotationBinding = annotation.resolveAnnotationBinding();
                if (annotationBinding != null) {
                    ITypeBinding annotationType = annotationBinding.getAnnotationType();
                    if (annotationType != null && annotationType.getQualifiedName().equals(nonNullByDefaultName)) {
                        return annotationBinding;
                    }
                }
            }
        }
    }
    return null;
}
Also used : IAnnotationBinding(org.eclipse.jdt.core.dom.IAnnotationBinding) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) Annotation(org.eclipse.jdt.core.dom.Annotation) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) IPackageBinding(org.eclipse.jdt.core.dom.IPackageBinding)

Example 18 with IExtendedModifier

use of org.eclipse.jdt.core.dom.IExtendedModifier in project eclipse.jdt.ls by eclipse.

the class SurroundWithTryCatchRefactoring method createTryCatchStatement.

private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String lineDelimiter) throws CoreException {
    List<Statement> result = new ArrayList<>(1);
    TryStatement tryStatement = getAST().newTryStatement();
    ITypeBinding[] exceptions = fAnalyzer.getExceptions();
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fAnalyzer.getEnclosingBodyDeclaration(), fImportRewrite);
    if (!fIsMultiCatch) {
        for (int i = 0; i < exceptions.length; i++) {
            ITypeBinding exception = exceptions[i];
            CatchClause catchClause = getAST().newCatchClause();
            tryStatement.catchClauses().add(catchClause);
            SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
            String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
            String name = fScope.createName(varName, false);
            decl.setName(getAST().newSimpleName(name));
            Type type = fImportRewrite.addImport(exception, getAST(), context, TypeLocation.EXCEPTION);
            decl.setType(type);
            catchClause.setException(decl);
            Statement st = getCatchBody(ASTNodes.getQualifiedTypeName(type), name, lineDelimiter);
            if (st != null) {
                catchClause.getBody().statements().add(st);
            }
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_TYPE + i, true).addPosition(fRewriter.track(decl.getType()), i == 0);
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_NAME + i, true).addPosition(fRewriter.track(decl.getName()), false);
        }
    } else {
        List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(exceptions);
        CatchClause catchClause = getAST().newCatchClause();
        SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
        String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
        String name = fScope.createName(varName, false);
        decl.setName(getAST().newSimpleName(name));
        UnionType unionType = getAST().newUnionType();
        List<Type> types = unionType.types();
        int i = 0;
        for (ITypeBinding exception : filteredExceptions) {
            Type type = fImportRewrite.addImport(exception, getAST(), context, TypeLocation.EXCEPTION);
            types.add(type);
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_TYPE + i, true).addPosition(fRewriter.track(type), i == 0);
            i++;
        }
        decl.setType(unionType);
        catchClause.setException(decl);
        fLinkedProposalModel.getPositionGroup(GROUP_EXC_NAME + 0, true).addPosition(fRewriter.track(decl.getName()), false);
        // $NON-NLS-1$
        Statement st = getCatchBody("Exception", name, lineDelimiter);
        if (st != null) {
            catchClause.getBody().statements().add(st);
        }
        tryStatement.catchClauses().add(catchClause);
    }
    List<ASTNode> variableDeclarations = getSpecialVariableDeclarationStatements();
    ListRewrite statements = fRewriter.getListRewrite(tryStatement.getBody(), Block.STATEMENTS_PROPERTY);
    boolean selectedNodeRemoved = false;
    ASTNode expressionStatement = null;
    for (int i = 0; i < fSelectedNodes.length; i++) {
        ASTNode node = fSelectedNodes[i];
        if (node instanceof VariableDeclarationStatement && variableDeclarations.contains(node)) {
            AST ast = getAST();
            VariableDeclarationStatement statement = (VariableDeclarationStatement) node;
            // Create a copy and remove the initializer
            VariableDeclarationStatement copy = (VariableDeclarationStatement) ASTNode.copySubtree(ast, statement);
            List<IExtendedModifier> modifiers = copy.modifiers();
            for (Iterator<IExtendedModifier> iter = modifiers.iterator(); iter.hasNext(); ) {
                IExtendedModifier modifier = iter.next();
                if (modifier.isModifier() && Modifier.isFinal(((Modifier) modifier).getKeyword().toFlagValue())) {
                    iter.remove();
                }
            }
            List<VariableDeclarationFragment> fragments = copy.fragments();
            for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
                VariableDeclarationFragment fragment = iter.next();
                fragment.setInitializer(null);
            }
            CompilationUnit root = (CompilationUnit) statement.getRoot();
            int extendedStart = root.getExtendedStartPosition(statement);
            // we have a leading comment and the comment is covered by the selection
            if (extendedStart != statement.getStartPosition() && extendedStart >= fSelection.getOffset()) {
                String commentToken = buffer.getText(extendedStart, statement.getStartPosition() - extendedStart);
                commentToken = Strings.trimTrailingTabsAndSpaces(commentToken);
                Type type = statement.getType();
                String typeName = buffer.getText(type.getStartPosition(), type.getLength());
                copy.setType((Type) fRewriter.createStringPlaceholder(commentToken + typeName, type.getNodeType()));
            }
            result.add(copy);
            // convert the fragments into expression statements
            fragments = statement.fragments();
            if (!fragments.isEmpty()) {
                List<ExpressionStatement> newExpressionStatements = new ArrayList<>();
                for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
                    VariableDeclarationFragment fragment = iter.next();
                    Expression initializer = fragment.getInitializer();
                    if (initializer != null) {
                        Assignment assignment = ast.newAssignment();
                        assignment.setLeftHandSide((Expression) fRewriter.createCopyTarget(fragment.getName()));
                        assignment.setRightHandSide((Expression) fRewriter.createCopyTarget(initializer));
                        newExpressionStatements.add(ast.newExpressionStatement(assignment));
                    }
                }
                if (!newExpressionStatements.isEmpty()) {
                    if (fSelectedNodes.length == 1) {
                        expressionStatement = fRewriter.createGroupNode(newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()]));
                    } else {
                        fRewriter.replace(statement, fRewriter.createGroupNode(newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])), null);
                    }
                } else {
                    fRewriter.remove(statement, null);
                    selectedNodeRemoved = true;
                }
            } else {
                fRewriter.remove(statement, null);
                selectedNodeRemoved = true;
            }
        }
    }
    result.add(tryStatement);
    ASTNode replacementNode;
    if (result.size() == 1) {
        replacementNode = result.get(0);
    } else {
        replacementNode = fRewriter.createGroupNode(result.toArray(new ASTNode[result.size()]));
    }
    if (fSelectedNodes.length == 1) {
        ASTNode selectedNode = fSelectedNodes[0];
        if (selectedNode instanceof MethodReference) {
            MethodReference methodReference = (MethodReference) selectedNode;
            IMethodBinding functionalMethod = QuickAssistProcessor.getFunctionalMethodForMethodReference(methodReference);
            // functionalMethod is non-null and non-generic. See ExceptionAnalyzer.handleMethodReference(MethodReference node).
            Assert.isTrue(functionalMethod != null && !functionalMethod.isGenericMethod());
            LambdaExpression lambda = QuickAssistProcessor.convertMethodRefernceToLambda(methodReference, functionalMethod, fRootNode, fRewriter, null, true);
            ASTNode statementInBlock = (ASTNode) ((Block) lambda.getBody()).statements().get(0);
            fRewriter.replace(statementInBlock, replacementNode, null);
            statements.insertLast(statementInBlock, null);
            return;
        }
        LambdaExpression enclosingLambda = ASTResolving.findEnclosingLambdaExpression(selectedNode);
        if (enclosingLambda != null && selectedNode.getLocationInParent() == LambdaExpression.BODY_PROPERTY && enclosingLambda.resolveMethodBinding() != null) {
            QuickAssistProcessor.changeLambdaBodyToBlock(enclosingLambda, getAST(), fRewriter);
            Block blockBody = (Block) fRewriter.get(enclosingLambda, LambdaExpression.BODY_PROPERTY);
            ASTNode statementInBlock = (ASTNode) blockBody.statements().get(0);
            fRewriter.replace(statementInBlock, replacementNode, null);
            statements.insertLast(statementInBlock, null);
            return;
        }
        if (expressionStatement != null) {
            statements.insertLast(expressionStatement, null);
        } else {
            if (!selectedNodeRemoved) {
                statements.insertLast(fRewriter.createMoveTarget(selectedNode), null);
            }
        }
        fRewriter.replace(selectedNode, replacementNode, null);
    } else {
        ListRewrite source = fRewriter.getListRewrite(fSelectedNodes[0].getParent(), (ChildListPropertyDescriptor) fSelectedNodes[0].getLocationInParent());
        ASTNode toMove = source.createMoveTarget(fSelectedNodes[0], fSelectedNodes[fSelectedNodes.length - 1], replacementNode, null);
        statements.insertLast(toMove, null);
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) UnionType(org.eclipse.jdt.core.dom.UnionType) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) Assignment(org.eclipse.jdt.core.dom.Assignment) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) UnionType(org.eclipse.jdt.core.dom.UnionType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) Block(org.eclipse.jdt.core.dom.Block) MethodReference(org.eclipse.jdt.core.dom.MethodReference) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 19 with IExtendedModifier

use of org.eclipse.jdt.core.dom.IExtendedModifier in project eclipse.jdt.ls by eclipse.

the class ExtractConstantRefactoring method getReplacementScope.

/*
	 * Elements returned by next() are BodyDeclaration or Annotation instances.
	 */
private Iterator<ASTNode> getReplacementScope() throws JavaModelException {
    boolean declPredecessorReached = false;
    Collection<ASTNode> scope = new ArrayList<>();
    AbstractTypeDeclaration containingType = getContainingTypeDeclarationNode();
    if (containingType instanceof EnumDeclaration) {
        // replace in all enum constants bodies
        EnumDeclaration enumDeclaration = (EnumDeclaration) containingType;
        scope.addAll(enumDeclaration.enumConstants());
    }
    for (Iterator<IExtendedModifier> iter = containingType.modifiers().iterator(); iter.hasNext(); ) {
        IExtendedModifier modifier = iter.next();
        if (modifier instanceof Annotation) {
            scope.add((ASTNode) modifier);
        }
    }
    for (Iterator<BodyDeclaration> bodyDeclarations = containingType.bodyDeclarations().iterator(); bodyDeclarations.hasNext(); ) {
        BodyDeclaration bodyDeclaration = bodyDeclarations.next();
        if (bodyDeclaration == getNodeToInsertConstantDeclarationAfter()) {
            declPredecessorReached = true;
        }
        if (insertFirst() || declPredecessorReached || !isStaticFieldOrStaticInitializer(bodyDeclaration)) {
            scope.add(bodyDeclaration);
        }
    }
    return scope.iterator();
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) Annotation(org.eclipse.jdt.core.dom.Annotation) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) EnumDeclaration(org.eclipse.jdt.core.dom.EnumDeclaration) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier)

Example 20 with IExtendedModifier

use of org.eclipse.jdt.core.dom.IExtendedModifier in project whole by wholeplatform.

the class JDTTransformerVisitor method setExtendedModifiers.

private void setExtendedModifiers(ExtendedModifiers modifiers, List<?> jdtModifiers) {
    for (Iterator<?> i = jdtModifiers.iterator(); i.hasNext(); ) {
        IExtendedModifier em = (IExtendedModifier) i.next();
        if (em.isAnnotation()) {
            acceptChild((Annotation) em);
            modifiers.wAdd(exp);
        } else if (em.isModifier()) {
            Modifier m = (Modifier) em;
            ModifierKeyword mk = m.getKeyword();
            int flags = mk.toFlagValue();
            if (Modifier.isPublic(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._public));
            if (Modifier.isPrivate(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._private));
            if (Modifier.isProtected(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._protected));
            if (Modifier.isStatic(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._static));
            if (Modifier.isFinal(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._final));
            if (Modifier.isSynchronized(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._synchronized));
            if (Modifier.isVolatile(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._volatile));
            if (Modifier.isTransient(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._transient));
            if (Modifier.isNative(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._native));
            if (Modifier.isAbstract(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._abstract));
            if (Modifier.isStrictfp(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum.strictftp));
            if (Modifier.isDefault(flags))
                modifiers.wAdd(lf.createModifier(ModifierEnum._default));
        }
    }
}
Also used : ModifierKeyword(org.eclipse.jdt.core.dom.Modifier.ModifierKeyword) Modifier(org.eclipse.jdt.core.dom.Modifier) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier)

Aggregations

IExtendedModifier (org.eclipse.jdt.core.dom.IExtendedModifier)46 Modifier (org.eclipse.jdt.core.dom.Modifier)27 ASTNode (org.eclipse.jdt.core.dom.ASTNode)15 Annotation (org.eclipse.jdt.core.dom.Annotation)14 ASTRewrite (org.autorefactor.jdt.core.dom.ASTRewrite)11 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)11 TextEditGroup (org.eclipse.text.edits.TextEditGroup)11 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)9 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)9 ArrayList (java.util.ArrayList)8 AST (org.eclipse.jdt.core.dom.AST)6 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)5 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)5 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)5 ModifierKeyword (org.eclipse.jdt.core.dom.Modifier.ModifierKeyword)5 Statement (org.eclipse.jdt.core.dom.Statement)5 Type (org.eclipse.jdt.core.dom.Type)5 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)5 Expression (org.eclipse.jdt.core.dom.Expression)4 SimpleName (org.eclipse.jdt.core.dom.SimpleName)4