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