Search in sources :

Example 1 with LinkedProposalModelCore

use of org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore in project eclipse.jdt.ls by eclipse.

the class RefactorProcessor method getConvertAnonymousToNestedProposal.

public static RefactoringCorrectionProposal getConvertAnonymousToNestedProposal(CodeActionParams params, IInvocationContext context, final ASTNode node, boolean returnAsCommand) throws CoreException {
    String label = CorrectionMessages.QuickAssistProcessor_convert_anonym_to_nested;
    ClassInstanceCreation cic = getClassInstanceCreation(node);
    if (cic == null) {
        return null;
    }
    final AnonymousClassDeclaration anonymTypeDecl = cic.getAnonymousClassDeclaration();
    if (anonymTypeDecl == null || anonymTypeDecl.resolveBinding() == null) {
        return null;
    }
    final ConvertAnonymousToNestedRefactoring refactoring = new ConvertAnonymousToNestedRefactoring(anonymTypeDecl);
    if (!refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
        return null;
    }
    if (returnAsCommand) {
        return new RefactoringCorrectionCommandProposal(label, CodeActionKind.Refactor, context.getCompilationUnit(), IProposalRelevance.CONVERT_ANONYMOUS_TO_NESTED, RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID, Arrays.asList(CONVERT_ANONYMOUS_CLASS_TO_NESTED_COMMAND, params));
    }
    String extTypeName = ASTNodes.getTypeName(cic.getType());
    ITypeBinding anonymTypeBinding = anonymTypeDecl.resolveBinding();
    String className;
    if (anonymTypeBinding.getInterfaces().length == 0) {
        className = Messages.format(CorrectionMessages.QuickAssistProcessor_name_extension_from_interface, extTypeName);
    } else {
        className = Messages.format(CorrectionMessages.QuickAssistProcessor_name_extension_from_class, extTypeName);
    }
    String[][] existingTypes = ((IType) anonymTypeBinding.getJavaElement()).resolveType(className);
    int i = 1;
    while (existingTypes != null) {
        i++;
        existingTypes = ((IType) anonymTypeBinding.getJavaElement()).resolveType(className + i);
    }
    refactoring.setClassName(i == 1 ? className : className + i);
    LinkedProposalModelCore linkedProposalModel = new LinkedProposalModelCore();
    refactoring.setLinkedProposalModel(linkedProposalModel);
    final ICompilationUnit cu = context.getCompilationUnit();
    RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, CodeActionKind.Refactor, cu, refactoring, IProposalRelevance.CONVERT_ANONYMOUS_TO_NESTED);
    proposal.setLinkedProposalModel(linkedProposalModel);
    return proposal;
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ConvertAnonymousToNestedRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) RefactoringCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.RefactoringCorrectionProposal) IType(org.eclipse.jdt.core.IType) LinkedProposalModelCore(org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) RefactoringCorrectionCommandProposal(org.eclipse.jdt.ls.core.internal.text.correction.RefactoringCorrectionCommandProposal)

Example 2 with LinkedProposalModelCore

use of org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore in project eclipse.jdt.ls by eclipse.

the class SurroundWithTryCatchRefactoring method createChange.

/* non Java-doc
	 * @see IRefactoring#createChange(IProgressMonitor)
	 */
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
    // $NON-NLS-1$
    final String NN = "";
    if (pm == null) {
        pm = new NullProgressMonitor();
    }
    pm.beginTask(NN, 2);
    try {
        final CompilationUnitChange result = new CompilationUnitChange(getName(), fCUnit);
        if (fLeaveDirty) {
            result.setSaveMode(TextFileChange.LEAVE_DIRTY);
        }
        MultiTextEdit root = new MultiTextEdit();
        result.setEdit(root);
        fRewriter = ASTRewrite.create(fAnalyzer.getEnclosingBodyDeclaration().getAST());
        fRewriter.setTargetSourceRangeComputer(new SelectionAwareSourceRangeComputer(fAnalyzer.getSelectedNodes(), fCUnit.getBuffer(), fSelection.getOffset(), fSelection.getLength()));
        fImportRewrite = CodeStyleConfiguration.createImportRewrite(fRootNode, true);
        fLinkedProposalModel = new LinkedProposalModelCore();
        fScope = CodeScopeBuilder.perform(fAnalyzer.getEnclosingBodyDeclaration(), fSelection).findScope(fSelection.getOffset(), fSelection.getLength());
        fScope.setCursor(fSelection.getOffset());
        fSelectedNodes = fAnalyzer.getSelectedNodes();
        createTryCatchStatement(fCUnit.getBuffer(), fCUnit.findRecommendedLineSeparator());
        if (fImportRewrite.hasRecordedChanges()) {
            TextEdit edit = fImportRewrite.rewriteImports(null);
            root.addChild(edit);
            result.addTextEditGroup(new TextEditGroup(NN, new TextEdit[] { edit }));
        }
        TextEdit change = fRewriter.rewriteAST();
        root.addChild(change);
        result.addTextEditGroup(new TextEditGroup(NN, new TextEdit[] { change }));
        return result;
    } finally {
        pm.done();
    }
}
Also used : SelectionAwareSourceRangeComputer(org.eclipse.jdt.ls.core.internal.corext.refactoring.util.SelectionAwareSourceRangeComputer) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) LinkedProposalModelCore(org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Example 3 with LinkedProposalModelCore

use of org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore 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 4 with LinkedProposalModelCore

use of org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore in project eclipse.jdt.ls by eclipse.

the class QuickAssistProcessor method getConvertMethodReferenceToLambdaProposal.

private static boolean getConvertMethodReferenceToLambdaProposal(IInvocationContext context, ASTNode covering, Collection<ChangeCorrectionProposal> resultingCollections) throws JavaModelException {
    MethodReference methodReference;
    if (covering instanceof MethodReference) {
        methodReference = (MethodReference) covering;
    } else if (covering.getParent() instanceof MethodReference) {
        methodReference = (MethodReference) covering.getParent();
    } else {
        return false;
    }
    IMethodBinding functionalMethod = getFunctionalMethodForMethodReference(methodReference);
    if (functionalMethod == null || functionalMethod.isGenericMethod()) {
        // generic lambda expressions are not allowed
        return false;
    }
    if (resultingCollections == null) {
        return true;
    }
    ASTRewrite rewrite = ASTRewrite.create(methodReference.getAST());
    LinkedProposalModelCore linkedProposalModel = new LinkedProposalModelCore();
    LambdaExpression lambda = convertMethodRefernceToLambda(methodReference, functionalMethod, context.getASTRoot(), rewrite, linkedProposalModel, false);
    // add proposal
    String label = CorrectionMessages.QuickAssistProcessor_convert_to_lambda_expression;
    LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_METHOD_REFERENCE_TO_LAMBDA);
    proposal.setLinkedProposalModel(linkedProposalModel);
    proposal.setEndPosition(rewrite.track(lambda));
    resultingCollections.add(proposal);
    return true;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) LinkedProposalModelCore(org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore) LinkedCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) MethodReference(org.eclipse.jdt.core.dom.MethodReference) TypeMethodReference(org.eclipse.jdt.core.dom.TypeMethodReference) SuperMethodReference(org.eclipse.jdt.core.dom.SuperMethodReference) ExpressionMethodReference(org.eclipse.jdt.core.dom.ExpressionMethodReference) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 5 with LinkedProposalModelCore

use of org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore in project eclipse.jdt.ls by eclipse.

the class RefactorProposalUtility method getExtractMethodProposal.

private static CUCorrectionProposal getExtractMethodProposal(CodeActionParams params, IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Map formattingOptions, boolean returnAsCommand, boolean inferSelectionSupport) throws CoreException {
    if (!(coveringNode instanceof Expression) && !(coveringNode instanceof Statement) && !(coveringNode instanceof Block)) {
        return null;
    }
    if (coveringNode instanceof Block) {
        List<Statement> statements = ((Block) coveringNode).statements();
        int startIndex = getIndex(context.getSelectionOffset(), statements);
        if (startIndex == -1) {
            return null;
        }
        int endIndex = getIndex(context.getSelectionOffset() + context.getSelectionLength(), statements);
        if (endIndex == -1 || endIndex <= startIndex) {
            return null;
        }
    }
    final ICompilationUnit cu = context.getCompilationUnit();
    final ExtractMethodRefactoring extractMethodRefactoring = new ExtractMethodRefactoring(context.getASTRoot(), context.getSelectionOffset(), context.getSelectionLength(), formattingOptions);
    String uniqueMethodName = getUniqueMethodName(coveringNode, "extracted");
    extractMethodRefactoring.setMethodName(uniqueMethodName);
    String label = CorrectionMessages.QuickAssistProcessor_extractmethod_description;
    int relevance = problemsAtLocation ? IProposalRelevance.EXTRACT_METHOD_ERROR : IProposalRelevance.EXTRACT_METHOD;
    if (context.getSelectionLength() == 0) {
        if (!inferSelectionSupport) {
            return null;
        }
        ASTNode parent = coveringNode;
        while (parent != null && parent instanceof Expression) {
            if (parent instanceof ParenthesizedExpression) {
                parent = parent.getParent();
                continue;
            }
            ExtractMethodRefactoring refactoring = new ExtractMethodRefactoring(context.getASTRoot(), parent.getStartPosition(), parent.getLength(), formattingOptions);
            if (refactoring.checkInferConditions(new NullProgressMonitor()).isOK()) {
                return new CUCorrectionCommandProposal(label, JavaCodeActionKind.REFACTOR_EXTRACT_METHOD, cu, relevance, APPLY_REFACTORING_COMMAND_ID, Arrays.asList(EXTRACT_METHOD_COMMAND, params));
            }
            parent = parent.getParent();
        }
        return null;
    } else if (extractMethodRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
        if (returnAsCommand) {
            return new CUCorrectionCommandProposal(label, JavaCodeActionKind.REFACTOR_EXTRACT_METHOD, cu, relevance, APPLY_REFACTORING_COMMAND_ID, Arrays.asList(EXTRACT_METHOD_COMMAND, params));
        }
        LinkedProposalModelCore linkedProposalModel = new LinkedProposalModelCore();
        extractMethodRefactoring.setLinkedProposalModel(linkedProposalModel);
        RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, JavaCodeActionKind.REFACTOR_EXTRACT_METHOD, cu, extractMethodRefactoring, relevance);
        proposal.setLinkedProposalModel(linkedProposalModel);
        return proposal;
    }
    return null;
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) RefactoringCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.RefactoringCorrectionProposal) ExtractMethodRefactoring(org.eclipse.jdt.ls.core.internal.corext.refactoring.code.ExtractMethodRefactoring) LinkedProposalModelCore(org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block)

Aggregations

LinkedProposalModelCore (org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore)12 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)9 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)9 RefactoringCorrectionProposal (org.eclipse.jdt.ls.core.internal.corrections.proposals.RefactoringCorrectionProposal)9 ASTNode (org.eclipse.jdt.core.dom.ASTNode)7 IntroduceParameterRefactoring (org.eclipse.jdt.ls.core.internal.corext.refactoring.code.IntroduceParameterRefactoring)7 Expression (org.eclipse.jdt.core.dom.Expression)6 ExtractMethodRefactoring (org.eclipse.jdt.ls.core.internal.corext.refactoring.code.ExtractMethodRefactoring)6 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)5 PromoteTempToFieldRefactoring (org.eclipse.jdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring)5 ExtractConstantRefactoring (org.eclipse.jdt.ls.core.internal.corext.refactoring.code.ExtractConstantRefactoring)5 ExtractFieldRefactoring (org.eclipse.jdt.ls.core.internal.corext.refactoring.code.ExtractFieldRefactoring)5 ExtractTempRefactoring (org.eclipse.jdt.ls.core.internal.corext.refactoring.code.ExtractTempRefactoring)5 Refactoring (org.eclipse.ltk.core.refactoring.Refactoring)5 LinkedCorrectionProposal (org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal)3 ArrayList (java.util.ArrayList)2 Block (org.eclipse.jdt.core.dom.Block)2 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)2 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)2 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)2