| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Collections.Immutable; |
| | | 3 | | |
| | | 4 | | using Microsoft.CodeAnalysis; |
| | | 5 | | using Microsoft.CodeAnalysis.CSharp; |
| | | 6 | | using Microsoft.CodeAnalysis.CSharp.Syntax; |
| | | 7 | | using Microsoft.CodeAnalysis.Diagnostics; |
| | | 8 | | |
| | | 9 | | namespace NexusLabs.Needlr.Analyzers; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Analyzer that validates [FromKeyedServices] usage against discovered [Keyed] registrations. |
| | | 13 | | /// Reports Info-level diagnostic when a key is not found in statically-discovered registrations. |
| | | 14 | | /// Only active when [assembly: GenerateTypeRegistry] is present. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <remarks> |
| | | 17 | | /// <para> |
| | | 18 | | /// This analyzer collects all [Keyed("key")] attributes from types in the compilation |
| | | 19 | | /// and validates that [FromKeyedServices("key")] parameters reference known keys. |
| | | 20 | | /// </para> |
| | | 21 | | /// <para> |
| | | 22 | | /// Keys registered via plugins at runtime cannot be validated at compile time. |
| | | 23 | | /// Users can suppress this diagnostic for such cases. |
| | | 24 | | /// </para> |
| | | 25 | | /// </remarks> |
| | | 26 | | [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| | | 27 | | public sealed class KeyedServiceResolutionAnalyzer : DiagnosticAnalyzer |
| | | 28 | | { |
| | | 29 | | private const string GenerateTypeRegistryAttributeName = "NexusLabs.Needlr.Generators.GenerateTypeRegistryAttribute" |
| | | 30 | | private const string FromKeyedServicesAttributeName = "Microsoft.Extensions.DependencyInjection.FromKeyedServicesAtt |
| | | 31 | | private const string KeyedAttributeName = "KeyedAttribute"; |
| | | 32 | | private const string KeyedAttributeFullName = "NexusLabs.Needlr.KeyedAttribute"; |
| | | 33 | | |
| | | 34 | | public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => |
| | 262 | 35 | | ImmutableArray.Create(DiagnosticDescriptors.KeyedServiceUnknownKey); |
| | | 36 | | |
| | | 37 | | public override void Initialize(AnalysisContext context) |
| | | 38 | | { |
| | 20 | 39 | | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| | 20 | 40 | | context.EnableConcurrentExecution(); |
| | | 41 | | |
| | 20 | 42 | | context.RegisterCompilationStartAction(compilationContext => |
| | 20 | 43 | | { |
| | 12 | 44 | | if (!HasGenerateTypeRegistryAttribute(compilationContext.Compilation)) |
| | 1 | 45 | | return; |
| | 20 | 46 | | |
| | 11 | 47 | | var fromKeyedServicesType = compilationContext.Compilation.GetTypeByMetadataName(FromKeyedServicesAttributeN |
| | 11 | 48 | | if (fromKeyedServicesType == null) |
| | 1 | 49 | | return; |
| | 20 | 50 | | |
| | 20 | 51 | | // Collect discovered [Keyed] registrations: key -> list of (serviceType, implType) |
| | 10 | 52 | | var discoveredKeys = new ConcurrentDictionary<string, ConcurrentBag<(string ServiceType, string ImplType)>>( |
| | 20 | 53 | | |
| | 20 | 54 | | // Collect pending usages to validate: (location, serviceType, key) |
| | 10 | 55 | | var pendingUsages = new ConcurrentBag<(Location Location, string ServiceType, string Key)>(); |
| | 20 | 56 | | |
| | 20 | 57 | | // Collect [Keyed] attributes from class declarations |
| | 10 | 58 | | compilationContext.RegisterSymbolAction( |
| | 48 | 59 | | ctx => CollectKeyedRegistration(ctx, discoveredKeys), |
| | 10 | 60 | | SymbolKind.NamedType); |
| | 20 | 61 | | |
| | 20 | 62 | | // Collect [FromKeyedServices] parameters |
| | 10 | 63 | | compilationContext.RegisterSyntaxNodeAction( |
| | 29 | 64 | | ctx => CollectKeyedServiceParameter(ctx, fromKeyedServicesType, pendingUsages), |
| | 10 | 65 | | SyntaxKind.Parameter); |
| | 20 | 66 | | |
| | 20 | 67 | | // Validate at compilation end |
| | 10 | 68 | | compilationContext.RegisterCompilationEndAction(endContext => |
| | 10 | 69 | | { |
| | 46 | 70 | | foreach (var (location, serviceType, key) in pendingUsages) |
| | 10 | 71 | | { |
| | 10 | 72 | | // Check if key is found in discovered registrations |
| | 13 | 73 | | if (discoveredKeys.TryGetValue(key, out var registrations)) |
| | 10 | 74 | | { |
| | 10 | 75 | | // Key exists - check if any registration matches the service type |
| | 10 | 76 | | // For now, just having the key is enough (interface matching is complex) |
| | 10 | 77 | | continue; |
| | 10 | 78 | | } |
| | 10 | 79 | | |
| | 10 | 80 | | // Key not found in statically-discovered registrations |
| | 10 | 81 | | var diagnostic = Diagnostic.Create( |
| | 10 | 82 | | DiagnosticDescriptors.KeyedServiceUnknownKey, |
| | 10 | 83 | | location, |
| | 10 | 84 | | serviceType, |
| | 10 | 85 | | key); |
| | 10 | 86 | | |
| | 10 | 87 | | endContext.ReportDiagnostic(diagnostic); |
| | 10 | 88 | | } |
| | 20 | 89 | | }); |
| | 30 | 90 | | }); |
| | 20 | 91 | | } |
| | | 92 | | |
| | | 93 | | private static bool HasGenerateTypeRegistryAttribute(Compilation compilation) |
| | | 94 | | { |
| | 35 | 95 | | foreach (var attribute in compilation.Assembly.GetAttributes()) |
| | | 96 | | { |
| | 11 | 97 | | var fullName = attribute.AttributeClass?.ToDisplayString(); |
| | 11 | 98 | | if (fullName == GenerateTypeRegistryAttributeName) |
| | 11 | 99 | | return true; |
| | | 100 | | } |
| | | 101 | | |
| | 1 | 102 | | return false; |
| | | 103 | | } |
| | | 104 | | |
| | | 105 | | private static void CollectKeyedRegistration( |
| | | 106 | | SymbolAnalysisContext context, |
| | | 107 | | ConcurrentDictionary<string, ConcurrentBag<(string, string)>> discoveredKeys) |
| | | 108 | | { |
| | 48 | 109 | | var typeSymbol = (INamedTypeSymbol)context.Symbol; |
| | | 110 | | |
| | | 111 | | // Skip non-classes |
| | 48 | 112 | | if (typeSymbol.TypeKind != TypeKind.Class) |
| | 12 | 113 | | return; |
| | | 114 | | |
| | | 115 | | // Look for [Keyed] attributes |
| | 104 | 116 | | foreach (var attr in typeSymbol.GetAttributes()) |
| | | 117 | | { |
| | 16 | 118 | | var attrClass = attr.AttributeClass; |
| | 16 | 119 | | if (attrClass == null) |
| | | 120 | | continue; |
| | | 121 | | |
| | 16 | 122 | | var name = attrClass.Name; |
| | 16 | 123 | | var fullName = attrClass.ToDisplayString(); |
| | | 124 | | |
| | 16 | 125 | | if (name != KeyedAttributeName && fullName != KeyedAttributeFullName) |
| | | 126 | | continue; |
| | | 127 | | |
| | | 128 | | // Extract the key from the constructor argument |
| | 3 | 129 | | if (attr.ConstructorArguments.Length == 0) |
| | | 130 | | continue; |
| | | 131 | | |
| | 3 | 132 | | var keyArg = attr.ConstructorArguments[0]; |
| | 3 | 133 | | if (keyArg.Value is not string key) |
| | | 134 | | continue; |
| | | 135 | | |
| | | 136 | | // Get the interfaces this type implements |
| | 3 | 137 | | var implTypeName = typeSymbol.ToDisplayString(); |
| | 12 | 138 | | foreach (var iface in typeSymbol.AllInterfaces) |
| | | 139 | | { |
| | | 140 | | // Skip framework interfaces |
| | 3 | 141 | | var ns = iface.ContainingNamespace?.ToDisplayString() ?? ""; |
| | 3 | 142 | | if (ns.StartsWith("System") || ns.StartsWith("Microsoft")) |
| | | 143 | | continue; |
| | | 144 | | |
| | 6 | 145 | | var bag = discoveredKeys.GetOrAdd(key, _ => new ConcurrentBag<(string, string)>()); |
| | 3 | 146 | | bag.Add((iface.ToDisplayString(), implTypeName)); |
| | | 147 | | } |
| | | 148 | | |
| | | 149 | | // Also add self-registration |
| | 3 | 150 | | var selfBag = discoveredKeys.GetOrAdd(key, _ => new ConcurrentBag<(string, string)>()); |
| | 3 | 151 | | selfBag.Add((implTypeName, implTypeName)); |
| | | 152 | | } |
| | 36 | 153 | | } |
| | | 154 | | |
| | | 155 | | private static void CollectKeyedServiceParameter( |
| | | 156 | | SyntaxNodeAnalysisContext context, |
| | | 157 | | INamedTypeSymbol fromKeyedServicesType, |
| | | 158 | | ConcurrentBag<(Location, string, string)> pendingUsages) |
| | | 159 | | { |
| | 29 | 160 | | var parameter = (ParameterSyntax)context.Node; |
| | | 161 | | |
| | | 162 | | // Get the parameter symbol to access attributes |
| | 29 | 163 | | var parameterSymbol = context.SemanticModel.GetDeclaredSymbol(parameter); |
| | 29 | 164 | | if (parameterSymbol == null) |
| | 0 | 165 | | return; |
| | | 166 | | |
| | | 167 | | // Look for [FromKeyedServices] attribute |
| | 73 | 168 | | foreach (var attr in parameterSymbol.GetAttributes()) |
| | | 169 | | { |
| | 14 | 170 | | if (!SymbolEqualityComparer.Default.Equals(attr.AttributeClass, fromKeyedServicesType)) |
| | | 171 | | continue; |
| | | 172 | | |
| | | 173 | | // Extract the key from the constructor argument |
| | 14 | 174 | | if (attr.ConstructorArguments.Length == 0) |
| | | 175 | | continue; |
| | | 176 | | |
| | 14 | 177 | | var keyArg = attr.ConstructorArguments[0]; |
| | 14 | 178 | | if (keyArg.Value is not string key) |
| | | 179 | | continue; |
| | | 180 | | |
| | | 181 | | // Get the parameter type |
| | 14 | 182 | | var parameterType = parameterSymbol.Type; |
| | 14 | 183 | | var typeName = parameterType.Name; |
| | | 184 | | |
| | | 185 | | // Skip framework types |
| | 14 | 186 | | var ns = parameterType.ContainingNamespace?.ToDisplayString() ?? ""; |
| | 14 | 187 | | if (ns.StartsWith("Microsoft.Extensions.") || |
| | 14 | 188 | | ns.StartsWith("Microsoft.AspNetCore.") || |
| | 14 | 189 | | ns == "System" || |
| | 14 | 190 | | ns.StartsWith("System.")) |
| | | 191 | | { |
| | | 192 | | continue; |
| | | 193 | | } |
| | | 194 | | |
| | 13 | 195 | | pendingUsages.Add((parameter.GetLocation(), typeName, key)); |
| | 13 | 196 | | break; |
| | | 197 | | } |
| | 16 | 198 | | } |
| | | 199 | | } |