Skip to content

Commit 13f2faa

Browse files
committed
fix: use modern generated trimming dependencies
- Root generic client constructors from the module initializer. - Emit compatibility attributes only when the consumer needs them. - Remove generated Preserve attributes and refresh snapshots.
1 parent 890c90b commit 13f2faa

80 files changed

Lines changed: 111 additions & 230 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/InterfaceStubGenerator.Shared/Emitter.cs‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,23 +72,24 @@ internal static class Emitter
7272
/// <summary>The XML metacharacters that force <see cref="Emitter.ToXmlDocumentationText"/> onto its escaping path.</summary>
7373
private static readonly char[] XmlEscapeChars = ['&', '<', '>'];
7474

75-
/// <summary>Emits the shared preserve attribute and factory registration code.</summary>
75+
/// <summary>Emits the shared factory registration code and required compatibility attributes.</summary>
7676
/// <param name="model">The context generation model describing the interfaces.</param>
7777
/// <param name="addSource">Callback used to add generated source files.</param>
7878
/// <param name="support">How the registration is hooked to assembly load in the consumer compilation.</param>
79+
/// <param name="needsDynamicDependencyPolyfill">Whether the consumer framework lacks the trimming attribute.</param>
7980
internal static void EmitSharedCode(
8081
ContextGenerationModel model,
8182
Action<string, SourceText> addSource,
82-
ModuleInitializerSupport support = ModuleInitializerSupport.Guarded)
83+
ModuleInitializerSupport support = ModuleInitializerSupport.Guarded,
84+
bool needsDynamicDependencyPolyfill = false)
8385
{
8486
if (model.Interfaces.Length == 0)
8587
{
8688
return;
8789
}
8890

8991
var generatedFileHeader = BuildSharedGeneratedFileHeader(model.Interfaces, model.EmitGeneratedCodeMarkers);
90-
SharedInfrastructureEmission.EmitPreserveAttribute(model, generatedFileHeader, addSource);
91-
SharedInfrastructureEmission.EmitGeneratedFactoryModule(model, generatedFileHeader, addSource, support);
92+
SharedInfrastructureEmission.EmitGeneratedFactoryModule(model, generatedFileHeader, addSource, support, needsDynamicDependencyPolyfill);
9293
}
9394

9495
/// <summary>Emits the generated implementation source for a single interface.</summary>
@@ -144,7 +145,6 @@ internal static void AppendInterfacePrefix(
144145
.Append(" ").Append(GeneratedCodeAttribute).AppendLine()
145146
.AppendLine(" [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]")
146147
.AppendLine(" [global::System.Diagnostics.DebuggerNonUserCode]")
147-
.Append(" [").Append(model.Options.PreserveAttributeDisplayName).AppendLine("]")
148148
.AppendLine(" [global::System.Reflection.Obfuscation(Exclude=true)]")
149149
.AppendLine(" [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]")
150150
.Append(" private sealed class ").Append(model.Names.Ns).Append(model.Names.ClassDeclaration).AppendLine()
@@ -366,6 +366,33 @@ internal static string BuildGeneratedFactoryRegistrations(
366366
return builder.ToString();
367367
}
368368

369+
/// <summary>Keeps constructors used by reflection for open generic clients.</summary>
370+
/// <param name="interfaces">The interfaces to generate implementations for.</param>
371+
/// <returns>Dependencies attached to the reachable module initializer.</returns>
372+
internal static string BuildGeneratedTrimmingDependencies(InterfaceModel[] interfaces)
373+
{
374+
var builder = new PooledStringBuilder();
375+
foreach (var model in interfaces)
376+
{
377+
if (model.Members.Constraints.Length == 0)
378+
{
379+
continue;
380+
}
381+
382+
_ = builder.Append(" [global::System.Diagnostics.CodeAnalysis.DynamicDependency(\".ctor\", typeof(")
383+
.Append(GeneratedNamespacePrefix).Append(model.Names.GeneratedClassName).Append('.')
384+
.Append(model.Names.Ns).Append(model.Names.ClassSuffix).Append('<');
385+
for (var i = 1; i < model.Members.Constraints.Length; i++)
386+
{
387+
_ = builder.Append(',');
388+
}
389+
390+
_ = builder.AppendLine(">))]");
391+
}
392+
393+
return builder.ToString();
394+
}
395+
369396
/// <summary>Builds the settings-only constructor when the generated implementation can avoid request-builder reflection.</summary>
370397
/// <param name="model">The interface model being emitted.</param>
371398
/// <param name="settingsFieldName">The unique generated field name that stores Refit settings.</param>

‎src/InterfaceStubGenerator.Shared/GeneratedTypeNaming.cs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,7 @@ internal static string BuildRefitInternalNamespace(string? refitInternalNamespac
2424
? Parser.RefitInternalGeneratedSuffix
2525
: refitInternalNamespace + Parser.RefitInternalGeneratedSuffix;
2626

27-
// Fold the assembly name in as a trailing segment so the PreserveAttribute this namespace houses no longer
28-
// collides across assemblies linked by [InternalsVisibleTo]. Blank names (unnamed compilations) leave the
29-
// namespace as-is, matching the historical single-assembly output.
27+
// Scope generated helper names to avoid collisions across assemblies linked by [InternalsVisibleTo].
3028
var assemblyScope = SanitizeAssemblyScope(assemblyName);
3129
var rawNamespace = assemblyScope.Length == 0
3230
? prefixedNamespace

‎src/InterfaceStubGenerator.Shared/InlineRequestClassification.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ internal static RequestModel ClassifyRequest(
8484
analysisOptions?.CancellationToken.ThrowIfCancellationRequested();
8585
var context = new InterfaceGenerationContext(
8686
[],
87-
new GenerationOptionsModel(string.Empty, string.Empty, analysisOptions?.GeneratedRequestBuilding ?? true, false),
87+
new GenerationOptionsModel(string.Empty, analysisOptions?.GeneratedRequestBuilding ?? true, false),
8888
new GenerationSymbolsModel(null, httpMethodBaseAttributeSymbol, formattableSymbol, null, null, returnTypeAdapterInterface, returnTypeAdapters, indexedCollectionFormatValue),
8989
new GenerationCapabilitiesModel(false, false, false, false),
9090
new GenerationCachesModel([], [with(SymbolEqualityComparer.Default)], [with(SymbolEqualityComparer.Default)], [with(SymbolEqualityComparer.Default)]));

‎src/InterfaceStubGenerator.Shared/InterfaceSemanticParsing.cs‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -105,17 +105,16 @@ internal static ContextGenerationModel ApplyGeneratorOptions(
105105
{
106106
if (options.DisableSourceGenerator)
107107
{
108-
return new(string.Empty, string.Empty, string.Empty, false, true, []);
108+
return new(string.Empty, string.Empty, false, true, []);
109109
}
110110

111111
var internalNamespace = GeneratedTypeNaming.BuildRefitInternalNamespace(options.RefitInternalNamespace, assemblyName);
112112
var generatedClassName = GeneratedTypeNaming.BuildGeneratedContainerName(assemblyName);
113113
if (models.Length == 0)
114114
{
115-
return new(internalNamespace, string.Empty, generatedClassName, options.GeneratedRequestBuilding, options.EmitGeneratedCodeMarkers, []);
115+
return new(internalNamespace, generatedClassName, options.GeneratedRequestBuilding, options.EmitGeneratedCodeMarkers, []);
116116
}
117117

118-
var preserveAttribute = $"global::{internalNamespace}.PreserveAttribute";
119118
var interfaces = new InterfaceModel[models.Length];
120119
Dictionary<string, int> keyCount = [with(StringComparer.OrdinalIgnoreCase)];
121120
for (var i = 0; i < models.Length; i++)
@@ -134,7 +133,6 @@ internal static ContextGenerationModel ApplyGeneratorOptions(
134133
FileName = $"{keyName}.g.cs",
135134
Options = model.Options with
136135
{
137-
PreserveAttributeDisplayName = preserveAttribute,
138136
GeneratedRequestBuilding = options.GeneratedRequestBuilding,
139137
EmitGeneratedCodeMarkers = options.EmitGeneratedCodeMarkers
140138
},
@@ -150,7 +148,6 @@ internal static ContextGenerationModel ApplyGeneratorOptions(
150148

151149
return new(
152150
internalNamespace,
153-
preserveAttribute,
154151
generatedClassName,
155152
options.GeneratedRequestBuilding,
156153
options.EmitGeneratedCodeMarkers,
@@ -239,11 +236,9 @@ private static InterfaceModel[] ParseSyntaxTree(
239236
CancellationToken cancellationToken)
240237
{
241238
var compilation = (CSharpCompilation)semanticModel.Compilation;
242-
var internalNamespace = GeneratedTypeNaming.BuildRefitInternalNamespace(null, compilation.AssemblyName);
243239
var context = Parser.CreateGenerationContext(
244240
compilation,
245241
[],
246-
internalNamespace,
247242
attribute,
248243
true,
249244
true,

‎src/InterfaceStubGenerator.Shared/InterfaceStubGeneratorV2.cs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,15 @@ public void Initialize(
112112

113113
var moduleInitializerSupport = context.CompilationProvider.Select(static (compilation, _) =>
114114
DetectModuleInitializerSupport(compilation));
115+
var needsDynamicDependencyPolyfill = context.CompilationProvider.Select(static (compilation, _) =>
116+
{
117+
var attribute = compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.DynamicDependencyAttribute");
118+
return attribute is null || !compilation.IsSymbolAccessibleWithin(attribute, compilation.Assembly);
119+
});
115120

116121
context.RegisterImplementationSourceOutput(
117-
contextModel.Combine(moduleInitializerSupport),
118-
static (spc, combined) => Emitter.EmitSharedCode(combined.Left, spc.AddSource, combined.Right));
122+
contextModel.Combine(moduleInitializerSupport).Combine(needsDynamicDependencyPolyfill),
123+
static (spc, combined) => Emitter.EmitSharedCode(combined.Left.Left, spc.AddSource, combined.Left.Right, combined.Right));
119124
}
120125

121126
/// <summary>Decides how the generated factory registration can be hooked to assembly load in a compilation.</summary>

‎src/InterfaceStubGenerator.Shared/Models/ContextGenerationModel.cs‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,12 @@ namespace Refit.Generator;
66

77
/// <summary>Model describing the shared generation context for a set of Refit interfaces.</summary>
88
/// <param name="RefitInternalNamespace">The namespace used for Refit internal generated types.</param>
9-
/// <param name="PreserveAttributeDisplayName">The display name of the preserve attribute.</param>
109
/// <param name="GeneratedClassName">The assembly-scoped name of the generated implementation container type.</param>
1110
/// <param name="GeneratedRequestBuilding">Whether generated request construction is enabled.</param>
1211
/// <param name="EmitGeneratedCodeMarkers">Whether generated files include generated-code analyzer skip markers.</param>
1312
/// <param name="Interfaces">The interfaces to generate implementations for.</param>
1413
internal sealed record ContextGenerationModel(
1514
string RefitInternalNamespace,
16-
string PreserveAttributeDisplayName,
1715
string GeneratedClassName,
1816
bool GeneratedRequestBuilding,
1917
bool EmitGeneratedCodeMarkers,
@@ -27,9 +25,6 @@ other is not null
2725
&& EqualityComparer<string>.Default.Equals(
2826
RefitInternalNamespace,
2927
other.RefitInternalNamespace)
30-
&& EqualityComparer<string>.Default.Equals(
31-
PreserveAttributeDisplayName,
32-
other.PreserveAttributeDisplayName)
3328
&& EqualityComparer<string>.Default.Equals(
3429
GeneratedClassName,
3530
other.GeneratedClassName)
@@ -46,7 +41,6 @@ public override int GetHashCode()
4641
{
4742
var hash = 0;
4843
hash = GeneratorModelEquality.Combine(hash, GeneratorModelEquality.GetHashCode(RefitInternalNamespace));
49-
hash = GeneratorModelEquality.Combine(hash, GeneratorModelEquality.GetHashCode(PreserveAttributeDisplayName));
5044
hash = GeneratorModelEquality.Combine(hash, GeneratorModelEquality.GetHashCode(GeneratedClassName));
5145
hash = GeneratorModelEquality.Combine(hash, GeneratorModelEquality.GetHashCode(GeneratedRequestBuilding));
5246
hash = GeneratorModelEquality.Combine(hash, GeneratorModelEquality.GetHashCode(EmitGeneratedCodeMarkers));

‎src/InterfaceStubGenerator.Shared/Models/GenerationOptionsModel.cs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,10 @@
55
namespace Refit.Generator;
66

77
/// <summary>Describes the consumer's generated source options.</summary>
8-
/// <param name="PreserveAttributeDisplayName">The display name of the generated preserve attribute.</param>
98
/// <param name="GeneratedClassName">The assembly-scoped name of the generated implementation container type.</param>
109
/// <param name="GeneratedRequestBuilding">Whether generated request construction is enabled.</param>
1110
/// <param name="EmitGeneratedCodeMarkers">Whether generated files include generated-code analyzer skip markers.</param>
1211
internal readonly record struct GenerationOptionsModel(
13-
string PreserveAttributeDisplayName,
1412
string GeneratedClassName,
1513
bool GeneratedRequestBuilding,
1614
bool EmitGeneratedCodeMarkers);

‎src/InterfaceStubGenerator.Shared/Models/InterfaceOptionsModel.cs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,13 @@
55
namespace Refit.Generator;
66

77
/// <summary>Describes the interface's options metadata.</summary>
8-
/// <param name="PreserveAttributeDisplayName">The display name of the Preserve attribute.</param>
98
/// <param name="GeneratedRequestBuilding">Whether generated request construction is enabled for this interface.</param>
109
/// <param name="EmitGeneratedCodeMarkers">Whether generated files include generated-code analyzer skip markers.</param>
1110
/// <param name="SupportsNullable">Whether the consumer compilation supports nullable reference type syntax.</param>
1211
/// <param name="SupportsStaticLambdas">Whether the consumer compilation supports the <c>static</c> lambda modifier (C# 9).</param>
1312
/// <param name="SupportsCollectionExpressions">Whether the consumer compilation supports collection expressions (C# 12),
1413
/// so path replacements can be passed as a stack-allocatable <c>[...]</c> span instead of an array.</param>
1514
internal readonly record struct InterfaceOptionsModel(
16-
string PreserveAttributeDisplayName,
1715
bool GeneratedRequestBuilding,
1816
bool EmitGeneratedCodeMarkers,
1917
bool SupportsNullable,

‎src/InterfaceStubGenerator.Shared/Parser.cs‎

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ internal static (
8787
var context = CreateGenerationContext(
8888
compilation,
8989
diagnostics,
90-
refitInternalNamespace,
9190
httpMethodBaseAttributeSymbol,
9291
generatedRequestBuilding,
9392
emitGeneratedCodeMarkers,
@@ -101,7 +100,6 @@ internal static (
101100

102101
var contextGenerationSpec = new ContextGenerationModel(
103102
refitInternalNamespace,
104-
context.Options.PreserveAttributeDisplayName,
105103
generatedClassName,
106104
generatedRequestBuilding,
107105
emitGeneratedCodeMarkers,
@@ -126,7 +124,6 @@ internal static (List<Diagnostic> Diagnostics, ContextGenerationModel ContextGen
126124
diagnostics,
127125
new(
128126
refitInternalNamespace,
129-
string.Empty,
130127
generatedClassName,
131128
generatedRequestBuilding,
132129
emitGeneratedCodeMarkers,
@@ -136,7 +133,6 @@ internal static (List<Diagnostic> Diagnostics, ContextGenerationModel ContextGen
136133
/// <summary>Resolves the well-known symbols and language capabilities used throughout a single generation pass.</summary>
137134
/// <param name="compilation">The compilation.</param>
138135
/// <param name="diagnostics">The list that collects diagnostics produced during processing.</param>
139-
/// <param name="refitInternalNamespace">The resolved internal generated namespace.</param>
140136
/// <param name="httpMethodBaseAttributeSymbol">The resolved Refit HTTP method attribute symbol.</param>
141137
/// <param name="generatedRequestBuilding">Whether generated request construction is enabled.</param>
142138
/// <param name="emitGeneratedCodeMarkers">Whether generated files include generated-code analyzer skip markers.</param>
@@ -145,7 +141,6 @@ internal static (List<Diagnostic> Diagnostics, ContextGenerationModel ContextGen
145141
internal static InterfaceGenerationContext CreateGenerationContext(
146142
CSharpCompilation compilation,
147143
List<Diagnostic> diagnostics,
148-
string refitInternalNamespace,
149144
INamedTypeSymbol httpMethodBaseAttributeSymbol,
150145
bool generatedRequestBuilding,
151146
bool emitGeneratedCodeMarkers,
@@ -167,13 +162,6 @@ internal static InterfaceGenerationContext CreateGenerationContext(
167162
var supportsNullable = options.LanguageVersion >= LanguageVersion.CSharp8;
168163
var supportsStaticLambdas = options.LanguageVersion >= LanguageVersion.CSharp9;
169164

170-
// The PreserveAttribute is emitted into the consumer's compilation by the emitter
171-
// (see Emitter.EmitSharedCode). Its fully-qualified display name is fully determined
172-
// by refitInternalNamespace, so we compute it directly instead of round-tripping
173-
// through compilation.AddSyntaxTrees + GetTypeByMetadataName + ToDisplayString on
174-
// every generator pass, which mutated the compilation and forced an extra bind.
175-
var preserveAttributeDisplayName = $"global::{refitInternalNamespace}.PreserveAttribute";
176-
177165
// The generated implementation container folds in the assembly name so each assembly emits a distinctly named
178166
// container; UniqueName reconstructs the identical name at runtime for reflection-based resolution.
179167
var generatedClassName = GeneratedTypeNaming.BuildGeneratedContainerName(compilation.AssemblyName);
@@ -185,7 +173,7 @@ internal static InterfaceGenerationContext CreateGenerationContext(
185173

186174
return new(
187175
diagnostics,
188-
new GenerationOptionsModel(preserveAttributeDisplayName, generatedClassName, generatedRequestBuilding, emitGeneratedCodeMarkers),
176+
new GenerationOptionsModel(generatedClassName, generatedRequestBuilding, emitGeneratedCodeMarkers),
189177
new GenerationSymbolsModel(
190178
disposableInterfaceSymbol,
191179
httpMethodBaseAttributeSymbol,
@@ -394,7 +382,6 @@ internal static InterfaceModel ProcessInterface(
394382
names.InterfaceDisplayName,
395383
names.ClassSuffix),
396384
new InterfaceOptionsModel(
397-
context.Options.PreserveAttributeDisplayName,
398385
context.Options.GeneratedRequestBuilding,
399386
context.Options.EmitGeneratedCodeMarkers,
400387
context.Capabilities.SupportsNullable,

0 commit comments

Comments
 (0)
⌂ 换网址