Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions docs/guide/aot.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion docs/guide/generation.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ spans and other ref structs, default interface members, events, indexers, and ne
Ref-struct and pointer signatures need `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>` (`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<T>]` 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`.

Expand Down
1 change: 0 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,6 @@ Set `<PublishAot>true</PublishAot>` 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
Expand Down
16 changes: 16 additions & 0 deletions src/Stunts.CodeAnalysis/SymbolExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,22 @@ static void CollectSymbols(INamedTypeSymbol symbol, HashSet<INamedTypeSymbol> se
}
}

/// <summary>
/// Whether the attribute class is the given registration attribute, such as
/// <see cref="StuntAttribute{T}"/>, with any number of type arguments.
/// </summary>
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;
}

/// <summary>
/// Sorts and validates types so that the base class is the first and the remaining
/// interface implementations are the rest.
Expand Down
98 changes: 74 additions & 24 deletions src/Stunts.CodeAnalysis/UnsafeSignatureAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,32 @@ namespace Stunts
/// version or the runtime lacks the ref-struct holders (<see cref="RefStructHolders"/>).
/// The generated code does not compile in those cases.
/// </summary>
/// <remarks>
/// It analyzes the stunts the generator creates: those of the calls to generator methods
/// and those of the registration attributes of the assembly.
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class UnsafeSignatureAnalyzer : DiagnosticAnalyzer
{
readonly Type generatorAttribute;
readonly Type registrationAttribute;

/// <summary>
/// Instantiates the analyzer for invocations annotated with <see cref="StuntGeneratorAttribute"/>.
/// Instantiates the analyzer for invocations annotated with <see cref="StuntGeneratorAttribute"/>
/// and registrations with <see cref="StuntAttribute{T}"/>.
/// </summary>
public UnsafeSignatureAnalyzer() : this(typeof(StuntGeneratorAttribute)) { }

/// <summary>
/// Customizes the analyzer by specifying a custom generator attribute.
/// </summary>
protected UnsafeSignatureAnalyzer(Type generatorAttribute)
=> this.generatorAttribute = generatorAttribute;
protected UnsafeSignatureAnalyzer(Type generatorAttribute) : this(generatorAttribute, typeof(StuntAttribute<>)) { }

/// <summary>
/// Customizes the analyzer by specifying custom generator and registration attributes.
/// </summary>
protected UnsafeSignatureAnalyzer(Type generatorAttribute, Type registrationAttribute)
=> (this.generatorAttribute, this.registrationAttribute) = (generatorAttribute, registrationAttribute);

/// <inheritdoc/>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
Expand All @@ -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<T>].
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<ITypeSymbol> stuntTypes, SyntaxNode source, Compilation compilation, AnalyzerOptions options, Action<Diagnostic> 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<INamedTypeSymbol>()
.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
Expand All @@ -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<INamedTypeSymbol> types, IAssemblySymbol assembly, Func<ITypeSymbol, bool> matches)
=> types.Select(type => Find(type, assembly, matches)).FirstOrDefault(member => member != null);
static ISymbol? Find(IEnumerable<INamedTypeSymbol> types, IAssemblySymbol assembly, bool constructors, Func<ITypeSymbol, bool> matches)
=> types.Select(type => Find(type, assembly, constructors, matches)).FirstOrDefault(member => member != null);

static ISymbol? Find(INamedTypeSymbol type, IAssemblySymbol assembly, Func<ITypeSymbol, bool> matches)
static ISymbol? Find(INamedTypeSymbol type, IAssemblySymbol assembly, bool constructors, Func<ITypeSymbol, bool> 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))
Expand Down Expand Up @@ -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())
Expand Down
3 changes: 0 additions & 3 deletions src/Stunts.CompiledProxy/Processors/CSharpAot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IMethodSymbol>().Any(method => method.ReturnType.IsRefLikeType || method.Parameters.Any(parameter => parameter.Type.IsRefLikeType)))
updated = updated.WithAdditionalAnnotations(new SyntaxAnnotation("Stunts.AotRefStruct"));
return unit.ReplaceNode(declaration, updated);
}

Expand Down
1 change: 0 additions & 1 deletion src/Stunts.CompiledProxy/StuntCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ enum StuntCacheFlags
NoConstructor = 2,
GenericMethods = 4,
AotQueryable = 8,
AotRefStruct = 16,
}

/// <summary>A cached generation result.</summary>
Expand Down
3 changes: 1 addition & 2 deletions src/Stunts.CompiledProxy/StuntFingerprint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ISyntaxProcessor> processors, NamingConvention naming, bool pretty)
{
var compilation = context.Compilation;
Expand All @@ -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();
Expand Down
Loading
Loading