From e215f26c837160b56c9b6e3824be9e07ac29c030 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Wed, 3 Jun 2026 17:25:34 +1000 Subject: [PATCH 01/10] Add new helper methods to deal with having multiple documents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I think it's 50/50 whether these helpers make it to the main branch, but for now it's really convenient to be able to obsolete all of the old methods, and be able to see which code has been modified to be explicit, and which are just using the old methods. I realise, in hindsight, that it was my own comment on a previous PR that caused things to be in this state 🤦‍♂️ --- .../src/Language/RazorCodeDocument.cs | 6 +++ .../Extensions/ProjectExtensions.cs | 40 +++++++++++++++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCodeDocument.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCodeDocument.cs index 4efecd29dded2..787a046e87cb4 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCodeDocument.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/RazorCodeDocument.cs @@ -261,6 +261,12 @@ internal RazorCodeDocument WithDocumentNode(DocumentIntermediateNode value) return new RazorCodeDocument(Source, Imports, ParserOptions, CodeGenerationOptions, _tagHelpers, _referencedTagHelpers, _syntaxTree, _tagHelperRewrittenSyntaxTree, _importSyntaxTrees, _tagHelperContext, value, _csharpDocument, _declCSharpDocument, _directiveTagHelperContributions); } + internal RazorCSharpDocument? GetCSharpDocument(bool declarationDocument) + => declarationDocument ? _declCSharpDocument : _csharpDocument; + + internal RazorCSharpDocument GetRequiredCSharpDocument(bool declarationDocument) + => GetCSharpDocument(declarationDocument).AssumeNotNull(); + internal bool TryGetImplCSharpDocument([NotNullWhen(true)] out RazorCSharpDocument? result) { result = _csharpDocument; diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs index f15b11ec0498f..d7f2836faed00 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs @@ -65,14 +65,19 @@ public static async ValueTask GetTagHelpersAsync( return generatedDocuments.SingleOrDefault(d => d.HintName == hintName); } + public static async Task TryGetSourceGeneratedDocumentForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken) + { + return (await TryGetSourceGeneratedDocumentsForRazorDocumentAsync(project, razorDocument, cancellationToken).ConfigureAwait(false)).ImplDoc; + } + /// /// Finds source generated documents by iterating through all of them. In OOP there are better options! /// - public static async Task TryGetSourceGeneratedDocumentForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken) + public static async Task<(SourceGeneratedDocument? ImplDoc, SourceGeneratedDocument? DeclDoc)> TryGetSourceGeneratedDocumentsForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken) { if (razorDocument.FilePath is null) { - return null; + return (null, null); } var generatedDocuments = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); @@ -80,10 +85,16 @@ public static async ValueTask GetTagHelpersAsync( // For misc files, and projects that don't have a globalconfig file (eg, non Razor SDK projects), the hint name will be based // on the full path of the file. var fullPathHintName = RazorSourceGenerator.GetIdentifierFromPath(razorDocument.FilePath); + var fullPathDeclHintName = RazorSourceGenerator.GetDeclIdentifierFromHintName(fullPathHintName); // For normal Razor SDK projects, the hint name will be based on the project-relative path of the file. var projectRelativeHintName = GetProjectRelativeHintName(razorDocument); + var projectRelativeDeclHintName = projectRelativeHintName is null ? null : RazorSourceGenerator.GetDeclIdentifierFromHintName(projectRelativeHintName); + + SourceGeneratedDocument? fullPathMatchedDoc = null; + SourceGeneratedDocument? fullPathMatchedDeclDoc = null; SourceGeneratedDocument? candidateDoc = null; + SourceGeneratedDocument? candidateDeclDoc = null; foreach (var doc in generatedDocuments) { if (!doc.IsRazorSourceGeneratedDocument()) @@ -94,7 +105,15 @@ public static async ValueTask GetTagHelpersAsync( if (doc.HintName == fullPathHintName) { // If the full path matches, we've found it for sure - return doc; + fullPathMatchedDoc = doc; + } + else if (doc.HintName == fullPathDeclHintName) + { + fullPathMatchedDeclDoc = doc; + } + else if (doc.HintName == projectRelativeDeclHintName) + { + candidateDeclDoc = doc; } else if (doc.HintName == projectRelativeHintName) { @@ -110,7 +129,20 @@ public static async ValueTask GetTagHelpersAsync( } } - return candidateDoc; + // Full path matches take precedence over candidates + if (fullPathMatchedDoc is not null) + { + return (fullPathMatchedDoc, fullPathMatchedDeclDoc); + } + + // If we didn't find a candidate impl doc, or found mulitple, bail out so we don't confuse callers in case there is a weird + // bug where its possible to have duplicate impl docs and one decl doc + if (candidateDoc is null) + { + return (null, null); + } + + return (candidateDoc, candidateDeclDoc); static string? GetProjectRelativeHintName(TextDocument razorDocument) { From 5b15f516d13d08196f60f38290fe410b05233f7a Mon Sep 17 00:00:00 2001 From: David Wengier Date: Wed, 3 Jun 2026 17:28:37 +1000 Subject: [PATCH 02/10] Unskip tests --- .../Endpoints/CohostDocumentPullDiagnosticsTest.cs | 14 +++++++------- .../Cohost/CohostDocumentPullDiagnosticsTest.cs | 6 +++--- .../Endpoints/CohostDocumentPullDiagnosticsTest.cs | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs index 89983c4d5ab89..1ca4092dcba0b 100644 --- a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs @@ -23,7 +23,7 @@ public void IJustMetYou() } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task CSharp() => VerifyDiagnosticsAsync("""
@@ -47,7 +47,7 @@ public Task Razor() """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task CSharpAndRazor_MiscellaneousFile() => VerifyDiagnosticsAsync("""
@@ -66,7 +66,7 @@ public void IJustMetYou() """, miscellaneousFile: true); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task CombinedAndNestedDiagnostics() => VerifyDiagnosticsAsync(""" @using System.Threading.Tasks; @@ -94,7 +94,7 @@ public void IJustMetYou()
"""); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task CSharpUnusedUsings() => VerifyDiagnosticsAsync(""" {|RZ0005:@using System|} @@ -110,7 +110,7 @@ public void BuildsStrings(StringBuilder b) } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task RazorUsingAlsoPresentInImports() => VerifyDiagnosticsAsync(""" @using System.Text @@ -128,7 +128,7 @@ public void BuildsStrings(StringBuilder b) } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task RazorUsedUsings() => VerifyDiagnosticsAsync( input: """ @@ -155,7 +155,7 @@ @namespace My.Fun.Namespace
""")]); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task RazorUnusedUsings() => VerifyDiagnosticsAsync( input: """ diff --git a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs index 0c146a9a0796f..715b67b42c531 100644 --- a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs @@ -22,7 +22,7 @@ namespace Microsoft.VisualStudio.Razor.LanguageClient.Cohost; public partial class CohostDocumentPullDiagnosticsTest { - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public async Task CSharpUnusedUsings_WarningDiagnosticsInVS() { var document = CreateProjectAndRazorDocument(""" @@ -56,7 +56,7 @@ public void BuildsStrings(StringBuilder b) tag => Assert.Equal(DiagnosticTag.Unnecessary, tag)); } - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task OneOfEachDiagnostic() { TestCode input = """ @@ -551,7 +551,7 @@ Task Send() => }]); } - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task TODOComments() => VerifyDiagnosticsAsync(""" @using System.Threading.Tasks; diff --git a/src/Razor/src/Razor/test/Microsoft.VisualStudioCode.RazorExtension.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs b/src/Razor/src/Razor/test/Microsoft.VisualStudioCode.RazorExtension.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs index 23f97c62ac6fa..27f73243eaa38 100644 --- a/src/Razor/src/Razor/test/Microsoft.VisualStudioCode.RazorExtension.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.VisualStudioCode.RazorExtension.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs @@ -21,7 +21,7 @@ namespace Microsoft.VisualStudio.Razor.LanguageClient.Cohost; public partial class CohostDocumentPullDiagnosticsTest { - [Fact(Skip = "PROTOTYPE(sonic): unused-using diagnostics are emitted from both the impl and decl halves of the split generated source, so this test sees 2 RZ0005 diagnostics back-mapped to the same razor position instead of 1. Needs decl/impl-aware diagnostic dedup. See PR #83887.")] + [Fact] public async Task CSharpUnusedUsings_HintDiagnosticsInVSCode() { var document = CreateProjectAndRazorDocument(""" From 79fd136467cebe6fe30721a0faf9e5b4cc591675 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Wed, 3 Jun 2026 17:29:00 +1000 Subject: [PATCH 03/10] Add new test coverage for missing scenarios --- .../CohostDocumentPullDiagnosticsTest.cs | 16 ++++++++++++++++ .../Cohost/CohostDocumentPullDiagnosticsTest.cs | 6 +++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs index 1ca4092dcba0b..800adee7dbf37 100644 --- a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs @@ -37,6 +37,14 @@ public void IJustMetYou() } """); + [Fact] + public Task CSharp_ImplicitExpression() + => VerifyDiagnosticsAsync(""" +
+ + @{|CS0103:CallMeMaybe|}() + """); + [Fact] public Task Razor() => VerifyDiagnosticsAsync(""" @@ -110,6 +118,14 @@ public void BuildsStrings(StringBuilder b) } """); + [Fact] + public Task CSharpUnusedUsings_NoCodeBlock() + => VerifyDiagnosticsAsync(""" + {|RZ0005:@using System|} + +
+ """); + [Fact] public Task RazorUsingAlsoPresentInImports() => VerifyDiagnosticsAsync(""" diff --git a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs index 715b67b42c531..45151dcd8f738 100644 --- a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs @@ -558,6 +558,10 @@ public Task TODOComments() // TODO: This isn't C# + @{ + // {|TODO:|}TODO: This is C# in an impl document + } + TODO: Nor is this
@@ -570,7 +574,7 @@ public Task TODOComments() @code { // This looks different because Roslyn only reports zero width ranges for task lists - // {|TODO:|}TODO: Write some C# code too + // {|TODO:|}TODO: Write some C# code in a decl document too } """, taskListRequest: true); From 6cc8841042fe37e4d1d0db7e769befcb56e441eb Mon Sep 17 00:00:00 2001 From: David Wengier Date: Wed, 3 Jun 2026 17:31:28 +1000 Subject: [PATCH 04/10] Make two C# requests and plumb both sets of diagnostics through to the end mapped result --- ...hostDocumentPullDiagnosticsEndpointBase.cs | 37 ++-- .../DocumentMapping/DocumentPositionInfo.cs | 3 +- .../Remote/IRemoteDiagnosticsService.cs | 6 +- .../RazorTranslateDiagnosticsService.cs | 168 +++++++++++++----- .../Diagnostics/RemoteDiagnosticsService.cs | 27 +-- .../CohostDocumentPullDiagnosticsEndpoint.cs | 33 ++-- 6 files changed, 192 insertions(+), 82 deletions(-) diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs index 08de668b7049d..1ca98990ccbd6 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs @@ -80,13 +80,13 @@ protected virtual TRequest CreateHtmlParams(Uri uri) return null; } - var csharpDiagnostics = csharpTask.VerifyCompleted(); + var (implDiagnostics, declDiagnostics) = csharpTask.VerifyCompleted(); var htmlDiagnostics = htmlTask.VerifyCompleted(); - _logger.LogDebug($"Calling OOP with the {csharpDiagnostics.Length} C# and {htmlDiagnostics.Length} Html diagnostics"); + _logger.LogDebug($"Calling OOP with the {implDiagnostics.Length} impl C# and {declDiagnostics.Length} decl C# and {htmlDiagnostics.Length} Html diagnostics"); var diagnostics = await _remoteServiceInvoker.TryInvokeAsync>( razorDocument.Project.Solution, - (service, solutionInfo, cancellationToken) => service.GetDiagnosticsAsync(solutionInfo, razorDocument.Id, csharpDiagnostics, htmlDiagnostics, cancellationToken), + (service, solutionInfo, cancellationToken) => service.GetDiagnosticsAsync(solutionInfo, razorDocument.Id, implDiagnostics, declDiagnostics, htmlDiagnostics, cancellationToken), cancellationToken).ConfigureAwait(false); if (cancellationToken.IsCancellationRequested || diagnostics.IsDefault) @@ -98,25 +98,32 @@ protected virtual TRequest CreateHtmlParams(Uri uri) return [.. diagnostics]; } - protected static Task TryGetGeneratedDocumentAsync(TextDocument razorDocument, CancellationToken cancellationToken) + private async Task<(LspDiagnostic[], LspDiagnostic[])> GetCSharpDiagnosticsAsync(TextDocument razorDocument, Guid correletionId, CancellationToken cancellationToken) { - return razorDocument.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(razorDocument, cancellationToken); - } + // Because we can't map from a random C# point to a Razor point without knowing which C# document we're talking about, we have to just make two requests + // and send back two sets of diagnostics - private async Task GetCSharpDiagnosticsAsync(TextDocument razorDocument, Guid correletionId, CancellationToken cancellationToken) - { - var generatedDocument = await TryGetGeneratedDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); - if (generatedDocument is null) + var generatedDocuments = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); + if (generatedDocuments.ImplDoc is null) { - return []; + return ([], []); } - _logger.LogDebug($"Getting C# diagnostics for {generatedDocument.FilePath}"); - using var _ = _telemetryReporter.TrackLspRequest(LspMethodName, "Razor.ExternalAccess", TelemetryThresholds.DiagnosticsSubLSPTelemetryThreshold, correletionId); var supportsVisualStudioExtensions = _clientCapabilitiesService.ClientCapabilities.SupportsVisualStudioExtensions; - var diagnostics = await CohostDocumentPullDiagnosticsHelpers.GetDocumentDiagnosticsAsync(generatedDocument, supportsVisualStudioExtensions, cancellationToken).ConfigureAwait(false); - return [.. diagnostics]; + + _logger.LogDebug($"Getting C# diagnostics for {generatedDocuments.ImplDoc.FilePath}"); + var implDiagnostics = await CohostDocumentPullDiagnosticsHelpers.GetDocumentDiagnosticsAsync(generatedDocuments.ImplDoc, supportsVisualStudioExtensions, cancellationToken).ConfigureAwait(false); + + if (generatedDocuments.DeclDoc is null) + { + return (implDiagnostics, []); + } + + _logger.LogDebug($"Getting C# diagnostics for {generatedDocuments.DeclDoc.FilePath}"); + var declDiagnostics = await CohostDocumentPullDiagnosticsHelpers.GetDocumentDiagnosticsAsync(generatedDocuments.DeclDoc, supportsVisualStudioExtensions, cancellationToken).ConfigureAwait(false); + + return (implDiagnostics, declDiagnostics); } private async Task GetHtmlDiagnosticsAsync(TextDocument razorDocument, Guid correletionId, CancellationToken cancellationToken) diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/DocumentPositionInfo.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/DocumentPositionInfo.cs index 69695930152c1..a91b077ad2c89 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/DocumentPositionInfo.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/DocumentPositionInfo.cs @@ -13,5 +13,6 @@ namespace Microsoft.CodeAnalysis.Razor.DocumentMapping; internal readonly record struct DocumentPositionInfo( [property: JsonPropertyName("languageKind")] RazorLanguageKind LanguageKind, [property: JsonPropertyName("position")] Position Position, - [property: JsonPropertyName("hostDocumentIndex")] int HostDocumentIndex); + [property: JsonPropertyName("hostDocumentIndex")] int HostDocumentIndex, + [property: JsonPropertyName("inDeclDocument")] bool InDeclDocument = false); diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Remote/IRemoteDiagnosticsService.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Remote/IRemoteDiagnosticsService.cs index 403f6504792e9..44e4562c77107 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Remote/IRemoteDiagnosticsService.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Remote/IRemoteDiagnosticsService.cs @@ -12,13 +12,15 @@ internal interface IRemoteDiagnosticsService : IRemoteJsonService ValueTask> GetDiagnosticsAsync( JsonSerializableRazorSolutionWrapper solutionInfo, JsonSerializableDocumentId documentId, - LspDiagnostic[] csharpDiagnostics, + LspDiagnostic[] csharpImplDiagnostics, + LspDiagnostic[] csharpDeclDiagnostics, LspDiagnostic[] htmlDiagnostics, CancellationToken cancellationToken); ValueTask> GetTaskListDiagnosticsAsync( JsonSerializableRazorSolutionWrapper solutionInfo, JsonSerializableDocumentId documentId, - LspDiagnostic[] csharpTaskItems, + LspDiagnostic[] csharpImplTaskItems, + LspDiagnostic[] csharpDeclTaskItems, CancellationToken cancellationToken); } diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs index 40e082c15a2b2..698d6cf8f43e9 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs @@ -16,7 +16,6 @@ using Microsoft.CodeAnalysis.Razor.DocumentMapping; using Microsoft.CodeAnalysis.Razor.Logging; using Microsoft.CodeAnalysis.Razor.ProjectSystem; -using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.Text; @@ -40,10 +39,6 @@ internal sealed class RazorTranslateDiagnosticsService(IDocumentMappingService d /// /// Translates code diagnostics from one representation into another. /// - /// - /// The of the objects - /// included in . - /// /// /// An array of objects to translate. /// @@ -52,32 +47,25 @@ internal sealed class RazorTranslateDiagnosticsService(IDocumentMappingService d /// /// A token that can be checked to cancel work. /// An array of translated diagnostics - internal async Task TranslateAsync( - RazorLanguageKind diagnosticKind, + internal async Task TranslateHtmlAsync( LspDiagnostic[] diagnostics, RemoteDocumentSnapshot documentSnapshot, CancellationToken cancellationToken) { var codeDocument = await documentSnapshot.GetGeneratedOutputAsync(cancellationToken).ConfigureAwait(false); - var filteredDiagnostics = diagnosticKind == RazorLanguageKind.CSharp - ? FilterCSharpDiagnostics(diagnostics, codeDocument) - : FilterHTMLDiagnostics(diagnostics, codeDocument); + var filteredDiagnostics = FilterHTMLDiagnostics(diagnostics, codeDocument); if (filteredDiagnostics.Length == 0) { - _logger.LogDebug($"No diagnostics remaining after filtering."); + _logger.LogDebug($"No Html diagnostics remaining after filtering."); return []; } - _logger.LogDebug($"{filteredDiagnostics.Length}/{diagnostics.Length} diagnostics remain after filtering {diagnosticKind}."); + _logger.LogDebug($"{filteredDiagnostics.Length}/{diagnostics.Length} diagnostics remain after filtering Html."); - var mappedDiagnostics = MapDiagnostics( - diagnosticKind, - filteredDiagnostics, - documentSnapshot, - codeDocument); + OverwriteProjectInformation(filteredDiagnostics, documentSnapshot); - return mappedDiagnostics; + return filteredDiagnostics; } private static LspDiagnostic[] FilterHTMLDiagnostics( @@ -101,39 +89,129 @@ private static LspDiagnostic[] FilterHTMLDiagnostics( return filteredDiagnostics; } - internal LspDiagnostic[] MapDiagnostics( - RazorLanguageKind languageKind, - LspDiagnostic[] diagnostics, + internal async Task TranslateCSharpAsync( + LspDiagnostic[] implDiagnostics, + LspDiagnostic[] declDiagnostics, RemoteDocumentSnapshot documentSnapshot, - RazorCodeDocument codeDocument) + CancellationToken cancellationToken) { - var projects = RazorDiagnosticHelper.GetProjectInformation(documentSnapshot); - using var mappedDiagnostics = new PooledArrayBuilder(); + var codeDocument = await documentSnapshot.GetGeneratedOutputAsync(cancellationToken).ConfigureAwait(false); + var implDocument = codeDocument.GetRequiredCSharpDocument(declarationDocument: false); + var declDocument = codeDocument.GetCSharpDocument(declarationDocument: true); - foreach (var diagnostic in diagnostics) + var filteredImplDiagnostics = FilterCSharpDiagnostics(implDiagnostics, implDocument); + var filteredDeclDiagnostics = declDocument is not null + ? FilterCSharpDiagnostics(declDiagnostics, declDocument) + : []; + + if (filteredImplDiagnostics.Length + filteredDeclDiagnostics.Length == 0) { - // C# requests don't map directly to where they are in the document. - if (languageKind == RazorLanguageKind.CSharp) + _logger.LogDebug($"No C# diagnostics remaining after filtering."); + return []; + } + + _logger.LogDebug($"{filteredImplDiagnostics.Length}/{implDiagnostics.Length} diagnostics remain after filtering C# impl."); + _logger.LogDebug($"{filteredDeclDiagnostics.Length}/{declDiagnostics.Length} diagnostics remain after filtering C# decl."); + + var mappedImplDiagnostics = MapCSharpDiagnostics(filteredImplDiagnostics, implDocument); + var mappedDeclDiagnostics = declDocument is not null + ? MapCSharpDiagnostics(filteredDeclDiagnostics, declDocument) + : []; + + // Now that we've mapped and filtered the C# diagnostics, but before we flatten them to one list, we need to process the + // unused using directives diagnostics. The compiler puts all of the users usings in both documents, so an unused using + // directive from one document, doesn't matter unless it appears in the other as well. + + // If there is no decl document though, we just used the impl diagnostics unfiltered + var finalDiagnostics = declDocument is not null + ? FilterUnusedUsingDirectiveDiagnostics(mappedImplDiagnostics, mappedDeclDiagnostics) + : mappedImplDiagnostics; + + OverwriteProjectInformation(finalDiagnostics, documentSnapshot); + + return finalDiagnostics; + } + + private static LspDiagnostic[] FilterUnusedUsingDirectiveDiagnostics(LspDiagnostic[] implDiagnostics, LspDiagnostic[] declDiagnostics) + { + using var filteredDiagnostics = new PooledArrayBuilder(); + + foreach (var diagnostic in implDiagnostics) + { + if (diagnostic.Code is not { Value: RemoveUnnecessaryImportsConstants.IDE0005_gen } || + ContainsMatchingGeneratedRemoveUnnecessaryImportsDiagnostic(declDiagnostics, diagnostic)) { - if (!TryGetOriginalDiagnosticRange(diagnostic, codeDocument, out var originalRange)) + filteredDiagnostics.Add(diagnostic); + } + } + + // By definition any diagnostics in decl that we want to keep will be kept because they will have a matching diagnostic in impl, + // so we can just need to filter decl diagnostics to ignore all unused using directives. + foreach (var diagnostic in declDiagnostics) + { + if (diagnostic.Code is not { Value: RemoveUnnecessaryImportsConstants.IDE0005_gen }) + { + filteredDiagnostics.Add(diagnostic); + } + } + + return filteredDiagnostics.ToArrayAndClear(); + + static bool ContainsMatchingGeneratedRemoveUnnecessaryImportsDiagnostic( + LspDiagnostic[] diagnostics, + LspDiagnostic diagnostic) + { + foreach (var otherDiagnostic in diagnostics) + { + if (diagnostic.Code is { Value: RemoveUnnecessaryImportsConstants.IDE0005_gen } && + IsSameDiagnosticSpan(diagnostic, otherDiagnostic)) { - continue; + return true; } + } + + return false; + } - diagnostic.Range = originalRange; + static bool IsSameDiagnosticSpan(LspDiagnostic diagnostic, LspDiagnostic otherDiagnostic) + => diagnostic.Range?.Start.Line == otherDiagnostic.Range?.Start.Line && + diagnostic.Range?.Start.Character == otherDiagnostic.Range?.Start.Character && + diagnostic.Range?.End.Line == otherDiagnostic.Range?.End.Line && + diagnostic.Range?.End.Character == otherDiagnostic.Range?.End.Character; + } + + internal LspDiagnostic[] MapCSharpDiagnostics(LspDiagnostic[] diagnostics, RazorCSharpDocument csharpDocument) + { + using var mappedDiagnostics = new PooledArrayBuilder(); + + foreach (var diagnostic in diagnostics) + { + // C# requests don't map directly to where they are in the document. + if (!TryGetOriginalDiagnosticRange(diagnostic, csharpDocument, out var originalRange)) + { + continue; } + diagnostic.Range = originalRange; + + mappedDiagnostics.Add(diagnostic); + } + + return mappedDiagnostics.ToArrayAndClear(); + } + + internal static void OverwriteProjectInformation(LspDiagnostic[] diagnostics, RemoteDocumentSnapshot documentSnapshot) + { + var projects = RazorDiagnosticHelper.GetProjectInformation(documentSnapshot); + foreach (var diagnostic in diagnostics) + { if (diagnostic is VSDiagnostic vsDiagnostic) { // We're the ones reporting the diagnostic, and it shows up as coming from our filename (not the generated one), so // the project info should be consistent too vsDiagnostic.Projects = projects; } - - mappedDiagnostics.Add(diagnostic); } - - return mappedDiagnostics.ToArray(); } private static bool InRazorComment( @@ -474,7 +552,7 @@ GenericBlockSyntax or } } - private LspDiagnostic[] FilterCSharpDiagnostics(LspDiagnostic[] diagnostics, RazorCodeDocument codeDocument) + private LspDiagnostic[] FilterCSharpDiagnostics(LspDiagnostic[] diagnostics, RazorCSharpDocument csharpDocument) { using var filteredDiagnostics = new PooledArrayBuilder(); @@ -490,8 +568,8 @@ private LspDiagnostic[] FilterCSharpDiagnostics(LspDiagnostic[] diagnostics, Raz if (str switch { - "CS1525" => ShouldIgnoreCS1525(diagnostic, codeDocument), - RemoveUnnecessaryImportsConstants.IDE0005_gen => IsUsingDirectiveUsed(diagnostic, codeDocument), + "CS1525" => ShouldIgnoreCS1525(diagnostic, csharpDocument), + RemoveUnnecessaryImportsConstants.IDE0005_gen => IsUsingDirectiveUsed(diagnostic, csharpDocument), // This diagnostics is produced by Roslyn to help its Remove Usings code fixer, so is irrelevant to us RemoveUnnecessaryImportsConstants.DiagnosticFixableId => true, _ => false @@ -505,10 +583,10 @@ private LspDiagnostic[] FilterCSharpDiagnostics(LspDiagnostic[] diagnostics, Raz return filteredDiagnostics.ToArrayAndClear(); - bool ShouldIgnoreCS1525(LspDiagnostic diagnostic, RazorCodeDocument codeDocument) + bool ShouldIgnoreCS1525(LspDiagnostic diagnostic, RazorCSharpDocument csharpDocument) { - if (CheckIfDocumentHasRazorDiagnostic(codeDocument, RazorDiagnosticFactory.TagHelper_EmptyBoundAttribute.Id) && - TryGetOriginalDiagnosticRange(diagnostic, codeDocument, out var originalRange) && + if (CheckIfDocumentHasRazorDiagnostic(csharpDocument.CodeDocument, RazorDiagnosticFactory.TagHelper_EmptyBoundAttribute.Id) && + TryGetOriginalDiagnosticRange(diagnostic, csharpDocument, out var originalRange) && originalRange.IsUndefined()) { // Empty attribute values will take the following form in the generated C# document: @@ -524,8 +602,10 @@ bool ShouldIgnoreCS1525(LspDiagnostic diagnostic, RazorCodeDocument codeDocument } } - private bool IsUsingDirectiveUsed(LspDiagnostic diagnostic, RazorCodeDocument codeDocument) + private bool IsUsingDirectiveUsed(LspDiagnostic diagnostic, RazorCSharpDocument csharpDocument) { + var codeDocument = csharpDocument.CodeDocument; + // In imports files, all usings are considered used if (codeDocument.IsImportsFile()) { @@ -544,7 +624,7 @@ private bool IsUsingDirectiveUsed(LspDiagnostic diagnostic, RazorCodeDocument co // diagnostic. Conveniently, this means we don't need to worry about actually reporting our own // unused diagnostics, so it's worth it. var syntaxTree = codeDocument.GetRequiredTagHelperRewrittenSyntaxTree(); - if (TryGetOriginalDiagnosticRange(diagnostic, codeDocument, out var originalRange) && + if (TryGetOriginalDiagnosticRange(diagnostic, csharpDocument, out var originalRange) && syntaxTree.FindInnermostNode(codeDocument.Source.Text, originalRange.Start) is { Parent.Parent: RazorUsingDirectiveSyntax usingDirectiveSyntax }) { return codeDocument.IsDirectiveUsed(usingDirectiveSyntax); @@ -558,10 +638,10 @@ private static bool CheckIfDocumentHasRazorDiagnostic(RazorCodeDocument codeDocu return codeDocument.GetRequiredTagHelperRewrittenSyntaxTree().Diagnostics.Any(razorDiagnosticCode, static (d, code) => d.Id == code); } - private bool TryGetOriginalDiagnosticRange(LspDiagnostic diagnostic, RazorCodeDocument codeDocument, [NotNullWhen(true)] out LspRange? originalRange) + private bool TryGetOriginalDiagnosticRange(LspDiagnostic diagnostic, RazorCSharpDocument csharpDocument, [NotNullWhen(true)] out LspRange? originalRange) { if (!_documentMappingService.TryMapToRazorDocumentRange( - codeDocument.GetRequiredImplCSharpDocument(), + csharpDocument, diagnostic.Range, MappingBehavior.Inferred, out originalRange)) diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs index 022ca4a853fc3..469f124ad6e92 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs @@ -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.Collections.Immutable; @@ -35,18 +35,20 @@ protected override IRemoteDiagnosticsService CreateService(in ServiceArgs args) public ValueTask> GetDiagnosticsAsync( JsonSerializableRazorSolutionWrapper solutionInfo, JsonSerializableDocumentId documentId, - LspDiagnostic[] csharpDiagnostics, + LspDiagnostic[] csharpImplDiagnostics, + LspDiagnostic[] csharpDeclDiagnostics, LspDiagnostic[] htmlDiagnostics, CancellationToken cancellationToken) => RunServiceAsync( solutionInfo, documentId, - context => GetDiagnosticsAsync(context, csharpDiagnostics, htmlDiagnostics, cancellationToken), + context => GetDiagnosticsAsync(context, csharpImplDiagnostics, csharpDeclDiagnostics, htmlDiagnostics, cancellationToken), cancellationToken); private async ValueTask> GetDiagnosticsAsync( RemoteDocumentContext context, - LspDiagnostic[] csharpDiagnostics, + LspDiagnostic[] csharpImplDiagnostics, + LspDiagnostic[] csharpDeclDiagnostics, LspDiagnostic[] htmlDiagnostics, CancellationToken cancellationToken) { @@ -55,8 +57,8 @@ private async ValueTask> GetDiagnosticsAsync( ImmutableArray allDiagnostics = [ .. GetRazorDiagnostics(context, codeDocument), - .. await _translateDiagnosticsService.TranslateAsync(RazorLanguageKind.CSharp, csharpDiagnostics, context.Snapshot, cancellationToken).ConfigureAwait(false), - .. await _translateDiagnosticsService.TranslateAsync(RazorLanguageKind.Html, htmlDiagnostics, context.Snapshot, cancellationToken).ConfigureAwait(false) + .. await _translateDiagnosticsService.TranslateCSharpAsync(csharpImplDiagnostics, csharpDeclDiagnostics, context.Snapshot, cancellationToken).ConfigureAwait(false), + .. await _translateDiagnosticsService.TranslateHtmlAsync(htmlDiagnostics, context.Snapshot, cancellationToken).ConfigureAwait(false) ]; // Our final pass is to update all unused directive errors to ensure they display how we want in the IDE. Doing it here @@ -151,24 +153,29 @@ private static ImmutableArray GetRazorDiagnostics(RemoteDocumentC public ValueTask> GetTaskListDiagnosticsAsync( JsonSerializableRazorSolutionWrapper solutionInfo, JsonSerializableDocumentId documentId, - LspDiagnostic[] csharpTaskItems, + LspDiagnostic[] csharpImplTaskItems, + LspDiagnostic[] csharpDeclTaskItems, CancellationToken cancellationToken) => RunServiceAsync( solutionInfo, documentId, - context => GetTaskListDiagnosticsAsync(context, csharpTaskItems, cancellationToken), + context => GetTaskListDiagnosticsAsync(context, csharpImplTaskItems, csharpDeclTaskItems, cancellationToken), cancellationToken); private async ValueTask> GetTaskListDiagnosticsAsync( RemoteDocumentContext context, - LspDiagnostic[] csharpTaskItems, + LspDiagnostic[] csharpImplTaskItems, + LspDiagnostic[] csharpDeclTaskItems, CancellationToken cancellationToken) { var codeDocument = await context.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false); using var diagnostics = new PooledArrayBuilder(); diagnostics.AddRange(TaskListDiagnosticProvider.GetTaskListDiagnostics(codeDocument, _clientSettingsManager.GetClientSettings().AdvancedSettings.TaskListDescriptors)); - diagnostics.AddRange(_translateDiagnosticsService.MapDiagnostics(RazorLanguageKind.CSharp, csharpTaskItems, context.Snapshot, codeDocument)); + + diagnostics.AddRange(_translateDiagnosticsService.MapCSharpDiagnostics(csharpImplTaskItems, codeDocument.GetRequiredCSharpDocument(declarationDocument: false))); + diagnostics.AddRange(_translateDiagnosticsService.MapCSharpDiagnostics(csharpDeclTaskItems, codeDocument.GetRequiredCSharpDocument(declarationDocument: true))); + return diagnostics.ToImmutableAndClear(); } } diff --git a/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostDocumentPullDiagnosticsEndpoint.cs b/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostDocumentPullDiagnosticsEndpoint.cs index 1f983d09e6394..7206abe0d22ae 100644 --- a/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostDocumentPullDiagnosticsEndpoint.cs +++ b/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostDocumentPullDiagnosticsEndpoint.cs @@ -148,11 +148,11 @@ protected override LspDiagnostic[] ExtractHtmlDiagnostics(VSInternalDiagnosticRe private async Task HandleTaskListItemRequestAsync(TextDocument razorDocument, CancellationToken cancellationToken) { - var csharpTaskItems = await GetCSharpTaskListItemsAsync(razorDocument, cancellationToken).ConfigureAwait(false); + var (implTaskItems, declTaskItems) = await GetCSharpTaskListItemsAsync(razorDocument, cancellationToken).ConfigureAwait(false); var diagnostics = await _remoteServiceInvoker.TryInvokeAsync>( razorDocument.Project.Solution, - (service, solutionInfo, cancellationToken) => service.GetTaskListDiagnosticsAsync(solutionInfo, razorDocument.Id, csharpTaskItems, cancellationToken), + (service, solutionInfo, cancellationToken) => service.GetTaskListDiagnosticsAsync(solutionInfo, razorDocument.Id, implTaskItems, declTaskItems, cancellationToken), cancellationToken).ConfigureAwait(false); if (diagnostics.IsDefaultOrEmpty) @@ -170,20 +170,33 @@ private async Task HandleTaskListItemRequestAsync( ]; } - private async Task GetCSharpTaskListItemsAsync(TextDocument razorDocument, CancellationToken cancellationToken) + private async Task<(LspDiagnostic[], LspDiagnostic[])> GetCSharpTaskListItemsAsync(TextDocument razorDocument, CancellationToken cancellationToken) { - var generatedDocument = await TryGetGeneratedDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); - if (generatedDocument is null) + var generatedDocuments = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); + if (generatedDocuments.ImplDoc is null) { - return []; + return ([], []); } var supportsVisualStudioExtensions = _clientCapabilitiesService.ClientCapabilities.SupportsVisualStudioExtensions; - var solutionServices = generatedDocument.Project.Solution.Services; + var solutionServices = generatedDocuments.ImplDoc.Project.Solution.Services; var globalOptionsService = solutionServices.ExportProvider.GetService(); - var items = await TaskListDiagnosticSource.GetTaskListItemsAsync(generatedDocument, globalOptionsService, cancellationToken).ConfigureAwait(false); - var csharpTaskItems = CohostDocumentPullDiagnosticsHelpers.ConvertDiagnostics(generatedDocument, supportsVisualStudioExtensions, globalOptionsService, items); - return [.. csharpTaskItems]; + + var implItems = await GetTaskListItemsAsync(generatedDocuments.ImplDoc).ConfigureAwait(false); + var declItems = await GetTaskListItemsAsync(generatedDocuments.DeclDoc).ConfigureAwait(false); + + return (implItems, declItems); + + async Task GetTaskListItemsAsync(SourceGeneratedDocument? doc) + { + if (doc is null) + { + return []; + } + + var implItems = await TaskListDiagnosticSource.GetTaskListItemsAsync(doc, globalOptionsService, cancellationToken).ConfigureAwait(false); + return CohostDocumentPullDiagnosticsHelpers.ConvertDiagnostics(doc, supportsVisualStudioExtensions, globalOptionsService, implItems); + } } internal TestAccessor GetTestAccessor() => new(this); From 64e5ef75c4565c6374dba44ad0f721578f365630 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Wed, 3 Jun 2026 17:38:02 +1000 Subject: [PATCH 05/10] Fix organise usings command --- .../OrganizeUsingsCommand.cs | 11 ++-- .../Cohost/OrganizeUsingsCommandTest.cs | 53 +++++++++++++------ 2 files changed, 45 insertions(+), 19 deletions(-) diff --git a/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/OrganizeUsingsCommand.cs b/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/OrganizeUsingsCommand.cs index e92e15b1d4d7c..c7f757e453363 100644 --- a/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/OrganizeUsingsCommand.cs +++ b/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/OrganizeUsingsCommand.cs @@ -61,19 +61,22 @@ private async Task> ExecuteRemoveAndSortUsingsAsync(S return []; } - var generatedDocument = await razorDocument.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); - if (generatedDocument is null) + var generatedDocuments = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); + if (generatedDocuments.ImplDoc is null) { return []; } // C# diagnostics - var csharpDiagnostics = await CohostDocumentPullDiagnosticsHelpers.GetDocumentDiagnosticsAsync(generatedDocument, supportsVisualStudioExtensions: true, cancellationToken).ConfigureAwait(false); + var implDiagnostics = await CohostDocumentPullDiagnosticsHelpers.GetDocumentDiagnosticsAsync(generatedDocuments.ImplDoc, supportsVisualStudioExtensions: true, cancellationToken).ConfigureAwait(false); + var declDiagnostics = generatedDocuments.DeclDoc is not null + ? await CohostDocumentPullDiagnosticsHelpers.GetDocumentDiagnosticsAsync(generatedDocuments.DeclDoc, supportsVisualStudioExtensions: true, cancellationToken).ConfigureAwait(false) + : []; // Razor diagnostics (to filter and hydrate cache) await _remoteServiceInvoker.TryInvokeAsync>( razorDocument.Project.Solution, - (service, solutionInfo, cancellationToken) => service.GetDiagnosticsAsync(solutionInfo, razorDocument.Id, [.. csharpDiagnostics], htmlDiagnostics: [], cancellationToken), + (service, solutionInfo, cancellationToken) => service.GetDiagnosticsAsync(solutionInfo, razorDocument.Id, implDiagnostics, declDiagnostics, htmlDiagnostics: [], cancellationToken), cancellationToken).ConfigureAwait(false); // Now do the remove and sort diff --git a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/OrganizeUsingsCommandTest.cs b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/OrganizeUsingsCommandTest.cs index 88fd2d9aa9aa9..1259d43cb9ee9 100644 --- a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/OrganizeUsingsCommandTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/OrganizeUsingsCommandTest.cs @@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.Razor.LanguageClient.Cohost; public class OrganizeUsingsCommandTest(ITestOutputHelper testOutputHelper) : CohostEndpointTestBase(testOutputHelper) { - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task SortOnly_NoUnused() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -45,6 +45,29 @@ public void M(StringBuilder b) } """); + [Fact] + public Task SortOnly_NoUnused_NoCodeBlock() + => VerifyRemoveAndSortUsingsAsync( + input: """ + @using System.Text + @using System + @using Microsoft.AspNetCore.Components.Forms + +
+ + @nameof(StringBuilder b) + @nameof(Console) + """, + expected: """ + @using System + @using System.Text + +
+ + @nameof(StringBuilder b) + @nameof(Console) + """); + [Fact] public Task RemoveOnly_AlreadySorted() => VerifyRemoveAndSortUsingsAsync( @@ -59,7 +82,7 @@ @using System.Text
"""); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task RemoveAndSort_Combined() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -91,10 +114,10 @@ public void M() } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task RemoveAndSort_Combined2() - => VerifyRemoveAndSortUsingsAsync( - input: """ + => VerifyRemoveAndSortUsingsAsync( + input: """ @using System.Text @using System.Buffers @using System @@ -109,7 +132,7 @@ public void M(StringBuilder sv) } } """, - expected: """ + expected: """ @using System @using System.Text @@ -148,7 +171,7 @@ @using System.Buffers
"""); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task SystemUsings_SortedFirst() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -185,7 +208,7 @@ public void M(StringBuilder b) } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task SingleUsing_Used_NoChange() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -215,7 +238,7 @@ public void M() } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task PageDirective_BeforeUsings() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -249,7 +272,7 @@ public void M(StringBuilder b) } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task PageDirective_BetweenUsings() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -283,7 +306,7 @@ public void M(StringBuilder b) } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task UsingsSpreadAcrossFile_UnusedRemoved() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -318,7 +341,7 @@ public void M(StringBuilder b) } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task UsingsSpreadAcrossFile_AllUsed_ConsolidatedIntoFirstGroup() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -354,7 +377,7 @@ public void M(StringBuilder b, ArrayPool pool) } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task SystemUsings_SortedBeforeNonSystem() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -498,7 +521,7 @@ public void M(StringBuilder b, ArrayPool pool) } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task AlreadySorted_NoUnused() => VerifyRemoveAndSortUsingsAsync( input: """ @@ -583,7 +606,7 @@ @using System """, fileKind: RazorFileKind.Legacy); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] public Task DuplicateUsings_Removed() => VerifyRemoveAndSortUsingsAsync( input: """ From 5b579f49054235e0be44233250716a5dee81b75c Mon Sep 17 00:00:00 2001 From: David Wengier Date: Wed, 3 Jun 2026 18:05:26 +1000 Subject: [PATCH 06/10] Change return type to be more convenient Every consumer immedately converted to an array anyway --- .../Diagnostics/CohostDocumentPullDiagnosticsHelpers.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsHelpers.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsHelpers.cs index 7fd9e5b31eeac..63511882c94b4 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsHelpers.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsHelpers.cs @@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.Razor.LanguageClient.Cohost; internal static class CohostDocumentPullDiagnosticsHelpers { - public static async Task> GetDocumentDiagnosticsAsync(Document document, bool supportsVisualStudioExtensions, CancellationToken cancellationToken) + public static async Task GetDocumentDiagnosticsAsync(Document document, bool supportsVisualStudioExtensions, CancellationToken cancellationToken) { var solutionServices = document.Project.Solution.Services; var globalOptionsService = solutionServices.ExportProvider.GetService(); @@ -29,7 +29,7 @@ public static async Task> GetDocumentDiagnosticsAs return ConvertDiagnostics(document, supportsVisualStudioExtensions, globalOptionsService, [.. diagnostics, .. encDiagnostics]); } - internal static ImmutableArray ConvertDiagnostics(Document document, bool supportsVisualStudioExtensions, IGlobalOptionService globalOptionsService, ImmutableArray diagnostics) + internal static LspDiagnostic[] ConvertDiagnostics(Document document, bool supportsVisualStudioExtensions, IGlobalOptionService globalOptionsService, ImmutableArray diagnostics) { var project = document.Project; // Potential duplicate is only set for workspace diagnostics, which Razor doesn't support @@ -44,6 +44,6 @@ internal static ImmutableArray ConvertDiagnostics(Document docume } } - return result.ToImmutableAndClear(); + return result.ToArrayAndClear(); } } From a694fd348addad6a15736f59da577959831d3d0b Mon Sep 17 00:00:00 2001 From: David Wengier Date: Wed, 3 Jun 2026 18:17:42 +1000 Subject: [PATCH 07/10] Use the implementation document for Razor diagnostics --- .../Diagnostics/RemoteDiagnosticsService.cs | 4 +++- .../Endpoints/CohostDocumentPullDiagnosticsTest.cs | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs index 469f124ad6e92..f96856719992e 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs @@ -111,7 +111,9 @@ private static ImmutableArray GetRazorDiagnostics(RemoteDocumentC using var diagnostics = new PooledArrayBuilder(); // First, RZ diagnostics. Yes, CSharpDocument.Documents are the Razor diagnostics. Don't ask. - var razorDiagnostics = codeDocument.GetRequiredImplCSharpDocument().Diagnostics; + // Right now Razor diagnostics are duplicated on both decl and impl documents, so it doesn't matter which + // one we use. + var razorDiagnostics = codeDocument.GetRequiredCSharpDocument(declarationDocument: false).Diagnostics; var convertedDiagnostics = RazorDiagnosticHelper.Convert(razorDiagnostics, codeDocument.Source.Text, context.Snapshot); diagnostics.AddRange(convertedDiagnostics); diff --git a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs index 800adee7dbf37..8b8d03841d3a4 100644 --- a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs @@ -55,6 +55,18 @@ public Task Razor()
"""); + [Fact] + public Task Razor_CodeBlock() + => VerifyDiagnosticsAsync(""" + @code + { + public void M() + { + RenderFragment x = @{|RZ10012:|}; + } + } + """); + [Fact] public Task CSharpAndRazor_MiscellaneousFile() => VerifyDiagnosticsAsync(""" From 24d6e1dd96e5da6eb0efd4663ab2b1f292249677 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Wed, 3 Jun 2026 18:19:31 +1000 Subject: [PATCH 08/10] PR Feedback --- ...hostDocumentPullDiagnosticsEndpointBase.cs | 8 +++---- .../Extensions/ProjectExtensions.cs | 4 ++-- .../RazorTranslateDiagnosticsService.cs | 2 +- .../Diagnostics/RemoteDiagnosticsService.cs | 6 +++++- .../CohostDocumentPullDiagnosticsTest.cs | 4 ++-- .../CohostDocumentPullDiagnosticsTest.cs | 21 +++++++++++++++++++ .../Cohost/OrganizeUsingsCommandTest.cs | 4 ++-- 7 files changed, 37 insertions(+), 12 deletions(-) diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs index 1ca98990ccbd6..e2d1e561b6065 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs @@ -98,7 +98,7 @@ protected virtual TRequest CreateHtmlParams(Uri uri) return [.. diagnostics]; } - private async Task<(LspDiagnostic[], LspDiagnostic[])> GetCSharpDiagnosticsAsync(TextDocument razorDocument, Guid correletionId, CancellationToken cancellationToken) + private async Task<(LspDiagnostic[], LspDiagnostic[])> GetCSharpDiagnosticsAsync(TextDocument razorDocument, Guid correlationId, CancellationToken cancellationToken) { // Because we can't map from a random C# point to a Razor point without knowing which C# document we're talking about, we have to just make two requests // and send back two sets of diagnostics @@ -109,7 +109,7 @@ protected virtual TRequest CreateHtmlParams(Uri uri) return ([], []); } - using var _ = _telemetryReporter.TrackLspRequest(LspMethodName, "Razor.ExternalAccess", TelemetryThresholds.DiagnosticsSubLSPTelemetryThreshold, correletionId); + using var _ = _telemetryReporter.TrackLspRequest(LspMethodName, "Razor.ExternalAccess", TelemetryThresholds.DiagnosticsSubLSPTelemetryThreshold, correlationId); var supportsVisualStudioExtensions = _clientCapabilitiesService.ClientCapabilities.SupportsVisualStudioExtensions; _logger.LogDebug($"Getting C# diagnostics for {generatedDocuments.ImplDoc.FilePath}"); @@ -126,7 +126,7 @@ protected virtual TRequest CreateHtmlParams(Uri uri) return (implDiagnostics, declDiagnostics); } - private async Task GetHtmlDiagnosticsAsync(TextDocument razorDocument, Guid correletionId, CancellationToken cancellationToken) + private async Task GetHtmlDiagnosticsAsync(TextDocument razorDocument, Guid correlationId, CancellationToken cancellationToken) { var diagnosticsParams = CreateHtmlParams(razorDocument.CreateSystemUri()); @@ -135,7 +135,7 @@ private async Task GetHtmlDiagnosticsAsync(TextDocument razorDo LspMethodName, diagnosticsParams, TelemetryThresholds.DiagnosticsSubLSPTelemetryThreshold, - correletionId, + correlationId, cancellationToken).ConfigureAwait(false); if (result is null) diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs index d7f2836faed00..987ede9ec0685 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs @@ -135,8 +135,8 @@ public static async ValueTask GetTagHelpersAsync( return (fullPathMatchedDoc, fullPathMatchedDeclDoc); } - // If we didn't find a candidate impl doc, or found mulitple, bail out so we don't confuse callers in case there is a weird - // bug where its possible to have duplicate impl docs and one decl doc + // If we didn't find a candidate impl doc, or found multiple, bail out so we don't confuse callers in case there is a weird + // bug where it's possible to have duplicate impl docs and one decl doc if (candidateDoc is null) { return (null, null); diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs index 698d6cf8f43e9..677084383e0cc 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs @@ -163,7 +163,7 @@ static bool ContainsMatchingGeneratedRemoveUnnecessaryImportsDiagnostic( { foreach (var otherDiagnostic in diagnostics) { - if (diagnostic.Code is { Value: RemoveUnnecessaryImportsConstants.IDE0005_gen } && + if (otherDiagnostic.Code is { Value: RemoveUnnecessaryImportsConstants.IDE0005_gen } && IsSameDiagnosticSpan(diagnostic, otherDiagnostic)) { return true; diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs index f96856719992e..2de1afc74730c 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RemoteDiagnosticsService.cs @@ -176,7 +176,11 @@ private async ValueTask> GetTaskListDiagnosticsAsy diagnostics.AddRange(TaskListDiagnosticProvider.GetTaskListDiagnostics(codeDocument, _clientSettingsManager.GetClientSettings().AdvancedSettings.TaskListDescriptors)); diagnostics.AddRange(_translateDiagnosticsService.MapCSharpDiagnostics(csharpImplTaskItems, codeDocument.GetRequiredCSharpDocument(declarationDocument: false))); - diagnostics.AddRange(_translateDiagnosticsService.MapCSharpDiagnostics(csharpDeclTaskItems, codeDocument.GetRequiredCSharpDocument(declarationDocument: true))); + + if (csharpDeclTaskItems.Length > 0) + { + diagnostics.AddRange(_translateDiagnosticsService.MapCSharpDiagnostics(csharpDeclTaskItems, codeDocument.GetRequiredCSharpDocument(declarationDocument: true))); + } return diagnostics.ToImmutableAndClear(); } diff --git a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs index 8b8d03841d3a4..d2290f7249732 100644 --- a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs @@ -39,7 +39,7 @@ public void IJustMetYou() [Fact] public Task CSharp_ImplicitExpression() - => VerifyDiagnosticsAsync(""" + => VerifyDiagnosticsAsync("""
@{|CS0103:CallMeMaybe|}() @@ -132,7 +132,7 @@ public void BuildsStrings(StringBuilder b) [Fact] public Task CSharpUnusedUsings_NoCodeBlock() - => VerifyDiagnosticsAsync(""" + => VerifyDiagnosticsAsync(""" {|RZ0005:@using System|}
diff --git a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs index 45151dcd8f738..cbd98faec964f 100644 --- a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/CohostDocumentPullDiagnosticsTest.cs @@ -579,6 +579,27 @@ public Task TODOComments() """, taskListRequest: true); + [Fact] + public Task TODOComments_NoDecl() + => VerifyDiagnosticsAsync(""" + @using System.Threading.Tasks; + + @{ + // {|TODO:|}TODO: This is C# in an impl document + } + + TODO: Nor is this + +
+ + @*{|TODO: TODO: This does |}*@ + + @* TODONT: This doesn't *@ + +
+ """, + taskListRequest: true); + private async Task VerifyDiagnosticsAsync( TestCode input, VSInternalDiagnosticReport[]? htmlResponse = null, diff --git a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/OrganizeUsingsCommandTest.cs b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/OrganizeUsingsCommandTest.cs index 1259d43cb9ee9..157ba84915224 100644 --- a/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/OrganizeUsingsCommandTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.UnitTests/Cohost/OrganizeUsingsCommandTest.cs @@ -55,7 +55,7 @@ @using Microsoft.AspNetCore.Components.Forms
- @nameof(StringBuilder b) + @nameof(StringBuilder) @nameof(Console) """, expected: """ @@ -64,7 +64,7 @@ @using System.Text
- @nameof(StringBuilder b) + @nameof(StringBuilder) @nameof(Console) """); From e6f7e5c32debbe3ae067180153e74a2da3dbf2b5 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Thu, 4 Jun 2026 15:04:02 +1000 Subject: [PATCH 09/10] PR Feedback --- ...hostDocumentPullDiagnosticsEndpointBase.cs | 4 +- .../Extensions/ProjectExtensions.cs | 45 +++++++++++++---- .../RazorTranslateDiagnosticsService.cs | 6 ++- .../CohostDocumentPullDiagnosticsEndpoint.cs | 4 +- .../OrganizeUsingsCommand.cs | 4 +- .../ComputedTargetPathTest.cs | 50 ++++++++++--------- .../CohostDocumentPullDiagnosticsTest.cs | 32 ++++++++++++ 7 files changed, 104 insertions(+), 41 deletions(-) diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs index e2d1e561b6065..c5fa9cff71da7 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs @@ -103,8 +103,8 @@ protected virtual TRequest CreateHtmlParams(Uri uri) // Because we can't map from a random C# point to a Razor point without knowing which C# document we're talking about, we have to just make two requests // and send back two sets of diagnostics - var generatedDocuments = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); - if (generatedDocuments.ImplDoc is null) + var csharpDocs = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); + if (csharpDocs is not { } generatedDocuments) { return ([], []); } diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs index 987ede9ec0685..f0786d6c0b9f3 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs @@ -67,25 +67,30 @@ public static async ValueTask GetTagHelpersAsync( public static async Task TryGetSourceGeneratedDocumentForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken) { - return (await TryGetSourceGeneratedDocumentsForRazorDocumentAsync(project, razorDocument, cancellationToken).ConfigureAwait(false)).ImplDoc; + return (await TryGetSourceGeneratedDocumentsForRazorDocumentAsync(project, razorDocument, cancellationToken).ConfigureAwait(false))?.ImplDoc; } /// /// Finds source generated documents by iterating through all of them. In OOP there are better options! /// - public static async Task<(SourceGeneratedDocument? ImplDoc, SourceGeneratedDocument? DeclDoc)> TryGetSourceGeneratedDocumentsForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken) + public static async Task TryGetSourceGeneratedDocumentsForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken) { if (razorDocument.FilePath is null) { - return (null, null); + return null; } var generatedDocuments = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); + // There are two possible ways hint names come about: The Razor SDK will product project relative paths for projects that use it + // and for non-Razor SDK projects we fallback to using the full path for hint names. We can't easily detect which situation we're + // in here, so the loop below handles both cases. + // For misc files, and projects that don't have a globalconfig file (eg, non Razor SDK projects), the hint name will be based // on the full path of the file. var fullPathHintName = RazorSourceGenerator.GetIdentifierFromPath(razorDocument.FilePath); var fullPathDeclHintName = RazorSourceGenerator.GetDeclIdentifierFromHintName(fullPathHintName); + // For normal Razor SDK projects, the hint name will be based on the project-relative path of the file. var projectRelativeHintName = GetProjectRelativeHintName(razorDocument); var projectRelativeDeclHintName = projectRelativeHintName is null ? null : RazorSourceGenerator.GetDeclIdentifierFromHintName(projectRelativeHintName); @@ -106,14 +111,19 @@ public static async ValueTask GetTagHelpersAsync( { // If the full path matches, we've found it for sure fullPathMatchedDoc = doc; + // Can we stop looping? + if (fullPathMatchedDeclDoc is not null) + { + break; + } } else if (doc.HintName == fullPathDeclHintName) { fullPathMatchedDeclDoc = doc; - } - else if (doc.HintName == projectRelativeDeclHintName) - { - candidateDeclDoc = doc; + if (fullPathMatchedDoc is not null) + { + break; + } } else if (doc.HintName == projectRelativeHintName) { @@ -121,28 +131,41 @@ public static async ValueTask GetTagHelpersAsync( { // Multiple documents with the same hint name found, can't be sure which one to return // This can happen as a result of a bug in the source generator: https://github.com/dotnet/razor/issues/11578 + // We can break the loop safely here, because if there are any project relative hint names, it means the project + // is using the Razor SDK, which will never product full path hint names. Or someone is doing something _very_ weird. + Debug.Assert(fullPathMatchedDoc is null && fullPathMatchedDeclDoc is null, "We don't expect full matches and partial matches in the same project"); candidateDoc = null; break; } candidateDoc = doc; } + else if (doc.HintName == projectRelativeDeclHintName) + { + if (candidateDeclDoc is not null) + { + candidateDoc = null; + break; + } + + candidateDeclDoc = doc; + } } // Full path matches take precedence over candidates if (fullPathMatchedDoc is not null) { - return (fullPathMatchedDoc, fullPathMatchedDeclDoc); + return new(fullPathMatchedDoc, fullPathMatchedDeclDoc); } // If we didn't find a candidate impl doc, or found multiple, bail out so we don't confuse callers in case there is a weird // bug where it's possible to have duplicate impl docs and one decl doc if (candidateDoc is null) { - return (null, null); + return null; } - return (candidateDoc, candidateDeclDoc); + return new(candidateDoc, candidateDeclDoc); static string? GetProjectRelativeHintName(TextDocument razorDocument) { @@ -167,3 +190,5 @@ public static async ValueTask GetTagHelpersAsync( } } } + +internal record struct SourceGeneratedDocuments(SourceGeneratedDocument ImplDoc, SourceGeneratedDocument? DeclDoc); diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs index 677084383e0cc..15d42d2c0c6bb 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs @@ -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; @@ -122,7 +122,9 @@ internal async Task TranslateCSharpAsync( // unused using directives diagnostics. The compiler puts all of the users usings in both documents, so an unused using // directive from one document, doesn't matter unless it appears in the other as well. - // If there is no decl document though, we just used the impl diagnostics unfiltered + // If there is no decl document though, we just used the impl diagnostics unfiltered. If there is a decl document, but no + // decl diagnostics, we still need to filter as it means that any unused using directive is in the impl diagnostics is not + // real, and needs to be filtered out. var finalDiagnostics = declDocument is not null ? FilterUnusedUsingDirectiveDiagnostics(mappedImplDiagnostics, mappedDeclDiagnostics) : mappedImplDiagnostics; diff --git a/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostDocumentPullDiagnosticsEndpoint.cs b/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostDocumentPullDiagnosticsEndpoint.cs index 7206abe0d22ae..663166eb768b0 100644 --- a/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostDocumentPullDiagnosticsEndpoint.cs +++ b/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostDocumentPullDiagnosticsEndpoint.cs @@ -172,8 +172,8 @@ private async Task HandleTaskListItemRequestAsync( private async Task<(LspDiagnostic[], LspDiagnostic[])> GetCSharpTaskListItemsAsync(TextDocument razorDocument, CancellationToken cancellationToken) { - var generatedDocuments = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); - if (generatedDocuments.ImplDoc is null) + var csharpDocs = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); + if (csharpDocs is not { } generatedDocuments) { return ([], []); } diff --git a/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/OrganizeUsingsCommand.cs b/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/OrganizeUsingsCommand.cs index c7f757e453363..39902dd37261e 100644 --- a/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/OrganizeUsingsCommand.cs +++ b/src/Razor/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/OrganizeUsingsCommand.cs @@ -61,8 +61,8 @@ private async Task> ExecuteRemoveAndSortUsingsAsync(S return []; } - var generatedDocuments = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); - if (generatedDocuments.ImplDoc is null) + var csharpDocs = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); + if (csharpDocs is not { } generatedDocuments) { return []; } diff --git a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/ComputedTargetPathTest.cs b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/ComputedTargetPathTest.cs index 8e01040655a26..b40d74fcc15d9 100644 --- a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/ComputedTargetPathTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/ComputedTargetPathTest.cs @@ -50,8 +50,8 @@ public async Task DoubleSlashInUri() _ = await document.Project.GetCompilationAsync(DisposalToken); - var generatedDocument = await document.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(document, DisposalToken); - Assert.NotNull(generatedDocument); + var generatedDocuments = await document.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(document, DisposalToken); + Assert.NotNull(generatedDocuments); } [Theory] @@ -77,9 +77,9 @@ public async Task SingleDocument(bool projectPath, bool generateConfigFile) _ = await document.Project.GetCompilationAsync(DisposalToken); - var generatedDocument = await document.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(document, DisposalToken); - Assert.NotNull(generatedDocument); - Assert.Equal($"{s_hintNamePrefix}/File1_razor.g.cs", generatedDocument.HintName); + var generatedDocuments = await document.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(document, DisposalToken); + Assert.NotNull(generatedDocuments); + Assert.Equal($"{s_hintNamePrefix}/File1_razor.g.cs", generatedDocuments.Value.ImplDoc.HintName); } [Theory] @@ -102,13 +102,15 @@ public async Task TwoDocumentsWithTheSameBaseFileName(bool generateTargetPath) var doc1 = solution.GetAdditionalDocument(doc1Id).AssumeNotNull(); var doc2 = solution.GetAdditionalDocument(doc2Id).AssumeNotNull(); - var generatedDocument = await doc1.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(doc1, DisposalToken); - Assert.NotNull(generatedDocument); - Assert.Equal($"Pages/Index_razor.g.cs", generatedDocument.HintName); + var generatedDocuments = await doc1.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(doc1, DisposalToken); + Assert.NotNull(generatedDocuments); + Assert.Equal($"Pages/Index_razor.g.cs", generatedDocuments.Value.ImplDoc.HintName); + Assert.Equal($"Pages/Index_razor.decl.g.cs", generatedDocuments.Value.DeclDoc.AssumeNotNull().HintName); - generatedDocument = await doc2.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(doc2, DisposalToken); - Assert.NotNull(generatedDocument); - Assert.Equal($"Components/Index_razor.g.cs", generatedDocument.HintName); + generatedDocuments = await doc2.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(doc2, DisposalToken); + Assert.NotNull(generatedDocuments); + Assert.Equal($"Components/Index_razor.g.cs", generatedDocuments.Value.ImplDoc.HintName); + Assert.Equal($"Components/Index_razor.decl.g.cs", generatedDocuments.Value.DeclDoc.AssumeNotNull().HintName); } [Theory] @@ -134,13 +136,15 @@ public async Task TwoDocumentsWithTheSameBaseFileName_FullPathHintName(bool proj var doc1 = solution.GetAdditionalDocument(doc1Id).AssumeNotNull(); var doc2 = solution.GetAdditionalDocument(doc2Id).AssumeNotNull(); - var generatedDocument = await doc1.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(doc1, DisposalToken); - Assert.NotNull(generatedDocument); - Assert.Equal($"{s_hintNamePrefix}/Pages/Index_razor.g.cs", generatedDocument.HintName); + var generatedDocuments = await doc1.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(doc1, DisposalToken); + Assert.NotNull(generatedDocuments); + Assert.Equal($"{s_hintNamePrefix}/Pages/Index_razor.g.cs", generatedDocuments.Value.ImplDoc.HintName); + Assert.Equal($"{s_hintNamePrefix}/Pages/Index_razor.decl.g.cs", generatedDocuments.Value.DeclDoc.AssumeNotNull().HintName); - generatedDocument = await doc2.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(doc2, DisposalToken); - Assert.NotNull(generatedDocument); - Assert.Equal($"{s_hintNamePrefix}/Components/Index_razor.g.cs", generatedDocument.HintName); + generatedDocuments = await doc2.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(doc2, DisposalToken); + Assert.NotNull(generatedDocuments); + Assert.Equal($"{s_hintNamePrefix}/Components/Index_razor.g.cs", generatedDocuments.Value.ImplDoc.HintName); + Assert.Equal($"{s_hintNamePrefix}/Components/Index_razor.decl.g.cs", generatedDocuments.Value.DeclDoc.AssumeNotNull().HintName); } [Theory] @@ -166,12 +170,12 @@ public async Task TwoDocumentsWithTheSameBaseHintName(bool projectPath, bool gen var doc1 = solution.GetAdditionalDocument(doc1Id).AssumeNotNull(); var doc2 = solution.GetAdditionalDocument(doc2Id).AssumeNotNull(); - var generatedDocument = await doc1.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(doc1, DisposalToken); - Assert.NotNull(generatedDocument); - Assert.Equal($"{s_hintNamePrefix}/Pages/Index_razor.g.cs", generatedDocument.HintName); + var generatedDocuments = await doc1.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(doc1, DisposalToken); + Assert.NotNull(generatedDocuments); + Assert.Equal($"{s_hintNamePrefix}/Pages/Index_razor.g.cs", generatedDocuments.Value.ImplDoc.HintName); - generatedDocument = await doc2.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(doc2, DisposalToken); - Assert.NotNull(generatedDocument); - Assert.Equal($"{s_hintNamePrefix}/Pages_Index_razor.g.cs", generatedDocument.HintName); + generatedDocuments = await doc2.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(doc2, DisposalToken); + Assert.NotNull(generatedDocuments); + Assert.Equal($"{s_hintNamePrefix}/Pages_Index_razor.g.cs", generatedDocuments.Value.ImplDoc.HintName); } } diff --git a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs index d2290f7249732..2b3166f203679 100644 --- a/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs +++ b/src/Razor/src/Razor/test/Microsoft.CodeAnalysis.Razor.CohostingShared.UnitTests/Endpoints/CohostDocumentPullDiagnosticsTest.cs @@ -130,6 +130,38 @@ public void BuildsStrings(StringBuilder b) } """); + [Fact] + public Task CSharpUsingUnusedInImplOnly() + => VerifyDiagnosticsAsync(""" + @using System.Text + +
+ + @code + { + public void BuildsStrings(StringBuilder b) + { + } + } + """); + + [Fact] + public Task CSharpUsingUnusedInDeclOnly() + => VerifyDiagnosticsAsync(""" + @using System.Text + + @nameof(StringBuilder) + +
+ + @code + { + public void BuildsStrings() + { + } + } + """); + [Fact] public Task CSharpUnusedUsings_NoCodeBlock() => VerifyDiagnosticsAsync(""" From e9b07da1347201f944ce9d35949334d7854e8919 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Thu, 4 Jun 2026 15:14:41 +1000 Subject: [PATCH 10/10] Apply suggestions from code review Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .../Extensions/ProjectExtensions.cs | 4 ++-- .../Diagnostics/RazorTranslateDiagnosticsService.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs index f0786d6c0b9f3..96992e62fea91 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs @@ -82,7 +82,7 @@ public static async ValueTask GetTagHelpersAsync( var generatedDocuments = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); - // There are two possible ways hint names come about: The Razor SDK will product project relative paths for projects that use it + // There are two possible ways hint names come about: The Razor SDK will produce project relative paths for projects that use it // and for non-Razor SDK projects we fallback to using the full path for hint names. We can't easily detect which situation we're // in here, so the loop below handles both cases. @@ -132,7 +132,7 @@ public static async ValueTask GetTagHelpersAsync( // Multiple documents with the same hint name found, can't be sure which one to return // This can happen as a result of a bug in the source generator: https://github.com/dotnet/razor/issues/11578 // We can break the loop safely here, because if there are any project relative hint names, it means the project - // is using the Razor SDK, which will never product full path hint names. Or someone is doing something _very_ weird. + // is using the Razor SDK, which will never produce full path hint names. Or someone is doing something _very_ weird. Debug.Assert(fullPathMatchedDoc is null && fullPathMatchedDeclDoc is null, "We don't expect full matches and partial matches in the same project"); candidateDoc = null; break; diff --git a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs index 15d42d2c0c6bb..a379fdac8d245 100644 --- a/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs +++ b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/Diagnostics/RazorTranslateDiagnosticsService.cs @@ -148,7 +148,7 @@ private static LspDiagnostic[] FilterUnusedUsingDirectiveDiagnostics(LspDiagnost } // By definition any diagnostics in decl that we want to keep will be kept because they will have a matching diagnostic in impl, - // so we can just need to filter decl diagnostics to ignore all unused using directives. + // so we just need to filter decl diagnostics to ignore all unused using directives. foreach (var diagnostic in declDiagnostics) { if (diagnostic.Code is not { Value: RemoveUnnecessaryImportsConstants.IDE0005_gen })