Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send back icons for FAR via LSP #47882

Merged
20 commits merged into from
Oct 7, 2020
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion eng/Versions.props
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
<CodeStyleAnalyzerVersion>3.8.0-2.20414.4</CodeStyleAnalyzerVersion>
<VisualStudioEditorPackagesVersion>16.8.39</VisualStudioEditorPackagesVersion>
<ILToolsPackageVersion>5.0.0-alpha1.19409.1</ILToolsPackageVersion>
<MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>16.8.103</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>
<MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>16.8.120</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>
<MicrosoftVisualStudioShellPackagesVersion>16.8.30406.65-pre</MicrosoftVisualStudioShellPackagesVersion>
</PropertyGroup>
<!--
Expand Down
4 changes: 4 additions & 0 deletions src/EditorFeatures/Core/Shared/Extensions/GlyphExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.CodeAnalysis.Tags;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Text.Adornments;

namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
Expand Down Expand Up @@ -221,5 +222,8 @@ public static ImageId GetImageId(this Glyph glyph)
throw new ArgumentException(nameof(glyph));
}
}

public static ImageElement GetImageElement(this Glyph glyph)
=> new ImageElement(glyph.GetImageId());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text.Adornments;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Roslyn.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
Expand Down Expand Up @@ -244,18 +245,20 @@ protected static LSP.VSCompletionItem CreateCompletionItem(
SortText = sortText ?? insertText,
InsertTextFormat = LSP.InsertTextFormat.Plaintext,
Kind = kind,
Data = new CompletionResolveData()
Data = JObject.FromObject(new CompletionResolveData()
{
DisplayText = insertText,
TextDocument = requestParameters.TextDocument,
Position = requestParameters.Position,
CompletionTrigger = new CompletionTrigger(ProtocolConversions.LSPToRoslynCompletionTriggerKind(requestParameters.Context.TriggerKind), char.Parse(requestParameters.Context.TriggerCharacter))
},
Preselect = preselect,
CompletionTrigger = requestParameters.Context == null
? new CompletionTrigger()
: new CompletionTrigger(ProtocolConversions.LSPToRoslynCompletionTriggerKind(requestParameters.Context.TriggerKind), char.Parse(requestParameters.Context.TriggerCharacter))
}),
Preselect = preselect
};

if (tags != null)
item.Icon = new ImageElement(tags.ToImmutableArray().GetFirstGlyph().GetImageId());
item.Icon = tags.ToImmutableArray().GetFirstGlyph().GetImageElement();

if (commitCharacters != null)
item.CommitCharacters = commitCharacters.Value.Select(c => c.ToString()).ToArray();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
Expand Down Expand Up @@ -93,7 +94,7 @@ public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition
var definitionItem = await GenerateVSReferenceItemAsync(
_id, definitionId: _id, _document, _position, definition.SourceSpans.FirstOrDefault(),
definition.DisplayableProperties, _metadataAsSourceFileService, definition.GetClassifiedText(),
symbolUsageInfo: null, CancellationToken).ConfigureAwait(false);
definition.Tags.GetFirstGlyph(), symbolUsageInfo: null, CancellationToken).ConfigureAwait(false);

if (definitionItem != null)
{
Expand Down Expand Up @@ -135,7 +136,7 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere
var referenceItem = await GenerateVSReferenceItemAsync(
_id, definitionId, _document, _position, reference.SourceSpan,
reference.AdditionalProperties, _metadataAsSourceFileService, definitionText: null,
reference.SymbolUsageInfo, CancellationToken).ConfigureAwait(false);
definitionGlyph: Glyph.None, reference.SymbolUsageInfo, CancellationToken).ConfigureAwait(false);

if (referenceItem != null)
{
Expand All @@ -153,6 +154,7 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere
ImmutableDictionary<string, string> properties,
IMetadataAsSourceFileService metadataAsSourceFileService,
ClassifiedTextElement? definitionText,
Glyph definitionGlyph,
SymbolUsageInfo? symbolUsageInfo,
CancellationToken cancellationToken)
{
Expand All @@ -176,6 +178,7 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere
{
DefinitionId = definitionId,
DefinitionText = definitionText, // Only definitions should have a non-null DefinitionText
DefinitionIcon = definitionGlyph.GetImageElement(),
DisplayPath = location.Uri.LocalPath,
Id = id,
Kind = symbolUsageInfo.HasValue ? ProtocolConversions.SymbolUsageInfoToReferenceKinds(symbolUsageInfo.Value) : Array.Empty<ReferenceKind>(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Elfie.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ public CompletionHandler(
return null;
}

if (request.Context?.TriggerCharacter == null)
{
return null;
Copy link
Contributor

@NTaylorMullen NTaylorMullen Oct 5, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TriggerCharacter being null in a proper functioning LSP client results in completions when typing out an identifier. I don't think returning null here is correct.
image

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, to be clear, Razor translates the LSP platform's requests into spec abiding LSP requests which ends up hitting this call path. If you checked this in it'd stop returning C# identifier completions in Razor scenarios 😢

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think for now we can just match the spec and say invoked if we get null. If we actually get null, this will result in completions coming up unexpectedly (as invoked is generally more aggressive). But VS is currently passing the trigger char 'incorrectly' so we'll only hit this in Razor right now.

Then we can followup with a longterm fix from https://github.com/microsoft/ms-lsp/issues/57#issuecomment-703863301 (probably some kind of new property)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated the PR to what I believe is spec-compliant behaviour, specifically in 0f09454 (#47882). PTAL.

}

// C# and VB share the same LSP language server, and thus share the same default trigger characters.
// We need to ensure the trigger character is valid in the document's language. For example, the '{'
// character, while a trigger character in VB, is not a trigger character in C#.
Expand Down Expand Up @@ -97,7 +102,7 @@ public CompletionHandler(
return new LSP.VSCompletionList
{
Items = list.Items.Select(item => CreateLSPCompletionItem(request, item, lspVSClientCapability, completionTrigger, commitCharactersRuleCache)).ToArray(),
SuggesstionMode = list.SuggestionModeItem != null,
SuggestionMode = list.SuggestionModeItem != null,
};

// Local functions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Microsoft.CodeAnalysis.LanguageServer.CustomProtocol;
using Microsoft.VisualStudio.Text.Adornments;
using Newtonsoft.Json.Linq;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;

namespace Microsoft.CodeAnalysis.LanguageServer.Handler
Expand All @@ -29,12 +30,16 @@ public CompletionResolveHandler()
{
}

private static CompletionResolveData GetCompletionResolveData(LSP.CompletionItem request)
{
Contract.ThrowIfNull(request.Data);

return ((JToken)request.Data).ToObject<CompletionResolveData>();
}

public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionItem request)
=> GetCompletionResolveData(request).TextDocument;

private static CompletionResolveData GetCompletionResolveData(LSP.CompletionItem completionItem)
=> completionItem.Data as CompletionResolveData ?? ((JToken)completionItem.Data).ToObject<CompletionResolveData>();

public async Task<LSP.CompletionItem> HandleRequestAsync(LSP.CompletionItem completionItem, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ public FindAllReferencesHandler(IMetadataAsSourceFileService metadataAsSourceFil
return Array.Empty<LSP.VSReferenceItem>();
}

// We only support streaming results back, so no point doing any work if the client doesn't
if (referenceParams.PartialResultToken == null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once pull diagnostics goes in we should switch this to use the progress implementation there.
Filed #48350

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I already logged #48150 (and #48151) for this :P
I started working on, but need to make changes to the BufferedProgress to make it thread safe, so yes, was waiting for pull diagnostics to be in first.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Woops, closed mine as dupe!

{
return Array.Empty<LSP.VSReferenceItem>();
}

var findUsagesService = document.GetRequiredLanguageService<IFindUsagesLSPService>();
var position = await document.GetPositionFromLinePositionAsync(
ProtocolConversions.PositionToLinePosition(referenceParams.Position), cancellationToken).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ void M()

var results = (LSP.VSCompletionList)await RunGetCompletionsAsync(workspace.CurrentSolution, completionParams).ConfigureAwait(false);
Assert.True(results.Items.Any());
Assert.True(results.SuggesstionMode);
Assert.True(results.SuggestionMode);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@

#nullable disable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
Expand Down Expand Up @@ -45,7 +49,44 @@ void M2()
Assert.Equal("M", results[1].ContainingMember);
Assert.Equal("M2", results[3].ContainingMember);

AssertValidDefinitionProperties(results, 0);
AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic);
}

[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this need to be skipped still?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't see the build results in the linked issue to see why they failed, but with the handler only supporting streaming I can't see how they ever passed, so was planning on unskipping when adding non-streaming support.

public async Task TestFindAllReferencesAsync_Class()
{
var markup =
@"class {|reference:A|}
{
public int someInt = 1;
void M()
{
var i = someInt + 1;
}
}
class B
{
int someInt = {|reference:A|}.someInt + 1;
void M2()
{
var j = someInt + {|caret:|}{|reference:A|}.someInt;
}
}";
using var workspace = CreateTestWorkspace(markup, out var locations);

var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First());
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));

var textElement = results[0].Text as ClassifiedTextElement;
Assert.NotNull(textElement);
var actualText = string.Concat(textElement.Runs.Select(r => r.Text));

Assert.Equal("class A", actualText);
Assert.Equal("B", results[1].ContainingType);
Assert.Equal("B", results[2].ContainingType);
Assert.Equal("M2", results[2].ContainingMember);

AssertValidDefinitionProperties(results, 0, Glyph.ClassInternal);
}

[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")]
Expand Down Expand Up @@ -80,7 +121,7 @@ void M2()
Assert.Equal("M", results[1].ContainingMember);
Assert.Equal("M2", results[3].ContainingMember);

AssertValidDefinitionProperties(results, 0);
AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want some test for something other than FieldPublic?

}

[WpfFact]
Expand Down Expand Up @@ -116,12 +157,13 @@ void M()
Assert.NotNull(results[0].Location.Uri);
}

private static LSP.ReferenceParams CreateReferenceParams(LSP.Location caret) =>
private static LSP.ReferenceParams CreateReferenceParams(LSP.Location caret, IProgress<object> progress) =>
new LSP.ReferenceParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri),
Position = caret.Range.Start,
Context = new LSP.ReferenceContext(),
PartialResultToken = progress
};

private static async Task<LSP.VSReferenceItem[]> RunFindAllReferencesAsync(Solution solution, LSP.Location caret)
Expand All @@ -131,17 +173,23 @@ private static LSP.ReferenceParams CreateReferenceParams(LSP.Location caret) =>
SupportsVisualStudioExtensions = true
};

var progress = new ProgressCollector<LSP.VSReferenceItem>();

var queue = CreateRequestQueue(solution);
return await GetLanguageServer(solution).ExecuteRequestAsync<LSP.ReferenceParams, LSP.VSReferenceItem[]>(queue, LSP.Methods.TextDocumentReferencesName,
CreateReferenceParams(caret), vsClientCapabilities, null, CancellationToken.None);
await GetLanguageServer(solution).ExecuteRequestAsync<LSP.ReferenceParams, LSP.VSReferenceItem[]>(queue, LSP.Methods.TextDocumentReferencesName,
CreateReferenceParams(caret, progress), vsClientCapabilities, null, CancellationToken.None);

return progress.GetItems();
}

private static void AssertValidDefinitionProperties(LSP.ReferenceItem[] referenceItems, int definitionIndex)
private static void AssertValidDefinitionProperties(LSP.VSReferenceItem[] referenceItems, int definitionIndex, Glyph definitionGlyph)
{
var definition = referenceItems[definitionIndex];
var definitionId = definition.DefinitionId;
Assert.NotNull(definition.DefinitionText);

Assert.Equal(definitionGlyph.GetImageId(), definition.DefinitionIcon.ImageId);

for (var i = 0; i < referenceItems.Length; i++)
{
if (i == definitionIndex)
Expand All @@ -150,9 +198,22 @@ private static void AssertValidDefinitionProperties(LSP.ReferenceItem[] referenc
}

Assert.Null(referenceItems[i].DefinitionText);
Assert.Equal(0, referenceItems[i].DefinitionIcon.ImageId.Id);
Assert.Equal(definitionId, referenceItems[i].DefinitionId);
Assert.NotEqual(definitionId, referenceItems[i].Id);
}
}

private sealed class ProgressCollector<T> : IProgress<object>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making a note here to switch this as well in #48350

{
private readonly List<T> _items = new List<T>();

public T[] GetItems() => _items.ToArray();

public void Report(object value)
{
_items.AddRange((T[])value);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public async Task<CompletionItem[]> HandleRequestAsync(CompletionParams request,
var completionService = document.Project.LanguageServices.GetRequiredService<IXamlCompletionService>();
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var offset = text.Lines.GetPosition(ProtocolConversions.PositionToLinePosition(request.Position));
var completionResult = await completionService.GetCompletionsAsync(new XamlCompletionContext(document, offset, request.Context.TriggerCharacter?.FirstOrDefault() ?? '\0'), cancellationToken: cancellationToken).ConfigureAwait(false);
var completionResult = await completionService.GetCompletionsAsync(new XamlCompletionContext(document, offset, request.Context?.TriggerCharacter?.FirstOrDefault() ?? '\0'), cancellationToken: cancellationToken).ConfigureAwait(false);
if (completionResult?.Completions == null)
{
return Array.Empty<CompletionItem>();
Expand All @@ -62,7 +62,7 @@ private static CompletionItem CreateCompletionItem(XamlCompletionItem xamlComple
CommitCharacters = xamlCompletion.CommitCharacters,
Detail = xamlCompletion.Detail,
InsertText = xamlCompletion.InsertText,
Preselect = xamlCompletion.Preselect,
Preselect = xamlCompletion.Preselect.GetValueOrDefault(),
SortText = xamlCompletion.SortText,
FilterText = xamlCompletion.FilterText,
Kind = GetItemKind(xamlCompletion.Kind),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,14 @@ public CompletionResolveHandler()

public async Task<LSP.CompletionItem> HandleRequestAsync(LSP.CompletionItem completionItem, RequestContext context, CancellationToken cancellationToken)
{
if (!(completionItem.Data is CompletionResolveData data))
CompletionResolveData data;
if (completionItem.Data is JToken token)
{
data = ((JToken)completionItem.Data).ToObject<CompletionResolveData>();
data = token.ToObject<CompletionResolveData>();
}
else
{
return completionItem;
}

var documentId = DocumentId.CreateFromSerialized(ProjectId.CreateFromSerialized(data.ProjectGuid), data.DocumentGuid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ private static async Task<ImmutableArray<SymbolInformation>> SearchDocumentAsync
/// </summary>
private static async Task SearchDocumentAndReportSymbolsAsync(Document document, WorkspaceSymbolParams args, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(args.PartialResultToken);
davidwengier marked this conversation as resolved.
Show resolved Hide resolved

var convertedResults = await SearchDocumentAsync(document, args.Query, cancellationToken).ConfigureAwait(false);
args.PartialResultToken.Report(convertedResults.ToArray());
}
Expand Down