Search in sources :

Example 6 with LinkedCorrectionProposal

use of org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal in project eclipse.jdt.ls by eclipse.

the class ReturnTypeSubProcessor method addVoidMethodReturnsProposals.

public static void addVoidMethodReturnsProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl instanceof MethodDeclaration && selectedNode.getNodeType() == ASTNode.RETURN_STATEMENT) {
        ReturnStatement returnStatement = (ReturnStatement) selectedNode;
        Expression expr = returnStatement.getExpression();
        if (expr != null) {
            AST ast = astRoot.getAST();
            ITypeBinding binding = Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
            if (binding == null) {
                // $NON-NLS-1$
                binding = ast.resolveWellKnownType("java.lang.Object");
            }
            if (binding.isWildcardType()) {
                binding = ASTResolving.normalizeWildcardType(binding, true, ast);
            }
            MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
            ASTRewrite rewrite = ASTRewrite.create(ast);
            String label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_voidmethodreturns_description, BindingLabelProvider.getBindingLabel(binding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
            LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.VOID_METHOD_RETURNS);
            ImportRewrite imports = proposal.createImportRewrite(astRoot);
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(methodDeclaration, imports);
            Type newReturnType = imports.addImport(binding, ast, importRewriteContext, TypeLocation.RETURN_TYPE);
            if (methodDeclaration.isConstructor()) {
                rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
                rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, newReturnType, null);
            } else {
                rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
            }
            // $NON-NLS-1$
            String key = "return_type";
            proposal.addLinkedPosition(rewrite.track(newReturnType), true, key);
            ITypeBinding[] bindings = ASTResolving.getRelaxingTypes(ast, binding);
            for (int i = 0; i < bindings.length; i++) {
                proposal.addLinkedPositionProposal(key, bindings[i]);
            }
            Javadoc javadoc = methodDeclaration.getJavadoc();
            if (javadoc != null) {
                TagElement newTag = ast.newTagElement();
                newTag.setTagName(TagElement.TAG_RETURN);
                TextElement commentStart = ast.newTextElement();
                newTag.fragments().add(commentStart);
                JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
                // $NON-NLS-1$
                proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
            }
            proposals.add(proposal);
        }
        ASTRewrite rewrite = ASTRewrite.create(decl.getAST());
        rewrite.remove(returnStatement.getExpression(), null);
        String label = CorrectionMessages.ReturnTypeSubProcessor_removereturn_description;
        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_RETURN);
        proposals.add(proposal);
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ASTRewriteCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) TextElement(org.eclipse.jdt.core.dom.TextElement) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) LinkedCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 7 with LinkedCorrectionProposal

use of org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal in project eclipse.jdt.ls by eclipse.

the class ReturnTypeSubProcessor method addMissingReturnTypeProposals.

public static void addMissingReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
        ReturnStatementCollector eval = new ReturnStatementCollector();
        decl.accept(eval);
        AST ast = astRoot.getAST();
        ITypeBinding typeBinding = eval.getTypeBinding(decl.getAST());
        typeBinding = Bindings.normalizeTypeBinding(typeBinding);
        if (typeBinding == null) {
            // $NON-NLS-1$
            typeBinding = ast.resolveWellKnownType("void");
        }
        if (typeBinding.isWildcardType()) {
            typeBinding = ASTResolving.normalizeWildcardType(typeBinding, true, ast);
        }
        ASTRewrite rewrite = ASTRewrite.create(ast);
        String label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_missingreturntype_description, BindingLabelProvider.getBindingLabel(typeBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.MISSING_RETURN_TYPE);
        ImportRewrite imports = proposal.createImportRewrite(astRoot);
        ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
        Type type = imports.addImport(typeBinding, ast, importRewriteContext, TypeLocation.RETURN_TYPE);
        rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, type, null);
        rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
        Javadoc javadoc = methodDeclaration.getJavadoc();
        if (javadoc != null && typeBinding != null) {
            TagElement newTag = ast.newTagElement();
            newTag.setTagName(TagElement.TAG_RETURN);
            TextElement commentStart = ast.newTextElement();
            newTag.fragments().add(commentStart);
            JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
            // $NON-NLS-1$
            proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
        }
        // $NON-NLS-1$
        String key = "return_type";
        proposal.addLinkedPosition(rewrite.track(type), true, key);
        if (typeBinding != null) {
            ITypeBinding[] bindings = ASTResolving.getRelaxingTypes(ast, typeBinding);
            for (int i = 0; i < bindings.length; i++) {
                proposal.addLinkedPositionProposal(key, bindings[i]);
            }
        }
        proposals.add(proposal);
        // change to constructor
        ASTNode parentType = ASTResolving.findParentType(decl);
        if (parentType instanceof AbstractTypeDeclaration) {
            boolean isInterface = parentType instanceof TypeDeclaration && ((TypeDeclaration) parentType).isInterface();
            if (!isInterface) {
                String constructorName = ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
                ASTNode nameNode = methodDeclaration.getName();
                label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_wrongconstructorname_description, BasicElementLabels.getJavaElementName(constructorName));
                proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, IProposalRelevance.CHANGE_TO_CONSTRUCTOR));
            }
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) TextElement(org.eclipse.jdt.core.dom.TextElement) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) LinkedCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) ReplaceCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ReplaceCorrectionProposal)

Example 8 with LinkedCorrectionProposal

use of org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal in project eclipse.jdt.ls by eclipse.

the class GetRefactorEditHandler method getEditsForRefactor.

public static RefactorWorkspaceEdit getEditsForRefactor(GetRefactorEditParams params) {
    final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.context.getTextDocument().getUri());
    if (unit == null) {
        return null;
    }
    int start = DiagnosticsHelper.getStartOffset(unit, params.context.getRange());
    int end = DiagnosticsHelper.getEndOffset(unit, params.context.getRange());
    InnovationContext context = new InnovationContext(unit, start, end - start);
    context.setASTRoot(CodeActionHandler.getASTRoot(unit));
    IProblemLocationCore[] locations = CodeActionHandler.getProblemLocationCores(unit, params.context.getContext().getDiagnostics());
    boolean problemsAtLocation = locations.length != 0;
    String positionKey = DEFAULT_POSITION_KEY;
    try {
        Map formatterOptions = params.options == null ? null : FormatterHandler.getOptions(params.options, unit);
        LinkedCorrectionProposal proposal = null;
        if (RefactorProposalUtility.EXTRACT_VARIABLE_COMMAND.equals(params.command) || RefactorProposalUtility.EXTRACT_VARIABLE_ALL_OCCURRENCE_COMMAND.equals(params.command) || RefactorProposalUtility.EXTRACT_CONSTANT_COMMAND.equals(params.command)) {
            SelectionInfo info = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), SelectionInfo.class) : null;
            if (info != null) {
                context = new InnovationContext(unit, info.offset, info.length);
            }
            proposal = (LinkedCorrectionProposal) getExtractVariableProposal(params.context, context, problemsAtLocation, params.command, formatterOptions);
        } else if (RefactorProposalUtility.ASSIGN_VARIABLE_COMMAND.equals(params.command)) {
            proposal = (LinkedCorrectionProposal) getAssignVariableProposal(params, context, problemsAtLocation, params.command, formatterOptions, locations);
        } else if (RefactorProposalUtility.ASSIGN_FIELD_COMMAND.equals(params.command)) {
            proposal = (LinkedCorrectionProposal) RefactorProposalUtility.getAssignFieldProposal(params.context, context, problemsAtLocation, formatterOptions, false, locations);
        } else if (RefactorProposalUtility.EXTRACT_METHOD_COMMAND.equals(params.command)) {
            SelectionInfo info = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), SelectionInfo.class) : null;
            if (info != null) {
                context = new InnovationContext(unit, info.offset, info.length);
            }
            proposal = (LinkedCorrectionProposal) getExtractMethodProposal(params.context, context, context.getCoveringNode(), problemsAtLocation, formatterOptions);
        } else if (RefactorProposalUtility.CONVERT_VARIABLE_TO_FIELD_COMMAND.equals(params.command)) {
            String initializeIn = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), String.class) : null;
            proposal = (LinkedCorrectionProposal) RefactorProposalUtility.getConvertVariableToFieldProposal(params.context, context, problemsAtLocation, formatterOptions, initializeIn, false);
        } else if (RefactorProposalUtility.EXTRACT_FIELD_COMMAND.equals(params.command)) {
            String initializeIn = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), String.class) : null;
            SelectionInfo info = (params.commandArguments != null && params.commandArguments.size() > 1) ? JSONUtility.toModel(params.commandArguments.get(1), SelectionInfo.class) : null;
            if (info != null) {
                context = new InnovationContext(unit, info.offset, info.length);
            }
            proposal = (LinkedCorrectionProposal) RefactorProposalUtility.getExtractFieldProposal(params.context, context, problemsAtLocation, formatterOptions, initializeIn, false);
        } else if (InvertBooleanUtility.INVERT_VARIABLE_COMMAND.equals(params.command)) {
            proposal = (LinkedCorrectionProposal) InvertBooleanUtility.getInvertVariableProposal(params.context, context, context.getCoveringNode(), false);
        } else if (RefactorProcessor.CONVERT_ANONYMOUS_CLASS_TO_NESTED_COMMAND.equals(params.command)) {
            proposal = RefactorProcessor.getConvertAnonymousToNestedProposal(params.context, context, context.getCoveringNode(), false);
            positionKey = "type_name";
        } else if (RefactorProposalUtility.INTRODUCE_PARAMETER_COMMAND.equals(params.command)) {
            // String initializeIn = (params.commandArguments != null && !params.commandArguments.isEmpty()) ? JSONUtility.toModel(params.commandArguments.get(0), String.class) : null;
            proposal = (LinkedCorrectionProposal) RefactorProposalUtility.getIntroduceParameterRefactoringProposals(params.context, context, context.getCoveringNode(), false, locations);
            positionKey = null;
            if (proposal instanceof RefactoringCorrectionProposal) {
                RefactoringCorrectionProposal rcp = (RefactoringCorrectionProposal) proposal;
                IntroduceParameterRefactoring refactoring = (IntroduceParameterRefactoring) rcp.getRefactoring();
                ParameterInfo parameterInfo = refactoring.getAddedParameterInfo();
                if (parameterInfo != null) {
                    positionKey = parameterInfo.getNewName();
                }
            }
        }
        if (proposal == null) {
            return null;
        }
        Change change = proposal.getChange();
        WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change);
        LinkedProposalModelCore linkedProposalModel = proposal.getLinkedProposalModel();
        Command additionalCommand = null;
        if (linkedProposalModel != null) {
            LinkedProposalPositionGroupCore linkedPositionGroup = linkedProposalModel.getPositionGroup(positionKey, false);
            if (linkedPositionGroup == null) {
                Iterator<LinkedProposalPositionGroupCore> iter = linkedProposalModel.getPositionGroupCoreIterator();
                while (iter.hasNext()) {
                    LinkedProposalPositionGroupCore lppgc = iter.next();
                    if (lppgc.getGroupId().startsWith(positionKey)) {
                        linkedPositionGroup = lppgc;
                        break;
                    }
                }
            }
            PositionInformation highlightPosition = getFirstTrackedNodePositionBySequenceRank(linkedPositionGroup);
            if (highlightPosition != null) {
                int offset = highlightPosition.getOffset();
                int length = highlightPosition.getLength();
                RenamePosition renamePosition = new RenamePosition(JDTUtils.toURI(unit), offset, length);
                additionalCommand = new Command("Rename", RENAME_COMMAND, Arrays.asList(renamePosition));
            }
        }
        return new RefactorWorkspaceEdit(edit, additionalCommand);
    } catch (CoreException e) {
    // do nothing.
    }
    return null;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IntroduceParameterRefactoring(org.eclipse.jdt.ls.core.internal.corext.refactoring.code.IntroduceParameterRefactoring) PositionInformation(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroupCore.PositionInformation) LinkedProposalPositionGroupCore(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroupCore) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) InnovationContext(org.eclipse.jdt.ls.core.internal.corrections.InnovationContext) ParameterInfo(org.eclipse.jdt.ls.core.internal.corext.refactoring.ParameterInfo) Change(org.eclipse.ltk.core.refactoring.Change) RefactoringCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.RefactoringCorrectionProposal) LinkedProposalModelCore(org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore) IProblemLocationCore(org.eclipse.jdt.internal.ui.text.correction.IProblemLocationCore) SelectionInfo(org.eclipse.jdt.ls.core.internal.handlers.InferSelectionHandler.SelectionInfo) CoreException(org.eclipse.core.runtime.CoreException) Command(org.eclipse.lsp4j.Command) LinkedCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal) Map(java.util.Map)

Aggregations

LinkedCorrectionProposal (org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal)8 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)7 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)6 AST (org.eclipse.jdt.core.dom.AST)6 ASTNode (org.eclipse.jdt.core.dom.ASTNode)5 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)5 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)5 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)5 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)5 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)5 Type (org.eclipse.jdt.core.dom.Type)5 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)5 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)5 Expression (org.eclipse.jdt.core.dom.Expression)4 Javadoc (org.eclipse.jdt.core.dom.Javadoc)4 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)4 TagElement (org.eclipse.jdt.core.dom.TagElement)4 TextElement (org.eclipse.jdt.core.dom.TextElement)4 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)3 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)3