public async Task Handle_ResolvesTagHelperElementCompletionItems()
        {
            // Arrange
            var documentPath            = "C:/path/to/document.cshtml";
            var tagHelperCompletionItem = new CompletionItem()
            {
                InsertText = "Test"
            };
            var tagHelperCompletionService = Mock.Of <TagHelperCompletionService>(
                service => service.GetCompletionsAt(It.IsAny <SourceSpan>(), It.IsAny <RazorCodeDocument>()) == new[] { tagHelperCompletionItem });
            var codeDocument       = CreateCodeDocument("<");
            var documentResolver   = CreateDocumentResolver(documentPath, codeDocument);
            var completionEndpoint = new RazorCompletionEndpoint(Dispatcher, documentResolver, CompletionFactsService, tagHelperCompletionService, TagHelperDescriptionFactory, LoggerFactory);
            var request            = new CompletionParams()
            {
                TextDocument = new TextDocumentIdentifier(new Uri(documentPath)),
                Position     = new Position(0, 1)
            };

            // Act
            var completionList = await Task.Run(() => completionEndpoint.Handle(request, default));

            // Assert
            Assert.Contains(completionList, item => item.InsertText == "Test");
        }
Exemplo n.º 2
0
        public async Task <CompletionList> Handle(CompletionParams request, CancellationToken token)
        {
            var(document, position) = _workspace.GetLogicalDocument(request);

            var completionService = document.GetLanguageService <CompletionService>();

            Microsoft.CodeAnalysis.Completion.CompletionTrigger trigger;
            if (request.Context.TriggerKind == OmniSharp.Extensions.LanguageServer.Protocol.Models.CompletionTriggerKind.TriggerCharacter)
            {
                trigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger.CreateInsertionTrigger(request.Context.TriggerCharacter[0]);
            }
            else
            {
                trigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger.Invoke;
            }

            var completionList = await completionService.GetCompletionsAsync(document, position, trigger, cancellationToken : token);

            if (completionList == null)
            {
                return(new CompletionList());
            }

            var completionItems = completionList.Items
                                  .Select(x => ConvertCompletionItem(document, completionList.Rules, x))
                                  .ToArray();

            return(completionItems);
        }
Exemplo n.º 3
0
        public async Task <CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken)
        {
            _router.Window.LogMessage(new LogMessageParams()
            {
                Type    = MessageType.Log,
                Message = "Proto file completion list request at line: " + (request.Position.Line + 1),
            });

            _threadManager.AssertBackgroundThread();

            var document = await Task.Factory.StartNew(
                () => {
                _snapshotManager.TryResolveDocument(request.TextDocument.Uri.AbsolutePath, out var doc);
                return(doc);
            },
                CancellationToken.None,
                TaskCreationOptions.None,
                _threadManager.ForegroundScheduler);

            var syntaxTree = await document.GetSyntaxTreeAsync();

            var completionItems = new List <CompletionItem>();

            foreach (var completionItemProvider in _completionItemProviders)
            {
                var owner = syntaxTree.Root.GetNodeAt((int)request.Position.Line, (int)request.Position.Character);
                var resolvedCompletions = completionItemProvider.GetCompletionItems(owner, request.Position, syntaxTree);
                completionItems.AddRange(resolvedCompletions);
            }

            var completionList = new CompletionList(completionItems);

            return(completionList);
        }
        private bool IsSimpleImplicitExpression(CompletionParams request, LSPDocumentSnapshot documentSnapshot, TextExtent?wordExtent)
        {
            if (string.Equals(request.Context.TriggerCharacter, "@", StringComparison.Ordinal))
            {
                // Completion was triggered with `@` this is always a simple implicit expression
                return(true);
            }

            if (wordExtent == null)
            {
                return(false);
            }

            if (!wordExtent.Value.IsSignificant)
            {
                // Word is only whitespace, definitely not an implicit expresison
                return(false);
            }

            // We need to look at the item before the word because `@` at the beginning of a word is not encapsulated in that word.
            var leadingWordCharacterIndex = Math.Max(0, wordExtent.Value.Span.Start.Position - 1);
            var leadingWordCharacter      = documentSnapshot.Snapshot[leadingWordCharacterIndex];

            if (leadingWordCharacter == '@')
            {
                // This means that completion was requested at something like @for|e and the word was "fore" with the previous character index being "@"
                return(true);
            }

            return(false);
        }
Exemplo n.º 5
0
        public async Task <CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken)
        {
            var text   = _workspaceService.GetMarineFileBuffer(request.TextDocument.Uri.Path);
            var tokens = new LexicalAnalyzer().GetTokens(text);
            var result = new SyntaxAnalyzer().Parse(tokens);

            var tasks = new List <Task <IEnumerable <CompletionItem> > >();
            FuncDefinitionAst currentFuncDefAst = null;

            if (result.programAst != null)
            {
                currentFuncDefAst = await Task.Run(() => GetCurrentFunctionAst(result.programAst, request.Position),
                                                   cancellationToken);

                if (currentFuncDefAst != null)
                {
                    tasks.Add(Task.Run(() => CreateFunctions(result.programAst), cancellationToken));

                    tasks.Add(Task.Run(() => CreateFunctionParamaters(currentFuncDefAst), cancellationToken));
                    tasks.Add(Task.Run(() => CreateVariables(currentFuncDefAst, request.Position), cancellationToken));

                    tasks.Add(Task.Run(CreateKeywords, cancellationToken));
                }
            }

            tasks.Add(Task.Run(() => CreateSnippets(currentFuncDefAst), cancellationToken));

            return(new CompletionList((await Task.WhenAll(tasks)).SelectMany(e => e)));
        }
Exemplo n.º 6
0
        internal virtual void Completion(LanguageClient client)
        {
            RequestId requestId;
            {
                var param = new CompletionParams();
#if false
                param.context.triggerKind      = CompletionTriggerKind.TriggerCharacter;
                param.context.triggerCharacter = ".";
#else
                param.context.triggerKind      = CompletionTriggerKind.TriggerCharacter;
                param.context.triggerCharacter = ".";
#endif
                param.textDocument.uri   = sourceUri.AbsoluteUri;
                param.position.line      = compilationPosition.line;
                param.position.character = compilationPosition.character;

                requestId = client.Send.TextDocumentCompletion(param);
            }
            var millisecondsTimeout = 6000;
            //Console.WriteLine(string.Format("millisecondsTimeout={0}", millisecondsTimeout));
            var completion = (CompletionList)client.QueryResponse(requestId, millisecondsTimeout).item;
            if (completion == null)
            {
                Console.WriteLine("Compilation is failed or timeout.");
                //throw new Exception();
            }
            else
            {
                Console.WriteLine("[Success]completion.items.Length={0}", completion.items.Length);
            }
        }
        public async Task <CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken)
        {
            var documentPath = request.TextDocument.Uri.ToUri().LocalPath;
            var buffer       = _bufferManager.GetBuffer(request.TextDocument.Uri);

            if (buffer == null)
            {
                return(new CompletionList());
            }

            var metdata = _metadataProvider.GetMetadataForDocument(documentPath);

            if (metdata == null)
            {
                return(new CompletionList());
            }

            var position         = Utils.PositionToOffset(request.Position, buffer.AsSpan());
            var completionResult = new CompletionEngine().GetCompletions(metdata, buffer.ToString(), position);

            if (completionResult == null)
            {
                return(new CompletionList());
            }

            List <CompletionItem> mappedComlpletions = new List <CompletionItem>();

            for (int i = 0; i < completionResult.Completions.Count; i++)
            {
                var completion = MapCompletion(completionResult.Completions[i], completionResult.StartPosition, request.Position, i.ToString().PadLeft(10, '0'), buffer);
                mappedComlpletions.Add(completion);
            }

            return(new CompletionList(mappedComlpletions));
        }
Exemplo n.º 8
0
        private CompletionList StructureMemberComplete(CompletionParams request)
        {
            var tree   = _bufferManager.GetParseTree(request.TextDocument.Uri);
            var symbol = GetSymbolUnderCursor(tree, request.Position);
            var items  = new List <CompletionItem>();

            if (symbol != null && symbol != tree)
            {
                var suffixes = GetSymbolSuffixes(symbol);
                var trailer  = GetSuffixTrailers(symbol);

                if (trailer.Count > 0)
                {
                    suffixes = GetTrailerSuffixes(trailer);
                }

                if (suffixes != null)
                {
                    foreach (var suffix in suffixes)
                    {
                        items.Add(GetSuffixCompletionItem(suffix.Key, suffix.Value));
                    }
                }
            }
            return(new CompletionList(items));
        }
Exemplo n.º 9
0
 public CompletionProcessor(ISymbolGuesser symbolGuesser, DafnyDocument document, CompletionParams request, CancellationToken cancellationToken)
 {
     this.symbolGuesser     = symbolGuesser;
     this.document          = document;
     this.request           = request;
     this.cancellationToken = cancellationToken;
 }
Exemplo n.º 10
0
        public async Task <CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken)
        {
            var documentHash = Hash.StringHash(request.TextDocument.Uri.GetFileSystemPath());
            var pos          = request.Position;
            var namesPtr     = TreeSitter.GetCompletionItems(documentHash, pos.Line, pos.Character, (int)request.Context.TriggerKind);
            var names        = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(namesPtr);

            if (names == null)
            {
                return(new CompletionList());
            }

            var nameList = names.Split(",");
            List <CompletionItem> items = new List <CompletionItem>(nameList.Length);

            int sortValue = 0;

            foreach (var name in nameList)
            {
                if (name == "")
                {
                    continue;
                }

                var completion = new CompletionItem();
                completion.Label      = name;
                completion.SortText   = sortValue.ToString("D8");
                completion.FilterText = name.ToLower();
                items.Add(completion);
                sortValue++;
            }

            return(new CompletionList(items));
        }
Exemplo n.º 11
0
 public Task <object> RequestCompletions(CompletionParams completionParams, CancellationToken token)
 {
     if (completionProvider != null)
     {
         return(completionProvider.RequestCompletions(completionParams, param => RequestCompletionsInternal(param, token)));
     }
     return(RequestCompletionsInternal(completionParams, token));
 }
        public override async Task <CompletionList> Completion(CompletionParams @params, CancellationToken cancellationToken)
        {
            var uri = @params.textDocument.uri;

            ProjectFiles.GetEntry(@params.textDocument, @params._version, out var entry, out var tree);
            TraceMessage($"Completions in {uri} at {@params.position}");

            tree = GetParseTree(entry, uri, cancellationToken, out var version) ?? tree;
            var analysis = entry != null ? await entry.GetAnalysisAsync(50, cancellationToken) : null;

            if (analysis == null)
            {
                TraceMessage($"No analysis found for {uri}");
                return(new CompletionList());
            }

            var opts = GetOptions(@params.context);
            var ctxt = new CompletionAnalysis(analysis, tree, @params.position, opts, Settings.completion, _displayTextBuilder, Logger, () => entry.ReadDocument(ProjectFiles.GetPart(uri), out _));

            var members = string.IsNullOrEmpty(@params._expr)
                ? ctxt.GetCompletions()
                : ctxt.GetCompletionsFromString(@params._expr);

            if (members == null)
            {
                TraceMessage($"No completions at {@params.position} in {uri}");
                return(new CompletionList());
            }

            if (!Settings.completion.showAdvancedMembers)
            {
                members = members.Where(m => !m.label.StartsWith("__"));
            }

            var filterKind = @params.context?._filterKind;

            if (filterKind.HasValue && filterKind != CompletionItemKind.None)
            {
                TraceMessage($"Only returning {filterKind.Value} items");
                members = members.Where(m => m.kind == filterKind.Value);
            }

            var res = new CompletionList {
                items            = members.ToArray(),
                _expr            = ctxt.ParentExpression?.ToCodeString(tree, CodeFormattingOptions.Traditional),
                _commitByDefault = ctxt.ShouldCommitByDefault,
                _allowSnippet    = ctxt.ShouldAllowSnippets
            };

            res._applicableSpan = GetApplicableSpan(ctxt, @params, tree);
            LogMessage(MessageType.Info, $"Found {res.items.Length} completions for {uri} at {@params.position} after filtering");

            await InvokeExtensionsAsync((ext, token)
                                        => (ext as ICompletionExtension)?.HandleCompletionAsync(uri, analysis, tree, @params.position, res, cancellationToken), cancellationToken);

            return(res);
        }
Exemplo n.º 13
0
        public async Task HandleRequestAsync_CSharpProjection_IdentifierTriggerCharacter_InvokesCSharpLanguageServerNull()
        {
            // Arrange
            var called       = false;
            var expectedItem = new CompletionItem()
            {
                InsertText = "DateTime"
            };
            var completionRequest = new CompletionParams()
            {
                TextDocument = new TextDocumentIdentifier()
                {
                    Uri = Uri
                },
                Context = new CompletionContext()
                {
                    TriggerKind = CompletionTriggerKind.TriggerCharacter, TriggerCharacter = "a"
                },
                Position = new Position(0, 1)
            };

            var documentManager = new TestDocumentManager();

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

            var requestInvoker = new Mock <LSPRequestInvoker>();

            requestInvoker
            .Setup(r => r.ReinvokeRequestOnServerAsync <CompletionParams, SumType <CompletionItem[], CompletionList>?>(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CompletionParams>(), It.IsAny <CancellationToken>()))
            .Callback <string, string, CompletionParams, CancellationToken>((method, serverContentType, completionParams, ct) =>
            {
                Assert.Equal(Methods.TextDocumentCompletionName, method);
                Assert.Equal(RazorLSPConstants.CSharpContentTypeName, serverContentType);
                called = true;
            })
            .Returns(Task.FromResult <SumType <CompletionItem[], CompletionList>?>(new[] { expectedItem }));

            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 completionHandler = new CompletionHandler(JoinableTaskContext, requestInvoker.Object, documentManager, projectionProvider.Object);

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

            // Assert
            Assert.True(called);
            Assert.NotEmpty((CompletionItem[])result.Value);
            var item = ((CompletionItem[])result.Value).First();

            Assert.Equal(expectedItem.InsertText, item.InsertText);
        }
Exemplo n.º 14
0
        public async Task <CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken)
        {
            // Util.Log("Handling completion request.");
            // return new CompletionList(new CompletionItem{Label ="new version op"});
            // var result = await CompletionInstance.ProvideCompletionItems(request, server, _bufferManager);
            var result = await CompletionInstance.ProvideCompletionItems(request, Server.Instance, LanguageServer);

            return(result);
        }
Exemplo n.º 15
0
        public async override Task <CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken)
        {
            var document = await documents.GetDocumentAsync(request.TextDocument);

            if (document == null)
            {
                logger.LogWarning("location requested for unloaded document {DocumentUri}", request.TextDocument.Uri);
                return(new CompletionList());
            }
            return(new CompletionProcessor(symbolGuesser, document, request, cancellationToken).Process());
        }
Exemplo n.º 16
0
        public override Task <CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken)
        {
            DafnyDocument?document;

            if (!_documents.TryGetDocument(request.TextDocument, out document))
            {
                _logger.LogWarning("location requested for unloaded document {DocumentUri}", request.TextDocument.Uri);
                return(Task.FromResult(new CompletionList()));
            }
            return(Task.FromResult(new CompletionProcessor(_symbolGuesser, document, request, cancellationToken).Process()));
        }