Skip to content

Commit 6f9b7b8

Browse files
Copilotcaptainsafia
andcommitted
Fix handling of implicitly declared EqualityContract on record types in validation generator
Co-authored-by: captainsafia <[email protected]>
1 parent bb982de commit 6f9b7b8

File tree

3 files changed

+195
-1
lines changed

3 files changed

+195
-1
lines changed

src/Validation/gen/Parsers/ValidationsGenerator.TypesParser.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,11 @@ internal bool TryExtractValidatableType(ITypeSymbol incomingTypeSymbol, WellKnow
105105
return true;
106106
}
107107

108+
private static bool IsEqualityContract(IPropertySymbol prop) =>
109+
prop.Name == "EqualityContract"
110+
&& prop.Type.ToDisplayString() == "System.Type"
111+
&& prop.DeclaredAccessibility == Accessibility.Protected;
112+
108113
internal ImmutableArray<ValidatableProperty> ExtractValidatableMembers(ITypeSymbol typeSymbol, WellKnownTypes wellKnownTypes, ref HashSet<ValidatableType> validatableTypes, ref List<ITypeSymbol> visitedTypes)
109114
{
110115
var members = new List<ValidatableProperty>();
@@ -162,7 +167,9 @@ internal ImmutableArray<ValidatableProperty> ExtractValidatableMembers(ITypeSymb
162167
{
163168
// Skip compiler generated properties and properties already processed via
164169
// the record processing logic above.
165-
if (member.IsImplicitlyDeclared || resolvedRecordProperty.Contains(member, SymbolEqualityComparer.Default))
170+
if (member.IsImplicitlyDeclared
171+
|| IsEqualityContract(member)
172+
|| resolvedRecordProperty.Contains(member, SymbolEqualityComparer.Default))
166173
{
167174
continue;
168175
}

src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/ValidationsGenerator.RecordType.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,4 +370,31 @@ async Task ValidInputProducesNoWarnings(Endpoint endpoint)
370370
});
371371

372372
}
373+
374+
[Fact]
375+
public async Task RecordTypes_DoNotIncludeEqualityContractProperty()
376+
{
377+
// Arrange
378+
var source = """
379+
using System;
380+
using System.ComponentModel.DataAnnotations;
381+
using Microsoft.AspNetCore.Builder;
382+
using Microsoft.AspNetCore.Http;
383+
using Microsoft.Extensions.Validation;
384+
using Microsoft.Extensions.DependencyInjection;
385+
386+
var builder = WebApplication.CreateBuilder();
387+
builder.Services.AddValidation();
388+
var app = builder.Build();
389+
390+
app.MapPost("/test-record", (TestRecord record) => Results.Ok("Passed"));
391+
392+
app.Run();
393+
394+
public record TestRecord([Required] string Name);
395+
""";
396+
397+
// Act & Assert - Verify the generated code doesn't include EqualityContract
398+
await Verify(source, out var compilation);
399+
}
373400
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
//HintName: ValidatableInfoResolver.g.cs
2+
#nullable enable annotations
3+
//------------------------------------------------------------------------------
4+
// <auto-generated>
5+
// This code was generated by a tool.
6+
//
7+
// Changes to this file may cause incorrect behavior and will be lost if
8+
// the code is regenerated.
9+
// </auto-generated>
10+
//------------------------------------------------------------------------------
11+
#nullable enable
12+
#pragma warning disable ASP0029
13+
14+
namespace System.Runtime.CompilerServices
15+
{
16+
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Validation.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")]
17+
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
18+
file sealed class InterceptsLocationAttribute : System.Attribute
19+
{
20+
public InterceptsLocationAttribute(int version, string data)
21+
{
22+
}
23+
}
24+
}
25+
26+
namespace Microsoft.Extensions.Validation.Generated
27+
{
28+
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Validation.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")]
29+
file sealed class GeneratedValidatablePropertyInfo : global::Microsoft.Extensions.Validation.ValidatablePropertyInfo
30+
{
31+
public GeneratedValidatablePropertyInfo(
32+
[param: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)]
33+
global::System.Type containingType,
34+
global::System.Type propertyType,
35+
string name,
36+
string displayName) : base(containingType, propertyType, name, displayName)
37+
{
38+
ContainingType = containingType;
39+
Name = name;
40+
}
41+
42+
[global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)]
43+
internal global::System.Type ContainingType { get; }
44+
internal string Name { get; }
45+
46+
protected override global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes()
47+
=> ValidationAttributeCache.GetValidationAttributes(ContainingType, Name);
48+
}
49+
50+
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Validation.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")]
51+
file sealed class GeneratedValidatableTypeInfo : global::Microsoft.Extensions.Validation.ValidatableTypeInfo
52+
{
53+
public GeneratedValidatableTypeInfo(
54+
[param: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.Interfaces)]
55+
global::System.Type type,
56+
ValidatablePropertyInfo[] members) : base(type, members) { }
57+
}
58+
59+
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Validation.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")]
60+
file class GeneratedValidatableInfoResolver : global::Microsoft.Extensions.Validation.IValidatableInfoResolver
61+
{
62+
public bool TryGetValidatableTypeInfo(global::System.Type type, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out global::Microsoft.Extensions.Validation.IValidatableInfo? validatableInfo)
63+
{
64+
validatableInfo = null;
65+
if (type == typeof(global::TestRecord))
66+
{
67+
validatableInfo = new GeneratedValidatableTypeInfo(
68+
type: typeof(global::TestRecord),
69+
members: [
70+
new GeneratedValidatablePropertyInfo(
71+
containingType: typeof(global::TestRecord),
72+
propertyType: typeof(string),
73+
name: "Name",
74+
displayName: "Name"
75+
),
76+
]
77+
);
78+
return true;
79+
}
80+
81+
return false;
82+
}
83+
84+
// No-ops, rely on runtime code for ParameterInfo-based resolution
85+
public bool TryGetValidatableParameterInfo(global::System.Reflection.ParameterInfo parameterInfo, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out global::Microsoft.Extensions.Validation.IValidatableInfo? validatableInfo)
86+
{
87+
validatableInfo = null;
88+
return false;
89+
}
90+
}
91+
92+
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Validation.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")]
93+
file static class GeneratedServiceCollectionExtensions
94+
{
95+
[InterceptsLocation]
96+
public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddValidation(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services, global::System.Action<global::Microsoft.Extensions.Validation.ValidationOptions>? configureOptions = null)
97+
{
98+
// Use non-extension method to avoid infinite recursion.
99+
return global::Microsoft.Extensions.DependencyInjection.ValidationServiceCollectionExtensions.AddValidation(services, options =>
100+
{
101+
options.Resolvers.Insert(0, new GeneratedValidatableInfoResolver());
102+
if (configureOptions is not null)
103+
{
104+
configureOptions(options);
105+
}
106+
});
107+
}
108+
}
109+
110+
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Validation.ValidationsGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")]
111+
file static class ValidationAttributeCache
112+
{
113+
private sealed record CacheKey([property: global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] global::System.Type ContainingType, string PropertyName);
114+
private static readonly global::System.Collections.Concurrent.ConcurrentDictionary<CacheKey, global::System.ComponentModel.DataAnnotations.ValidationAttribute[]> _cache = new();
115+
116+
public static global::System.ComponentModel.DataAnnotations.ValidationAttribute[] GetValidationAttributes(
117+
[global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)]
118+
global::System.Type containingType,
119+
string propertyName)
120+
{
121+
var key = new CacheKey(containingType, propertyName);
122+
return _cache.GetOrAdd(key, static k =>
123+
{
124+
var results = new global::System.Collections.Generic.List<global::System.ComponentModel.DataAnnotations.ValidationAttribute>();
125+
126+
// Get attributes from the property
127+
var property = k.ContainingType.GetProperty(k.PropertyName);
128+
if (property != null)
129+
{
130+
var propertyAttributes = global::System.Reflection.CustomAttributeExtensions
131+
.GetCustomAttributes<global::System.ComponentModel.DataAnnotations.ValidationAttribute>(property, inherit: true);
132+
133+
results.AddRange(propertyAttributes);
134+
}
135+
136+
// Check constructors for parameters that match the property name
137+
// to handle record scenarios
138+
foreach (var constructor in k.ContainingType.GetConstructors())
139+
{
140+
// Look for parameter with matching name (case insensitive)
141+
var parameter = global::System.Linq.Enumerable.FirstOrDefault(
142+
constructor.GetParameters(),
143+
p => string.Equals(p.Name, k.PropertyName, global::System.StringComparison.OrdinalIgnoreCase));
144+
145+
if (parameter != null)
146+
{
147+
var paramAttributes = global::System.Reflection.CustomAttributeExtensions
148+
.GetCustomAttributes<global::System.ComponentModel.DataAnnotations.ValidationAttribute>(parameter, inherit: true);
149+
150+
results.AddRange(paramAttributes);
151+
152+
break;
153+
}
154+
}
155+
156+
return results.ToArray();
157+
});
158+
}
159+
}
160+
}

0 commit comments

Comments
 (0)