Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -987,7 +987,7 @@ public void ComponentDirectiveVisitor_DoesNotMatch_LegacyTagHelpers()
}

[Fact]
public void ComponentDirectiveVisitor_AddsErrorOnLegacyTagHelperDirectives()
public void ComponentDirectiveVisitor_IgnoresLegacyTagHelperDirectives()
{
// Arrange
var currentNamespace = "SomeProject";
Expand All @@ -1013,15 +1013,12 @@ public void ComponentDirectiveVisitor_AddsErrorOnLegacyTagHelperDirectives()
visitor.Visit(tree);
var results = visitor.GetResults();

// Assert
// Assert: the component visitor ignores the legacy @tagHelperPrefix -- it applies no prefix and
// still resolves the component. The RZ9978 diagnostic for tag-helper directives in a component is
// emitted during IR lowering, not by this visitor.
Assert.Null(visitor.TagHelperPrefix);
var result = Assert.Single(results);
Assert.Same(componentDescriptor, result);
var erroredNode = tree.Root.DescendantNodes().FirstOrDefault(n => n is CSharpStatementLiteralSyntax);
Assert.NotNull(erroredNode);
var directiveChunkGenerator = (TagHelperPrefixDirectiveChunkGenerator)erroredNode.GetChunkGenerator();
var diagnostic = Assert.Single(directiveChunkGenerator.Diagnostics);
Assert.Equal("RZ9978", diagnostic.Id);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ @tagHelperPrefix th
The directives @addTagHelper, @removeTagHelper and @tagHelperPrefix are not valid in a component document. Use '@using <namespace>' directive instead.
""", item.GetMessage(CultureInfo.CurrentCulture));
Assert.Equal(0, item.Span.LineIndex);
Assert.Equal(0, item.Span.CharacterIndex);
Assert.Equal(14, item.Span.CharacterIndex);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Does this mean the squiggles are just for the erroneous @addTagHelper content, not the directive itself? Not a big deal I guess, just wondering.

Are there tests for empty directives, to ensure we still have something to report on?

(I'm reviewing commit-at-a-time so haven't seen baselines yet, which might answer these questions)

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.

Oh yeah, good catch. I'll update it so it walks up the tree to find the actual directive its attached to so we squiggle the whole thing (and add an empty test too)

},
item =>
{
Expand All @@ -86,7 +86,7 @@ @tagHelperPrefix th
The directives @addTagHelper, @removeTagHelper and @tagHelperPrefix are not valid in a component document. Use '@using <namespace>' directive instead.
""", item.GetMessage(CultureInfo.CurrentCulture));
Assert.Equal(1, item.Span.LineIndex);
Assert.Equal(0, item.Span.CharacterIndex);
Assert.Equal(17, item.Span.CharacterIndex);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2044,28 +2044,49 @@ public override void VisitCSharpImplicitExpression(CSharpImplicitExpressionSynta
}
public override void VisitCSharpStatementLiteral(CSharpStatementLiteralSyntax node)
{
if (node.ChunkGenerator is null or StatementChunkGenerator)
switch (node.ChunkGenerator)
{
var isAttributeValue = _builder.Current is CSharpCodeAttributeValueIntermediateNode;
// @addTagHelper / @removeTagHelper / @tagHelperPrefix are not valid in a component
// document. Tag-helper discovery runs after IR lowering, so the diagnostic is attached to
// the chunk generator here; the base visitor copies it onto the resulting IR node.
case AddTagHelperChunkGenerator addTagHelper:
addTagHelper.Diagnostics.Add(
ComponentDiagnosticFactory.Create_UnsupportedTagHelperDirective(BuildSourceSpanFromNode(node)));
break;
case RemoveTagHelperChunkGenerator removeTagHelper:
removeTagHelper.Diagnostics.Add(
ComponentDiagnosticFactory.Create_UnsupportedTagHelperDirective(BuildSourceSpanFromNode(node)));
break;
case TagHelperPrefixDirectiveChunkGenerator tagHelperPrefix:
tagHelperPrefix.Diagnostics.Add(
ComponentDiagnosticFactory.Create_UnsupportedTagHelperDirective(BuildSourceSpanFromNode(node)));
break;

if (!isAttributeValue)
case null:
case StatementChunkGenerator:
{
var statementNode = new CSharpCodeIntermediateNode()
var isAttributeValue = _builder.Current is CSharpCodeAttributeValueIntermediateNode;

if (!isAttributeValue)
{
Source = BuildSourceSpanFromNode(node)
};
_builder.Push(statementNode);
}
var statementNode = new CSharpCodeIntermediateNode()
{
Source = BuildSourceSpanFromNode(node)
};
_builder.Push(statementNode);
}

_builder.Add(IntermediateNodeFactory.CSharpToken(
arg: node,
contentFactory: static node => node.GetContent(),
source: BuildSourceSpanFromNode(node)));
_builder.Add(IntermediateNodeFactory.CSharpToken(
arg: node,
contentFactory: static node => node.GetContent(),
source: BuildSourceSpanFromNode(node)));

if (!isAttributeValue)
{
_builder.Pop();
if (!isAttributeValue)
{
_builder.Pop();
}
}
break;
}

base.VisitCSharpStatementLiteral(node);
Expand Down Expand Up @@ -2105,6 +2126,30 @@ public ComponentImportFileKindVisitor(
{
}

public override void VisitCSharpStatementLiteral(CSharpStatementLiteralSyntax node)
{
switch (node.ChunkGenerator)
{
// @addTagHelper / @removeTagHelper / @tagHelperPrefix are not valid in a component import
// document. Tag-helper discovery runs after IR lowering, so the diagnostic is attached to
// the chunk generator here; the base visitor copies it onto the resulting IR directive node.
case AddTagHelperChunkGenerator addTagHelper:
addTagHelper.Diagnostics.Add(
ComponentDiagnosticFactory.Create_UnsupportedTagHelperDirective(BuildSourceSpanFromNode(node)));
break;
case RemoveTagHelperChunkGenerator removeTagHelper:
removeTagHelper.Diagnostics.Add(
ComponentDiagnosticFactory.Create_UnsupportedTagHelperDirective(BuildSourceSpanFromNode(node)));
break;
case TagHelperPrefixDirectiveChunkGenerator tagHelperPrefix:
tagHelperPrefix.Diagnostics.Add(
ComponentDiagnosticFactory.Create_UnsupportedTagHelperDirective(BuildSourceSpanFromNode(node)));
break;
}

base.VisitCSharpStatementLiteral(node);
}

public override void VisitMarkupElement(MarkupElementSyntax node)
{
_document.AddDiagnostic(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -496,51 +496,12 @@ protected override void ProcessChunkGenerator(BaseRazorDirectiveSyntax node, ISp
{
switch (chunkGenerator)
{
case AddTagHelperChunkGenerator addTagHelper:
ProcessAddTagHelper(node, addTagHelper);
break;
case RemoveTagHelperChunkGenerator removeTagHelper:
ProcessRemoveTagHelper(node, removeTagHelper);
break;
case TagHelperPrefixDirectiveChunkGenerator tagHelperPrefix:
ProcessTagHelperPrefix(node, tagHelperPrefix);
break;
case AddImportChunkGenerator { IsStatic: false } addImport:
ProcessAddImport(node, addImport);
break;
}
}

private void ProcessAddTagHelper(BaseRazorDirectiveSyntax node, AddTagHelperChunkGenerator addTagHelper)
{
// We only add diagnostics if we're visiting the source document, not an import
if (IsSourceDocument)
{
addTagHelper.Diagnostics.Add(
ComponentDiagnosticFactory.Create_UnsupportedTagHelperDirective(node.GetSourceSpan(Source)));
}
}

private void ProcessRemoveTagHelper(BaseRazorDirectiveSyntax node, RemoveTagHelperChunkGenerator removeTagHelper)
{
// We only add diagnostics if we're visiting the source document, not an import
if (IsSourceDocument)
{
removeTagHelper.Diagnostics.Add(
ComponentDiagnosticFactory.Create_UnsupportedTagHelperDirective(node.GetSourceSpan(Source)));
}
}

private void ProcessTagHelperPrefix(BaseRazorDirectiveSyntax node, TagHelperPrefixDirectiveChunkGenerator tagHelperPrefix)
{
// We only add diagnostics if we're visiting the source document, not an import
if (IsSourceDocument)
{
tagHelperPrefix.Diagnostics.Add(
ComponentDiagnosticFactory.Create_UnsupportedTagHelperDirective(node.GetSourceSpan(Source)));
}
}

private void ProcessAddImport(BaseRazorDirectiveSyntax node, AddImportChunkGenerator addImport)
{
// Get the namespace from the using statement.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ public sealed class DocumentIntermediateNode : IntermediateNode
/// </summary>
internal bool IsSplitImplDocument { get; set; }

/// <summary>
/// The markup-free decl subtree captured by <see cref="DefaultRazorMarkupSplitPhase"/> when it split
/// this component, for <see cref="DefaultRazorDeclCSharpLoweringPhase"/> to lower into the decl C#
/// document before tag-helper discovery. Null when the document wasn't split.
/// </summary>
internal DocumentIntermediateNode DeclDocumentNode { get; set; }

public RazorCodeGenerationOptions Options { get; set; }

public CodeTarget Target { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Reflection.PortableExecutable;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.AspNetCore.Razor.Language.Intermediate;
using Microsoft.AspNetCore.Razor.Language.Legacy;
using Roslyn.Test.Utilities;
using Xunit;
Expand Down Expand Up @@ -44,18 +45,54 @@ protected RazorBaselineIntegrationTestBase(TestProject.Layer layer)
protected void AssertDocumentNodeMatchesBaseline(RazorCodeDocument codeDocument, [CallerMemberName]string testName = "")
{
var document = codeDocument.GetRequiredDocumentNode();
var baselineFilePath = GetBaselineFilePath(codeDocument, ".ir.txt", testName);
AssertIntermediateNodeMatchesBaseline(codeDocument, document, ".ir.txt", testName);

// When the split partitioned the component, the decl half is lowered from a separate IR subtree
// stashed on the document node before tag-helper resolution. Baseline it alongside the impl tree so
// the partition is reviewable at the IR level: the members the split moves out of the impl tree show
// up here rather than silently disappearing from the impl baseline.
AssertIntermediateNodeMatchesBaseline(codeDocument, document.DeclDocumentNode, ".decl.ir.txt", testName);
}

private void AssertIntermediateNodeMatchesBaseline(RazorCodeDocument codeDocument, DocumentIntermediateNode document, string extension, string testName)
{
var baselineFilePath = GetBaselineFilePath(codeDocument, extension, testName);

if (GenerateBaselines.ShouldGenerate)
{
var baselineFullPath = Path.Combine(TestProjectRoot, baselineFilePath);

if (document is null)
{
// No decl half (a fallback, a suppressed primary body, or a non-split document) -- remove any
// decl baseline on disk, which has no decl half to match.
if (File.Exists(baselineFullPath))
{
File.Delete(baselineFullPath);
}

return;
}

Directory.CreateDirectory(Path.GetDirectoryName(baselineFullPath));
WriteBaseline(IntermediateNodeSerializer.Serialize(document), baselineFullPath);

return;
}

var irFile = TestFile.Create(baselineFilePath, GetType().Assembly);

if (document is null)
{
// No decl half, so its baseline must not exist.
if (irFile.Exists())
{
throw new XunitException($"The resource {baselineFilePath} exists but the document has no matching half.");
}

return;
}

if (!irFile.Exists())
{
throw new XunitException($"The resource {baselineFilePath} was not found.");
Expand All @@ -73,18 +110,26 @@ protected void AssertCSharpDocumentMatchesBaseline(RazorCodeDocument codeDocumen
var implDocument = codeDocument.GetRequiredImplCSharpDocument();
AssertCSharpHalfMatchesBaseline(codeDocument, implDocument, ".codegen.cs", ".diagnostics.txt", ".mappings.txt", testName);

// When the decl phase has split the document, also assert the decl half against
// its own set of baselines. Note that the decl half is written with
// reportDiagnostics: false: the impl writer seeds its synthetic root with
// documentNode.GetAllDiagnostics() and reports the full set, so suppressing
// duplicate reporting on the decl side keeps each Razor-detected diagnostic on
// exactly one half. As a side effect there is no .decl.diagnostics.txt baseline
// to commit -- the regen path treats an empty diagnostics list as "delete the
// baseline file" and the decl half always has one.
// When the split partitioned the component, also assert the decl half against its own set of
// baselines. Note that the decl half is written with reportDiagnostics: false: the impl writer
// seeds its synthetic root with documentNode.GetAllDiagnostics() and reports the full set, so
// suppressing duplicate reporting on the decl side keeps each Razor-detected diagnostic on exactly
// one half. As a side effect there is no .decl.diagnostics.txt baseline to commit -- the regen path
// treats an empty diagnostics list as "delete the baseline file" and the decl half always has one.
//
// When there is no decl half (the component lowers as a single document, or isn't a component), a
// decl baseline on disk has nothing to match, so delete-stale / assert-absent it to keep orphaned
// decl output out of the tree. This mirrors the decl-IR handling in AssertIntermediateNodeMatchesBaseline.
if (codeDocument.GetDeclCSharpDocument() is { } declDocument)
{
AssertCSharpHalfMatchesBaseline(codeDocument, declDocument, ".decl.codegen.cs", ".decl.diagnostics.txt", ".decl.mappings.txt", testName);
}
else
{
AssertNoBaseline(codeDocument, ".decl.codegen.cs", testName);
AssertNoBaseline(codeDocument, ".decl.diagnostics.txt", testName);
AssertNoBaseline(codeDocument, ".decl.mappings.txt", testName);
}

if (verifyLinePragmas)
{
Expand Down Expand Up @@ -169,6 +214,31 @@ private void AssertCSharpHalfMatchesBaseline(
Assert.Equal(baselineMappings, actualMappings);
}

// Ensures a decl-half baseline does not exist: deletes a stale file when generating, asserts its
// absence when verifying. A decl baseline is only valid when the document produces a decl half, so a
// document with none must have no decl baseline on disk to match against.
private void AssertNoBaseline(RazorCodeDocument codeDocument, string extension, string testName)
{
var baselineFilePath = GetBaselineFilePath(codeDocument, extension, testName);

if (GenerateBaselines.ShouldGenerate)
{
var baselineFullPath = Path.Combine(TestProjectRoot, baselineFilePath);
if (File.Exists(baselineFullPath))
{
File.Delete(baselineFullPath);
}

return;
}

var file = TestFile.Create(baselineFilePath, GetType().Assembly);
if (file.Exists())
{
throw new XunitException($"The resource {baselineFilePath} exists but the document has no decl half.");
}
}

protected void AssertLinePragmas(RazorCodeDocument codeDocument)
{
var csharpDocument = codeDocument.GetImplCSharpDocument();
Expand Down