Skip to content

Commit df16e67

Browse files
kzucodealta-agent
andcommitted
Fix runtime, analyzer, code-fix, and generator correctness bugs (Phase 1)
- Make BehaviorPipeline stateless across retries, preserve stack traces via ExceptionDispatchInfo, and make BehaviorsCollection/RecordingBehavior/DynamicStuntInterceptor thread-safe - Guard AsyncRegistry continuations and trimming, fix Argument/MethodInvocation/Ref/Stunt.Get/StuntExtensions edge cases, and tighten DefaultEqualityBehavior/TargetBehavior/NotifyPropertyChangeBehavior matching - Guard ObservabilityBehavior Activity lifecycle and return faulted Task/ValueTask from DataAnnotationsBehavior - Fix ST001 title, split missing-generator MSBuild error to ST024, add ST025/ST026/ST027, harden StuntCache.Prune, and fix NamingConvention, SymbolExtensions, SymbolFullNameExtensions, StuntClosure, GenericWrapperAnalyzer, ValidateTypesAnalyzer, AddPartialCodeFix, MemberScaffold, AttributeReplication, and CSharpRewrite Co-authored-by: CodeAlta <noreply@codealta.io>
1 parent 86c0c4b commit df16e67

54 files changed

Lines changed: 1449 additions & 226 deletions

Some content is hidden

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

‎src/Stunts.CodeAnalysis/GenericWrapperAnalyzer.cs‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,14 @@ public override void Initialize(AnalysisContext context)
5858
return;
5959

6060
start.RegisterOperationAction(operation => AnalyzeInvocation(operation, closure), OperationKind.Invocation);
61-
start.RegisterSymbolAction(symbol => AnalyzeMethod(symbol, closure), SymbolKind.Method);
61+
start.RegisterOperationAction(operation => AnalyzeLocalFunction(operation, closure), OperationKind.LocalFunction);
62+
start.RegisterSymbolAction(symbol => AnalyzeMethod((IMethodSymbol)symbol.Symbol, closure, symbol.ReportDiagnostic, symbol.CancellationToken), SymbolKind.Method);
6263
});
6364
}
6465

66+
static void AnalyzeLocalFunction(OperationAnalysisContext context, StuntClosure closure)
67+
=> AnalyzeMethod(((ILocalFunctionOperation)context.Operation).Symbol, closure, context.ReportDiagnostic, context.CancellationToken);
68+
6569
static void AnalyzeInvocation(OperationAnalysisContext context, StuntClosure closure)
6670
{
6771
var invocation = (IInvocationOperation)context.Operation;
@@ -106,13 +110,12 @@ static void AnalyzeInvocation(OperationAnalysisContext context, StuntClosure clo
106110
}
107111
}
108112

109-
static void AnalyzeMethod(SymbolAnalysisContext context, StuntClosure closure)
113+
static void AnalyzeMethod(IMethodSymbol method, StuntClosure closure, Action<Diagnostic> report, System.Threading.CancellationToken cancellationToken)
110114
{
111-
var method = (IMethodSymbol)context.Symbol;
112115
if (method.DeclaringSyntaxReferences.IsEmpty || !closure.IsGenerator(method))
113116
return;
114117

115-
var result = closure.GetDefinitions(method, context.CancellationToken);
118+
var result = closure.GetDefinitions(method, cancellationToken);
116119
var diagnostic = result.Error switch
117120
{
118121
StuntClosureError.VirtualWrapper => Diagnostic.Create(
@@ -127,7 +130,7 @@ static void AnalyzeMethod(SymbolAnalysisContext context, StuntClosure closure)
127130
};
128131

129132
if (diagnostic != null)
130-
context.ReportDiagnostic(diagnostic);
133+
report(diagnostic);
131134
}
132135

133136
static void Collect(ITypeSymbol type, HashSet<ITypeParameterSymbol> parameters)

‎src/Stunts.CodeAnalysis/InterfaceImplementation.cs‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,59 @@ static class InterfaceImplementation
3939

4040
return null;
4141
}
42+
43+
public static ISymbol? StaticAbstractMember(INamedTypeSymbol type)
44+
{
45+
var interfaces = type.TypeKind == TypeKind.Interface
46+
? type.AllInterfaces.Insert(0, type)
47+
: type.AllInterfaces;
48+
foreach (var iface in interfaces)
49+
{
50+
foreach (var member in iface.GetMembers())
51+
{
52+
if (!member.IsStatic)
53+
continue;
54+
55+
var isStaticAbstract = member switch
56+
{
57+
IPropertySymbol property => property.IsAbstract || property.GetMethod?.IsAbstract == true || property.SetMethod?.IsAbstract == true,
58+
IEventSymbol ev => ev.IsAbstract || ev.AddMethod?.IsAbstract == true || ev.RemoveMethod?.IsAbstract == true,
59+
IMethodSymbol method => method.IsAbstract && method.MethodKind is not (MethodKind.PropertyGet or MethodKind.PropertySet or MethodKind.EventAdd or MethodKind.EventRemove),
60+
_ => false,
61+
};
62+
if (!isStaticAbstract)
63+
continue;
64+
if (type.TypeKind != TypeKind.Interface && type.FindImplementationForInterfaceMember(member) != null)
65+
continue;
66+
67+
return member;
68+
}
69+
}
70+
71+
return null;
72+
}
73+
74+
public static INamedTypeSymbol? FileLocalType(ITypeSymbol type)
75+
{
76+
switch (type)
77+
{
78+
case IArrayTypeSymbol array:
79+
return FileLocalType(array.ElementType);
80+
case IPointerTypeSymbol pointer:
81+
return FileLocalType(pointer.PointedAtType);
82+
case INamedTypeSymbol named:
83+
if (named.IsFileLocal)
84+
return named;
85+
if (named.ContainingType != null && FileLocalType(named.ContainingType) is INamedTypeSymbol containing)
86+
return containing;
87+
foreach (var arg in named.TypeArguments)
88+
{
89+
if (FileLocalType(arg) is INamedTypeSymbol argFileLocal)
90+
return argFileLocal;
91+
}
92+
return null;
93+
default:
94+
return null;
95+
}
96+
}
4297
}

‎src/Stunts.CodeAnalysis/NamingConvention.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,13 +172,13 @@ static string Hash(string value)
172172
/// The full type name for the given (optional) base type and implemented interfaces.
173173
/// </summary>
174174
public string GetFullName(IEnumerable<INamedTypeSymbol> symbols)
175-
=> GetNamespace(RootNamespace, symbols.FirstOrDefault()?.ContainingNamespace) + "." + GetName(symbols);
175+
=> GetNamespace(symbols) + "." + GetName(symbols);
176176

177177
/// <summary>
178178
/// The namespace for the given (optional) base type and implemented interfaces.
179179
/// </summary>
180180
public string GetNamespace(IEnumerable<INamedTypeSymbol> symbols)
181-
=> GetNamespace(RootNamespace, symbols.FirstOrDefault()?.ContainingNamespace);
181+
=> GetNamespace(RootNamespace, Sorted(symbols).FirstOrDefault()?.ContainingNamespace);
182182

183183
string GetNamespace(string rootNamespace, INamespaceSymbol? containingNamespace)
184184
=> containingNamespace == null || containingNamespace.IsGlobalNamespace ? rootNamespace : rootNamespace + "." + containingNamespace.ToString();

‎src/Stunts.CodeAnalysis/NestedTypeStunt.cs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,22 @@ public static bool MustNest(INamedTypeSymbol type)
2323
/// must be nested to be inherited.
2424
/// </summary>
2525
public static INamedTypeSymbol? NonPartialContainer(INamedTypeSymbol type)
26+
=> NonPartialContainers(type).FirstOrDefault();
27+
28+
/// <summary>
29+
/// All enclosing types that are not declared partial (innermost first), when
30+
/// <paramref name="type"/> must be nested to be inherited.
31+
/// </summary>
32+
public static System.Collections.Generic.IEnumerable<INamedTypeSymbol> NonPartialContainers(INamedTypeSymbol type)
2633
{
2734
if (!MustNest(type))
28-
return null;
35+
yield break;
2936

3037
for (var current = type.ContainingType; current != null; current = current.ContainingType)
3138
{
3239
if (!IsPartial(current))
33-
return current;
40+
yield return current;
3441
}
35-
36-
return null;
3742
}
3843

3944
/// <summary>

‎src/Stunts.CodeAnalysis/RuntimeSignature.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ static class RuntimeSignature
1212
/// The <see cref="StuntDiagnostics.UnsupportedRuntimeSignature"/> of the first member the
1313
/// stunt of the type intercepts with such a signature, or null when it has none.
1414
/// </summary>
15-
public static Diagnostic? Unsupported(INamedTypeSymbol type, Compilation compilation, Location location)
15+
public static Diagnostic? Unsupported(INamedTypeSymbol type, Compilation compilation, Location location, bool constructors = true)
1616
{
17-
foreach (var member in InterceptedMembers.Of(type, compilation.Assembly, constructors: true))
17+
foreach (var member in InterceptedMembers.Of(type, compilation.Assembly, constructors))
1818
{
1919
var reason =
2020
InterceptedMembers.Uses(member, IsSpecial) ? "uses TypedReference, ArgIterator, or RuntimeArgumentHandle" :
@@ -41,5 +41,5 @@ static bool IsSpecial(ITypeSymbol type)
4141
};
4242

4343
static bool IsHeld(ITypeSymbol type)
44-
=> type.IsRefLikeType || type.TypeKind is TypeKind.Pointer or TypeKind.FunctionPointer;
44+
=> type.IsRefLikeType || type is ITypeParameterSymbol { AllowsRefLikeType: true } || type.TypeKind is TypeKind.Pointer or TypeKind.FunctionPointer;
4545
}

‎src/Stunts.CodeAnalysis/SignatureRef.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// <auto-generated/>
2+
#nullable enable
13
#pragma warning disable CS8500
24
using System;
35
using System.Runtime.CompilerServices;

‎src/Stunts.CodeAnalysis/SignatureRefGenerator.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
3434
return;
3535

3636
source.AddSource(
37-
"SignatureRef.cs",
37+
"SignatureRef.g.cs",
3838
SourceText.From(ThisAssembly.Resources.SignatureRef.Text, Encoding.UTF8));
3939
});
4040
}

‎src/Stunts.CodeAnalysis/StuntClosure.cs‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,13 @@ public sealed class StuntClosure
8888
"_" + new string(generatorName.Select(c => char.IsLetterOrDigit(c) ? c : '_').ToArray());
8989
}
9090

91+
/// <summary>
92+
/// Creates the closure for the given compilation using <see cref="StuntGeneratorAttribute"/>,
93+
/// or <see langword="null"/> if it is not available in the compilation.
94+
/// </summary>
95+
public static StuntClosure? Create(Compilation compilation)
96+
=> Create(compilation, typeof(StuntGeneratorAttribute));
97+
9198
/// <summary>
9299
/// Creates the closure for the given compilation, or <see langword="null"/> if
93100
/// the <paramref name="generatorAttribute"/> is not available in it.
@@ -413,9 +420,14 @@ public ITypeSymbol Substitute(ITypeSymbol type, IReadOnlyDictionary<ITypeParamet
413420
return Compilation.CreatePointerTypeSymbol(Substitute(pointer.PointedAtType, map));
414421
case INamedTypeSymbol named when ContainsTypeParameter(named):
415422
var definition = named.OriginalDefinition;
416-
if (named.ContainingType is INamedTypeSymbol container && ContainsTypeParameter(container) &&
417-
Substitute(container, map) is INamedTypeSymbol substituted)
418-
definition = substituted.GetTypeMembers(named.Name, named.Arity).FirstOrDefault() ?? definition;
423+
if (named.ContainingType is INamedTypeSymbol container)
424+
{
425+
var substituted = ContainsTypeParameter(container)
426+
? Substitute(container, map) as INamedTypeSymbol
427+
: container;
428+
if (substituted != null)
429+
definition = substituted.GetTypeMembers(named.Name, named.Arity).FirstOrDefault() ?? definition;
430+
}
419431

420432
return definition.Arity == 0
421433
? definition

‎src/Stunts.CodeAnalysis/StuntDiagnostics.cs‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,45 @@ public static class StuntDiagnostics
9090
"The holders use the allows ref struct constraint, so they are added only when the target runtime " +
9191
"(.NET 9 or later) and the language version (C# 13 or later) support it. Without them, the generated stunt does not compile.");
9292

93+
/// <summary>
94+
/// Diagnostic reported when an interface has a <c>static abstract</c> member that
95+
/// cannot be implemented through an instance behavior pipeline.
96+
/// </summary>
97+
public static DiagnosticDescriptor StaticAbstractInterfaceMember { get; } = new DiagnosticDescriptor(
98+
"ST025",
99+
"Interface has static abstract members",
100+
"'{0}' cannot be proxied because interface member '{1}' is static abstract",
101+
"Build",
102+
DiagnosticSeverity.Error,
103+
true,
104+
"Static abstract interface members cannot be implemented through an instance behavior pipeline.");
105+
106+
/// <summary>
107+
/// Diagnostic reported when a stunt target or one of its type arguments is declared
108+
/// with the <c>file</c> modifier and therefore inaccessible from generated source files.
109+
/// </summary>
110+
public static DiagnosticDescriptor FileLocalType { get; } = new DiagnosticDescriptor(
111+
"ST026",
112+
"File-local type cannot be proxied",
113+
"'{0}' cannot be proxied because it is declared file-local and is inaccessible from generated source files",
114+
"Build",
115+
DiagnosticSeverity.Error,
116+
true,
117+
"Types declared with the file modifier are only visible within their declaring file, so a compile-time stunt in a generated file cannot reference or inherit from them.");
118+
119+
/// <summary>
120+
/// Diagnostic reported when generating a specific stunt fails unexpectedly, isolating
121+
/// the failure so other stunts in the compilation can still be generated.
122+
/// </summary>
123+
public static DiagnosticDescriptor GenerationFailed { get; } = new DiagnosticDescriptor(
124+
"ST027",
125+
"Stunt generation failed",
126+
"Failed to generate stunt for '{0}': {1}",
127+
"Build",
128+
DiagnosticSeverity.Error,
129+
true,
130+
"An unexpected error occurred while generating the stunt for this type combination.");
131+
93132
/// <summary>
94133
/// Diagnostic reported whenever type parameters specified for a
95134
/// <see cref="StuntGeneratorAttribute"/>-annotated method contain a base
@@ -98,7 +137,7 @@ public static class StuntDiagnostics
98137
/// </summary>
99138
public static DiagnosticDescriptor BaseTypeNotFirst { get; } = new DiagnosticDescriptor(
100139
"ST001",
101-
nameof(Strings.BaseTypeNotFirst.Title),
140+
Strings.BaseTypeNotFirst.Title,
102141
Resources.BaseTypeNotFirst_Message,
103142
"Build",
104143
DiagnosticSeverity.Error,

‎src/Stunts.CodeAnalysis/SymbolExtensions.cs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@ namespace Stunts.CodeAnalysis
1212
/// </summary>
1313
public static class SymbolExtensions
1414
{
15-
const string TaskFullName = "System.Threading.Tasks.Task";
16-
1715
/// <summary>
1816
/// Retrieves the distinct set of symbols that can be intercepted from the
1917
/// given list, by inspecting each one and all its properties and methods
@@ -171,14 +169,20 @@ public static bool TryValidateGeneratorTypes(this IEnumerable<ITypeSymbol> types
171169
}
172170

173171
/// <summary>
174-
/// Whether the given type symbol is either an interface or a non-sealed class, and not a generic task.
172+
/// Whether the given type symbol is either an interface or a non-sealed class, and not a task.
175173
/// </summary>
176174
public static bool CanBeIntercepted(this ITypeSymbol symbol)
177175
=> symbol != null &&
178176
symbol.CanBeReferencedByName &&
179177
!symbol.IsValueType &&
180-
!symbol.MetadataName.StartsWith(TaskFullName, StringComparison.Ordinal) &&
178+
!IsTaskType(symbol) &&
181179
(symbol.TypeKind == TypeKind.Interface ||
182180
(symbol.TypeKind == TypeKind.Class && symbol.IsSealed == false));
181+
182+
static bool IsTaskType(ITypeSymbol symbol)
183+
=> symbol is INamedTypeSymbol named &&
184+
named.ContainingType == null &&
185+
named.Name == "Task" &&
186+
named.ContainingNamespace?.ToDisplayString() == "System.Threading.Tasks";
183187
}
184188
}

0 commit comments

Comments
 (0)