Search in sources :

Example 1 with TryStatement

use of org.eclipse.jdt.core.dom.TryStatement in project AutoRefactor by JnRouvignac.

the class CleanCodeRatherThanSemicolonRefactoring method visit.

@Override
public boolean visit(EmptyStatement node) {
    ASTNode parent = node.getParent();
    if (parent instanceof Block) {
        this.ctx.getRefactorings().remove(node);
        return DO_NOT_VISIT_SUBTREE;
    }
    parent = getParentIgnoring(node, Block.class);
    if (parent instanceof IfStatement) {
        IfStatement is = (IfStatement) parent;
        List<Statement> thenStmts = asList(is.getThenStatement());
        List<Statement> elseStmts = asList(is.getElseStatement());
        boolean thenIsEmptyStmt = thenStmts.size() == 1 && is(thenStmts.get(0), EmptyStatement.class);
        boolean elseIsEmptyStmt = elseStmts.size() == 1 && is(elseStmts.get(0), EmptyStatement.class);
        if (thenIsEmptyStmt && elseIsEmptyStmt) {
            this.ctx.getRefactorings().remove(parent);
            return DO_NOT_VISIT_SUBTREE;
        } else if (thenIsEmptyStmt && is.getElseStatement() == null) {
            this.ctx.getRefactorings().remove(is);
            return DO_NOT_VISIT_SUBTREE;
        } else if (elseIsEmptyStmt) {
            this.ctx.getRefactorings().remove(is.getElseStatement());
            return DO_NOT_VISIT_SUBTREE;
        }
    } else if (parent instanceof TryStatement) {
        TryStatement ts = (TryStatement) parent;
        return maybeRemoveEmptyStmtBody(node, ts, ts.getBody());
    } else if (parent instanceof EnhancedForStatement) {
        EnhancedForStatement efs = (EnhancedForStatement) parent;
        return maybeRemoveEmptyStmtBody(node, efs, efs.getBody());
    } else if (parent instanceof ForStatement) {
        ForStatement fs = (ForStatement) parent;
        return maybeRemoveEmptyStmtBody(node, fs, fs.getBody());
    } else if (parent instanceof WhileStatement) {
        WhileStatement ws = (WhileStatement) parent;
        return maybeRemoveEmptyStmtBody(node, ws, ws.getBody());
    }
    return VISIT_SUBTREE;
}
Also used : IfStatement(org.eclipse.jdt.core.dom.IfStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) Block(org.eclipse.jdt.core.dom.Block) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement)

Example 2 with TryStatement

use of org.eclipse.jdt.core.dom.TryStatement in project AutoRefactor by JnRouvignac.

the class HotSpotIntrinsicedAPIsRefactoring method replaceWithSystemArrayCopy.

private boolean replaceWithSystemArrayCopy(ForStatement node, Expression srcArrayExpr, Expression srcPos, Expression destArrayExpr, Expression destPos, Expression length) {
    final ASTBuilder b = this.ctx.getASTBuilder();
    final TryStatement tryS = b.try0(b.block(b.toStmt(b.invoke("System", "arraycopy", srcArrayExpr, srcPos, destArrayExpr, destPos, length))), b.catch0("IndexOutOfBoundsException", "e", b.throw0(b.new0("ArrayIndexOutOfBoundsException", b.invoke("e", "getMessage")))));
    this.ctx.getRefactorings().replace(node, tryS);
    return DO_NOT_VISIT_SUBTREE;
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement) ASTBuilder(org.autorefactor.refactoring.ASTBuilder)

Example 3 with TryStatement

use of org.eclipse.jdt.core.dom.TryStatement 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 4 with TryStatement

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

the class QuickAssistProcessor method removeCatchBlock.

private static void removeCatchBlock(ASTRewrite rewrite, CatchClause catchClause) {
    TryStatement tryStatement = (TryStatement) catchClause.getParent();
    if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null || !tryStatement.resources().isEmpty()) {
        rewrite.remove(catchClause, null);
    } else {
        Block block = tryStatement.getBody();
        List<Statement> statements = block.statements();
        int nStatements = statements.size();
        if (nStatements == 1) {
            ASTNode first = statements.get(0);
            rewrite.replace(tryStatement, rewrite.createCopyTarget(first), null);
        } else if (nStatements > 1) {
            ListRewrite listRewrite = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
            ASTNode first = statements.get(0);
            ASTNode last = statements.get(statements.size() - 1);
            ASTNode newStatement = listRewrite.createCopyTarget(first, last);
            if (ASTNodes.isControlStatementBody(tryStatement.getLocationInParent())) {
                Block newBlock = rewrite.getAST().newBlock();
                newBlock.statements().add(newStatement);
                newStatement = newBlock;
            }
            rewrite.replace(tryStatement, newStatement, null);
        } else {
            rewrite.remove(tryStatement, null);
        }
    }
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite)

Example 5 with TryStatement

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

the class CompilationUnitBuilder method newAcceptMethod.

public MethodDeclaration newAcceptMethod(String visitorInterfaceName) {
    MethodDeclaration method = ast.newMethodDeclaration();
    method.setConstructor(false);
    method.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    method.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
    method.setName(ast.newSimpleName("accept"));
    method.parameters().add(newSingleVariableDeclaration(visitorInterfaceName, "visitor"));
    if (!isInterface) {
        Block body = newBlock();
        TryStatement tryStm = newTryStatement();
        MethodInvocation callExp = ast.newMethodInvocation();
        callExp.setExpression(ast.newSimpleName("visitor"));
        callExp.setName(ast.newSimpleName("visit"));
        callExp.arguments().add(ast.newThisExpression());
        tryStm.getBody().statements().add(newExpressionStatement(callExp));
        callExp = ast.newMethodInvocation();
        callExp.setExpression(newSimpleName(IWholeRuntimeException.class.getName()));
        callExp.setName(ast.newSimpleName("asWholeException"));
        callExp.arguments().add(newSimpleName("e"));
        callExp.arguments().add(ast.newThisExpression());
        callExp.arguments().add(newMethodInvocation(ast.newSimpleName("visitor"), "getBindings"));
        tryStm.catchClauses().add(newCatchClause(newSingleVariableDeclaration("Exception", "e"), newThrowStatement(callExp)));
        body.statements().add(tryStm);
        method.setBody(body);
    }
    return method;
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Block(org.eclipse.jdt.core.dom.Block) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation)

Aggregations

TryStatement (org.eclipse.jdt.core.dom.TryStatement)25 Statement (org.eclipse.jdt.core.dom.Statement)12 CatchClause (org.eclipse.jdt.core.dom.CatchClause)11 ASTNode (org.eclipse.jdt.core.dom.ASTNode)10 Block (org.eclipse.jdt.core.dom.Block)8 ArrayList (java.util.ArrayList)7 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)7 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)7 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)7 IfStatement (org.eclipse.jdt.core.dom.IfStatement)6 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)6 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)6 Type (org.eclipse.jdt.core.dom.Type)6 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)6 ForStatement (org.eclipse.jdt.core.dom.ForStatement)5 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)5 List (java.util.List)4 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)4 AST (org.eclipse.jdt.core.dom.AST)4 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)4