From ee28515cd2825a1a1efb412b8e3d9c2466a0e8f9 Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Sun, 29 Nov 2026 01:45:31 -0300 Subject: [PATCH] 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] 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 Co-authored-by: CodeAlta --- AGENTS.md | 19 ++- docs/guide/aot.md | 3 +- docs/guide/generation.md | 3 +- readme.md | 1 - src/Stunts.CodeAnalysis/SymbolExtensions.cs | 16 +++ .../UnsafeSignatureAnalyzer.cs | 98 ++++++++++---- .../Processors/CSharpAot.cs | 3 - src/Stunts.CompiledProxy/StuntCache.cs | 1 - src/Stunts.CompiledProxy/StuntFingerprint.cs | 3 +- src/Stunts.CompiledProxy/StuntGenerator.cs | 18 +-- .../CodeAnalysis/ST009_UnsafeSignature.cs | 124 ++++++++++++++++++ src/Stunts.UnitTests/StuntGeneratorTests.cs | 14 -- 12 files changed, 232 insertions(+), 71 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 43cf23b..0585b81 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -207,15 +207,22 @@ fallbacks. Static constructors do not count as available instance constructors d `ST014` (from `Stunts.targets`) warns when those are set without compile-time stunts; `ST015` warns about generic intercepted methods and queryable defaults. Ref-struct holders are emitted only when the target runtime supports by-ref-like generics and the language version is C# 13 or later -(`allows ref struct`). `RefStructHolders` is that condition, for `SignatureRefGenerator`, -`CSharpAot` (the `ST015` about ref structs) and `UnsafeSignatureAnalyzer`, which reports `ST023` -at the call when a ref-struct signature has no holders. It reads the version from the -`ParseOptions` by reflection, since `Stunts.CodeAnalysis` cannot reference the C# compiler -assembly (`RS1038`). +(`allows ref struct`). `RefStructHolders` is that condition, for `SignatureRefGenerator` and +`UnsafeSignatureAnalyzer`, which reports `ST023` when a ref-struct signature has no holders. It +reads the version from the `ParseOptions` by reflection, since `Stunts.CodeAnalysis` cannot +reference the C# compiler assembly (`RS1038`). Native AOT coverage includes .NET 8 and .NET 10. Keep the netstandard2.0 runtime for analyzer hosts and legacy consumers, and ship the net8.0 runtime for Native AOT consumers. +`UnsafeSignatureAnalyzer` reports `ST009` and `ST023` where a stunt is asked for: a call to a +generator method, or a registration attribute of the assembly (`SymbolExtensions.IsRegistrationAttribute`, +shared with the generator). It walks what the generator intercepts: overridable and interface +members, and for compile-time stunts the accessible constructors of the base class (run-time +stunts do not intercept constructors). Delegate stunts are left out: `DelegateScaffold` passes the +arguments of `Invoke` to `MethodInvocation.Create` without holders, so a ref struct or pointer in +a delegate signature does not compile under any setting. + Visual Basic only supports run-time stunts: `Stunts.targets` forces `EnableCompileTimeStunts` to false for VB and warns (`ST011`) unless Stunts.DynamicProxy is installed. `GenericWrapperAnalyzer` is C#-only and is skipped when `EnableCompileTimeStunts` is explicitly false. @@ -269,7 +276,7 @@ for 7. `StuntFingerprint` keys hash the compilation-wide inputs processors read (generator configuration, each processor's `IConfiguredSyntaxProcessor.Configuration` (such as the `DefaultImports` namespaces), language version, nullable, -unsafe and metadata import options, pretty-printing, by-ref-like generics support, the corlib +unsafe and metadata import options, pretty-printing, the corlib identity, and the accessibility of the optional attributes the generated code uses, looked up in the compilation the stunt binds against: the treeless one for metadata-only stunts), plus each candidate type's declaration: attributes, containers, base types, interfaces, and every diff --git a/docs/guide/aot.md b/docs/guide/aot.md index 281d671..ae10795 100644 --- a/docs/guide/aot.md +++ b/docs/guide/aot.md @@ -36,10 +36,9 @@ in ordinary builds, so you see them before publishing: | --- | --- | --- | | `ST014` | Run-time proxies require dynamic code | Enable compile-time stunts | | `ST015` | Generic intercepted methods use run-time `MakeGenericMethod` | Use non-generic members with closed parameter and return types | -| `ST015` | Ref-struct interception needs by-ref-like generics | Target .NET 9 or later, with C# 13 or later | | `ST015` | `IQueryable` defaults require dynamic code | Register an AOT-compatible typed `DefaultValueProvider` factory, or avoid `DefaultValueBehavior` for that member | -Ref-struct holders need .NET 9 and C# 13 or later, and ref-struct and pointer signatures need unsafe blocks. +Ref-struct signatures need .NET 9 and C# 13 or later (`ST023`), and ref-struct and pointer signatures need unsafe blocks (`ST009`). ## Stunts the generator can't see diff --git a/docs/guide/generation.md b/docs/guide/generation.md index 9c5dee2..30ce894 100644 --- a/docs/guide/generation.md +++ b/docs/guide/generation.md @@ -27,7 +27,8 @@ spans and other ref structs, default interface members, events, indexers, and ne Ref-struct and pointer signatures need `true` (`ST009`). Ref-struct signatures also need .NET 9 and C# 13 or later (`ST023`). -What can't be proxied is reported at the call that asks for it: see [Diagnostics](diagnostics.md). +What can't be proxied is reported at the call or the `[assembly: Stunt]` attribute that asks +for it: see [Diagnostics](diagnostics.md). Internal interface members are supported when the stunt is in the same assembly, or in a friend assembly through `InternalsVisibleTo`. diff --git a/readme.md b/readme.md index 188ed3a..7c253e3 100644 --- a/readme.md +++ b/readme.md @@ -260,7 +260,6 @@ Set `true` to publish a native executable. `IsAotCompat | --- | --- | --- | | `ST014` | Runtime proxies require dynamic code | Enable compile-time stunts | | `ST015` | Generic intercepted methods use runtime `MakeGenericMethod` | Use non-generic members with closed parameter and return types | -| `ST015` | Ref-struct interception needs by-ref-like generics | Target .NET 9 or later, with C# 13 or later | | `ST015` | `IQueryable` defaults require dynamic code | Register an AOT-compatible typed `DefaultValueProvider` factory, or avoid `DefaultValueBehavior` for that member | Generated stunts register typed constructors from a module initializer, so they are created diff --git a/src/Stunts.CodeAnalysis/SymbolExtensions.cs b/src/Stunts.CodeAnalysis/SymbolExtensions.cs index f07c828..f823537 100644 --- a/src/Stunts.CodeAnalysis/SymbolExtensions.cs +++ b/src/Stunts.CodeAnalysis/SymbolExtensions.cs @@ -55,6 +55,22 @@ static void CollectSymbols(INamedTypeSymbol symbol, HashSet se } } + /// + /// Whether the attribute class is the given registration attribute, such as + /// , with any number of type arguments. + /// + public static bool IsRegistrationAttribute(this INamedTypeSymbol type, Type registrationAttribute) + { + var name = registrationAttribute.Name; + var tick = name.IndexOf('`'); + if (tick > 0) + name = name.Substring(0, tick); + + return type.Name == name && + type.ContainingType == null && + type.ContainingNamespace.ToDisplayString() == registrationAttribute.Namespace; + } + /// /// Sorts and validates types so that the base class is the first and the remaining /// interface implementations are the rest. diff --git a/src/Stunts.CodeAnalysis/UnsafeSignatureAnalyzer.cs b/src/Stunts.CodeAnalysis/UnsafeSignatureAnalyzer.cs index d19f2de..d1121cc 100644 --- a/src/Stunts.CodeAnalysis/UnsafeSignatureAnalyzer.cs +++ b/src/Stunts.CodeAnalysis/UnsafeSignatureAnalyzer.cs @@ -15,21 +15,32 @@ namespace Stunts /// version or the runtime lacks the ref-struct holders (). /// The generated code does not compile in those cases. /// + /// + /// It analyzes the stunts the generator creates: those of the calls to generator methods + /// and those of the registration attributes of the assembly. + /// [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class UnsafeSignatureAnalyzer : DiagnosticAnalyzer { readonly Type generatorAttribute; + readonly Type registrationAttribute; /// - /// Instantiates the analyzer for invocations annotated with . + /// Instantiates the analyzer for invocations annotated with + /// and registrations with . /// public UnsafeSignatureAnalyzer() : this(typeof(StuntGeneratorAttribute)) { } /// /// Customizes the analyzer by specifying a custom generator attribute. /// - protected UnsafeSignatureAnalyzer(Type generatorAttribute) - => this.generatorAttribute = generatorAttribute; + protected UnsafeSignatureAnalyzer(Type generatorAttribute) : this(generatorAttribute, typeof(StuntAttribute<>)) { } + + /// + /// Customizes the analyzer by specifying custom generator and registration attributes. + /// + protected UnsafeSignatureAnalyzer(Type generatorAttribute, Type registrationAttribute) + => (this.generatorAttribute, this.registrationAttribute) = (generatorAttribute, registrationAttribute); /// public sealed override ImmutableArray SupportedDiagnostics { get; } @@ -42,47 +53,76 @@ public override void Initialize(AnalysisContext context) context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(start => { - if (StuntClosure.Create(start.Compilation, generatorAttribute) is StuntClosure closure) - start.RegisterOperationAction(operation => AnalyzeOperation(operation, closure), OperationKind.Invocation); + if (StuntClosure.Create(start.Compilation, generatorAttribute) is not StuntClosure closure) + return; + + start.RegisterOperationAction(operation => AnalyzeInvocation(operation, closure), OperationKind.Invocation); + start.RegisterSemanticModelAction(AnalyzeRegistrations); }); } - void AnalyzeOperation(OperationAnalysisContext context, StuntClosure closure) + void AnalyzeInvocation(OperationAnalysisContext context, StuntClosure closure) { var invocation = (IInvocationOperation)context.Operation; - if (!closure.IsGenerator(invocation.TargetMethod)) - return; + if (closure.IsGenerator(invocation.TargetMethod)) + Analyze( + closure.Close(invocation.TargetMethod, context.CancellationToken).SelectMany(stuntDefinition => stuntDefinition.Types), + invocation.Syntax, context.Compilation, context.Options, context.ReportDiagnostic); + } + + // The stunts asked for with the registration attribute, as in [assembly: Stunt]. + void AnalyzeRegistrations(SemanticModelAnalysisContext context) + { + var compilation = context.SemanticModel.Compilation; + foreach (var attribute in compilation.Assembly.GetAttributes()) + { + if (attribute.ApplicationSyntaxReference is SyntaxReference reference && + reference.SyntaxTree == context.SemanticModel.SyntaxTree && + attribute.AttributeClass is { IsGenericType: true } type && + type.IsRegistrationAttribute(registrationAttribute)) + Analyze(type.TypeArguments, reference.GetSyntax(context.CancellationToken), compilation, context.Options, context.ReportDiagnostic); + } + } - var unsafeOff = !BuildProperties.CompileTimeStuntsAndUnsafe(context.Options.AnalyzerConfigOptionsProvider.GlobalOptions); + // Reports at the source that asks for a stunt of the given types. + static void Analyze(IEnumerable stuntTypes, SyntaxNode source, Compilation compilation, AnalyzerOptions options, Action report) + { + var global = options.AnalyzerConfigOptionsProvider.GlobalOptions; + var unsafeOff = !BuildProperties.CompileTimeStuntsAndUnsafe(global); // Visual Basic only has run-time stunts, which the unsafe check already reports. - var holders = invocation.Language == LanguageNames.CSharp - ? HoldersFix(context.Compilation, invocation.Syntax.SyntaxTree.Options) : null; + var holders = source.Language == LanguageNames.CSharp + ? HoldersFix(compilation, source.SyntaxTree.Options) : null; if (!unsafeOff && holders == null) return; - var types = closure.Close(invocation.TargetMethod, context.CancellationToken) - .SelectMany(stuntDefinition => stuntDefinition.Types) + var types = stuntTypes .Distinct(SymbolEqualityComparer.Default) .OfType() .Where(type => type.TypeKind != TypeKind.Error) .ToList(); + // Run-time stunts do not intercept constructors. + var constructors = !BuildProperties.CompileTimeStuntsDisabled(global); - if (unsafeOff && Find(types, context.Compilation.Assembly, IsUnsafe) is ISymbol member) - context.ReportDiagnostic(Diagnostic.Create( + if (unsafeOff && Find(types, compilation.Assembly, constructors, IsUnsafe) is ISymbol member) + report(Diagnostic.Create( StuntDiagnostics.UnsafeSignature, - invocation.Syntax.GetLocation(), + source.GetLocation(), member.ContainingType.Name, - member.Name)); + Name(member))); - if (holders != null && Find(types, context.Compilation.Assembly, type => type.IsRefLikeType) is ISymbol held) - context.ReportDiagnostic(Diagnostic.Create( + if (holders != null && Find(types, compilation.Assembly, constructors, type => type.IsRefLikeType) is ISymbol held) + report(Diagnostic.Create( StuntDiagnostics.RefStructSignature, - invocation.Syntax.GetLocation(), + source.GetLocation(), held.ContainingType.Name, - held.Name, + Name(held), holders)); } + // A constructor has the name of its type, as it is written. + static string Name(ISymbol member) + => member is IMethodSymbol { MethodKind: MethodKind.Constructor } ? member.ContainingType.Name : member.Name; + // What to change for the ref-struct holders to exist, or null when they are supported. static string? HoldersFix(Compilation compilation, ParseOptions parseOptions) => (RefStructHolders.SupportedByRuntime(compilation), RefStructHolders.SupportedByLanguage(parseOptions)) switch @@ -94,11 +134,16 @@ void AnalyzeOperation(OperationAnalysisContext context, StuntClosure closure) }; // The first intercepted member with a type in its signature that matches. - static ISymbol? Find(IEnumerable types, IAssemblySymbol assembly, Func matches) - => types.Select(type => Find(type, assembly, matches)).FirstOrDefault(member => member != null); + static ISymbol? Find(IEnumerable types, IAssemblySymbol assembly, bool constructors, Func matches) + => types.Select(type => Find(type, assembly, constructors, matches)).FirstOrDefault(member => member != null); - static ISymbol? Find(INamedTypeSymbol type, IAssemblySymbol assembly, Func matches) + static ISymbol? Find(INamedTypeSymbol type, IAssemblySymbol assembly, bool constructors, Func matches) { + // A delegate stunt does not pass a ref struct or pointer through the pipeline: no + // build property or language version makes its generated code compile. + if (type.TypeKind == TypeKind.Delegate) + return null; + if (type.TypeKind == TypeKind.Interface) { foreach (var current in new[] { type }.Concat(type.AllInterfaces)) @@ -127,6 +172,11 @@ void AnalyzeOperation(OperationAnalysisContext context, StuntClosure closure) } } + // A compile-time stunt intercepts each accessible constructor of its base class. + if (constructors && type.InstanceConstructors.FirstOrDefault(constructor => + Accessible(constructor, assembly) && Uses(constructor, matches)) is IMethodSymbol intercepted) + return intercepted; + foreach (var iface in type.AllInterfaces) { foreach (var member in iface.GetMembers()) diff --git a/src/Stunts.CompiledProxy/Processors/CSharpAot.cs b/src/Stunts.CompiledProxy/Processors/CSharpAot.cs index fa56340..e90d256 100644 --- a/src/Stunts.CompiledProxy/Processors/CSharpAot.cs +++ b/src/Stunts.CompiledProxy/Processors/CSharpAot.cs @@ -114,9 +114,6 @@ type.TypeKind is TypeKind.Pointer or TypeKind.FunctionPointer or TypeKind.TypePa .WithBody(Block(registrations))); if (usesQueryable) updated = updated.WithAdditionalAnnotations(new SyntaxAnnotation("Stunts.AotQueryable")); - if (!RefStructHolders.Supported(context.Compilation, context.ParseOptions) && - symbol.GetMembers().OfType().Any(method => method.ReturnType.IsRefLikeType || method.Parameters.Any(parameter => parameter.Type.IsRefLikeType))) - updated = updated.WithAdditionalAnnotations(new SyntaxAnnotation("Stunts.AotRefStruct")); return unit.ReplaceNode(declaration, updated); } diff --git a/src/Stunts.CompiledProxy/StuntCache.cs b/src/Stunts.CompiledProxy/StuntCache.cs index 3d96498..da70a36 100644 --- a/src/Stunts.CompiledProxy/StuntCache.cs +++ b/src/Stunts.CompiledProxy/StuntCache.cs @@ -20,7 +20,6 @@ enum StuntCacheFlags NoConstructor = 2, GenericMethods = 4, AotQueryable = 8, - AotRefStruct = 16, } /// A cached generation result. diff --git a/src/Stunts.CompiledProxy/StuntFingerprint.cs b/src/Stunts.CompiledProxy/StuntFingerprint.cs index 069c037..38360e2 100644 --- a/src/Stunts.CompiledProxy/StuntFingerprint.cs +++ b/src/Stunts.CompiledProxy/StuntFingerprint.cs @@ -99,7 +99,7 @@ static string Describe(ISyntaxProcessor processor) => processor is IConfiguredSy : processor.GetType().FullName!; // The inputs every stunt of a compilation shares: the generator configuration, the - // language and runtime features the processors check, and the target framework. + // language features the processors check, and the target framework. static string Environment(ProcessorContext context, StuntGenerator generator, IEnumerable processors, NamingConvention naming, bool pretty) { var compilation = context.Compilation; @@ -116,7 +116,6 @@ static string Environment(ProcessorContext context, StuntGenerator generator, IE .Append(compilation.Options.MetadataImportOptions).Append('|') .Append((compilation.Options as CSharpCompilationOptions)?.AllowUnsafe).Append('|') .Append(pretty).Append('|') - .Append(compilation.SupportsRuntimeCapability(RuntimeCapability.ByRefLikeGenerics)).Append('|') .Append(compilation.GetSpecialType(SpecialType.System_Object).ContainingAssembly?.Identity.GetDisplayName()).Append('|'); return builder.ToString(); diff --git a/src/Stunts.CompiledProxy/StuntGenerator.cs b/src/Stunts.CompiledProxy/StuntGenerator.cs index ab8fbaa..b5ee419 100644 --- a/src/Stunts.CompiledProxy/StuntGenerator.cs +++ b/src/Stunts.CompiledProxy/StuntGenerator.cs @@ -363,8 +363,6 @@ void OnExecute(ProcessorContext context, NamingConvention naming) context.ReportDiagnostic(Diagnostic.Create(StuntDiagnostics.AotUnsupportedMember, source.GetLocation(), "generic intercepted methods require runtime MakeGenericMethod")); if ((flags & StuntCacheFlags.AotQueryable) != 0) context.ReportDiagnostic(Diagnostic.Create(StuntDiagnostics.AotUnsupportedMember, source.GetLocation(), "IQueryable default values require dynamic code; register a typed DefaultValueProvider factory")); - if ((flags & StuntCacheFlags.AotRefStruct) != 0) - context.ReportDiagnostic(Diagnostic.Create(StuntDiagnostics.AotUnsupportedMember, source.GetLocation(), "ref-struct interception requires by-ref-like generics (.NET 9 and C# 13 or later)")); } // At this point, we should have a type that has at least one public constructor @@ -570,8 +568,6 @@ static StuntCacheFlags Flags(SyntaxNode syntax, SyntaxNode updated) if (updated.GetAnnotatedNodes("Stunts.AotQueryable").Any()) flags |= StuntCacheFlags.AotQueryable; - if (updated.GetAnnotatedNodes("Stunts.AotRefStruct").Any()) - flags |= StuntCacheFlags.AotRefStruct; return flags; } @@ -795,7 +791,7 @@ SemanticModel Model(SyntaxTree tree) context.CancellationToken.ThrowIfCancellationRequested(); if (Model(attribute.SyntaxTree).GetSymbolInfo(attribute, context.CancellationToken).Symbol is IMethodSymbol constructor && constructor.ContainingType is { IsGenericType: true } type && - IsRegistrationAttribute(type) && + type.IsRegistrationAttribute(registrationAttribute) && Candidate(type.TypeArguments) is INamedTypeSymbol[] candidate) yield return (attribute, candidate, own); } @@ -812,18 +808,6 @@ public IEnumerable GetGeneratorMethods(ProcessorContext context, } } - bool IsRegistrationAttribute(INamedTypeSymbol type) - { - var name = registrationAttribute.Name; - var tick = name.IndexOf('`'); - if (tick > 0) - name = name.Substring(0, tick); - - return type.Name == name && - type.ContainingType == null && - type.ContainingNamespace.ToDisplayString() == registrationAttribute.Namespace; - } - static INamedTypeSymbol[]? Candidate(ImmutableArray types) { if (types.Length == 0 || !types.All(type => type is INamedTypeSymbol named && CanGenerateFor(named))) diff --git a/src/Stunts.UnitTests/CodeAnalysis/ST009_UnsafeSignature.cs b/src/Stunts.UnitTests/CodeAnalysis/ST009_UnsafeSignature.cs index aca4c4a..ef6d73d 100644 --- a/src/Stunts.UnitTests/CodeAnalysis/ST009_UnsafeSignature.cs +++ b/src/Stunts.UnitTests/CodeAnalysis/ST009_UnsafeSignature.cs @@ -217,6 +217,103 @@ public void ReportsBothDiagnosticsWhenUnsafeBlocksAreOffWithoutTheHolders() diagnostics.Select(diagnostic => diagnostic.Id).OrderBy(id => id)); } + [Fact] + public void ReportsAConstructorParameterWhenUnsafeBlocksAreOff() + { + var diagnostic = Assert.Single(Analyze(SpanConstructor, compileTimeStunts: true, allowUnsafe: false)); + + Assert.Equal(StuntDiagnostics.UnsafeSignature.Id, diagnostic.Id); + Assert.Equal( + "'Buffer.Buffer' uses a ref struct or pointer and requires compile-time stunts and AllowUnsafeBlocks", + diagnostic.GetMessage()); + } + + [Fact] + public void ReportsAConstructorParameterWithoutTheHolders() + { + var diagnostic = Assert.Single(Analyze(SpanConstructor, languageVersion: LanguageVersion.CSharp12)); + + Assert.Equal(StuntDiagnostics.RefStructSignature.Id, diagnostic.Id); + Assert.Equal( + "'Buffer.Buffer' uses a ref struct, which requires .NET 9 and C# 13 or later. Set LangVersion to 13 or later.", + diagnostic.GetMessage()); + } + + [Fact] + public void DoesNotReportAConstructorOfARunTimeStunt() + { + Assert.Empty(Analyze(SpanConstructor, compileTimeStunts: false, allowUnsafe: true, LanguageVersion.CSharp12)); + } + + [Fact] + public void DoesNotReportAnInaccessibleConstructor() + { + Assert.Empty(Analyze(""" + using System; + using Stunts; + + public class Buffer + { + public Buffer() { } + Buffer(Span data) { } + } + + public class Test + { + public void Run() => Stunt.Of(); + } + """, compileTimeStunts: true, allowUnsafe: false, LanguageVersion.CSharp12)); + } + + [Fact] + public void ReportsARegistrationWithoutTheHolders() + { + var diagnostic = Assert.Single(Analyze(SpanRegistration, languageVersion: LanguageVersion.CSharp12)); + + Assert.Equal(StuntDiagnostics.RefStructSignature.Id, diagnostic.Id); + Assert.Contains("'Buffer.Sum'", diagnostic.GetMessage()); + Assert.Equal("Stunt", diagnostic.Location.SourceTree!.GetText().ToString(diagnostic.Location.SourceSpan)); + } + + [Fact] + public void ReportsARegistrationWithInterfacesWhenUnsafeBlocksAreOff() + { + var diagnostic = Assert.Single(Analyze( + SpanRegistration.Replace("Stunt", "Stunt"), compileTimeStunts: true, allowUnsafe: false)); + + Assert.Equal(StuntDiagnostics.UnsafeSignature.Id, diagnostic.Id); + Assert.Contains("'Buffer.Sum'", diagnostic.GetMessage()); + Assert.Equal("Stunt", diagnostic.Location.SourceTree!.GetText().ToString(diagnostic.Location.SourceSpan)); + } + + [Fact] + public void DoesNotReportARegistrationWhenBothFlagsAreOn() + { + Assert.Empty(Analyze(SpanRegistration)); + } + + [Fact] + public void DoesNotReportADelegate() + { + // A delegate stunt has no use for the holders or for unsafe blocks. + Assert.Empty(Analyze(""" + using System; + using System.Buffers; + using Stunts; + + public delegate int Sum(Span data); + + public class Test + { + public void Run() + { + Stunt.Of(); + Stunt.Of>(); + } + } + """, compileTimeStunts: true, allowUnsafe: false, LanguageVersion.CSharp12)); + } + const string SpanStunt = """ using System; using Stunts; @@ -232,6 +329,33 @@ public class Test } """; + const string SpanConstructor = """ + using System; + using Stunts; + + public class Buffer + { + public Buffer(Span data) { } + } + + public class Test + { + public void Run() => Stunt.Of(); + } + """; + + const string SpanRegistration = """ + using System; + using Stunts; + + [assembly: Stunt] + + public class Buffer + { + public virtual int Sum(Span data) => 0; + } + """; + // A core library without RuntimeFeature.ByRefLikeGenerics, as the ones before .NET 9. const string SpanStuntWithoutByRefLikeGenerics = """ namespace System diff --git a/src/Stunts.UnitTests/StuntGeneratorTests.cs b/src/Stunts.UnitTests/StuntGeneratorTests.cs index d0b3272..8a1e9fe 100644 --- a/src/Stunts.UnitTests/StuntGeneratorTests.cs +++ b/src/Stunts.UnitTests/StuntGeneratorTests.cs @@ -323,20 +323,6 @@ public static class Test { public static IQuery Create() => Stunt.Of(); compilation.Emit(false); } - [Fact] - public void WarnsAboutRefStructsWithoutHoldersForAot() - { - var (diagnostics, _) = GetGeneratedOutput(@" -using System; -using Stunts; -public interface IBuffer { int Sum(Span data); } -public static class Test { public static IBuffer Create() => Stunt.Of(); }", aotProperty: "PublishAot", languageVersion: LanguageVersion.CSharp12); - - var diagnostic = Assert.Single(diagnostics); - Assert.Equal("ST015", diagnostic.Id); - Assert.Contains("C# 13", diagnostic.GetMessage()); - } - [Fact] public void CreatesInaccessibleNestedStunts() {