Search in sources :

Example 26 with Modifier

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

the class SingularFieldQuickFix method replaceAssignment.

/**
 * Replaces the assignment with a variable declaration. If the assignment is the only one in the block for this
 * variable, the final modifier is added to the declaration.
 */
@SuppressWarnings("unchecked")
private void replaceAssignment(final VariableDeclarationFragment node, final Assignment assignment, final boolean finalDeclaration) {
    final FieldDeclaration fieldDeclaration = (FieldDeclaration) node.getParent();
    final VariableDeclarationStatement declaration = (VariableDeclarationStatement) node.getAST().createInstance(VariableDeclarationStatement.class);
    declaration.setType(ASTUtil.copy(fieldDeclaration.getType()));
    final VariableDeclarationFragment fragment = (VariableDeclarationFragment) node.getAST().createInstance(VariableDeclarationFragment.class);
    fragment.setName(ASTUtil.copy(node.getName()));
    fragment.setInitializer(ASTUtil.copy(assignment.getRightHandSide()));
    declaration.fragments().add(fragment);
    if (finalDeclaration) {
        final Modifier modifier = (Modifier) node.getAST().createInstance(Modifier.class);
        modifier.setKeyword(ModifierKeyword.FINAL_KEYWORD);
        declaration.modifiers().add(modifier);
    }
    ASTUtil.replace(assignment.getParent(), declaration);
}
Also used : VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) Modifier(org.eclipse.jdt.core.dom.Modifier) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Example 27 with Modifier

use of org.eclipse.jdt.core.dom.Modifier in project che by eclipse.

the class ModifierRewrite method internalSetModifiers.

/**
	 * Sets the given modifiers and removes all other modifiers that match the consideredFlags mask.
	 * Does not touch other flags and leaves annotations in place.
	 *
	 * @param modifiers the modifiers to set
	 * @param consideredFlags mask of modifiers to consider
	 * @param editGroup the edit group in which to collect the corresponding text edits, or
	 *            <code>null</code> if ungrouped
	 * @return a tracked position that contains the changed modifiers
	 */
private PositionInformation internalSetModifiers(int modifiers, int consideredFlags, TextEditGroup editGroup) {
    int newModifiers = modifiers & consideredFlags;
    ITrackedNodePosition trackedFallback = null;
    List<ITrackedNodePosition> trackedNodes = new ArrayList<ITrackedNodePosition>();
    // remove modifiers
    List<IExtendedModifier> originalList = fModifierRewrite.getOriginalList();
    for (int i = 0; i < originalList.size(); i++) {
        ASTNode curr = (ASTNode) originalList.get(i);
        if (curr instanceof Modifier) {
            int flag = ((Modifier) curr).getKeyword().toFlagValue();
            if ((consideredFlags & flag) != 0) {
                if ((newModifiers & flag) == 0) {
                    fModifierRewrite.remove(curr, editGroup);
                    if (trackedFallback == null)
                        trackedFallback = fModifierRewrite.getASTRewrite().track(curr);
                }
                newModifiers &= ~flag;
            }
        }
    }
    // find last annotation
    IExtendedModifier lastAnnotation = null;
    List<IExtendedModifier> extendedList = fModifierRewrite.getRewrittenList();
    for (int i = 0; i < extendedList.size(); i++) {
        IExtendedModifier curr = extendedList.get(i);
        if (curr.isAnnotation())
            lastAnnotation = curr;
    }
    // add modifiers
    List<Modifier> newNodes = ASTNodeFactory.newModifiers(fAst, newModifiers);
    for (int i = 0; i < newNodes.size(); i++) {
        Modifier curr = newNodes.get(i);
        if ((curr.getKeyword().toFlagValue() & VISIBILITY_MODIFIERS) != 0) {
            if (lastAnnotation != null)
                fModifierRewrite.insertAfter(curr, (ASTNode) lastAnnotation, editGroup);
            else
                fModifierRewrite.insertFirst(curr, editGroup);
        } else {
            fModifierRewrite.insertLast(curr, editGroup);
        }
        trackedNodes.add(fModifierRewrite.getASTRewrite().track(curr));
    }
    if (trackedNodes.isEmpty()) {
        if (trackedFallback == null) {
            // out of tricks...
            trackedFallback = fModifierRewrite.getASTRewrite().track(fModifierRewrite.getParent());
        }
        return new LinkedProposalPositionGroup.StartPositionInformation(trackedFallback);
    } else {
        return new LinkedProposalPositionGroup.TrackedNodesPosition(trackedNodes);
    }
}
Also used : ArrayList(java.util.ArrayList) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ITrackedNodePosition(org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition) Modifier(org.eclipse.jdt.core.dom.Modifier) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier)

Example 28 with Modifier

use of org.eclipse.jdt.core.dom.Modifier in project che by eclipse.

the class StubUtility2 method getImplementationModifiers.

private static List<IExtendedModifier> getImplementationModifiers(AST ast, IMethodBinding method, boolean inInterface, ImportRewrite importRewrite, ImportRewriteContext context) throws JavaModelException {
    IJavaProject javaProject = importRewrite.getCompilationUnit().getJavaProject();
    int modifiers = method.getModifiers() & ~Modifier.ABSTRACT & ~Modifier.NATIVE & ~Modifier.PRIVATE;
    if (inInterface) {
        modifiers = modifiers & ~Modifier.PROTECTED;
        if (!method.getDeclaringClass().isInterface()) {
            modifiers = modifiers | Modifier.PUBLIC;
        }
    } else {
        modifiers = modifiers & ~Modifier.DEFAULT;
    }
    IAnnotationBinding[] annotations = method.getAnnotations();
    if (modifiers != Modifier.NONE && annotations.length > 0) {
        // need an AST of the source method to preserve order of modifiers
        IMethod iMethod = (IMethod) method.getJavaElement();
        if (iMethod != null && JavaElementUtil.isSourceAvailable(iMethod)) {
            CheASTParser parser = CheASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(iMethod.getTypeRoot());
            parser.setIgnoreMethodBodies(true);
            CompilationUnit otherCU = (CompilationUnit) parser.createAST(null);
            ASTNode otherMethod = NodeFinder.perform(otherCU, iMethod.getSourceRange());
            if (otherMethod instanceof MethodDeclaration) {
                MethodDeclaration otherMD = (MethodDeclaration) otherMethod;
                ArrayList<IExtendedModifier> result = new ArrayList<IExtendedModifier>();
                List<IExtendedModifier> otherModifiers = otherMD.modifiers();
                for (IExtendedModifier otherModifier : otherModifiers) {
                    if (otherModifier instanceof Modifier) {
                        int otherFlag = ((Modifier) otherModifier).getKeyword().toFlagValue();
                        if ((otherFlag & modifiers) != 0) {
                            modifiers = ~otherFlag & modifiers;
                            result.addAll(ast.newModifiers(otherFlag));
                        }
                    } else {
                        Annotation otherAnnotation = (Annotation) otherModifier;
                        String n = otherAnnotation.getTypeName().getFullyQualifiedName();
                        for (IAnnotationBinding annotation : annotations) {
                            ITypeBinding otherAnnotationType = annotation.getAnnotationType();
                            String qn = otherAnnotationType.getQualifiedName();
                            if (qn.endsWith(n) && (qn.length() == n.length() || qn.charAt(qn.length() - n.length() - 1) == '.')) {
                                if (StubUtility2.isCopyOnInheritAnnotation(otherAnnotationType, javaProject))
                                    result.add(importRewrite.addAnnotation(annotation, ast, context));
                                break;
                            }
                        }
                    }
                }
                result.addAll(ASTNodeFactory.newModifiers(ast, modifiers));
                return result;
            }
        }
    }
    ArrayList<IExtendedModifier> result = new ArrayList<IExtendedModifier>();
    for (IAnnotationBinding annotation : annotations) {
        if (StubUtility2.isCopyOnInheritAnnotation(annotation.getAnnotationType(), javaProject))
            result.add(importRewrite.addAnnotation(annotation, ast, context));
    }
    result.addAll(ASTNodeFactory.newModifiers(ast, modifiers));
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ArrayList(java.util.ArrayList) Annotation(org.eclipse.jdt.core.dom.Annotation) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) IJavaProject(org.eclipse.jdt.core.IJavaProject) IAnnotationBinding(org.eclipse.jdt.core.dom.IAnnotationBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) IMethod(org.eclipse.jdt.core.IMethod) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) Modifier(org.eclipse.jdt.core.dom.Modifier)

Example 29 with Modifier

use of org.eclipse.jdt.core.dom.Modifier in project che by eclipse.

the class ModifierCorrectionSubProcessor method addAbstractMethodProposals.

public static void addAbstractMethodProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    MethodDeclaration decl;
    if (selectedNode instanceof SimpleName) {
        decl = (MethodDeclaration) selectedNode.getParent();
    } else if (selectedNode instanceof MethodDeclaration) {
        decl = (MethodDeclaration) selectedNode;
    } else {
        return;
    }
    ASTNode parentType = ASTResolving.findParentType(decl);
    TypeDeclaration parentTypeDecl = null;
    boolean parentIsAbstractClass = false;
    if (parentType instanceof TypeDeclaration) {
        parentTypeDecl = (TypeDeclaration) parentType;
        parentIsAbstractClass = !parentTypeDecl.isInterface() && Modifier.isAbstract(parentTypeDecl.getModifiers());
    }
    boolean hasNoBody = decl.getBody() == null;
    int id = problem.getProblemId();
    if (id == IProblem.AbstractMethodInAbstractClass || id == IProblem.EnumAbstractMethodMustBeImplemented || id == IProblem.AbstractMethodInEnum || parentIsAbstractClass) {
        AST ast = astRoot.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        removeModifier(decl, rewrite, Modifier.ABSTRACT);
        if (hasNoBody) {
            Block newBody = ast.newBlock();
            rewrite.set(decl, MethodDeclaration.BODY_PROPERTY, newBody, null);
            Type returnType = decl.getReturnType2();
            if (returnType != null) {
                Expression expr = ASTNodeFactory.newDefaultExpression(ast, returnType, decl.getExtraDimensions());
                if (expr != null) {
                    ReturnStatement returnStatement = ast.newReturnStatement();
                    returnStatement.setExpression(expr);
                    newBody.statements().add(returnStatement);
                }
            }
        }
        String label = CorrectionMessages.ModifierCorrectionSubProcessor_removeabstract_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_ABSTRACT_MODIFIER, image);
        proposals.add(proposal);
    }
    if (!hasNoBody && id == IProblem.BodyForAbstractMethod) {
        AST ast = decl.getAST();
        {
            ASTRewrite rewrite = ASTRewrite.create(ast);
            rewrite.remove(decl.getBody(), null);
            String label = CorrectionMessages.ModifierCorrectionSubProcessor_removebody_description;
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_METHOD_BODY, image);
            proposals.add(proposal);
        }
        if (JavaModelUtil.is18OrHigher(cu.getJavaProject()) && parentTypeDecl.isInterface()) {
            {
                // insert proposal to add static modifier
                ASTRewrite rewrite = ASTRewrite.create(ast);
                removeModifier(decl, rewrite, Modifier.ABSTRACT);
                Modifier newModifier = ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD);
                rewrite.getListRewrite(decl, MethodDeclaration.MODIFIERS2_PROPERTY).insertLast(newModifier, null);
                String label = Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertostatic_description, decl.getName());
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                int included = Modifier.STATIC;
                int excluded = Modifier.ABSTRACT | Modifier.DEFAULT;
                proposals.add(new ModifierChangeCorrectionProposal(label, cu, decl.resolveBinding(), decl, included, excluded, IProposalRelevance.ADD_STATIC_MODIFIER, image));
            }
            {
                // insert proposal to add default modifier
                ASTRewrite rewrite = ASTRewrite.create(ast);
                removeModifier(decl, rewrite, Modifier.ABSTRACT);
                Modifier newModifier = ast.newModifier(Modifier.ModifierKeyword.DEFAULT_KEYWORD);
                rewrite.getListRewrite(decl, MethodDeclaration.MODIFIERS2_PROPERTY).insertLast(newModifier, null);
                String label = Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertodefault_description, decl.getName());
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                int included = Modifier.DEFAULT;
                int excluded = Modifier.ABSTRACT | Modifier.STATIC;
                proposals.add(new ModifierChangeCorrectionProposal(label, cu, decl.resolveBinding(), decl, included, excluded, IProposalRelevance.ADD_DEFAULT_MODIFIER, image));
            }
        }
    }
    if (id == IProblem.AbstractMethodInAbstractClass && parentTypeDecl != null) {
        addMakeTypeAbstractProposal(context, parentTypeDecl, proposals);
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) Expression(org.eclipse.jdt.core.dom.Expression) ModifierChangeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.ModifierChangeCorrectionProposal) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) Modifier(org.eclipse.jdt.core.dom.Modifier)

Example 30 with Modifier

use of org.eclipse.jdt.core.dom.Modifier in project lombok by rzwitserloot.

the class PatchValEclipse method createModifier.

public static Modifier createModifier(AST ast, ModifierKeyword keyword, int start, int end) {
    Modifier modifier = null;
    try {
        modifier = Reflection.modifierConstructor.newInstance(ast);
    } catch (InstantiationException e) {
        throw Lombok.sneakyThrow(e);
    } catch (IllegalAccessException e) {
        throw Lombok.sneakyThrow(e);
    } catch (InvocationTargetException e) {
        throw Lombok.sneakyThrow(e);
    }
    if (modifier != null) {
        modifier.setKeyword(keyword);
        modifier.setSourceRange(start, end - start + 1);
    }
    return modifier;
}
Also used : IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) Modifier(org.eclipse.jdt.core.dom.Modifier) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

Modifier (org.eclipse.jdt.core.dom.Modifier)49 IExtendedModifier (org.eclipse.jdt.core.dom.IExtendedModifier)39 ASTNode (org.eclipse.jdt.core.dom.ASTNode)16 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)12 ASTRewrite (org.autorefactor.jdt.core.dom.ASTRewrite)11 TextEditGroup (org.eclipse.text.edits.TextEditGroup)11 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)9 AST (org.eclipse.jdt.core.dom.AST)7 ArrayList (java.util.ArrayList)6 Block (org.eclipse.jdt.core.dom.Block)6 ModifierKeyword (org.eclipse.jdt.core.dom.Modifier.ModifierKeyword)6 SimpleType (org.eclipse.jdt.core.dom.SimpleType)6 Type (org.eclipse.jdt.core.dom.Type)6 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)5 ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)5 Expression (org.eclipse.jdt.core.dom.Expression)5 SimpleName (org.eclipse.jdt.core.dom.SimpleName)5 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)5 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)5 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)4