Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<IRemoteDiagnosticsService, ImmutableArray<LspDiagnostic>>(
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)
Expand All @@ -98,28 +98,35 @@ protected virtual TRequest CreateHtmlParams(Uri uri)
return [.. diagnostics];
}

protected static Task<SourceGeneratedDocument?> 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<LspDiagnostic[]> 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);
Comment thread
davidwengier marked this conversation as resolved.
Resolved

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<LspDiagnostic[]> GetHtmlDiagnosticsAsync(TextDocument razorDocument, Guid correletionId, CancellationToken cancellationToken)
private async Task<LspDiagnostic[]> GetHtmlDiagnosticsAsync(TextDocument razorDocument, Guid correlationId, CancellationToken cancellationToken)
{
var diagnosticsParams = CreateHtmlParams(razorDocument.CreateSystemUri());

Expand All @@ -128,7 +135,7 @@ private async Task<LspDiagnostic[]> GetHtmlDiagnosticsAsync(TextDocument razorDo
LspMethodName,
diagnosticsParams,
TelemetryThresholds.DiagnosticsSubLSPTelemetryThreshold,
correletionId,
correlationId,
cancellationToken).ConfigureAwait(false);

if (result is null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.Razor.LanguageClient.Cohost;

internal static class CohostDocumentPullDiagnosticsHelpers
{
public static async Task<ImmutableArray<LspDiagnostic>> GetDocumentDiagnosticsAsync(Document document, bool supportsVisualStudioExtensions, CancellationToken cancellationToken)
public static async Task<LspDiagnostic[]> GetDocumentDiagnosticsAsync(Document document, bool supportsVisualStudioExtensions, CancellationToken cancellationToken)
{
var solutionServices = document.Project.Solution.Services;
var globalOptionsService = solutionServices.ExportProvider.GetService<IGlobalOptionService>();
Expand All @@ -29,7 +29,7 @@ public static async Task<ImmutableArray<LspDiagnostic>> GetDocumentDiagnosticsAs
return ConvertDiagnostics(document, supportsVisualStudioExtensions, globalOptionsService, [.. diagnostics, .. encDiagnostics]);
}

internal static ImmutableArray<LspDiagnostic> ConvertDiagnostics(Document document, bool supportsVisualStudioExtensions, IGlobalOptionService globalOptionsService, ImmutableArray<DiagnosticData> diagnostics)
internal static LspDiagnostic[] ConvertDiagnostics(Document document, bool supportsVisualStudioExtensions, IGlobalOptionService globalOptionsService, ImmutableArray<DiagnosticData> diagnostics)
{
var project = document.Project;
// Potential duplicate is only set for workspace diagnostics, which Razor doesn't support
Expand All @@ -44,6 +44,6 @@ internal static ImmutableArray<LspDiagnostic> ConvertDiagnostics(Document docume
}
}

return result.ToImmutableAndClear();
return result.ToArrayAndClear();
}
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Oops, didn't mean to commit this. This is part of getting code actions to work with Sonic, which is what I decided to start with, but turns out code actions depends on diagnostics, so I changed direction a little.

Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment on lines 13 to +17
Comment thread
davidwengier marked this conversation as resolved.
Resolved

Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,15 @@ public static async ValueTask<TagHelperCollection> GetTagHelpersAsync(
return generatedDocuments.SingleOrDefault(d => d.HintName == hintName);
}

public static async Task<SourceGeneratedDocument?> TryGetSourceGeneratedDocumentForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken)
{
return (await TryGetSourceGeneratedDocumentsForRazorDocumentAsync(project, razorDocument, cancellationToken).ConfigureAwait(false))?.ImplDoc;
}

/// <summary>
/// Finds source generated documents by iterating through all of them. In OOP there are better options!
/// </summary>
public static async Task<SourceGeneratedDocument?> TryGetSourceGeneratedDocumentForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken)
public static async Task<SourceGeneratedDocuments?> TryGetSourceGeneratedDocumentsForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken)
{
if (razorDocument.FilePath is null)
{
Expand All @@ -77,13 +82,24 @@ public static async ValueTask<TagHelperCollection> 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())
Expand All @@ -94,23 +110,62 @@ public static async ValueTask<TagHelperCollection> 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)
{
if (candidateDoc is not null)
{
// 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)
Comment thread
davidwengier marked this conversation as resolved.
Resolved
{
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)
{
Expand All @@ -135,3 +190,5 @@ public static async ValueTask<TagHelperCollection> GetTagHelpersAsync(
}
}
}

internal record struct SourceGeneratedDocuments(SourceGeneratedDocument ImplDoc, SourceGeneratedDocument? DeclDoc);
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ internal interface IRemoteDiagnosticsService : IRemoteJsonService
ValueTask<ImmutableArray<LspDiagnostic>> GetDiagnosticsAsync(
JsonSerializableRazorSolutionWrapper solutionInfo,
JsonSerializableDocumentId documentId,
LspDiagnostic[] csharpDiagnostics,
LspDiagnostic[] csharpImplDiagnostics,
LspDiagnostic[] csharpDeclDiagnostics,
LspDiagnostic[] htmlDiagnostics,
CancellationToken cancellationToken);

ValueTask<ImmutableArray<LspDiagnostic>> GetTaskListDiagnosticsAsync(
JsonSerializableRazorSolutionWrapper solutionInfo,
JsonSerializableDocumentId documentId,
LspDiagnostic[] csharpTaskItems,
LspDiagnostic[] csharpImplTaskItems,
LspDiagnostic[] csharpDeclTaskItems,
CancellationToken cancellationToken);
}
Loading
Loading