Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
b7318df
Track declaration Razor C# documents
davidwengier Jun 9, 2026
e8b0e11
Unwrap Razor CodeLens resolve data
davidwengier Jun 9, 2026
286c492
Use declaration document for Razor CodeLens
davidwengier Jun 9, 2026
a88a999
Add legacy Razor CodeLens tests
davidwengier Jun 9, 2026
aef113b
Simplify Razor semantic tokens
davidwengier Jun 9, 2026
17a367c
Make Razor document symbols SONIC-aware
davidwengier Jun 9, 2026
f0a760c
Add Razor document symbol SONIC coverage
davidwengier Jun 9, 2026
47254eb
Make Razor selection ranges SONIC-aware
davidwengier Jun 9, 2026
8d16ffc
Add Razor selection range SONIC coverage
davidwengier Jun 9, 2026
7c5c384
Fix CI issues
davidwengier Jun 9, 2026
427e60e
Make Razor spell check SONIC-aware
davidwengier Jun 9, 2026
9f61e1d
Add SONIC spell check tests
davidwengier Jun 9, 2026
b546c73
Make Razor inline completion SONIC-aware
davidwengier Jun 9, 2026
3f2934d
Add SONIC inline completion tests
davidwengier Jun 9, 2026
e363e6a
Make Razor type hierarchy SONIC-aware
davidwengier Jun 9, 2026
e8c348a
Add SONIC type hierarchy tests
davidwengier Jun 9, 2026
5413ad3
Make Razor go to implementation SONIC-aware
davidwengier Jun 9, 2026
495fb29
Add SONIC go to implementation tests
davidwengier Jun 9, 2026
8d540df
Make Razor find all references SONIC-aware
davidwengier Jun 9, 2026
bfc7b72
Add SONIC find all references tests
davidwengier Jun 9, 2026
b171b00
Move document and edit mapping code up to Remote.Razor
davidwengier Jun 10, 2026
844035f
Move resource
davidwengier Jun 10, 2026
c9b000f
Delete unused file
davidwengier Jun 10, 2026
db79a4d
Move MEF exports to the real classes, and remove indirection
davidwengier Jun 10, 2026
43d93eb
Rename file
davidwengier Jun 10, 2026
1e8434a
Strongly type and simplify logic, now that there is no abstraction to…
davidwengier Jun 10, 2026
9fa0075
Make edit service and mapping service handle multiple C# documents
davidwengier Jun 10, 2026
db803ac
Move document position info code
davidwengier Jun 10, 2026
b41ce6b
Remove unused Razor using directive
davidwengier Jun 10, 2026
6b65bbb
Move formatting files up to Remote.Razor
davidwengier Jun 10, 2026
3796b77
Move almost all of FormattingUtilities
davidwengier Jun 10, 2026
d60bd03
Move C# formatting options helper back a to shared location
davidwengier Jun 10, 2026
e4059b1
Move trigger characters to where they're actually used
davidwengier Jun 10, 2026
b63641b
Fix namespaces and usings
davidwengier Jun 10, 2026
8f4a32d
Add IVT
davidwengier Jun 10, 2026
e46ed32
Move resources
davidwengier Jun 10, 2026
51db216
Update tests
davidwengier Jun 10, 2026
24d5d26
Move MEF attributes and remote unnecessary indirection
davidwengier Jun 10, 2026
74d6760
Unskip tests
davidwengier Jun 11, 2026
62c0956
Make formatting sonic compatible
davidwengier Jun 11, 2026
df11094
Update dependent services so they at least compile
davidwengier Jun 11, 2026
a4948b7
Fix "Show Formatting Document" feature
davidwengier Jun 11, 2026
4ec51a3
Unskip tests (and add one)
davidwengier Jun 11, 2026
f1cbb12
Remove stale comment
davidwengier Jun 11, 2026
e384ef0
Fix benchmark
davidwengier Jun 11, 2026
cffd735
Make Razor inlay hints SONIC-aware
davidwengier Jun 11, 2026
e5affc8
Add SONIC inlay hint tests
davidwengier Jun 11, 2026
d758621
Make Razor folding ranges SONIC-aware
davidwengier Jun 11, 2026
2057517
Add SONIC folding range tests
davidwengier Jun 11, 2026
3eb3b12
Move files from Workspaces to Remote and unify namespaces
davidwengier Jun 11, 2026
c9d98ae
Move MEF export
davidwengier Jun 11, 2026
bff73ca
Rename file
davidwengier Jun 11, 2026
577e795
Make Razor go to definition SONIC-aware
davidwengier Jun 11, 2026
4c73cf3
Correctness
davidwengier Jun 11, 2026
87ff5ca
[Sonic] Inlay hints, folding ranges, and go to definition (#84102)
davidwengier Jun 12, 2026
11d5cb6
[Sonic] Support multiple C# documents in formatting (#84097)
davidwengier Jun 12, 2026
d00caf2
[Sonic] Move edit service up to Remote and make it sonic aware (#84086)
davidwengier Jun 12, 2026
f877407
[Sonic] Make even more Razor features to be sonic compatible (#84075)
davidwengier Jun 12, 2026
6f75f9b
Fix grammatical error
davidwengier Jun 12, 2026
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
Expand Up @@ -134,7 +134,7 @@ protected override RazorCodeDocument ExecuteCore(RazorCodeDocument codeDocument,
// The decl writer suppresses diagnostic collection because every diagnostic on the
// decl tree is also reachable from the original tree the impl half lowers from;
// letting both writers report would surface every Razor-detected issue twice.
var declDocument = RazorCSharpDocumentWriter.Write(declDocNode, codeDocument, reportDiagnostics: false, cancellationToken);
var declDocument = RazorCSharpDocumentWriter.Write(declDocNode, codeDocument, reportDiagnostics: false, cancellationToken, isDeclarationDocument: true);

return codeDocument.WithDeclCSharpDocument(declDocument);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@ public sealed class RazorCSharpDocument
public ImmutableArray<SourceMapping> SourceMappingsSortedByGenerated { get; }
public ImmutableArray<SourceMapping> SourceMappingsSortedByOriginal { get; }
public ImmutableArray<LinePragma> LinePragmas { get; }
public bool IsDeclarationDocument { get; }

public RazorCSharpDocument(
RazorCodeDocument codeDocument,
SourceText text,
ImmutableArray<RazorDiagnostic> diagnostics,
ImmutableArray<SourceMapping> sourceMappings = default,
ImmutableArray<LinePragma> linePragmas = default)
ImmutableArray<LinePragma> linePragmas = default,
bool isDeclarationDocument = false)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

bool isDeclarationDocument = false

I assume we don't see there being any additional differences needed between decl/impl docs? If there were to be, it might be worth considering whether this could be an abstract base class, having impl and decl derivations.

@davidwengier davidwengier Jun 9, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think if anything, we could probably simplify this a lot more. The SourceText property used to be the only way to get the C# text, but with cohosting we can get it from the Roslyn solution snapshot. The diagnostics property is weird in sonic, since currently both documents duplicate all diagnostics, so I could see those moving up to RazorCodeDocument. I'm pretty sure linePragmas is only used for tests. Which means a RazorCSharpDocument could become a simple record that just stores source mappings and whether its a declaration document. In fact, I could see an argument for source mappings to store isDeclarationDocument, and have them just be a property on RazorCodeDocument and make this unnecessary altogether. Though I've no idea what impact that would have on the compiler, I'm not as familiar with that codebase.

I definitely still want to improve the architecture here, along with the DocumentContext and DocumentSnapshot stuff, but the longer the sonic feature branch lives, the more stressed I become about conflicts.

Comment thread
davidwengier marked this conversation as resolved.
Resolved
{
Comment thread
davidwengier marked this conversation as resolved.
Resolved
ArgHelper.ThrowIfNull(codeDocument);
ArgHelper.ThrowIfNull(text);
Expand All @@ -48,5 +50,6 @@ public RazorCSharpDocument(

SourceMappingsSortedByOriginal = SourceMappingsSortedByGenerated.Sort(static (m1, m2) => m1.OriginalSpan.CompareByStartThenLength(m2.OriginalSpan));
LinePragmas = linePragmas.NullToEmpty();
IsDeclarationDocument = isDeclarationDocument;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@
/// </summary>
internal static class RazorCSharpDocumentWriter
{
public static RazorCSharpDocument Write(

Check failure on line 19 in src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs

View check run for this annotation

Azure Pipelines / roslyn-CI (Correctness Correctness_Analyzers)

src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs#L19

src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs(19,39): error CA1068: (NETCORE_ENGINEERING_TELEMETRY=Build) Method 'Microsoft.AspNetCore.Razor.Language.RazorCSharpDocumentWriter.Write(Microsoft.AspNetCore.Razor.Language.Intermediate.DocumentIntermediateNode, Microsoft.AspNetCore.Razor.Language.RazorCodeDocument, bool, System.Threading.CancellationToken, bool)' should take CancellationToken as the last parameter (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1068)

Check failure on line 19 in src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs

View check run for this annotation

Azure Pipelines / roslyn-CI (Correctness Correctness_Analyzers)

src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs#L19

src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs(19,39): error CA1068: (NETCORE_ENGINEERING_TELEMETRY=Build) Method 'Microsoft.AspNetCore.Razor.Language.RazorCSharpDocumentWriter.Write(Microsoft.AspNetCore.Razor.Language.Intermediate.DocumentIntermediateNode, Microsoft.AspNetCore.Razor.Language.RazorCodeDocument, bool, System.Threading.CancellationToken, bool)' should take CancellationToken as the last parameter (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1068)

Check failure on line 19 in src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs

View check run for this annotation

Azure Pipelines / roslyn-CI

src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs#L19

src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs(19,39): error CA1068: (NETCORE_ENGINEERING_TELEMETRY=Build) Method 'Microsoft.AspNetCore.Razor.Language.RazorCSharpDocumentWriter.Write(Microsoft.AspNetCore.Razor.Language.Intermediate.DocumentIntermediateNode, Microsoft.AspNetCore.Razor.Language.RazorCodeDocument, bool, System.Threading.CancellationToken, bool)' should take CancellationToken as the last parameter (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1068)

Check failure on line 19 in src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs

View check run for this annotation

Azure Pipelines / roslyn-CI

src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs#L19

src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCSharpDocumentWriter.cs(19,39): error CA1068: (NETCORE_ENGINEERING_TELEMETRY=Build) Method 'Microsoft.AspNetCore.Razor.Language.RazorCSharpDocumentWriter.Write(Microsoft.AspNetCore.Razor.Language.Intermediate.DocumentIntermediateNode, Microsoft.AspNetCore.Razor.Language.RazorCodeDocument, bool, System.Threading.CancellationToken, bool)' should take CancellationToken as the last parameter (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1068)
DocumentIntermediateNode documentNode,
RazorCodeDocument codeDocument,
bool reportDiagnostics = true,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default,
bool isDeclarationDocument = false)
{
ArgHelper.ThrowIfNull(codeDocument);

Expand All @@ -44,7 +45,8 @@
text,
context.GetDiagnostics(),
context.GetSourceMappings(),
context.GetLinePragmas());
context.GetLinePragmas(),
isDeclarationDocument);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@

using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.PooledObjects;
using Microsoft.CodeAnalysis.LanguageServer.Handler.CodeLens;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Razor.DocumentMapping;
using Microsoft.CodeAnalysis.Razor.Remote;
using Microsoft.CodeAnalysis.Razor.Workspaces.CodeLens;
using Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem;

namespace Microsoft.CodeAnalysis.Remote.Razor;
Expand Down Expand Up @@ -39,23 +41,16 @@ protected override IRemoteCodeLensService CreateService(in ServiceArgs args)
CancellationToken cancellationToken)
{
var snapshot = context.Snapshot;
var generatedDocument = await snapshot.GetGeneratedDocumentAsync(cancellationToken).ConfigureAwait(false);
var csharpDocument = await GetCSharpDocumentAsync(context, cancellationToken).ConfigureAwait(false);
var generatedDocument = await snapshot.GetGeneratedDocumentAsync(csharpDocument.IsDeclarationDocument, cancellationToken).ConfigureAwait(false);
var globalOptions = generatedDocument.Project.Solution.Services.ExportProvider.GetService<IGlobalOptionService>();

var csharpCodeLens = await CodeLensHandler.GetCodeLensAsync(textDocumentIdentifier, generatedDocument, globalOptions, cancellationToken).ConfigureAwait(false);

if (csharpCodeLens is null)
{
return null;
}

var codeDocument = await context.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false);
var csharpDocument = codeDocument.GetImplCSharpDocument();
if (csharpDocument is null)
{
return null;
}

using var results = new PooledArrayBuilder<LspCodeLens>(csharpCodeLens.Length);

foreach (var codeLens in csharpCodeLens)
Expand All @@ -68,6 +63,19 @@ protected override IRemoteCodeLensService CreateService(in ServiceArgs args)
}

return results.ToArrayAndClear();

static async ValueTask<RazorCSharpDocument> GetCSharpDocumentAsync(RemoteDocumentContext context, CancellationToken cancellationToken)
{
var codeDocument = await context.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false);
// CodeLens items are only produced for the class members in a generated C# file, so they will always be in the
// decl document if it exists.
if (codeDocument.GetCSharpDocument(declarationDocument: true) is { } declCSharpDocument)
{
return declCSharpDocument;
}

return codeDocument.GetRequiredCSharpDocument(declarationDocument: false);
}
}

public ValueTask<LspCodeLens?> ResolveCodeLensAsync(
Expand All @@ -84,7 +92,14 @@ protected override IRemoteCodeLensService CreateService(in ServiceArgs args)
private async ValueTask<LspCodeLens?> ResolveCodeLensAsync(RemoteDocumentContext context, LspCodeLens codeLens, CancellationToken cancellationToken)
{
var snapshot = context.Snapshot;
var generatedDocument = await snapshot.GetGeneratedDocumentAsync(cancellationToken).ConfigureAwait(false);
var razorData = RazorCodeLensResolveData.Unwrap(codeLens);
if (razorData.OriginalData is { } originalData)
{
codeLens.Data = originalData;
}

var generatedDocument = await snapshot.TryGetGeneratedDocumentAsync(declarationDocument: true, cancellationToken).ConfigureAwait(false)
?? await snapshot.GetGeneratedDocumentAsync(declarationDocument: false, cancellationToken).ConfigureAwait(false);

return await CodeLensResolveHandler.ResolveCodeLensAsync(codeLens, generatedDocument, cancellationToken).ConfigureAwait(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,20 @@ internal sealed class DocumentSymbolService(IDocumentMappingService documentMapp
{
if (csharpSymbols.TryGetFirst(out var documentSymbols))
{
return RemapDocumentSymbols(fileKind, csharpDocument, documentSymbols);
return RemapDocumentSymbols(fileKind, csharpDocument, documentSymbols, synthesizeRenderMethodIfEmpty: true);
}
else if (csharpSymbols.TryGetSecond(out var symbolInformations))
{
using var _ = ListPool<SymbolInformation>.GetPooledObject(out var mappedSymbols);
var foundRenderMethodSymbol = false;

foreach (var symbolInformation in symbolInformations)
{
// SymbolInformation is obsolete, but things still return it so we have to handle it
#pragma warning disable CS0618 // Type or member is obsolete
if (symbolInformation.Name == RenderMethodSignature(fileKind))
{
foundRenderMethodSymbol = true;
symbolInformation.Name = RenderMethodDisplay(fileKind);
symbolInformation.Location.Range = LspFactory.DefaultRange;
symbolInformation.Location.DocumentUri = razorDocumentUri;
Expand All @@ -46,6 +48,11 @@ internal sealed class DocumentSymbolService(IDocumentMappingService documentMapp
#pragma warning restore CS0618 // Type or member is obsolete
}

if (!foundRenderMethodSymbol)
{
mappedSymbols.Insert(0, CreateRenderMethodSymbolInformation(fileKind, razorDocumentUri));
}

return mappedSymbols.ToArray();
}
else
Expand All @@ -55,7 +62,7 @@ internal sealed class DocumentSymbolService(IDocumentMappingService documentMapp
}
}

private DocumentSymbol[]? RemapDocumentSymbols(RazorFileKind fileKind, RazorCSharpDocument csharpDocument, DocumentSymbol[]? documentSymbols)
private DocumentSymbol[]? RemapDocumentSymbols(RazorFileKind fileKind, RazorCSharpDocument csharpDocument, DocumentSymbol[]? documentSymbols, bool synthesizeRenderMethodIfEmpty)
{
if (documentSymbols is null)
{
Expand All @@ -68,19 +75,24 @@ internal sealed class DocumentSymbolService(IDocumentMappingService documentMapp
{
if (TryRemapRanges(csharpDocument, documentSymbol))
{
documentSymbol.Children = RemapDocumentSymbols(fileKind, csharpDocument, documentSymbol.Children);
documentSymbol.Children = RemapDocumentSymbols(fileKind, csharpDocument, documentSymbol.Children, synthesizeRenderMethodIfEmpty: false);

mappedSymbols.Add(documentSymbol);
}
else if (documentSymbol.Children is [_, ..] &&
RemapDocumentSymbols(fileKind, csharpDocument, documentSymbol.Children) is [_, ..] mappedChildren)
RemapDocumentSymbols(fileKind, csharpDocument, documentSymbol.Children, synthesizeRenderMethodIfEmpty: false) is [_, ..] mappedChildren)
{
// This range didn't map, but some/all of its children did, so we promote them to this level so we don't
// lose any information.
mappedSymbols.AddRange(mappedChildren);
}
}

if (synthesizeRenderMethodIfEmpty && mappedSymbols.Count == 0)
{
mappedSymbols.Add(CreateRenderMethodDocumentSymbol(fileKind));
}

return mappedSymbols.ToArray();

bool TryRemapRanges(RazorCSharpDocument csharpDocument, DocumentSymbol documentSymbol)
Expand Down Expand Up @@ -117,4 +129,30 @@ private static string RenderMethodDisplay(RazorFileKind fileKind)
? "ExecuteAsync()"
: "BuildRenderTree()"; // We hide __builder because it can be misleading to users: https://github.com/dotnet/razor/issues/11960

private static SymbolInformation CreateRenderMethodSymbolInformation(RazorFileKind fileKind, DocumentUri razorDocumentUri)
{
// SymbolInformation is obsolete, but things still return it so we have to handle it
#pragma warning disable CS0618 // Type or member is obsolete
return new SymbolInformation
{
Name = RenderMethodDisplay(fileKind),
Kind = Roslyn.LanguageServer.Protocol.SymbolKind.Method,
Location = new()
{
DocumentUri = razorDocumentUri,
Range = LspFactory.DefaultRange,
},
};
#pragma warning restore CS0618 // Type or member is obsolete
}

private static DocumentSymbol CreateRenderMethodDocumentSymbol(RazorFileKind fileKind)
=> new()
{
Name = RenderMethodDisplay(fileKind),
Kind = Roslyn.LanguageServer.Protocol.SymbolKind.Method,
Range = LspFactory.DefaultRange,
SelectionRange = LspFactory.DefaultRange,
};

}
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.Threading;
Expand Down Expand Up @@ -31,8 +31,12 @@ protected override IRemoteDocumentSymbolService CreateService(in ServiceArgs arg

private async ValueTask<SumType<DocumentSymbol[], SymbolInformation[]>?> GetDocumentSymbolsAsync(RemoteDocumentContext context, bool useHierarchicalSymbols, CancellationToken cancellationToken)
{
var codeDocument = await context.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false);
var csharpDocument = codeDocument.GetCSharpDocument(declarationDocument: true)
?? codeDocument.GetRequiredCSharpDocument(declarationDocument: false);

var generatedDocument = await context.Snapshot
.GetGeneratedDocumentAsync(cancellationToken)
.GetGeneratedDocumentAsync(csharpDocument.IsDeclarationDocument, cancellationToken)
.ConfigureAwait(false);

var csharpSymbols = await DocumentSymbolsHandler.GetDocumentSymbolsAsync(
Expand All @@ -49,9 +53,6 @@ protected override IRemoteDocumentSymbolService CreateService(in ServiceArgs arg
csharpSymbols = ConvertDocumentSymbols(roslynDocumentSymbols);
}

var codeDocument = await context.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false);
var csharpDocument = codeDocument.GetRequiredImplCSharpDocument();

return _documentSymbolService.GetDocumentSymbols(context.Snapshot.FileKind, context.Uri, csharpDocument, csharpSymbols);
}

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.Threading;
Expand Down Expand Up @@ -40,9 +40,13 @@ protected override IRemoteSelectionRangeService CreateService(in ServiceArgs arg
{
var codeDocument = await context.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false);

using var mappedPositions = new PooledArrayBuilder<LinePosition>();
foreach (var position in positions)
// Each position can map to either the implementation or declaration C# document. Keep the
// position info in request order so we can query each generated document separately and still
// return selection ranges in the same order as the original request.
var positionInfos = new DocumentPositionInfo[positions.Length];
for (var i = 0; i < positions.Length; i++)
{
var position = positions[i];
if (!codeDocument.Source.Text.TryGetAbsoluteIndex(position, out var hostDocumentIndex))
{
return null;
Expand All @@ -54,30 +58,67 @@ protected override IRemoteSelectionRangeService CreateService(in ServiceArgs arg
return null;
}

mappedPositions.Add(positionInfo.Position.ToLinePosition());
positionInfos[i] = positionInfo;
}

var generatedDocument = await context.Snapshot
.GetGeneratedDocumentAsync(cancellationToken)
.ConfigureAwait(false);
var selectionRanges = new SelectionRange[positions.Length];

var linePositions = mappedPositions.ToImmutable();
var csharpSelectionRanges = await SelectionRangeHandler.GetSelectionRangesAsync(generatedDocument, linePositions, cancellationToken)
.ConfigureAwait(false);

if (csharpSelectionRanges is null)
if (!await AddSelectionRangesAsync(inDeclDocument: false, cancellationToken).ConfigureAwait(false))
{
return null;
}

var csharpDocument = codeDocument.GetRequiredImplCSharpDocument();
var selectionRanges = new SelectionRange[csharpSelectionRanges.Length];
for (var i = 0; i < csharpSelectionRanges.Length; i++)
if (!await AddSelectionRangesAsync(inDeclDocument: true, cancellationToken).ConfigureAwait(false))
{
selectionRanges[i] = MapSelectionRange(csharpDocument, csharpSelectionRanges[i], positions[i], isRoot: true)!;
return null;
}

return selectionRanges;

async ValueTask<bool> AddSelectionRangesAsync(
bool inDeclDocument,
CancellationToken cancellationToken)
{
// Roslyn selection range requests are scoped to a single document, so collect just the
// positions that belong to the requested generated C# document.
using var linePositions = new PooledArrayBuilder<LinePosition>();
foreach (var positionInfo in positionInfos)
{
if (positionInfo.InDeclDocument == inDeclDocument)
{
linePositions.Add(positionInfo.Position.ToLinePosition());
}
}

if (linePositions.Count == 0)
{
return true;
}

var generatedDocument = await context.Snapshot.GetGeneratedDocumentAsync(inDeclDocument, cancellationToken).ConfigureAwait(false);

var csharpSelectionRanges = await SelectionRangeHandler.GetSelectionRangesAsync(generatedDocument, linePositions.ToImmutable(), cancellationToken).ConfigureAwait(false);
if (csharpSelectionRanges is null)
{
return false;
}

var csharpDocument = codeDocument.GetRequiredCSharpDocument(inDeclDocument);
var csharpSelectionRangeIndex = 0;

// The Roslyn results match the filtered line position order. Walk the original positions
// again so each mapped result goes back to its original request index.
for (var i = 0; i < positionInfos.Length; i++)
{
if (positionInfos[i].InDeclDocument == inDeclDocument)
{
selectionRanges[i] = MapSelectionRange(csharpDocument, csharpSelectionRanges[csharpSelectionRangeIndex], positions[i], isRoot: true)!;
csharpSelectionRangeIndex++;
}
}

return true;
}
}

private SelectionRange? MapSelectionRange(RazorCSharpDocument csharpDocument, SelectionRange? csharpSelectionRange, Position originalPosition, bool isRoot)
Expand Down
Loading
Loading