Search in sources :

Example 1 with LspVariableBinding

use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.

the class MoveHandler method getInstanceMethodDestinations.

private static MoveDestinationsResponse getInstanceMethodDestinations(CodeActionParams params) {
    final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
    if (unit == null) {
        return new MoveDestinationsResponse("Cannot find the compilation unit associated with " + params.getTextDocument().getUri());
    }
    MethodDeclaration methodDeclaration = getSelectedMethodDeclaration(unit, params);
    if (methodDeclaration == null) {
        return new MoveDestinationsResponse("The selected element is not a method.");
    }
    IMethodBinding methodBinding = methodDeclaration.resolveBinding();
    if (methodBinding == null || !(methodBinding.getJavaElement() instanceof IMethod)) {
        return new MoveDestinationsResponse("The selected element is not a method.");
    }
    IMethod method = (IMethod) methodBinding.getJavaElement();
    MoveInstanceMethodProcessor processor = new MoveInstanceMethodProcessor(method, PreferenceManager.getCodeGenerationSettings(unit));
    Refactoring refactoring = new MoveRefactoring(processor);
    CheckConditionsOperation check = new CheckConditionsOperation(refactoring, CheckConditionsOperation.INITIAL_CONDITONS);
    try {
        check.run(new NullProgressMonitor());
        if (check.getStatus().hasFatalError()) {
            return new MoveDestinationsResponse(check.getStatus().getMessageMatchingSeverity(RefactoringStatus.FATAL));
        }
        IVariableBinding[] possibleTargets = processor.getPossibleTargets();
        LspVariableBinding[] targets = Stream.of(possibleTargets).map(target -> new LspVariableBinding(target)).toArray(LspVariableBinding[]::new);
        return new MoveDestinationsResponse(targets);
    } catch (CoreException e) {
        JavaLanguageServerPlugin.log(e);
    }
    return new MoveDestinationsResponse("Cannot find any target to move the method to.");
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) RefactoringAvailabilityTesterCore(org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTesterCore) Arrays(java.util.Arrays) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) CreateChangeOperation(org.eclipse.ltk.core.refactoring.CreateChangeOperation) ProjectUtils(org.eclipse.jdt.ls.core.internal.ProjectUtils) CoreException(org.eclipse.core.runtime.CoreException) StringUtils(org.apache.commons.lang3.StringUtils) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) Refactoring(org.eclipse.ltk.core.refactoring.Refactoring) JavaMoveProcessor(org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.JavaMoveProcessor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) DiagnosticsHelper(org.eclipse.jdt.ls.core.internal.corrections.DiagnosticsHelper) IPath(org.eclipse.core.runtime.IPath) Gson(com.google.gson.Gson) Change(org.eclipse.ltk.core.refactoring.Change) URI(java.net.URI) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) ASTNode(org.eclipse.jdt.core.dom.ASTNode) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) IJavaProject(org.eclipse.jdt.core.IJavaProject) Collection(java.util.Collection) Set(java.util.Set) IReorgDestination(org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgDestination) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) Collectors(java.util.stream.Collectors) IConfirmQuery(org.eclipse.jdt.internal.corext.refactoring.reorg.IConfirmQuery) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Objects(java.util.Objects) IType(org.eclipse.jdt.core.IType) List(java.util.List) Stream(java.util.stream.Stream) ReorgPolicyFactory(org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.ReorgPolicyFactory) InnovationContext(org.eclipse.jdt.ls.core.internal.corrections.InnovationContext) Optional(java.util.Optional) ChangeUtil(org.eclipse.jdt.ls.core.internal.ChangeUtil) MoveInstanceMethodProcessor(org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ResourcesPlugin(org.eclipse.core.resources.ResourcesPlugin) RefactorWorkspaceEdit(org.eclipse.jdt.ls.core.internal.handlers.GetRefactorEditHandler.RefactorWorkspaceEdit) JavaModelException(org.eclipse.jdt.core.JavaModelException) SubMonitor(org.eclipse.core.runtime.SubMonitor) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) MoveStaticMembersProcessor(org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersProcessor) IMember(org.eclipse.jdt.core.IMember) CheckConditionsOperation(org.eclipse.ltk.core.refactoring.CheckConditionsOperation) MoveRefactoring(org.eclipse.ltk.core.refactoring.participants.MoveRefactoring) ArrayList(java.util.ArrayList) SymbolInformation(org.eclipse.lsp4j.SymbolInformation) IContainer(org.eclipse.core.resources.IContainer) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) ProjectsManager(org.eclipse.jdt.ls.core.internal.managers.ProjectsManager) IProject(org.eclipse.core.resources.IProject) JdtFlags(org.eclipse.jdt.internal.corext.util.JdtFlags) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) ReorgDestinationFactory(org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.ReorgDestinationFactory) LinkedHashSet(java.util.LinkedHashSet) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) ResourceUtils(org.eclipse.jdt.ls.core.internal.ResourceUtils) JSONUtility(org.eclipse.jdt.ls.core.internal.JSONUtility) JavaCore(org.eclipse.jdt.core.JavaCore) LspVariableBinding(org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) PreferenceManager(org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager) ReorgUtils(org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.ReorgUtils) IJavaElement(org.eclipse.jdt.core.IJavaElement) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IReorgQueries(org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgQueries) IResource(org.eclipse.core.resources.IResource) IMethod(org.eclipse.jdt.core.IMethod) MoveInnerToTopRefactoring(org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) Comparator(java.util.Comparator) IMovePolicy(org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) LspVariableBinding(org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) MoveRefactoring(org.eclipse.ltk.core.refactoring.participants.MoveRefactoring) CoreException(org.eclipse.core.runtime.CoreException) CheckConditionsOperation(org.eclipse.ltk.core.refactoring.CheckConditionsOperation) IMethod(org.eclipse.jdt.core.IMethod) Refactoring(org.eclipse.ltk.core.refactoring.Refactoring) MoveRefactoring(org.eclipse.ltk.core.refactoring.participants.MoveRefactoring) MoveInnerToTopRefactoring(org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring) MoveInstanceMethodProcessor(org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor)

Example 2 with LspVariableBinding

use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.

the class SourceAssistProcessor method getSourceActionCommands.

public List<Either<Command, CodeAction>> getSourceActionCommands(CodeActionParams params, IInvocationContext context, IProblemLocationCore[] locations, IProgressMonitor monitor) {
    List<Either<Command, CodeAction>> $ = new ArrayList<>();
    ICompilationUnit cu = context.getCompilationUnit();
    IType type = getSelectionType(context);
    boolean isInTypeDeclaration = isInTypeDeclaration(context);
    boolean isInImportDeclaration = isInImportDeclaration(context);
    try {
        // Generate Constructor QuickAssist
        IJavaElement element = JDTUtils.findElementAtSelection(cu, params.getRange().getEnd().getLine(), params.getRange().getEnd().getCharacter(), this.preferenceManager, new NullProgressMonitor());
        if (element instanceof IField || isInTypeDeclaration) {
            Optional<Either<Command, CodeAction>> quickAssistGenerateConstructors = getGenerateConstructorsAction(params, context, type, JavaCodeActionKind.QUICK_ASSIST, monitor);
            addSourceActionCommand($, params.getContext(), quickAssistGenerateConstructors);
        }
    } catch (JavaModelException e) {
        JavaLanguageServerPlugin.logException(e);
    }
    // Generate Constructor Source Action
    Optional<Either<Command, CodeAction>> sourceGenerateConstructors = getGenerateConstructorsAction(params, context, type, JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS, monitor);
    addSourceActionCommand($, params.getContext(), sourceGenerateConstructors);
    // Organize Imports
    if (preferenceManager.getClientPreferences().isAdvancedOrganizeImportsSupported()) {
        // Generate QuickAssist
        if (isInImportDeclaration) {
            Optional<Either<Command, CodeAction>> quickAssistOrganizeImports = getOrganizeImportsAction(params, JavaCodeActionKind.QUICK_ASSIST);
            addSourceActionCommand($, params.getContext(), quickAssistOrganizeImports);
        }
        // Generate Source Action
        Optional<Either<Command, CodeAction>> sourceOrganizeImports = getOrganizeImportsAction(params, CodeActionKind.SourceOrganizeImports);
        addSourceActionCommand($, params.getContext(), sourceOrganizeImports);
    } else {
        CodeActionProposal organizeImportsProposal = (pm) -> {
            TextEdit edit = getOrganizeImportsProposal(context, pm);
            return convertToWorkspaceEdit(cu, edit);
        };
        // Generate QuickAssist
        if (isInImportDeclaration) {
            Optional<Either<Command, CodeAction>> sourceOrganizeImports = getCodeActionFromProposal(params.getContext(), context.getCompilationUnit(), CorrectionMessages.ReorgCorrectionsSubProcessor_organizeimports_description, JavaCodeActionKind.QUICK_ASSIST, organizeImportsProposal);
            addSourceActionCommand($, params.getContext(), sourceOrganizeImports);
        }
        // Generate Source Action
        Optional<Either<Command, CodeAction>> sourceOrganizeImports = getCodeActionFromProposal(params.getContext(), context.getCompilationUnit(), CorrectionMessages.ReorgCorrectionsSubProcessor_organizeimports_description, CodeActionKind.SourceOrganizeImports, organizeImportsProposal);
        addSourceActionCommand($, params.getContext(), sourceOrganizeImports);
    }
    if (!UNSUPPORTED_RESOURCES.contains(cu.getResource().getName())) {
        // Override/Implement Methods QuickAssist
        if (isInTypeDeclaration) {
            Optional<Either<Command, CodeAction>> quickAssistOverrideMethods = getOverrideMethodsAction(params, JavaCodeActionKind.QUICK_ASSIST);
            addSourceActionCommand($, params.getContext(), quickAssistOverrideMethods);
        }
        // Override/Implement Methods Source Action
        Optional<Either<Command, CodeAction>> sourceOverrideMethods = getOverrideMethodsAction(params, JavaCodeActionKind.SOURCE_OVERRIDE_METHODS);
        addSourceActionCommand($, params.getContext(), sourceOverrideMethods);
    }
    // Generate Getter and Setter QuickAssist
    if (isInTypeDeclaration) {
        Optional<Either<Command, CodeAction>> quickAssistGetterSetter = getGetterSetterAction(params, context, type, JavaCodeActionKind.QUICK_ASSIST, isInTypeDeclaration);
        addSourceActionCommand($, params.getContext(), quickAssistGetterSetter);
    }
    // Generate Getter and Setter Source Action
    Optional<Either<Command, CodeAction>> sourceGetterSetter = getGetterSetterAction(params, context, type, JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS, isInTypeDeclaration);
    addSourceActionCommand($, params.getContext(), sourceGetterSetter);
    // Generate hashCode() and equals()
    if (supportsHashCodeEquals(context, type, monitor)) {
        // Generate QuickAssist
        if (isInTypeDeclaration) {
            Optional<Either<Command, CodeAction>> quickAssistHashCodeEquals = getHashCodeEqualsAction(params, JavaCodeActionKind.QUICK_ASSIST);
            addSourceActionCommand($, params.getContext(), quickAssistHashCodeEquals);
        }
        // Generate Source Action
        Optional<Either<Command, CodeAction>> sourceActionHashCodeEquals = getHashCodeEqualsAction(params, JavaCodeActionKind.SOURCE_GENERATE_HASHCODE_EQUALS);
        addSourceActionCommand($, params.getContext(), sourceActionHashCodeEquals);
    }
    // Generate toString()
    if (supportsGenerateToString(type)) {
        boolean nonStaticFields = true;
        try {
            nonStaticFields = hasFields(type, false);
        } catch (JavaModelException e) {
        // do nothing.
        }
        if (nonStaticFields) {
            // Generate QuickAssist
            if (isInTypeDeclaration) {
                Optional<Either<Command, CodeAction>> generateToStringQuickAssist = getGenerateToStringAction(params, JavaCodeActionKind.QUICK_ASSIST);
                addSourceActionCommand($, params.getContext(), generateToStringQuickAssist);
            }
            // Generate Source Action
            Optional<Either<Command, CodeAction>> generateToStringCommand = getGenerateToStringAction(params, JavaCodeActionKind.SOURCE_GENERATE_TO_STRING);
            addSourceActionCommand($, params.getContext(), generateToStringCommand);
        } else {
            CodeActionProposal generateToStringProposal = (pm) -> {
                IJavaElement insertPosition = isInTypeDeclaration ? CodeGenerationUtils.findInsertElement(type, null) : CodeGenerationUtils.findInsertElement(type, context.getSelectionOffset());
                TextEdit edit = GenerateToStringHandler.generateToString(type, new LspVariableBinding[0], insertPosition, pm);
                return convertToWorkspaceEdit(cu, edit);
            };
            // Generate QuickAssist
            if (isInTypeDeclaration) {
                Optional<Either<Command, CodeAction>> generateToStringQuickAssist = getCodeActionFromProposal(params.getContext(), context.getCompilationUnit(), ActionMessages.GenerateToStringAction_label, JavaCodeActionKind.QUICK_ASSIST, generateToStringProposal);
                addSourceActionCommand($, params.getContext(), generateToStringQuickAssist);
            }
            // Generate Source Action
            Optional<Either<Command, CodeAction>> generateToStringCommand = getCodeActionFromProposal(params.getContext(), context.getCompilationUnit(), ActionMessages.GenerateToStringAction_label, JavaCodeActionKind.SOURCE_GENERATE_TO_STRING, generateToStringProposal);
            addSourceActionCommand($, params.getContext(), generateToStringCommand);
        }
    }
    // Generate Delegate Methods
    Optional<Either<Command, CodeAction>> generateDelegateMethods = getGenerateDelegateMethodsAction(params, context, type);
    addSourceActionCommand($, params.getContext(), generateDelegateMethods);
    // Add final modifiers where possible
    Optional<Either<Command, CodeAction>> generateFinalModifiers = addFinalModifierWherePossibleAction(context);
    addSourceActionCommand($, params.getContext(), generateFinalModifiers);
    return $;
}
Also used : CodeActionProposal(org.eclipse.jdt.ls.core.internal.handlers.CodeActionProposal) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Arrays(java.util.Arrays) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) CoreException(org.eclipse.core.runtime.CoreException) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) GenerateToStringHandler(org.eclipse.jdt.ls.core.internal.handlers.GenerateToStringHandler) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) Statement(org.eclipse.jdt.core.dom.Statement) CodeActionHandler(org.eclipse.jdt.ls.core.internal.handlers.CodeActionHandler) DiagnosticsHelper(org.eclipse.jdt.ls.core.internal.corrections.DiagnosticsHelper) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) VariableDeclarationFixCore(org.eclipse.jdt.internal.corext.fix.VariableDeclarationFixCore) CodeActionProposal(org.eclipse.jdt.ls.core.internal.handlers.CodeActionProposal) OrganizeImportsHandler(org.eclipse.jdt.ls.core.internal.handlers.OrganizeImportsHandler) ASTNodes(org.eclipse.jdt.internal.corext.dom.ASTNodes) CodeAction(org.eclipse.lsp4j.CodeAction) ASTNode(org.eclipse.jdt.core.dom.ASTNode) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) IProposalRelevance(org.eclipse.jdt.ls.core.internal.corrections.proposals.IProposalRelevance) FixCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.FixCorrectionProposal) Set(java.util.Set) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) TextEditConverter(org.eclipse.jdt.ls.core.internal.TextEditConverter) Sets(com.google.common.collect.Sets) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) GenerateDelegateMethodsHandler(org.eclipse.jdt.ls.core.internal.handlers.GenerateDelegateMethodsHandler) IType(org.eclipse.jdt.core.IType) IProposableFix(org.eclipse.jdt.internal.corext.fix.IProposableFix) IInvocationContext(org.eclipse.jdt.ls.core.internal.corrections.IInvocationContext) IProblemLocationCore(org.eclipse.jdt.internal.ui.text.correction.IProblemLocationCore) List(java.util.List) Stream(java.util.stream.Stream) Command(org.eclipse.lsp4j.Command) Modifier(java.lang.reflect.Modifier) InnovationContext(org.eclipse.jdt.ls.core.internal.corrections.InnovationContext) Optional(java.util.Optional) ChangeUtil(org.eclipse.jdt.ls.core.internal.ChangeUtil) GenerateGetterSetterOperation(org.eclipse.jdt.ls.core.internal.codemanipulation.GenerateGetterSetterOperation) IField(org.eclipse.jdt.core.IField) JavaModelException(org.eclipse.jdt.core.JavaModelException) JavaCodeActionKind(org.eclipse.jdt.ls.core.internal.JavaCodeActionKind) CodeGenerationUtils(org.eclipse.jdt.ls.core.internal.handlers.CodeGenerationUtils) CorrectionMessages(org.eclipse.jdt.ls.core.internal.corrections.CorrectionMessages) CodeActionContext(org.eclipse.lsp4j.CodeActionContext) ArrayList(java.util.ArrayList) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) OrganizeImportsOperation(org.eclipse.jdt.core.manipulation.OrganizeImportsOperation) GenerateConstructorsHandler(org.eclipse.jdt.ls.core.internal.handlers.GenerateConstructorsHandler) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) CheckConstructorsResponse(org.eclipse.jdt.ls.core.internal.handlers.GenerateConstructorsHandler.CheckConstructorsResponse) AccessorField(org.eclipse.jdt.ls.core.internal.codemanipulation.GenerateGetterSetterOperation.AccessorField) JdtFlags(org.eclipse.jdt.internal.corext.util.JdtFlags) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) LspVariableBinding(org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) TextEdit(org.eclipse.text.edits.TextEdit) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) PreferenceManager(org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager) CoreASTProvider(org.eclipse.jdt.core.manipulation.CoreASTProvider) IJavaElement(org.eclipse.jdt.core.IJavaElement) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CodeActionKind(org.eclipse.lsp4j.CodeActionKind) Collections(java.util.Collections) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) JavaModelException(org.eclipse.jdt.core.JavaModelException) LspVariableBinding(org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding) ArrayList(java.util.ArrayList) IField(org.eclipse.jdt.core.IField) IType(org.eclipse.jdt.core.IType) TextEdit(org.eclipse.text.edits.TextEdit) Either(org.eclipse.lsp4j.jsonrpc.messages.Either)

Example 3 with LspVariableBinding

use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.

the class MoveHandler method moveInstanceMethod.

private static RefactorWorkspaceEdit moveInstanceMethod(CodeActionParams params, LspVariableBinding destination, IProgressMonitor monitor) {
    final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
    if (unit == null) {
        return new RefactorWorkspaceEdit("Failed to move instance method because cannot find the compilation unit associated with " + params.getTextDocument().getUri());
    }
    MethodDeclaration methodDeclaration = getSelectedMethodDeclaration(unit, params);
    if (methodDeclaration == null || destination == null) {
        return new RefactorWorkspaceEdit("Failed to move instance method because no method is selected or no destination is specified.");
    }
    IMethodBinding methodBinding = methodDeclaration.resolveBinding();
    if (methodBinding == null || !(methodBinding.getJavaElement() instanceof IMethod)) {
        return new RefactorWorkspaceEdit("Failed to move instance method because the selected element is not a method.");
    }
    SubMonitor subMonitor = SubMonitor.convert(monitor, "Moving instance method...", 100);
    IMethod method = (IMethod) methodBinding.getJavaElement();
    MoveInstanceMethodProcessor processor = new MoveInstanceMethodProcessor(method, PreferenceManager.getCodeGenerationSettings(unit));
    Refactoring refactoring = new MoveRefactoring(processor);
    CheckConditionsOperation check = new CheckConditionsOperation(refactoring, CheckConditionsOperation.INITIAL_CONDITONS);
    try {
        check.run(subMonitor.split(20));
        if (check.getStatus().getSeverity() >= RefactoringStatus.FATAL) {
            JavaLanguageServerPlugin.logError("Failed to execute the 'move' refactoring.");
            JavaLanguageServerPlugin.logError(check.getStatus().toString());
            return new RefactorWorkspaceEdit("Failed to move instance method. Reason: " + check.getStatus().toString());
        }
        IVariableBinding[] possibleTargets = processor.getPossibleTargets();
        Optional<IVariableBinding> target = Stream.of(possibleTargets).filter(possibleTarget -> Objects.equals(possibleTarget.getKey(), destination.bindingKey)).findFirst();
        if (target.isPresent()) {
            processor.setTarget(target.get());
            processor.setDeprecateDelegates(false);
            processor.setInlineDelegator(true);
            processor.setRemoveDelegator(true);
            check = new CheckConditionsOperation(refactoring, CheckConditionsOperation.FINAL_CONDITIONS);
            check.run(subMonitor.split(60));
            if (check.getStatus().getSeverity() >= RefactoringStatus.FATAL) {
                JavaLanguageServerPlugin.logError("Failed to execute the 'move' refactoring.");
                JavaLanguageServerPlugin.logError(check.getStatus().toString());
                return new RefactorWorkspaceEdit("Failed to move instance method. Reason: " + check.getStatus().toString());
            }
            Change change = processor.createChange(subMonitor.split(20));
            return new RefactorWorkspaceEdit(ChangeUtil.convertToWorkspaceEdit(change));
        } else {
            return new RefactorWorkspaceEdit("Failed to move instance method because cannot find the target " + destination.name);
        }
    } catch (CoreException e) {
        JavaLanguageServerPlugin.log(e);
        return new RefactorWorkspaceEdit("Failed to move instance method because of " + e.toString());
    } finally {
        subMonitor.done();
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) RefactoringAvailabilityTesterCore(org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTesterCore) Arrays(java.util.Arrays) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) CreateChangeOperation(org.eclipse.ltk.core.refactoring.CreateChangeOperation) ProjectUtils(org.eclipse.jdt.ls.core.internal.ProjectUtils) CoreException(org.eclipse.core.runtime.CoreException) StringUtils(org.apache.commons.lang3.StringUtils) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) Refactoring(org.eclipse.ltk.core.refactoring.Refactoring) JavaMoveProcessor(org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.JavaMoveProcessor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) DiagnosticsHelper(org.eclipse.jdt.ls.core.internal.corrections.DiagnosticsHelper) IPath(org.eclipse.core.runtime.IPath) Gson(com.google.gson.Gson) Change(org.eclipse.ltk.core.refactoring.Change) URI(java.net.URI) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) ASTNode(org.eclipse.jdt.core.dom.ASTNode) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) IJavaProject(org.eclipse.jdt.core.IJavaProject) Collection(java.util.Collection) Set(java.util.Set) IReorgDestination(org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgDestination) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) Collectors(java.util.stream.Collectors) IConfirmQuery(org.eclipse.jdt.internal.corext.refactoring.reorg.IConfirmQuery) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Objects(java.util.Objects) IType(org.eclipse.jdt.core.IType) List(java.util.List) Stream(java.util.stream.Stream) ReorgPolicyFactory(org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.ReorgPolicyFactory) InnovationContext(org.eclipse.jdt.ls.core.internal.corrections.InnovationContext) Optional(java.util.Optional) ChangeUtil(org.eclipse.jdt.ls.core.internal.ChangeUtil) MoveInstanceMethodProcessor(org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ResourcesPlugin(org.eclipse.core.resources.ResourcesPlugin) RefactorWorkspaceEdit(org.eclipse.jdt.ls.core.internal.handlers.GetRefactorEditHandler.RefactorWorkspaceEdit) JavaModelException(org.eclipse.jdt.core.JavaModelException) SubMonitor(org.eclipse.core.runtime.SubMonitor) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) MoveStaticMembersProcessor(org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersProcessor) IMember(org.eclipse.jdt.core.IMember) CheckConditionsOperation(org.eclipse.ltk.core.refactoring.CheckConditionsOperation) MoveRefactoring(org.eclipse.ltk.core.refactoring.participants.MoveRefactoring) ArrayList(java.util.ArrayList) SymbolInformation(org.eclipse.lsp4j.SymbolInformation) IContainer(org.eclipse.core.resources.IContainer) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) ProjectsManager(org.eclipse.jdt.ls.core.internal.managers.ProjectsManager) IProject(org.eclipse.core.resources.IProject) JdtFlags(org.eclipse.jdt.internal.corext.util.JdtFlags) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) ReorgDestinationFactory(org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.ReorgDestinationFactory) LinkedHashSet(java.util.LinkedHashSet) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) ResourceUtils(org.eclipse.jdt.ls.core.internal.ResourceUtils) JSONUtility(org.eclipse.jdt.ls.core.internal.JSONUtility) JavaCore(org.eclipse.jdt.core.JavaCore) LspVariableBinding(org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) PreferenceManager(org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager) ReorgUtils(org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.ReorgUtils) IJavaElement(org.eclipse.jdt.core.IJavaElement) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IReorgQueries(org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgQueries) IResource(org.eclipse.core.resources.IResource) IMethod(org.eclipse.jdt.core.IMethod) MoveInnerToTopRefactoring(org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) Comparator(java.util.Comparator) IMovePolicy(org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SubMonitor(org.eclipse.core.runtime.SubMonitor) Change(org.eclipse.ltk.core.refactoring.Change) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) MoveRefactoring(org.eclipse.ltk.core.refactoring.participants.MoveRefactoring) CoreException(org.eclipse.core.runtime.CoreException) CheckConditionsOperation(org.eclipse.ltk.core.refactoring.CheckConditionsOperation) RefactorWorkspaceEdit(org.eclipse.jdt.ls.core.internal.handlers.GetRefactorEditHandler.RefactorWorkspaceEdit) IMethod(org.eclipse.jdt.core.IMethod) Refactoring(org.eclipse.ltk.core.refactoring.Refactoring) MoveRefactoring(org.eclipse.ltk.core.refactoring.participants.MoveRefactoring) MoveInnerToTopRefactoring(org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring) MoveInstanceMethodProcessor(org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor)

Example 4 with LspVariableBinding

use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.

the class MoveHandler method move.

public static RefactorWorkspaceEdit move(MoveParams moveParams, IProgressMonitor monitor) {
    if (moveParams == null) {
        return new RefactorWorkspaceEdit("moveParams should not be empty.");
    }
    try {
        if ("moveResource".equalsIgnoreCase(moveParams.moveKind)) {
            String targetUri = null;
            if (moveParams.destination instanceof String) {
                targetUri = (String) moveParams.destination;
            } else {
                String json = (moveParams.destination == null ? null : new Gson().toJson(moveParams.destination));
                PackageNode packageNode = JSONUtility.toLsp4jModel(json, PackageNode.class);
                if (packageNode == null) {
                    return new RefactorWorkspaceEdit("Invalid destination object: " + moveParams.destination);
                }
                targetUri = packageNode.uri;
            }
            return moveCU(moveParams.sourceUris, targetUri, moveParams.updateReferences, monitor);
        } else if ("moveInstanceMethod".equalsIgnoreCase(moveParams.moveKind)) {
            String json = (moveParams.destination == null ? null : new Gson().toJson(moveParams.destination));
            LspVariableBinding variableBinding = JSONUtility.toLsp4jModel(json, LspVariableBinding.class);
            if (variableBinding == null) {
                return new RefactorWorkspaceEdit("Invalid destination object: " + moveParams.destination);
            }
            return moveInstanceMethod(moveParams.params, variableBinding, monitor);
        } else if ("moveStaticMember".equalsIgnoreCase(moveParams.moveKind)) {
            String typeName = resolveTargetTypeName(moveParams.destination);
            return moveStaticMember(moveParams.params, typeName, monitor);
        } else if ("moveTypeToNewFile".equalsIgnoreCase(moveParams.moveKind)) {
            return moveTypeToNewFile(moveParams.params, monitor);
        } else if ("moveTypeToClass".equalsIgnoreCase(moveParams.moveKind)) {
            String typeName = resolveTargetTypeName(moveParams.destination);
            return moveTypeToClass(moveParams.params, typeName, monitor);
        }
    } catch (IllegalArgumentException e) {
        return new RefactorWorkspaceEdit(e.getMessage());
    }
    return new RefactorWorkspaceEdit("Unsupported move operation.");
}
Also used : LspVariableBinding(org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding) Gson(com.google.gson.Gson) RefactorWorkspaceEdit(org.eclipse.jdt.ls.core.internal.handlers.GetRefactorEditHandler.RefactorWorkspaceEdit)

Example 5 with LspVariableBinding

use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.

the class GenerateConstructorsHandler method checkConstructorStatus.

public static CheckConstructorsResponse checkConstructorStatus(IType type, IProgressMonitor monitor) {
    if (type == null || type.getCompilationUnit() == null) {
        return new CheckConstructorsResponse();
    }
    try {
        CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(type.getCompilationUnit(), CoreASTProvider.WAIT_YES, monitor);
        if (astRoot == null) {
            return new CheckConstructorsResponse();
        }
        ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
        if (typeBinding == null) {
            return new CheckConstructorsResponse();
        }
        IMethodBinding[] superConstructors = getVisibleConstructors(astRoot, typeBinding);
        Map<IJavaElement, IVariableBinding> fieldsToBindings = new HashMap<>();
        for (IVariableBinding field : typeBinding.getDeclaredFields()) {
            if (field.isSynthetic() || Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            if (Modifier.isFinal(field.getModifiers())) {
                ASTNode declaringNode = astRoot.findDeclaringNode(field);
                // Do not add final fields which have been set in the <clinit>
                if (declaringNode instanceof VariableDeclarationFragment && ((VariableDeclarationFragment) declaringNode).getInitializer() != null) {
                    continue;
                }
            }
            fieldsToBindings.put(field.getJavaElement(), field);
        }
        List<IVariableBinding> fields = new ArrayList<>();
        // Sort the fields by the order in which they appear in the source or class file.
        for (IField field : type.getFields()) {
            IVariableBinding fieldBinding = fieldsToBindings.remove(field);
            if (fieldBinding != null) {
                fields.add(fieldBinding);
            }
        }
        // @formatter:off
        return new CheckConstructorsResponse(Arrays.stream(superConstructors).map(binding -> new LspMethodBinding(binding)).toArray(LspMethodBinding[]::new), fields.stream().map(binding -> new LspVariableBinding(binding)).toArray(LspVariableBinding[]::new));
    // @formatter:on
    } catch (JavaModelException e) {
        JavaLanguageServerPlugin.logException("Failed to check constructor status", e);
    }
    return new CheckConstructorsResponse();
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaModelException(org.eclipse.jdt.core.JavaModelException) LspVariableBinding(org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) IField(org.eclipse.jdt.core.IField) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) LspMethodBinding(org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspMethodBinding)

Aggregations

LspVariableBinding (org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding)6 ArrayList (java.util.ArrayList)5 IJavaElement (org.eclipse.jdt.core.IJavaElement)5 JavaModelException (org.eclipse.jdt.core.JavaModelException)5 ASTNode (org.eclipse.jdt.core.dom.ASTNode)5 Arrays (java.util.Arrays)4 List (java.util.List)4 Optional (java.util.Optional)4 CoreException (org.eclipse.core.runtime.CoreException)4 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)4 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)4 IType (org.eclipse.jdt.core.IType)4 JavaLanguageServerPlugin (org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin)4 DiagnosticsHelper (org.eclipse.jdt.ls.core.internal.corrections.DiagnosticsHelper)4 CodeActionParams (org.eclipse.lsp4j.CodeActionParams)4 WorkspaceEdit (org.eclipse.lsp4j.WorkspaceEdit)4 Gson (com.google.gson.Gson)3 Set (java.util.Set)3 Stream (java.util.stream.Stream)3 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)3