Skip to content

Commit 270d808

Browse files
kzuclaudecodealta-agent
committed
Report ST013 for a ref return of a ref struct or pointer
A member or delegate that returns a ref struct or pointer by reference (ref Span<int> Current()) made the generator emit code that does not compile (CS8150), with no Stunts diagnostic: the stunt returns the held value from a local slot, which a ref return cannot do, and Ref<T>, which carries the other ref returns, cannot take a ref struct or pointer as T. RuntimeSignature now finds those signatures too, for methods, properties, indexers and the Invoke of a delegate. ST013 reports them where the stunt is asked for, with the reason in its message, and the generator skips that stunt, so the other stunts of the project are still generated. RuntimeSignature had a walk of its own that also returned members the stunt does not intercept: an interface member the base class implements, or a member a derived class seals. It now reads the members from InterceptedMembers, the walk of UnsafeSignatureAnalyzer moved to a class both share, so ST013 no longer rejects a stunt for such a member. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Co-authored-by: CodeAlta <noreply@codealta.io>
1 parent d1c1807 commit 270d808

10 files changed

Lines changed: 265 additions & 160 deletions

File tree

‎AGENTS.md‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -356,11 +356,16 @@ Same-assembly and friend-assembly implementations remain supported, as do classe
356356
existing concrete implementation. `ST012_InaccessibleInterfaceMember` tests the actual C#
357357
compiler restriction using separate metadata assemblies.
358358

359-
`RuntimeSignature` similarly reports `ST013` for interceptable signatures using
360-
`TypedReference`, `ArgIterator`, or `RuntimeArgumentHandle`, which cannot be represented by
361-
the pipeline's boxed arguments or generic holders. Invalid candidates do not prevent unrelated
359+
`RuntimeSignature` similarly reports `ST013` for the signatures no build setting lets the pipeline
360+
carry: those using `TypedReference`, `ArgIterator`, or `RuntimeArgumentHandle`, which fit neither
361+
its boxed arguments nor its generic holders, and those returning a ref struct or pointer by
362+
reference, which `Ref<T>` cannot take as `T`. Invalid candidates do not prevent unrelated
362363
valid stunts from being generated.
363364

365+
`RuntimeSignature` and `UnsafeSignatureAnalyzer` read the members a stunt intercepts from
366+
`InterceptedMembers`, so a member the stunt leaves alone (a sealed override, an interface member
367+
the base class implements) is not reported.
368+
364369
### Standalone package
365370

366371
`Stunts.CompiledProxy` is also packed on its own, as the only reference of a project that builds a

‎docs/guide/diagnostics.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ the stunt, at build time.
2222
| `ST010` | Error | Delegate type combined with other types | A delegate stunt has the delegate as its only type argument. |
2323
| `ST011` | Warning | Compile-time stunts are disabled or not supported | Install Stunts.DynamicProxy for run-time stunts. Always the case for Visual Basic. |
2424
| `ST012` | Error | Interface member is inaccessible | An abstract interface member (an internal setter of another assembly, for example) can't be implemented here. |
25-
| `ST013` | Error | Unsupported CLR signature | `TypedReference`, `ArgIterator` and `RuntimeArgumentHandle` can't go through the pipeline. |
25+
| `ST013` | Error | Unsupported CLR signature | `TypedReference`, `ArgIterator` and `RuntimeArgumentHandle` can't go through the pipeline, and neither can a ref struct or pointer returned by reference (`ref Span<int>`): return it by value. |
2626
| `ST014` | Warning | Native AOT requires compile-time stunts | Set `EnableCompileTimeStunts` to `true`. See [Native AOT](aot.md). |
2727
| `ST015` | Warning | Stunt member requires dynamic code | See the alternatives in [Native AOT](aot.md#warnings). |
2828
| `ST016` | Error | Generic stunt wrapper must be a generator method | Mark the wrapper `[StuntGenerator]` (code fix available). See [Custom factories](factories.md#generic-wrappers). |

‎readme.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -298,9 +298,10 @@ or `<EnableStuntsCache>false</EnableStuntsCache>` to always regenerate.
298298

299299
Unsupported targets produce diagnostics at the factory call: `ST012` identifies inaccessible
300300
abstract interface members (such as an internal setter from another assembly, which C# cannot
301-
implement), while `ST013` identifies signatures using `TypedReference`, `ArgIterator`, or
302-
`RuntimeArgumentHandle`, which the behavior pipeline cannot represent. Internal interface
303-
members remain supported when accessible through the same assembly or `InternalsVisibleTo`.
301+
implement), while `ST013` identifies signatures the behavior pipeline cannot represent: those
302+
using `TypedReference`, `ArgIterator`, or `RuntimeArgumentHandle`, and those returning a ref
303+
struct or pointer by reference (`ref Span<int>`). Internal interface members remain supported
304+
when accessible through the same assembly or `InternalsVisibleTo`.
304305

305306
<!-- #manual -->
306307
> NOTE: even though generated proxies are the main usage for Stunts, the API was designed so that you can also consume the behavior pipeline easily from hand-coded proxies too.
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using Microsoft.CodeAnalysis;
5+
6+
namespace Stunts.CodeAnalysis;
7+
8+
/// <summary>
9+
/// The members of a type that its stunt intercepts, for the checks of their signatures.
10+
/// </summary>
11+
static class InterceptedMembers
12+
{
13+
/// <summary>
14+
/// The <c>Invoke</c> method of a delegate, or the overridable and interface members of a
15+
/// class or interface, with the accessible constructors of the class when
16+
/// <paramref name="constructors"/> is true: a compile-time stunt intercepts them, and a
17+
/// run-time stunt does not.
18+
/// </summary>
19+
/// <param name="type">The type the stunt inherits or implements.</param>
20+
/// <param name="assembly">The assembly that contains the stunt.</param>
21+
/// <param name="constructors">Whether the stunt intercepts the constructors.</param>
22+
public static IEnumerable<ISymbol> Of(INamedTypeSymbol type, IAssemblySymbol assembly, bool constructors)
23+
{
24+
if (type.TypeKind == TypeKind.Delegate)
25+
{
26+
if (type.DelegateInvokeMethod is IMethodSymbol invoke)
27+
yield return invoke;
28+
29+
yield break;
30+
}
31+
32+
if (type.TypeKind == TypeKind.Interface)
33+
{
34+
foreach (var current in new[] { type }.Concat(type.AllInterfaces))
35+
{
36+
foreach (var member in current.GetMembers())
37+
{
38+
if (IsInterfaceMember(member))
39+
yield return member;
40+
}
41+
}
42+
43+
yield break;
44+
}
45+
46+
var overridden = new HashSet<ISymbol>(SymbolEqualityComparer.Default);
47+
for (var current = type; current != null && current.SpecialType != SpecialType.System_Object; current = current.BaseType)
48+
{
49+
foreach (var member in current.GetMembers())
50+
{
51+
if (Overridden(member) is ISymbol previous)
52+
overridden.Add(previous);
53+
if (overridden.Contains(member))
54+
continue;
55+
if (IsOverridable(member, assembly))
56+
yield return member;
57+
}
58+
}
59+
60+
if (constructors)
61+
{
62+
foreach (var constructor in type.InstanceConstructors)
63+
{
64+
if (Accessible(constructor, assembly))
65+
yield return constructor;
66+
}
67+
}
68+
69+
foreach (var iface in type.AllInterfaces)
70+
{
71+
foreach (var member in iface.GetMembers())
72+
{
73+
if (!IsInterfaceMember(member))
74+
continue;
75+
76+
var implementation = type.FindImplementationForInterfaceMember(member);
77+
if (implementation == null || implementation.ContainingType.TypeKind == TypeKind.Interface)
78+
yield return member;
79+
}
80+
}
81+
}
82+
83+
/// <summary>
84+
/// Whether a type of the signature of the member (its return, property or event type, or
85+
/// one of its parameters) matches.
86+
/// </summary>
87+
public static bool Uses(ISymbol member, Func<ITypeSymbol, bool> matches) => member switch
88+
{
89+
IMethodSymbol method => matches(method.ReturnType) || method.Parameters.Any(parameter => matches(parameter.Type)),
90+
IPropertySymbol property => matches(property.Type) || property.Parameters.Any(parameter => matches(parameter.Type)),
91+
IEventSymbol symbol => matches(symbol.Type),
92+
_ => false,
93+
};
94+
95+
static bool IsOverridable(ISymbol member, IAssemblySymbol assembly)
96+
=> IsCallable(member) &&
97+
!member.IsSealed &&
98+
(member.IsAbstract || member.IsVirtual || member.IsOverride) &&
99+
Accessible(member, assembly);
100+
101+
static bool IsInterfaceMember(ISymbol member)
102+
=> IsCallable(member) && !IsExplicit(member);
103+
104+
static bool IsCallable(ISymbol member)
105+
{
106+
if (member.IsStatic || member.IsImplicitlyDeclared)
107+
return false;
108+
109+
if (member is IMethodSymbol method)
110+
return method.MethodKind == MethodKind.Ordinary && method.CanBeReferencedByName;
111+
112+
return member is IPropertySymbol or IEventSymbol;
113+
}
114+
115+
static bool IsExplicit(ISymbol member) => member switch
116+
{
117+
IMethodSymbol method => method.ExplicitInterfaceImplementations.Length > 0,
118+
IPropertySymbol property => property.ExplicitInterfaceImplementations.Length > 0,
119+
IEventSymbol symbol => symbol.ExplicitInterfaceImplementations.Length > 0,
120+
_ => false,
121+
};
122+
123+
static bool Accessible(ISymbol member, IAssemblySymbol assembly)
124+
{
125+
switch (member.DeclaredAccessibility)
126+
{
127+
case Accessibility.Public:
128+
case Accessibility.Protected:
129+
case Accessibility.ProtectedOrInternal:
130+
return true;
131+
case Accessibility.Internal:
132+
return member.ContainingAssembly.GivesAccessTo(assembly);
133+
case Accessibility.ProtectedAndInternal:
134+
return SymbolEqualityComparer.Default.Equals(member.ContainingAssembly, assembly);
135+
default:
136+
return false;
137+
}
138+
}
139+
140+
static ISymbol? Overridden(ISymbol member) => member switch
141+
{
142+
IMethodSymbol method => method.OverriddenMethod,
143+
IPropertySymbol property => property.OverriddenProperty,
144+
IEventSymbol symbol => symbol.OverriddenEvent,
145+
_ => null,
146+
};
147+
}
Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,45 @@
1-
using System.Linq;
21
using Microsoft.CodeAnalysis;
32

43
namespace Stunts.CodeAnalysis;
54

5+
/// <summary>
6+
/// Finds the signatures the behavior pipeline cannot carry under any build setting, in boxed
7+
/// arguments or in holders.
8+
/// </summary>
69
static class RuntimeSignature
710
{
8-
public static ISymbol? UnsupportedMember(INamedTypeSymbol type, Compilation compilation)
11+
/// <summary>
12+
/// The <see cref="StuntDiagnostics.UnsupportedRuntimeSignature"/> of the first member the
13+
/// stunt of the type intercepts with such a signature, or null when it has none.
14+
/// </summary>
15+
public static Diagnostic? Unsupported(INamedTypeSymbol type, Compilation compilation, Location location)
916
{
10-
var types = type.TypeKind == TypeKind.Interface
11-
? type.AllInterfaces.Insert(0, type)
12-
: type.AllInterfaces.Add(type);
13-
foreach (var current in types)
17+
foreach (var member in InterceptedMembers.Of(type, compilation.Assembly, constructors: true))
1418
{
15-
for (var declaring = current; declaring != null; declaring = declaring.BaseType)
16-
{
17-
foreach (var member in declaring.GetMembers())
18-
{
19-
if (member.IsStatic || member.IsSealed ||
20-
!(member.IsVirtual || member.IsAbstract || member.IsOverride ||
21-
member is IMethodSymbol { MethodKind: MethodKind.Constructor }) ||
22-
member.DeclaredAccessibility is Accessibility.Private or Accessibility.ProtectedAndInternal ||
23-
member.DeclaredAccessibility == Accessibility.Internal && !declaring.ContainingAssembly.GivesAccessTo(compilation.Assembly))
24-
continue;
25-
if (member is IMethodSymbol method &&
26-
(Unsupported(method.ReturnType) || method.Parameters.Any(parameter => Unsupported(parameter.Type))))
27-
return member;
28-
}
29-
}
19+
var reason =
20+
InterceptedMembers.Uses(member, IsSpecial) ? "uses TypedReference, ArgIterator, or RuntimeArgumentHandle" :
21+
ReturnsHeldByRef(member) ? "returns a ref struct or pointer by reference" :
22+
null;
23+
if (reason != null)
24+
return Diagnostic.Create(
25+
StuntDiagnostics.UnsupportedRuntimeSignature, location, type.Name, member.ToDisplayString(), reason);
3026
}
3127

3228
return null;
3329
}
3430

35-
static bool Unsupported(ITypeSymbol type)
31+
static bool IsSpecial(ITypeSymbol type)
3632
=> type.SpecialType is SpecialType.System_TypedReference or SpecialType.System_ArgIterator or SpecialType.System_RuntimeArgumentHandle;
33+
34+
// A ref return goes through Ref<T>, which cannot take as T the types that go through a
35+
// holder: ref structs and pointers.
36+
static bool ReturnsHeldByRef(ISymbol member) => member switch
37+
{
38+
IMethodSymbol method => (method.ReturnsByRef || method.ReturnsByRefReadonly) && IsHeld(method.ReturnType),
39+
IPropertySymbol property => (property.ReturnsByRef || property.ReturnsByRefReadonly) && IsHeld(property.Type),
40+
_ => false,
41+
};
42+
43+
static bool IsHeld(ITypeSymbol type)
44+
=> type.IsRefLikeType || type.TypeKind is TypeKind.Pointer or TypeKind.FunctionPointer;
3745
}

‎src/Stunts.CodeAnalysis/StuntDiagnostics.cs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -237,16 +237,18 @@ public static class StuntDiagnostics
237237
"All abstract interface members, including property and event accessors, must be accessible to the generated implementation.");
238238

239239
/// <summary>
240-
/// Diagnostic reported when a signature uses a special CLR type that cannot
241-
/// be stored in invocation arguments or ref-struct holders.
240+
/// Diagnostic reported when a signature cannot go through the behavior pipeline under
241+
/// any build setting: it uses a special CLR type that cannot be stored in invocation
242+
/// arguments or ref-struct holders, or it returns a ref struct or pointer by reference.
242243
/// </summary>
243244
public static DiagnosticDescriptor UnsupportedRuntimeSignature { get; } = new DiagnosticDescriptor(
244245
"ST013",
245246
"Unsupported CLR signature",
246-
"'{0}' cannot be proxied because '{1}' uses TypedReference, ArgIterator, or RuntimeArgumentHandle",
247+
"'{0}' cannot be proxied because '{1}' {2}",
247248
"Build",
248249
DiagnosticSeverity.Error,
249250
true,
250-
"These special CLR types cannot be boxed or used as generic arguments, so the behavior pipeline cannot intercept them.");
251+
"TypedReference, ArgIterator and RuntimeArgumentHandle cannot be boxed or used as generic arguments, and a ref struct " +
252+
"or pointer returned by reference cannot be the type argument of Ref<T>, so the behavior pipeline cannot intercept them.");
251253
}
252254
}

0 commit comments

Comments
 (0)