diff --git a/.github/instructions/Razor.instructions.md b/.github/instructions/Razor.instructions.md index 9e05da0d6eb2e..ebc0f71720380 100644 --- a/.github/instructions/Razor.instructions.md +++ b/.github/instructions/Razor.instructions.md @@ -15,6 +15,9 @@ their original sub-tree layout The bug is more likely in existing logic than a missing feature. - **Helpers**: Review existing helpers (`UsingDirectiveHelper`, `AddUsingsHelper`, etc.) before writing new utility methods. Don't duplicate. +- **Warning levels**: Track warnings with non-zero `RazorWarningLevel` values in + [`docs/razor/warning-levels.md`](../../docs/razor/warning-levels.md), including the diagnostic + ID, warning level, exact message, and trigger condition. ## File Types diff --git a/docs/razor/WarningWavesProposal.md b/docs/razor/WarningWavesProposal.md index affce29ac415b..ef0f55cc6547f 100644 --- a/docs/razor/WarningWavesProposal.md +++ b/docs/razor/WarningWavesProposal.md @@ -1,6 +1,6 @@ # Proposal: Warning Levels for Razor -> **Status:** The infrastructure described here was implemented in [dotnet/razor#13016](https://github.com/dotnet/razor/pull/13016) and ships in Razor 18.7. The shipped feature is named **warning levels** (`RazorWarningLevel`) rather than warning waves. No new warnings have been classified at non-default levels yet — that work is layered on top of this infrastructure as warnings are introduced. +> **Status:** The infrastructure described here was implemented in [dotnet/razor#13016](https://github.com/dotnet/razor/pull/13016) and ships in Razor 18.7. The shipped feature is named **warning levels** (`RazorWarningLevel`) rather than warning waves. Warnings classified at non-default levels are tracked in [Razor warning levels](warning-levels.md). ## Summary @@ -40,7 +40,7 @@ Each warning is tagged with an integer **warning level**. The compiler reports a **Default behaviour.** When `RazorWarningLevel` is not set, the compiler uses `RazorLanguageVersion.GetDefaultWarningLevel()`, which currently returns the language version's major number. So a project on Razor 11 implicitly gets `RazorWarningLevel = 11` and therefore sees every level <= 11. -**Existing warnings are unaffected.** All warnings that exist today were authored without specifying a level, so they default to level `0` and continue to be reported regardless of the configured `RazorWarningLevel`. No project sees a behavior change until new warnings are added at higher levels. +**Existing level-0 warnings are unaffected.** Warnings authored without specifying a level default to level `0` and continue to be reported regardless of the configured `RazorWarningLevel`. Warning-wave diagnostics use non-zero levels and are filtered as described above. ### Configuration @@ -148,12 +148,11 @@ The infrastructure landed in [#13016](https://github.com/dotnet/razor/pull/13016 - ✅ `CodeRenderingContext.GetDiagnostics()` filters warnings by level. - ✅ `RZ3601` reported for invalid `RazorWarningLevel` values. - ✅ `RazorLanguageVersion.GetDefaultWarningLevel()` defines the default (currently `Major`). +- ✅ Non-zero-level warnings are catalogued in [Razor warning levels](warning-levels.md). Still to do (follow-up work): -- Author the first batch of non-zero-level warnings. - IDE/tooling integration so live diagnostics also respect the configured level. -- User-facing documentation listing each warning and the level at which it was introduced. ## Open Questions diff --git a/docs/razor/warning-levels.md b/docs/razor/warning-levels.md new file mode 100644 index 0000000000000..6cfc445d15474 --- /dev/null +++ b/docs/razor/warning-levels.md @@ -0,0 +1,15 @@ +# Razor warning levels + +Razor diagnostics introduced in warning waves are assigned a non-zero warning level. A diagnostic +is reported when its level is less than or equal to the configured `RazorWarningLevel`. See the +[warning levels proposal](WarningWavesProposal.md) for the design and configuration details. + +## Warnings + +| Diagnostic | Warning level | Message | When reported | +|------------|---------------|---------|---------------| +| `RZ3907` | 11 | `The '@model' directive is not applied to the generated base class because the '@inherits' directive does not contain ''.` | An MVC view has an explicit `@model` directive and an `@inherits` directive without the literal `` placeholder. | +| `RZ10025` | 11 | `The component '{0}' does not have a parameter named '{1}'.` | An explicit attribute on a resolved component does not bind to a known component parameter, and no valid capture-unmatched-values parameter can accept it. | +| `RZ10026` | 11 | `The bind attribute '{0}' does not match any parameter on component '{1}'.` | A component `@bind-*` attribute has a statically known target name that does not match a component parameter. | +| `RZ10027` | 11 | `The bind attribute '{0}' requires a matching change parameter named '{1}' on component '{2}'.` | A component bind target exists, but its statically known companion change parameter does not. | +| `RZ10028` | 11 | `The attribute '{0}' could not be bound to any directive attribute.` | A parser-recognized directive attribute in a component document reaches tag-helper resolution without any semantic bound-attribute match. | diff --git a/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentBindIntegrationTest.cs b/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentBindIntegrationTest.cs index 428026c8417f0..c155df6ca3b6a 100644 --- a/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentBindIntegrationTest.cs +++ b/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentBindIntegrationTest.cs @@ -1,7 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System; using System.Globalization; +using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests; @@ -134,4 +136,321 @@ @using Test Assert.Equal("Found a malformed 'InputText' tag helper. Tag helpers must have a start and end tag or be self closing.", diagnostic.GetMessage(CultureInfo.CurrentCulture)); }); } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/13125")] + public void BindToComponent_MissingTarget_NoWarningAtAnalysisLevel10() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + } + """)); + + var generated = CompileToCSharp( + """ + @using Test + + + @code { + public int ParentValue { get; set; } + } + """, + configuration: Configuration with { RazorWarningLevel = 10 }); + + Assert.Empty(generated.RazorDiagnostics); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/13125")] + public void BindToComponent_MissingTarget_ButAcceptsUnmatched_NoWarningAtAnalysisLevel11() + { + AdditionalSyntaxTrees.Add(Parse(""" + using System.Collections.Generic; + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + [Parameter(CaptureUnmatchedValues = true)] + public Dictionary AdditionalAttributes { get; set; } + } + """)); + + var generated = CompileToCSharp( + """ + @using Test + + + @code { + public int ParentValue { get; set; } + } + """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Empty(generated.RazorDiagnostics); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/13125")] + public void BindToComponent_MissingTarget_WarnsAtAnalysisLevel11() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + } + """)); + + const string content = """ + @using Test + + + @code { + public int ParentValue { get; set; } + } + """; + + var generated = CompileToCSharp( + content, + configuration: Configuration with { RazorWarningLevel = 11 }); + + var diagnostic = Assert.Single(generated.RazorDiagnostics); + Assert.Equal("RZ10026", diagnostic.Id); + Assert.Equal(RazorDiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Equal(11, diagnostic.WarningLevel); + Assert.Equal( + "The bind attribute '@bind-Missing' does not match any parameter on component 'MyComponent'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + AssertDiagnosticSpan(content, diagnostic, "Missing"); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/13125")] + public void BindToComponent_MissingChangeParameter_NoWarningAtAnalysisLevel10() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + [Parameter] + public int Value { get; set; } + } + """)); + + var generated = CompileToCSharp( + """ + @using Test + + + @code { + public int ParentValue { get; set; } + } + """, + configuration: Configuration with { RazorWarningLevel = 10 }); + + Assert.Empty(generated.RazorDiagnostics); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/13125")] + public void BindToComponent_MissingChangeParameter_WarnsAtAnalysisLevel11() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + [Parameter] + public int Value { get; set; } + } + """)); + + const string content = """ + @using Test + + + @code { + public int ParentValue { get; set; } + } + """; + + var generated = CompileToCSharp( + content, + configuration: Configuration with { RazorWarningLevel = 11 }); + + var diagnostic = Assert.Single(generated.RazorDiagnostics); + Assert.Equal("RZ10027", diagnostic.Id); + Assert.Equal(RazorDiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Equal(11, diagnostic.WarningLevel); + Assert.Equal( + "The bind attribute '@bind-Value' requires a matching change parameter named 'ValueChanged' on component 'MyComponent'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + AssertDiagnosticSpan(content, diagnostic, "Value"); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/13125")] + public void BindToComponent_MissingChangeParameter_ButAcceptsUnmatched_NoWarningAtAnalysisLevel11() + { + AdditionalSyntaxTrees.Add(Parse(""" + using System.Collections.Generic; + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + [Parameter] + public int Value { get; set; } + + [Parameter(CaptureUnmatchedValues = true)] + public Dictionary AdditionalAttributes { get; set; } + } + """)); + + var generated = CompileToCSharp( + """ + @using Test + + + @code { + public int ParentValue { get; set; } + } + """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Empty(generated.RazorDiagnostics); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/13125")] + public void BindToComponent_MissingExplicitChangeParameter_WarnsAtAnalysisLevel11() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + [Parameter] + public int Value { get; set; } + } + """)); + + const string content = """ + @using Test + + + @code { + public int ParentValue { get; set; } + } + """; + + var generated = CompileToCSharp( + content, + configuration: Configuration with { RazorWarningLevel = 11 }); + + var diagnostic = Assert.Single(generated.RazorDiagnostics); + Assert.Equal("RZ10027", diagnostic.Id); + Assert.Equal(RazorDiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Equal(11, diagnostic.WarningLevel); + Assert.Equal( + "The bind attribute '@bind-Value' requires a matching change parameter named 'OnChanged' on component 'MyComponent'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + AssertDiagnosticSpan(content, diagnostic, "OnChanged"); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/13125")] + public void BindToComponent_DynamicEvent_NoWarningAtAnalysisLevel11() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + [Parameter] + public int Value { get; set; } + } + """)); + + var generated = CompileToCSharp( + """ + @using Test + + + @code { + public int ParentValue { get; set; } + + private string EventName => "ValueChanged"; + } + """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Empty(generated.RazorDiagnostics); + CompileToAssembly(generated); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/13125")] + public void BindToComponent_ValidTargetsAndModifiers_NoWarningsAtAnalysisLevel11() + { + AdditionalSyntaxTrees.Add(Parse(""" + using System; + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + [Parameter] + public int Value { get; set; } + + [Parameter] + public Action ValueChanged { get; set; } + + [Parameter] + public Action OnChanged { get; set; } + } + """)); + + var generated = CompileToCSharp( + """ + @using Test + + + + + + @code { + public int ParentValue { get; set; } + + private void UpdateValue(int value) => ParentValue = value; + + private void After() + { + } + } + """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Empty(generated.RazorDiagnostics); + CompileToAssembly(generated); + } + + private static void AssertDiagnosticSpan(string content, RazorDiagnostic diagnostic, string expected) + { + var index = content.IndexOf(expected, StringComparison.Ordinal); + Assert.NotNull(diagnostic.Span.FilePath); + Assert.Equal(index, diagnostic.Span.AbsoluteIndex); + Assert.Equal(expected.Length, diagnostic.Span.Length); + } } diff --git a/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentDiagnosticRazorIntegrationTest.cs b/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentDiagnosticRazorIntegrationTest.cs index 74f9dc0fc18e8..e1f6434494706 100644 --- a/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentDiagnosticRazorIntegrationTest.cs +++ b/src/Razor/src/Compiler/Microsoft.AspNetCore.Razor.Language/test/IntegrationTests/ComponentDiagnosticRazorIntegrationTest.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System; using System.Globalization; using Roslyn.Test.Utilities; using Xunit; @@ -158,6 +159,132 @@ public void DirectiveAttribute_ComplexContent_ReportsError() diagnostic.GetMessage(CultureInfo.CurrentCulture)); } + [Fact, WorkItem("https://github.com/dotnet/razor/issues/7650")] + public void UnboundDirectiveAttribute_OnElement_Level10_DoesNotReportWarning() + { + // Arrange & Act + var generated = CompileToCSharp( + """
""", + configuration: Configuration with { RazorWarningLevel = 10 }); + + // Assert + Assert.Empty(generated.RazorDiagnostics); + Assert.Contains("AddMarkupContent", generated.Code); + Assert.Contains("""
""", generated.Code); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/7650")] + public void UnboundDirectiveAttribute_OnElement_Level11_ReportsWarning() + { + // Arrange & Act + var generated = CompileToCSharp( + """
""", + configuration: Configuration with { RazorWarningLevel = 11 }); + + // Assert + AssertUnboundDirectiveAttributeDiagnostic(Assert.Single(generated.RazorDiagnostics), "@unknown"); + Assert.Contains("AddMarkupContent", generated.Code); + Assert.Contains("""
""", generated.Code); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/7650")] + public void UnboundDirectiveAttribute_OnComponent_Level10_DoesNotReportWarning() + { + // Arrange + AddTestComponent(); + + // Act + var generated = CompileToCSharp( + """""", + configuration: Configuration with { RazorWarningLevel = 10 }); + + // Assert + Assert.Empty(generated.RazorDiagnostics); + Assert.Contains("AddComponentParameter", generated.Code); + Assert.Contains("\"@unknown\"", generated.Code); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/7650")] + public void UnboundDirectiveAttribute_OnComponent_Level11_ReportsWarning() + { + // Arrange + AddTestComponent(); + + // Act + var generated = CompileToCSharp( + """""", + configuration: Configuration with { RazorWarningLevel = 11 }); + + // Assert + AssertUnboundDirectiveAttributeDiagnostic(Assert.Single(generated.RazorDiagnostics), "@unknown"); + Assert.Contains("AddComponentParameter", generated.Code); + Assert.Contains("\"@unknown\"", generated.Code); + } + + [Theory, WorkItem("https://github.com/dotnet/razor/issues/7650")] + [InlineData("@onclickx=\"true\"", "@onclickx")] + [InlineData("@onclick:unknown=\"true\"", "@onclick:unknown")] + [InlineData("@ref:suppressField", "@ref:suppressField")] + public void UnboundDirectiveAttribute_MalformedOrNearMatch_ReportsWarning(string attribute, string attributeName) + { + // Arrange & Act + var generated = CompileToCSharp( + $""" + @using Microsoft.AspNetCore.Components.Web +
+ """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + // Assert + AssertUnboundDirectiveAttributeDiagnostic(Assert.Single(generated.RazorDiagnostics), attributeName); + } + + [Theory, WorkItem("https://github.com/dotnet/razor/issues/7650")] + [InlineData("
")] + [InlineData("
")] + public void UnboundDirectiveAttribute_EscapedName_DoesNotReportWarning(string content) + { + // Arrange & Act + var generated = CompileToCSharp( + content, + configuration: Configuration with { RazorWarningLevel = 11 }); + + // Assert + Assert.Empty(generated.RazorDiagnostics); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/7650")] + public void UnboundDirectiveAttribute_OnEscapedElement_DoesNotReportWarning() + { + // Arrange & Act + var generated = CompileToCSharp( + """""", + configuration: Configuration with { RazorWarningLevel = 11 }); + + // Assert + Assert.Empty(generated.RazorDiagnostics); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/7650")] + public void UnboundDirectiveAttribute_AlreadyBoundDirectives_DoNotReportWarning() + { + // Arrange & Act + var generated = CompileToCSharp( + """ + @using Microsoft.AspNetCore.Components.Web +
+ + """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + // Assert + Assert.Empty(generated.RazorDiagnostics); + } + [Fact] public void Component_StartsWithLowerCase_ReportsError() { @@ -268,4 +395,386 @@ public class MyComponent : ComponentBase "The start tag name 'MyComponent' does not match the end tag name 'mycomponent'. Components must have matching start and end tag names (case-sensitive).", diagnostic.GetMessage(CultureInfo.CurrentCulture)); } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_UnknownParameter_RazorWarningLevel10_DoesNotWarn() + { + AddGenericComponentWithKnownParameter(); + + const string content = """"""; + + var generated = CompileToCSharp( + content, + configuration: Configuration with { RazorWarningLevel = 10 }); + + Assert.Empty(generated.RazorDiagnostics); + AssertUnknownParameterIsGenerated(generated.Code); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_UnknownParameter_RazorWarningLevel11_Warns() + { + AddGenericComponentWithKnownParameter(); + + const string content = """"""; + + var generated = CompileToCSharp( + content, + configuration: Configuration with { RazorWarningLevel = 11 }); + + var diagnostic = Assert.Single(generated.RazorDiagnostics); + Assert.Equal("RZ10025", diagnostic.Id); + Assert.Equal(RazorDiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Equal(11, diagnostic.WarningLevel); + Assert.Equal( + "The component 'MyComponent' does not have a parameter named 'Unknown'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + var unknownParameterIndex = content.IndexOf("Unknown", StringComparison.Ordinal); + Assert.NotNull(diagnostic.Span.FilePath); + Assert.Equal(unknownParameterIndex, diagnostic.Span.AbsoluteIndex); + Assert.Equal(unknownParameterIndex, diagnostic.Span.CharacterIndex); + Assert.Equal("Unknown".Length, diagnostic.Span.Length); + AssertUnknownParameterIsGenerated(generated.Code); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_MultipleUnknownParameters_Warn() + { + AddGenericComponentWithKnownParameter(); + + const string content = """"""; + + var generated = CompileToCSharp( + content, + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Collection( + generated.RazorDiagnostics, + diagnostic => AssertDiagnostic(diagnostic, "FirstUnknown"), + diagnostic => AssertDiagnostic(diagnostic, "SecondUnknown")); + Assert.Contains("\"FirstUnknown\"", generated.Code); + Assert.Contains("\"SecondUnknown\"", generated.Code); + Assert.Equal(2, generated.Code.Split( + ["AddComponentParameter"], + StringSplitOptions.None).Length - 1); + + void AssertDiagnostic(RazorDiagnostic diagnostic, string parameterName) + { + Assert.Equal("RZ10025", diagnostic.Id); + Assert.Equal(RazorDiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Equal(11, diagnostic.WarningLevel); + Assert.Equal( + $"The component 'MyComponent' does not have a parameter named '{parameterName}'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + var parameterIndex = content.IndexOf(parameterName, StringComparison.Ordinal); + Assert.NotNull(diagnostic.Span.FilePath); + Assert.Equal(parameterIndex, diagnostic.Span.AbsoluteIndex); + Assert.Equal(parameterIndex, diagnostic.Span.CharacterIndex); + Assert.Equal(parameterName.Length, diagnostic.Span.Length); + } + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_KnownAndUnknownParameters_Warns() + { + AddGenericComponentWithKnownParameter(); + + const string content = """"""; + + var generated = CompileToCSharp( + content, + configuration: Configuration with { RazorWarningLevel = 11 }); + + var diagnostic = Assert.Single(generated.RazorDiagnostics); + Assert.Equal("RZ10025", diagnostic.Id); + Assert.Equal( + "The component 'MyComponent' does not have a parameter named 'Unknown'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + Assert.Contains("\"Unknown\"", generated.Code); + Assert.Equal(2, generated.Code.Split( + ["AddComponentParameter"], + StringSplitOptions.None).Length - 1); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_KnownAndMultipleUnknownParameters_Warn() + { + AddGenericComponentWithKnownParameter(); + + const string content = """"""; + + var generated = CompileToCSharp( + content, + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Collection( + generated.RazorDiagnostics, + diagnostic => AssertDiagnostic(diagnostic, "FirstUnknown"), + diagnostic => AssertDiagnostic(diagnostic, "SecondUnknown")); + Assert.Contains("\"FirstUnknown\"", generated.Code); + Assert.Contains("\"SecondUnknown\"", generated.Code); + Assert.Equal(3, generated.Code.Split( + ["AddComponentParameter"], + StringSplitOptions.None).Length - 1); + + void AssertDiagnostic(RazorDiagnostic diagnostic, string parameterName) + { + Assert.Equal("RZ10025", diagnostic.Id); + Assert.Equal(RazorDiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Equal(11, diagnostic.WarningLevel); + Assert.Equal( + $"The component 'MyComponent' does not have a parameter named '{parameterName}'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + var parameterIndex = content.IndexOf(parameterName, StringComparison.Ordinal); + Assert.NotNull(diagnostic.Span.FilePath); + Assert.Equal(parameterIndex, diagnostic.Span.AbsoluteIndex); + Assert.Equal(parameterIndex, diagnostic.Span.CharacterIndex); + Assert.Equal(parameterName.Length, diagnostic.Span.Length); + } + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_KnownParameter_WithDifferentCasing_DoesNotWarn() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public abstract class ComponentBaseWithParameter : ComponentBase + { + [Parameter] public string Known { get; set; } + } + + public class MyComponent : ComponentBaseWithParameter + { + } + """)); + + var generated = CompileToCSharp( + """ + + + """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Empty(generated.RazorDiagnostics); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_ValidInheritedCaptureUnmatchedValuesParameter_DoesNotWarn() + { + AdditionalSyntaxTrees.Add(Parse(""" + using System.Collections.Generic; + using Microsoft.AspNetCore.Components; + + namespace Test; + + public abstract class ComponentBaseWithAdditionalAttributes : ComponentBase + { + [Parameter] public TValue Known { get; set; } + + [Parameter(CaptureUnmatchedValues = true)] + public IReadOnlyDictionary AdditionalAttributes { get; set; } + } + + public class MyComponent : ComponentBaseWithAdditionalAttributes + { + } + """)); + + var generated = CompileToCSharp( + """""", + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Empty(generated.RazorDiagnostics); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_InvalidCaptureUnmatchedValuesParameters_Warn() + { + AdditionalSyntaxTrees.Add(Parse(""" + using System.Collections.Generic; + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class CaptureDisabled : ComponentBase + { + [Parameter(CaptureUnmatchedValues = false)] + public IReadOnlyDictionary AdditionalAttributes { get; set; } + } + + public class WrongType : ComponentBase + { + [Parameter(CaptureUnmatchedValues = true)] + public string AdditionalAttributes { get; set; } + } + + public class DuplicateCapture : ComponentBase + { + [Parameter(CaptureUnmatchedValues = true)] + public IReadOnlyDictionary AdditionalAttributes { get; set; } + + [Parameter(CaptureUnmatchedValues = true)] + public IDictionary OtherAttributes { get; set; } + } + + public class UserDefinedConversionCapture : ComponentBase + { + [Parameter(CaptureUnmatchedValues = true)] + public AttributeCollection AdditionalAttributes { get; set; } + } + + public class AttributeCollection + { + public static implicit operator AttributeCollection(Dictionary attributes) + => new(); + } + """)); + + var generated = CompileToCSharp( + """ + + + + + """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Collection( + generated.RazorDiagnostics, + diagnostic => + { + Assert.Equal("RZ10025", diagnostic.Id); + Assert.Equal( + "The component 'CaptureDisabled' does not have a parameter named 'Unknown'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + }, + diagnostic => + { + Assert.Equal("RZ10025", diagnostic.Id); + Assert.Equal( + "The component 'WrongType' does not have a parameter named 'Unknown'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + }, + diagnostic => + { + Assert.Equal("RZ10025", diagnostic.Id); + Assert.Equal( + "The component 'DuplicateCapture' does not have a parameter named 'Unknown'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + }, + diagnostic => + { + Assert.Equal("RZ10025", diagnostic.Id); + Assert.Equal( + "The component 'UserDefinedConversionCapture' does not have a parameter named 'Unknown'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + }); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_HtmlSplatAndDirectiveAttributes_DoNotWarn() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + } + """)); + + var generated = CompileToCSharp( + """ + @using System.Collections.Generic + +
+ + + @code { + private MyComponent _component = default!; + } + """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + Assert.Empty(generated.RazorDiagnostics); + } + + [Fact, WorkItem("https://github.com/dotnet/razor/issues/11114")] + public void Component_UnknownParameter_WithSplat_Warns() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + } + """)); + + var generated = CompileToCSharp( + """ + @using System.Collections.Generic + + + """, + configuration: Configuration with { RazorWarningLevel = 11 }); + + var diagnostic = Assert.Single(generated.RazorDiagnostics); + Assert.Equal("RZ10025", diagnostic.Id); + Assert.Equal( + "The component 'MyComponent' does not have a parameter named 'Unknown'.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + } + + private void AddGenericComponentWithKnownParameter() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + [Parameter] public TValue Known { get; set; } + } + """)); + } + + private static void AssertUnknownParameterIsGenerated(string code) + { + Assert.Contains("\"Unknown\"", code); + Assert.Equal(1, code.Split( + ["AddComponentParameter"], + StringSplitOptions.None).Length - 1); + } + + private void AddTestComponent() + { + AdditionalSyntaxTrees.Add(Parse(""" + using Microsoft.AspNetCore.Components; + + namespace Test; + + public class MyComponent : ComponentBase + { + [Parameter] + public string Value { get; set; } + } + """)); + } + + private static void AssertUnboundDirectiveAttributeDiagnostic(RazorDiagnostic diagnostic, string attributeName) + { + Assert.Equal("RZ10028", diagnostic.Id); + Assert.Equal(RazorDiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Equal( + $"The attribute '{attributeName}' could not be bound to any directive attribute.", + diagnostic.GetMessage(CultureInfo.CurrentCulture)); + Assert.Equal(attributeName.Length, diagnostic.Span.Length); + } } diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentBindLoweringPass.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentBindLoweringPass.cs index cd83bef8b616c..f3fac4eb3533a 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentBindLoweringPass.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentBindLoweringPass.cs @@ -434,12 +434,39 @@ private static ImmutableArray RewriteUsage(IntermediateNode pa } } - var original = GetAttributeContent(bindEntry.GetEffectiveBindNode()); + var targetNode = bindEntry.GetEffectiveBindNode(); + + var original = GetAttributeContent(targetNode); if (string.IsNullOrEmpty(original.Content)) { // This can happen in error cases, the parser will already have flagged this // as an error, so ignore it. - return [bindEntry.GetEffectiveBindNode()]; + return [targetNode]; + } + + if (parent is ComponentIntermediateNode component && + !string.IsNullOrEmpty(valueAttributeName) && + !component.Component.AcceptsUnmatchedAttributes()) + { + var source = GetOriginalPropertySpan(targetNode) ?? targetNode.Source; + + if (valueAttribute is null) + { + component.AddDiagnostic(ComponentDiagnosticFactory.CreateBindAttribute_MissingTarget( + source, + bindEntry.OriginalAttributeName, + component.TagName)); + } + else if (changeAttributeNode is null && + !string.IsNullOrEmpty(changeAttributeName) && + changeAttribute is null) + { + component.AddDiagnostic(ComponentDiagnosticFactory.CreateBindAttribute_MissingChangeAttribute( + bindEntry.BindEventNode?.Source ?? source, + bindEntry.OriginalAttributeName, + changeAttributeName, + component.TagName)); + } } // Look for a format. If we find one then we need to pass the format into the @@ -507,8 +534,6 @@ ref valueExpressionTokens.AsRef(), ref changeExpressionTokens.AsRef()); } - var targetNode = bindEntry.GetEffectiveBindNode(); - if (parent is MarkupElementIntermediateNode) { var valueNode = new HtmlAttributeIntermediateNode() diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentDiagnosticFactory.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentDiagnosticFactory.cs index e3cbba91fb242..48aed034d692c 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentDiagnosticFactory.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentDiagnosticFactory.cs @@ -442,4 +442,44 @@ public static RazorDiagnostic CreateRenderModeAttribute_ComponentDeclaredRenderM { return RazorDiagnostic.Create(RenderModeAttribute_ComponentDeclaredRenderMode, source, component); } + + public static readonly RazorDiagnosticDescriptor UnknownComponentParameter = + new($"{DiagnosticPrefix}10025", + "The component '{0}' does not have a parameter named '{1}'.", + RazorDiagnosticSeverity.Warning, + warningLevel: 11); + + public static RazorDiagnostic Create_UnknownComponentParameter(SourceSpan? source, string component, string parameter) + => RazorDiagnostic.Create(UnknownComponentParameter, source, component, parameter); + + public static readonly RazorDiagnosticDescriptor BindAttribute_MissingTarget = + new($"{DiagnosticPrefix}10026", + "The bind attribute '{0}' does not match any parameter on component '{1}'.", + RazorDiagnosticSeverity.Warning, + warningLevel: 11); + + public static RazorDiagnostic CreateBindAttribute_MissingTarget(SourceSpan? source, string attribute, string component) + => RazorDiagnostic.Create(BindAttribute_MissingTarget, source, attribute, component); + + public static readonly RazorDiagnosticDescriptor BindAttribute_MissingChangeAttribute = + new($"{DiagnosticPrefix}10027", + "The bind attribute '{0}' requires a matching change parameter named '{1}' on component '{2}'.", + RazorDiagnosticSeverity.Warning, + warningLevel: 11); + + public static RazorDiagnostic CreateBindAttribute_MissingChangeAttribute( + SourceSpan? source, + string attribute, + string changeAttribute, + string component) + => RazorDiagnostic.Create(BindAttribute_MissingChangeAttribute, source, attribute, changeAttribute, component); + + public static readonly RazorDiagnosticDescriptor UnboundDirectiveAttribute = + new($"{DiagnosticPrefix}10028", + "The attribute '{0}' could not be bound to any directive attribute.", + RazorDiagnosticSeverity.Warning, + warningLevel: 11); + + public static RazorDiagnostic Create_UnboundDirectiveAttribute(SourceSpan? source, string attribute) + => RazorDiagnostic.Create(UnboundDirectiveAttribute, source, attribute); } diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentLoweringPass.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentLoweringPass.cs index e635d18bc6f1a..afa17132e5726 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentLoweringPass.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentLoweringPass.cs @@ -650,6 +650,16 @@ private bool TryGetAttributeStringContent(TagHelperPropertyIntermediateNode prop public override void VisitTagHelperHtmlAttribute(TagHelperHtmlAttributeIntermediateNode node) { var attribute = new ComponentAttributeIntermediateNode(node); + + if (!node.IsDirectiveAttributeCandidate && + !_component.Component.AcceptsUnmatchedAttributes()) + { + attribute.AddDiagnostic(ComponentDiagnosticFactory.Create_UnknownComponentParameter( + node.AttributeNameSpan, + _component.TagName, + node.AttributeName)); + } + _children.Add(attribute); // Since we don't support complex content, we can rewrite the inside of this diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentMetadata.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentMetadata.cs index 9a7d5db597056..c2983897bd6e0 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentMetadata.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentMetadata.cs @@ -11,6 +11,7 @@ public sealed record class ComponentMetadata() : MetadataObject(MetadataKind.Com public bool IsGeneric { get; init; } public bool HasRenderModeDirective { get; init; } + internal bool AcceptsUnmatchedAttributes { get; init; } internal override bool HasDefaultValue => Equals(Default); @@ -18,18 +19,21 @@ private protected override void BuildChecksum(in Checksum.Builder builder) { builder.Append(IsGeneric); builder.Append(HasRenderModeDirective); + builder.Append(AcceptsUnmatchedAttributes); } public ref struct Builder { public bool IsGeneric { get; set; } public bool HasRenderModeDirective { get; set; } + internal bool AcceptsUnmatchedAttributes { get; set; } public readonly ComponentMetadata Build() => new() { IsGeneric = IsGeneric, - HasRenderModeDirective = HasRenderModeDirective + HasRenderModeDirective = HasRenderModeDirective, + AcceptsUnmatchedAttributes = AcceptsUnmatchedAttributes }; } } diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentsApi.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentsApi.cs index f664697057057..0879cbc1cd751 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentsApi.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/ComponentsApi.cs @@ -26,6 +26,7 @@ public static class ParameterAttribute { public const string FullTypeName = "Microsoft.AspNetCore.Components.ParameterAttribute"; public const string MetadataName = FullTypeName; + public const string CaptureUnmatchedValues = nameof(CaptureUnmatchedValues); } public static class LayoutAttribute @@ -50,6 +51,11 @@ public static class IDictionary public const string MetadataName = "System.Collection.IDictionary`2"; } + public static class Dictionary + { + public const string MetadataName = "System.Collections.Generic.Dictionary`2"; + } + public static class IComponentRenderMode { public const string FullTypeName = "Microsoft.AspNetCore.Components.IComponentRenderMode"; diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/TagHelperDescriptorExtensions.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/TagHelperDescriptorExtensions.cs index 5161508e1b744..0e7ab01b550e8 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/TagHelperDescriptorExtensions.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Components/TagHelperDescriptorExtensions.cs @@ -30,6 +30,13 @@ public static bool IsGenericTypedComponent(this TagHelperDescriptor tagHelper) Metadata: ComponentMetadata { IsGeneric: true } }; + public static bool AcceptsUnmatchedAttributes(this TagHelperDescriptor tagHelper) + => tagHelper is + { + Kind: TagHelperKind.Component, + Metadata: ComponentMetadata { AcceptsUnmatchedAttributes: true } + }; + /// /// Given a taghelper binding it finds the BoundAttribute that is a type parameter and then the /// actual binding value for that type. diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/DefaultRazorIntermediateNodeLoweringPhase.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/DefaultRazorIntermediateNodeLoweringPhase.cs index 1ce9d53c1cc73..d26a461722bd4 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/DefaultRazorIntermediateNodeLoweringPhase.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/DefaultRazorIntermediateNodeLoweringPhase.cs @@ -1617,6 +1617,8 @@ private void VisitHtmlContent(SyntaxNode node) /// private class ComponentFileKindVisitor : LoweringVisitor { + private bool _isCurrentAttributeNameEscaped; + public ComponentFileKindVisitor( DocumentIntermediateNode document, IntermediateNodeBuilder builder, @@ -1696,8 +1698,11 @@ public override void VisitMarkupStartTag(MarkupStartTagSyntax node) // just process the attributes. // // Visit the attributes + var previousWasEscape = false; foreach (var block in node.Attributes) { + _isCurrentAttributeNameEscaped = previousWasEscape; + if (block is MarkupAttributeBlockSyntax attribute) { VisitMarkupAttributeBlock(attribute); @@ -1706,7 +1711,11 @@ public override void VisitMarkupStartTag(MarkupStartTagSyntax node) { VisitMarkupMinimizedAttributeBlock(minimized); } + + previousWasEscape = block is MarkupEphemeralTextLiteralSyntax; } + + _isCurrentAttributeNameEscaped = false; } public override void VisitMarkupEndTag(MarkupEndTagSyntax node) @@ -1736,6 +1745,7 @@ public override void VisitMarkupAttributeBlock(MarkupAttributeBlockSyntax node) { AttributeName = name, IsMinimized = false, + IsDirectiveAttributeCandidate = IsDirectiveAttributeCandidate(node.Name), Source = source, ValueContent = node.Value?.GetContent(), ValueSourceSpan = valueSourceSpan, @@ -1882,6 +1892,7 @@ public override void VisitMarkupMinimizedAttributeBlock(MarkupMinimizedAttribute { AttributeName = name, IsMinimized = true, + IsDirectiveAttributeCandidate = IsDirectiveAttributeCandidate(node.Name), Source = source, AttributeStructure = AttributeStructure.Minimized, AttributeNameSpan = BuildSourceSpanFromNode(node.Name), @@ -1894,6 +1905,14 @@ public override void VisitMarkupMinimizedAttributeBlock(MarkupMinimizedAttribute } } + private bool IsDirectiveAttributeCandidate(MarkupTextLiteralSyntax name) + { + var tokens = name.LiteralTokens; + return !_isCurrentAttributeNameEscaped && + tokens is [{ Kind: SyntaxKind.Transition }, ..] && + (tokens.Count == 1 || tokens[1].Kind != SyntaxKind.Transition); + } + // Example // // Prefix= (space) diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/DefaultTagHelperResolutionPhase.ComponentTagHelperResolver.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/DefaultTagHelperResolutionPhase.ComponentTagHelperResolver.cs index 9202c53ce16a2..36d54f6c8a4e1 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/DefaultTagHelperResolutionPhase.ComponentTagHelperResolver.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/DefaultTagHelperResolutionPhase.ComponentTagHelperResolver.cs @@ -59,6 +59,14 @@ public override void AddUnmatchedElementDiagnostic( convertedNode.AddDiagnostic( ComponentDiagnosticFactory.Create_UnexpectedMarkupElement(originalNode.TagName, originalNode.StartTagSpan ?? originalNode.Source)); } + + foreach (var child in originalNode.Children) + { + if (child is UnresolvedAttributeIntermediateNode unresolvedAttribute) + { + AddUnboundDirectiveAttributeDiagnostic(documentNode, unresolvedAttribute); + } + } } protected override void LowerComplexNonStringValues( @@ -171,6 +179,11 @@ private void ConvertUnresolvedAttributeToTagHelper( } else { + if (!hasMatches) + { + AddUnboundDirectiveAttributeDiagnostic(context.DocumentNode, unresolvedAttr); + } + ConvertToUnresolvedUnboundAttribute(tagHelperNode, unresolvedAttr, attributeName, isDuplicateBound); } } @@ -379,6 +392,8 @@ private static void ConvertToUnresolvedUnboundAttribute( { AttributeName = attributeName, AttributeStructure = unresolvedAttr.AttributeStructure, + AttributeNameSpan = unresolvedAttr.AttributeNameSpan, + IsDirectiveAttributeCandidate = unresolvedAttr.IsDirectiveAttributeCandidate, }; if (!unresolvedAttr.IsMinimized && unresolvedAttr.AsTagHelperAttribute is HtmlAttributeIntermediateNode fallbackAttr) @@ -928,6 +943,7 @@ private static void ConvertComponentAttributeToTagHelper( { AttributeName = attributeName, AttributeStructure = InferAttributeStructure(htmlAttr), + AttributeNameSpan = attributeNameSpan, }; thHtml.Children.AddRange(htmlAttr.Children); @@ -1162,6 +1178,19 @@ public override void ConvertToPlainElement(IntermediateNode parent, int index, U parent.Children[index] = markupElement; } + + private static void AddUnboundDirectiveAttributeDiagnostic( + DocumentIntermediateNode documentNode, + UnresolvedAttributeIntermediateNode attribute) + { + if (attribute.IsDirectiveAttributeCandidate) + { + documentNode.AddDiagnostic(ComponentDiagnosticFactory.Create_UnboundDirectiveAttribute( + attribute.AttributeNameSpan, + attribute.AttributeName)); + } + } + private static bool LooksLikeUnexpectedComponent(DocumentIntermediateNode? documentNode, string? tagName) { return documentNode != null && diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Intermediate/TagHelperHtmlAttributeIntermediateNode.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Intermediate/TagHelperHtmlAttributeIntermediateNode.cs index 0b72b22c21e67..bebdab5881353 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Intermediate/TagHelperHtmlAttributeIntermediateNode.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Intermediate/TagHelperHtmlAttributeIntermediateNode.cs @@ -7,6 +7,8 @@ public sealed class TagHelperHtmlAttributeIntermediateNode : IntermediateNode { public required string AttributeName { get; init; } public required AttributeStructure AttributeStructure { get; init; } + internal SourceSpan? AttributeNameSpan { get; init; } + internal bool IsDirectiveAttributeCandidate { get; init; } public override IntermediateNodeCollection Children { get => field ??= []; } diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Intermediate/UnresolvedAttributeIntermediateNode.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Intermediate/UnresolvedAttributeIntermediateNode.cs index 34a27e6fc400e..e0cda6d547568 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Intermediate/UnresolvedAttributeIntermediateNode.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/Intermediate/UnresolvedAttributeIntermediateNode.cs @@ -18,6 +18,12 @@ internal sealed class UnresolvedAttributeIntermediateNode : IntermediateNode /// Whether this is a minimized attribute (no value). public bool IsMinimized { get; set; } + /// + /// Whether the parser treated the leading @ as a Razor transition rather than an escaped + /// literal. Semantic resolution determines whether the candidate binds to a directive attribute. + /// + public bool IsDirectiveAttributeCandidate { get; set; } + /// The raw value content of the attribute (for all-literal values only). public string? ValueContent { get; set; } @@ -79,6 +85,7 @@ protected override IntermediateNode CloneNode() { AttributeName = AttributeName, IsMinimized = IsMinimized, + IsDirectiveAttributeCandidate = IsDirectiveAttributeCandidate, ValueContent = ValueContent, ValueSourceSpan = ValueSourceSpan, AttributeStructure = AttributeStructure, diff --git a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/TagHelpers/Producers/ComponentTagHelperProducer.cs b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/TagHelpers/Producers/ComponentTagHelperProducer.cs index d725039006214..b1f1a2d4bb7b7 100644 --- a/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/TagHelpers/Producers/ComponentTagHelperProducer.cs +++ b/src/Razor/src/Compiler/Microsoft.CodeAnalysis.Razor.Compiler/src/Language/TagHelpers/Producers/ComponentTagHelperProducer.cs @@ -21,11 +21,19 @@ internal sealed partial class ComponentTagHelperProducer : TagHelperProducer { private readonly Compilation _compilation; private readonly BindTagHelperProducer? _bindTagHelperProducer; + private readonly INamedTypeSymbol? _dictionaryOfStringObject; private ComponentTagHelperProducer(Compilation compilation, BindTagHelperProducer? bindTagHelperProducer) { _compilation = compilation; _bindTagHelperProducer = bindTagHelperProducer; + + if (compilation.GetTypeByMetadataName(ComponentsApi.Dictionary.MetadataName) is { } dictionaryType) + { + _dictionaryOfStringObject = dictionaryType.Construct( + compilation.GetSpecialType(SpecialType.System_String), + compilation.GetSpecialType(SpecialType.System_Object)); + } } public override TagHelperProducerKind Kind => TagHelperProducerKind.Component; @@ -47,15 +55,18 @@ public override void AddTagHelpersForType( // First, compute the relevant properties for this type so that we // don't need to compute them twice. var properties = GetProperties(type); + var acceptsUnmatchedAttributes = AcceptsUnmatchedAttributes(properties); - var shortNameMatchingDescriptor = CreateShortNameMatchingDescriptor(_compilation, type, properties); + var shortNameMatchingDescriptor = CreateShortNameMatchingDescriptor( + _compilation, type, properties, acceptsUnmatchedAttributes); results.Add(shortNameMatchingDescriptor); // If the component is in the global namespace, skip adding this descriptor which will be the same as the short name one. TagHelperDescriptor? fullyQualifiedNameMatchingDescriptor = null; if (!type.ContainingNamespace.IsGlobalNamespace) { - fullyQualifiedNameMatchingDescriptor = CreateFullyQualifiedNameMatchingDescriptor(_compilation, type, properties); + fullyQualifiedNameMatchingDescriptor = CreateFullyQualifiedNameMatchingDescriptor( + _compilation, type, properties, acceptsUnmatchedAttributes); results.Add(fullyQualifiedNameMatchingDescriptor); } @@ -84,19 +95,22 @@ public override void AddTagHelpersForType( private static TagHelperDescriptor CreateShortNameMatchingDescriptor( Compilation compilation, INamedTypeSymbol type, - ImmutableArray<(IPropertySymbol property, PropertyKind kind)> properties) - => CreateNameMatchingDescriptor(compilation, type, properties, fullyQualified: false); + ImmutableArray<(IPropertySymbol property, PropertyKind kind)> properties, + bool acceptsUnmatchedAttributes) + => CreateNameMatchingDescriptor(compilation, type, properties, acceptsUnmatchedAttributes, fullyQualified: false); private static TagHelperDescriptor CreateFullyQualifiedNameMatchingDescriptor( Compilation compilation, INamedTypeSymbol type, - ImmutableArray<(IPropertySymbol property, PropertyKind kind)> properties) - => CreateNameMatchingDescriptor(compilation, type, properties, fullyQualified: true); + ImmutableArray<(IPropertySymbol property, PropertyKind kind)> properties, + bool acceptsUnmatchedAttributes) + => CreateNameMatchingDescriptor(compilation, type, properties, acceptsUnmatchedAttributes, fullyQualified: true); private static TagHelperDescriptor CreateNameMatchingDescriptor( Compilation compilation, INamedTypeSymbol type, ImmutableArray<(IPropertySymbol property, PropertyKind kind)> properties, + bool acceptsUnmatchedAttributes, bool fullyQualified) { var typeName = TypeNameObject.From(type); @@ -109,6 +123,7 @@ private static TagHelperDescriptor CreateNameMatchingDescriptor( builder.SetTypeName(typeName); var metadata = new ComponentMetadata.Builder(); + metadata.AcceptsUnmatchedAttributes = acceptsUnmatchedAttributes; builder.CaseSensitive = true; @@ -193,6 +208,59 @@ private static TagHelperDescriptor CreateNameMatchingDescriptor( return builder.Build(); } + private bool AcceptsUnmatchedAttributes(ImmutableArray<(IPropertySymbol property, PropertyKind kind)> properties) + { + IPropertySymbol? captureUnmatchedValuesProperty = null; + + foreach (var (property, kind) in properties) + { + if (kind == PropertyKind.Ignored || !HasCaptureUnmatchedValues(property)) + { + continue; + } + + if (captureUnmatchedValuesProperty is not null) + { + // A component cannot have multiple parameters that capture unmatched values. + return false; + } + + captureUnmatchedValuesProperty = property; + } + + if (captureUnmatchedValuesProperty is null || _dictionaryOfStringObject is null) + { + return false; + } + + var conversion = _compilation.ClassifyConversion(_dictionaryOfStringObject, captureUnmatchedValuesProperty.Type); + + // The runtime assigns this dictionary through reflection, so user-defined conversions do not apply. + return conversion.IsIdentity || (conversion.IsImplicit && conversion.IsReference); + + static bool HasCaptureUnmatchedValues(IPropertySymbol property) + { + var parameterAttribute = property.GetAttributes().FirstOrDefault( + static attribute => attribute.HasFullName(ComponentsApi.ParameterAttribute.MetadataName)); + + if (parameterAttribute is null) + { + return false; + } + + foreach (var (name, value) in parameterAttribute.NamedArguments) + { + if (name == ComponentsApi.ParameterAttribute.CaptureUnmatchedValues && + value.Value is true) + { + return true; + } + } + + return false; + } + } + private static void CreateProperty(Compilation compilation, TagHelperDescriptorBuilder builder, INamedTypeSymbol containingSymbol, IPropertySymbol property, PropertyKind kind) { builder.BindAttribute(pb =>