示例#1
0
        public async Task <QuickFixResponse> Handle(FindImplementationsRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);
            var response = new QuickFixResponse();

            if (document != null)
            {
                var semanticModel = await document.GetSemanticModelAsync();

                var sourceText = await document.GetTextAsync();

                var position   = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
                var symbol     = SymbolFinder.FindSymbolAtPosition(semanticModel, position, _workspace);
                var quickFixes = new List <QuickFix>();

                var implementations = await SymbolFinder.FindImplementationsAsync(symbol, _workspace.CurrentSolution);
                await AddQuickFixes(quickFixes, implementations);

                var overrides = await SymbolFinder.FindOverridesAsync(symbol, _workspace.CurrentSolution);
                await AddQuickFixes(quickFixes, overrides);

                var derivedTypes = await GetDerivedTypes(symbol);
                await AddQuickFixes(quickFixes, derivedTypes);

                response = new QuickFixResponse(quickFixes.OrderBy(q => q.FileName)
                                                .ThenBy(q => q.Line)
                                                .ThenBy(q => q.Column));
            }

            return(response);
        }
        public async Task <FixUsingsResponse> Handle(FixUsingsRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);
            var response = new FixUsingsResponse();

            if (document != null)
            {
                var fixUsingsResponse = await new FixUsingsWorker(_loggerFactory, _loader).FixUsings(_workspace.CurrentSolution, _codeActionProviders, request.FileName);
                response.AmbiguousResults = fixUsingsResponse.AmbiguousResults;

                if (request.ApplyTextChanges)
                {
                    _workspace.TryApplyChanges(fixUsingsResponse.Solution);
                }

                if (!request.WantsTextChanges)
                {
                    // return the new document
                    var docText = await fixUsingsResponse.Solution.GetDocument(document.Id).GetTextAsync();

                    response.Buffer = docText.ToString();
                }
                else
                {
                    // return the text changes
                    var changes = await fixUsingsResponse.Solution.GetDocument(document.Id).GetTextChangesAsync(document);

                    response.Changes = await LinePositionSpanTextChange.Convert(document, changes);
                }
            }

            return(response);
        }
示例#3
0
        public async Task <FixUsingsResponse> Handle(FixUsingsRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);
            var response = new FixUsingsResponse();

            if (document != null)
            {
                response = await new FixUsingsWorker().FixUsings(_workspace, _codeActionProviders, document);

                if (!request.WantsTextChanges)
                {
                    // return the new document
                    var docText = await _workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync();

                    response.Buffer = docText.ToString();
                }
                else
                {
                    // return the text changes
                    var changes = await _workspace.CurrentSolution.GetDocument(document.Id).GetTextChangesAsync(document);

                    response.Changes = await LinePositionSpanTextChange.Convert(document, changes);
                }
            }

            return(response);
        }
示例#4
0
        public async Task <TypeLookupResponse> Handle(TypeLookupRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);
            var response = new TypeLookupResponse();

            if (document != null)
            {
                var semanticModel = await document.GetSemanticModelAsync();

                var sourceText = await document.GetTextAsync();

                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line, request.Column));
                var symbol   = await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, _workspace);

                if (symbol != null)
                {
                    //non regular C# code semantics (interactive, script) don't allow namespaces
                    if (document.SourceCodeKind == SourceCodeKind.Regular && symbol.Kind == SymbolKind.NamedType && !symbol.ContainingNamespace.IsGlobalNamespace)
                    {
                        response.Type = $"{symbol.ContainingNamespace.ToDisplayString()}.{symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)}";
                    }
                    else
                    {
                        response.Type = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
                    }

                    if (request.IncludeDocumentation)
                    {
                        response.Documentation = DocumentationConverter.ConvertDocumentation(symbol.GetDocumentationCommentXml(), _formattingOptions.NewLine);
                    }
                }
            }
            return(response);
        }
示例#5
0
        public static async Task <ISymbol> SymbolFromQuickFix(OmnisharpWorkspace workspace, QuickFix result)
        {
            var document   = workspace.GetDocument(result.FileName);
            var sourceText = await document.GetTextAsync();

            var position      = sourceText.Lines.GetPosition(new LinePosition(result.Line - 1, result.Column - 1));
            var semanticModel = await document.GetSemanticModelAsync();

            return(SymbolFinder.FindSymbolAtPosition(semanticModel, position, workspace));
        }
示例#6
0
        public async Task <QuickFixResponse> Handle(FindUsagesRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);
            var response = new QuickFixResponse();

            if (document != null)
            {
                var locations     = new List <Location>();
                var semanticModel = await document.GetSemanticModelAsync();

                var sourceText = await document.GetTextAsync();

                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line, request.Column));
                var symbol   = await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, _workspace);

                var definition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _workspace.CurrentSolution);

                var usages = request.OnlyThisFile
                    ? await SymbolFinder.FindReferencesAsync(definition ?? symbol, _workspace.CurrentSolution, ImmutableHashSet.Create(document))
                    : await SymbolFinder.FindReferencesAsync(definition ?? symbol, _workspace.CurrentSolution);

                foreach (var usage in usages.Where(u => u.Definition.CanBeReferencedByName || (symbol as IMethodSymbol)?.MethodKind == MethodKind.Constructor))
                {
                    foreach (var location in usage.Locations)
                    {
                        locations.Add(location.Location);
                    }

                    if (!request.ExcludeDefinition)
                    {
                        var definitionLocations = usage.Definition.Locations
                                                  .Where(loc => loc.IsInSource && (!request.OnlyThisFile || loc.SourceTree.FilePath == request.FileName));

                        foreach (var location in definitionLocations)
                        {
                            locations.Add(location);
                        }
                    }
                }

                var quickFixTasks = locations.Distinct().Select(async l => await QuickFixHelper.GetQuickFix(_workspace, l));

                var quickFixes = await Task.WhenAll(quickFixTasks);

                response = new QuickFixResponse(quickFixes.Distinct()
                                                .OrderBy(q => q.FileName)
                                                .ThenBy(q => q.Line)
                                                .ThenBy(q => q.Column));
            }

            return(response);
        }
        public static async Task<IEnumerable<CodeAction>> GetActions(OmnisharpWorkspace workspace, IEnumerable<ICodeActionProvider> codeActionProviders, ILogger logger, ICodeActionRequest request)
        {
            var actions = new List<CodeAction>();
            var originalDocument = workspace.GetDocument(request.FileName);
            if (originalDocument == null)
            {
                return actions;
            }

            var refactoringContext = await GetRefactoringContext(originalDocument, request, actions);
            var codeFixContext = await GetCodeFixContext(originalDocument, request, actions);
            await CollectRefactoringActions(codeActionProviders, logger, refactoringContext);
            await CollectCodeFixActions(codeActionProviders, logger, codeFixContext);
            actions.Reverse();
            return actions;
        }
        public async Task <CodeFormatResponse> Handle(CodeFormatRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);

            if (document == null)
            {
                return(null);
            }

            var newText = await OmniSharp.Roslyn.CSharp.Workers.Format.Formatting.GetFormattedDocument(_workspace, _options, document);

            return(new CodeFormatResponse()
            {
                Buffer = newText
            });
        }
示例#9
0
        private async Task <CodeRefactoringContext?> GetContext(CodeActionRequest request, List <CodeAction> actionsDestination)
        {
            var document = _workspace.GetDocument(request.FileName);

            if (document != null)
            {
                var sourceText = await document.GetTextAsync();

                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
                var location = new TextSpan(position, 1);
                return(new CodeRefactoringContext(document, location, (a) => actionsDestination.Add(a), CancellationToken.None));
            }

            //todo, handle context creation issues
            return(null);
        }
示例#10
0
        Task <object> IProjectSystem.GetProjectModel(string path)
        {
            var document = _workspace.GetDocument(path);

            if (document == null)
            {
                return(Task.FromResult <object>(null));
            }

            var project = GetProject(document.Project.FilePath);

            if (project == null)
            {
                return(Task.FromResult <object>(null));
            }

            return(Task.FromResult <object>(new MSBuildProject(project)));
        }
示例#11
0
        public async Task <FormatRangeResponse> Handle(FormatAfterKeystrokeRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);

            if (document == null)
            {
                return(null);
            }

            var lines    = (await document.GetSyntaxTreeAsync()).GetText().Lines;
            int position = lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
            var changes  = await OmniSharp.Roslyn.CSharp.Workers.Format.Formatting.GetFormattingChangesAfterKeystroke(_workspace, _options, document, position, request.Char);

            return(new FormatRangeResponse()
            {
                Changes = changes
            });
        }
示例#12
0
        public Task <object> GetProjectModel(string path)
        {
            _logger.LogDebug($"GetProjectModel {path}");
            var document = _omnisharpWorkspace.GetDocument(path);

            if (document == null)
            {
                return(Task.FromResult <object>(null));
            }

            var projectPath = document.Project.FilePath;

            _logger.LogDebug($"GetProjectModel {path}=>{projectPath}");
            var projectEntry       = _projectStates.GetOrAddEntry(projectPath);
            var projectInformation = new DotNetProjectInformation(projectEntry);

            return(Task.FromResult <object>(projectInformation));
        }
        public async Task <FormatRangeResponse> Handle(FormatRangeRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);

            if (document == null)
            {
                return(null);
            }

            var lines   = (await document.GetSyntaxTreeAsync()).GetText().Lines;
            var start   = lines.GetPosition(new LinePosition(request.Line, request.Column));
            var end     = lines.GetPosition(new LinePosition(request.EndLine, request.EndColumn));
            var changes = await OmniSharp.Roslyn.CSharp.Workers.Format.Formatting.GetFormattingChangesForRange(_workspace, _options, document, start, end);

            return(new FormatRangeResponse()
            {
                Changes = changes
            });
        }
        private async Task <IEnumerable <CodeAction> > GetActions(ICodeActionRequest request)
        {
            var actions = new List <CodeAction>();

            _originalDocument = _workspace.GetDocument(request.FileName);
            if (_originalDocument == null)
            {
                return(actions);
            }

            var refactoringContext = await GetRefactoringContext(request, actions);

            var codeFixContext = await GetCodeFixContext(request, actions);

            await CollectRefactoringActions(refactoringContext);
            await CollectCodeFixActions(codeFixContext);

            actions.Reverse();
            return(actions);
        }
示例#15
0
        public static async Task <IEnumerable <CodeAction> > GetActions(OmnisharpWorkspace workspace, IEnumerable <ICodeActionProvider> codeActionProviders, ILogger logger, ICodeActionRequest request)
        {
            var actions          = new List <CodeAction>();
            var originalDocument = workspace.GetDocument(request.FileName);

            if (originalDocument == null)
            {
                return(actions);
            }

            var refactoringContext = await GetRefactoringContext(originalDocument, request, actions);

            var codeFixContext = await GetCodeFixContext(originalDocument, request, actions);

            await CollectRefactoringActions(codeActionProviders, logger, refactoringContext);
            await CollectCodeFixActions(codeActionProviders, logger, codeFixContext);

            actions.Reverse();
            return(actions);
        }
示例#16
0
        public Task <object> GetProjectModel(string path)
        {
            _logger.LogDebug($"GetProjectModel {path}");
            var document = _omnisharpWorkspace.GetDocument(path);

            if (document == null)
            {
                return(Task.FromResult <object>(null));
            }

            var projectPath = document.Project.FilePath;

            _logger.LogDebug($"GetProjectModel {path}=>{projectPath}");
            //var projectInformation = _projectStates.Get(projectPath).FirstOrDefault()?.Information;
            //if (projectInformation == null)
            //{
            return(Task.FromResult <object>(null));
            //}

            //return Task.FromResult<object>(new DotNetProjectInformation(projectPath, projectInformation));
        }
示例#17
0
        public async Task <QuickFixResponse> Handle(GotoRegionRequest request)
        {
            var regions  = new List <QuickFix>();
            var document = _workspace.GetDocument(request.FileName);

            if (document != null)
            {
                var root = await document.GetSyntaxRootAsync();

                var regionTrivias = root.DescendantNodesAndTokens()
                                    .Where(node => node.HasLeadingTrivia)
                                    .SelectMany(node => node.GetLeadingTrivia())
                                    .Where(x => (x.RawKind == (int)SyntaxKind.RegionDirectiveTrivia ||
                                                 x.RawKind == (int)SyntaxKind.EndRegionDirectiveTrivia));

                foreach (var regionTrivia in regionTrivias.Distinct())
                {
                    regions.Add(await QuickFixHelper.GetQuickFix(_workspace, regionTrivia.GetLocation()));
                }
            }
            return(new QuickFixResponse(regions));
        }
示例#18
0
        public async Task <GetTestCommandResponse> Handle(TestCommandRequest request)
        {
            var quickFixes = new List <QuickFix>();

            var document = _workspace.GetDocument(request.FileName);
            var response = new GetTestCommandResponse();

            if (document != null)
            {
                var semanticModel = await document.GetSemanticModelAsync();

                var syntaxTree = semanticModel.SyntaxTree;
                var sourceText = await document.GetTextAsync();

                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line, request.Column));
                var node     = syntaxTree.GetRoot().FindToken(position).Parent;

                SyntaxNode method = node.FirstAncestorOrSelf <MethodDeclarationSyntax>();
                SyntaxNode type   = GetTypeDeclaration(node);

                if (type == null)
                {
                    return(response);
                }

                var symbol  = semanticModel.GetDeclaredSymbol(method ?? type);
                var context = new TestContext(document.Project.FilePath, request.Type, symbol);

                response.TestCommand = _testCommandProviders
                                       .Select(t => t.GetTestCommand(context))
                                       .FirstOrDefault(c => c != null);

                var directory = Path.GetDirectoryName(document.Project.FilePath);
                response.Directory = directory;
            }

            return(response);
        }
示例#19
0
        public async Task <RenameResponse> Handle(RenameRequest request)
        {
            var response = new RenameResponse();

            var document = _workspace.GetDocument(request.FileName);

            if (document != null)
            {
                var sourceText = await document.GetTextAsync();

                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line, request.Column));

                var symbol = await SymbolFinder.FindSymbolAtPositionAsync(document, position);

                Solution solution = _workspace.CurrentSolution;

                if (symbol != null)
                {
                    try
                    {
                        solution = await Renamer.RenameSymbolAsync(solution, symbol, request.RenameTo, _workspace.Options);
                    }
                    catch (ArgumentException e)
                    {
                        response.ErrorMessage = e.Message;
                    }
                }

                var changes         = new Dictionary <string, ModifiedFileResponse>();
                var solutionChanges = solution.GetChanges(_workspace.CurrentSolution);

                foreach (var projectChange in solutionChanges.GetProjectChanges())
                {
                    foreach (var changedDocumentId in projectChange.GetChangedDocuments())
                    {
                        var changedDocument = solution.GetDocument(changedDocumentId);

                        ModifiedFileResponse modifiedFileResponse;
                        if (!changes.TryGetValue(changedDocument.FilePath, out modifiedFileResponse))
                        {
                            modifiedFileResponse = new ModifiedFileResponse(changedDocument.FilePath);
                            changes[changedDocument.FilePath] = modifiedFileResponse;
                        }

                        if (!request.WantsTextChanges)
                        {
                            var changedText = await changedDocument.GetTextAsync();

                            modifiedFileResponse.Buffer = changedText.ToString();
                        }
                        else
                        {
                            var originalDocument = _workspace.CurrentSolution.GetDocument(changedDocumentId);
                            var textChanges      = await changedDocument.GetTextChangesAsync(originalDocument);

                            var linePositionSpanTextChanges = await LinePositionSpanTextChange.Convert(originalDocument, textChanges);

                            modifiedFileResponse.Changes = modifiedFileResponse.Changes != null
                                ? modifiedFileResponse.Changes.Union(linePositionSpanTextChanges)
                                : linePositionSpanTextChanges;
                        }
                    }
                }

                if (request.ApplyTextChanges)
                {
                    // Attempt to update the workspace
                    if (_workspace.TryApplyChanges(solution))
                    {
                        response.Changes = changes.Values;
                    }
                }
                else
                {
                    response.Changes = changes.Values;
                }
            }

            return(response);
        }
示例#20
0
        public async Task <GotoDefinitionResponse> Handle(GotoDefinitionRequest request)
        {
            var quickFixes = new List <QuickFix>();

            var document = _workspace.GetDocument(request.FileName);
            var response = new GotoDefinitionResponse();

            if (document != null)
            {
                var semanticModel = await document.GetSemanticModelAsync();

                var syntaxTree = semanticModel.SyntaxTree;
                var sourceText = await document.GetTextAsync();

                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
                var symbol   = SymbolFinder.FindSymbolAtPosition(semanticModel, position, _workspace);

                if (symbol != null)
                {
                    var location = symbol.Locations.First();

                    if (location.IsInSource)
                    {
                        var lineSpan = symbol.Locations.First().GetMappedLineSpan();
                        response = new GotoDefinitionResponse
                        {
                            FileName = lineSpan.Path,
                            Line     = lineSpan.StartLinePosition.Line + 1,
                            Column   = lineSpan.StartLinePosition.Character + 1
                        };
                    }
                    else if (location.IsInMetadata && request.WantMetadata)
                    {
                        var cancellationSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(request.Timeout));
                        var metadataDocument   = await _metadataHelper.GetDocumentFromMetadata(document.Project, symbol, cancellationSource.Token);

                        if (metadataDocument != null)
                        {
                            cancellationSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(request.Timeout));
                            var metadataLocation = await _metadataHelper.GetSymbolLocationFromMetadata(symbol, metadataDocument, cancellationSource.Token);

                            var lineSpan = metadataLocation.GetMappedLineSpan();

                            response = new GotoDefinitionResponse
                            {
                                Line           = lineSpan.StartLinePosition.Line + 1,
                                Column         = lineSpan.StartLinePosition.Character + 1,
                                MetadataSource = new MetadataSource()
                                {
                                    AssemblyName = symbol.ContainingAssembly.Name,
                                    ProjectName  = document.Project.Name,
                                    TypeName     = _metadataHelper.GetSymbolName(symbol)
                                },
                            };
                        }
                    }
                }
            }

            return(response);
        }
示例#21
0
 public static async Task<ISymbol> SymbolFromQuickFix(OmnisharpWorkspace workspace, QuickFix result)
 {
     var document = workspace.GetDocument(result.FileName);
     var sourceText = await document.GetTextAsync();
     var position = sourceText.Lines.GetPosition(new LinePosition(result.Line - 1, result.Column - 1));
     var semanticModel = await document.GetSemanticModelAsync();
     return SymbolFinder.FindSymbolAtPosition(semanticModel, position, workspace);
 }