Search in sources :

Example 36 with Block

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

the class CallInliner method initializeInsertionPoint.

private void initializeInsertionPoint(int nos) {
    fInsertionIndex = -1;
    fNeedsStatement = false;
    // if we have a constructor invocation the invocation itself is already a statement
    ASTNode parentStatement = fInvocation instanceof Statement ? fInvocation : ASTNodes.getParent(fInvocation, Statement.class);
    if (parentStatement == null)
        return;
    ASTNode container = parentStatement.getParent();
    int type = container.getNodeType();
    if (type == ASTNode.BLOCK) {
        Block block = (Block) container;
        fListRewrite = fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
        fInsertionIndex = fListRewrite.getRewrittenList().indexOf(parentStatement);
    } else if (type == ASTNode.SWITCH_STATEMENT) {
        SwitchStatement switchStatement = (SwitchStatement) container;
        fListRewrite = fRewrite.getListRewrite(switchStatement, SwitchStatement.STATEMENTS_PROPERTY);
        fInsertionIndex = fListRewrite.getRewrittenList().indexOf(parentStatement);
    } else if (isControlStatement(container) || type == ASTNode.LABELED_STATEMENT) {
        fNeedsStatement = true;
        if (nos > 1 || needsBlockAroundDanglingIf()) {
            Block block = fInvocation.getAST().newBlock();
            fInsertionIndex = 0;
            Statement currentStatement = null;
            switch(type) {
                case ASTNode.LABELED_STATEMENT:
                    currentStatement = ((LabeledStatement) container).getBody();
                    break;
                case ASTNode.FOR_STATEMENT:
                    currentStatement = ((ForStatement) container).getBody();
                    break;
                case ASTNode.ENHANCED_FOR_STATEMENT:
                    currentStatement = ((EnhancedForStatement) container).getBody();
                    break;
                case ASTNode.WHILE_STATEMENT:
                    currentStatement = ((WhileStatement) container).getBody();
                    break;
                case ASTNode.DO_STATEMENT:
                    currentStatement = ((DoStatement) container).getBody();
                    break;
                case ASTNode.IF_STATEMENT:
                    IfStatement node = (IfStatement) container;
                    Statement thenPart = node.getThenStatement();
                    if (fTargetNode == thenPart || ASTNodes.isParent(fTargetNode, thenPart)) {
                        currentStatement = thenPart;
                    } else {
                        currentStatement = node.getElseStatement();
                    }
                    break;
            }
            Assert.isNotNull(currentStatement);
            fRewrite.replace(currentStatement, block, null);
            fListRewrite = fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
            // The method to be inlined is not the body of the control statement.
            if (currentStatement != fTargetNode) {
                fListRewrite.insertLast(fRewrite.createCopyTarget(currentStatement), null);
            } else {
                // We can't replace a copy with something else. So we
                // have to insert all statements to be inlined.
                fTargetNode = null;
            }
        }
    }
// We only insert one new statement or we delete the existing call.
// So there is no need to have an insertion index.
}
Also used : IfStatement(org.eclipse.jdt.core.dom.IfStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) 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) 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)

Example 37 with Block

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

the class CodeRefactoringUtil method checkMethodSyntaxErrors.

public static RefactoringStatus checkMethodSyntaxErrors(int selectionStart, int selectionLength, CompilationUnit cuNode, String invalidSelectionMessage) {
    SelectionAnalyzer analyzer = new SelectionAnalyzer(Selection.createFromStartLength(selectionStart, selectionLength), true);
    cuNode.accept(analyzer);
    ASTNode coveringNode = analyzer.getLastCoveringNode();
    if (!(coveringNode instanceof Block) || !(coveringNode.getParent() instanceof MethodDeclaration))
        return RefactoringStatus.createFatalErrorStatus(invalidSelectionMessage);
    if (ASTNodes.getMessages(coveringNode, ASTNodes.NODE_ONLY).length == 0)
        return RefactoringStatus.createFatalErrorStatus(invalidSelectionMessage);
    MethodDeclaration methodDecl = (MethodDeclaration) coveringNode.getParent();
    String message = Messages.format(RefactoringCoreMessages.CodeRefactoringUtil_error_message, BasicElementLabels.getJavaElementName(methodDecl.getName().getIdentifier()));
    return RefactoringStatus.createFatalErrorStatus(message);
}
Also used : SelectionAnalyzer(org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block)

Example 38 with Block

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

the class SurroundWithAnalyzer method endVisit.

@Override
public void endVisit(CompilationUnit node) {
    postProcessSelectedNodes(internalGetSelectedNodes());
    BodyDeclaration enclosingNode = null;
    superCall: {
        if (getStatus().hasFatalError())
            break superCall;
        if (!hasSelectedNodes()) {
            ASTNode coveringNode = getLastCoveringNode();
            if (coveringNode instanceof Block) {
                Block block = (Block) coveringNode;
                Message[] messages = ASTNodes.getMessages(block, ASTNodes.NODE_ONLY);
                if (messages.length > 0) {
                    invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_compile_errors, JavaStatusContext.create(getCompilationUnit(), block));
                    break superCall;
                }
            }
            invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_doesNotCover);
            break superCall;
        }
        enclosingNode = (BodyDeclaration) ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class);
        if (!(enclosingNode instanceof MethodDeclaration) && !(enclosingNode instanceof Initializer)) {
            invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_doesNotContain);
            break superCall;
        }
        if (!onlyStatements()) {
            invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_onlyStatements);
        }
        fLocals = LocalDeclarationAnalyzer.perform(enclosingNode, getSelection());
    }
    super.endVisit(node);
}
Also used : Message(org.eclipse.jdt.core.dom.Message) Initializer(org.eclipse.jdt.core.dom.Initializer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 39 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 40 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)

Aggregations

Block (org.eclipse.jdt.core.dom.Block)105 ASTNode (org.eclipse.jdt.core.dom.ASTNode)61 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)45 AST (org.eclipse.jdt.core.dom.AST)44 Statement (org.eclipse.jdt.core.dom.Statement)42 Expression (org.eclipse.jdt.core.dom.Expression)39 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)38 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)37 ForStatement (org.eclipse.jdt.core.dom.ForStatement)35 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)35 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)34 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)30 IfStatement (org.eclipse.jdt.core.dom.IfStatement)30 WhileStatement (org.eclipse.jdt.core.dom.WhileStatement)28 DoStatement (org.eclipse.jdt.core.dom.DoStatement)26 Type (org.eclipse.jdt.core.dom.Type)26 SimpleName (org.eclipse.jdt.core.dom.SimpleName)22 SwitchStatement (org.eclipse.jdt.core.dom.SwitchStatement)21 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)19 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)18