Search in sources :

Example 11 with Block

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

the class AssignToVariableAssistProposal method doAddLocal.

private ASTRewrite doAddLocal() {
    Expression expression = ((ExpressionStatement) fNodeToAssign).getExpression();
    AST ast = fNodeToAssign.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    createImportRewrite((CompilationUnit) fNodeToAssign.getRoot());
    String[] varNames = suggestLocalVariableNames(fTypeBinding, expression);
    for (int i = 0; i < varNames.length; i++) {
        addLinkedPositionProposal(KEY_NAME, varNames[i], null);
    }
    VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
    newDeclFrag.setName(ast.newSimpleName(varNames[0]));
    newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression));
    Type type = evaluateType(ast);
    if (ASTNodes.isControlStatementBody(fNodeToAssign.getLocationInParent())) {
        Block block = ast.newBlock();
        block.statements().add(rewrite.createMoveTarget(fNodeToAssign));
        rewrite.replace(fNodeToAssign, block, null);
    }
    if (needsSemicolon(expression)) {
        VariableDeclarationStatement varStatement = ast.newVariableDeclarationStatement(newDeclFrag);
        varStatement.setType(type);
        rewrite.replace(expression, varStatement, null);
    } else {
        // trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement
        VariableDeclarationExpression varExpression = ast.newVariableDeclarationExpression(newDeclFrag);
        varExpression.setType(type);
        rewrite.replace(expression, varExpression, null);
    }
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
    addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
    // set cursor after expression statement
    setEndPosition(rewrite.track(fNodeToAssign));
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) Type(org.eclipse.jdt.core.dom.Type) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement)

Example 12 with Block

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

the class ExtractMethodAnalyzer method visit.

@Override
public boolean visit(LambdaExpression node) {
    Selection selection = getSelection();
    int selectionStart = selection.getOffset();
    int selectionExclusiveEnd = selection.getExclusiveEnd();
    int lambdaStart = node.getStartPosition();
    int lambdaExclusiveEnd = lambdaStart + node.getLength();
    ASTNode body = node.getBody();
    int bodyStart = body.getStartPosition();
    int bodyExclusiveEnd = bodyStart + body.getLength();
    boolean isValidSelection = false;
    if ((body instanceof Block) && (bodyStart < selectionStart && selectionExclusiveEnd <= bodyExclusiveEnd)) {
        // if selection is inside lambda body's block
        isValidSelection = true;
    } else if (body instanceof Expression) {
        try {
            TokenScanner scanner = new TokenScanner(fCUnit);
            int arrowExclusiveEnd = scanner.getTokenEndOffset(ITerminalSymbols.TokenNameARROW, lambdaStart);
            if (selectionStart >= arrowExclusiveEnd) {
                isValidSelection = true;
            }
        } catch (CoreException e) {
        // ignore
        }
    }
    if (selectionStart <= lambdaStart && selectionExclusiveEnd >= lambdaExclusiveEnd) {
        // if selection covers the lambda node
        isValidSelection = true;
    }
    if (!isValidSelection) {
        return false;
    }
    return super.visit(node);
}
Also used : TokenScanner(org.eclipse.jdt.internal.corext.dom.TokenScanner) CoreException(org.eclipse.core.runtime.CoreException) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) Selection(org.eclipse.jdt.internal.corext.dom.Selection) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block)

Example 13 with Block

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

the class IntroduceIndirectionRefactoring method createIntermediaryMethod.

private void createIntermediaryMethod() throws CoreException {
    CompilationUnitRewrite imRewrite = getCachedCURewrite(fIntermediaryType.getCompilationUnit());
    AST ast = imRewrite.getAST();
    MethodDeclaration intermediary = ast.newMethodDeclaration();
    // Intermediary class is non-anonymous
    AbstractTypeDeclaration type = (AbstractTypeDeclaration) typeToDeclaration(fIntermediaryType, imRewrite.getRoot());
    // Name
    intermediary.setName(ast.newSimpleName(fIntermediaryMethodName));
    // Flags
    List<IExtendedModifier> modifiers = intermediary.modifiers();
    if (!fIntermediaryType.isInterface()) {
        modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    }
    modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
    // Parameters
    String targetParameterName = StubUtility.suggestArgumentName(getProject(), fIntermediaryFirstParameterType.getName(), fTargetMethod.getParameterNames());
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(type, imRewrite.getImportRewrite());
    if (!isStaticTarget()) {
        // Add first param
        SingleVariableDeclaration parameter = imRewrite.getAST().newSingleVariableDeclaration();
        Type t = imRewrite.getImportRewrite().addImport(fIntermediaryFirstParameterType, imRewrite.getAST(), context);
        if (fIntermediaryFirstParameterType.isGenericType()) {
            ParameterizedType parameterized = imRewrite.getAST().newParameterizedType(t);
            ITypeBinding[] typeParameters = fIntermediaryFirstParameterType.getTypeParameters();
            for (int i = 0; i < typeParameters.length; i++) parameterized.typeArguments().add(imRewrite.getImportRewrite().addImport(typeParameters[i], imRewrite.getAST()));
            t = parameterized;
        }
        parameter.setType(t);
        parameter.setName(imRewrite.getAST().newSimpleName(targetParameterName));
        intermediary.parameters().add(parameter);
    }
    // Add other params
    copyArguments(intermediary, imRewrite);
    // Add type parameters of declaring type (and enclosing types)
    if (!isStaticTarget() && fIntermediaryFirstParameterType.isGenericType())
        addTypeParameters(imRewrite, intermediary.typeParameters(), fIntermediaryFirstParameterType);
    // Add type params of method
    copyTypeParameters(intermediary, imRewrite);
    // Return type
    intermediary.setReturnType2(imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getReturnType(), ast, context));
    // Exceptions
    copyExceptions(intermediary, imRewrite);
    // Body
    MethodInvocation invocation = imRewrite.getAST().newMethodInvocation();
    invocation.setName(imRewrite.getAST().newSimpleName(fTargetMethod.getElementName()));
    if (isStaticTarget()) {
        Type importedType = imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getDeclaringClass(), ast, context);
        invocation.setExpression(ASTNodeFactory.newName(ast, ASTNodes.asString(importedType)));
    } else {
        invocation.setExpression(imRewrite.getAST().newSimpleName(targetParameterName));
    }
    copyInvocationParameters(invocation, ast);
    Statement call = encapsulateInvocation(intermediary, invocation);
    final Block body = imRewrite.getAST().newBlock();
    body.statements().add(call);
    intermediary.setBody(body);
    // method comment
    ICompilationUnit targetCU = imRewrite.getCu();
    if (StubUtility.doAddComments(targetCU.getJavaProject())) {
        String comment = CodeGeneration.getMethodComment(targetCU, getIntermediaryTypeName(), intermediary, null, StubUtility.getLineDelimiterUsed(targetCU));
        if (comment != null) {
            Javadoc javadoc = (Javadoc) imRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
            intermediary.setJavadoc(javadoc);
        }
    }
    // Add the completed method to the intermediary type:
    ChildListPropertyDescriptor typeBodyDeclarationsProperty = typeToBodyDeclarationProperty(fIntermediaryType, imRewrite.getRoot());
    ListRewrite bodyDeclarationsListRewrite = imRewrite.getASTRewrite().getListRewrite(type, typeBodyDeclarationsProperty);
    bodyDeclarationsListRewrite.insertAt(intermediary, ASTNodes.getInsertionIndex(intermediary, type.bodyDeclarations()), imRewrite.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_create_new_method));
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Javadoc(org.eclipse.jdt.core.dom.Javadoc) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IType(org.eclipse.jdt.core.IType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) Block(org.eclipse.jdt.core.dom.Block) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 14 with Block

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

the class ExtractMethodAnalyzer method computeLastStatementSelected.

private void computeLastStatementSelected() {
    ASTNode[] nodes = getSelectedNodes();
    if (nodes.length == 0) {
        fIsLastStatementSelected = false;
    } else {
        Block body = null;
        LambdaExpression enclosingLambdaExpr = ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
        if (enclosingLambdaExpr != null) {
            ASTNode lambdaBody = enclosingLambdaExpr.getBody();
            if (lambdaBody instanceof Block) {
                body = (Block) lambdaBody;
            } else {
                fIsLastStatementSelected = true;
                return;
            }
        } else {
            if (fEnclosingBodyDeclaration instanceof MethodDeclaration) {
                body = ((MethodDeclaration) fEnclosingBodyDeclaration).getBody();
            } else if (fEnclosingBodyDeclaration instanceof Initializer) {
                body = ((Initializer) fEnclosingBodyDeclaration).getBody();
            }
        }
        if (body != null) {
            List<Statement> statements = body.statements();
            if (statements.size() > 0) {
                fIsLastStatementSelected = nodes[nodes.length - 1] == statements.get(statements.size() - 1);
            } else {
                fIsLastStatementSelected = true;
            }
        }
    }
}
Also used : Initializer(org.eclipse.jdt.core.dom.Initializer) 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) TryStatement(org.eclipse.jdt.core.dom.TryStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 15 with Block

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

the class ExtractMethodAnalyzer method canHandleBranches.

private String canHandleBranches() {
    if (fReturnValue != null)
        return RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch;
    ASTNode[] selectedNodes = getSelectedNodes();
    final ASTNode lastSelectedNode = selectedNodes[selectedNodes.length - 1];
    Statement body = getParentLoopBody(lastSelectedNode.getParent());
    if (!(body instanceof Block))
        return RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch;
    if (body != lastSelectedNode) {
        Block block = (Block) body;
        List<Statement> statements = block.statements();
        ASTNode lastStatementInLoop = statements.get(statements.size() - 1);
        if (lastSelectedNode != lastStatementInLoop)
            return RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch;
    }
    final String[] continueMatchesLoopProblem = { null };
    for (int i = 0; i < selectedNodes.length; i++) {
        final ASTNode astNode = selectedNodes[i];
        astNode.accept(new ASTVisitor() {

            ArrayList<String> fLocalLoopLabels = new ArrayList<String>();

            @Override
            public boolean visit(BreakStatement node) {
                SimpleName label = node.getLabel();
                if (label != null && !fLocalLoopLabels.contains(label.getIdentifier())) {
                    continueMatchesLoopProblem[0] = Messages.format(RefactoringCoreMessages.ExtractMethodAnalyzer_branch_break_mismatch, //$NON-NLS-1$
                    new Object[] { ("break " + label.getIdentifier()) });
                }
                return false;
            }

            @Override
            public boolean visit(LabeledStatement node) {
                SimpleName label = node.getLabel();
                if (label != null)
                    fLocalLoopLabels.add(label.getIdentifier());
                return true;
            }

            @Override
            public void endVisit(ContinueStatement node) {
                SimpleName label = node.getLabel();
                if (label != null && !fLocalLoopLabels.contains(label.getIdentifier())) {
                    if (fEnclosingLoopLabel == null || !label.getIdentifier().equals(fEnclosingLoopLabel.getIdentifier())) {
                        continueMatchesLoopProblem[0] = Messages.format(RefactoringCoreMessages.ExtractMethodAnalyzer_branch_continue_mismatch, //$NON-NLS-1$
                        new Object[] { "continue " + label.getIdentifier() });
                    }
                }
            }
        });
    }
    return continueMatchesLoopProblem[0];
}
Also used : 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) TryStatement(org.eclipse.jdt.core.dom.TryStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement)

Aggregations

Block (org.eclipse.jdt.core.dom.Block)89 ASTNode (org.eclipse.jdt.core.dom.ASTNode)53 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)43 AST (org.eclipse.jdt.core.dom.AST)41 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)38 Statement (org.eclipse.jdt.core.dom.Statement)37 Expression (org.eclipse.jdt.core.dom.Expression)36 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)33 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)33 ForStatement (org.eclipse.jdt.core.dom.ForStatement)32 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)31 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)27 IfStatement (org.eclipse.jdt.core.dom.IfStatement)26 WhileStatement (org.eclipse.jdt.core.dom.WhileStatement)25 DoStatement (org.eclipse.jdt.core.dom.DoStatement)24 Type (org.eclipse.jdt.core.dom.Type)24 SimpleName (org.eclipse.jdt.core.dom.SimpleName)20 SwitchStatement (org.eclipse.jdt.core.dom.SwitchStatement)19 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)19 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)17