| | | 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 | | using NexusLabs.Needlr.Roslyn.Shared; |
| | | 9 | | |
| | | 10 | | namespace NexusLabs.Needlr.Analyzers; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Analyzer that detects circular dependencies in service registrations. |
| | | 14 | | /// A circular dependency occurs when a service directly or indirectly depends on itself. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <remarks> |
| | | 17 | | /// Examples: |
| | | 18 | | /// - A → B → A (direct cycle) |
| | | 19 | | /// - A → B → C → A (indirect cycle) |
| | | 20 | | /// </remarks> |
| | | 21 | | [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| | | 22 | | public sealed class CircularDependencyAnalyzer : DiagnosticAnalyzer |
| | | 23 | | { |
| | | 24 | | public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => |
| | 270 | 25 | | ImmutableArray.Create(DiagnosticDescriptors.CircularDependency); |
| | | 26 | | |
| | | 27 | | public override void Initialize(AnalysisContext context) |
| | | 28 | | { |
| | 25 | 29 | | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| | 25 | 30 | | context.EnableConcurrentExecution(); |
| | | 31 | | |
| | | 32 | | // We need to analyze at compilation level to build the full dependency graph |
| | 25 | 33 | | context.RegisterCompilationStartAction(compilationContext => |
| | 25 | 34 | | { |
| | 15 | 35 | | var dependencyGraph = new DependencyGraphBuilder(); |
| | 25 | 36 | | |
| | 25 | 37 | | // First pass: collect all types and their dependencies |
| | 15 | 38 | | compilationContext.RegisterSyntaxNodeAction( |
| | 133 | 39 | | nodeContext => CollectDependencies(nodeContext, dependencyGraph), |
| | 15 | 40 | | SyntaxKind.ClassDeclaration); |
| | 25 | 41 | | |
| | 25 | 42 | | // End of compilation: analyze for cycles |
| | 15 | 43 | | compilationContext.RegisterCompilationEndAction( |
| | 30 | 44 | | endContext => AnalyzeForCycles(endContext, dependencyGraph)); |
| | 40 | 45 | | }); |
| | 25 | 46 | | } |
| | | 47 | | |
| | | 48 | | private static void CollectDependencies(SyntaxNodeAnalysisContext context, DependencyGraphBuilder graph) |
| | | 49 | | { |
| | 133 | 50 | | var classDeclaration = (ClassDeclarationSyntax)context.Node; |
| | | 51 | | |
| | | 52 | | // Skip abstract classes |
| | 133 | 53 | | if (classDeclaration.Modifiers.Any(SyntaxKind.AbstractKeyword)) |
| | | 54 | | { |
| | 0 | 55 | | return; |
| | | 56 | | } |
| | | 57 | | |
| | 133 | 58 | | var classSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclaration); |
| | 133 | 59 | | if (classSymbol == null) |
| | | 60 | | { |
| | 0 | 61 | | return; |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | // Check if this is a registered service (has registration attributes) |
| | 133 | 65 | | if (!IsRegisteredService(classSymbol)) |
| | | 66 | | { |
| | 103 | 67 | | return; |
| | | 68 | | } |
| | | 69 | | |
| | 30 | 70 | | var dependencies = new List<INamedTypeSymbol>(); |
| | 30 | 71 | | var location = classDeclaration.Identifier.GetLocation(); |
| | | 72 | | |
| | | 73 | | // Collect dependencies from primary constructor |
| | 30 | 74 | | if (classDeclaration.ParameterList != null) |
| | | 75 | | { |
| | 20 | 76 | | foreach (var parameter in classDeclaration.ParameterList.Parameters) |
| | | 77 | | { |
| | 5 | 78 | | if (parameter.Type == null) continue; |
| | | 79 | | |
| | 5 | 80 | | var typeInfo = context.SemanticModel.GetTypeInfo(parameter.Type); |
| | 5 | 81 | | if (typeInfo.Type is INamedTypeSymbol paramType) |
| | | 82 | | { |
| | 5 | 83 | | dependencies.Add(paramType); |
| | | 84 | | } |
| | | 85 | | } |
| | | 86 | | } |
| | | 87 | | |
| | | 88 | | // Collect dependencies from explicit constructors |
| | 30 | 89 | | var constructors = classDeclaration.Members |
| | 30 | 90 | | .OfType<ConstructorDeclarationSyntax>() |
| | 16 | 91 | | .Where(c => !c.Modifiers.Any(SyntaxKind.StaticKeyword)) |
| | 30 | 92 | | .ToList(); |
| | | 93 | | |
| | 92 | 94 | | foreach (var constructor in constructors) |
| | | 95 | | { |
| | 64 | 96 | | foreach (var parameter in constructor.ParameterList.Parameters) |
| | | 97 | | { |
| | 16 | 98 | | if (parameter.Type == null) continue; |
| | | 99 | | |
| | 16 | 100 | | var typeInfo = context.SemanticModel.GetTypeInfo(parameter.Type); |
| | 16 | 101 | | if (typeInfo.Type is INamedTypeSymbol paramType) |
| | | 102 | | { |
| | 16 | 103 | | dependencies.Add(paramType); |
| | | 104 | | } |
| | | 105 | | } |
| | | 106 | | } |
| | | 107 | | |
| | | 108 | | // A type with [GenerateConstructor] or a positive field-level constructor guard |
| | | 109 | | // trigger has its effective constructor emitted by a sibling source generator |
| | | 110 | | // rather than authored in this class's own syntax tree, so its dependencies must |
| | | 111 | | // be derived from the shared eligible-field model instead of from constructor |
| | | 112 | | // parameter syntax. This makes such a dependency participate in cycle detection |
| | | 113 | | // exactly like a hand-written constructor parameter. GetEligibleConstructorFields |
| | | 114 | | // already excludes fields marked [ConstructorIgnore] and fields with an |
| | | 115 | | // initializer, so those never contribute a false dependency here. |
| | 30 | 116 | | if (GeneratedConstructorEligibility.IsEligibleForGeneratedConstructor(classSymbol)) |
| | | 117 | | { |
| | 28 | 118 | | foreach (var field in GeneratedConstructorEligibility.GetEligibleConstructorFields(classSymbol)) |
| | | 119 | | { |
| | 7 | 120 | | if (field.Type is INamedTypeSymbol fieldType) |
| | | 121 | | { |
| | 7 | 122 | | dependencies.Add(fieldType); |
| | | 123 | | } |
| | | 124 | | } |
| | | 125 | | } |
| | | 126 | | |
| | 30 | 127 | | graph.AddNode(classSymbol, dependencies, location); |
| | 30 | 128 | | } |
| | | 129 | | |
| | | 130 | | private static void AnalyzeForCycles(CompilationAnalysisContext context, DependencyGraphBuilder graph) |
| | | 131 | | { |
| | 15 | 132 | | var cycles = graph.DetectCycles(); |
| | | 133 | | |
| | 50 | 134 | | foreach (var cycle in cycles) |
| | | 135 | | { |
| | 32 | 136 | | var cycleDescription = string.Join(" → ", cycle.Path.Select(t => t.Name)) + " → " + cycle.Path[0].Name; |
| | | 137 | | |
| | 10 | 138 | | var diagnostic = Diagnostic.Create( |
| | 10 | 139 | | DiagnosticDescriptors.CircularDependency, |
| | 10 | 140 | | cycle.Location, |
| | 10 | 141 | | cycleDescription); |
| | | 142 | | |
| | 10 | 143 | | context.ReportDiagnostic(diagnostic); |
| | | 144 | | } |
| | 15 | 145 | | } |
| | | 146 | | |
| | | 147 | | private static bool IsRegisteredService(INamedTypeSymbol typeSymbol) |
| | | 148 | | { |
| | 133 | 149 | | var registrationAttributes = new[] |
| | 133 | 150 | | { |
| | 133 | 151 | | "RegisterAsAttribute", "RegisterAs", |
| | 133 | 152 | | "SingletonAttribute", "Singleton", |
| | 133 | 153 | | "ScopedAttribute", "Scoped", |
| | 133 | 154 | | "TransientAttribute", "Transient", |
| | 133 | 155 | | "AutoRegisterAttribute", "AutoRegister" |
| | 133 | 156 | | }; |
| | | 157 | | |
| | 496 | 158 | | foreach (var attribute in typeSymbol.GetAttributes()) |
| | | 159 | | { |
| | 130 | 160 | | var attributeName = attribute.AttributeClass?.Name; |
| | 130 | 161 | | if (attributeName != null && registrationAttributes.Contains(attributeName)) |
| | | 162 | | { |
| | 30 | 163 | | return true; |
| | | 164 | | } |
| | | 165 | | } |
| | | 166 | | |
| | 103 | 167 | | return false; |
| | | 168 | | } |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// Builds a dependency graph and detects cycles. |
| | | 172 | | /// </summary> |
| | | 173 | | private class DependencyGraphBuilder |
| | | 174 | | { |
| | 15 | 175 | | private readonly Dictionary<INamedTypeSymbol, NodeInfo> _nodes = new(SymbolEqualityComparer.Default); |
| | 15 | 176 | | private readonly object _lock = new(); |
| | | 177 | | |
| | | 178 | | public void AddNode(INamedTypeSymbol type, List<INamedTypeSymbol> dependencies, Location location) |
| | | 179 | | { |
| | 30 | 180 | | lock (_lock) |
| | | 181 | | { |
| | 30 | 182 | | _nodes[type] = new NodeInfo(dependencies, location); |
| | 30 | 183 | | } |
| | 30 | 184 | | } |
| | | 185 | | |
| | | 186 | | public List<CycleInfo> DetectCycles() |
| | | 187 | | { |
| | 15 | 188 | | var cycles = new List<CycleInfo>(); |
| | 15 | 189 | | var visited = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); |
| | 15 | 190 | | var recursionStack = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); |
| | 15 | 191 | | var path = new List<INamedTypeSymbol>(); |
| | | 192 | | |
| | | 193 | | // Sort by full type name for deterministic iteration order |
| | 44 | 194 | | var sortedNodes = _nodes.Keys.OrderBy(n => n.ToDisplayString()).ToList(); |
| | 90 | 195 | | foreach (var node in sortedNodes) |
| | | 196 | | { |
| | 30 | 197 | | if (!visited.Contains(node)) |
| | | 198 | | { |
| | 17 | 199 | | DetectCyclesDfs(node, visited, recursionStack, path, cycles); |
| | | 200 | | } |
| | | 201 | | } |
| | | 202 | | |
| | 15 | 203 | | return cycles; |
| | | 204 | | } |
| | | 205 | | |
| | | 206 | | private void DetectCyclesDfs( |
| | | 207 | | INamedTypeSymbol current, |
| | | 208 | | HashSet<INamedTypeSymbol> visited, |
| | | 209 | | HashSet<INamedTypeSymbol> recursionStack, |
| | | 210 | | List<INamedTypeSymbol> path, |
| | | 211 | | List<CycleInfo> cycles) |
| | | 212 | | { |
| | 32 | 213 | | visited.Add(current); |
| | 32 | 214 | | recursionStack.Add(current); |
| | 32 | 215 | | path.Add(current); |
| | | 216 | | |
| | 32 | 217 | | if (_nodes.TryGetValue(current, out var nodeInfo)) |
| | | 218 | | { |
| | 116 | 219 | | foreach (var dependency in nodeInfo.Dependencies) |
| | | 220 | | { |
| | | 221 | | // Resolve interface to implementation if possible |
| | 28 | 222 | | var resolvedDep = ResolveDependency(dependency); |
| | | 223 | | |
| | 28 | 224 | | if (!visited.Contains(resolvedDep)) |
| | | 225 | | { |
| | 15 | 226 | | DetectCyclesDfs(resolvedDep, visited, recursionStack, path, cycles); |
| | | 227 | | } |
| | 13 | 228 | | else if (recursionStack.Contains(resolvedDep)) |
| | | 229 | | { |
| | | 230 | | // Found a cycle - extract the cycle path |
| | 10 | 231 | | var cycleStartIndex = path.IndexOf(resolvedDep); |
| | 10 | 232 | | if (cycleStartIndex >= 0) |
| | | 233 | | { |
| | 10 | 234 | | var cyclePath = path.Skip(cycleStartIndex).ToList(); |
| | 10 | 235 | | cycles.Add(new CycleInfo(cyclePath, nodeInfo.Location)); |
| | | 236 | | } |
| | | 237 | | } |
| | | 238 | | } |
| | | 239 | | } |
| | | 240 | | |
| | 32 | 241 | | path.RemoveAt(path.Count - 1); |
| | 32 | 242 | | recursionStack.Remove(current); |
| | 32 | 243 | | } |
| | | 244 | | |
| | | 245 | | private INamedTypeSymbol ResolveDependency(INamedTypeSymbol dependency) |
| | | 246 | | { |
| | | 247 | | // If it's an interface or abstract, try to find an implementation in our graph |
| | 28 | 248 | | if (dependency.TypeKind == TypeKind.Interface || dependency.IsAbstract) |
| | | 249 | | { |
| | 0 | 250 | | foreach (var kvp in _nodes) |
| | | 251 | | { |
| | 0 | 252 | | var type = kvp.Key; |
| | 0 | 253 | | if (type.AllInterfaces.Any(i => SymbolEqualityComparer.Default.Equals(i, dependency)) || |
| | 0 | 254 | | (type.BaseType != null && SymbolEqualityComparer.Default.Equals(type.BaseType, dependency))) |
| | | 255 | | { |
| | 0 | 256 | | return type; |
| | | 257 | | } |
| | | 258 | | } |
| | | 259 | | } |
| | | 260 | | |
| | 28 | 261 | | return dependency; |
| | 0 | 262 | | } |
| | | 263 | | |
| | | 264 | | private sealed class NodeInfo |
| | | 265 | | { |
| | 30 | 266 | | public List<INamedTypeSymbol> Dependencies { get; } |
| | 10 | 267 | | public Location Location { get; } |
| | | 268 | | |
| | 30 | 269 | | public NodeInfo(List<INamedTypeSymbol> dependencies, Location location) |
| | | 270 | | { |
| | 30 | 271 | | Dependencies = dependencies; |
| | 30 | 272 | | Location = location; |
| | 30 | 273 | | } |
| | | 274 | | } |
| | | 275 | | } |
| | | 276 | | |
| | | 277 | | private sealed class CycleInfo |
| | | 278 | | { |
| | 20 | 279 | | public List<INamedTypeSymbol> Path { get; } |
| | 10 | 280 | | public Location Location { get; } |
| | | 281 | | |
| | 10 | 282 | | public CycleInfo(List<INamedTypeSymbol> path, Location location) |
| | | 283 | | { |
| | 10 | 284 | | Path = path; |
| | 10 | 285 | | Location = location; |
| | 10 | 286 | | } |
| | | 287 | | } |
| | | 288 | | } |