Search in sources :

Example 1 with AST

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

the class GetterSetterUtil method getAssignedValue.

/**
	 * Converts an assignment, postfix expression or prefix expression into an assignable equivalent expression using the getter.
	 *
	 * @param node the assignment/prefix/postfix node
	 * @param astRewrite the astRewrite to use
	 * @param getterExpression the expression to insert for read accesses or <code>null</code> if such an expression does not exist
	 * @param variableType the type of the variable that the result will be assigned to
	 * @param is50OrHigher <code>true</code> if a 5.0 or higher environment can be used
	 * @return an expression that can be assigned to the type variableType with node being replaced by a equivalent expression using the getter
	 */
public static Expression getAssignedValue(ASTNode node, ASTRewrite astRewrite, Expression getterExpression, ITypeBinding variableType, boolean is50OrHigher) {
    InfixExpression.Operator op = null;
    AST ast = astRewrite.getAST();
    if (isNotInBlock(node))
        return null;
    if (node.getNodeType() == ASTNode.ASSIGNMENT) {
        Assignment assignment = ((Assignment) node);
        Expression rightHandSide = assignment.getRightHandSide();
        Expression copiedRightOp = (Expression) astRewrite.createCopyTarget(rightHandSide);
        if (assignment.getOperator() == Operator.ASSIGN) {
            ITypeBinding rightHandSideType = rightHandSide.resolveTypeBinding();
            copiedRightOp = createNarrowCastIfNessecary(copiedRightOp, rightHandSideType, ast, variableType, is50OrHigher);
            return copiedRightOp;
        }
        if (getterExpression != null) {
            InfixExpression infix = ast.newInfixExpression();
            infix.setLeftOperand(getterExpression);
            infix.setOperator(ASTNodes.convertToInfixOperator(assignment.getOperator()));
            ITypeBinding infixType = infix.resolveTypeBinding();
            if (NecessaryParenthesesChecker.needsParenthesesForRightOperand(rightHandSide, infix, variableType)) {
                ParenthesizedExpression p = ast.newParenthesizedExpression();
                p.setExpression(copiedRightOp);
                copiedRightOp = p;
            }
            infix.setRightOperand(copiedRightOp);
            return createNarrowCastIfNessecary(infix, infixType, ast, variableType, is50OrHigher);
        }
    } else if (node.getNodeType() == ASTNode.POSTFIX_EXPRESSION) {
        PostfixExpression po = (PostfixExpression) node;
        if (po.getOperator() == PostfixExpression.Operator.INCREMENT)
            op = InfixExpression.Operator.PLUS;
        if (po.getOperator() == PostfixExpression.Operator.DECREMENT)
            op = InfixExpression.Operator.MINUS;
    } else if (node.getNodeType() == ASTNode.PREFIX_EXPRESSION) {
        PrefixExpression pe = (PrefixExpression) node;
        if (pe.getOperator() == PrefixExpression.Operator.INCREMENT)
            op = InfixExpression.Operator.PLUS;
        if (pe.getOperator() == PrefixExpression.Operator.DECREMENT)
            op = InfixExpression.Operator.MINUS;
    }
    if (op != null && getterExpression != null) {
        return createInfixInvocationFromPostPrefixExpression(op, getterExpression, ast, variableType, is50OrHigher);
    }
    return null;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) AST(org.eclipse.jdt.core.dom.AST) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression)

Example 2 with AST

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

the class StubUtility2 method createConstructorStub.

public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, ITypeBinding typeBinding, IMethodBinding superConstructor, IVariableBinding[] variableBindings, int modifiers, CodeGenerationSettings settings) throws CoreException {
    AST ast = rewrite.getAST();
    MethodDeclaration decl = ast.newMethodDeclaration();
    decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
    decl.setName(ast.newSimpleName(typeBinding.getName()));
    decl.setConstructor(true);
    List<SingleVariableDeclaration> parameters = decl.parameters();
    if (superConstructor != null) {
        createTypeParameters(imports, context, ast, superConstructor, decl);
        createParameters(unit.getJavaProject(), imports, context, ast, superConstructor, null, decl);
        createThrownExceptions(decl, superConstructor, imports, context, ast);
    }
    Block body = ast.newBlock();
    decl.setBody(body);
    String delimiter = StubUtility.getLineDelimiterUsed(unit);
    if (superConstructor != null) {
        SuperConstructorInvocation invocation = ast.newSuperConstructorInvocation();
        SingleVariableDeclaration varDecl = null;
        for (Iterator<SingleVariableDeclaration> iterator = parameters.iterator(); iterator.hasNext(); ) {
            varDecl = iterator.next();
            invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
        }
        body.statements().add(invocation);
    }
    List<String> prohibited = new ArrayList<String>();
    for (final Iterator<SingleVariableDeclaration> iterator = parameters.iterator(); iterator.hasNext(); ) prohibited.add(iterator.next().getName().getIdentifier());
    String param = null;
    List<String> list = new ArrayList<String>(prohibited);
    String[] excluded = null;
    for (int i = 0; i < variableBindings.length; i++) {
        SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
        var.setType(imports.addImport(variableBindings[i].getType(), ast, context));
        excluded = new String[list.size()];
        list.toArray(excluded);
        param = suggestParameterName(unit, variableBindings[i], excluded);
        list.add(param);
        var.setName(ast.newSimpleName(param));
        parameters.add(var);
    }
    list = new ArrayList<String>(prohibited);
    for (int i = 0; i < variableBindings.length; i++) {
        excluded = new String[list.size()];
        list.toArray(excluded);
        final String paramName = suggestParameterName(unit, variableBindings[i], excluded);
        list.add(paramName);
        final String fieldName = variableBindings[i].getName();
        Expression expression = null;
        if (paramName.equals(fieldName) || settings.useKeywordThis) {
            FieldAccess access = ast.newFieldAccess();
            access.setExpression(ast.newThisExpression());
            access.setName(ast.newSimpleName(fieldName));
            expression = access;
        } else
            expression = ast.newSimpleName(fieldName);
        Assignment assignment = ast.newAssignment();
        assignment.setLeftHandSide(expression);
        assignment.setRightHandSide(ast.newSimpleName(paramName));
        assignment.setOperator(Assignment.Operator.ASSIGN);
        body.statements().add(ast.newExpressionStatement(assignment));
    }
    if (settings != null && settings.createComments) {
        String string = CodeGeneration.getMethodComment(unit, typeBinding.getName(), decl, superConstructor, delimiter);
        if (string != null) {
            Javadoc javadoc = (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
            decl.setJavadoc(javadoc);
        }
    }
    return decl;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ArrayList(java.util.ArrayList) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Assignment(org.eclipse.jdt.core.dom.Assignment) Expression(org.eclipse.jdt.core.dom.Expression) Block(org.eclipse.jdt.core.dom.Block) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess)

Example 3 with AST

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

the class ReturnTypeSubProcessor method addMissingReturnStatementProposals.

public static void addMissingReturnStatementProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
    if (selectedNode == null) {
        return;
    }
    ReturnStatement existingStatement = (selectedNode instanceof ReturnStatement) ? (ReturnStatement) selectedNode : null;
    // Lambda Expression can be in a MethodDeclaration or a Field Declaration
    if (selectedNode instanceof LambdaExpression) {
        MissingReturnTypeInLambdaCorrectionProposal proposal = new MissingReturnTypeInLambdaCorrectionProposal(cu, (LambdaExpression) selectedNode, existingStatement, IProposalRelevance.MISSING_RETURN_TYPE);
        proposals.add(proposal);
    } else {
        BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
        if (decl instanceof MethodDeclaration) {
            MethodDeclaration methodDecl = (MethodDeclaration) decl;
            Block block = methodDecl.getBody();
            if (block == null) {
                return;
            }
            proposals.add(new MissingReturnTypeCorrectionProposal(cu, methodDecl, existingStatement, IProposalRelevance.MISSING_RETURN_TYPE));
            Type returnType = methodDecl.getReturnType2();
            if (returnType != null && !"void".equals(ASTNodes.asString(returnType))) {
                //$NON-NLS-1$
                AST ast = methodDecl.getAST();
                ASTRewrite rewrite = ASTRewrite.create(ast);
                rewrite.replace(returnType, ast.newPrimitiveType(PrimitiveType.VOID), null);
                Javadoc javadoc = methodDecl.getJavadoc();
                if (javadoc != null) {
                    TagElement tagElement = JavadocTagsSubProcessor.findTag(javadoc, TagElement.TAG_RETURN, null);
                    if (tagElement != null) {
                        rewrite.remove(tagElement, null);
                    }
                }
                String label = CorrectionMessages.ReturnTypeSubProcessor_changetovoid_description;
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_RETURN_TYPE_TO_VOID, image);
                proposals.add(proposal);
            }
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) MissingReturnTypeInLambdaCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.MissingReturnTypeInLambdaCorrectionProposal) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) MissingReturnTypeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.MissingReturnTypeCorrectionProposal) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 4 with AST

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

the class ReturnTypeSubProcessor method addMissingReturnTypeProposals.

public static void addMissingReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
        ReturnStatementCollector eval = new ReturnStatementCollector();
        decl.accept(eval);
        AST ast = astRoot.getAST();
        ITypeBinding typeBinding = eval.getTypeBinding(decl.getAST());
        typeBinding = Bindings.normalizeTypeBinding(typeBinding);
        if (typeBinding == null) {
            //$NON-NLS-1$
            typeBinding = ast.resolveWellKnownType("void");
        }
        if (typeBinding.isWildcardType()) {
            typeBinding = ASTResolving.normalizeWildcardType(typeBinding, true, ast);
        }
        ASTRewrite rewrite = ASTRewrite.create(ast);
        String label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_missingreturntype_description, BindingLabelProvider.getBindingLabel(typeBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.MISSING_RETURN_TYPE, image);
        ImportRewrite imports = proposal.createImportRewrite(astRoot);
        ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
        Type type = imports.addImport(typeBinding, ast, importRewriteContext);
        rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, type, null);
        rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
        Javadoc javadoc = methodDeclaration.getJavadoc();
        if (javadoc != null && typeBinding != null) {
            TagElement newTag = ast.newTagElement();
            newTag.setTagName(TagElement.TAG_RETURN);
            TextElement commentStart = ast.newTextElement();
            newTag.fragments().add(commentStart);
            JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
            //$NON-NLS-1$
            proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
        }
        //$NON-NLS-1$
        String key = "return_type";
        proposal.addLinkedPosition(rewrite.track(type), true, key);
        if (typeBinding != null) {
            ITypeBinding[] bindings = ASTResolving.getRelaxingTypes(ast, typeBinding);
            for (int i = 0; i < bindings.length; i++) {
                proposal.addLinkedPositionProposal(key, bindings[i]);
            }
        }
        proposals.add(proposal);
        // change to constructor
        ASTNode parentType = ASTResolving.findParentType(decl);
        if (parentType instanceof AbstractTypeDeclaration) {
            boolean isInterface = parentType instanceof TypeDeclaration && ((TypeDeclaration) parentType).isInterface();
            if (!isInterface) {
                String constructorName = ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
                ASTNode nameNode = methodDeclaration.getName();
                label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_wrongconstructorname_description, BasicElementLabels.getJavaElementName(constructorName));
                proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, IProposalRelevance.CHANGE_TO_CONSTRUCTOR));
            }
        }
    }
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Image(org.eclipse.swt.graphics.Image) TextElement(org.eclipse.jdt.core.dom.TextElement) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) 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) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) ReplaceCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.ReplaceCorrectionProposal)

Example 5 with AST

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

the class SuppressWarningsSubProcessor method addUnknownSuppressWarningProposals.

/**
	 * Adds a proposal to correct the name of the SuppressWarning annotation
	 * @param context the context
	 * @param problem the problem
	 * @param proposals the resulting proposals
	 */
public static void addUnknownSuppressWarningProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ASTNode coveringNode = context.getCoveringNode();
    if (!(coveringNode instanceof StringLiteral))
        return;
    AST ast = coveringNode.getAST();
    StringLiteral literal = (StringLiteral) coveringNode;
    String literalValue = literal.getLiteralValue();
    String[] allWarningTokens = CorrectionEngine.getAllWarningTokens();
    for (int i = 0; i < allWarningTokens.length; i++) {
        String curr = allWarningTokens[i];
        if (NameMatcher.isSimilarName(literalValue, curr)) {
            StringLiteral newLiteral = ast.newStringLiteral();
            newLiteral.setLiteralValue(curr);
            ASTRewrite rewrite = ASTRewrite.create(ast);
            rewrite.replace(literal, newLiteral, null);
            String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_fix_suppress_token_label, new String[] { curr });
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.FIX_SUPPRESS_TOKEN, image);
            proposals.add(proposal);
        }
    }
    addRemoveUnusedSuppressWarningProposals(context, problem, proposals);
}
Also used : ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) AST(org.eclipse.jdt.core.dom.AST) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Image(org.eclipse.swt.graphics.Image)

Aggregations

AST (org.eclipse.jdt.core.dom.AST)149 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)78 Expression (org.eclipse.jdt.core.dom.Expression)65 ASTNode (org.eclipse.jdt.core.dom.ASTNode)64 Type (org.eclipse.jdt.core.dom.Type)49 SimpleName (org.eclipse.jdt.core.dom.SimpleName)45 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)43 Block (org.eclipse.jdt.core.dom.Block)41 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)38 CastExpression (org.eclipse.jdt.core.dom.CastExpression)37 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)37 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)37 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)35 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)34 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)34 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)33 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)31 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)29 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)29 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)29