Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/Razor/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
<IsIntegrationTestProject>false</IsIntegrationTestProject>
<IsIntegrationTestProject Condition="$(MSBuildProjectName.EndsWith('.IntegrationTests'))">true</IsIntegrationTestProject>
<AddPublicApiAnalyzers Condition="'$(IsTestProject)' == 'true' OR '$(IsUnitTestProject)' == 'true' OR '$(IsIntegrationTestProject)' == 'true'">false</AddPublicApiAnalyzers>

<!-- PROTOTYPE(sonic): Uncomment to make the error list your todo list -->
<!--<DefineConstants>$(DefineConstants);SONICDEV</DefineConstants>-->
Comment thread
davidwengier marked this conversation as resolved.
Resolved
</PropertyGroup>
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />

Expand Down
Original file line number Diff line number Diff line change
@@ -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.Generic;
Expand Down Expand Up @@ -267,15 +267,24 @@ internal RazorCodeDocument WithDocumentNode(DocumentIntermediateNode value)
internal RazorCSharpDocument GetRequiredCSharpDocument(bool declarationDocument)
=> GetCSharpDocument(declarationDocument).AssumeNotNull();

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
#endif
internal bool TryGetImplCSharpDocument([NotNullWhen(true)] out RazorCSharpDocument? result)
{
result = _csharpDocument;
return result is not null;
}

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
#endif
internal RazorCSharpDocument? GetImplCSharpDocument()
=> _csharpDocument;

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
#endif
internal RazorCSharpDocument GetRequiredImplCSharpDocument()
=> _csharpDocument.AssumeNotNull();

Expand All @@ -289,6 +298,9 @@ internal RazorCodeDocument WithImplCSharpDocument(RazorCSharpDocument value)
return new RazorCodeDocument(Source, Imports, ParserOptions, CodeGenerationOptions, _tagHelpers, _referencedTagHelpers, _syntaxTree, _tagHelperRewrittenSyntaxTree, _importSyntaxTrees, _tagHelperContext, _documentNode, value, _declCSharpDocument, _directiveTagHelperContributions);
}

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
#endif
internal RazorCSharpDocument? GetDeclCSharpDocument()
=> _declCSharpDocument;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,40 +8,12 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.CodeAnalysis.Razor;
using Microsoft.NET.Sdk.Razor.SourceGenerators;

namespace Microsoft.CodeAnalysis;

internal static class ProjectExtensions
{
/// <summary>
/// Gets the available <see cref="TagHelperDescriptor">tag helpers</see> from the specified
/// <see cref="Project"/> using the given <see cref="RazorProjectEngine"/>.
/// </summary>
public static async ValueTask<TagHelperCollection> GetTagHelpersAsync(
this Project project,
RazorProjectEngine projectEngine,
CancellationToken cancellationToken)
{
if (!projectEngine.Engine.TryGetFeature(out ITagHelperDiscoveryService? discoveryService))
{
return [];
}

var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
if (compilation is null || !CompilationTagHelperFeature.IsValidCompilation(compilation))
{
return [];
}

const TagHelperDiscoveryOptions Options = TagHelperDiscoveryOptions.ExcludeHidden |
TagHelperDiscoveryOptions.IncludeDocumentation;

return discoveryService.GetTagHelpers(compilation, Options, cancellationToken);
}

public static Task<SourceGeneratedDocument?> TryGetCSharpDocumentForGeneratedDocumentAsync(this Project project, SourceGeneratedDocumentIdentity identity, CancellationToken cancellationToken)
{
Debug.Assert(identity.DocumentId.ProjectId == project.Id, "Generated document URI does not belong to this project.");
Expand All @@ -65,6 +37,9 @@ public static async ValueTask<TagHelperCollection> GetTagHelpersAsync(
return generatedDocuments.SingleOrDefault(d => d.HintName == hintName);
}

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
Comment thread
davidwengier marked this conversation as resolved.
Resolved
#endif
public static async Task<SourceGeneratedDocument?> TryGetSourceGeneratedDocumentForRazorDocumentAsync(this Project project, TextDocument razorDocument, CancellationToken cancellationToken)
{
return (await TryGetSourceGeneratedDocumentsForRazorDocumentAsync(project, razorDocument, cancellationToken).ConfigureAwait(false))?.ImplDoc;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
// 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;
Comment thread
davidwengier marked this conversation as resolved.
Resolved
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.AspNetCore.Razor.Language.Intermediate;
using Microsoft.AspNetCore.Razor.Language.Syntax;
using Microsoft.CodeAnalysis.Razor;
using Microsoft.CodeAnalysis.Razor.Protocol;
using Microsoft.CodeAnalysis.Text;

Expand All @@ -31,6 +29,9 @@ public static bool TryGetSyntaxRoot(this RazorCodeDocument codeDocument, [NotNul
public static Syntax.SyntaxNode GetRequiredSyntaxRoot(this RazorCodeDocument codeDocument)
=> codeDocument.GetRequiredTagHelperRewrittenSyntaxTree().Root;

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call GetRequiredCSharpDocument and use the Text property on that, to prove that you thought about which document to get")]
#endif
public static SourceText GetCSharpSourceText(this RazorCodeDocument document)
=> document.GetRequiredImplCSharpDocument().Text;
Comment thread
davidwengier marked this conversation as resolved.
Resolved

Expand All @@ -48,70 +49,26 @@ public static SourceText GetCSharpSourceText(this RazorCodeDocument document)
/// keeps the behavior conservative.
/// </remarks>
public static RazorCSharpDocument GetCSharpDocumentForHintName(this RazorCodeDocument document, string hintName)
{
return GetCSharpDocumentForHintName(document, hintName, out _);
}

public static RazorCSharpDocument GetCSharpDocumentForHintName(this RazorCodeDocument document, string hintName, out bool isDeclDocument)
{
if (hintName.EndsWith(".decl.g.cs", System.StringComparison.Ordinal) &&
document.GetDeclCSharpDocument() is { } declDocument)
document.GetCSharpDocument(declarationDocument: true) is { } declDocument)
{
isDeclDocument = true;
return declDocument;
}

return document.GetRequiredImplCSharpDocument();
isDeclDocument = false;
return document.GetRequiredCSharpDocument(declarationDocument: false);
}

public static SourceText GetHtmlSourceText(this RazorCodeDocument document, CancellationToken cancellationToken)
=> GetCachedData(document).GetOrComputeHtmlDocument(cancellationToken).Text;

public static bool TryGetMinimalCSharpRange(this RazorCodeDocument codeDocument, LinePositionSpan razorRange, out LinePositionSpan csharpRange)
{
SourceSpan? minGeneratedSpan = null;
SourceSpan? maxGeneratedSpan = null;

var sourceText = codeDocument.Source.Text;
var textSpan = sourceText.GetTextSpan(razorRange);
var csharpDoc = codeDocument.GetRequiredImplCSharpDocument();

// We want to find the min and max C# source mapping that corresponds with our Razor range.
foreach (var mapping in csharpDoc.SourceMappingsSortedByOriginal)
{
var mappedTextSpan = mapping.OriginalSpan.AsTextSpan();

if (textSpan.OverlapsWith(mappedTextSpan))
{
if (minGeneratedSpan is null || mapping.GeneratedSpan.AbsoluteIndex < minGeneratedSpan.Value.AbsoluteIndex)
{
minGeneratedSpan = mapping.GeneratedSpan;
}

var mappingEndIndex = mapping.GeneratedSpan.AbsoluteIndex + mapping.GeneratedSpan.Length;
if (maxGeneratedSpan is null || mappingEndIndex > maxGeneratedSpan.Value.AbsoluteIndex + maxGeneratedSpan.Value.Length)
{
maxGeneratedSpan = mapping.GeneratedSpan;
}
}
else if (mappedTextSpan.Start > textSpan.End)
{
// This span (and all following) are after the area we're interested in
break;
}
}

// Create a new projected range based on our calculated min/max source spans.
if (minGeneratedSpan is not null && maxGeneratedSpan is not null)
{
var csharpSourceText = codeDocument.GetCSharpSourceText();
var startRange = csharpSourceText.GetLinePositionSpan(minGeneratedSpan.Value);
var endRange = csharpSourceText.GetLinePositionSpan(maxGeneratedSpan.Value);

csharpRange = new LinePositionSpan(startRange.Start, endRange.End);
Debug.Assert(csharpRange.Start.CompareTo(csharpRange.End) <= 0, "Range.Start should not be larger than Range.End");

return true;
}

csharpRange = default;
return false;
}

public static bool ComponentNamespaceMatches(this RazorCodeDocument razorCodeDocument, string? fullyQualifiedNamespace)
{
var namespaceNode = (NamespaceDeclarationIntermediateNode)razorCodeDocument
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ async ValueTask<RazorSyntaxTree> GetSyntaxTreeCoreAsync(CancellationToken cancel
}
}

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call GetCodeDocument and get the right CSharpDocument from that, to prove that you thought about which document to get")]
#endif
public ValueTask<SourceText> GetCSharpSourceTextAsync(CancellationToken cancellationToken)
{
Comment thread
davidwengier marked this conversation as resolved.
Resolved
return TryGetCodeDocument(out var codeDocument)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,18 @@ internal interface IDocumentSnapshot
ValueTask<VersionStamp> GetTextVersionAsync(CancellationToken cancellationToken);
ValueTask<RazorCodeDocument> GetGeneratedOutputAsync(CancellationToken cancellationToken);

/// <summary>
/// Gets the Roslyn syntax tree for the generated C# for this Razor document
/// </summary>
/// <remarks>
/// ⚠️ Should be used sparingly in language server scenarios.
/// </remarks>
#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
#endif
ValueTask<SyntaxTree> GetCSharpSyntaxTreeAsync(CancellationToken cancellationToken);

/// <summary>
/// Returns the decl-half source generated document for this Razor document, or
/// <see langword="null"/> when the source generator did not emit a decl half (e.g.
/// .cshtml files, non-component documents, or components whose primary method body is
/// suppressed).
/// Gets the Roslyn syntax tree for the generated C# for this Razor document
/// </summary>
/// <remarks>
/// Implementations that do not have access to source-generator output (e.g. test
/// doubles) should return <see langword="null"/>.
/// ⚠️ Should be used sparingly in language server scenarios.
/// </remarks>
ValueTask<SourceGeneratedDocument?> TryGetDeclGeneratedDocumentAsync(CancellationToken cancellationToken);
ValueTask<SyntaxTree> GetCSharpSyntaxTreeAsync(bool declarationDocument, CancellationToken cancellationToken);
Comment thread
davidwengier marked this conversation as resolved.
Resolved
Comment thread
davidwengier marked this conversation as resolved.
Resolved

bool TryGetText([NotNullWhen(true)] out SourceText? result);
bool TryGetTextVersion(out VersionStamp result);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,22 @@ public IDocumentSnapshot WithText(SourceText text)
return snapshotManager.GetSnapshot(newDocument);
}

public async ValueTask<SourceGeneratedDocument> GetGeneratedDocumentAsync(CancellationToken cancellationToken)
public async ValueTask<SourceGeneratedDocument> GetGeneratedDocumentAsync(bool declarationDocument, CancellationToken cancellationToken)
{
return declarationDocument
? (await TryGetDeclGeneratedDocumentInternalAsync(cancellationToken).ConfigureAwait(false)).AssumeNotNull()
: await GetGeneratedDocumentInternalAsync(cancellationToken).ConfigureAwait(false);
}
Comment thread
davidwengier marked this conversation as resolved.
Resolved

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
#endif
public ValueTask<SourceGeneratedDocument> GetGeneratedDocumentAsync(CancellationToken cancellationToken)
{
return GetGeneratedDocumentInternalAsync(cancellationToken);
}

private async ValueTask<SourceGeneratedDocument> GetGeneratedDocumentInternalAsync(CancellationToken cancellationToken)
{
if (_generatedDocument is not null)
{
Expand All @@ -102,7 +117,15 @@ public async ValueTask<SourceGeneratedDocument> GetGeneratedDocumentAsync(Cancel
/// Returns the decl-half generated document for this Razor document, or <see langword="null"/> when the
/// source generator did not emit a decl-half for it. Caches the (possibly null) result.
/// </summary>
public async ValueTask<SourceGeneratedDocument?> TryGetDeclGeneratedDocumentAsync(CancellationToken cancellationToken)
#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
#endif
public ValueTask<SourceGeneratedDocument?> TryGetDeclGeneratedDocumentAsync(CancellationToken cancellationToken)
{
return TryGetDeclGeneratedDocumentInternalAsync(cancellationToken);
}

private async ValueTask<SourceGeneratedDocument?> TryGetDeclGeneratedDocumentInternalAsync(CancellationToken cancellationToken)
{
if (Volatile.Read(ref _declGeneratedDocumentInitialized))
{
Expand All @@ -116,9 +139,17 @@ public async ValueTask<SourceGeneratedDocument> GetGeneratedDocumentAsync(Cancel
return declDocument;
}

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
#endif
public ValueTask<SyntaxTree> GetCSharpSyntaxTreeAsync(CancellationToken cancellationToken)
{
var document = _generatedDocument;
return GetCSharpSyntaxTreeAsync(declarationDocument: false, cancellationToken);
}

public ValueTask<SyntaxTree> GetCSharpSyntaxTreeAsync(bool declarationDocument, CancellationToken cancellationToken)
{
var document = declarationDocument ? _declGeneratedDocument : _generatedDocument;
if (document is not null &&
document.TryGetSyntaxTree(out var tree))
{
Expand All @@ -129,7 +160,7 @@ public ValueTask<SyntaxTree> GetCSharpSyntaxTreeAsync(CancellationToken cancella

async ValueTask<SyntaxTree> GetCSharpSyntaxTreeCoreAsync(Document? document, CancellationToken cancellationToken)
{
document ??= await GetGeneratedDocumentAsync(cancellationToken).ConfigureAwait(false);
document ??= await GetGeneratedDocumentAsync(declarationDocument, cancellationToken).ConfigureAwait(false);

var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return tree.AssumeNotNull();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using Microsoft.CodeAnalysis.Razor.DocumentMapping;
using Microsoft.CodeAnalysis.Razor.Protocol;
using Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.LanguageServer;

namespace Microsoft.CodeAnalysis.Remote.Razor;
Expand Down Expand Up @@ -45,21 +44,6 @@ protected DocumentPositionInfo GetPositionInfo(RazorCodeDocument codeDocument, i
return positionInfo;
}

protected bool TryGetDocumentPositionInfo(RazorCodeDocument codeDocument, Position position, out DocumentPositionInfo positionInfo)
=> TryGetDocumentPositionInfo(codeDocument, position, preferCSharpOverHtml: false, out positionInfo);

protected bool TryGetDocumentPositionInfo(RazorCodeDocument codeDocument, Position position, bool preferCSharpOverHtml, out DocumentPositionInfo positionInfo)
{
if (!codeDocument.Source.Text.TryGetAbsoluteIndex(position, out var hostDocumentIndex))
{
positionInfo = default;
return false;
}

positionInfo = GetPositionInfo(codeDocument, hostDocumentIndex, preferCSharpOverHtml);
return true;
}

protected ValueTask<T> RunServiceAsync<T>(
RazorSolutionWrapper solutionInfo,
DocumentId razorDocumentId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,19 @@ public ValueTask<SourceText> GetTextAsync(CancellationToken cancellationToken)
public ValueTask<VersionStamp> GetTextVersionAsync(CancellationToken cancellationToken)
=> throw new NotImplementedException();

#if SONICDEV
[System.Obsolete("PROTOTYPE(sonic): Call the overload that takes a bool to prove that you thought about which document to get")]
#endif
public ValueTask<SyntaxTree> GetCSharpSyntaxTreeAsync(CancellationToken cancellationToken)
{
return new(CSharpSyntaxTree.ParseText(_codeDocument.GetCSharpSourceText(), cancellationToken: cancellationToken));
return GetCSharpSyntaxTreeAsync(declarationDocument: false, cancellationToken);
}

public ValueTask<SourceGeneratedDocument?> TryGetDeclGeneratedDocumentAsync(CancellationToken cancellationToken)
=> new(default(SourceGeneratedDocument));
public ValueTask<SyntaxTree> GetCSharpSyntaxTreeAsync(bool declarationDocument, CancellationToken cancellationToken)
{
var csharpDocument = _codeDocument.GetRequiredCSharpDocument(declarationDocument);
return new(CSharpSyntaxTree.ParseText(csharpDocument.Text, cancellationToken: cancellationToken));
}

public bool TryGetGeneratedOutput([NotNullWhen(true)] out RazorCodeDocument? result)
{
Expand Down
Loading