Skip to content

Commit 10a0af7

Browse files
authored
Fix AOT-compatible generic property metadata getters (#7499) (#7524)
1 parent 85dda7c commit 10a0af7

13 files changed

Lines changed: 316 additions & 9 deletions

‎src/TUnit.Core.SourceGenerator/Utilities/MetadataGenerationHelper.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ public static void WritePropertyMetadata(ICodeWriter writer, IPropertySymbol pro
347347
private static string GetPropertyAccessor(INamedTypeSymbol namedTypeSymbol, IPropertySymbol property)
348348
{
349349
// For generic types with unresolved type parameters, we can't cast to the open generic type
350-
// We need to use dynamic or reflection
350+
// Resolve the closed declaring type from each instance and cache its reflected property.
351351
var hasUnresolvedTypeParameters = namedTypeSymbol.IsGenericType &&
352352
(namedTypeSymbol.TypeArguments.Any(t => t.TypeKind == TypeKind.TypeParameter) ||
353353
namedTypeSymbol.TypeArguments.OfType<ITypeParameterSymbol>().Any() ||
@@ -359,8 +359,8 @@ private static string GetPropertyAccessor(INamedTypeSymbol namedTypeSymbol, IPro
359359
// Can't access static members on an unbound generic type like WebApplicationTest<,>
360360
// Use reflection to get the value at runtime
361361
? $"_ => typeof({namedTypeSymbol.GloballyQualified()}).GetProperty(\"{property.Name}\")?.GetValue(null)"
362-
// Use dynamic to avoid invalid cast to open generic type
363-
: $"o => ((dynamic)o).{IdentifierHelper.Escape(property.Name)}";
362+
// The factory roots public properties and caches reflection for each runtime type.
363+
: $"global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof({namedTypeSymbol.GloballyQualified()}), \"{property.Name}\")";
364364
}
365365

366366
var safeTypeName = namedTypeSymbol.GloballyQualified();
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
using System.Collections.Concurrent;
2+
using System.ComponentModel;
3+
using System.Diagnostics.CodeAnalysis;
4+
using System.Reflection;
5+
6+
namespace TUnit.Core;
7+
8+
/// <summary>
9+
/// Creates property accessors for source-generated metadata.
10+
/// </summary>
11+
[EditorBrowsable(EditorBrowsableState.Never)]
12+
public static class PropertyMetadataFactory
13+
{
14+
/// <summary>
15+
/// Creates a cached reflection getter for an instance property on an open generic declaring type.
16+
/// Each closed declaring type is resolved from the instance without runtime code generation.
17+
/// </summary>
18+
public static Func<object?, object?> CreateGenericGetter(
19+
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type declaringType,
20+
string propertyName)
21+
{
22+
var properties = new ConcurrentDictionary<Type, PropertyInfo>();
23+
Func<Type, PropertyInfo> resolveProperty = ResolveProperty;
24+
return instance =>
25+
{
26+
if (instance is null)
27+
{
28+
throw new ArgumentNullException(nameof(instance));
29+
}
30+
var property = properties.GetOrAdd(instance.GetType(), resolveProperty);
31+
return property.GetValue(instance);
32+
};
33+
34+
[UnconditionalSuppressMessage("Trimming", "IL2070",
35+
Justification = "The matching closed type is an instantiation of declaringType, whose public properties are preserved by the annotated parameter.")]
36+
[UnconditionalSuppressMessage("Trimming", "IL2075",
37+
Justification = "Base types are only inspected until the preserved generic declaring type is found; no properties on other types are accessed.")]
38+
PropertyInfo ResolveProperty(Type instanceType)
39+
{
40+
for (var type = instanceType; type != null; type = type.BaseType)
41+
{
42+
if (type.IsGenericType && type.GetGenericTypeDefinition() == declaringType)
43+
{
44+
return type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
45+
?? throw new MissingMemberException(type.FullName, propertyName);
46+
}
47+
}
48+
49+
throw new ArgumentException($"Type '{instanceType}' does not inherit from '{declaringType}'.", "instance");
50+
}
51+
}
52+
}

‎tests/TUnit.Core.SourceGenerator.Tests/GenericMethodWithDataSourceTests.Generic_Method_With_MethodDataSource_Should_Generate_Tests.verified.txt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,7 +1128,7 @@ internal static class TUnit_TestProject_Bugs__4431_GenericClassWithClassDataSour
11281128
Name = "DataSource",
11291129
IsStatic = false,
11301130
IsNullable = false,
1131-
Getter = o => ((dynamic)o).DataSource,
1131+
Getter = global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof(global::TUnit.TestProject.Bugs._4431.GenericClassWithClassDataSource<>), "DataSource"),
11321132
ClassMetadata = null!,
11331133
ContainingTypeMetadata = null!
11341134
}
@@ -1254,7 +1254,7 @@ internal static class TUnit_TestProject_Bugs__4431_GenericClassGenericMethodWith
12541254
Name = "DataSource",
12551255
IsStatic = false,
12561256
IsNullable = false,
1257-
Getter = o => ((dynamic)o).DataSource,
1257+
Getter = global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof(global::TUnit.TestProject.Bugs._4431.GenericClassGenericMethodWithDataSources<>), "DataSource"),
12581258
ClassMetadata = null!,
12591259
ContainingTypeMetadata = null!
12601260
}
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
// <auto-generated/>
2+
#pragma warning disable
3+
4+
#nullable enable
5+
namespace TUnit.Generated;
6+
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]
7+
[global::System.CodeDom.Compiler.GeneratedCode("TUnit", "VERSION_SCRUBBED")]
8+
internal static class TUnit_TestProject_Bugs__7499_GenericPropertyMetadataTests_T_MetadataGettersReadClosedInstance_TestSource
9+
{
10+
private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>", new global::TUnit.Core.ClassMetadata
11+
{
12+
Type = typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>),
13+
TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]),
14+
Name = "GenericPropertyMetadataTests",
15+
Namespace = "TUnit.TestProject.Bugs._7499",
16+
Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"),
17+
Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>), true, new global::TUnit.Core.ParameterMetadata[]
18+
{
19+
global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false)
20+
}),
21+
Properties = new global::TUnit.Core.PropertyMetadata[]
22+
{
23+
new global::TUnit.Core.PropertyMetadata
24+
{
25+
ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>).GetProperty("Value"),
26+
Type = typeof(object),
27+
Name = "Value",
28+
IsStatic = false,
29+
IsNullable = false,
30+
Getter = global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>), "Value"),
31+
ClassMetadata = null!,
32+
ContainingTypeMetadata = null!
33+
},
34+
new global::TUnit.Core.PropertyMetadata
35+
{
36+
ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>).GetProperty("Label", typeof(string)),
37+
Type = typeof(string),
38+
Name = "Label",
39+
IsStatic = false,
40+
IsNullable = false,
41+
Getter = global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>), "Label"),
42+
ClassMetadata = null!,
43+
ContainingTypeMetadata = null!
44+
},
45+
new global::TUnit.Core.PropertyMetadata
46+
{
47+
ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>).GetProperty("Optional"),
48+
Type = typeof(object),
49+
Name = "Optional",
50+
IsStatic = false,
51+
IsNullable = true,
52+
Getter = global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>), "Optional"),
53+
ClassMetadata = null!,
54+
ContainingTypeMetadata = null!
55+
}
56+
},
57+
Parent = null
58+
});
59+
private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<>);
60+
private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("MetadataGettersReadClosedInstance", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata);
61+
private static global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<string> __CreateInstance_0(global::System.Type[] typeArgs, object?[] args)
62+
{
63+
return (global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<string>)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<string>), args)!;
64+
}
65+
private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<string> instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken)
66+
{
67+
try
68+
{
69+
return new global::System.Threading.Tasks.ValueTask(instance.MetadataGettersReadClosedInstance());
70+
}
71+
catch (global::System.Exception ex)
72+
{
73+
return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex));
74+
}
75+
}
76+
private static global::System.Attribute[] __Attributes_0(int groupIndex)
77+
{
78+
return new global::System.Attribute[]
79+
{
80+
new global::TUnit.Core.TestAttribute(),
81+
new global::TUnit.Core.ArgumentsAttribute("first"),
82+
new global::TUnit.Core.ArgumentsAttribute("second"),
83+
new global::TUnit.Core.ArgumentsAttribute(42),
84+
new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass)
85+
};
86+
}
87+
public static readonly global::TUnit.Core.TestEntry<global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<string>>[] Entries_0 = new global::TUnit.Core.TestEntry<global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<string>>[]
88+
{
89+
global::TUnit.Core.TestEntryFactory.Create<global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<string>>(
90+
methodName: "MetadataGettersReadClosedInstance",
91+
fullyQualifiedName: "TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<string>.MetadataGettersReadClosedInstance",
92+
filePath: "",
93+
lineNumber: 15,
94+
hasDataSource: true,
95+
classDataSources: new global::TUnit.Core.IDataSourceAttribute[]
96+
{
97+
new global::TUnit.Core.ArgumentsAttribute("first"),
98+
new global::TUnit.Core.ArgumentsAttribute("second"),
99+
},
100+
methodMetadata: __mm_0,
101+
createInstance: __CreateInstance_0,
102+
invokeBody: __Invoke_0,
103+
methodIndex: 0,
104+
createAttributes: __Attributes_0,
105+
attributeGroupIndex: 0),
106+
};
107+
private static global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<int> __CreateInstance_1(global::System.Type[] typeArgs, object?[] args)
108+
{
109+
return (global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<int>)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<int>), new object[] { 42 })!;
110+
}
111+
private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<int> instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken)
112+
{
113+
try
114+
{
115+
return new global::System.Threading.Tasks.ValueTask(instance.MetadataGettersReadClosedInstance());
116+
}
117+
catch (global::System.Exception ex)
118+
{
119+
return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex));
120+
}
121+
}
122+
private static global::System.Attribute[] __Attributes_1(int groupIndex)
123+
{
124+
return new global::System.Attribute[]
125+
{
126+
new global::TUnit.Core.TestAttribute(),
127+
new global::TUnit.Core.ArgumentsAttribute("first"),
128+
new global::TUnit.Core.ArgumentsAttribute("second"),
129+
new global::TUnit.Core.ArgumentsAttribute(42),
130+
new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass)
131+
};
132+
}
133+
public static readonly global::TUnit.Core.TestEntry<global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<int>>[] Entries_1 = new global::TUnit.Core.TestEntry<global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<int>>[]
134+
{
135+
global::TUnit.Core.TestEntryFactory.Create<global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<int>>(
136+
methodName: "MetadataGettersReadClosedInstance",
137+
fullyQualifiedName: "TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<int>.MetadataGettersReadClosedInstance",
138+
filePath: "",
139+
lineNumber: 15,
140+
hasDataSource: true,
141+
classDataSources: new global::TUnit.Core.IDataSourceAttribute[]
142+
{
143+
new global::TUnit.Core.ArgumentsAttribute(42),
144+
},
145+
methodMetadata: __mm_0,
146+
createInstance: __CreateInstance_1,
147+
invokeBody: __Invoke_1,
148+
methodIndex: 0,
149+
createAttributes: __Attributes_1,
150+
attributeGroupIndex: 0),
151+
};
152+
}
153+
internal static partial class TUnit_TestRegistration
154+
{
155+
static readonly int _r_TUnit_TestProject_Bugs__7499_GenericPropertyMetadataTests_T_MetadataGettersReadClosedInstance_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries<global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<string>>(static () => TUnit_TestProject_Bugs__7499_GenericPropertyMetadataTests_T_MetadataGettersReadClosedInstance_TestSource.Entries_0);
156+
}
157+
internal static partial class TUnit_TestRegistration
158+
{
159+
static readonly int _r_TUnit_TestProject_Bugs__7499_GenericPropertyMetadataTests_T_MetadataGettersReadClosedInstance_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries<global::TUnit.TestProject.Bugs._7499.GenericPropertyMetadataTests<int>>(static () => TUnit_TestProject_Bugs__7499_GenericPropertyMetadataTests_T_MetadataGettersReadClosedInstance_TestSource.Entries_1);
160+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
namespace TUnit.Core.SourceGenerator.Tests;
2+
3+
internal class GenericPropertyMetadataTests : TestsBase
4+
{
5+
[Test]
6+
public Task GeneratesCachedAotCompatibleGetters() => RunTest(
7+
Path.Combine(Git.TestsDirectory.FullName, "TUnit.TestProject", "Bugs", "_7499", "GenericPropertyMetadataTests.cs"),
8+
async files =>
9+
{
10+
var output = string.Join("\n", files);
11+
await Assert.That(output).DoesNotContain("((dynamic)o)");
12+
await Assert.That(output).Contains("PropertyMetadataFactory.CreateGenericGetter");
13+
});
14+
}

‎tests/TUnit.Core.SourceGenerator.Tests/Tests7107.Test.verified.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -900,7 +900,7 @@ internal static class TUnit_TestProject_Bugs__7107_ClassAndMethodRowsConstraintT
900900
Name = "Value",
901901
IsStatic = false,
902902
IsNullable = false,
903-
Getter = o => ((dynamic)o).Value,
903+
Getter = global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof(global::TUnit.TestProject.Bugs._7107.ClassAndMethodRowsConstraintTests<>), "Value"),
904904
ClassMetadata = null!,
905905
ContainingTypeMetadata = null!
906906
}

‎tests/TUnit.Core.SourceGenerator.Tests/Tests7222.Test.verified.txt‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -784,7 +784,7 @@ internal static class TUnit_TestProject_Bugs__7222_ClassRowsGenerateGenericTestA
784784
Name = "Value",
785785
IsStatic = false,
786786
IsNullable = false,
787-
Getter = o => ((dynamic)o).Value,
787+
Getter = global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof(global::TUnit.TestProject.Bugs._7222.ClassRowsGenerateGenericTestArityTests<>), "Value"),
788788
ClassMetadata = null!,
789789
ContainingTypeMetadata = null!
790790
}
@@ -1181,7 +1181,7 @@ internal static class TUnit_TestProject_Bugs__7222_BroadSourceOnGenericClassRowT
11811181
Name = "Value",
11821182
IsStatic = false,
11831183
IsNullable = false,
1184-
Getter = o => ((dynamic)o).Value,
1184+
Getter = global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof(global::TUnit.TestProject.Bugs._7222.BroadSourceOnGenericClassRowTests<>), "Value"),
11851185
ClassMetadata = null!,
11861186
ContainingTypeMetadata = null!
11871187
}
@@ -1339,7 +1339,7 @@ internal static class TUnit_TestProject_Bugs__7222_BroadSourceJoinsClassRowTests
13391339
Name = "Value",
13401340
IsStatic = false,
13411341
IsNullable = false,
1342-
Getter = o => ((dynamic)o).Value,
1342+
Getter = global::TUnit.Core.PropertyMetadataFactory.CreateGenericGetter(typeof(global::TUnit.TestProject.Bugs._7222.BroadSourceJoinsClassRowTests<>), "Value"),
13431343
ClassMetadata = null!,
13441344
ContainingTypeMetadata = null!
13451345
}

‎tests/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet10_0.verified.txt‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1241,6 +1241,10 @@ namespace
12411241
[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicProperties)]
12421242
public required Type { get; init; }
12431243
}
1244+
public static class PropertyMetadataFactory
1245+
{
1246+
public static <object?, object?> CreateGenericGetter([.(..PublicProperties)] declaringType, string propertyName) { }
1247+
}
12441248
public static class PropertySourceRegistry
12451249
{
12461250
[.("Reflection discovery is used when source-generated metadata is not available")]

‎tests/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet8_0.verified.txt‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1241,6 +1241,10 @@ namespace
12411241
[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicProperties)]
12421242
public required Type { get; init; }
12431243
}
1244+
public static class PropertyMetadataFactory
1245+
{
1246+
public static <object?, object?> CreateGenericGetter([.(..PublicProperties)] declaringType, string propertyName) { }
1247+
}
12441248
public static class PropertySourceRegistry
12451249
{
12461250
[.("Reflection discovery is used when source-generated metadata is not available")]

‎tests/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet9_0.verified.txt‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1241,6 +1241,10 @@ namespace
12411241
[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicProperties)]
12421242
public required Type { get; init; }
12431243
}
1244+
public static class PropertyMetadataFactory
1245+
{
1246+
public static <object?, object?> CreateGenericGetter([.(..PublicProperties)] declaringType, string propertyName) { }
1247+
}
12441248
public static class PropertySourceRegistry
12451249
{
12461250
[.("Reflection discovery is used when source-generated metadata is not available")]

0 commit comments

Comments
 (0)