Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
Expand Down Expand Up @@ -197,7 +197,8 @@ public static bool TryGetProvisionalCompletionInfo(
LspFactory.CreatePosition(
previousPosition.Line,
previousPosition.Character + 1),
previousCharacterPositionInfo.HostDocumentIndex + 1);
previousCharacterPositionInfo.HostDocumentIndex + 1,
previousCharacterPositionInfo.InDeclDocument);

result = new CompletionPositionInfo(addProvisionalDot, provisionalPositionInfo, ShouldIncludeDelegationSnippets: false);
return true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
Expand Down Expand Up @@ -36,14 +36,15 @@ public static DocumentPositionInfo GetPositionInfo(

var position = sourceText.GetPosition(razorIndex);

var inDeclDocument = false;
var languageKind = codeDocument.GetLanguageKind(razorIndex, rightAssociative: false);
if (languageKind is RazorLanguageKind.CSharp)
{
if (service.TryMapToCSharpDocumentPosition(codeDocument.GetRequiredImplCSharpDocument(), razorIndex, out Position? mappedPosition, out _))
if (service.TryMapToCSharpDocumentLinePosition(codeDocument, razorIndex, out var mappedPosition, out _, out inDeclDocument))
{
// For C# locations, we attempt to return the corresponding position
// within the projected document
position = mappedPosition;
position = mappedPosition.ToPosition();
}
else
{
Expand All @@ -54,7 +55,7 @@ public static DocumentPositionInfo GetPositionInfo(
}
}

return new DocumentPositionInfo(languageKind, position, razorIndex);
return new DocumentPositionInfo(languageKind, position, razorIndex, inDeclDocument);
}

public static bool TryMapToRazorDocumentRange(this IDocumentMappingService service, RazorCSharpDocument csharpDocument, LspRange csharpRange, MappingBehavior mappingBehavior, [NotNullWhen(true)] out LspRange? razorRange)
Expand Down Expand Up @@ -91,4 +92,38 @@ public static bool TryMapToCSharpPositionOrNext(this IDocumentMappingService ser
csharpPosition = result ? csharpLinePosition.ToPosition() : null;
return result;
}

/// <summary>
/// Convenience method to map from Razor to C#, which checks both impl and decl documents
/// </summary>
/// <remarks>
/// A position in a Razor document could map to one of two different C# documents, but the only situation
/// where it would map to both, is when the resulting position in the C# document is semantically equivalent.
/// ie, a Razor using or namespace directive would map to both the decl and impl documents, but in either case
/// it ends up at a C# using or namespace directive, so it doesn't matter which one we get back.
///
/// For all other positions in the Razor document, only one document will be mappable.
///
/// Note that the same is NOT true in reverse: A mappable position in a C# document might be unique to either
/// the decl or impl document, but that would only be a coincidence. Part of the reason we emit inDeclDocument
/// as an out parameter is because in order to map back to Razor later, we must know which document the C# position
/// came from.
/// </remarks>
public static bool TryMapToCSharpDocumentLinePosition(this IDocumentMappingService service, RazorCodeDocument codeDocument, int razorIndex, out LinePosition csharpPosition, out int csharpIndex, out bool inDeclDocument)
{
inDeclDocument = false;
if (service.TryMapToCSharpDocumentPosition(codeDocument.GetRequiredCSharpDocument(declarationDocument: false), razorIndex, out csharpPosition, out csharpIndex))
{
return true;
}

inDeclDocument = true;
if (codeDocument.GetCSharpDocument(declarationDocument: true) is { } declDocument &&
service.TryMapToCSharpDocumentPosition(declDocument, razorIndex, out csharpPosition, out csharpIndex))
{
return true;
}

return false;
Comment thread
davidwengier marked this conversation as resolved.
Resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
using Microsoft.CodeAnalysis.Razor.Remote;
using Microsoft.CodeAnalysis.Razor.Telemetry;
using Microsoft.CodeAnalysis.Razor.Workspaces.Settings;
using Microsoft.CodeAnalysis.Remote.Razor.Hover;
using Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem;
using Microsoft.CodeAnalysis.Text;
using CompletionResponse = Microsoft.CodeAnalysis.Razor.Remote.RemoteResponse<Microsoft.CodeAnalysis.Razor.Protocol.Completion.CompletionResult>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using Microsoft.CodeAnalysis.Razor.Tooltip;
using Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem;

namespace Microsoft.CodeAnalysis.Remote.Razor;
namespace Microsoft.CodeAnalysis.Remote.Razor.Hover;

internal sealed class ComponentAvailabilityService(RemoteSolutionSnapshot solutionSnapshot) : AbstractComponentAvailabilityService
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.CodeAnalysis.Razor.Hover;
namespace Microsoft.CodeAnalysis.Remote.Razor.Hover;

internal readonly record struct HoverDisplayOptions(MarkupKind MarkupKind, bool SupportsVisualStudioExtensions)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
using Microsoft.VisualStudio.Editor.Razor;
using Roslyn.Text.Adornments;

namespace Microsoft.CodeAnalysis.Razor.Hover;
namespace Microsoft.CodeAnalysis.Remote.Razor.Hover;

internal static class HoverFactory
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Razor.DocumentMapping;
using Microsoft.CodeAnalysis.Razor.Hover;
using Microsoft.CodeAnalysis.Razor.Protocol;
using Microsoft.CodeAnalysis.Razor.Remote;
using Microsoft.CodeAnalysis.Remote.Razor.Hover;
using Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem;
using static Microsoft.CodeAnalysis.Razor.Remote.RemoteResponse<Roslyn.LanguageServer.Protocol.Hover?>;

Expand All @@ -30,7 +29,7 @@ protected override IRemoteHoverService CreateService(in ServiceArgs args)

protected override IDocumentPositionInfoStrategy DocumentPositionInfoStrategy => PreferAttributeNameDocumentPositionInfoStrategy.Instance;

public ValueTask<RemoteResponse<Hover?>> GetHoverAsync(
public ValueTask<RemoteResponse<LspHover?>> GetHoverAsync(
JsonSerializableRazorSolutionWrapper solutionInfo,
JsonSerializableDocumentId documentId,
Position position,
Expand All @@ -41,7 +40,7 @@ protected override IRemoteHoverService CreateService(in ServiceArgs args)
context => GetHoverAsync(context, position, cancellationToken),
cancellationToken);

private async ValueTask<RemoteResponse<Hover?>> GetHoverAsync(
private async ValueTask<RemoteResponse<LspHover?>> GetHoverAsync(
RemoteDocumentContext context,
Position position,
CancellationToken cancellationToken)
Expand All @@ -65,7 +64,7 @@ protected override IRemoteHoverService CreateService(in ServiceArgs args)
if (positionInfo.LanguageKind == RazorLanguageKind.CSharp)
{
var generatedDocument = await context.Snapshot
.GetGeneratedDocumentAsync(cancellationToken)
.GetGeneratedDocumentAsync(positionInfo.InDeclDocument, cancellationToken)
.ConfigureAwait(false);

var globalOptions = generatedDocument.Project.Solution.Services.ExportProvider.GetService<IGlobalOptionService>();
Expand All @@ -85,7 +84,7 @@ protected override IRemoteHoverService CreateService(in ServiceArgs args)

// Map the hover range back to the host document
if (csharpHover.Range is { } range &&
DocumentMappingService.TryMapToRazorDocumentRange(codeDocument.GetRequiredImplCSharpDocument(), range.ToLinePositionSpan(), out var hostDocumentSpan))
DocumentMappingService.TryMapToRazorDocumentRange(codeDocument.GetRequiredCSharpDocument(positionInfo.InDeclDocument), range.ToLinePositionSpan(), out var hostDocumentSpan))
{
csharpHover.Range = LspFactory.CreateRange(hostDocumentSpan);
}
Expand All @@ -112,7 +111,7 @@ protected override IRemoteHoverService CreateService(in ServiceArgs args)
}

// As there is a C# hover, stop further handling.
return new RemoteResponse<Hover?>(StopHandling: true, Result: csharpHover);
return new RemoteResponse<LspHover?>(StopHandling: true, Result: csharpHover);
}

if (positionInfo.LanguageKind is not (RazorLanguageKind.Html or RazorLanguageKind.Razor))
Expand Down Expand Up @@ -141,37 +140,6 @@ protected override IRemoteHoverService CreateService(in ServiceArgs args)
return CallHtml;
}

// Ensure that we convert our Hover to a Roslyn Hover.
var resultHover = ConvertHover(razorHover);

return Results(resultHover);
}

/// <summary>
/// Converts a <see cref="Hover"/> to a <see cref="Hover"/>.
/// </summary>
/// <remarks>
/// Once Razor moves wholly over to Roslyn.LanguageServer.Protocol, this method can be removed.
/// </remarks>
private static Hover ConvertHover(Hover hover)
{
// Note: Razor only ever produces a Hover with MarkupContent or a VSInternalHover with RawContents.
// Both variants return a Range.

return hover switch
{
VSInternalHover { Range: var range, RawContent: { } rawContent } => new VSInternalHover()
{
Range = range,
Contents = string.Empty,
RawContent = rawContent
},
Hover { Range: var range, Contents.Fourth: MarkupContent contents } => new Hover()
{
Range = range,
Contents = contents
},
_ => Assumed.Unreachable<Hover>(),
};
return Results(razorHover);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
Expand Down Expand Up @@ -31,13 +31,13 @@ protected DocumentPositionInfo GetPositionInfo(RazorCodeDocument codeDocument, i
// Sometimes Html can actually be mapped to C#, like for example component attributes, which map to
// C# properties, even though they appear entirely in a Html context. Since remapping is pretty cheap
// it's easier to just try mapping, and see what happens, rather than checking for specific syntax nodes.
if (DocumentMappingService.TryMapToCSharpDocumentPosition(codeDocument.GetRequiredImplCSharpDocument(), positionInfo.HostDocumentIndex, out Position? csharpPosition, out _))
if (DocumentMappingService.TryMapToCSharpDocumentLinePosition(codeDocument, positionInfo.HostDocumentIndex, out var csharpPosition, out _, out var inDeclDocument))
{
// We're just gonna pretend this mapped perfectly normally onto C#. Moving this logic to the actual position info
// calculating code is possible, but could have untold effects, so opt-in is better (for now?)

// TODO: Not using a with operator here because it doesn't work in OOP for some reason.
positionInfo = new DocumentPositionInfo(RazorLanguageKind.CSharp, csharpPosition, positionInfo.HostDocumentIndex);
positionInfo = new DocumentPositionInfo(RazorLanguageKind.CSharp, csharpPosition.ToPosition(), positionInfo.HostDocumentIndex, inDeclDocument);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public async Task Html_EndTag()
}

[ConditionalFact(typeof(IsEnglishLocal))]
public async Task CSharp()
public async Task CSharp_Impl()
{
TestCode code = """
<PageTitle></PageTitle>
Expand Down Expand Up @@ -178,6 +178,80 @@ await VerifyHoverAsync(code, async (hover, document) =>
});
}

[ConditionalFact(typeof(IsEnglishLocal))]
public async Task CSharp_Decl()
{
TestCode code = """
<PageTitle></PageTitle>
<div></div>

@code
{
public void M()
{
var $$[|myVariable|] = "Hello";

var length = myVariable.Length;
}
}
""";

await VerifyHoverAsync(code, async (hover, document) =>
{
await VerifyRangeAsync(hover, code.Span, document);

hover.VerifyContents(
Container(
Container(
Image,
ClassifiedText( // (local variable) string myVariable
Punctuation("("),
Text("local variable"),
Punctuation(")"),
WhiteSpace(" "),
Keyword("string"),
WhiteSpace(" "),
LocalName("myVariable")))));
});
}

[ConditionalFact(typeof(IsEnglishLocal))]
public async Task CSharp_Legacy()
{
TestCode code = """
<PageTitle></PageTitle>
<div></div>

@functions
{
public void M()
{
var $$[|myVariable|] = "Hello";

var length = myVariable.Length;
}
}
""";

await VerifyHoverAsync(code, fileKind: RazorFileKind.Legacy, htmlResponse: null, async (hover, document) =>
{
await VerifyRangeAsync(hover, code.Span, document);

hover.VerifyContents(
Container(
Container(
Image,
ClassifiedText( // (local variable) string myVariable
Punctuation("("),
Text("local variable"),
Punctuation(")"),
WhiteSpace(" "),
Keyword("string"),
WhiteSpace(" "),
LocalName("myVariable")))));
});
}

[Fact]
public async Task ComponentAttribute()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Test.Common;
using Microsoft.CodeAnalysis.Remote.Razor;
using Microsoft.CodeAnalysis.Remote.Razor.Hover;
using Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem;
using Microsoft.VisualStudio.Razor.LanguageClient.Cohost;
using Roslyn.Test.Utilities;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@
using Moq;
using Xunit;
using Xunit.Abstractions;
using Roslyn.LanguageServer.Protocol;

namespace Microsoft.CodeAnalysis.Razor.Hover;
namespace Microsoft.CodeAnalysis.Remote.Razor.Hover;

public class HoverFactoryTest(ITestOutputHelper testOutput) : ToolingTestBase(testOutput)
{
Expand Down