From b132ad25b75e54f8836f71e0282ee305cf6f508c Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Fri, 19 Jun 2026 20:42:45 +0100 Subject: [PATCH 1/7] perf(sourcegen): consolidate per-file ModuleInitializers into merged .cctor (#6226) Several generators emitted a separate [ModuleInitializer] per file/class, each costing a type load + serial tier-0 JIT at module load. Fold them into the existing consolidated-.cctor pattern: per-file static field initializers on shared partial shells declared by InfrastructureGenerator, triggered once via RunClassConstructor. - InfrastructureGenerator declares + triggers 4 new shells in TUnit.Generated: TUnit_PropertyRegistration, TUnit_ConverterRegistration, TUnit_StaticPropertyRegistration, TUnit_DynamicTestRegistration. - PropertyInjection (4 sites), AotConverter, StaticProperty and DynamicTests now contribute `static readonly int _r_X = Registry.Register(...)` fields instead of per-file [ModuleInitializer] methods. - 5 registry Register/RegisterDynamic methods return int (dummy 0) so they can be used as field initializers (matches existing RegisterEntries/RegisterHook). Registrations are emitted eager-inline with no factory lambdas: a factory lambda would add one compiler-generated method (a new JIT call) per type. The test/hook generators are unchanged - they already consolidate into a merged .cctor and deliberately keep a lazy `() => Source.Entries` factory to defer heavy, parallelizable metadata construction to discovery. Free aggregation via the compiler's partial-class merge - no .Collect() fan-in added to the incremental pipeline. Reflection mode is unaffected: registry consumer methods are unchanged and reflection never calls Register. --- ...rGeneratorTests.GeneratesCode.verified.txt | 146 +++++++++--------- ...mpilesSuccessfully.DotNet10_0.verified.txt | 12 ++ ...ompilesSuccessfully.DotNet8_0.verified.txt | 12 ++ ...ompilesSuccessfully.DotNet9_0.verified.txt | 12 ++ ...s_CompilesSuccessfully.Net4_7.verified.txt | 12 ++ .../CodeGenerators/DynamicTestsGenerator.cs | 64 ++++---- .../CodeGenerators/InfrastructureGenerator.cs | 22 ++- .../StaticPropertyInitializationGenerator.cs | 70 ++++++--- .../Generators/AotConverterGenerator.cs | 22 +-- .../PropertyInjectionSourceGenerator.cs | 94 +++++------ TUnit.Core/Converters/AotConverterRegistry.cs | 8 +- .../Discovery/InitializerPropertyRegistry.cs | 8 +- TUnit.Core/PropertySourceRegistry.cs | 8 +- TUnit.Core/SourceRegistrar.cs | 7 +- .../StaticPropertyRegistry.cs | 8 +- ...Has_No_API_Changes.DotNet10_0.verified.txt | 10 +- ..._Has_No_API_Changes.DotNet8_0.verified.txt | 10 +- ..._Has_No_API_Changes.DotNet9_0.verified.txt | 10 +- ...ary_Has_No_API_Changes.Net4_7.verified.txt | 10 +- 19 files changed, 321 insertions(+), 224 deletions(-) diff --git a/TUnit.Core.SourceGenerator.Tests/AotConverterGeneratorTests.GeneratesCode.verified.txt b/TUnit.Core.SourceGenerator.Tests/AotConverterGeneratorTests.GeneratesCode.verified.txt index 16ab7c3f351..a09623f365a 100644 --- a/TUnit.Core.SourceGenerator.Tests/AotConverterGeneratorTests.GeneratesCode.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AotConverterGeneratorTests.GeneratesCode.verified.txt @@ -1297,80 +1297,74 @@ internal sealed class AotConverter_67 : IAotConverter return value; // Return original value if type doesn't match } } -internal static class AotConverterRegistration -{ - [global::System.Runtime.CompilerServices.ModuleInitializer] - [global::System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA2255:The 'ModuleInitializer' attribute should not be used in libraries", - Justification = "Test framework needs to register AOT converters for conversion operators")] - public static void Initialize() - { - AotConverterRegistry.Register(new AotConverter_0()); - AotConverterRegistry.Register(new AotConverter_1()); - AotConverterRegistry.Register(new AotConverter_2()); - AotConverterRegistry.Register(new AotConverter_3()); - AotConverterRegistry.Register(new AotConverter_4()); - AotConverterRegistry.Register(new AotConverter_5()); - AotConverterRegistry.Register(new AotConverter_6()); - AotConverterRegistry.Register(new AotConverter_7()); - AotConverterRegistry.Register(new AotConverter_8()); - AotConverterRegistry.Register(new AotConverter_9()); - AotConverterRegistry.Register(new AotConverter_10()); - AotConverterRegistry.Register(new AotConverter_11()); - AotConverterRegistry.Register(new AotConverter_12()); - AotConverterRegistry.Register(new AotConverter_13()); - AotConverterRegistry.Register(new AotConverter_14()); - AotConverterRegistry.Register(new AotConverter_15()); - AotConverterRegistry.Register(new AotConverter_16()); - AotConverterRegistry.Register(new AotConverter_17()); - AotConverterRegistry.Register(new AotConverter_18()); - AotConverterRegistry.Register(new AotConverter_19()); - AotConverterRegistry.Register(new AotConverter_20()); - AotConverterRegistry.Register(new AotConverter_21()); - AotConverterRegistry.Register(new AotConverter_22()); - AotConverterRegistry.Register(new AotConverter_23()); - AotConverterRegistry.Register(new AotConverter_24()); - AotConverterRegistry.Register(new AotConverter_25()); - AotConverterRegistry.Register(new AotConverter_26()); - AotConverterRegistry.Register(new AotConverter_27()); - AotConverterRegistry.Register(new AotConverter_28()); - AotConverterRegistry.Register(new AotConverter_29()); - AotConverterRegistry.Register(new AotConverter_30()); - AotConverterRegistry.Register(new AotConverter_31()); - AotConverterRegistry.Register(new AotConverter_32()); - AotConverterRegistry.Register(new AotConverter_33()); - AotConverterRegistry.Register(new AotConverter_34()); - AotConverterRegistry.Register(new AotConverter_35()); - AotConverterRegistry.Register(new AotConverter_36()); - AotConverterRegistry.Register(new AotConverter_37()); - AotConverterRegistry.Register(new AotConverter_38()); - AotConverterRegistry.Register(new AotConverter_39()); - AotConverterRegistry.Register(new AotConverter_40()); - AotConverterRegistry.Register(new AotConverter_41()); - AotConverterRegistry.Register(new AotConverter_42()); - AotConverterRegistry.Register(new AotConverter_43()); - AotConverterRegistry.Register(new AotConverter_44()); - AotConverterRegistry.Register(new AotConverter_45()); - AotConverterRegistry.Register(new AotConverter_46()); - AotConverterRegistry.Register(new AotConverter_47()); - AotConverterRegistry.Register(new AotConverter_48()); - AotConverterRegistry.Register(new AotConverter_49()); - AotConverterRegistry.Register(new AotConverter_50()); - AotConverterRegistry.Register(new AotConverter_51()); - AotConverterRegistry.Register(new AotConverter_52()); - AotConverterRegistry.Register(new AotConverter_53()); - AotConverterRegistry.Register(new AotConverter_54()); - AotConverterRegistry.Register(new AotConverter_55()); - AotConverterRegistry.Register(new AotConverter_56()); - AotConverterRegistry.Register(new AotConverter_57()); - AotConverterRegistry.Register(new AotConverter_58()); - AotConverterRegistry.Register(new AotConverter_59()); - AotConverterRegistry.Register(new AotConverter_60()); - AotConverterRegistry.Register(new AotConverter_61()); - AotConverterRegistry.Register(new AotConverter_62()); - AotConverterRegistry.Register(new AotConverter_63()); - AotConverterRegistry.Register(new AotConverter_64()); - AotConverterRegistry.Register(new AotConverter_65()); - AotConverterRegistry.Register(new AotConverter_66()); - AotConverterRegistry.Register(new AotConverter_67()); - } +internal static partial class TUnit_ConverterRegistration +{ + static readonly int _r_AotConverter_0 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_0()); + static readonly int _r_AotConverter_1 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_1()); + static readonly int _r_AotConverter_2 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_2()); + static readonly int _r_AotConverter_3 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_3()); + static readonly int _r_AotConverter_4 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_4()); + static readonly int _r_AotConverter_5 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_5()); + static readonly int _r_AotConverter_6 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_6()); + static readonly int _r_AotConverter_7 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_7()); + static readonly int _r_AotConverter_8 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_8()); + static readonly int _r_AotConverter_9 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_9()); + static readonly int _r_AotConverter_10 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_10()); + static readonly int _r_AotConverter_11 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_11()); + static readonly int _r_AotConverter_12 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_12()); + static readonly int _r_AotConverter_13 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_13()); + static readonly int _r_AotConverter_14 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_14()); + static readonly int _r_AotConverter_15 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_15()); + static readonly int _r_AotConverter_16 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_16()); + static readonly int _r_AotConverter_17 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_17()); + static readonly int _r_AotConverter_18 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_18()); + static readonly int _r_AotConverter_19 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_19()); + static readonly int _r_AotConverter_20 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_20()); + static readonly int _r_AotConverter_21 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_21()); + static readonly int _r_AotConverter_22 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_22()); + static readonly int _r_AotConverter_23 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_23()); + static readonly int _r_AotConverter_24 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_24()); + static readonly int _r_AotConverter_25 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_25()); + static readonly int _r_AotConverter_26 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_26()); + static readonly int _r_AotConverter_27 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_27()); + static readonly int _r_AotConverter_28 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_28()); + static readonly int _r_AotConverter_29 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_29()); + static readonly int _r_AotConverter_30 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_30()); + static readonly int _r_AotConverter_31 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_31()); + static readonly int _r_AotConverter_32 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_32()); + static readonly int _r_AotConverter_33 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_33()); + static readonly int _r_AotConverter_34 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_34()); + static readonly int _r_AotConverter_35 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_35()); + static readonly int _r_AotConverter_36 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_36()); + static readonly int _r_AotConverter_37 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_37()); + static readonly int _r_AotConverter_38 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_38()); + static readonly int _r_AotConverter_39 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_39()); + static readonly int _r_AotConverter_40 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_40()); + static readonly int _r_AotConverter_41 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_41()); + static readonly int _r_AotConverter_42 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_42()); + static readonly int _r_AotConverter_43 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_43()); + static readonly int _r_AotConverter_44 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_44()); + static readonly int _r_AotConverter_45 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_45()); + static readonly int _r_AotConverter_46 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_46()); + static readonly int _r_AotConverter_47 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_47()); + static readonly int _r_AotConverter_48 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_48()); + static readonly int _r_AotConverter_49 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_49()); + static readonly int _r_AotConverter_50 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_50()); + static readonly int _r_AotConverter_51 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_51()); + static readonly int _r_AotConverter_52 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_52()); + static readonly int _r_AotConverter_53 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_53()); + static readonly int _r_AotConverter_54 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_54()); + static readonly int _r_AotConverter_55 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_55()); + static readonly int _r_AotConverter_56 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_56()); + static readonly int _r_AotConverter_57 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_57()); + static readonly int _r_AotConverter_58 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_58()); + static readonly int _r_AotConverter_59 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_59()); + static readonly int _r_AotConverter_60 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_60()); + static readonly int _r_AotConverter_61 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_61()); + static readonly int _r_AotConverter_62 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_62()); + static readonly int _r_AotConverter_63 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_63()); + static readonly int _r_AotConverter_64 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_64()); + static readonly int _r_AotConverter_65 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_65()); + static readonly int _r_AotConverter_66 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_66()); + static readonly int _r_AotConverter_67 = global::TUnit.Core.Converters.AotConverterRegistry.Register(new AotConverter_67()); } diff --git a/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet10_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet10_0.verified.txt index e0a05c3d5fa..0d938ba771a 100644 --- a/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet10_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet10_0.verified.txt @@ -101,6 +101,10 @@ file static class TUnitInfrastructure } global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_TestRegistration).TypeHandle); global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_HookRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_PropertyRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_ConverterRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_StaticPropertyRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_DynamicTestRegistration).TypeHandle); try { global::TUnit.Core.GlobalContext.Current.GlobalLogger.LogDebug("[ModuleInitializer:TestsBase`1] TUnit infrastructure initialized"); @@ -114,4 +118,12 @@ namespace TUnit.Generated internal static partial class TUnit_TestRegistration { } [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] internal static partial class TUnit_HookRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_PropertyRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_ConverterRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_StaticPropertyRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_DynamicTestRegistration { } } diff --git a/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet8_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet8_0.verified.txt index e0a05c3d5fa..0d938ba771a 100644 --- a/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet8_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet8_0.verified.txt @@ -101,6 +101,10 @@ file static class TUnitInfrastructure } global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_TestRegistration).TypeHandle); global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_HookRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_PropertyRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_ConverterRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_StaticPropertyRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_DynamicTestRegistration).TypeHandle); try { global::TUnit.Core.GlobalContext.Current.GlobalLogger.LogDebug("[ModuleInitializer:TestsBase`1] TUnit infrastructure initialized"); @@ -114,4 +118,12 @@ namespace TUnit.Generated internal static partial class TUnit_TestRegistration { } [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] internal static partial class TUnit_HookRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_PropertyRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_ConverterRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_StaticPropertyRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_DynamicTestRegistration { } } diff --git a/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet9_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet9_0.verified.txt index e0a05c3d5fa..0d938ba771a 100644 --- a/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet9_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.DotNet9_0.verified.txt @@ -101,6 +101,10 @@ file static class TUnitInfrastructure } global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_TestRegistration).TypeHandle); global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_HookRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_PropertyRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_ConverterRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_StaticPropertyRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_DynamicTestRegistration).TypeHandle); try { global::TUnit.Core.GlobalContext.Current.GlobalLogger.LogDebug("[ModuleInitializer:TestsBase`1] TUnit infrastructure initialized"); @@ -114,4 +118,12 @@ namespace TUnit.Generated internal static partial class TUnit_TestRegistration { } [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] internal static partial class TUnit_HookRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_PropertyRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_ConverterRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_StaticPropertyRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_DynamicTestRegistration { } } diff --git a/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.Net4_7.verified.txt b/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.Net4_7.verified.txt index e03a68e441a..b956198c882 100644 --- a/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.Net4_7.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DuplicateTypeNameAcrossAssembliesTests.InfrastructureGenerator_WithDuplicateTypeNames_CompilesSuccessfully.Net4_7.verified.txt @@ -101,6 +101,10 @@ file static class TUnitInfrastructure } global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_TestRegistration).TypeHandle); global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_HookRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_PropertyRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_ConverterRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_StaticPropertyRegistration).TypeHandle); + global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_DynamicTestRegistration).TypeHandle); try { global::TUnit.Core.GlobalContext.Current.GlobalLogger.LogDebug("[ModuleInitializer:TestsBase`1] TUnit infrastructure initialized"); @@ -114,4 +118,12 @@ namespace TUnit.Generated internal static partial class TUnit_TestRegistration { } [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] internal static partial class TUnit_HookRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_PropertyRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_ConverterRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_StaticPropertyRegistration { } + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute] + internal static partial class TUnit_DynamicTestRegistration { } } diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs index f2fdd993e64..2b599054068 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs @@ -95,40 +95,46 @@ private static void GenerateTests(SourceProductionContext context, DynamicTestMo sourceBuilder.AppendLine("using global::TUnit.Core;"); sourceBuilder.AppendLine("using global::TUnit.Core.Extensions;"); sourceBuilder.AppendLine(); - sourceBuilder.AppendLine("namespace TUnit.SourceGenerated;"); - sourceBuilder.AppendLine(); - sourceBuilder.AppendLine("[global::System.Diagnostics.StackTraceHidden]"); - sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"); - sourceBuilder.AppendLine($"[global::System.CodeDom.Compiler.GeneratedCode(\"TUnit\", \"{typeof(DynamicTestsGenerator).Assembly.GetName().Version}\")]"); - using (sourceBuilder.BeginBlock($"file partial class {className} : global::TUnit.Core.IDynamicTestSource")) + using (sourceBuilder.BeginBlock("namespace TUnit.SourceGenerated")) { - sourceBuilder.AppendLine("[global::System.Runtime.CompilerServices.ModuleInitializer]"); - using (sourceBuilder.BeginBlock("public static void Initialise()")) + sourceBuilder.AppendLine("[global::System.Diagnostics.StackTraceHidden]"); + sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"); + sourceBuilder.AppendLine($"[global::System.CodeDom.Compiler.GeneratedCode(\"TUnit\", \"{typeof(DynamicTestsGenerator).Assembly.GetName().Version}\")]"); + using (sourceBuilder.BeginBlock($"file partial class {className} : global::TUnit.Core.IDynamicTestSource")) { - sourceBuilder.AppendLine($"global::TUnit.Core.SourceRegistrar.RegisterDynamic(new {className}());"); + using (sourceBuilder.BeginBlock("public global::System.Collections.Generic.IReadOnlyList CollectDynamicTests(string sessionId)")) + { + using (sourceBuilder.BeginBlock("try")) + { + sourceBuilder.AppendLine( + $""" + var context = new global::TUnit.Core.DynamicTestBuilderContext({SymbolDisplay.FormatLiteral(model.FilePath, quote: true)}, {model.LineNumber}); + """); + + var receiver = model.IsStatic + ? model.FullyQualifiedTypeName + : $"new {model.FullyQualifiedTypeName}()"; + + sourceBuilder.AppendLine($"{receiver}.{model.MethodName}(context);"); + sourceBuilder.AppendLine("return context.Tests;"); + } + using (sourceBuilder.BeginBlock("catch (global::System.Exception exception)")) + { + GenerateFailedTestCode(sourceBuilder, model); + } + } } + } - sourceBuilder.EnsureNewLine(); - using (sourceBuilder.BeginBlock("public global::System.Collections.Generic.IReadOnlyList CollectDynamicTests(string sessionId)")) + // Contribute a static field initializer to the shared TUnit_DynamicTestRegistration + // partial (declared by InfrastructureGenerator) instead of a per-file [ModuleInitializer]. + // All contributions merge into one .cctor triggered once via RunClassConstructor. + sourceBuilder.EnsureNewLine(); + using (sourceBuilder.BeginBlock("namespace TUnit.Generated")) + { + using (sourceBuilder.BeginBlock("internal static partial class TUnit_DynamicTestRegistration")) { - using (sourceBuilder.BeginBlock("try")) - { - sourceBuilder.AppendLine( - $""" - var context = new global::TUnit.Core.DynamicTestBuilderContext({SymbolDisplay.FormatLiteral(model.FilePath, quote: true)}, {model.LineNumber}); - """); - - var receiver = model.IsStatic - ? model.FullyQualifiedTypeName - : $"new {model.FullyQualifiedTypeName}()"; - - sourceBuilder.AppendLine($"{receiver}.{model.MethodName}(context);"); - sourceBuilder.AppendLine("return context.Tests;"); - } - using (sourceBuilder.BeginBlock("catch (global::System.Exception exception)")) - { - GenerateFailedTestCode(sourceBuilder, model); - } + sourceBuilder.AppendLine($"static readonly int _r_Dynamic_{className}_{model.MethodName} = global::TUnit.Core.SourceRegistrar.RegisterDynamic(new global::TUnit.SourceGenerated.{className}());"); } } diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/InfrastructureGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/InfrastructureGenerator.cs index aaf2f37faf7..ae50c842e82 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/InfrastructureGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/InfrastructureGenerator.cs @@ -449,12 +449,18 @@ private static void GenerateCode(SourceProductionContext context, AssemblyInfoMo sourceBuilder.AppendLine(); // Trigger consolidated registration .cctors. - // Per-class/per-method test sources and per-hook sources contribute static field - // initializers to shared partial classes. RunClassConstructor forces each .cctor - // to execute, performing all registrations in ONE JIT-compiled method per class. - // No try/catch needed — InfrastructureGenerator always emits both shell classes. + // Test sources, hooks, property injection sources, AOT converters, static property + // initializers and dynamic test sources each contribute static field initializers to + // a shared partial class per concern. RunClassConstructor forces each .cctor to + // execute, performing all registrations in ONE JIT-compiled method per concern instead + // of N per-file [ModuleInitializer] methods. + // No try/catch needed — InfrastructureGenerator always emits these shell classes. sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_TestRegistration).TypeHandle);"); sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_HookRegistration).TypeHandle);"); + sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_PropertyRegistration).TypeHandle);"); + sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_ConverterRegistration).TypeHandle);"); + sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_StaticPropertyRegistration).TypeHandle);"); + sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_DynamicTestRegistration).TypeHandle);"); sourceBuilder.AppendLine(); sourceBuilder.AppendLine("try"); @@ -479,6 +485,14 @@ private static void GenerateCode(SourceProductionContext context, AssemblyInfoMo sourceBuilder.AppendLine("internal static partial class TUnit_TestRegistration { }"); sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); sourceBuilder.AppendLine("internal static partial class TUnit_HookRegistration { }"); + sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); + sourceBuilder.AppendLine("internal static partial class TUnit_PropertyRegistration { }"); + sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); + sourceBuilder.AppendLine("internal static partial class TUnit_ConverterRegistration { }"); + sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); + sourceBuilder.AppendLine("internal static partial class TUnit_StaticPropertyRegistration { }"); + sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); + sourceBuilder.AppendLine("internal static partial class TUnit_DynamicTestRegistration { }"); sourceBuilder.Unindent(); sourceBuilder.AppendLine("}"); diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs index 14bd5190815..2aec5de2dcd 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs @@ -205,55 +205,75 @@ private static string GenerateInitializationCode(EquatableArray"); - writer.AppendLine("/// Module initializer that registers static property metadata"); - writer.AppendLine("/// "); - writer.AppendLine("[global::System.Runtime.CompilerServices.ModuleInitializer]"); - writer.AppendLine("public static void Initialize()"); + // Generate individual property initializer methods that return the value and set the property + var generatedMethods = new HashSet(); + foreach (var propertyData in staticProperties) + { + var methodName = $"Initialize_{propertyData.Property.ContainingType.Name}_{propertyData.Property.Name}"; + if (generatedMethods.Add(methodName)) + { + GenerateIndividualPropertyInitializer(writer, propertyData); + } + } + + writer.Unindent(); + writer.AppendLine("}"); + + writer.Unindent(); + writer.AppendLine("}"); + writer.AppendLine(); + + // Contribute static field initializers to the shared TUnit_StaticPropertyRegistration partial + // (declared by InfrastructureGenerator). The compiler merges all contributions into one .cctor, + // triggered once via RunClassConstructor — replacing the per-assembly [ModuleInitializer]. + writer.AppendLine("namespace TUnit.Generated"); + writer.AppendLine("{"); + writer.Indent(); + writer.AppendLine("internal static partial class TUnit_StaticPropertyRegistration"); writer.AppendLine("{"); writer.Indent(); - // Register each property with metadata + var registeredFields = new HashSet(); foreach (var propertyData in staticProperties) { var typeName = propertyData.Property.ContainingType.GloballyQualified; var methodName = $"Initialize_{propertyData.Property.ContainingType.Name}_{propertyData.Property.Name}"; + var fieldName = $"_r_{SafeName(typeName)}_{propertyData.Property.Name}"; - writer.AppendLine("global::TUnit.Core.StaticProperties.StaticPropertyRegistry.Register(new global::TUnit.Core.StaticProperties.StaticPropertyMetadata"); + if (!registeredFields.Add(fieldName)) + { + continue; + } + + writer.AppendLine($"static readonly int {fieldName} = global::TUnit.Core.StaticProperties.StaticPropertyRegistry.Register(new global::TUnit.Core.StaticProperties.StaticPropertyMetadata"); writer.AppendLine("{"); writer.Indent(); writer.AppendLine($"PropertyName = \"{propertyData.Property.Name}\","); writer.AppendLine($"PropertyType = typeof({propertyData.Property.GloballyQualifiedType}),"); writer.AppendLine($"DeclaringType = typeof({typeName}),"); - writer.AppendLine($"InitializerAsync = {methodName}"); + writer.AppendLine($"InitializerAsync = global::TUnit.Core.Generated.StaticPropertyInitializer.{methodName}"); writer.Unindent(); writer.AppendLine("});"); } writer.Unindent(); writer.AppendLine("}"); - writer.AppendLine(); - - // Generate individual property initializer methods that return the value and set the property - var generatedMethods = new HashSet(); - foreach (var propertyData in staticProperties) - { - var methodName = $"Initialize_{propertyData.Property.ContainingType.Name}_{propertyData.Property.Name}"; - if (generatedMethods.Add(methodName)) - { - GenerateIndividualPropertyInitializer(writer, propertyData); - } - } - - writer.Unindent(); - writer.AppendLine("}"); - writer.Unindent(); writer.AppendLine("}"); return writer.ToString(); } + private static string SafeName(string globallyQualified) + { + var sb = new StringBuilder(globallyQualified.Length); + foreach (var c in globallyQualified) + { + sb.Append(char.IsLetterOrDigit(c) ? c : '_'); + } + return sb.ToString(); + } + private static void GenerateIndividualPropertyInitializer(CodeWriter writer, PropertyWithDataSourceModel propertyData) { var propertyName = propertyData.Property.Name; @@ -264,7 +284,7 @@ private static void GenerateIndividualPropertyInitializer(CodeWriter writer, Pro writer.AppendLine("/// "); writer.AppendLine($"/// Initializer for {typeName}.{propertyName}"); writer.AppendLine("/// "); - writer.AppendLine($"private static async global::System.Threading.Tasks.Task {methodName}()"); + writer.AppendLine($"internal static async global::System.Threading.Tasks.Task {methodName}()"); writer.AppendLine("{"); writer.Indent(); diff --git a/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs b/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs index 234a4a802a7..7cbac46b1cd 100644 --- a/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs +++ b/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs @@ -646,31 +646,25 @@ private void GenerateConverters(SourceProductionContext context, EquatableArray< writer.AppendLine("}"); writer.AppendLine(); - registrations.Add($"AotConverterRegistry.Register(new {converterClassName}());"); + registrations.Add(converterClassName); } - writer.AppendLine("internal static class AotConverterRegistration"); + // Contribute static field initializers to the shared TUnit_ConverterRegistration partial + // (declared by InfrastructureGenerator). The compiler merges all contributions into one + // .cctor, triggered once via RunClassConstructor from the single module initializer — + // avoiding a separate [ModuleInitializer] method here. + writer.AppendLine("internal static partial class TUnit_ConverterRegistration"); writer.AppendLine("{"); writer.Indent(); - writer.AppendLine("[global::System.Runtime.CompilerServices.ModuleInitializer]"); - writer.AppendLine("[global::System.Diagnostics.CodeAnalysis.SuppressMessage(\"Performance\", \"CA2255:The 'ModuleInitializer' attribute should not be used in libraries\","); - writer.AppendLine(" Justification = \"Test framework needs to register AOT converters for conversion operators\")]"); - writer.AppendLine("public static void Initialize()"); - writer.AppendLine("{"); - writer.Indent(); - - foreach (var registration in registrations) + foreach (var converterClassName in registrations) { - writer.AppendLine(registration); + writer.AppendLine($"static readonly int _r_{converterClassName} = global::TUnit.Core.Converters.AotConverterRegistry.Register(new {converterClassName}());"); } writer.Unindent(); writer.AppendLine("}"); - writer.Unindent(); - writer.AppendLine("}"); - context.AddSource("AotConverters.g.cs", writer.ToString()); } diff --git a/TUnit.Core.SourceGenerator/Generators/PropertyInjectionSourceGenerator.cs b/TUnit.Core.SourceGenerator/Generators/PropertyInjectionSourceGenerator.cs index 6f4aecf601b..ab15dc50ee5 100644 --- a/TUnit.Core.SourceGenerator/Generators/PropertyInjectionSourceGenerator.cs +++ b/TUnit.Core.SourceGenerator/Generators/PropertyInjectionSourceGenerator.cs @@ -583,16 +583,8 @@ private static void GeneratePropertyInjectionSource(SourceProductionContext cont var sb = new StringBuilder(); WriteFileHeader(sb); - // Module initializer - sb.AppendLine($"internal static class {model.SafeClassName}_PropertyInjectionInitializer"); + sb.AppendLine("namespace TUnit.Core"); sb.AppendLine("{"); - sb.AppendLine(" [global::System.Runtime.CompilerServices.ModuleInitializer]"); - sb.AppendLine(" public static void Initialize()"); - sb.AppendLine(" {"); - sb.AppendLine($" global::TUnit.Core.PropertySourceRegistry.Register(typeof({model.ClassFullyQualifiedName}), new {sourceClassName}());"); - sb.AppendLine(" }"); - sb.AppendLine("}"); - sb.AppendLine(); // Property source class sb.AppendLine($"internal sealed class {sourceClassName} : IPropertySource"); @@ -652,6 +644,18 @@ private static void GeneratePropertyInjectionSource(SourceProductionContext cont } } + sb.AppendLine("}"); + + // Contribute a static field initializer to the shared TUnit_PropertyRegistration partial + // instead of a per-class [ModuleInitializer]. All contributions merge into one .cctor. + sb.AppendLine("namespace TUnit.Generated"); + sb.AppendLine("{"); + sb.AppendLine("internal static partial class TUnit_PropertyRegistration"); + sb.AppendLine("{"); + sb.AppendLine($"static readonly int _r_{model.SafeClassName}_PropSource = global::TUnit.Core.PropertySourceRegistry.Register(typeof({model.ClassFullyQualifiedName}), new global::TUnit.Core.{sourceClassName}());"); + sb.AppendLine("}"); + sb.AppendLine("}"); + context.AddSource(fileName, sb.ToString()); } @@ -757,26 +761,24 @@ private static void GenerateInitializerPropertySource(SourceProductionContext co sb.AppendLine("namespace TUnit.Generated;"); sb.AppendLine(); - sb.AppendLine($"internal static class {model.SafeTypeName}_InitializerPropertiesInitializer"); + // Contribute a static field initializer to the shared TUnit_PropertyRegistration partial + // instead of a per-type [ModuleInitializer]. All contributions merge into one .cctor. + sb.AppendLine("internal static partial class TUnit_PropertyRegistration"); sb.AppendLine("{"); - sb.AppendLine(" [global::System.Runtime.CompilerServices.ModuleInitializer]"); - sb.AppendLine(" public static void Initialize()"); + sb.AppendLine($" static readonly int _r_{model.SafeTypeName}_InitProps = InitializerPropertyRegistry.Register(typeof({model.TypeFullyQualified}), new InitializerPropertyInfo[]"); sb.AppendLine(" {"); - sb.AppendLine($" InitializerPropertyRegistry.Register(typeof({model.TypeFullyQualified}), new InitializerPropertyInfo[]"); - sb.AppendLine(" {"); foreach (var prop in model.Properties) { - sb.AppendLine(" new InitializerPropertyInfo"); - sb.AppendLine(" {"); - sb.AppendLine($" PropertyName = \"{prop.PropertyName}\","); - sb.AppendLine($" PropertyType = typeof({prop.PropertyTypeFullyQualified}),"); - sb.AppendLine($" GetValue = static obj => (({model.TypeFullyQualified})obj).{prop.PropertyName}"); - sb.AppendLine(" },"); + sb.AppendLine(" new InitializerPropertyInfo"); + sb.AppendLine(" {"); + sb.AppendLine($" PropertyName = \"{prop.PropertyName}\","); + sb.AppendLine($" PropertyType = typeof({prop.PropertyTypeFullyQualified}),"); + sb.AppendLine($" GetValue = static obj => (({model.TypeFullyQualified})obj).{prop.PropertyName}"); + sb.AppendLine(" },"); } - sb.AppendLine(" });"); - sb.AppendLine(" }"); + sb.AppendLine(" });"); sb.AppendLine("}"); context.AddSource(fileName, sb.ToString()); @@ -794,16 +796,8 @@ private static void GenerateGenericPropertyInjectionSource(SourceProductionConte var sb = new StringBuilder(); WriteFileHeader(sb); - // Module initializer - sb.AppendLine($"internal static class {model.SafeTypeName}_Generic_PropertyInjectionInitializer"); + sb.AppendLine("namespace TUnit.Core"); sb.AppendLine("{"); - sb.AppendLine(" [global::System.Runtime.CompilerServices.ModuleInitializer]"); - sb.AppendLine(" public static void Initialize()"); - sb.AppendLine(" {"); - sb.AppendLine($" global::TUnit.Core.PropertySourceRegistry.Register(typeof({model.ConcreteTypeFullyQualified}), new {sourceClassName}());"); - sb.AppendLine(" }"); - sb.AppendLine("}"); - sb.AppendLine(); // Property source class sb.AppendLine($"internal sealed class {sourceClassName} : IPropertySource"); @@ -862,6 +856,18 @@ private static void GenerateGenericPropertyInjectionSource(SourceProductionConte } } + sb.AppendLine("}"); + + // Contribute a static field initializer to the shared TUnit_PropertyRegistration partial + // instead of a per-type [ModuleInitializer]. All contributions merge into one .cctor. + sb.AppendLine("namespace TUnit.Generated"); + sb.AppendLine("{"); + sb.AppendLine("internal static partial class TUnit_PropertyRegistration"); + sb.AppendLine("{"); + sb.AppendLine($"static readonly int _r_{model.SafeTypeName}_Generic_PropSource = global::TUnit.Core.PropertySourceRegistry.Register(typeof({model.ConcreteTypeFullyQualified}), new global::TUnit.Core.{sourceClassName}());"); + sb.AppendLine("}"); + sb.AppendLine("}"); + context.AddSource(fileName, sb.ToString()); } @@ -881,26 +887,24 @@ private static void GenerateGenericInitializerPropertySource(SourceProductionCon sb.AppendLine("namespace TUnit.Generated;"); sb.AppendLine(); - sb.AppendLine($"internal static class {model.SafeTypeName}_Generic_InitializerPropertiesInitializer"); + // Contribute a static field initializer to the shared TUnit_PropertyRegistration partial + // instead of a per-type [ModuleInitializer]. All contributions merge into one .cctor. + sb.AppendLine("internal static partial class TUnit_PropertyRegistration"); sb.AppendLine("{"); - sb.AppendLine(" [global::System.Runtime.CompilerServices.ModuleInitializer]"); - sb.AppendLine(" public static void Initialize()"); + sb.AppendLine($" static readonly int _r_{model.SafeTypeName}_Generic_InitProps = InitializerPropertyRegistry.Register(typeof({model.ConcreteTypeFullyQualified}), new InitializerPropertyInfo[]"); sb.AppendLine(" {"); - sb.AppendLine($" InitializerPropertyRegistry.Register(typeof({model.ConcreteTypeFullyQualified}), new InitializerPropertyInfo[]"); - sb.AppendLine(" {"); foreach (var prop in model.InitializerProperties) { - sb.AppendLine(" new InitializerPropertyInfo"); - sb.AppendLine(" {"); - sb.AppendLine($" PropertyName = \"{prop.PropertyName}\","); - sb.AppendLine($" PropertyType = typeof({prop.PropertyTypeFullyQualified}),"); - sb.AppendLine($" GetValue = static obj => (({model.ConcreteTypeFullyQualified})obj).{prop.PropertyName}"); - sb.AppendLine(" },"); + sb.AppendLine(" new InitializerPropertyInfo"); + sb.AppendLine(" {"); + sb.AppendLine($" PropertyName = \"{prop.PropertyName}\","); + sb.AppendLine($" PropertyType = typeof({prop.PropertyTypeFullyQualified}),"); + sb.AppendLine($" GetValue = static obj => (({model.ConcreteTypeFullyQualified})obj).{prop.PropertyName}"); + sb.AppendLine(" },"); } - sb.AppendLine(" });"); - sb.AppendLine(" }"); + sb.AppendLine(" });"); sb.AppendLine("}"); context.AddSource(fileName, sb.ToString()); @@ -920,8 +924,6 @@ private static void WriteFileHeader(StringBuilder sb) sb.AppendLine("using TUnit.Core.Enums;"); sb.AppendLine("using System.Linq;"); sb.AppendLine(); - sb.AppendLine("namespace TUnit.Core;"); - sb.AppendLine(); } private static void WriteGeneratedFileHeader(StringBuilder sb) diff --git a/TUnit.Core/Converters/AotConverterRegistry.cs b/TUnit.Core/Converters/AotConverterRegistry.cs index 22bd65354b6..8bf8854a932 100644 --- a/TUnit.Core/Converters/AotConverterRegistry.cs +++ b/TUnit.Core/Converters/AotConverterRegistry.cs @@ -10,11 +10,15 @@ public static class AotConverterRegistry private static readonly ConcurrentDictionary<(Type Source, Type Target), IAotConverter> Converters = new(); /// - /// Registers a converter + /// Registers a converter. Called by generated code from a static field initializer on the + /// consolidated registration .cctor (so the per-assembly module initializer collapses + /// into one merged .cctor). + /// Returns a dummy value for use as a static field initializer. /// - public static void Register(IAotConverter converter) + public static int Register(IAotConverter converter) { Converters.TryAdd((converter.SourceType, converter.TargetType), converter); + return 0; } /// diff --git a/TUnit.Core/Discovery/InitializerPropertyRegistry.cs b/TUnit.Core/Discovery/InitializerPropertyRegistry.cs index fe7269a3db2..731a1681dd9 100644 --- a/TUnit.Core/Discovery/InitializerPropertyRegistry.cs +++ b/TUnit.Core/Discovery/InitializerPropertyRegistry.cs @@ -14,11 +14,15 @@ public static class InitializerPropertyRegistry private static readonly ConcurrentDictionary Registry = new(); /// - /// Registers property metadata for a type. Called by generated code. + /// Registers property metadata for a type. Called by generated code from a static field + /// initializer on the consolidated registration .cctor (so N per-file module + /// initializers collapse into one merged .cctor). + /// Returns a dummy value for use as a static field initializer. /// - public static void Register(Type type, InitializerPropertyInfo[] properties) + public static int Register(Type type, InitializerPropertyInfo[] properties) { Registry[type] = properties; + return 0; } /// diff --git a/TUnit.Core/PropertySourceRegistry.cs b/TUnit.Core/PropertySourceRegistry.cs index 7783e6dcee9..365de757f26 100644 --- a/TUnit.Core/PropertySourceRegistry.cs +++ b/TUnit.Core/PropertySourceRegistry.cs @@ -12,11 +12,15 @@ public static class PropertySourceRegistry private static readonly ConcurrentDictionary _sources = new(); /// - /// Registers a property source for a type. Called by generated code. + /// Registers a property source for a type. Called by generated code from a static field + /// initializer on the consolidated registration .cctor (so N per-class module + /// initializers collapse into one merged .cctor). + /// Returns a dummy value for use as a static field initializer. /// - public static void Register(Type type, IPropertySource source) + public static int Register(Type type, IPropertySource source) { _sources[type] = source; + return 0; } /// diff --git a/TUnit.Core/SourceRegistrar.cs b/TUnit.Core/SourceRegistrar.cs index 007a4557b8a..89c88b7a004 100644 --- a/TUnit.Core/SourceRegistrar.cs +++ b/TUnit.Core/SourceRegistrar.cs @@ -35,12 +35,15 @@ public static void RegisterAssembly(Func assemblyLoader) } /// - /// Registers a test source. + /// Registers a dynamic test source. Returns a dummy value so it can be used as a static field + /// initializer on the consolidated registration .cctor, collapsing per-source module + /// initializers into one merged .cctor. /// /// The test source to register. - public static void RegisterDynamic(IDynamicTestSource testSource) + public static int RegisterDynamic(IDynamicTestSource testSource) { Sources.DynamicTestSources.Enqueue(testSource); + return 0; } /// diff --git a/TUnit.Core/StaticProperties/StaticPropertyRegistry.cs b/TUnit.Core/StaticProperties/StaticPropertyRegistry.cs index e0da855d7e8..c22a768d6cf 100644 --- a/TUnit.Core/StaticProperties/StaticPropertyRegistry.cs +++ b/TUnit.Core/StaticProperties/StaticPropertyRegistry.cs @@ -12,11 +12,15 @@ public static class StaticPropertyRegistry private static readonly ConcurrentDictionary _initializedValues = new(); /// - /// Register a static property for initialization + /// Register a static property for initialization. Called by generated code from a static field + /// initializer on the consolidated registration .cctor (so the per-assembly module + /// initializer collapses into one merged .cctor). + /// Returns a dummy value for use as a static field initializer. /// - public static void Register(StaticPropertyMetadata metadata) + public static int Register(StaticPropertyMetadata metadata) { _registeredProperties.Add(metadata); + return 0; } /// diff --git a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet10_0.verified.txt b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet10_0.verified.txt index 2a4fbf0bc74..eb377e64940 100644 --- a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet10_0.verified.txt +++ b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet10_0.verified.txt @@ -1199,7 +1199,7 @@ namespace public static .PropertyDataSource[]? GetPropertyDataSources( type) { } public static .PropertyInjectionData[]? GetPropertyInjectionData( type) { } public static ..IPropertySource? GetSource( type) { } - public static void Register( type, ..IPropertySource source) { } + public static int Register( type, ..IPropertySource source) { } } [(.Assembly, AllowMultiple=false, Inherited=false)] public sealed class ReflectionModeAttribute : @@ -1293,7 +1293,7 @@ namespace public SourceRegistrar() { } public static bool IsEnabled { get; set; } public static void RegisterAssembly(<.Assembly> assemblyLoader) { } - public static void RegisterDynamic(.IDynamicTestSource testSource) { } + public static int RegisterDynamic(.IDynamicTestSource testSource) { } public static int RegisterEntries<[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..PublicMethods | ..PublicProperties)] T>(<.TestEntry[]> factory) where T : class { } public static void RegisterGlobalInitializer(<.> initializer) { } @@ -1854,7 +1854,7 @@ namespace .Converters { public static class AotConverterRegistry { - public static void Register(. converter) { } + public static int Register(. converter) { } public static void Register( converter) { } public static bool TryConvert( sourceType, targetType, object? value, out object? result) { } public static bool TryGetConverter( sourceType, targetType, out .? converter) { } @@ -1920,7 +1920,7 @@ namespace .Discovery { public static .[]? GetProperties( type) { } public static bool HasRegistration( type) { } - public static void Register( type, .[] properties) { } + public static int Register( type, .[] properties) { } } } namespace .Enums @@ -3059,7 +3059,7 @@ namespace .StaticProperties public static class StaticPropertyRegistry { public static .<.> GetRegisteredProperties() { } - public static void Register(. metadata) { } + public static int Register(. metadata) { } public static bool TryGetInitializedValue( declaringType, string propertyName, out object? value) { } } } \ No newline at end of file diff --git a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet8_0.verified.txt b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet8_0.verified.txt index f6c2a7836aa..625ea2a9b57 100644 --- a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet8_0.verified.txt +++ b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet8_0.verified.txt @@ -1199,7 +1199,7 @@ namespace public static .PropertyDataSource[]? GetPropertyDataSources( type) { } public static .PropertyInjectionData[]? GetPropertyInjectionData( type) { } public static ..IPropertySource? GetSource( type) { } - public static void Register( type, ..IPropertySource source) { } + public static int Register( type, ..IPropertySource source) { } } [(.Assembly, AllowMultiple=false, Inherited=false)] public sealed class ReflectionModeAttribute : @@ -1293,7 +1293,7 @@ namespace public SourceRegistrar() { } public static bool IsEnabled { get; set; } public static void RegisterAssembly(<.Assembly> assemblyLoader) { } - public static void RegisterDynamic(.IDynamicTestSource testSource) { } + public static int RegisterDynamic(.IDynamicTestSource testSource) { } public static int RegisterEntries<[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..PublicMethods | ..PublicProperties)] T>(<.TestEntry[]> factory) where T : class { } public static void RegisterGlobalInitializer(<.> initializer) { } @@ -1854,7 +1854,7 @@ namespace .Converters { public static class AotConverterRegistry { - public static void Register(. converter) { } + public static int Register(. converter) { } public static void Register( converter) { } public static bool TryConvert( sourceType, targetType, object? value, out object? result) { } public static bool TryGetConverter( sourceType, targetType, out .? converter) { } @@ -1920,7 +1920,7 @@ namespace .Discovery { public static .[]? GetProperties( type) { } public static bool HasRegistration( type) { } - public static void Register( type, .[] properties) { } + public static int Register( type, .[] properties) { } } } namespace .Enums @@ -3059,7 +3059,7 @@ namespace .StaticProperties public static class StaticPropertyRegistry { public static .<.> GetRegisteredProperties() { } - public static void Register(. metadata) { } + public static int Register(. metadata) { } public static bool TryGetInitializedValue( declaringType, string propertyName, out object? value) { } } } \ No newline at end of file diff --git a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet9_0.verified.txt b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet9_0.verified.txt index b52b811d34d..d056c3106e9 100644 --- a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet9_0.verified.txt +++ b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet9_0.verified.txt @@ -1199,7 +1199,7 @@ namespace public static .PropertyDataSource[]? GetPropertyDataSources( type) { } public static .PropertyInjectionData[]? GetPropertyInjectionData( type) { } public static ..IPropertySource? GetSource( type) { } - public static void Register( type, ..IPropertySource source) { } + public static int Register( type, ..IPropertySource source) { } } [(.Assembly, AllowMultiple=false, Inherited=false)] public sealed class ReflectionModeAttribute : @@ -1293,7 +1293,7 @@ namespace public SourceRegistrar() { } public static bool IsEnabled { get; set; } public static void RegisterAssembly(<.Assembly> assemblyLoader) { } - public static void RegisterDynamic(.IDynamicTestSource testSource) { } + public static int RegisterDynamic(.IDynamicTestSource testSource) { } public static int RegisterEntries<[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..PublicMethods | ..PublicProperties)] T>(<.TestEntry[]> factory) where T : class { } public static void RegisterGlobalInitializer(<.> initializer) { } @@ -1854,7 +1854,7 @@ namespace .Converters { public static class AotConverterRegistry { - public static void Register(. converter) { } + public static int Register(. converter) { } public static void Register( converter) { } public static bool TryConvert( sourceType, targetType, object? value, out object? result) { } public static bool TryGetConverter( sourceType, targetType, out .? converter) { } @@ -1920,7 +1920,7 @@ namespace .Discovery { public static .[]? GetProperties( type) { } public static bool HasRegistration( type) { } - public static void Register( type, .[] properties) { } + public static int Register( type, .[] properties) { } } } namespace .Enums @@ -3059,7 +3059,7 @@ namespace .StaticProperties public static class StaticPropertyRegistry { public static .<.> GetRegisteredProperties() { } - public static void Register(. metadata) { } + public static int Register(. metadata) { } public static bool TryGetInitializedValue( declaringType, string propertyName, out object? value) { } } } \ No newline at end of file diff --git a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.Net4_7.verified.txt b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.Net4_7.verified.txt index c6a3114e729..b99149ea715 100644 --- a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.Net4_7.verified.txt +++ b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.Net4_7.verified.txt @@ -1157,7 +1157,7 @@ namespace public static .PropertyDataSource[]? GetPropertyDataSources( type) { } public static .PropertyInjectionData[]? GetPropertyInjectionData( type) { } public static ..IPropertySource? GetSource( type) { } - public static void Register( type, ..IPropertySource source) { } + public static int Register( type, ..IPropertySource source) { } } [(.Assembly, AllowMultiple=false, Inherited=false)] public sealed class ReflectionModeAttribute : @@ -1249,7 +1249,7 @@ namespace public SourceRegistrar() { } public static bool IsEnabled { get; set; } public static void RegisterAssembly(<.Assembly> assemblyLoader) { } - public static void RegisterDynamic(.IDynamicTestSource testSource) { } + public static int RegisterDynamic(.IDynamicTestSource testSource) { } public static int RegisterEntries(<.TestEntry[]> factory) where T : class { } public static void RegisterGlobalInitializer(<.> initializer) { } @@ -1793,7 +1793,7 @@ namespace .Converters { public static class AotConverterRegistry { - public static void Register(. converter) { } + public static int Register(. converter) { } public static void Register( converter) { } public static bool TryConvert( sourceType, targetType, object? value, out object? result) { } public static bool TryGetConverter( sourceType, targetType, out .? converter) { } @@ -1859,7 +1859,7 @@ namespace .Discovery { public static .[]? GetProperties( type) { } public static bool HasRegistration( type) { } - public static void Register( type, .[] properties) { } + public static int Register( type, .[] properties) { } } } namespace .Enums @@ -2981,7 +2981,7 @@ namespace .StaticProperties public static class StaticPropertyRegistry { public static .<.> GetRegisteredProperties() { } - public static void Register(. metadata) { } + public static int Register(. metadata) { } public static bool TryGetInitializedValue( declaringType, string propertyName, out object? value) { } } } \ No newline at end of file From 508b3aec8e1361b81f52fc67ba62168834ba85e0 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Fri, 19 Jun 2026 20:51:35 +0100 Subject: [PATCH 2/7] refactor(sourcegen): tidy registration-shell emission - InfrastructureGenerator: emit the 6 registration-shell declarations and their RunClassConstructor triggers from one shared RegistrationShells list instead of 12 hand-written AppendLine pairs (output byte-identical). - AotConverterGenerator: rename `registrations` -> `converterClassNames` now that the list holds class names rather than registration statements. --- .../CodeGenerators/InfrastructureGenerator.cs | 40 ++++++++++--------- .../Generators/AotConverterGenerator.cs | 6 +-- 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/InfrastructureGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/InfrastructureGenerator.cs index ae50c842e82..b494c7cff01 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/InfrastructureGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/InfrastructureGenerator.cs @@ -33,6 +33,19 @@ public class InfrastructureGenerator : IIncrementalGenerator "7cec85d7bea7798e", // .NET Core ]; + // Shared partial-class shells in TUnit.Generated, one per registration concern. Per-file + // generated code contributes static field initializers to these; the compiler merges each into + // a single .cctor, triggered once from the module initializer below via RunClassConstructor. + private static readonly string[] RegistrationShells = + [ + "TUnit_TestRegistration", + "TUnit_HookRegistration", + "TUnit_PropertyRegistration", + "TUnit_ConverterRegistration", + "TUnit_StaticPropertyRegistration", + "TUnit_DynamicTestRegistration", + ]; + public void Initialize(IncrementalGeneratorInitializationContext context) { var enabledProvider = context.AnalyzerConfigOptionsProvider @@ -455,12 +468,10 @@ private static void GenerateCode(SourceProductionContext context, AssemblyInfoMo // execute, performing all registrations in ONE JIT-compiled method per concern instead // of N per-file [ModuleInitializer] methods. // No try/catch needed — InfrastructureGenerator always emits these shell classes. - sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_TestRegistration).TypeHandle);"); - sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_HookRegistration).TypeHandle);"); - sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_PropertyRegistration).TypeHandle);"); - sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_ConverterRegistration).TypeHandle);"); - sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_StaticPropertyRegistration).TypeHandle);"); - sourceBuilder.AppendLine("global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.TUnit_DynamicTestRegistration).TypeHandle);"); + foreach (var shell in RegistrationShells) + { + sourceBuilder.AppendLine($"global::System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(global::TUnit.Generated.{shell}).TypeHandle);"); + } sourceBuilder.AppendLine(); sourceBuilder.AppendLine("try"); @@ -481,18 +492,11 @@ private static void GenerateCode(SourceProductionContext context, AssemblyInfoMo sourceBuilder.AppendLine("namespace TUnit.Generated"); sourceBuilder.AppendLine("{"); sourceBuilder.Indent(); - sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); - sourceBuilder.AppendLine("internal static partial class TUnit_TestRegistration { }"); - sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); - sourceBuilder.AppendLine("internal static partial class TUnit_HookRegistration { }"); - sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); - sourceBuilder.AppendLine("internal static partial class TUnit_PropertyRegistration { }"); - sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); - sourceBuilder.AppendLine("internal static partial class TUnit_ConverterRegistration { }"); - sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); - sourceBuilder.AppendLine("internal static partial class TUnit_StaticPropertyRegistration { }"); - sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); - sourceBuilder.AppendLine("internal static partial class TUnit_DynamicTestRegistration { }"); + foreach (var shell in RegistrationShells) + { + sourceBuilder.AppendLine("[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]"); + sourceBuilder.AppendLine($"internal static partial class {shell} {{ }}"); + } sourceBuilder.Unindent(); sourceBuilder.AppendLine("}"); diff --git a/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs b/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs index 7cbac46b1cd..453aa936fc8 100644 --- a/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs +++ b/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs @@ -542,7 +542,7 @@ private void GenerateConverters(SourceProductionContext context, EquatableArray< writer.AppendLine(); var converterIndex = 0; - var registrations = new List(); + var converterClassNames = new List(); foreach (var conversion in conversions) { @@ -646,7 +646,7 @@ private void GenerateConverters(SourceProductionContext context, EquatableArray< writer.AppendLine("}"); writer.AppendLine(); - registrations.Add(converterClassName); + converterClassNames.Add(converterClassName); } // Contribute static field initializers to the shared TUnit_ConverterRegistration partial @@ -657,7 +657,7 @@ private void GenerateConverters(SourceProductionContext context, EquatableArray< writer.AppendLine("{"); writer.Indent(); - foreach (var converterClassName in registrations) + foreach (var converterClassName in converterClassNames) { writer.AppendLine($"static readonly int _r_{converterClassName} = global::TUnit.Core.Converters.AotConverterRegistry.Register(new {converterClassName}());"); } From 4f088ceba234d4d31413a8ccacdcdf677dc9e946 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Fri, 19 Jun 2026 20:57:33 +0100 Subject: [PATCH 3/7] fix(sourcegen): make consolidated registration field names collision-proof Addresses code review on #6286. - StaticPropertyInitializationGenerator: `SafeName` maps every non-alphanumeric char to `_`, so two distinct types whose fully-qualified names differ only in `.` vs `_` (e.g. A_B.C vs A.B_C) produced the same `_r_...` field in the single merged `TUnit_StaticPropertyRegistration` .cctor -> duplicate-field compile error. Append a stable per-build hash of the FQN + property name. - DynamicTestsGenerator: `_r_Dynamic_{class}_{method}` (and the generated file name) collided for same-named overloads on one class, or same-minimal-name classes in different namespaces. Add a stable hash of the fully-qualified type + method + line to both the file name and the field, so such cases now generate distinct files/fields instead of failing. --- .../CodeGenerators/DynamicTestsGenerator.cs | 9 +++++++-- .../StaticPropertyInitializationGenerator.cs | 6 +++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs index 2b599054068..9a6ab38d753 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs @@ -88,6 +88,11 @@ private static void GenerateTests(SourceProductionContext context, DynamicTestMo { var className = model.MinimalTypeName; + // Disambiguator (stable within a build) so distinct sources that share a minimal type + // name + method name — different namespaces, or same-named overloads on different lines — + // get unique generated file names AND unique fields on the shared registration partial. + var uniqueSuffix = ((uint)$"{model.FullyQualifiedTypeName}.{model.MethodName}#{model.LineNumber}".GetHashCode()).ToString("x8"); + using var sourceBuilder = new CodeWriter(); sourceBuilder.AppendLine("using global::System.Linq;"); @@ -134,13 +139,13 @@ private static void GenerateTests(SourceProductionContext context, DynamicTestMo { using (sourceBuilder.BeginBlock("internal static partial class TUnit_DynamicTestRegistration")) { - sourceBuilder.AppendLine($"static readonly int _r_Dynamic_{className}_{model.MethodName} = global::TUnit.Core.SourceRegistrar.RegisterDynamic(new global::TUnit.SourceGenerated.{className}());"); + sourceBuilder.AppendLine($"static readonly int _r_Dynamic_{className}_{model.MethodName}_{uniqueSuffix} = global::TUnit.Core.SourceRegistrar.RegisterDynamic(new global::TUnit.SourceGenerated.{className}());"); } } // Deterministic filename - no GUID needed since file keyword prevents collisions // and each method is unique within its type - context.AddSource($"Dynamic_{className}_{model.MethodName}.g.cs", sourceBuilder.ToString()); + context.AddSource($"Dynamic_{className}_{model.MethodName}_{uniqueSuffix}.g.cs", sourceBuilder.ToString()); } catch (Exception ex) { diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs index 2aec5de2dcd..50824d93a82 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs @@ -238,7 +238,11 @@ private static string GenerateInitializationCode(EquatableArray Date: Fri, 19 Jun 2026 21:57:29 +0100 Subject: [PATCH 4/7] fix(sourcegen): collision-proof + deterministic registration field names Addresses follow-up code review on #6286. - PropertyInjectionSourceGenerator: the four `_r_..._PropSource` / `_InitProps` (and Generic variants) fields on the merged `TUnit_PropertyRegistration` .cctor were keyed only on `GetSafeClassName`, which collapses every separator to `_`. Two types whose FQNs differ only in `.` vs `_` produced a duplicate field -> compile error in user code. Append a stable hash of the full type name, matching the StaticProperty/Dynamic fix in 106a84276. - Replace `string.GetHashCode()` disambiguators (randomized per-process since .NET Core 2.1) with the existing deterministic FNV-1a `FileNameHelper. GetStableHashCode` across PropertyInjection, StaticProperty and DynamicTests. Generated hint/field names now stay stable across compiler restarts, preserving Roslyn's incremental cache. `GetStableHashCode` made public for reuse. Property/Static/Dynamic outputs aren't snapshotted; Infra/AotConverter snapshots unchanged (untouched generators). Snapshot suite green. --- .../CodeGenerators/DynamicTestsGenerator.cs | 10 +++++---- .../StaticPropertyInitializationGenerator.cs | 8 ++++--- .../PropertyInjectionSourceGenerator.cs | 21 +++++++++++++------ .../Helpers/FileNameHelper.cs | 6 ++++-- 4 files changed, 30 insertions(+), 15 deletions(-) diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs index 9a6ab38d753..d2c2cd989b6 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/DynamicTestsGenerator.cs @@ -1,5 +1,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using TUnit.Core.SourceGenerator.Helpers; using TUnit.Core.SourceGenerator.Models.Extracted; namespace TUnit.Core.SourceGenerator.CodeGenerators; @@ -88,10 +89,11 @@ private static void GenerateTests(SourceProductionContext context, DynamicTestMo { var className = model.MinimalTypeName; - // Disambiguator (stable within a build) so distinct sources that share a minimal type - // name + method name — different namespaces, or same-named overloads on different lines — - // get unique generated file names AND unique fields on the shared registration partial. - var uniqueSuffix = ((uint)$"{model.FullyQualifiedTypeName}.{model.MethodName}#{model.LineNumber}".GetHashCode()).ToString("x8"); + // Disambiguator so distinct sources that share a minimal type name + method name — + // different namespaces, or same-named overloads on different lines — get unique generated + // file names AND unique fields on the shared registration partial. FNV-1a (not + // string.GetHashCode) so the file/field names stay stable across compiler restarts. + var uniqueSuffix = FileNameHelper.GetStableHashCode($"{model.FullyQualifiedTypeName}.{model.MethodName}#{model.LineNumber}").ToString("x8"); using var sourceBuilder = new CodeWriter(); diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs index 50824d93a82..1606ec71981 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs @@ -4,6 +4,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using TUnit.Core.SourceGenerator.Extensions; +using TUnit.Core.SourceGenerator.Helpers; using TUnit.Core.SourceGenerator.CodeGenerators.Helpers; using TUnit.Core.SourceGenerator.Models; using TUnit.Core.SourceGenerator.CodeGenerators.Formatting; @@ -239,9 +240,10 @@ private static string GenerateInitializationCode(EquatableArray DeduplicateConcreteGenericT private static void GeneratePropertyInjectionSource(SourceProductionContext context, ClassPropertyInjectionModel model) { - var sourceClassName = $"PropertyInjectionSource_{Math.Abs(model.ClassFullyQualifiedName.GetHashCode()):x}"; + // Stable (per-build deterministic) hash of the full type name. SafeClassName collapses every + // separator to '_', so two types whose FQNs differ only in '.' vs '_' share a SafeClassName; + // the hash keeps both the source-class name and the merged-.cctor field unique. + var stableHash = FileNameHelper.GetStableHashCode(model.ClassFullyQualifiedName).ToString("x8"); + var sourceClassName = $"PropertyInjectionSource_{stableHash}"; var fileName = $"{model.SafeClassName}_PropertyInjection.g.cs"; var sb = new StringBuilder(); @@ -652,7 +657,7 @@ private static void GeneratePropertyInjectionSource(SourceProductionContext cont sb.AppendLine("{"); sb.AppendLine("internal static partial class TUnit_PropertyRegistration"); sb.AppendLine("{"); - sb.AppendLine($"static readonly int _r_{model.SafeClassName}_PropSource = global::TUnit.Core.PropertySourceRegistry.Register(typeof({model.ClassFullyQualifiedName}), new global::TUnit.Core.{sourceClassName}());"); + sb.AppendLine($"static readonly int _r_{model.SafeClassName}_PropSource_{stableHash} = global::TUnit.Core.PropertySourceRegistry.Register(typeof({model.ClassFullyQualifiedName}), new global::TUnit.Core.{sourceClassName}());"); sb.AppendLine("}"); sb.AppendLine("}"); @@ -752,6 +757,7 @@ private static void GeneratePropertyMetadata(StringBuilder sb, PropertyDataSourc private static void GenerateInitializerPropertySource(SourceProductionContext context, AsyncInitializerModel model) { var fileName = $"{model.SafeTypeName}_InitializerProperties.g.cs"; + var stableHash = FileNameHelper.GetStableHashCode(model.TypeFullyQualified).ToString("x8"); var sb = new StringBuilder(); WriteGeneratedFileHeader(sb); @@ -765,7 +771,7 @@ private static void GenerateInitializerPropertySource(SourceProductionContext co // instead of a per-type [ModuleInitializer]. All contributions merge into one .cctor. sb.AppendLine("internal static partial class TUnit_PropertyRegistration"); sb.AppendLine("{"); - sb.AppendLine($" static readonly int _r_{model.SafeTypeName}_InitProps = InitializerPropertyRegistry.Register(typeof({model.TypeFullyQualified}), new InitializerPropertyInfo[]"); + sb.AppendLine($" static readonly int _r_{model.SafeTypeName}_InitProps_{stableHash} = InitializerPropertyRegistry.Register(typeof({model.TypeFullyQualified}), new InitializerPropertyInfo[]"); sb.AppendLine(" {"); foreach (var prop in model.Properties) @@ -790,7 +796,9 @@ private static void GenerateInitializerPropertySource(SourceProductionContext co /// private static void GenerateGenericPropertyInjectionSource(SourceProductionContext context, ConcreteGenericTypeModel model) { - var sourceClassName = $"PropertyInjectionSource_Generic_{Math.Abs(model.ConcreteTypeFullyQualified.GetHashCode()):x}"; + // See GeneratePropertyInjectionSource: deterministic hash disambiguates SafeTypeName collisions. + var stableHash = FileNameHelper.GetStableHashCode(model.ConcreteTypeFullyQualified).ToString("x8"); + var sourceClassName = $"PropertyInjectionSource_Generic_{stableHash}"; var fileName = $"{model.SafeTypeName}_Generic_PropertyInjection.g.cs"; var sb = new StringBuilder(); @@ -864,7 +872,7 @@ private static void GenerateGenericPropertyInjectionSource(SourceProductionConte sb.AppendLine("{"); sb.AppendLine("internal static partial class TUnit_PropertyRegistration"); sb.AppendLine("{"); - sb.AppendLine($"static readonly int _r_{model.SafeTypeName}_Generic_PropSource = global::TUnit.Core.PropertySourceRegistry.Register(typeof({model.ConcreteTypeFullyQualified}), new global::TUnit.Core.{sourceClassName}());"); + sb.AppendLine($"static readonly int _r_{model.SafeTypeName}_Generic_PropSource_{stableHash} = global::TUnit.Core.PropertySourceRegistry.Register(typeof({model.ConcreteTypeFullyQualified}), new global::TUnit.Core.{sourceClassName}());"); sb.AppendLine("}"); sb.AppendLine("}"); @@ -878,6 +886,7 @@ private static void GenerateGenericPropertyInjectionSource(SourceProductionConte private static void GenerateGenericInitializerPropertySource(SourceProductionContext context, ConcreteGenericTypeModel model) { var fileName = $"{model.SafeTypeName}_Generic_InitializerProperties.g.cs"; + var stableHash = FileNameHelper.GetStableHashCode(model.ConcreteTypeFullyQualified).ToString("x8"); var sb = new StringBuilder(); WriteGeneratedFileHeader(sb); @@ -891,7 +900,7 @@ private static void GenerateGenericInitializerPropertySource(SourceProductionCon // instead of a per-type [ModuleInitializer]. All contributions merge into one .cctor. sb.AppendLine("internal static partial class TUnit_PropertyRegistration"); sb.AppendLine("{"); - sb.AppendLine($" static readonly int _r_{model.SafeTypeName}_Generic_InitProps = InitializerPropertyRegistry.Register(typeof({model.ConcreteTypeFullyQualified}), new InitializerPropertyInfo[]"); + sb.AppendLine($" static readonly int _r_{model.SafeTypeName}_Generic_InitProps_{stableHash} = InitializerPropertyRegistry.Register(typeof({model.ConcreteTypeFullyQualified}), new InitializerPropertyInfo[]"); sb.AppendLine(" {"); foreach (var prop in model.InitializerProperties) diff --git a/TUnit.Core.SourceGenerator/Helpers/FileNameHelper.cs b/TUnit.Core.SourceGenerator/Helpers/FileNameHelper.cs index 70987c9cb9b..95b013bdf7d 100644 --- a/TUnit.Core.SourceGenerator/Helpers/FileNameHelper.cs +++ b/TUnit.Core.SourceGenerator/Helpers/FileNameHelper.cs @@ -179,9 +179,11 @@ public static string GetSafeMethodId(IMethodSymbol methodSymbol) /// /// Computes a deterministic hash code for a string (FNV-1a). - /// Unlike string.GetHashCode(), this is stable across processes and platforms. + /// Unlike string.GetHashCode(), this is stable across processes and platforms, + /// so it is safe to bake into generated identifiers and hint names that must stay + /// consistent across compiler restarts (preserving Roslyn's incremental cache). /// - private static uint GetStableHashCode(string str) + public static uint GetStableHashCode(string str) { unchecked { From 55d6a3f569b72669f884b21cc9ed373143dfd8b3 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 28 Jun 2026 12:30:24 +0100 Subject: [PATCH 5/7] fix(sourcegen): wrap AotConverter registration in explicit namespace block Code-review finding B: AotConverterGenerator emitted its converter classes and the TUnit_ConverterRegistration partial under a file-scoped `namespace TUnit.Generated;`. While functionally correct, this diverged from the shell pattern used by InfrastructureGenerator and StaticPropertyInitializationGenerator, which use an explicit `namespace TUnit.Generated { ... }` block. Convert to the block form so the partial reliably merges with the shell and the codebase stays consistent. Finding A (PropertyInjectionSourceGenerator field-name collision) was already resolved in commit 85d1f7f5ae: all four merged-partial field names (_PropSource, _InitProps, and their _Generic variants) already carry a deterministic FileNameHelper.GetStableHashCode suffix. No further change needed. --- .../Generators/AotConverterGenerator.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs b/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs index 453aa936fc8..c0728b4dd08 100644 --- a/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs +++ b/TUnit.Core.SourceGenerator/Generators/AotConverterGenerator.cs @@ -538,8 +538,9 @@ private void GenerateConverters(SourceProductionContext context, EquatableArray< writer.AppendLine("using System;"); writer.AppendLine("using TUnit.Core.Converters;"); writer.AppendLine(); - writer.AppendLine("namespace TUnit.Generated;"); - writer.AppendLine(); + writer.AppendLine("namespace TUnit.Generated"); + writer.AppendLine("{"); + writer.Indent(); var converterIndex = 0; var converterClassNames = new List(); @@ -665,6 +666,9 @@ private void GenerateConverters(SourceProductionContext context, EquatableArray< writer.Unindent(); writer.AppendLine("}"); + writer.Unindent(); + writer.AppendLine("}"); + context.AddSource("AotConverters.g.cs", writer.ToString()); } From 6d378e0874bb73a31ca92c2ab6c60ab1d1fa362e Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 28 Jun 2026 12:58:31 +0100 Subject: [PATCH 6/7] fix(sourcegen): make static property initializer method names FQN-unique The static property initializer method name was built from the simple ContainingType.Name only, while the registration field name already used an FQN-based stable hash. Two types sharing a simple name in different namespaces (e.g. Acme.Tests.MyFixture and Acme.Shared.MyFixture) each with a same-named static property collapsed to ONE generated initializer method (hardcoding the first type's FQN), yet emitted two field registrations both pointing at that single method. The second type's property was then initialized against the wrong type silently. Hoist the per-FQN stable hash into a shared helper and suffix the method name with it, so distinct FQNs generate distinct methods and the field registration references the matching hash-suffixed method name. --- .../StaticPropertyInitializationGenerator.cs | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs index 1606ec71981..f1dbc59e85b 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs @@ -210,10 +210,10 @@ private static string GenerateInitializationCode(EquatableArray(); foreach (var propertyData in staticProperties) { - var methodName = $"Initialize_{propertyData.Property.ContainingType.Name}_{propertyData.Property.Name}"; + var methodName = GetInitializerMethodName(propertyData); if (generatedMethods.Add(methodName)) { - GenerateIndividualPropertyInitializer(writer, propertyData); + GenerateIndividualPropertyInitializer(writer, propertyData, methodName); } } @@ -238,12 +238,12 @@ private static string GenerateInitializationCode(EquatableArray"); From e2bd729e9a768dee58b8c5ad0d2fcc71a378895e Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 28 Jun 2026 13:17:35 +0100 Subject: [PATCH 7/7] refactor(sourcegen): consolidate SafeName into FileNameHelper --- .../StaticPropertyInitializationGenerator.cs | 12 +----------- .../Helpers/FileNameHelper.cs | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs index f1dbc59e85b..cddd8454fa0 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerators/StaticPropertyInitializationGenerator.cs @@ -244,7 +244,7 @@ private static string GenerateInitializationCode(EquatableArray + /// Sanitizes a string into a safe C# identifier fragment by mapping every + /// non-alphanumeric character to '_'. Used for generated field/method names. + /// + public static string SafeName(string value) + { + var sb = new StringBuilder(value.Length); + foreach (var c in value) + { + sb.Append(char.IsLetterOrDigit(c) ? c : '_'); + } + return sb.ToString(); + } + /// /// Sanitizes a string to be safe for use in a filename. /// Replaces invalid characters with underscores.