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.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.CohostingShared/Diagnostics/CohostDocumentPullDiagnosticsEndpointBase.cs index 08de668b7049d..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 @@ -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,28 +98,35 @@ 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 correlationId, 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 csharpDocs = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); + if (csharpDocs is not { } generatedDocuments) { - return []; + return ([], []); } - _logger.LogDebug($"Getting C# diagnostics for {generatedDocument.FilePath}"); - - 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; - 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) + private async Task GetHtmlDiagnosticsAsync(TextDocument razorDocument, Guid correlationId, CancellationToken cancellationToken) { var diagnosticsParams = CreateHtmlParams(razorDocument.CreateSystemUri()); @@ -128,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.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(); } } 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/Extensions/ProjectExtensions.cs b/src/Razor/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/ProjectExtensions.cs index f15b11ec0498f..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 @@ -65,10 +65,15 @@ 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 TryGetSourceGeneratedDocumentsForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken) { if (razorDocument.FilePath is null) { @@ -77,13 +82,24 @@ 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 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. + // 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 +110,20 @@ public static async ValueTask GetTagHelpersAsync( if (doc.HintName == fullPathHintName) { // If the full path matches, we've found it for sure - return doc; + fullPathMatchedDoc = doc; + // Can we stop looping? + if (fullPathMatchedDeclDoc is not null) + { + break; + } + } + else if (doc.HintName == fullPathDeclHintName) + { + fullPathMatchedDeclDoc = doc; + if (fullPathMatchedDoc is not null) + { + break; + } } else if (doc.HintName == projectRelativeHintName) { @@ -102,15 +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 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; } candidateDoc = doc; } + else if (doc.HintName == projectRelativeDeclHintName) + { + if (candidateDeclDoc is not null) + { + candidateDoc = null; + break; + } + + candidateDeclDoc = doc; + } } - return candidateDoc; + // Full path matches take precedence over candidates + if (fullPathMatchedDoc is not null) + { + 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; + } + + return new(candidateDoc, candidateDeclDoc); static string? GetProjectRelativeHintName(TextDocument razorDocument) { @@ -135,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.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..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 @@ -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; @@ -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,131 @@ 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. 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; + + 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 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 (otherDiagnostic.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 +554,7 @@ GenericBlockSyntax or } } - private LspDiagnostic[] FilterCSharpDiagnostics(LspDiagnostic[] diagnostics, RazorCodeDocument codeDocument) + private LspDiagnostic[] FilterCSharpDiagnostics(LspDiagnostic[] diagnostics, RazorCSharpDocument csharpDocument) { using var filteredDiagnostics = new PooledArrayBuilder(); @@ -490,8 +570,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 +585,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 +604,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 +626,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 +640,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..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 @@ -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 @@ -109,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); @@ -151,24 +155,33 @@ 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))); + + if (csharpDeclTaskItems.Length > 0) + { + 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..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 @@ -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 csharpDocs = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); + if (csharpDocs is not { } generatedDocuments) { - 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); 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..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,19 +61,22 @@ private async Task> ExecuteRemoveAndSortUsingsAsync(S return []; } - var generatedDocument = await razorDocument.Project.TryGetSourceGeneratedDocumentForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); - if (generatedDocument is null) + var csharpDocs = await razorDocument.Project.TryGetSourceGeneratedDocumentsForRazorDocumentAsync(razorDocument, cancellationToken).ConfigureAwait(false); + if (csharpDocs is not { } generatedDocuments) { 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.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 89983c4d5ab89..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 @@ -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("""
@@ -37,6 +37,14 @@ public void IJustMetYou() } """); + [Fact] + public Task CSharp_ImplicitExpression() + => VerifyDiagnosticsAsync(""" +
+ + @{|CS0103:CallMeMaybe|}() + """); + [Fact] public Task Razor() => VerifyDiagnosticsAsync(""" @@ -47,7 +55,19 @@ public Task Razor() """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [Fact] + public Task Razor_CodeBlock() + => VerifyDiagnosticsAsync(""" + @code + { + public void M() + { + RenderFragment x = @{|RZ10012:|}; + } + } + """); + + [Fact] public Task CSharpAndRazor_MiscellaneousFile() => VerifyDiagnosticsAsync("""
@@ -66,7 +86,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 +114,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 +130,47 @@ public void BuildsStrings(StringBuilder b) } """); - [Fact(Skip = "PROTOTYPE(sonic): cohosting feature not yet decl/impl split aware; see PR #83887")] + [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(""" + {|RZ0005:@using System|} + +
+ """); + + [Fact] public Task RazorUsingAlsoPresentInImports() => VerifyDiagnosticsAsync(""" @using System.Text @@ -128,7 +188,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 +215,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..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 @@ -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,13 +551,17 @@ 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; // TODO: This isn't C# + @{ + // {|TODO:|}TODO: This is C# in an impl document + } + TODO: Nor is this
@@ -570,11 +574,32 @@ 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); + [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 88fd2d9aa9aa9..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 @@ -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) + @nameof(Console) + """, + expected: """ + @using System + @using System.Text + +
+ + @nameof(StringBuilder) + @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: """ 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("""