Skip to content
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -251,4 +252,266 @@ 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 = """<MyComponent TValue="string" Unknown="value" />""";

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()
Comment thread
davidwengier marked this conversation as resolved.
Resolved
{
AddGenericComponentWithKnownParameter();

const string content = """<MyComponent TValue="string" Unknown="value" />""";

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_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(
"""
<MyComponent Known="first" />
<MyComponent known="second" />
""",
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<TValue> : ComponentBase
{
[Parameter] public TValue Known { get; set; }

[Parameter(CaptureUnmatchedValues = true)]
public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; }
}

public class MyComponent : ComponentBaseWithAdditionalAttributes<string>
{
}
"""));

var generated = CompileToCSharp(
"""<MyComponent Known="value" Unknown="value" />""",
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<string, object> AdditionalAttributes { get; set; }
}

public class WrongType : ComponentBase
{
[Parameter(CaptureUnmatchedValues = true)]
public string AdditionalAttributes { get; set; }
}

public class DuplicateCapture : ComponentBase
{
[Parameter(CaptureUnmatchedValues = true)]
public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; }

[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object> OtherAttributes { get; set; }
}

public class UserDefinedConversionCapture : ComponentBase
{
[Parameter(CaptureUnmatchedValues = true)]
public AttributeCollection AdditionalAttributes { get; set; }
}

public class AttributeCollection
{
public static implicit operator AttributeCollection(Dictionary<string, object> attributes)
=> new();
}
"""));

var generated = CompileToCSharp(
"""
<CaptureDisabled Unknown="value" />
<WrongType Unknown="value" />
<DuplicateCapture Unknown="value" />
<UserDefinedConversionCapture Unknown="value" />
""",
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

<div class="value" data-unknown="value"></div>
<MyComponent @attributes="new Dictionary<string, object>()" @key="this" @ref="_component" />

@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

<MyComponent @attributes="new Dictionary<string, object>()" Unknown="value" />
""",
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<TValue> : 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);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -442,4 +442,13 @@ 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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,16 @@ private bool TryGetAttributeStringContent(TagHelperPropertyIntermediateNode prop
public override void VisitTagHelperHtmlAttribute(TagHelperHtmlAttributeIntermediateNode node)
{
var attribute = new ComponentAttributeIntermediateNode(node);

// A splat cannot make an explicitly unmatched attribute valid.
Comment thread
davidwengier marked this conversation as resolved.
Resolved
if (!_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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,29 @@ 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);

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
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
};

/// <summary>
/// Given a taghelper binding it finds the BoundAttribute that is a type parameter and then the
/// actual binding value for that type.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ private static void ConvertToUnresolvedUnboundAttribute(
{
AttributeName = attributeName,
AttributeStructure = unresolvedAttr.AttributeStructure,
AttributeNameSpan = unresolvedAttr.AttributeNameSpan,
};

if (!unresolvedAttr.IsMinimized && unresolvedAttr.AsTagHelperAttribute is HtmlAttributeIntermediateNode fallbackAttr)
Expand Down Expand Up @@ -928,6 +929,7 @@ private static void ConvertComponentAttributeToTagHelper(
{
AttributeName = attributeName,
AttributeStructure = InferAttributeStructure(htmlAttr),
AttributeNameSpan = attributeNameSpan,
};

thHtml.Children.AddRange(htmlAttr.Children);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ public sealed class TagHelperHtmlAttributeIntermediateNode : IntermediateNode
{
public required string AttributeName { get; init; }
public required AttributeStructure AttributeStructure { get; init; }
internal SourceSpan? AttributeNameSpan { get; init; }

public override IntermediateNodeCollection Children { get => field ??= []; }

Expand Down
Loading