Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
Expand Up @@ -4,7 +4,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
Expand All @@ -13,6 +12,7 @@
using Microsoft.CodeAnalysis.Razor;
using Microsoft.CodeAnalysis.Razor.ProjectSystem;
using Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.Remote.Razor.DocumentMapping;

Expand All @@ -25,32 +25,88 @@ public async Task MapWorkspaceEditAsync(IDocumentSnapshot contextDocumentSnapsho
throw new InvalidOperationException("RemoteRazorEditService can only be used with RemoteDocumentSnapshot instances.");
}

// Collect both workspace edit shapes into TextDocumentEdits so URI coalescing and duplicate
// edit handling run once across the whole edit.
using var builder = new PooledArrayBuilder<SumType<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>();

if (workspaceEdit.DocumentChanges is not null)
{
using var builder = new PooledArrayBuilder<SumType<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>();
foreach (var edit in workspaceEdit.EnumerateEdits())
{
if (edit.TryGetFirst(out var textDocumentEdit))
{
await MapTextDocumentEditAsync(originSnapshot, textDocumentEdit, cancellationToken).ConfigureAwait(false);
if (textDocumentEdit.Edits.Length == 0)
{
continue;
}
}

builder.Add(edit);
}

workspaceEdit.DocumentChanges = builder.ToArrayAndClear();
}

if (workspaceEdit.Changes is { } changeMap)
{
workspaceEdit.Changes = await MapDocumentEditsAsync(originSnapshot, changeMap, cancellationToken).ConfigureAwait(false);
builder.AddRange(await MapDocumentEditsAsync(originSnapshot, changeMap, cancellationToken).ConfigureAwait(false));
}

var solution = originSnapshot.TextDocument.Project.Solution;
var normalizedDocumentChanges = await NormalizeDocumentChangesAsync(solution, builder.ToArrayAndClear(), cancellationToken).ConfigureAwait(false);
if (workspaceEdit.DocumentChanges is not null)
{
workspaceEdit.DocumentChanges = normalizedDocumentChanges;
}
else
{
workspaceEdit.Changes = ConvertToChangeMap(normalizedDocumentChanges);
}
}

private static async Task<SumType<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>[]> NormalizeDocumentChangesAsync(
Solution solution,
SumType<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>[] documentChanges,
CancellationToken cancellationToken)
{
// Multiple generated C# documents can map edits back to the same Razor document.
// Keep one TextDocumentEdit per URI so duplicate mapped edits are applied against the same source text.
using var _ = DictionaryPool<DocumentUri, TextDocumentEdit>.GetPooledObject(out var textDocumentEditsByUri);
using var builder = new PooledArrayBuilder<SumType<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>(documentChanges.Length);

foreach (var documentChange in documentChanges)
{
if (!documentChange.TryGetFirst(out var textDocumentEdit))
{
builder.Add(documentChange);
continue;
}

if (textDocumentEdit.Edits.Length == 0)
{
continue;
}

var uri = textDocumentEdit.TextDocument.DocumentUri;
if (!textDocumentEditsByUri.TryGetValue(uri, out var existingTextDocumentEdit))
{
textDocumentEditsByUri.Add(uri, textDocumentEdit);
builder.Add(textDocumentEdit);
continue;
}

existingTextDocumentEdit.Edits = [.. existingTextDocumentEdit.Edits, .. textDocumentEdit.Edits];
}

// After coalescing by URI, collapse exact duplicate edits that can be produced by the
// implementation and declaration generated documents mapping to the same Razor span.
var normalizedDocumentChanges = builder.ToArrayAndClear();
foreach (var documentChange in normalizedDocumentChanges)
{
if (documentChange.TryGetFirst(out var textDocumentEdit))
{
await DeduplicateTextDocumentEditAsync(solution, textDocumentEdit, cancellationToken).ConfigureAwait(false);
}
}

return normalizedDocumentChanges;
}

private async Task MapTextDocumentEditAsync(RemoteDocumentSnapshot contextDocumentSnapshot, TextDocumentEdit entry, CancellationToken cancellationToken)
{
var generatedDocumentUri = entry.TextDocument.DocumentUri.GetRequiredSystemUri();
Expand Down Expand Up @@ -104,9 +160,11 @@ private async Task MapTextDocumentEditAsync(RemoteDocumentSnapshot contextDocume
entry.Edits = mappedEdits.SelectAsPlainArray(static e => new SumType<TextEdit, AnnotatedTextEdit>(e));
}

private async Task<Dictionary<string, TextEdit[]>> MapDocumentEditsAsync(RemoteDocumentSnapshot contextDocumentSnapshot, Dictionary<string, TextEdit[]> changes, CancellationToken cancellationToken)
private async Task<SumType<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>[]> MapDocumentEditsAsync(RemoteDocumentSnapshot contextDocumentSnapshot, Dictionary<string, TextEdit[]> changes, CancellationToken cancellationToken)
{
var mappedChanges = new Dictionary<string, TextEdit[]>(capacity: changes.Count);
// Map legacy Changes into TextDocumentEdits so MapWorkspaceEditAsync can normalize both shapes together.
using var builder = new PooledArrayBuilder<SumType<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>(changes.Count);
var solution = contextDocumentSnapshot.TextDocument.Project.Solution;

foreach (var (uriString, edits) in changes)
{
Expand All @@ -116,17 +174,17 @@ private async Task<Dictionary<string, TextEdit[]>> MapDocumentEditsAsync(RemoteD
if (_filePathService.IsVirtualHtmlFile(generatedDocumentUri))
{
var razorUri = _filePathService.GetRazorDocumentUri(generatedDocumentUri);
mappedChanges[razorUri.AbsoluteUri] = edits;
builder.Add(CreateTextDocumentEdit(razorUri.CreateDocumentUriFromSystemUri(), edits.AsSpan()));
continue;
}

// Check if the edit is actually for a generated document, because if not we don't need to do anything
if (!_filePathService.IsVirtualCSharpFile(generatedDocumentUri))
{
mappedChanges[uriString] = edits;
builder.Add(CreateTextDocumentEdit(new(uriString), edits.AsSpan()));
continue;
}

var solution = contextDocumentSnapshot.TextDocument.Project.Solution;
var razorDocument = await _snapshotManager.TryGetRazorDocumentAsync(solution, generatedDocumentUri, cancellationToken).ConfigureAwait(false);
if (razorDocument is null)
{
Expand All @@ -147,10 +205,48 @@ private async Task<Dictionary<string, TextEdit[]>> MapDocumentEditsAsync(RemoteD
continue;
}

mappedChanges[razorDocument.CreateSystemUri().AbsoluteUri] = ImmutableCollectionsMarshal.AsArray(mappedEdits)!;
builder.Add(CreateTextDocumentEdit(razorDocument.GetURI(), mappedEdits.AsSpan()));
}

return builder.ToArrayAndClear();
}

private static TextDocumentEdit CreateTextDocumentEdit(DocumentUri documentUri, ReadOnlySpan<TextEdit> edits)
{
var textEdits = new SumType<TextEdit, AnnotatedTextEdit>[edits.Length];
for (var i = 0; i < edits.Length; i++)
{
textEdits[i] = edits[i];
}

return new TextDocumentEdit
{
TextDocument = new OptionalVersionedTextDocumentIdentifier { DocumentUri = documentUri },
Edits = textEdits
};
}

private static Dictionary<string, TextEdit[]> ConvertToChangeMap(SumType<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>[] documentChanges)
{
var changes = new Dictionary<string, TextEdit[]>(capacity: documentChanges.Length);

foreach (var documentChange in documentChanges)
{
if (documentChange.TryGetFirst(out var textDocumentEdit))
{
var textEdits = new TextEdit[textDocumentEdit.Edits.Length];
for (var i = 0; i < textDocumentEdit.Edits.Length; i++)
{
textEdits[i] = (TextEdit)textDocumentEdit.Edits[i];
}

changes.Add(
textDocumentEdit.TextDocument.DocumentUri.GetRequiredSystemUri().AbsoluteUri,
textEdits);
}
}

return mappedChanges;
return changes;
}

private async Task<ImmutableArray<TextEdit>> GetMappedTextEditsAsync(RemoteDocumentSnapshot snapshot, RazorCSharpDocument csharpDocument, TextEdit[] edits, CancellationToken cancellationToken)
Expand All @@ -162,4 +258,44 @@ private async Task<ImmutableArray<TextEdit>> GetMappedTextEditsAsync(RemoteDocum

return mappedEdits.SelectAsArray(razorSourceText.GetTextEdit);
}

private static async Task DeduplicateTextDocumentEditAsync(Solution solution, TextDocumentEdit entry, CancellationToken cancellationToken)
{
if (entry.Edits.Length <= 1)
{
return;
}

var document = await solution.GetTextDocumentAsync(entry.TextDocument, cancellationToken).ConfigureAwait(false);
if (document is null)
{
return;
}

var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
entry.Edits = Deduplicate(sourceText, entry.Edits);
Comment thread
davidwengier marked this conversation as resolved.
Resolved
}

private static SumType<TextEdit, AnnotatedTextEdit>[] Deduplicate(SourceText sourceText, SumType<TextEdit, AnnotatedTextEdit>[] edits)
{
if (edits.Length <= 1)
{
return edits;
}

using var _ = HashSetPool<(int Start, int Length, string? NewText)>.GetPooledObject(out var seenEdits);
using var builder = new PooledArrayBuilder<SumType<TextEdit, AnnotatedTextEdit>>(edits.Length);

foreach (var edit in edits)
{
var textEdit = (TextEdit)edit;
var change = sourceText.GetTextChange(textEdit);
if (seenEdits.Add((change.Span.Start, change.Span.Length, change.NewText)))
{
builder.Add(edit);
}
}
Comment thread
davidwengier marked this conversation as resolved.
Resolved

return builder.ToArrayAndClear();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ protected override IRemoteRenameService CreateService(in ServiceArgs args)
var positionInfo = GetPositionInfo(codeDocument, hostDocumentIndex, preferCSharpOverHtml: true);

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

var razorEdit = await _renameService
Expand Down Expand Up @@ -134,7 +134,7 @@ protected override IRemoteRenameService CreateService(in ServiceArgs args)
return RemoteResponse<LspRange?>.CallHtml;
}

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

var csharpRange = await PrepareRenameHandler.GetRenameRangeAsync(generatedDocument, positionInfo.Position.ToLinePosition(), cancellationToken).ConfigureAwait(false);

Expand All @@ -143,7 +143,7 @@ protected override IRemoteRenameService CreateService(in ServiceArgs args)
return RemoteResponse<LspRange?>.NoFurtherHandling;
}

if (!DocumentMappingService.TryMapToRazorDocumentRange(codeDocument.GetRequiredImplCSharpDocument(), csharpRange, out var mappedRange))
if (!DocumentMappingService.TryMapToRazorDocumentRange(codeDocument.GetRequiredCSharpDocument(positionInfo.InDeclDocument), csharpRange, out var mappedRange))
{
return RemoteResponse<LspRange?>.NoFurtherHandling;
}
Expand Down Expand Up @@ -228,7 +228,11 @@ protected override IRemoteRenameService CreateService(in ServiceArgs args)
return null;
}

var generatedDocument = await context.Snapshot.GetGeneratedDocumentAsync(cancellationToken).ConfigureAwait(false);
// Component file rename updates the generated component class declaration, which lives in the
// declaration document under SONIC. Fall back to implementation for legacy documents that do
// not have a separate declaration document.
var generatedDocument = await context.Snapshot.TryGetGeneratedDocumentAsync(declarationDocument: true, cancellationToken).ConfigureAwait(false)
?? await context.Snapshot.GetGeneratedDocumentAsync(declarationDocument: false, cancellationToken).ConfigureAwait(false);
Comment thread
davidwengier marked this conversation as resolved.
Resolved
var text = await generatedDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var tree = await generatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var declaration = tree.AssumeNotNull().DescendantNodes().OfType<ClassDeclarationSyntax>().FirstOrDefault();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Microsoft.VisualStudio.Razor.LanguageClient.Cohost;

public class CohostPrepareRenameEndpointTest(ITestOutputHelper testOutputHelper) : CohostEndpointTestBase(testOutputHelper)
{
[Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")]
[Fact]
public Task CSharp_Method()
=> VerifyPrepareRenameAsync(
input: """
Expand Down
Loading
Loading