Search in sources :

Example 91 with FieldDeclaration

use of org.eclipse.jdt.core.dom.FieldDeclaration in project eclipse-cs by checkstyle.

the class RedundantModifierQuickfix method handleGetCorrectingASTVisitor.

/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo, final int markerStartOffset) {
    return new ASTVisitor() {

        @SuppressWarnings("unchecked")
        @Override
        public boolean visit(MethodDeclaration node) {
            if (containsPosition(node, markerStartOffset)) {
                List<ModifierKeyword> redundantKeyWords = Collections.emptyList();
                if (node.getParent() instanceof TypeDeclaration) {
                    TypeDeclaration type = (TypeDeclaration) node.getParent();
                    if (type.isInterface()) {
                        redundantKeyWords = Arrays.asList(new ModifierKeyword[] { ModifierKeyword.PUBLIC_KEYWORD, ModifierKeyword.ABSTRACT_KEYWORD, ModifierKeyword.FINAL_KEYWORD });
                    } else if (Modifier.isFinal(type.getModifiers())) {
                        redundantKeyWords = Arrays.asList(new ModifierKeyword[] { ModifierKeyword.FINAL_KEYWORD });
                    }
                }
                deleteRedundantModifiers(node.modifiers(), redundantKeyWords);
            }
            return true;
        }

        @SuppressWarnings("unchecked")
        @Override
        public boolean visit(FieldDeclaration node) {
            // recalculate start position because optional javadoc is mixed
            // into the original start position
            int pos = node.getStartPosition() + (node.getJavadoc() != null ? node.getJavadoc().getLength() + JAVADOC_COMMENT_LENGTH : 0);
            if (containsPosition(lineInfo, pos)) {
                List<ModifierKeyword> redundantKeyWords = Collections.emptyList();
                if (node.getParent() instanceof TypeDeclaration) {
                    TypeDeclaration type = (TypeDeclaration) node.getParent();
                    if (type.isInterface()) {
                        redundantKeyWords = Arrays.asList(new ModifierKeyword[] { ModifierKeyword.PUBLIC_KEYWORD, ModifierKeyword.ABSTRACT_KEYWORD, ModifierKeyword.FINAL_KEYWORD, ModifierKeyword.STATIC_KEYWORD });
                    }
                } else if (node.getParent() instanceof AnnotationTypeDeclaration) {
                    redundantKeyWords = Arrays.asList(new ModifierKeyword[] { ModifierKeyword.PUBLIC_KEYWORD, ModifierKeyword.ABSTRACT_KEYWORD, ModifierKeyword.FINAL_KEYWORD, ModifierKeyword.STATIC_KEYWORD });
                }
                deleteRedundantModifiers(node.modifiers(), redundantKeyWords);
            }
            return true;
        }

        @SuppressWarnings("unchecked")
        @Override
        public boolean visit(AnnotationTypeMemberDeclaration node) {
            // recalculate start position because optional javadoc is mixed
            // into the original start position
            int pos = node.getStartPosition() + (node.getJavadoc() != null ? node.getJavadoc().getLength() + JAVADOC_COMMENT_LENGTH : 0);
            if (containsPosition(lineInfo, pos)) {
                if (node.getParent() instanceof AnnotationTypeDeclaration) {
                    List<ModifierKeyword> redundantKeyWords = Arrays.asList(new ModifierKeyword[] { ModifierKeyword.PUBLIC_KEYWORD, ModifierKeyword.ABSTRACT_KEYWORD, ModifierKeyword.FINAL_KEYWORD, ModifierKeyword.STATIC_KEYWORD });
                    deleteRedundantModifiers(node.modifiers(), redundantKeyWords);
                }
            }
            return true;
        }

        private void deleteRedundantModifiers(List<ASTNode> modifiers, List<ModifierKeyword> redundantModifierKeywords) {
            Iterator<ASTNode> it = modifiers.iterator();
            while (it.hasNext()) {
                ASTNode node = it.next();
                if (node instanceof Modifier) {
                    Modifier modifier = (Modifier) node;
                    if (redundantModifierKeywords.contains(modifier.getKeyword())) {
                        it.remove();
                    }
                }
            }
        }
    };
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) ModifierKeyword(org.eclipse.jdt.core.dom.Modifier.ModifierKeyword) AnnotationTypeMemberDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) List(java.util.List) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) Modifier(org.eclipse.jdt.core.dom.Modifier)

Example 92 with FieldDeclaration

use of org.eclipse.jdt.core.dom.FieldDeclaration in project evosuite by EvoSuite.

the class JUnitCodeGenerator method after.

@SuppressWarnings("unchecked")
@Override
public void after(CaptureLog log) {
    if (this.isXStreamNeeded) {
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName(new String[] { "com", "thoughtworks", "xstream", "XStream" }));
        cu.imports().add(id);
        // create XSTREAM constant: private static final XStream XSTREAM = new XStream();
        final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
        vd.setName(ast.newSimpleName("XSTREAM"));
        final ClassInstanceCreation ci = ast.newClassInstanceCreation();
        ci.setType(this.createAstType("XStream", ast));
        vd.setInitializer(ci);
        final FieldDeclaration xstreamConst = ast.newFieldDeclaration(vd);
        xstreamConst.setType(this.createAstType("XStream", ast));
        xstreamConst.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
        xstreamConst.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
        xstreamConst.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));
        td.bodyDeclarations().add(xstreamConst);
        this.isXStreamNeeded = false;
    }
    // -- creates utility method to set field value via reflections
    if (this.isSetFieldMethodNeeded) {
        this.createSetFieldMethod(td, cu, ast);
        this.isSetFieldMethodNeeded = false;
    }
    // -- creates utility method to get field value via reflections
    if (this.isGetFieldMethodNeeded) {
        this.createGetFieldMethod(td, cu, ast);
        this.isGetFieldMethodNeeded = false;
    }
    // -- creates utility method to call method via reflections
    if (this.isCallMethodMethodNeeded) {
        this.createCallMethod(td, cu, ast);
        this.isCallMethodMethodNeeded = false;
    }
    // -- creates utility method to call constructor via reflections
    if (this.isNewInstanceMethodNeeded) {
        this.createNewInstanceMethod(td, cu, ast);
        this.isNewInstanceMethodNeeded = false;
    }
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Example 93 with FieldDeclaration

use of org.eclipse.jdt.core.dom.FieldDeclaration in project bndtools by bndtools.

the class AbstractBuildErrorDetailsHandler method createFieldMarkerData.

/**
 * Create a marker on a Java Method
 *
 * @param javaProject
 * @param className - the fully qualified class name (e.g java.lang.String)
 * @param methodName
 * @param methodSignature - signatures are in "internal form" e.g. (Ljava.lang.Integer;[Ljava/lang/String;Z)V
 * @param markerAttributes - attributes that should be included in the marker, typically a message. The start and
 *            end points for the marker are added by this method.
 * @param hasResolutions - true if the marker will have resolutions
 * @return Marker Data that can be used to create an {@link IMarker}, or null if no location can be found
 * @throws JavaModelException
 */
public static final MarkerData createFieldMarkerData(IJavaProject javaProject, final String className, final String fieldName, final Map<String, Object> markerAttributes, boolean hasResolutions) throws JavaModelException {
    final CompilationUnit ast = createAST(javaProject, className);
    if (ast == null)
        return null;
    ast.accept(new ASTVisitor() {

        @Override
        public boolean visit(FieldDeclaration fieldDecl) {
            if (matches(ast, fieldDecl, fieldName)) {
                // Create the marker attribs here
                markerAttributes.put(IMarker.CHAR_START, fieldDecl.getStartPosition());
                markerAttributes.put(IMarker.CHAR_END, fieldDecl.getStartPosition() + fieldDecl.getLength());
            }
            return false;
        }

        private boolean matches(@SuppressWarnings("unused") CompilationUnit ast, FieldDeclaration fieldDecl, String fieldName) {
            @SuppressWarnings("unchecked") List<VariableDeclarationFragment> list = (List<VariableDeclarationFragment>) fieldDecl.getStructuralProperty(FieldDeclaration.FRAGMENTS_PROPERTY);
            for (VariableDeclarationFragment vdf : list) {
                if (fieldName.equals(vdf.getName().toString())) {
                    return true;
                }
            }
            return false;
        }
    });
    if (!markerAttributes.containsKey(IMarker.CHAR_START))
        return null;
    return new MarkerData(ast.getJavaElement().getResource(), markerAttributes, hasResolutions);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) List(java.util.List) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 94 with FieldDeclaration

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

the class JavadocTagsSubProcessor method getMissingJavadocCommentProposals.

public static void getMissingJavadocCommentProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) throws CoreException {
    ASTNode node = problem.getCoveringNode(context.getASTRoot());
    if (node == null) {
        return;
    }
    BodyDeclaration declaration = ASTResolving.findParentBodyDeclaration(node);
    if (declaration == null) {
        return;
    }
    ICompilationUnit cu = context.getCompilationUnit();
    ITypeBinding binding = Bindings.getBindingOfParentType(declaration);
    if (binding == null) {
        return;
    }
    if (declaration instanceof MethodDeclaration) {
        MethodDeclaration methodDecl = (MethodDeclaration) declaration;
        IMethodBinding methodBinding = methodDecl.resolveBinding();
        IMethodBinding overridden = null;
        if (methodBinding != null) {
            overridden = Bindings.findOverriddenMethod(methodBinding, true);
        }
        String string = CodeGeneration.getMethodComment(cu, binding.getName(), methodDecl, overridden, String.valueOf('\n'));
        if (string != null) {
            String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_method_description;
            proposals.add(new AddJavadocCommentProposal(label, cu, IProposalRelevance.ADD_JAVADOC_METHOD, declaration.getStartPosition(), string));
        }
    } else if (declaration instanceof AbstractTypeDeclaration) {
        String typeQualifiedName = Bindings.getTypeQualifiedName(binding);
        String[] typeParamNames;
        if (declaration instanceof TypeDeclaration) {
            List<TypeParameter> typeParams = ((TypeDeclaration) declaration).typeParameters();
            typeParamNames = new String[typeParams.size()];
            for (int i = 0; i < typeParamNames.length; i++) {
                typeParamNames[i] = (typeParams.get(i)).getName().getIdentifier();
            }
        } else {
            typeParamNames = new String[0];
        }
        String string = CodeGeneration.getTypeComment(cu, typeQualifiedName, typeParamNames, String.valueOf('\n'));
        if (string != null) {
            String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_type_description;
            proposals.add(new AddJavadocCommentProposal(label, cu, IProposalRelevance.ADD_JAVADOC_TYPE, declaration.getStartPosition(), string));
        }
    } else if (declaration instanceof FieldDeclaration) {
        // $NON-NLS-1$
        String comment = "/**\n *\n */\n";
        List<VariableDeclarationFragment> fragments = ((FieldDeclaration) declaration).fragments();
        if (fragments != null && fragments.size() > 0) {
            VariableDeclaration decl = fragments.get(0);
            String fieldName = decl.getName().getIdentifier();
            String typeName = binding.getName();
            comment = CodeGeneration.getFieldComment(cu, typeName, fieldName, String.valueOf('\n'));
        }
        if (comment != null) {
            String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_field_description;
            proposals.add(new AddJavadocCommentProposal(label, cu, IProposalRelevance.ADD_JAVADOC_FIELD, declaration.getStartPosition(), comment));
        }
    } else if (declaration instanceof EnumConstantDeclaration) {
        EnumConstantDeclaration enumDecl = (EnumConstantDeclaration) declaration;
        String id = enumDecl.getName().getIdentifier();
        String comment = CodeGeneration.getFieldComment(cu, binding.getName(), id, String.valueOf('\n'));
        String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_enumconst_description;
        proposals.add(new AddJavadocCommentProposal(label, cu, IProposalRelevance.ADD_JAVADOC_ENUM, declaration.getStartPosition(), comment));
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) EnumConstantDeclaration(org.eclipse.jdt.core.dom.EnumConstantDeclaration) 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) List(java.util.List) ArrayList(java.util.ArrayList) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 95 with FieldDeclaration

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

the class NewVariableCorrectionProposal method doAddField.

private ASTRewrite doAddField(CompilationUnit astRoot) {
    SimpleName node = fOriginalNode;
    boolean isInDifferentCU = false;
    ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
    if (newTypeDecl == null) {
        astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
        isInDifferentCU = true;
    }
    ImportRewrite imports = createImportRewrite(astRoot);
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);
    if (newTypeDecl != null) {
        AST ast = newTypeDecl.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
        fragment.setName(ast.newSimpleName(node.getIdentifier()));
        Type type = evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding, TypeLocation.FIELD);
        FieldDeclaration newDecl = ast.newFieldDeclaration(fragment);
        newDecl.setType(type);
        newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));
        if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
            fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
        }
        ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
        List<BodyDeclaration> decls = ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);
        int maxOffset = isInDifferentCU ? -1 : node.getStartPosition();
        int insertIndex = findFieldInsertIndex(decls, newDecl, maxOffset);
        ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property);
        listRewriter.insertAt(newDecl, insertIndex, null);
        return rewrite;
    }
    return null;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Aggregations

FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)103 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)53 ASTNode (org.eclipse.jdt.core.dom.ASTNode)51 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)46 AST (org.eclipse.jdt.core.dom.AST)26 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)26 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)26 Type (org.eclipse.jdt.core.dom.Type)24 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)22 Block (org.eclipse.jdt.core.dom.Block)17 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)16 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)16 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)16 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)16 ArrayList (java.util.ArrayList)15 SimpleName (org.eclipse.jdt.core.dom.SimpleName)15 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)14 Expression (org.eclipse.jdt.core.dom.Expression)14 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)14 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)13