| | | 1 | | // Copyright (c) NexusLabs. All rights reserved. |
| | | 2 | | // Licensed under the MIT License. |
| | | 3 | | |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Collections.Immutable; |
| | | 6 | | using System.Linq; |
| | | 7 | | |
| | | 8 | | using Microsoft.CodeAnalysis; |
| | | 9 | | using Microsoft.CodeAnalysis.CSharp; |
| | | 10 | | using Microsoft.CodeAnalysis.CSharp.Syntax; |
| | | 11 | | using Microsoft.CodeAnalysis.Diagnostics; |
| | | 12 | | |
| | | 13 | | namespace NexusLabs.Needlr.Generators; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Analyzer that validates [Options] attribute usage for validation configuration: |
| | | 17 | | /// - NDLRGEN014: Validator type has no validation method |
| | | 18 | | /// - NDLRGEN015: Validator type mismatch |
| | | 19 | | /// - NDLRGEN016: Validation method not found |
| | | 20 | | /// - NDLRGEN017: Validation method has wrong signature |
| | | 21 | | /// - NDLRGEN018: Validator won't run (ValidateOnStart = false) |
| | | 22 | | /// - NDLRGEN019: ValidateMethod won't run (ValidateOnStart = false) |
| | | 23 | | /// </summary> |
| | | 24 | | [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| | | 25 | | public sealed class OptionsAttributeAnalyzer : DiagnosticAnalyzer |
| | | 26 | | { |
| | | 27 | | private const string OptionsAttributeName = "OptionsAttribute"; |
| | | 28 | | private const string GeneratorsNamespace = "NexusLabs.Needlr.Generators"; |
| | | 29 | | private const string IOptionsValidatorName = "IOptionsValidator"; |
| | | 30 | | |
| | | 31 | | public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => |
| | 8 | 32 | | ImmutableArray.Create( |
| | 8 | 33 | | DiagnosticDescriptors.ValidatorTypeMissingInterface, |
| | 8 | 34 | | DiagnosticDescriptors.ValidatorTypeMismatch, |
| | 8 | 35 | | DiagnosticDescriptors.ValidateMethodNotFound, |
| | 8 | 36 | | DiagnosticDescriptors.ValidateMethodWrongSignature, |
| | 8 | 37 | | DiagnosticDescriptors.ValidatorWontRun, |
| | 8 | 38 | | DiagnosticDescriptors.ValidateMethodWontRun); |
| | | 39 | | |
| | | 40 | | public override void Initialize(AnalysisContext context) |
| | | 41 | | { |
| | 8 | 42 | | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| | 8 | 43 | | context.EnableConcurrentExecution(); |
| | | 44 | | |
| | 8 | 45 | | context.RegisterSyntaxNodeAction(AnalyzeOptionsAttribute, SyntaxKind.Attribute); |
| | 8 | 46 | | } |
| | | 47 | | |
| | | 48 | | private static void AnalyzeOptionsAttribute(SyntaxNodeAnalysisContext context) |
| | | 49 | | { |
| | 8 | 50 | | var attributeSyntax = (AttributeSyntax)context.Node; |
| | 8 | 51 | | var attributeSymbol = context.SemanticModel.GetSymbolInfo(attributeSyntax).Symbol?.ContainingType; |
| | | 52 | | |
| | 8 | 53 | | if (attributeSymbol == null) |
| | 0 | 54 | | return; |
| | | 55 | | |
| | | 56 | | // Check if this is an [Options] attribute |
| | 8 | 57 | | if (!IsOptionsAttribute(attributeSymbol)) |
| | 0 | 58 | | return; |
| | | 59 | | |
| | | 60 | | // Get the class this attribute is applied to |
| | 8 | 61 | | var classDeclaration = attributeSyntax.Parent?.Parent as ClassDeclarationSyntax; |
| | 8 | 62 | | if (classDeclaration == null) |
| | 0 | 63 | | return; |
| | | 64 | | |
| | 8 | 65 | | var classSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclaration); |
| | 8 | 66 | | if (classSymbol == null) |
| | 0 | 67 | | return; |
| | | 68 | | |
| | | 69 | | // Extract attribute properties |
| | 8 | 70 | | var attributeData = classSymbol.GetAttributes() |
| | 16 | 71 | | .FirstOrDefault(a => IsOptionsAttribute(a.AttributeClass)); |
| | | 72 | | |
| | 8 | 73 | | if (attributeData == null) |
| | 0 | 74 | | return; |
| | | 75 | | |
| | 8 | 76 | | bool validateOnStart = false; |
| | 8 | 77 | | string? validateMethod = null; |
| | 8 | 78 | | INamedTypeSymbol? validatorType = null; |
| | | 79 | | |
| | 40 | 80 | | foreach (var namedArg in attributeData.NamedArguments) |
| | | 81 | | { |
| | 12 | 82 | | switch (namedArg.Key) |
| | | 83 | | { |
| | | 84 | | case "ValidateOnStart": |
| | 5 | 85 | | validateOnStart = namedArg.Value.Value is true; |
| | 5 | 86 | | break; |
| | | 87 | | case "ValidateMethod": |
| | 3 | 88 | | validateMethod = namedArg.Value.Value as string; |
| | 3 | 89 | | break; |
| | | 90 | | case "Validator": |
| | 4 | 91 | | validatorType = namedArg.Value.Value as INamedTypeSymbol; |
| | | 92 | | break; |
| | | 93 | | } |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | // NDLRGEN018: Validator specified but ValidateOnStart is false |
| | 8 | 97 | | if (validatorType != null && !validateOnStart) |
| | | 98 | | { |
| | 1 | 99 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 100 | | DiagnosticDescriptors.ValidatorWontRun, |
| | 1 | 101 | | attributeSyntax.GetLocation(), |
| | 1 | 102 | | validatorType.Name)); |
| | | 103 | | } |
| | | 104 | | |
| | | 105 | | // NDLRGEN019: ValidateMethod specified but ValidateOnStart is false |
| | 8 | 106 | | if (validateMethod != null && !validateOnStart) |
| | | 107 | | { |
| | 1 | 108 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 109 | | DiagnosticDescriptors.ValidateMethodWontRun, |
| | 1 | 110 | | attributeSyntax.GetLocation(), |
| | 1 | 111 | | validateMethod)); |
| | | 112 | | } |
| | | 113 | | |
| | | 114 | | // If ValidateOnStart is true, validate the configuration |
| | 8 | 115 | | if (validateOnStart) |
| | | 116 | | { |
| | 5 | 117 | | var targetType = validatorType ?? classSymbol; |
| | 5 | 118 | | var methodName = validateMethod ?? "Validate"; |
| | | 119 | | |
| | | 120 | | // Check if validator is recognized by an extension (e.g., FluentValidation) |
| | | 121 | | // If so, skip our method signature checks - the extension handles it |
| | 5 | 122 | | var isRecognizedByExtension = validatorType != null && IsRecognizedByValidatorProvider(validatorType, contex |
| | | 123 | | |
| | | 124 | | // Find the validation method |
| | 5 | 125 | | var validationMethod = FindValidationMethod(targetType, methodName); |
| | | 126 | | |
| | | 127 | | // NDLRGEN016: Method not found |
| | | 128 | | // Skip if validator is recognized by an extension - they have their own method signatures |
| | 5 | 129 | | if (validationMethod == null && !isRecognizedByExtension) |
| | | 130 | | { |
| | | 131 | | // Only report if ValidateMethod was explicitly specified or Validator was specified |
| | | 132 | | // (convention-based discovery is optional - no method is OK if not specified) |
| | 2 | 133 | | if (validateMethod != null || validatorType != null) |
| | | 134 | | { |
| | 2 | 135 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 2 | 136 | | DiagnosticDescriptors.ValidateMethodNotFound, |
| | 2 | 137 | | attributeSyntax.GetLocation(), |
| | 2 | 138 | | methodName, |
| | 2 | 139 | | targetType.Name)); |
| | | 140 | | } |
| | | 141 | | } |
| | 3 | 142 | | else if (validationMethod != null && !isRecognizedByExtension) |
| | | 143 | | { |
| | | 144 | | // NDLRGEN017: Check method signature |
| | 3 | 145 | | var signatureError = ValidateMethodSignature(validationMethod, classSymbol, validatorType != null); |
| | 3 | 146 | | if (signatureError != null) |
| | | 147 | | { |
| | 0 | 148 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 0 | 149 | | DiagnosticDescriptors.ValidateMethodWrongSignature, |
| | 0 | 150 | | attributeSyntax.GetLocation(), |
| | 0 | 151 | | methodName, |
| | 0 | 152 | | targetType.Name, |
| | 0 | 153 | | signatureError)); |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | // NDLRGEN015: Validator type mismatch (if external validator with parameter) |
| | 3 | 157 | | if (validatorType != null && !validationMethod.IsStatic && validationMethod.Parameters.Length == 1) |
| | | 158 | | { |
| | 2 | 159 | | var paramType = validationMethod.Parameters[0].Type; |
| | 2 | 160 | | if (!SymbolEqualityComparer.Default.Equals(paramType, classSymbol)) |
| | | 161 | | { |
| | 1 | 162 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 163 | | DiagnosticDescriptors.ValidatorTypeMismatch, |
| | 1 | 164 | | attributeSyntax.GetLocation(), |
| | 1 | 165 | | validatorType.Name, |
| | 1 | 166 | | paramType.Name, |
| | 1 | 167 | | classSymbol.Name)); |
| | | 168 | | } |
| | | 169 | | } |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | // NDLRGEN014: Check if validator implements IOptionsValidator<T> or is recognized by an extension |
| | 5 | 173 | | if (validatorType != null && validationMethod == null && !isRecognizedByExtension) |
| | | 174 | | { |
| | 1 | 175 | | var implementsInterface = ImplementsIOptionsValidator(validatorType, classSymbol); |
| | 1 | 176 | | if (!implementsInterface) |
| | | 177 | | { |
| | 1 | 178 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 179 | | DiagnosticDescriptors.ValidatorTypeMissingInterface, |
| | 1 | 180 | | attributeSyntax.GetLocation(), |
| | 1 | 181 | | validatorType.Name, |
| | 1 | 182 | | classSymbol.Name)); |
| | | 183 | | } |
| | | 184 | | } |
| | | 185 | | } |
| | 8 | 186 | | } |
| | | 187 | | |
| | | 188 | | private static bool IsOptionsAttribute(INamedTypeSymbol? attributeClass) |
| | | 189 | | { |
| | 16 | 190 | | if (attributeClass == null) |
| | 0 | 191 | | return false; |
| | | 192 | | |
| | 16 | 193 | | return attributeClass.Name == OptionsAttributeName && |
| | 16 | 194 | | attributeClass.ContainingNamespace?.ToDisplayString() == GeneratorsNamespace; |
| | | 195 | | } |
| | | 196 | | |
| | | 197 | | private static IMethodSymbol? FindValidationMethod(INamedTypeSymbol targetType, string methodName) |
| | | 198 | | { |
| | 33 | 199 | | foreach (var member in targetType.GetMembers()) |
| | | 200 | | { |
| | 13 | 201 | | if (member is IMethodSymbol method && method.Name == methodName) |
| | | 202 | | { |
| | | 203 | | // Accept methods with 0 or 1 parameters |
| | 3 | 204 | | if (method.Parameters.Length <= 1) |
| | 3 | 205 | | return method; |
| | | 206 | | } |
| | | 207 | | } |
| | | 208 | | |
| | 2 | 209 | | return null; |
| | | 210 | | } |
| | | 211 | | |
| | | 212 | | private static string? ValidateMethodSignature(IMethodSymbol method, INamedTypeSymbol optionsType, bool isExternalVa |
| | | 213 | | { |
| | | 214 | | // Check return type - should be IEnumerable<something> |
| | 3 | 215 | | if (method.ReturnType is not INamedTypeSymbol returnType) |
| | 0 | 216 | | return "IEnumerable<ValidationError> or IEnumerable<string>"; |
| | | 217 | | |
| | 3 | 218 | | var isEnumerable = returnType.OriginalDefinition.ToDisplayString() == "System.Collections.Generic.IEnumerable<T> |
| | 3 | 219 | | returnType.AllInterfaces.Any(i => i.OriginalDefinition.ToDisplayString() == "System.Collectio |
| | | 220 | | |
| | 3 | 221 | | if (!isEnumerable && returnType.ToDisplayString() != "System.Collections.IEnumerable") |
| | | 222 | | { |
| | 0 | 223 | | return "IEnumerable<ValidationError> or IEnumerable<string>"; |
| | | 224 | | } |
| | | 225 | | |
| | | 226 | | // Check parameters |
| | 3 | 227 | | if (isExternalValidator) |
| | | 228 | | { |
| | | 229 | | // External validator should have one parameter of the options type |
| | 2 | 230 | | if (method.Parameters.Length != 1) |
| | | 231 | | { |
| | 0 | 232 | | return $"IEnumerable<ValidationError> {method.Name}({optionsType.Name} options)"; |
| | | 233 | | } |
| | | 234 | | } |
| | | 235 | | else |
| | | 236 | | { |
| | | 237 | | // Self-validation should have no parameters (unless static with one param) |
| | 1 | 238 | | if (!method.IsStatic && method.Parameters.Length != 0) |
| | | 239 | | { |
| | 0 | 240 | | return $"IEnumerable<ValidationError> {method.Name}()"; |
| | | 241 | | } |
| | | 242 | | |
| | 1 | 243 | | if (method.IsStatic && method.Parameters.Length != 1) |
| | | 244 | | { |
| | 0 | 245 | | return $"static IEnumerable<ValidationError> {method.Name}({optionsType.Name} options)"; |
| | | 246 | | } |
| | | 247 | | } |
| | | 248 | | |
| | 3 | 249 | | return null; // Valid signature |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | private static bool ImplementsIOptionsValidator(INamedTypeSymbol validatorType, INamedTypeSymbol optionsType) |
| | | 253 | | { |
| | 2 | 254 | | foreach (var iface in validatorType.AllInterfaces) |
| | | 255 | | { |
| | 0 | 256 | | if (iface.Name == IOptionsValidatorName && |
| | 0 | 257 | | iface.ContainingNamespace?.ToDisplayString() == GeneratorsNamespace && |
| | 0 | 258 | | iface.IsGenericType && |
| | 0 | 259 | | iface.TypeArguments.Length == 1) |
| | | 260 | | { |
| | | 261 | | // Check if the type argument matches the options type |
| | 0 | 262 | | if (SymbolEqualityComparer.Default.Equals(iface.TypeArguments[0], optionsType)) |
| | 0 | 263 | | return true; |
| | | 264 | | } |
| | | 265 | | } |
| | | 266 | | |
| | 1 | 267 | | return false; |
| | | 268 | | } |
| | | 269 | | |
| | | 270 | | private static bool IsRecognizedByValidatorProvider(INamedTypeSymbol validatorType, Compilation compilation) |
| | | 271 | | { |
| | | 272 | | // Collect all ValidatorProvider attributes from all referenced assemblies |
| | 3 | 273 | | var validatorBaseTypes = new HashSet<string>(); |
| | | 274 | | |
| | 1020 | 275 | | foreach (var reference in compilation.References) |
| | | 276 | | { |
| | 507 | 277 | | if (compilation.GetAssemblyOrModuleSymbol(reference) is not IAssemblySymbol assemblySymbol) |
| | | 278 | | continue; |
| | | 279 | | |
| | 20058 | 280 | | foreach (var attr in assemblySymbol.GetAttributes()) |
| | | 281 | | { |
| | 9525 | 282 | | if (attr.AttributeClass?.Name != "ValidatorProviderAttribute") |
| | | 283 | | continue; |
| | 0 | 284 | | if (attr.AttributeClass.ContainingNamespace?.ToDisplayString() != GeneratorsNamespace) |
| | | 285 | | continue; |
| | | 286 | | |
| | 0 | 287 | | if (attr.ConstructorArguments.Length > 0 && |
| | 0 | 288 | | attr.ConstructorArguments[0].Value is string baseTypeName) |
| | | 289 | | { |
| | 0 | 290 | | validatorBaseTypes.Add(baseTypeName); |
| | | 291 | | } |
| | | 292 | | } |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | // Check if validatorType inherits from any recognized base |
| | 3 | 296 | | return validatorBaseTypes.Any(baseTypeName => |
| | 3 | 297 | | InheritsFromByMetadataName(validatorType, baseTypeName)); |
| | | 298 | | } |
| | | 299 | | |
| | | 300 | | private static bool InheritsFromByMetadataName(INamedTypeSymbol type, string metadataName) |
| | | 301 | | { |
| | 0 | 302 | | var current = type.BaseType; |
| | 0 | 303 | | while (current != null) |
| | | 304 | | { |
| | 0 | 305 | | var fullName = current.OriginalDefinition.ContainingNamespace?.ToDisplayString() + "." + |
| | 0 | 306 | | current.OriginalDefinition.MetadataName; |
| | 0 | 307 | | if (fullName == metadataName) |
| | 0 | 308 | | return true; |
| | 0 | 309 | | current = current.BaseType; |
| | | 310 | | } |
| | 0 | 311 | | return false; |
| | | 312 | | } |
| | | 313 | | } |