Search in sources :

Example 11 with UnionType

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

the class QuickAssistProcessor method getTryWithResourceProposals.

public static boolean getTryWithResourceProposals(IInvocationContext context, ASTNode node, ArrayList<ASTNode> coveredNodes, Collection<ChangeCorrectionProposal> resultingCollections) throws IllegalArgumentException, CoreException {
    if (!JavaModelUtil.is1d8OrHigher(context.getCompilationUnit().getJavaProject())) {
        return false;
    }
    ASTNode parentStatement = ASTResolving.findAncestor(node, ASTNode.VARIABLE_DECLARATION_STATEMENT);
    if (!(parentStatement instanceof VariableDeclarationStatement) && !(parentStatement instanceof ExpressionStatement) && !(node instanceof SimpleName) && (coveredNodes == null || coveredNodes.isEmpty())) {
        return false;
    }
    List<ASTNode> coveredStatements = new ArrayList<>();
    if (coveredNodes == null || coveredNodes.isEmpty() && parentStatement != null) {
        coveredStatements.add(parentStatement);
    } else {
        for (ASTNode coveredNode : coveredNodes) {
            Statement statement = ASTResolving.findParentStatement(coveredNode);
            if (statement == null) {
                continue;
            }
            if (!coveredStatements.contains(statement)) {
                coveredStatements.add(statement);
            }
        }
    }
    List<ASTNode> coveredAutoClosableNodes = QuickAssistProcessorUtil.getCoveredAutoClosableNodes(coveredStatements);
    if (coveredAutoClosableNodes.isEmpty()) {
        return false;
    }
    ASTNode parentBodyDeclaration = (node instanceof Block || node instanceof BodyDeclaration) ? node : ASTNodes.getFirstAncestorOrNull(node, Block.class, BodyDeclaration.class);
    int start = coveredAutoClosableNodes.get(0).getStartPosition();
    int end = start;
    for (ASTNode astNode : coveredAutoClosableNodes) {
        int endPosition = QuickAssistProcessorUtil.findEndPostion(astNode);
        end = Math.max(end, endPosition);
    }
    // recursive loop to find all nodes affected by wrapping in try block
    List<ASTNode> nodesInRange = SurroundWithTryWithResourcesRefactoringCore.findNodesInRange(parentBodyDeclaration, start, end);
    int oldEnd = end;
    while (true) {
        int newEnd = oldEnd;
        for (ASTNode astNode : nodesInRange) {
            int endPosition = QuickAssistProcessorUtil.findEndPostion(astNode);
            newEnd = Math.max(newEnd, endPosition);
        }
        if (newEnd > oldEnd) {
            oldEnd = newEnd;
            nodesInRange = SurroundWithTryWithResourcesRefactoringCore.findNodesInRange(parentBodyDeclaration, start, newEnd);
            continue;
        }
        break;
    }
    nodesInRange.removeAll(coveredAutoClosableNodes);
    CompilationUnit cu = (CompilationUnit) node.getRoot();
    IBuffer buffer = context.getCompilationUnit().getBuffer();
    AST ast = node.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    boolean modifyExistingTry = false;
    TryStatement newTryStatement = null;
    Block newTryBody = null;
    TryStatement enclosingTry = (TryStatement) ASTResolving.findAncestor(node, ASTNode.TRY_STATEMENT);
    ListRewrite resourcesRewriter = null;
    ListRewrite clausesRewriter = null;
    if (enclosingTry == null || enclosingTry.getBody() == null || enclosingTry.getBody().statements().get(0) != coveredNodes.get(0)) {
        newTryStatement = ast.newTryStatement();
        newTryBody = ast.newBlock();
        newTryStatement.setBody(newTryBody);
    } else {
        modifyExistingTry = true;
        resourcesRewriter = rewrite.getListRewrite(enclosingTry, TryStatement.RESOURCES2_PROPERTY);
        clausesRewriter = rewrite.getListRewrite(enclosingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
    }
    ICompilationUnit icu = context.getCompilationUnit();
    ASTNode lastNode = nodesInRange.isEmpty() ? coveredAutoClosableNodes.get(coveredAutoClosableNodes.size() - 1) : nodesInRange.get(nodesInRange.size() - 1);
    Selection selection = Selection.createFromStartLength(start, lastNode.getStartPosition() - start + lastNode.getLength());
    SurroundWithTryWithResourcesAnalyzer analyzer = new SurroundWithTryWithResourcesAnalyzer(icu, selection);
    cu.accept(analyzer);
    ITypeBinding[] exceptions = analyzer.getExceptions(analyzer.getSelection());
    List<ITypeBinding> allExceptions = new ArrayList<>(Arrays.asList(exceptions));
    int resourceCount = 0;
    for (ASTNode coveredNode : coveredAutoClosableNodes) {
        ASTNode findAncestor = ASTResolving.findAncestor(coveredNode, ASTNode.VARIABLE_DECLARATION_STATEMENT);
        if (findAncestor == null) {
            findAncestor = ASTResolving.findAncestor(coveredNode, ASTNode.ASSIGNMENT);
        }
        if (findAncestor instanceof VariableDeclarationStatement) {
            VariableDeclarationStatement vds = (VariableDeclarationStatement) findAncestor;
            String commentToken = null;
            int extendedStatementStart = cu.getExtendedStartPosition(vds);
            if (vds.getStartPosition() > extendedStatementStart) {
                commentToken = buffer.getText(extendedStatementStart, vds.getStartPosition() - extendedStatementStart);
            }
            Type type = vds.getType();
            ITypeBinding typeBinding = type.resolveBinding();
            if (typeBinding != null) {
                IMethodBinding close = SurroundWithTryWithResourcesRefactoringCore.findAutocloseMethod(typeBinding);
                if (close != null) {
                    for (ITypeBinding exceptionType : close.getExceptionTypes()) {
                        if (!allExceptions.contains(exceptionType)) {
                            allExceptions.add(exceptionType);
                        }
                    }
                }
            }
            String typeName = buffer.getText(type.getStartPosition(), type.getLength());
            for (Object object : vds.fragments()) {
                VariableDeclarationFragment variableDeclarationFragment = (VariableDeclarationFragment) object;
                VariableDeclarationFragment newVariableDeclarationFragment = ast.newVariableDeclarationFragment();
                SimpleName name = variableDeclarationFragment.getName();
                if (commentToken == null) {
                    int extendedStart = cu.getExtendedStartPosition(variableDeclarationFragment);
                    commentToken = buffer.getText(extendedStart, variableDeclarationFragment.getStartPosition() - extendedStart);
                }
                commentToken = Strings.trimTrailingTabsAndSpaces(commentToken);
                newVariableDeclarationFragment.setName(ast.newSimpleName(name.getIdentifier()));
                Expression newExpression = null;
                Expression initializer = variableDeclarationFragment.getInitializer();
                if (initializer == null) {
                    rewrite.remove(coveredNode, null);
                    continue;
                } else {
                    newExpression = (Expression) rewrite.createMoveTarget(initializer);
                }
                newVariableDeclarationFragment.setInitializer(newExpression);
                VariableDeclarationExpression newVariableDeclarationExpression = ast.newVariableDeclarationExpression(newVariableDeclarationFragment);
                newVariableDeclarationExpression.setType((Type) rewrite.createStringPlaceholder(commentToken + typeName, type.getNodeType()));
                resourceCount++;
                if (modifyExistingTry) {
                    resourcesRewriter.insertLast(newVariableDeclarationExpression, null);
                } else {
                    newTryStatement.resources().add(newVariableDeclarationExpression);
                }
                commentToken = null;
            }
        }
    }
    if (resourceCount == 0) {
        return false;
    }
    String label = CorrectionMessages.QuickAssistProcessor_convert_to_try_with_resource;
    LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.SURROUND_WITH_TRY_CATCH);
    ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
    CatchClause catchClause = ast.newCatchClause();
    SingleVariableDeclaration decl = ast.newSingleVariableDeclaration();
    String varName = StubUtility.getExceptionVariableName(icu.getJavaProject());
    parentBodyDeclaration.getRoot().accept(analyzer);
    CodeScopeBuilder.Scope scope = CodeScopeBuilder.perform(analyzer.getEnclosingBodyDeclaration(), selection).findScope(selection.getOffset(), selection.getLength());
    scope.setCursor(selection.getOffset());
    String name = scope.createName(varName, false);
    decl.setName(ast.newSimpleName(name));
    List<ITypeBinding> mustRethrowList = new ArrayList<>();
    List<ITypeBinding> catchExceptions = analyzer.calculateCatchesAndRethrows(ASTNodes.filterSubtypes(allExceptions), mustRethrowList);
    List<ITypeBinding> filteredExceptions = ASTNodes.filterSubtypes(catchExceptions);
    if (catchExceptions.size() > 0) {
        // $NON-NLS-1$
        final String GROUP_EXC_NAME = "exc_name";
        // $NON-NLS-1$
        final String GROUP_EXC_TYPE = "exc_type";
        LinkedProposalModelCore linkedProposalModel = new LinkedProposalModelCore();
        int i = 0;
        if (!modifyExistingTry) {
            for (ITypeBinding mustThrow : mustRethrowList) {
                CatchClause newClause = ast.newCatchClause();
                SingleVariableDeclaration newDecl = ast.newSingleVariableDeclaration();
                newDecl.setName(ast.newSimpleName(name));
                Type importType = imports.addImport(mustThrow, ast, importRewriteContext, TypeLocation.EXCEPTION);
                newDecl.setType(importType);
                newClause.setException(newDecl);
                ThrowStatement newThrowStatement = ast.newThrowStatement();
                newThrowStatement.setExpression(ast.newSimpleName(name));
                linkedProposalModel.getPositionGroup(GROUP_EXC_NAME + i, true).addPosition(rewrite.track(decl.getName()), false);
                newClause.getBody().statements().add(newThrowStatement);
                newTryStatement.catchClauses().add(newClause);
                ++i;
            }
        }
        UnionType unionType = ast.newUnionType();
        List<Type> types = unionType.types();
        for (ITypeBinding exception : filteredExceptions) {
            Type type = imports.addImport(exception, ast, importRewriteContext, TypeLocation.EXCEPTION);
            types.add(type);
            linkedProposalModel.getPositionGroup(GROUP_EXC_TYPE + i, true).addPosition(rewrite.track(type), i == 0);
            i++;
        }
        decl.setType(unionType);
        catchClause.setException(decl);
        linkedProposalModel.getPositionGroup(GROUP_EXC_NAME + 0, true).addPosition(rewrite.track(decl.getName()), false);
        Statement st = null;
        // $NON-NLS-1$
        String s = StubUtility.getCatchBodyContent(icu, "Exception", name, coveredNodes.isEmpty() ? node : coveredNodes.get(0), icu.findRecommendedLineSeparator());
        if (s != null) {
            st = (Statement) rewrite.createStringPlaceholder(s, ASTNode.RETURN_STATEMENT);
        }
        if (st != null) {
            catchClause.getBody().statements().add(st);
        }
        if (modifyExistingTry) {
            clausesRewriter.insertLast(catchClause, null);
        } else {
            newTryStatement.catchClauses().add(catchClause);
        }
    }
    if (modifyExistingTry) {
        for (int i = 0; i < coveredAutoClosableNodes.size(); i++) {
            rewrite.remove(coveredAutoClosableNodes.get(i), null);
        }
    } else {
        if (!nodesInRange.isEmpty()) {
            ASTNode firstNode = nodesInRange.get(0);
            ASTNode methodDeclaration = ASTResolving.findAncestor(firstNode, ASTNode.BLOCK);
            ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, Block.STATEMENTS_PROPERTY);
            ASTNode createCopyTarget = listRewrite.createMoveTarget(firstNode, nodesInRange.get(nodesInRange.size() - 1));
            rewrite.getListRewrite(newTryBody, Block.STATEMENTS_PROPERTY).insertFirst(createCopyTarget, null);
        }
        // replace first node and delete the rest of selected nodes
        rewrite.replace(coveredAutoClosableNodes.get(0), newTryStatement, null);
        for (int i = 1; i < coveredAutoClosableNodes.size(); i++) {
            rewrite.remove(coveredAutoClosableNodes.get(i), null);
        }
    }
    resultingCollections.add(proposal);
    return true;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) UnionType(org.eclipse.jdt.core.dom.UnionType) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Selection(org.eclipse.jdt.internal.corext.dom.Selection) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) SurroundWithTryWithResourcesAnalyzer(org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryWithResourcesAnalyzer) IBuffer(org.eclipse.jdt.core.IBuffer) 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) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ThrowStatement(org.eclipse.jdt.core.dom.ThrowStatement) CodeScopeBuilder(org.eclipse.jdt.internal.corext.dom.CodeScopeBuilder) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) ThrowStatement(org.eclipse.jdt.core.dom.ThrowStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) CatchClause(org.eclipse.jdt.core.dom.CatchClause) UnionType(org.eclipse.jdt.core.dom.UnionType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) LinkedProposalModelCore(org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) SwitchExpression(org.eclipse.jdt.core.dom.SwitchExpression) LinkedCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 12 with UnionType

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

the class ASTNodeFactory method newType.

/**
	 * Returns the new type node corresponding to the type of the given declaration
	 * including the extra dimensions. If the type is a {@link UnionType}, use the LUB type.
	 * If the <code>importRewrite</code> is <code>null</code>, the type may be fully-qualified.
	 * 
	 * @param ast The AST to create the resulting type with.
	 * @param declaration The variable declaration to get the type from
	 * @param importRewrite the import rewrite to use, or <code>null</code>
	 * @param context the import rewrite context, or <code>null</code>
	 * @return a new type node created with the given AST.
	 * 
	 * @since 3.7.1
	 */
public static Type newType(AST ast, VariableDeclaration declaration, ImportRewrite importRewrite, ImportRewriteContext context) {
    if (declaration instanceof VariableDeclarationFragment && declaration.getParent() instanceof LambdaExpression) {
        return newType((LambdaExpression) declaration.getParent(), (VariableDeclarationFragment) declaration, ast, importRewrite, context);
    }
    Type type = ASTNodes.getType(declaration);
    if (declaration instanceof SingleVariableDeclaration) {
        Type type2 = ((SingleVariableDeclaration) declaration).getType();
        if (type2 instanceof UnionType) {
            ITypeBinding typeBinding = type2.resolveBinding();
            if (typeBinding != null) {
                if (importRewrite != null) {
                    type = importRewrite.addImport(typeBinding, ast, context);
                    return type;
                } else {
                    String qualifiedName = typeBinding.getQualifiedName();
                    if (qualifiedName.length() > 0) {
                        type = ast.newSimpleType(ast.newName(qualifiedName));
                        return type;
                    }
                }
            }
            // XXX: fallback for intersection types or unresolved types: take first type of union
            type = (Type) ((UnionType) type2).types().get(0);
            return type;
        }
    }
    type = (Type) ASTNode.copySubtree(ast, type);
    List<Dimension> extraDimensions = declaration.extraDimensions();
    if (!extraDimensions.isEmpty()) {
        ArrayType arrayType;
        if (type instanceof ArrayType) {
            arrayType = (ArrayType) type;
        } else {
            arrayType = ast.newArrayType(type, 0);
            type = arrayType;
        }
        arrayType.dimensions().addAll(ASTNode.copySubtrees(ast, extraDimensions));
    }
    return type;
}
Also used : ArrayType(org.eclipse.jdt.core.dom.ArrayType) UnionType(org.eclipse.jdt.core.dom.UnionType) Type(org.eclipse.jdt.core.dom.Type) UnionType(org.eclipse.jdt.core.dom.UnionType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) Dimension(org.eclipse.jdt.core.dom.Dimension) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 13 with UnionType

use of org.eclipse.jdt.core.dom.UnionType in project che 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<Statement>(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);
            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);
            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<ExpressionStatement>();
                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) {
        if (expressionStatement != null) {
            statements.insertLast(expressionStatement, null);
        } else {
            if (!selectedNodeRemoved)
                statements.insertLast(fRewriter.createMoveTarget(fSelectedNodes[0]), null);
        }
        fRewriter.replace(fSelectedNodes[0], 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 : 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.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.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement)

Example 14 with UnionType

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

the class UseMultiCatchRefactoring method unionTypes.

private UnionType unionTypes(Type... types) {
    final List<Type> allTypes = new ArrayList<Type>();
    collectAllUnionedTypes(allTypes, Arrays.asList(types));
    removeSupersededAlternatives(allTypes);
    final ASTBuilder b = this.ctx.getASTBuilder();
    final UnionType result = this.ctx.getAST().newUnionType();
    final List<Type> unionedTypes = types(result);
    for (Type unionedType : allTypes) {
        unionedTypes.add(b.copy(unionedType));
    }
    return result;
}
Also used : UnionType(org.eclipse.jdt.core.dom.UnionType) Type(org.eclipse.jdt.core.dom.Type) UnionType(org.eclipse.jdt.core.dom.UnionType) ArrayList(java.util.ArrayList) ASTBuilder(org.autorefactor.refactoring.ASTBuilder)

Example 15 with UnionType

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

the class UseMultiCatchRefactoring method resolveBinding.

private Binding resolveBinding(CatchClause catchClause) {
    SingleVariableDeclaration svd = catchClause.getException();
    Type type = svd.getType();
    switch(type.getNodeType()) {
        case SIMPLE_TYPE:
            return new SingleBinding(type.resolveBinding());
        case UNION_TYPE:
            List<Type> types = types((UnionType) type);
            ITypeBinding[] typeBindings = new ITypeBinding[types.size()];
            for (int j = 0; j < types.size(); j++) {
                typeBindings[j] = types.get(j).resolveBinding();
            }
            return new MultiBinding(typeBindings);
        default:
            // TODO JNR throw
            return null;
    }
}
Also used : Type(org.eclipse.jdt.core.dom.Type) UnionType(org.eclipse.jdt.core.dom.UnionType) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding)

Aggregations

UnionType (org.eclipse.jdt.core.dom.UnionType)21 Type (org.eclipse.jdt.core.dom.Type)20 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)11 ArrayType (org.eclipse.jdt.core.dom.ArrayType)10 ParameterizedType (org.eclipse.jdt.core.dom.ParameterizedType)10 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)10 CatchClause (org.eclipse.jdt.core.dom.CatchClause)9 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)9 AST (org.eclipse.jdt.core.dom.AST)8 ASTNode (org.eclipse.jdt.core.dom.ASTNode)8 ArrayList (java.util.ArrayList)7 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)7 NameQualifiedType (org.eclipse.jdt.core.dom.NameQualifiedType)7 SimpleType (org.eclipse.jdt.core.dom.SimpleType)7 Statement (org.eclipse.jdt.core.dom.Statement)7 TryStatement (org.eclipse.jdt.core.dom.TryStatement)7 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)7 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)6 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)6 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)5