Search in sources :

Example 16 with ReturnStatement

use of org.eclipse.jdt.core.dom.ReturnStatement in project flux 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);
        proposals.add(proposal);
    }
    if (!hasNoBody && id == IProblem.BodyForAbstractMethod) {
        AST ast = decl.getAST();
        {
            ASTRewrite rewrite = ASTRewrite.create(ast);
            rewrite.remove(decl.getBody(), null);
            int excluded;
            if (parentTypeDecl.isInterface()) {
                excluded = ~(Modifier.PUBLIC | Modifier.ABSTRACT);
            } else {
                excluded = ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.ABSTRACT);
            }
            ModifierRewrite.create(rewrite, decl).setModifiers(0, excluded, 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);
            proposals.add(proposal);
        }
        if (JavaModelUtil.is18OrHigher(cu.getJavaProject()) && parentTypeDecl.isInterface()) {
            {
                // insert proposal to add static modifier
                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));
            }
            {
                // insert proposal to add default modifier
                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));
            }
        }
    }
    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) 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)

Example 17 with ReturnStatement

use of org.eclipse.jdt.core.dom.ReturnStatement in project flux by eclipse.

the class AdvancedQuickAssistProcessor method createReturnExpression.

private static ReturnStatement createReturnExpression(ASTRewrite rewrite, Expression expression) {
    AST ast = rewrite.getAST();
    ReturnStatement thenReturn = ast.newReturnStatement();
    thenReturn.setExpression((Expression) rewrite.createCopyTarget(expression));
    return thenReturn;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement)

Example 18 with ReturnStatement

use of org.eclipse.jdt.core.dom.ReturnStatement in project flux by eclipse.

the class AdvancedQuickAssistProcessor method getConvertToIfReturnProposals.

private static boolean getConvertToIfReturnProposals(IInvocationContext context, ASTNode coveringNode, ArrayList<ICommandAccess> resultingCollections) {
    if (!(coveringNode instanceof IfStatement)) {
        return false;
    }
    IfStatement ifStatement = (IfStatement) coveringNode;
    if (ifStatement.getElseStatement() != null) {
        return false;
    }
    // enclosing lambda or method should return 'void'
    LambdaExpression enclosingLambda = ASTResolving.findEnclosingLambdaExpression(ifStatement);
    if (enclosingLambda != null) {
        IMethodBinding lambdaMethodBinding = enclosingLambda.resolveMethodBinding();
        if (lambdaMethodBinding == null) {
            return false;
        }
        if (!(ifStatement.getAST().resolveWellKnownType("void").equals(lambdaMethodBinding.getReturnType()))) {
            //$NON-NLS-1$
            return false;
        }
    } else {
        MethodDeclaration coveringMethod = ASTResolving.findParentMethodDeclaration(ifStatement);
        if (coveringMethod == null) {
            return false;
        }
        Type returnType = coveringMethod.getReturnType2();
        if (!isVoid(returnType)) {
            return false;
        }
    }
    // should be present in a block
    if (!(ifStatement.getParent() instanceof Block)) {
        return false;
    }
    // should have at least one statement in 'then' part other than 'return'
    Statement thenStatement = ifStatement.getThenStatement();
    if (thenStatement instanceof ReturnStatement) {
        return false;
    }
    if (thenStatement instanceof Block) {
        List<Statement> thenStatements = ((Block) thenStatement).statements();
        if (thenStatements.isEmpty() || (thenStatements.size() == 1 && (thenStatements.get(0) instanceof ReturnStatement))) {
            return false;
        }
    }
    // should have no further executable statement
    if (!isLastStatementInEnclosingMethodOrLambda(ifStatement)) {
        return false;
    }
    //  we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    AST ast = coveringNode.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    // create inverted 'if' statement
    Expression inversedExpression = getInversedExpression(rewrite, ifStatement.getExpression());
    IfStatement newIf = ast.newIfStatement();
    newIf.setExpression(inversedExpression);
    newIf.setThenStatement(ast.newReturnStatement());
    ListRewrite listRewriter = rewrite.getListRewrite(ifStatement.getParent(), (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
    listRewriter.replace(ifStatement, newIf, null);
    // remove last 'return' in 'then' block
    ArrayList<Statement> statements = getUnwrappedStatements(ifStatement.getThenStatement());
    Statement lastStatement = statements.get(statements.size() - 1);
    if (lastStatement instanceof ReturnStatement) {
        statements.remove(lastStatement);
    }
    // add statements from 'then' to the end of block
    for (Statement statement : statements) {
        listRewriter.insertLast(rewrite.createMoveTarget(statement), null);
    }
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_convertToIfReturn;
    //		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_IF_RETURN);
    resultingCollections.add(proposal);
    return true;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) AssertStatement(org.eclipse.jdt.core.dom.AssertStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) IfStatement(org.eclipse.jdt.core.dom.IfStatement) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 19 with ReturnStatement

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

the class SelfEncapsulateFieldRefactoring method createSetterMethod.

private MethodDeclaration createSetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
    FieldDeclaration field = (FieldDeclaration) ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
    Type type = field.getType();
    MethodDeclaration result = ast.newMethodDeclaration();
    result.setName(ast.newSimpleName(fSetterName));
    result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
    if (fSetterMustReturnValue) {
        result.setReturnType2((Type) rewriter.createCopyTarget(type));
    }
    SingleVariableDeclaration param = ast.newSingleVariableDeclaration();
    result.parameters().add(param);
    param.setName(ast.newSimpleName(fArgName));
    param.setType((Type) rewriter.createCopyTarget(type));
    List<Dimension> extraDimensions = DimensionRewrite.copyDimensions(fFieldDeclaration.extraDimensions(), rewriter);
    param.extraDimensions().addAll(extraDimensions);
    Block block = ast.newBlock();
    result.setBody(block);
    String fieldAccess = createFieldAccess();
    String body = CodeGeneration.getSetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fSetterName, fieldAccess, fArgName, lineDelimiter);
    if (body != null) {
        ASTNode setterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
        block.statements().add(setterNode);
    } else {
        Assignment ass = ast.newAssignment();
        ass.setLeftHandSide((Expression) rewriter.createStringPlaceholder(fieldAccess, ASTNode.QUALIFIED_NAME));
        ass.setRightHandSide(ast.newSimpleName(fArgName));
        block.statements().add(ass);
    }
    if (fSetterMustReturnValue) {
        ReturnStatement rs = ast.newReturnStatement();
        rs.setExpression(ast.newSimpleName(fArgName));
        block.statements().add(rs);
    }
    if (fGenerateJavadoc) {
        String string = CodeGeneration.getSetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fSetterName, fField.getElementName(), ASTNodes.asString(type), fArgName, StubUtility.getBaseName(fField), lineDelimiter);
        if (string != null) {
            Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
            result.setJavadoc(javadoc);
        }
    }
    return result;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) IType(org.eclipse.jdt.core.IType) Type(org.eclipse.jdt.core.dom.Type) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Dimension(org.eclipse.jdt.core.dom.Dimension) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Example 20 with ReturnStatement

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

the class IntroduceFactoryRefactoring method createFactoryMethod.

/**
	 * Creates and returns a new MethodDeclaration that represents the factory method to be used in
	 * place of direct calls to the constructor in question.
	 * 
	 * @param ast An AST used as a factory for various AST nodes
	 * @param ctorBinding binding for the constructor being wrapped
	 * @param unitRewriter the ASTRewrite to be used
	 * @return the new method declaration
	 * @throws CoreException if an exception occurs while accessing its corresponding resource
	 */
private MethodDeclaration createFactoryMethod(AST ast, IMethodBinding ctorBinding, ASTRewrite unitRewriter) throws CoreException {
    MethodDeclaration newMethod = ast.newMethodDeclaration();
    SimpleName newMethodName = ast.newSimpleName(fNewMethodName);
    ClassInstanceCreation newCtorCall = ast.newClassInstanceCreation();
    ReturnStatement ret = ast.newReturnStatement();
    Block body = ast.newBlock();
    List<Statement> stmts = body.statements();
    String retTypeName = ctorBinding.getName();
    createFactoryMethodSignature(ast, newMethod);
    newMethod.setName(newMethodName);
    newMethod.setBody(body);
    ITypeBinding declaringClass = fCtorBinding.getDeclaringClass();
    ITypeBinding[] ctorOwnerTypeParameters = declaringClass.getTypeParameters();
    setMethodReturnType(newMethod, retTypeName, ctorOwnerTypeParameters, ast);
    newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.STATIC | Modifier.PUBLIC));
    setCtorTypeArguments(newCtorCall, retTypeName, ctorOwnerTypeParameters, ast);
    createFactoryMethodConstructorArgs(ast, newCtorCall);
    if (Modifier.isAbstract(declaringClass.getModifiers())) {
        AnonymousClassDeclaration decl = ast.newAnonymousClassDeclaration();
        IMethodBinding[] unimplementedMethods = getUnimplementedMethods(declaringClass);
        CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fCUHandle.getJavaProject());
        ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fFactoryCU, decl.getStartPosition(), fImportRewriter);
        for (int i = 0; i < unimplementedMethods.length; i++) {
            IMethodBinding unImplementedMethod = unimplementedMethods[i];
            MethodDeclaration newMethodDecl = StubUtility2.createImplementationStub(fCUHandle, unitRewriter, fImportRewriter, context, unImplementedMethod, unImplementedMethod.getDeclaringClass().getName(), settings, false);
            decl.bodyDeclarations().add(newMethodDecl);
        }
        newCtorCall.setAnonymousClassDeclaration(decl);
    }
    ret.setExpression(newCtorCall);
    stmts.add(ret);
    return newMethod;
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block)

Aggregations

ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)34 Block (org.eclipse.jdt.core.dom.Block)24 AST (org.eclipse.jdt.core.dom.AST)23 Expression (org.eclipse.jdt.core.dom.Expression)22 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)21 ASTNode (org.eclipse.jdt.core.dom.ASTNode)20 Type (org.eclipse.jdt.core.dom.Type)19 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)18 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)14 Statement (org.eclipse.jdt.core.dom.Statement)12 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)11 SimpleName (org.eclipse.jdt.core.dom.SimpleName)11 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)11 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)10 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)9 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)9 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)9 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)8 DoStatement (org.eclipse.jdt.core.dom.DoStatement)8 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)8