From 3f63a01354090f5428c7b7009220f017837aaf58 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Wed, 11 Sep 2024 16:35:54 +1000 Subject: [PATCH] Allow access to Roslyn diagnostics from Razor --- .../Razor/Cohost/Handlers/Diagnostics.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/Tools/ExternalAccess/Razor/Cohost/Handlers/Diagnostics.cs diff --git a/src/Tools/ExternalAccess/Razor/Cohost/Handlers/Diagnostics.cs b/src/Tools/ExternalAccess/Razor/Cohost/Handlers/Diagnostics.cs new file mode 100644 index 0000000000000..b0313ab63e20e --- /dev/null +++ b/src/Tools/ExternalAccess/Razor/Cohost/Handlers/Diagnostics.cs @@ -0,0 +1,39 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.LanguageServer; +using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.PooledObjects; +using LSP = Roslyn.LanguageServer.Protocol; + +namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Cohost.Handlers; + +internal static class Diagnostics +{ + public static async Task> GetDocumentDiagnosticsAsync(Document document, bool supportsVisualStudioExtensions, CancellationToken cancellationToken) + { + var globalOptionsService = document.Project.Solution.Services.ExportProvider.GetService(); + var diagnosticAnalyzerService = document.Project.Solution.Services.ExportProvider.GetService(); + + var diagnostics = await diagnosticAnalyzerService.GetDiagnosticsForSpanAsync(document, range: null, cancellationToken).ConfigureAwait(false); + + var project = document.Project; + // isLiveSource means build might override a diagnostics, but this method is only used by tooling, so builds aren't relevant + const bool IsLiveSource = false; + // Potential duplicate is only set for workspace diagnostics + const bool PotentialDuplicate = false; + + var result = ArrayBuilder.GetInstance(capacity: diagnostics.Length); + foreach (var diagnostic in diagnostics) + { + result.AddRange(ProtocolConversions.ConvertDiagnostic(diagnostic, supportsVisualStudioExtensions, project, IsLiveSource, PotentialDuplicate, globalOptionsService)); + } + + return result.ToImmutableAndFree(); + } +}