示例#1
0
        ILocationContainer IWorker.References(string absFilename, long line, long column)
        {
            var param = new ReferenceParams();

            param.context.includeDeclaration = true;
            return(CommonProcessingOfGoto(absFilename, line, column, param, (ITextDocumentPositionParams arg) => client_.Send.TextDocumentReferences((ReferenceParams)arg)));
        }
示例#2
0
        public Task <VSInternalReferenceItem[]?> GetTextDocumentReferencesAsync(ReferenceParams referencesParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return(RequestDispatcher.ExecuteRequestAsync <ReferenceParams, VSInternalReferenceItem[]?>(Queue, Methods.TextDocumentReferencesName,
                                                                                                       referencesParams, _clientCapabilities, ClientName, cancellationToken));
        }
        public Task <Location[]> GetReferences(FilePath fileName, Position position, CancellationToken token)
        {
            if (!IsStarted)
            {
                return(Task.FromResult(new Location[0]));
            }

            if (!IsReferencesProvider)
            {
                Log("Get references is not supported by server for '{0}'. File: '{1}'", Methods.TextDocumentReferencesName, fileName);
                return(Task.FromResult(new Location [0]));
            }

            var message = new ReferenceParams {
                Context = new ReferenceContext {
                    IncludeDeclaration = true
                },
                TextDocument = TextDocumentIdentifierFactory.Create(fileName),
                Position     = position
            };

            Log("Sending '{0}'. File: '{1}'", Methods.TextDocumentReferencesName, fileName);

            return(jsonRpc.InvokeWithParameterObjectAsync(
                       Methods.TextDocumentReferences,
                       message,
                       token));
        }
        /// <summary>
        ///     Request References LocationInformation for a symbol location information at the specified document position.
        /// </summary>
        /// <param name="filePath">
        ///     The full file-system path of the text document.
        /// </param>
        /// <param name="line">
        ///     The target line (0-based).
        /// </param>
        /// <param name="column">
        ///     The target column (0-based).
        /// </param>
        /// <param name="includeDeclaration"></param>
        /// <param name="cancellationToken">
        ///     An optional <see cref="CancellationToken"/> that can be used to cancel the request.
        /// </param>
        /// <returns>
        ///     A <see cref="Task{TResult}"/> that resolves to the hover information or <c>null</c> if no hover information is available at the specified position.
        /// </returns>
        public async Task <LocationContainer> References(string filePath, int line, int column, bool includeDeclaration,
                                                         CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'filePath'.", nameof(filePath));
            }

            Uri documentUri = DocumentUri.FromFileSystemPath(filePath);

            var request = new ReferenceParams
            {
                TextDocument = new TextDocumentItem
                {
                    LanguageId = "C++",
                    Uri        = documentUri
                },
                Position = new Position
                {
                    Line      = line,
                    Character = column
                },
                Context = new ReferenceContext()
                {
                    IncludeDeclaration = includeDeclaration
                }
            };

            return(await Client.SendRequest <LocationContainer>(DocumentNames.References, request, cancellationToken).ConfigureAwait(false));
        }
示例#5
0
        public Task <VSReferenceItem[]> GetTextDocumentReferencesAsync(ReferenceParams referencesParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return(_requestHandlerProvider.ExecuteRequestAsync <ReferenceParams, VSReferenceItem[]>(_queue, Methods.TextDocumentReferencesName,
                                                                                                    referencesParams, _clientCapabilities, _clientName, cancellationToken));
        }
示例#6
0
        public override Task <LocationContainer> Handle(ReferenceParams request, CancellationToken cancellationToken)
        {
            ScriptFile scriptFile = _workspaceService.GetFile(request.TextDocument.Uri);

            SymbolReference foundSymbol =
                _symbolsService.FindSymbolAtLocation(
                    scriptFile,
                    request.Position.Line + 1,
                    request.Position.Character + 1);

            List <SymbolReference> referencesResult =
                _symbolsService.FindReferencesOfSymbol(
                    foundSymbol,
                    _workspaceService.ExpandScriptReferences(scriptFile),
                    _workspaceService);

            var locations = new List <Location>();

            if (referencesResult != null)
            {
                foreach (SymbolReference foundReference in referencesResult)
                {
                    locations.Add(new Location
                    {
                        Uri   = DocumentUri.From(foundReference.FilePath),
                        Range = GetRangeFromScriptRegion(foundReference.ScriptRegion)
                    });
                }
            }

            return(Task.FromResult(new LocationContainer(locations)));
        }
        public override async Task <LSP.VSReferenceItem[]> HandleRequestAsync(
            ReferenceParams referenceParams,
            ClientCapabilities clientCapabilities,
            string?clientName,
            CancellationToken cancellationToken)
        {
            Debug.Assert(clientCapabilities.HasVisualStudioLspCapability());

            var document = SolutionProvider.GetDocument(referenceParams.TextDocument, clientName);

            if (document == null)
            {
                return(Array.Empty <LSP.VSReferenceItem>());
            }

            var findUsagesService = document.GetRequiredLanguageService <IFindUsagesLSPService>();
            var position          = await document.GetPositionFromLinePositionAsync(
                ProtocolConversions.PositionToLinePosition(referenceParams.Position), cancellationToken).ConfigureAwait(false);

            var context = new FindUsagesLSPContext(document, position, _metadataAsSourceFileService, cancellationToken);

            // Finds the references for the symbol at the specific position in the document, reporting them via streaming to the LSP client.
            // TODO: Change back FAR to use streaming once the following LSP bug is fixed:
            // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1094786/
            await findUsagesService.FindReferencesAsync(document, position, context).ConfigureAwait(false);

            return(context.GetReferences().ToArray());
        }
        public override async Task <LSP.VSReferenceItem[]> HandleRequestAsync(ReferenceParams referenceParams, RequestContext context, CancellationToken cancellationToken)
        {
            Debug.Assert(context.ClientCapabilities.HasVisualStudioLspCapability());

            var document = SolutionProvider.GetDocument(referenceParams.TextDocument, context.ClientName);

            if (document == null)
            {
                return(Array.Empty <LSP.VSReferenceItem>());
            }

            var findUsagesService = document.GetRequiredLanguageService <IFindUsagesLSPService>();
            var position          = await document.GetPositionFromLinePositionAsync(
                ProtocolConversions.PositionToLinePosition(referenceParams.Position), cancellationToken).ConfigureAwait(false);

            var findUsagesContext = new FindUsagesLSPContext(
                referenceParams.PartialResultToken, document, position, _metadataAsSourceFileService, cancellationToken);

            // Finds the references for the symbol at the specific position in the document, reporting them via streaming to the LSP client.
            await findUsagesService.FindReferencesAsync(document, position, findUsagesContext).ConfigureAwait(false);

            await findUsagesContext.OnCompletedAsync().ConfigureAwait(false);

            // The results have already been reported to the client, so we don't need to return anything here.
            return(Array.Empty <LSP.VSReferenceItem>());
        }
示例#9
0
        public override Task <LocationContainer> Handle(ReferenceParams request, CancellationToken cancellationToken)
        {
            var result = this.symbolResolver.ResolveSymbol(request.TextDocument.Uri, request.Position);

            if (result == null)
            {
                return(Task.FromResult(new LocationContainer()));
            }

            if (result.Symbol is PropertySymbol)
            {
                // TODO: Implement for PropertySymbol
                return(Task.FromResult(new LocationContainer()));
            }

            var references = result.Context.Compilation.GetEntrypointSemanticModel()
                             .FindReferences(result.Symbol)
                             .Where(referenceSyntax => request.Context.IncludeDeclaration || !(referenceSyntax is INamedDeclarationSyntax))
                             .Select(referenceSyntax => new Location
            {
                Uri   = request.TextDocument.Uri,
                Range = PositionHelper.GetNameRange(result.Context.LineStarts, referenceSyntax),
            });

            return(Task.FromResult(new LocationContainer(references)));
        }
示例#10
0
        public override async Task <LSP.ReferenceItem[]?> HandleRequestAsync(ReferenceParams referenceParams, RequestContext context, CancellationToken cancellationToken)
        {
            Debug.Assert(context.ClientCapabilities.HasVisualStudioLspCapability());

            var document = context.Document;

            if (document == null)
            {
                return(Array.Empty <LSP.VSReferenceItem>());
            }

            using var progress = BufferedProgress.Create <VSReferenceItem>(referenceParams.PartialResultToken);

            var findUsagesService = document.GetRequiredLanguageService <IFindUsagesLSPService>();
            var position          = await document.GetPositionFromLinePositionAsync(
                ProtocolConversions.PositionToLinePosition(referenceParams.Position), cancellationToken).ConfigureAwait(false);

            var findUsagesContext = new FindUsagesLSPContext(
                progress, document, position, _metadataAsSourceFileService, cancellationToken);

            // Finds the references for the symbol at the specific position in the document, reporting them via streaming to the LSP client.
            await findUsagesService.FindReferencesAsync(document, position, findUsagesContext).ConfigureAwait(false);

            await findUsagesContext.OnCompletedAsync().ConfigureAwait(false);

            return(progress.GetValues());
        }
示例#11
0
        public async Task HandleRequestAsync_ProjectionNotFound_ReturnsNull()
        {
            // Arrange
            var documentManager = new TestDocumentManager();

            documentManager.AddDocument(Uri, Mock.Of <LSPDocumentSnapshot>());
            var requestInvoker          = Mock.Of <LSPRequestInvoker>();
            var projectionProvider      = Mock.Of <LSPProjectionProvider>();
            var documentMappingProvider = Mock.Of <LSPDocumentMappingProvider>();
            var progressListener        = Mock.Of <LSPProgressListener>();
            var referencesHandler       = new FindAllReferencesHandler(requestInvoker, documentManager, projectionProvider, documentMappingProvider, progressListener);

            referencesHandler.WaitForProgressNotificationTimeout = TestWaitForProgressNotificationTimeout;
            var referenceRequest = new ReferenceParams()
            {
                TextDocument = new TextDocumentIdentifier()
                {
                    Uri = Uri
                },
                Position = new Position(0, 1)
            };

            // Act
            var result = await referencesHandler.HandleRequestAsync(referenceRequest, new ClientCapabilities(), CancellationToken.None).ConfigureAwait(false);

            // Assert
            Assert.Null(result);
        }
示例#12
0
        public object[] OnTextDocumentFindReferences(ReferenceParams parameter, CancellationToken token)
        {
            this.traceSource.TraceEvent(TraceEventType.Information, 0, $"Received: {JToken.FromObject(parameter)}");
            var result = server.SendReferences(parameter, returnLocationsOnly: true, token: token);

            this.traceSource.TraceEvent(TraceEventType.Information, 0, $"Sent: {JToken.FromObject(result)}");
            return(result);
        }
        public Task <VSReferenceItem[]> FindAllReferencesAsync(ReferenceParams referenceParams, CancellationToken cancellationToken)
        {
            if (referenceParams is null)
            {
                throw new ArgumentNullException(nameof(referenceParams));
            }

            return(ExecuteRequestAsync <ReferenceParams, VSReferenceItem[]>(Methods.TextDocumentReferencesName, referenceParams, _clientCapabilities, cancellationToken));
        }
示例#14
0
        public async Task HandleRequestAsync_RemapFailure_DiscardsLocation()
        {
            // Arrange
            var progressReported = false;
            var documentManager  = new TestDocumentManager();

            documentManager.AddDocument(Uri, Mock.Of <LSPDocumentSnapshot>());

            var virtualCSharpUri = new Uri("C:/path/to/file.razor.g.cs");
            var csharpLocation   = GetReferenceItem(100, virtualCSharpUri);

            var(requestInvoker, progressListener) = MockServices(csharpLocation, out var token);

            var projectionResult = new ProjectionResult()
            {
                LanguageKind = RazorLanguageKind.CSharp,
            };
            var projectionProvider = new Mock <LSPProjectionProvider>();

            projectionProvider.Setup(p => p.GetProjectionAsync(It.IsAny <LSPDocumentSnapshot>(), It.IsAny <Position>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(projectionResult));

            var documentMappingProvider = new Mock <LSPDocumentMappingProvider>();

            documentMappingProvider.Setup(d => d.MapToDocumentRangesAsync(RazorLanguageKind.CSharp, Uri, new[] { csharpLocation.Location.Range }, It.IsAny <CancellationToken>())).
            Returns(Task.FromResult <RazorMapToDocumentRangesResponse>(null));

            var languageServiceBroker = Mock.Of <ILanguageServiceBroker2>();

            var referencesHandler = new FindAllReferencesHandler(requestInvoker, documentManager, projectionProvider.Object, documentMappingProvider.Object, progressListener);

            referencesHandler.WaitForProgressNotificationTimeout = TestWaitForProgressNotificationTimeout;

            var progressToken = new ProgressWithCompletion <object>((val) =>
            {
                var results = Assert.IsType <VSReferenceItem[]>(val);
                Assert.Empty(results);
                progressReported = true;
            });
            var referenceRequest = new ReferenceParams()
            {
                TextDocument = new TextDocumentIdentifier()
                {
                    Uri = Uri
                },
                Position           = new Position(10, 5),
                PartialResultToken = progressToken
            };

            // Act
            var result = await referencesHandler.HandleRequestAsync(referenceRequest, new ClientCapabilities(), token, CancellationToken.None).ConfigureAwait(false);

            // Assert
            Assert.True(progressReported);
            Assert.Empty(result);
        }
示例#15
0
        public async Task HandleRequestAsync_CSharpProjection_DoesNotRemapNonRazorFiles()
        {
            // Arrange
            var progressReported = false;
            var documentManager  = new TestDocumentManager();

            documentManager.AddDocument(Uri, Mock.Of <LSPDocumentSnapshot>());

            var externalCSharpUri      = new Uri("C:/path/to/someotherfile.cs");
            var externalCsharpLocation = GetReferenceItem(100, 100, 100, 100, externalCSharpUri);

            var(requestInvoker, progressListener) = MockServices(externalCsharpLocation, out var token);

            var projectionResult = new ProjectionResult()
            {
                LanguageKind = RazorLanguageKind.CSharp,
            };
            var projectionProvider = new Mock <LSPProjectionProvider>();

            projectionProvider.Setup(p => p.GetProjectionAsync(It.IsAny <LSPDocumentSnapshot>(), It.IsAny <Position>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(projectionResult));

            var documentMappingProvider = Mock.Of <LSPDocumentMappingProvider>();
            var languageServiceBroker   = Mock.Of <ILanguageServiceBroker2>();

            var referencesHandler = new FindAllReferencesHandler(requestInvoker, documentManager, projectionProvider.Object, documentMappingProvider, progressListener);

            referencesHandler.WaitForProgressNotificationTimeout = TestWaitForProgressNotificationTimeout;

            var progressToken = new ProgressWithCompletion <object>((val) =>
            {
                var results        = Assert.IsType <VSReferenceItem[]>(val);
                var actualLocation = Assert.Single(results);
                AssertVSReferenceItem(externalCsharpLocation, actualLocation);
                progressReported = true;
            });
            var referenceRequest = new ReferenceParams()
            {
                TextDocument = new TextDocumentIdentifier()
                {
                    Uri = Uri
                },
                Position           = new Position(10, 5),
                PartialResultToken = progressToken
            };

            // Act
            var result = await referencesHandler.HandleRequestAsync(referenceRequest, new ClientCapabilities(), token, CancellationToken.None).ConfigureAwait(false);

            // Assert
            Assert.True(progressReported);
        }
示例#16
0
        public override Task <LocationContainer> Handle(ReferenceParams request, CancellationToken cancellationToken)
        {
            var port = Workspace.GetPortAt(request.TextDocument.Uri, request.Position.ToLocation());

            if (port == null)
            {
                return(Task.FromResult(LocationContainer.From(Array.Empty <Location>())));
            }

            var refs = Workspace.FindReferencesTo(request.TextDocument.Uri, port);

            return(Task.FromResult(LocationContainer.From(refs.Select(o => new Location
            {
                Range = o.Span.ToRange(),
                Uri = request.TextDocument.Uri
            }))));
        }
        public void SimpleTest(string expected)
        {
            var model = new ReferenceParams {
                Context = new ReferenceContext {
                    IncludeDeclaration = true,
                },
                Position     = new Position(1, 2),
                TextDocument = new TextDocumentIdentifier(new Uri("file:///abc/123.cs"))
            };
            var result = Fixture.SerializeObject(model);

            result.Should().Be(expected);

            var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject <ReferenceParams>(expected);

            deresult.Should().BeEquivalentTo(model);
        }
示例#18
0
        public async Task HandleRequestAsync_ProgressListener_ReturnsNull()
        {
            // Arrange
            var documentManager = new TestDocumentManager();

            documentManager.AddDocument(Uri, Mock.Of <LSPDocumentSnapshot>());
            var requestInvoker = Mock.Of <LSPRequestInvoker>();

            var projectionResult = new ProjectionResult()
            {
                LanguageKind = RazorLanguageKind.CSharp,
            };
            var projectionProvider = new Mock <LSPProjectionProvider>();

            projectionProvider.Setup(p => p.GetProjectionAsync(It.IsAny <LSPDocumentSnapshot>(), It.IsAny <Position>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(projectionResult));

            Task onCompleted             = null;
            var  documentMappingProvider = Mock.Of <LSPDocumentMappingProvider>();
            var  progressListener        = Mock.Of <LSPProgressListener>(l =>
                                                                         l.TryListenForProgress(
                                                                             It.IsAny <string>(),
                                                                             It.IsAny <Func <JToken, CancellationToken, Task> >(),
                                                                             It.IsAny <TimeSpan>(),
                                                                             It.IsAny <CancellationToken>(),
                                                                             out onCompleted) == false);

            var referencesHandler = new FindAllReferencesHandler(requestInvoker, documentManager, projectionProvider.Object, documentMappingProvider, progressListener);

            referencesHandler.WaitForProgressNotificationTimeout = TestWaitForProgressNotificationTimeout;
            var referenceRequest = new ReferenceParams()
            {
                TextDocument = new TextDocumentIdentifier()
                {
                    Uri = Uri
                },
                Position = new Position(0, 1)
            };

            // Act
            var result = await referencesHandler.HandleRequestAsync(referenceRequest, new ClientCapabilities(), CancellationToken.None).ConfigureAwait(false);

            // Assert
            Assert.Null(result);
        }
示例#19
0
        public async Task <LocationContainer> Handle(ReferenceParams request, CancellationToken cancellationToken)
        {
            return(await Task.Run <LocationContainer>(() =>
            {
                bool includeDeclaration = request.Context.IncludeDeclaration;

                // Get the declaration key from the provided range and uri.
                var key = _languageServer.LastParse?.ScriptFromUri(request.TextDocument.Uri.ToUri())?.Elements.KeyFromPosition(request.Position).key;

                // Missing script or no definition found.
                if (key == null)
                {
                    return new LocationContainer();
                }

                // Get the locations.
                return new LocationContainer(_languageServer.LastParse.GetComponent <SymbolLinkComponent>().CallsFromDeclaration(key).Select(link => link.Location.ToLsLocation()));
            }));
        }
示例#20
0
        public async override Task <LocationContainer> Handle(ReferenceParams request, CancellationToken token)
        {
            var omnisharpRequest = new FindUsagesRequest
            {
                FileName          = Helpers.FromUri(request.TextDocument.Uri),
                Column            = Convert.ToInt32(request.Position.Character),
                Line              = Convert.ToInt32(request.Position.Line),
                OnlyThisFile      = false,
                ExcludeDefinition = !request.Context.IncludeDeclaration
            };

            var omnisharpResponse = await _findUsagesHandler.Handle(omnisharpRequest);

            return(omnisharpResponse.QuickFixes?.Select(x => new Location
            {
                Uri = Helpers.ToUri(x.FileName),
                Range = x.ToRange()
            }).ToArray());
        }
        // not working!
        public void GetMethodFastInvoke_MethodNameAndTypeArrayAndParameterModifier()
        {
            // need to set this up to test
            // http://msdn.microsoft.com/en-us/library/4s2kzbw8.aspx
            // can do this in a better type safe way!
            ReferenceParams <TestClass, object> fast = typeof(TestClass).GetMethodFastInvokeAsRefenceCall <TestClass, object>("TestMethodReferenceParams", BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, new Type[] { typeof(string).MakeByRefType(), typeof(string).MakeByRefType() }, null);
            TestClass tc     = new TestClass("injected");
            string    test   = string.Empty;
            string    param1 = "param1";
            string    param2 = "param2";

            object[] arr = new object[] { param1, param2 };

            //test = fast(tc, new object[] { param1, param2 }).ToString();
            fast(tc, ref arr);

            // Assert.AreEqual(test, "param1:end-param2:end-injected");
            Assert.AreEqual(arr[0], "param1:end");
            Assert.AreEqual(arr[1], "param2:end");
        }
        public Location[] FindReferences(ReferenceParams parameter)
        {
            TextDocumentItem currentTextDocument = FindDocument(parameter.TextDocument);

            if (currentTextDocument == null)
            {
                Log(string.Format("FindReferences: TextDocument.Uri does not match any document."));
                return(null);
            }

            string[] lines = currentTextDocument.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

            string item = GetReferenceItem(lines, parameter.Position);

            if (string.IsNullOrEmpty(item))
            {
                Log(string.Format("FindReferences: No item to search for."));
                return(null);
            }

            Log(string.Format("FindReferences: Searching for '{0}' in '{1}'", item, currentTextDocument.Uri));

            var locations = FindReferences(item, currentTextDocument.Uri, lines).ToList();

            if (textDocuments.Count > 1)
            {
                lock (textDocuments) {
                    foreach (var document in textDocuments.Where(doc => doc != currentTextDocument))
                    {
                        Log(string.Format("FindReferences: Searching for '{0}' in '{1}'", item, document.Uri));

                        lines = document.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                        var otherLocations = FindReferences(item, document.Uri, lines);
                        locations.AddRange(otherLocations);
                    }
                }
            }

            return(locations.ToArray());
        }
示例#23
0
        public async Task <LocationContainer> Handle(ReferenceParams request, CancellationToken cancellationToken)
        {
            return(await Task.Run(() =>
            {
                bool includeDeclaration = request.Context.IncludeDeclaration;

                var allSymbolLinks = _languageServer.LastParse?.GetComponent <SymbolLinkComponent>().GetSymbolLinks();
                if (allSymbolLinks == null)
                {
                    return new LocationContainer();
                }

                ICallable use = null;
                Location declaredAt = null;

                foreach (var pair in allSymbolLinks)
                {
                    foreach (var link in pair.Value)
                    {
                        if (link.Location.uri.Compare(request.TextDocument.Uri.ToUri()) && link.Location.range.IsInside(request.Position))
                        {
                            use = pair.Key;
                            declaredAt = link.Location;
                        }
                    }
                }

                if (use == null)
                {
                    return new LocationContainer();
                }

                return allSymbolLinks[use]
                .GetSymbolLinks(includeDeclaration)
                // Convert to Language Server API location.
                .Select(loc => loc.Location.ToLsLocation())
                .ToArray();
            }));
        }
示例#24
0
        public async Task <LocationContainer> Handle(ReferenceParams request, CancellationToken cancellationToken)
        {
            try
            {
                var scriptFile = _projectManager.GetScriptForFilePath(request.TextDocument.Uri.ToFilePath());
                if (scriptFile == null)
                {
                    return(null);
                }

                var identifier = scriptFile.Node.GetDescendantNodeOfTypeAtPosition <IdentifierNode>(request.Position.ToPosition());
                if (identifier == null)
                {
                    return(null);
                }

                var symbol = identifier.GetDeclaredOrReferencedSymbol();
                if (symbol == null)
                {
                    return(null);
                }

                var referencingNodes = await symbol.FindReferences(cancellationToken);

                return(referencingNodes.Select(node => new Location()
                {
                    Range = node.Range.ToRange(),
                    Uri = PathUtilities.ToFileUri(node.GetScriptFile().FilePath)
                }).ToArray());
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Error while handling request.");
            }

            return(null);
        }
示例#25
0
        public void GenerateRequest()
        {
            var procName = tables.Find(x => x.CDataTableName == tableInput.tableName);

            if (procName == null)
            {
                return;
            }

            var referenceParams = new ReferenceParams();

            referenceParams.Fileds     = GetFiledsRequest();
            referenceParams.Order      = GetOrderRequest();
            referenceParams.Limit      = tableInput.Limit;
            referenceParams.Page       = tableInput.Page;
            referenceParams.TableName  = procName.TableName;
            referenceParams.Conditions = GetConditionsRequest();

            var jsonParams = JsonConvert.SerializeObject(referenceParams, Formatting.Indented);

            RequestBody = $"proc_name={procName.ReferenceProcName}&params=\n{jsonParams}";

            this.StateHasChanged();
        }
示例#26
0
        public async Task HandleRequestAsync_HtmlProjection_InvokesHtmlLanguageServer()
        {
            // Arrange
            var lspFarEndpointCalled = false;
            var progressReported     = false;
            var expectedUri1         = new Uri("C:/path/to/file1.razor");
            var expectedUri2         = new Uri("C:/path/to/file2.razor");
            var expectedLocation1    = GetReferenceItem(5, expectedUri1);
            var expectedLocation2    = GetReferenceItem(10, expectedUri2);
            var documentManager      = new TestDocumentManager();

            documentManager.AddDocument(Uri, Mock.Of <LSPDocumentSnapshot>());

            var virtualHtmlUri1 = new Uri("C:/path/to/file1.razor__virtual.html");
            var virtualHtmlUri2 = new Uri("C:/path/to/file2.razor__virtual.html");
            var htmlLocation1   = GetReferenceItem(100, virtualHtmlUri1);
            var htmlLocation2   = GetReferenceItem(200, virtualHtmlUri2);

            var languageServiceBroker = Mock.Of <ILanguageServiceBroker2>();

            using var lspProgressListener = new DefaultLSPProgressListener(languageServiceBroker);

            var token          = Guid.NewGuid().ToString();
            var parameterToken = new JObject
            {
                { "token", token },
                { "value", JArray.FromObject(new[] { htmlLocation1, htmlLocation2 }) }
            };

            var requestInvoker = new Mock <LSPRequestInvoker>();

            requestInvoker
            .Setup(r => r.ReinvokeRequestOnServerAsync <TextDocumentPositionParams, VSReferenceItem[]>(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <TextDocumentPositionParams>(), It.IsAny <CancellationToken>()))
            .Callback <string, string, TextDocumentPositionParams, CancellationToken>((method, serverContentType, definitionParams, ct) =>
            {
                Assert.Equal(Methods.TextDocumentReferencesName, method);
                Assert.Equal(RazorLSPConstants.HtmlLSPContentTypeName, serverContentType);
                lspFarEndpointCalled = true;

                _ = lspProgressListener.ProcessProgressNotificationAsync(Methods.ProgressNotificationName, parameterToken);
            })
            .Returns(Task.FromResult(Array.Empty <VSReferenceItem>()));

            var projectionResult = new ProjectionResult()
            {
                LanguageKind = RazorLanguageKind.Html,
            };
            var projectionProvider = new Mock <LSPProjectionProvider>();

            projectionProvider.Setup(p => p.GetProjectionAsync(It.IsAny <LSPDocumentSnapshot>(), It.IsAny <Position>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(projectionResult));

            var remappingResult1 = new RazorMapToDocumentRangesResponse()
            {
                Ranges = new[] { expectedLocation1.Location.Range }
            };
            var remappingResult2 = new RazorMapToDocumentRangesResponse()
            {
                Ranges = new[] { expectedLocation2.Location.Range }
            };
            var documentMappingProvider = new Mock <LSPDocumentMappingProvider>();

            documentMappingProvider
            .Setup(d => d.MapToDocumentRangesAsync(RazorLanguageKind.Html, It.IsAny <Uri>(), It.IsAny <Range[]>(), It.IsAny <CancellationToken>()))
            .Returns <RazorLanguageKind, Uri, Range[], CancellationToken>((languageKind, uri, ranges, ct) => Task.FromResult(uri.LocalPath.Contains("file1") ? remappingResult1 : remappingResult2));

            var referencesHandler = new FindAllReferencesHandler(requestInvoker.Object, documentManager, projectionProvider.Object, documentMappingProvider.Object, lspProgressListener);

            referencesHandler.WaitForProgressNotificationTimeout = TestWaitForProgressNotificationTimeout;

            var progressToken = new ProgressWithCompletion <object>((val) =>
            {
                var results = Assert.IsType <VSReferenceItem[]>(val);
                Assert.Collection(results,
                                  a => AssertVSReferenceItem(expectedLocation1, a),
                                  b => AssertVSReferenceItem(expectedLocation2, b));
                progressReported = true;
            });
            var referenceRequest = new ReferenceParams()
            {
                TextDocument = new TextDocumentIdentifier()
                {
                    Uri = Uri
                },
                Position           = new Position(10, 5),
                PartialResultToken = progressToken
            };

            // Act
            var result = await referencesHandler.HandleRequestAsync(referenceRequest, new ClientCapabilities(), token, CancellationToken.None).ConfigureAwait(false);

            // Assert
            Assert.True(lspFarEndpointCalled);
            Assert.True(progressReported);
        }
示例#27
0
 public Task <VSReferenceItem[]> GetTextDocumentReferencesAsync(ReferenceParams referencesParams, CancellationToken cancellationToken)
 => _requestHandlerProvider.ExecuteRequestAsync <ReferenceParams, VSReferenceItem[]>(Methods.TextDocumentReferencesName,
                                                                                     referencesParams, _clientCapabilities, _clientName, cancellationToken);
示例#28
0
 /// <summary>
 /// Returns an array with all locations where the symbol at the given position - if any - is referenced.
 /// Returns null if the given file is listed as to be ignored,
 /// or if some parameters are unspecified (null),
 /// or if the specified position is not a valid position within the currently processed file content,
 /// or if no symbol exists at the specified position at this time.
 /// </summary>
 public Location[] SymbolReferences(ReferenceParams param) =>
 ValidFileUri(param?.TextDocument?.Uri) && !IgnoreFile(param.TextDocument.Uri) ? this.Projects.SymbolReferences(param) : null;
示例#29
0
        public async Task HandleRequestAsync_LargeProject_InvokesCSharpLanguageServer()
        {
            // Validates batching mechanism for the progress notification on large projects

            // Arrange
            var lspFarEndpointCalled = false;

            const int BATCH_SIZE     = 10;
            const int NUM_BATCHES    = 10;
            const int NUM_DOCUMENTS  = BATCH_SIZE * NUM_BATCHES;
            const int MAPPING_OFFSET = 10;

            var expectedUris             = new Uri[NUM_DOCUMENTS];
            var virtualUris              = new Uri[NUM_DOCUMENTS];
            var expectedReferences       = new VSReferenceItem[NUM_BATCHES][];
            var csharpUnmappedReferences = new VSReferenceItem[NUM_BATCHES][];
            var parameterTokens          = new JObject[NUM_BATCHES];

            var token = Guid.NewGuid().ToString();

            var documentNumber = 0;

            for (var batch = 0; batch < NUM_BATCHES; ++batch)
            {
                expectedReferences[batch]       = new VSReferenceItem[BATCH_SIZE];
                csharpUnmappedReferences[batch] = new VSReferenceItem[BATCH_SIZE];

                for (var documentInBatch = 0; documentInBatch < BATCH_SIZE; ++documentInBatch)
                {
                    expectedUris[documentNumber] = new Uri($"C:/path/to/file{documentNumber}.razor");
                    virtualUris[documentNumber]  = new Uri($"C:/path/to/file{documentNumber}.razor.g.cs");
                    expectedReferences[batch][documentInBatch] = GetReferenceItem(documentNumber, expectedUris[documentNumber]);

                    var umappedOffset = documentNumber * MAPPING_OFFSET;
                    csharpUnmappedReferences[batch][documentInBatch] = GetReferenceItem(umappedOffset, virtualUris[documentNumber]);
                    documentNumber++;
                }

                parameterTokens[batch] = new JObject
                {
                    { "token", token },
                    { "value", JArray.FromObject(csharpUnmappedReferences[batch]) }
                };
            }

            var documentManager = new TestDocumentManager();

            documentManager.AddDocument(Uri, Mock.Of <LSPDocumentSnapshot>());

            var languageServiceBroker = Mock.Of <ILanguageServiceBroker2>();

            using var lspProgressListener = new DefaultLSPProgressListener(languageServiceBroker);

            var requestInvoker = new Mock <LSPRequestInvoker>();

            requestInvoker
            .Setup(r => r.ReinvokeRequestOnServerAsync <TextDocumentPositionParams, VSReferenceItem[]>(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <TextDocumentPositionParams>(), It.IsAny <CancellationToken>()))
            .Callback <string, string, TextDocumentPositionParams, CancellationToken>((method, serverContentType, definitionParams, ct) =>
            {
                Assert.Equal(Methods.TextDocumentReferencesName, method);
                Assert.Equal(RazorLSPConstants.CSharpContentTypeName, serverContentType);
                lspFarEndpointCalled = true;

                for (var i = 0; i < NUM_BATCHES; ++i)
                {
                    _ = lspProgressListener.ProcessProgressNotificationAsync(Methods.ProgressNotificationName, parameterTokens[i]);
                }
            })
            .Returns(Task.FromResult(Array.Empty <VSReferenceItem>()));

            var projectionResult = new ProjectionResult()
            {
                LanguageKind = RazorLanguageKind.CSharp,
            };
            var projectionProvider = new Mock <LSPProjectionProvider>();

            projectionProvider.Setup(p => p.GetProjectionAsync(It.IsAny <LSPDocumentSnapshot>(), It.IsAny <Position>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(projectionResult));

            var documentMappingProvider = new Mock <LSPDocumentMappingProvider>();

            documentMappingProvider
            .Setup(d => d.MapToDocumentRangesAsync(RazorLanguageKind.CSharp, It.IsAny <Uri>(), It.IsAny <Range[]>(), It.IsAny <CancellationToken>()))
            .Returns <RazorLanguageKind, Uri, Range[], CancellationToken>((languageKind, uri, ranges, ct) =>
            {
                var unmappedPosition = ranges[0].Start.Line;
                var mappedPosition   = unmappedPosition / MAPPING_OFFSET;

                var mappedRange = new Range()
                {
                    Start = new Position(mappedPosition, mappedPosition),
                    End   = new Position(mappedPosition, mappedPosition)
                };

                var response = new RazorMapToDocumentRangesResponse()
                {
                    Ranges = new[] { mappedRange }
                };

                return(Task.FromResult(response));
            });

            var referencesHandler = new FindAllReferencesHandler(requestInvoker.Object, documentManager, projectionProvider.Object, documentMappingProvider.Object, lspProgressListener);

            referencesHandler.WaitForProgressNotificationTimeout = TestWaitForProgressNotificationTimeout;

            var progressBatchesReported = new ConcurrentBag <VSReferenceItem[]>();
            var progressToken           = new ProgressWithCompletion <object>((val) =>
            {
                var results = Assert.IsType <VSReferenceItem[]>(val);
                Assert.Equal(BATCH_SIZE, results.Length);
                progressBatchesReported.Add(results);
            });
            var referenceRequest = new ReferenceParams()
            {
                TextDocument = new TextDocumentIdentifier()
                {
                    Uri = Uri
                },
                Position           = new Position(10, 5),
                PartialResultToken = progressToken
            };

            // Act
            var result = await referencesHandler.HandleRequestAsync(referenceRequest, new ClientCapabilities(), token, CancellationToken.None).ConfigureAwait(false);

            // Assert
            Assert.True(lspFarEndpointCalled);

            var sortedBatchesReported = progressBatchesReported.ToList();

            sortedBatchesReported.Sort((VSReferenceItem[] a, VSReferenceItem[] b) =>
            {
                var indexA = a[0].Location.Range.Start.Character;
                var indexB = b[0].Location.Range.Start.Character;
                return(indexA.CompareTo(indexB));
            });

            Assert.Equal(NUM_BATCHES, sortedBatchesReported.Count);

            for (var batch = 0; batch < NUM_BATCHES; ++batch)
            {
                for (var documentInBatch = 0; documentInBatch < BATCH_SIZE; ++documentInBatch)
                {
                    AssertVSReferenceItem(
                        expectedReferences[batch][documentInBatch],
                        sortedBatchesReported[batch][documentInBatch]);
                }
            }
        }
示例#30
0
 public override TextDocumentIdentifier?GetTextDocumentIdentifier(ReferenceParams request) => request.TextDocument;