| | | 1 | | using System.Collections.Immutable; |
| | | 2 | | |
| | | 3 | | using Microsoft.CodeAnalysis; |
| | | 4 | | using Microsoft.CodeAnalysis.CSharp; |
| | | 5 | | using Microsoft.CodeAnalysis.CSharp.Syntax; |
| | | 6 | | using Microsoft.CodeAnalysis.Diagnostics; |
| | | 7 | | |
| | | 8 | | namespace NexusLabs.Needlr.Analyzers; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Analyzer that detects when a longer-lived service holds a reference to a shorter-lived IDisposable. |
| | | 12 | | /// This is a more severe form of captive dependency because the disposed object will still be referenced. |
| | | 13 | | /// </summary> |
| | | 14 | | /// <remarks> |
| | | 15 | | /// This analyzer is conservative to avoid false positives: |
| | | 16 | | /// - Only fires when both consumer and dependency have explicit lifetime attributes |
| | | 17 | | /// - Only fires when the dependency type itself (not just interface) implements IDisposable/IAsyncDisposable |
| | | 18 | | /// - Does not fire for factory patterns (Func<T>, Lazy<T>, IServiceScopeFactory) |
| | | 19 | | /// </remarks> |
| | | 20 | | [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| | | 21 | | public sealed class DisposableCaptiveDependencyAnalyzer : DiagnosticAnalyzer |
| | | 22 | | { |
| | | 23 | | private enum LifetimeRank |
| | | 24 | | { |
| | | 25 | | Unknown = -1, |
| | | 26 | | Transient = 0, |
| | | 27 | | Scoped = 1, |
| | | 28 | | Singleton = 2 |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => |
| | 344 | 32 | | ImmutableArray.Create(DiagnosticDescriptors.DisposableCaptiveDependency); |
| | | 33 | | |
| | | 34 | | public override void Initialize(AnalysisContext context) |
| | | 35 | | { |
| | 38 | 36 | | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| | 38 | 37 | | context.EnableConcurrentExecution(); |
| | | 38 | | |
| | 38 | 39 | | context.RegisterSyntaxNodeAction(AnalyzeClassDeclaration, SyntaxKind.ClassDeclaration); |
| | 38 | 40 | | } |
| | | 41 | | |
| | | 42 | | private static void AnalyzeClassDeclaration(SyntaxNodeAnalysisContext context) |
| | | 43 | | { |
| | 155 | 44 | | var classDeclaration = (ClassDeclarationSyntax)context.Node; |
| | | 45 | | |
| | | 46 | | // Skip abstract classes - they can't be instantiated directly |
| | 155 | 47 | | if (classDeclaration.Modifiers.Any(SyntaxKind.AbstractKeyword)) |
| | | 48 | | { |
| | 1 | 49 | | return; |
| | | 50 | | } |
| | | 51 | | |
| | 154 | 52 | | var classSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclaration); |
| | 154 | 53 | | if (classSymbol == null) |
| | | 54 | | { |
| | 0 | 55 | | return; |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | // Only analyze types with EXPLICIT lifetime attributes to avoid false positives |
| | 154 | 59 | | var consumerLifetime = GetExplicitLifetimeFromAttributes(classSymbol); |
| | 154 | 60 | | if (consumerLifetime == LifetimeRank.Unknown) |
| | | 61 | | { |
| | 112 | 62 | | return; // No explicit lifetime, skip to avoid false positives |
| | | 63 | | } |
| | | 64 | | |
| | | 65 | | // Transient types can safely depend on anything |
| | 42 | 66 | | if (consumerLifetime == LifetimeRank.Transient) |
| | | 67 | | { |
| | 5 | 68 | | return; |
| | | 69 | | } |
| | | 70 | | |
| | | 71 | | // Find constructors and analyze their parameters |
| | 37 | 72 | | var constructors = classDeclaration.Members |
| | 37 | 73 | | .OfType<ConstructorDeclarationSyntax>() |
| | 17 | 74 | | .Where(c => !c.Modifiers.Any(SyntaxKind.StaticKeyword)) |
| | 37 | 75 | | .ToList(); |
| | | 76 | | |
| | | 77 | | // Check primary constructor parameters |
| | 37 | 78 | | if (classDeclaration.ParameterList != null) |
| | | 79 | | { |
| | 2 | 80 | | AnalyzeParameters( |
| | 2 | 81 | | context, |
| | 2 | 82 | | classDeclaration.ParameterList.Parameters, |
| | 2 | 83 | | classSymbol, |
| | 2 | 84 | | consumerLifetime); |
| | | 85 | | } |
| | | 86 | | |
| | | 87 | | // Analyze explicit constructor parameters |
| | 108 | 88 | | foreach (var constructor in constructors) |
| | | 89 | | { |
| | 17 | 90 | | AnalyzeParameters( |
| | 17 | 91 | | context, |
| | 17 | 92 | | constructor.ParameterList.Parameters, |
| | 17 | 93 | | classSymbol, |
| | 17 | 94 | | consumerLifetime); |
| | | 95 | | } |
| | 37 | 96 | | } |
| | | 97 | | |
| | | 98 | | private static void AnalyzeParameters( |
| | | 99 | | SyntaxNodeAnalysisContext context, |
| | | 100 | | SeparatedSyntaxList<ParameterSyntax> parameters, |
| | | 101 | | INamedTypeSymbol consumerSymbol, |
| | | 102 | | LifetimeRank consumerLifetime) |
| | | 103 | | { |
| | 80 | 104 | | foreach (var parameter in parameters) |
| | | 105 | | { |
| | 21 | 106 | | if (parameter.Type == null) |
| | | 107 | | { |
| | | 108 | | continue; |
| | | 109 | | } |
| | | 110 | | |
| | 21 | 111 | | var typeInfo = context.SemanticModel.GetTypeInfo(parameter.Type); |
| | 21 | 112 | | var parameterType = typeInfo.Type as INamedTypeSymbol; |
| | 21 | 113 | | if (parameterType == null) |
| | | 114 | | { |
| | | 115 | | continue; |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | // Skip factory patterns - these are safe |
| | 21 | 119 | | if (IsFactoryPattern(parameterType)) |
| | | 120 | | { |
| | | 121 | | continue; |
| | | 122 | | } |
| | | 123 | | |
| | | 124 | | // For interfaces, get the concrete type if we can determine it |
| | 19 | 125 | | var concreteType = GetConcreteTypeForAnalysis(parameterType); |
| | 19 | 126 | | if (concreteType == null) |
| | | 127 | | { |
| | | 128 | | continue; // Can't determine concrete type, skip to avoid false positives |
| | | 129 | | } |
| | | 130 | | |
| | | 131 | | // Get the EXPLICIT lifetime of the dependency |
| | 18 | 132 | | var dependencyLifetime = GetExplicitLifetimeFromAttributes(concreteType); |
| | 18 | 133 | | if (dependencyLifetime == LifetimeRank.Unknown) |
| | | 134 | | { |
| | | 135 | | continue; // No explicit lifetime, skip to avoid false positives |
| | | 136 | | } |
| | | 137 | | |
| | | 138 | | // Check for mismatch: consumer lifetime > dependency lifetime |
| | 17 | 139 | | if ((int)consumerLifetime <= (int)dependencyLifetime) |
| | | 140 | | { |
| | | 141 | | continue; // No mismatch |
| | | 142 | | } |
| | | 143 | | |
| | | 144 | | // Check if the dependency implements IDisposable or IAsyncDisposable |
| | 15 | 145 | | var disposableInterface = GetDisposableInterface(concreteType); |
| | 15 | 146 | | if (disposableInterface == null) |
| | | 147 | | { |
| | | 148 | | continue; // Not disposable, let NDLRCOR005 handle generic lifetime mismatch |
| | | 149 | | } |
| | | 150 | | |
| | 12 | 151 | | var diagnostic = Diagnostic.Create( |
| | 12 | 152 | | DiagnosticDescriptors.DisposableCaptiveDependency, |
| | 12 | 153 | | parameter.GetLocation(), |
| | 12 | 154 | | consumerSymbol.Name, |
| | 12 | 155 | | GetLifetimeName(consumerLifetime), |
| | 12 | 156 | | concreteType.Name, |
| | 12 | 157 | | GetLifetimeName(dependencyLifetime), |
| | 12 | 158 | | disposableInterface); |
| | | 159 | | |
| | 12 | 160 | | context.ReportDiagnostic(diagnostic); |
| | | 161 | | } |
| | 19 | 162 | | } |
| | | 163 | | |
| | | 164 | | /// <summary> |
| | | 165 | | /// Gets the lifetime ONLY from explicit attributes. Returns Unknown if no explicit attribute. |
| | | 166 | | /// This is more conservative than LifetimeMismatchAnalyzer which defaults to Singleton. |
| | | 167 | | /// </summary> |
| | | 168 | | private static LifetimeRank GetExplicitLifetimeFromAttributes(INamedTypeSymbol typeSymbol) |
| | | 169 | | { |
| | 623 | 170 | | foreach (var attribute in typeSymbol.GetAttributes()) |
| | | 171 | | { |
| | 169 | 172 | | var attributeName = attribute.AttributeClass?.Name; |
| | | 173 | | |
| | 169 | 174 | | if (attributeName is "SingletonAttribute" or "Singleton") |
| | | 175 | | { |
| | 18 | 176 | | return LifetimeRank.Singleton; |
| | | 177 | | } |
| | | 178 | | |
| | 151 | 179 | | if (attributeName is "ScopedAttribute" or "Scoped") |
| | | 180 | | { |
| | 32 | 181 | | return LifetimeRank.Scoped; |
| | | 182 | | } |
| | | 183 | | |
| | 119 | 184 | | if (attributeName is "TransientAttribute" or "Transient") |
| | | 185 | | { |
| | 9 | 186 | | return LifetimeRank.Transient; |
| | | 187 | | } |
| | | 188 | | } |
| | | 189 | | |
| | 113 | 190 | | return LifetimeRank.Unknown; |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | /// <summary> |
| | | 194 | | /// Check if the type is a factory pattern that safely handles lifetime management. |
| | | 195 | | /// </summary> |
| | | 196 | | private static bool IsFactoryPattern(INamedTypeSymbol typeSymbol) |
| | | 197 | | { |
| | 21 | 198 | | var name = typeSymbol.Name; |
| | 21 | 199 | | var fullName = typeSymbol.ToDisplayString(); |
| | | 200 | | |
| | | 201 | | // Func<T> - factory delegates |
| | 21 | 202 | | if (name == "Func" && typeSymbol.IsGenericType) |
| | | 203 | | { |
| | 1 | 204 | | return true; |
| | | 205 | | } |
| | | 206 | | |
| | | 207 | | // Lazy<T> - deferred resolution |
| | 20 | 208 | | if (name == "Lazy" && typeSymbol.IsGenericType) |
| | | 209 | | { |
| | 1 | 210 | | return true; |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | // IServiceScopeFactory - scope management |
| | 19 | 214 | | if (name == "IServiceScopeFactory" || fullName.Contains("IServiceScopeFactory")) |
| | | 215 | | { |
| | 0 | 216 | | return true; |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | // IServiceProvider - direct resolution |
| | 19 | 220 | | if (name == "IServiceProvider" || fullName.Contains("IServiceProvider")) |
| | | 221 | | { |
| | 0 | 222 | | return true; |
| | | 223 | | } |
| | | 224 | | |
| | 19 | 225 | | return false; |
| | | 226 | | } |
| | | 227 | | |
| | | 228 | | /// <summary> |
| | | 229 | | /// Get the concrete type to analyze. For concrete classes, returns the type itself. |
| | | 230 | | /// For interfaces, returns null (we can't determine the implementation). |
| | | 231 | | /// </summary> |
| | | 232 | | private static INamedTypeSymbol? GetConcreteTypeForAnalysis(INamedTypeSymbol typeSymbol) |
| | | 233 | | { |
| | | 234 | | // For interfaces, we can't determine the concrete implementation at compile time |
| | 19 | 235 | | if (typeSymbol.TypeKind == TypeKind.Interface) |
| | | 236 | | { |
| | 1 | 237 | | return null; |
| | | 238 | | } |
| | | 239 | | |
| | | 240 | | // For abstract classes, we can't determine which subclass will be used |
| | 18 | 241 | | if (typeSymbol.IsAbstract) |
| | | 242 | | { |
| | 0 | 243 | | return null; |
| | | 244 | | } |
| | | 245 | | |
| | 18 | 246 | | return typeSymbol; |
| | | 247 | | } |
| | | 248 | | |
| | | 249 | | /// <summary> |
| | | 250 | | /// Check if the type implements IDisposable or IAsyncDisposable. |
| | | 251 | | /// </summary> |
| | | 252 | | private static string? GetDisposableInterface(INamedTypeSymbol typeSymbol) |
| | | 253 | | { |
| | 42 | 254 | | foreach (var iface in typeSymbol.AllInterfaces) |
| | | 255 | | { |
| | 12 | 256 | | var fullName = iface.ToDisplayString(); |
| | 12 | 257 | | if (fullName == "System.IDisposable") |
| | | 258 | | { |
| | 10 | 259 | | return "IDisposable"; |
| | | 260 | | } |
| | | 261 | | |
| | 2 | 262 | | if (fullName == "System.IAsyncDisposable") |
| | | 263 | | { |
| | 2 | 264 | | return "IAsyncDisposable"; |
| | | 265 | | } |
| | | 266 | | } |
| | | 267 | | |
| | 3 | 268 | | return null; |
| | | 269 | | } |
| | | 270 | | |
| | 24 | 271 | | private static string GetLifetimeName(LifetimeRank lifetime) => lifetime switch |
| | 24 | 272 | | { |
| | 10 | 273 | | LifetimeRank.Singleton => "Singleton", |
| | 10 | 274 | | LifetimeRank.Scoped => "Scoped", |
| | 4 | 275 | | LifetimeRank.Transient => "Transient", |
| | 0 | 276 | | _ => "Unknown" |
| | 24 | 277 | | }; |
| | | 278 | | } |