Skip to content

Commit 6fe0714

Browse files
kzuclaudecodealta-agent
committed
Report ST009 and ST023 for constructors and assembly registrations
UnsafeSignatureAnalyzer only looked at the overridable and interface members of the stunts asked for by a call, so two paths still failed inside generated code with no Stunts diagnostic: - A compile-time stunt intercepts each accessible constructor of its base class, with the same holders and unsafe code as a method. The analyzer now walks those constructors, unless compile-time stunts are explicitly off: run-time stunts do not intercept constructors. - A stunt asked for with [assembly: Stunt<T>] was never analyzed. The registration attributes of the assembly are now analyzed too, and the diagnostic is reported at the attribute. The check that recognizes the attribute moves to SymbolExtensions.IsRegistrationAttribute, shared with the generator. Delegate stunts are left out on purpose: DelegateScaffold passes the arguments of Invoke to MethodInvocation.Create without holders, so a ref struct in a delegate signature fails with CS9244 under any setting, and the fixes ST009 and ST023 name would not help. With registrations covered, the ST015 warning about ref structs repeats ST023, an error: it is removed with its cache flag, its rows in the docs, and the by-ref-like generics input of the fingerprint, which only that check read. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Co-authored-by: CodeAlta <noreply@codealta.io>
1 parent 26ea406 commit 6fe0714

12 files changed

Lines changed: 232 additions & 71 deletions

File tree

‎AGENTS.md‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -207,15 +207,22 @@ fallbacks. Static constructors do not count as available instance constructors d
207207
`ST014` (from `Stunts.targets`) warns when those are set without compile-time stunts; `ST015`
208208
warns about generic intercepted methods and queryable defaults. Ref-struct holders are emitted only
209209
when the target runtime supports by-ref-like generics and the language version is C# 13 or later
210-
(`allows ref struct`). `RefStructHolders` is that condition, for `SignatureRefGenerator`,
211-
`CSharpAot` (the `ST015` about ref structs) and `UnsafeSignatureAnalyzer`, which reports `ST023`
212-
at the call when a ref-struct signature has no holders. It reads the version from the
213-
`ParseOptions` by reflection, since `Stunts.CodeAnalysis` cannot reference the C# compiler
214-
assembly (`RS1038`).
210+
(`allows ref struct`). `RefStructHolders` is that condition, for `SignatureRefGenerator` and
211+
`UnsafeSignatureAnalyzer`, which reports `ST023` when a ref-struct signature has no holders. It
212+
reads the version from the `ParseOptions` by reflection, since `Stunts.CodeAnalysis` cannot
213+
reference the C# compiler assembly (`RS1038`).
215214
Native AOT coverage includes .NET 8 and .NET 10.
216215
Keep the netstandard2.0 runtime for analyzer hosts and legacy consumers, and ship the net8.0
217216
runtime for Native AOT consumers.
218217

218+
`UnsafeSignatureAnalyzer` reports `ST009` and `ST023` where a stunt is asked for: a call to a
219+
generator method, or a registration attribute of the assembly (`SymbolExtensions.IsRegistrationAttribute`,
220+
shared with the generator). It walks what the generator intercepts: overridable and interface
221+
members, and for compile-time stunts the accessible constructors of the base class (run-time
222+
stunts do not intercept constructors). Delegate stunts are left out: `DelegateScaffold` passes the
223+
arguments of `Invoke` to `MethodInvocation.Create` without holders, so a ref struct or pointer in
224+
a delegate signature does not compile under any setting.
225+
219226
Visual Basic only supports run-time stunts: `Stunts.targets` forces `EnableCompileTimeStunts`
220227
to false for VB and warns (`ST011`) unless Stunts.DynamicProxy is installed. `GenericWrapperAnalyzer`
221228
is C#-only and is skipped when `EnableCompileTimeStunts` is explicitly false.
@@ -269,7 +276,7 @@ for 7.
269276
`StuntFingerprint` keys hash the compilation-wide inputs processors read (generator
270277
configuration, each processor's `IConfiguredSyntaxProcessor.Configuration` (such as the
271278
`DefaultImports` namespaces), language version, nullable,
272-
unsafe and metadata import options, pretty-printing, by-ref-like generics support, the corlib
279+
unsafe and metadata import options, pretty-printing, the corlib
273280
identity, and the accessibility of the optional attributes the generated code uses, looked up
274281
in the compilation the stunt binds against: the treeless one for metadata-only stunts), plus
275282
each candidate type's declaration: attributes, containers, base types, interfaces, and every

‎docs/guide/aot.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,9 @@ in ordinary builds, so you see them before publishing:
3636
| --- | --- | --- |
3737
| `ST014` | Run-time proxies require dynamic code | Enable compile-time stunts |
3838
| `ST015` | Generic intercepted methods use run-time `MakeGenericMethod` | Use non-generic members with closed parameter and return types |
39-
| `ST015` | Ref-struct interception needs by-ref-like generics | Target .NET 9 or later, with C# 13 or later |
4039
| `ST015` | `IQueryable` defaults require dynamic code | Register an AOT-compatible typed `DefaultValueProvider` factory, or avoid `DefaultValueBehavior` for that member |
4140

42-
Ref-struct holders need .NET 9 and C# 13 or later, and ref-struct and pointer signatures need unsafe blocks.
41+
Ref-struct signatures need .NET 9 and C# 13 or later (`ST023`), and ref-struct and pointer signatures need unsafe blocks (`ST009`).
4342

4443
## Stunts the generator can't see
4544

‎docs/guide/generation.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ spans and other ref structs, default interface members, events, indexers, and ne
2727
Ref-struct and pointer signatures need `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>` (`ST009`).
2828
Ref-struct signatures also need .NET 9 and C# 13 or later (`ST023`).
2929

30-
What can't be proxied is reported at the call that asks for it: see [Diagnostics](diagnostics.md).
30+
What can't be proxied is reported at the call or the `[assembly: Stunt<T>]` attribute that asks
31+
for it: see [Diagnostics](diagnostics.md).
3132
Internal interface members are supported when the stunt is in the same assembly, or in a friend
3233
assembly through `InternalsVisibleTo`.
3334

‎readme.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,6 @@ Set `<PublishAot>true</PublishAot>` to publish a native executable. `IsAotCompat
260260
| --- | --- | --- |
261261
| `ST014` | Runtime proxies require dynamic code | Enable compile-time stunts |
262262
| `ST015` | Generic intercepted methods use runtime `MakeGenericMethod` | Use non-generic members with closed parameter and return types |
263-
| `ST015` | Ref-struct interception needs by-ref-like generics | Target .NET 9 or later, with C# 13 or later |
264263
| `ST015` | `IQueryable` defaults require dynamic code | Register an AOT-compatible typed `DefaultValueProvider` factory, or avoid `DefaultValueBehavior` for that member |
265264

266265
Generated stunts register typed constructors from a module initializer, so they are created

‎src/Stunts.CodeAnalysis/SymbolExtensions.cs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,22 @@ static void CollectSymbols(INamedTypeSymbol symbol, HashSet<INamedTypeSymbol> se
5555
}
5656
}
5757

58+
/// <summary>
59+
/// Whether the attribute class is the given registration attribute, such as
60+
/// <see cref="StuntAttribute{T}"/>, with any number of type arguments.
61+
/// </summary>
62+
public static bool IsRegistrationAttribute(this INamedTypeSymbol type, Type registrationAttribute)
63+
{
64+
var name = registrationAttribute.Name;
65+
var tick = name.IndexOf('`');
66+
if (tick > 0)
67+
name = name.Substring(0, tick);
68+
69+
return type.Name == name &&
70+
type.ContainingType == null &&
71+
type.ContainingNamespace.ToDisplayString() == registrationAttribute.Namespace;
72+
}
73+
5874
/// <summary>
5975
/// Sorts and validates types so that the base class is the first and the remaining
6076
/// interface implementations are the rest.

‎src/Stunts.CodeAnalysis/UnsafeSignatureAnalyzer.cs‎

Lines changed: 74 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,32 @@ namespace Stunts
1515
/// version or the runtime lacks the ref-struct holders (<see cref="RefStructHolders"/>).
1616
/// The generated code does not compile in those cases.
1717
/// </summary>
18+
/// <remarks>
19+
/// It analyzes the stunts the generator creates: those of the calls to generator methods
20+
/// and those of the registration attributes of the assembly.
21+
/// </remarks>
1822
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
1923
public class UnsafeSignatureAnalyzer : DiagnosticAnalyzer
2024
{
2125
readonly Type generatorAttribute;
26+
readonly Type registrationAttribute;
2227

2328
/// <summary>
24-
/// Instantiates the analyzer for invocations annotated with <see cref="StuntGeneratorAttribute"/>.
29+
/// Instantiates the analyzer for invocations annotated with <see cref="StuntGeneratorAttribute"/>
30+
/// and registrations with <see cref="StuntAttribute{T}"/>.
2531
/// </summary>
2632
public UnsafeSignatureAnalyzer() : this(typeof(StuntGeneratorAttribute)) { }
2733

2834
/// <summary>
2935
/// Customizes the analyzer by specifying a custom generator attribute.
3036
/// </summary>
31-
protected UnsafeSignatureAnalyzer(Type generatorAttribute)
32-
=> this.generatorAttribute = generatorAttribute;
37+
protected UnsafeSignatureAnalyzer(Type generatorAttribute) : this(generatorAttribute, typeof(StuntAttribute<>)) { }
38+
39+
/// <summary>
40+
/// Customizes the analyzer by specifying custom generator and registration attributes.
41+
/// </summary>
42+
protected UnsafeSignatureAnalyzer(Type generatorAttribute, Type registrationAttribute)
43+
=> (this.generatorAttribute, this.registrationAttribute) = (generatorAttribute, registrationAttribute);
3344

3445
/// <inheritdoc/>
3546
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
@@ -42,47 +53,76 @@ public override void Initialize(AnalysisContext context)
4253
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
4354
context.RegisterCompilationStartAction(start =>
4455
{
45-
if (StuntClosure.Create(start.Compilation, generatorAttribute) is StuntClosure closure)
46-
start.RegisterOperationAction(operation => AnalyzeOperation(operation, closure), OperationKind.Invocation);
56+
if (StuntClosure.Create(start.Compilation, generatorAttribute) is not StuntClosure closure)
57+
return;
58+
59+
start.RegisterOperationAction(operation => AnalyzeInvocation(operation, closure), OperationKind.Invocation);
60+
start.RegisterSemanticModelAction(AnalyzeRegistrations);
4761
});
4862
}
4963

50-
void AnalyzeOperation(OperationAnalysisContext context, StuntClosure closure)
64+
void AnalyzeInvocation(OperationAnalysisContext context, StuntClosure closure)
5165
{
5266
var invocation = (IInvocationOperation)context.Operation;
53-
if (!closure.IsGenerator(invocation.TargetMethod))
54-
return;
67+
if (closure.IsGenerator(invocation.TargetMethod))
68+
Analyze(
69+
closure.Close(invocation.TargetMethod, context.CancellationToken).SelectMany(stuntDefinition => stuntDefinition.Types),
70+
invocation.Syntax, context.Compilation, context.Options, context.ReportDiagnostic);
71+
}
72+
73+
// The stunts asked for with the registration attribute, as in [assembly: Stunt<T>].
74+
void AnalyzeRegistrations(SemanticModelAnalysisContext context)
75+
{
76+
var compilation = context.SemanticModel.Compilation;
77+
foreach (var attribute in compilation.Assembly.GetAttributes())
78+
{
79+
if (attribute.ApplicationSyntaxReference is SyntaxReference reference &&
80+
reference.SyntaxTree == context.SemanticModel.SyntaxTree &&
81+
attribute.AttributeClass is { IsGenericType: true } type &&
82+
type.IsRegistrationAttribute(registrationAttribute))
83+
Analyze(type.TypeArguments, reference.GetSyntax(context.CancellationToken), compilation, context.Options, context.ReportDiagnostic);
84+
}
85+
}
5586

56-
var unsafeOff = !BuildProperties.CompileTimeStuntsAndUnsafe(context.Options.AnalyzerConfigOptionsProvider.GlobalOptions);
87+
// Reports at the source that asks for a stunt of the given types.
88+
static void Analyze(IEnumerable<ITypeSymbol> stuntTypes, SyntaxNode source, Compilation compilation, AnalyzerOptions options, Action<Diagnostic> report)
89+
{
90+
var global = options.AnalyzerConfigOptionsProvider.GlobalOptions;
91+
var unsafeOff = !BuildProperties.CompileTimeStuntsAndUnsafe(global);
5792
// Visual Basic only has run-time stunts, which the unsafe check already reports.
58-
var holders = invocation.Language == LanguageNames.CSharp
59-
? HoldersFix(context.Compilation, invocation.Syntax.SyntaxTree.Options) : null;
93+
var holders = source.Language == LanguageNames.CSharp
94+
? HoldersFix(compilation, source.SyntaxTree.Options) : null;
6095
if (!unsafeOff && holders == null)
6196
return;
6297

63-
var types = closure.Close(invocation.TargetMethod, context.CancellationToken)
64-
.SelectMany(stuntDefinition => stuntDefinition.Types)
98+
var types = stuntTypes
6599
.Distinct(SymbolEqualityComparer.Default)
66100
.OfType<INamedTypeSymbol>()
67101
.Where(type => type.TypeKind != TypeKind.Error)
68102
.ToList();
103+
// Run-time stunts do not intercept constructors.
104+
var constructors = !BuildProperties.CompileTimeStuntsDisabled(global);
69105

70-
if (unsafeOff && Find(types, context.Compilation.Assembly, IsUnsafe) is ISymbol member)
71-
context.ReportDiagnostic(Diagnostic.Create(
106+
if (unsafeOff && Find(types, compilation.Assembly, constructors, IsUnsafe) is ISymbol member)
107+
report(Diagnostic.Create(
72108
StuntDiagnostics.UnsafeSignature,
73-
invocation.Syntax.GetLocation(),
109+
source.GetLocation(),
74110
member.ContainingType.Name,
75-
member.Name));
111+
Name(member)));
76112

77-
if (holders != null && Find(types, context.Compilation.Assembly, type => type.IsRefLikeType) is ISymbol held)
78-
context.ReportDiagnostic(Diagnostic.Create(
113+
if (holders != null && Find(types, compilation.Assembly, constructors, type => type.IsRefLikeType) is ISymbol held)
114+
report(Diagnostic.Create(
79115
StuntDiagnostics.RefStructSignature,
80-
invocation.Syntax.GetLocation(),
116+
source.GetLocation(),
81117
held.ContainingType.Name,
82-
held.Name,
118+
Name(held),
83119
holders));
84120
}
85121

122+
// A constructor has the name of its type, as it is written.
123+
static string Name(ISymbol member)
124+
=> member is IMethodSymbol { MethodKind: MethodKind.Constructor } ? member.ContainingType.Name : member.Name;
125+
86126
// What to change for the ref-struct holders to exist, or null when they are supported.
87127
static string? HoldersFix(Compilation compilation, ParseOptions parseOptions)
88128
=> (RefStructHolders.SupportedByRuntime(compilation), RefStructHolders.SupportedByLanguage(parseOptions)) switch
@@ -94,11 +134,16 @@ void AnalyzeOperation(OperationAnalysisContext context, StuntClosure closure)
94134
};
95135

96136
// The first intercepted member with a type in its signature that matches.
97-
static ISymbol? Find(IEnumerable<INamedTypeSymbol> types, IAssemblySymbol assembly, Func<ITypeSymbol, bool> matches)
98-
=> types.Select(type => Find(type, assembly, matches)).FirstOrDefault(member => member != null);
137+
static ISymbol? Find(IEnumerable<INamedTypeSymbol> types, IAssemblySymbol assembly, bool constructors, Func<ITypeSymbol, bool> matches)
138+
=> types.Select(type => Find(type, assembly, constructors, matches)).FirstOrDefault(member => member != null);
99139

100-
static ISymbol? Find(INamedTypeSymbol type, IAssemblySymbol assembly, Func<ITypeSymbol, bool> matches)
140+
static ISymbol? Find(INamedTypeSymbol type, IAssemblySymbol assembly, bool constructors, Func<ITypeSymbol, bool> matches)
101141
{
142+
// A delegate stunt does not pass a ref struct or pointer through the pipeline: no
143+
// build property or language version makes its generated code compile.
144+
if (type.TypeKind == TypeKind.Delegate)
145+
return null;
146+
102147
if (type.TypeKind == TypeKind.Interface)
103148
{
104149
foreach (var current in new[] { type }.Concat(type.AllInterfaces))
@@ -127,6 +172,11 @@ void AnalyzeOperation(OperationAnalysisContext context, StuntClosure closure)
127172
}
128173
}
129174

175+
// A compile-time stunt intercepts each accessible constructor of its base class.
176+
if (constructors && type.InstanceConstructors.FirstOrDefault(constructor =>
177+
Accessible(constructor, assembly) && Uses(constructor, matches)) is IMethodSymbol intercepted)
178+
return intercepted;
179+
130180
foreach (var iface in type.AllInterfaces)
131181
{
132182
foreach (var member in iface.GetMembers())

‎src/Stunts.CompiledProxy/Processors/CSharpAot.cs‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,9 +114,6 @@ type.TypeKind is TypeKind.Pointer or TypeKind.FunctionPointer or TypeKind.TypePa
114114
.WithBody(Block(registrations)));
115115
if (usesQueryable)
116116
updated = updated.WithAdditionalAnnotations(new SyntaxAnnotation("Stunts.AotQueryable"));
117-
if (!RefStructHolders.Supported(context.Compilation, context.ParseOptions) &&
118-
symbol.GetMembers().OfType<IMethodSymbol>().Any(method => method.ReturnType.IsRefLikeType || method.Parameters.Any(parameter => parameter.Type.IsRefLikeType)))
119-
updated = updated.WithAdditionalAnnotations(new SyntaxAnnotation("Stunts.AotRefStruct"));
120117
return unit.ReplaceNode(declaration, updated);
121118
}
122119

‎src/Stunts.CompiledProxy/StuntCache.cs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ enum StuntCacheFlags
2020
NoConstructor = 2,
2121
GenericMethods = 4,
2222
AotQueryable = 8,
23-
AotRefStruct = 16,
2423
}
2524

2625
/// <summary>A cached generation result.</summary>

‎src/Stunts.CompiledProxy/StuntFingerprint.cs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ static string Describe(ISyntaxProcessor processor) => processor is IConfiguredSy
9999
: processor.GetType().FullName!;
100100

101101
// The inputs every stunt of a compilation shares: the generator configuration, the
102-
// language and runtime features the processors check, and the target framework.
102+
// language features the processors check, and the target framework.
103103
static string Environment(ProcessorContext context, StuntGenerator generator, IEnumerable<ISyntaxProcessor> processors, NamingConvention naming, bool pretty)
104104
{
105105
var compilation = context.Compilation;
@@ -116,7 +116,6 @@ static string Environment(ProcessorContext context, StuntGenerator generator, IE
116116
.Append(compilation.Options.MetadataImportOptions).Append('|')
117117
.Append((compilation.Options as CSharpCompilationOptions)?.AllowUnsafe).Append('|')
118118
.Append(pretty).Append('|')
119-
.Append(compilation.SupportsRuntimeCapability(RuntimeCapability.ByRefLikeGenerics)).Append('|')
120119
.Append(compilation.GetSpecialType(SpecialType.System_Object).ContainingAssembly?.Identity.GetDisplayName()).Append('|');
121120

122121
return builder.ToString();

0 commit comments

Comments
 (0)