| | | 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 | | |
| | | 30 | | public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => |
| | 32 | 31 | | ImmutableArray.Create( |
| | 32 | 32 | | DiagnosticDescriptors.ValidatorTypeMissingInterface, |
| | 32 | 33 | | DiagnosticDescriptors.ValidatorTypeMismatch, |
| | 32 | 34 | | DiagnosticDescriptors.ValidateMethodNotFound, |
| | 32 | 35 | | DiagnosticDescriptors.ValidateMethodWrongSignature, |
| | 32 | 36 | | DiagnosticDescriptors.ValidatorWontRun, |
| | 32 | 37 | | DiagnosticDescriptors.ValidateMethodWontRun); |
| | | 38 | | |
| | | 39 | | public override void Initialize(AnalysisContext context) |
| | | 40 | | { |
| | 32 | 41 | | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| | 32 | 42 | | context.EnableConcurrentExecution(); |
| | | 43 | | |
| | 32 | 44 | | context.RegisterSyntaxNodeAction(AnalyzeOptionsAttribute, SyntaxKind.Attribute); |
| | 32 | 45 | | } |
| | | 46 | | |
| | | 47 | | private static void AnalyzeOptionsAttribute(SyntaxNodeAnalysisContext context) |
| | | 48 | | { |
| | 33 | 49 | | var attributeSyntax = (AttributeSyntax)context.Node; |
| | 33 | 50 | | var attributeSymbol = context.SemanticModel.GetSymbolInfo(attributeSyntax).Symbol?.ContainingType; |
| | | 51 | | |
| | 33 | 52 | | if (attributeSymbol == null) |
| | 0 | 53 | | return; |
| | | 54 | | |
| | | 55 | | // Check if this is an [Options] attribute |
| | 33 | 56 | | if (!IsOptionsAttribute(attributeSymbol)) |
| | 2 | 57 | | return; |
| | | 58 | | |
| | | 59 | | // Get the type this attribute is applied to |
| | 31 | 60 | | var typeDeclaration = attributeSyntax.Parent?.Parent as TypeDeclarationSyntax; |
| | 31 | 61 | | if (typeDeclaration == null) |
| | 0 | 62 | | return; |
| | | 63 | | |
| | 31 | 64 | | var optionsType = context.SemanticModel.GetDeclaredSymbol(typeDeclaration); |
| | 31 | 65 | | if (optionsType == null) |
| | 0 | 66 | | return; |
| | | 67 | | |
| | | 68 | | // Extract attribute properties |
| | 31 | 69 | | var attributeData = optionsType.GetAttributes() |
| | 62 | 70 | | .FirstOrDefault(a => IsOptionsAttribute(a.AttributeClass)); |
| | | 71 | | |
| | 31 | 72 | | if (attributeData == null) |
| | 0 | 73 | | return; |
| | | 74 | | |
| | 31 | 75 | | bool validateOnStart = false; |
| | 31 | 76 | | string? validateMethod = null; |
| | 31 | 77 | | INamedTypeSymbol? validatorType = null; |
| | | 78 | | |
| | 154 | 79 | | foreach (var namedArg in attributeData.NamedArguments) |
| | | 80 | | { |
| | 46 | 81 | | switch (namedArg.Key) |
| | | 82 | | { |
| | | 83 | | case "ValidateOnStart": |
| | 28 | 84 | | validateOnStart = namedArg.Value.Value is true; |
| | 28 | 85 | | break; |
| | | 86 | | case "ValidateMethod": |
| | 4 | 87 | | validateMethod = namedArg.Value.Value as string; |
| | 4 | 88 | | break; |
| | | 89 | | case "Validator": |
| | 14 | 90 | | validatorType = namedArg.Value.Value as INamedTypeSymbol; |
| | | 91 | | break; |
| | | 92 | | } |
| | | 93 | | } |
| | | 94 | | |
| | | 95 | | // NDLRGEN018: Validator specified but ValidateOnStart is false |
| | 31 | 96 | | if (validatorType != null && !validateOnStart) |
| | | 97 | | { |
| | 1 | 98 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 99 | | DiagnosticDescriptors.ValidatorWontRun, |
| | 1 | 100 | | attributeSyntax.GetLocation(), |
| | 1 | 101 | | validatorType.Name)); |
| | | 102 | | } |
| | | 103 | | |
| | | 104 | | // NDLRGEN019: ValidateMethod specified but ValidateOnStart is false |
| | 31 | 105 | | if (validateMethod != null && !validateOnStart) |
| | | 106 | | { |
| | 1 | 107 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 108 | | DiagnosticDescriptors.ValidateMethodWontRun, |
| | 1 | 109 | | attributeSyntax.GetLocation(), |
| | 1 | 110 | | validateMethod)); |
| | | 111 | | } |
| | | 112 | | |
| | | 113 | | // If ValidateOnStart is true, validate the configuration |
| | 31 | 114 | | if (validateOnStart) |
| | | 115 | | { |
| | 28 | 116 | | var targetType = validatorType ?? optionsType; |
| | 28 | 117 | | var methodName = validateMethod ?? "Validate"; |
| | | 118 | | |
| | | 119 | | // Check if validator is recognized by an extension (e.g., FluentValidation) |
| | | 120 | | // If so, skip our method signature checks - the extension handles it |
| | 28 | 121 | | var isRecognizedByExtension = validatorType != null && IsRecognizedByValidatorProvider(validatorType, contex |
| | 28 | 122 | | if (isRecognizedByExtension) |
| | 2 | 123 | | return; |
| | | 124 | | |
| | 26 | 125 | | var validationMethods = OptionsAttributeHelper |
| | 26 | 126 | | .GetValidationMethods(targetType, methodName) |
| | 26 | 127 | | .ToArray(); |
| | 26 | 128 | | var validMethod = validationMethods.FirstOrDefault(method => |
| | 48 | 129 | | OptionsAttributeHelper.GetValidationMethodSignatureError( |
| | 48 | 130 | | method, |
| | 48 | 131 | | optionsType, |
| | 48 | 132 | | validatorType != null) == null && |
| | 48 | 133 | | (validatorType == null || |
| | 48 | 134 | | (method.Parameters.Length == 1 && |
| | 48 | 135 | | SymbolEqualityComparer.Default.Equals(method.Parameters[0].Type, optionsType)))); |
| | | 136 | | |
| | 26 | 137 | | if (validMethod != null) |
| | 7 | 138 | | return; |
| | | 139 | | |
| | 19 | 140 | | if (validationMethods.Length > 0) |
| | | 141 | | { |
| | 13 | 142 | | var validationMethod = validationMethods[0]; |
| | 13 | 143 | | var signatureError = |
| | 13 | 144 | | OptionsAttributeHelper.GetValidationMethodSignatureError( |
| | 13 | 145 | | validationMethod, |
| | 13 | 146 | | optionsType, |
| | 13 | 147 | | validatorType != null); |
| | 13 | 148 | | if (signatureError != null) |
| | | 149 | | { |
| | 12 | 150 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 12 | 151 | | DiagnosticDescriptors.ValidateMethodWrongSignature, |
| | 12 | 152 | | attributeSyntax.GetLocation(), |
| | 12 | 153 | | methodName, |
| | 12 | 154 | | targetType.Name, |
| | 12 | 155 | | signatureError)); |
| | | 156 | | } |
| | 1 | 157 | | else if (validatorType != null) |
| | | 158 | | { |
| | 1 | 159 | | var parameterType = validationMethod.Parameters[0].Type; |
| | 1 | 160 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 161 | | DiagnosticDescriptors.ValidatorTypeMismatch, |
| | 1 | 162 | | attributeSyntax.GetLocation(), |
| | 1 | 163 | | validatorType.Name, |
| | 1 | 164 | | parameterType.Name, |
| | 1 | 165 | | optionsType.Name)); |
| | | 166 | | } |
| | | 167 | | |
| | 1 | 168 | | return; |
| | | 169 | | } |
| | | 170 | | |
| | 6 | 171 | | if (validatorType != null && validateMethod == null) |
| | | 172 | | { |
| | 3 | 173 | | var interfaceTypeArguments = OptionsAttributeHelper |
| | 3 | 174 | | .GetIOptionsValidatorTypeArguments(validatorType) |
| | 3 | 175 | | .ToArray(); |
| | 3 | 176 | | if (interfaceTypeArguments.Any(typeArgument => |
| | 5 | 177 | | SymbolEqualityComparer.Default.Equals(typeArgument, optionsType))) |
| | | 178 | | { |
| | 1 | 179 | | return; |
| | | 180 | | } |
| | | 181 | | |
| | 2 | 182 | | if (interfaceTypeArguments.Length > 0) |
| | | 183 | | { |
| | 1 | 184 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 185 | | DiagnosticDescriptors.ValidatorTypeMismatch, |
| | 1 | 186 | | attributeSyntax.GetLocation(), |
| | 1 | 187 | | validatorType.Name, |
| | 1 | 188 | | interfaceTypeArguments[0].Name, |
| | 1 | 189 | | optionsType.Name)); |
| | 1 | 190 | | return; |
| | | 191 | | } |
| | | 192 | | |
| | 1 | 193 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 1 | 194 | | DiagnosticDescriptors.ValidatorTypeMissingInterface, |
| | 1 | 195 | | attributeSyntax.GetLocation(), |
| | 1 | 196 | | validatorType.Name, |
| | 1 | 197 | | optionsType.Name)); |
| | 1 | 198 | | return; |
| | | 199 | | } |
| | | 200 | | |
| | | 201 | | // Convention-based self-validation is optional. |
| | 3 | 202 | | if (validateMethod != null) |
| | | 203 | | { |
| | 3 | 204 | | context.ReportDiagnostic(Diagnostic.Create( |
| | 3 | 205 | | DiagnosticDescriptors.ValidateMethodNotFound, |
| | 3 | 206 | | attributeSyntax.GetLocation(), |
| | 3 | 207 | | methodName, |
| | 3 | 208 | | targetType.Name)); |
| | | 209 | | } |
| | | 210 | | } |
| | 6 | 211 | | } |
| | | 212 | | |
| | | 213 | | private static bool IsOptionsAttribute(INamedTypeSymbol? attributeClass) |
| | | 214 | | { |
| | 64 | 215 | | if (attributeClass == null) |
| | 0 | 216 | | return false; |
| | | 217 | | |
| | 64 | 218 | | return attributeClass.Name == OptionsAttributeName && |
| | 64 | 219 | | attributeClass.ContainingNamespace?.ToDisplayString() == GeneratorsNamespace; |
| | | 220 | | } |
| | | 221 | | |
| | | 222 | | private static bool IsRecognizedByValidatorProvider(INamedTypeSymbol validatorType, Compilation compilation) |
| | | 223 | | { |
| | | 224 | | // Collect all ValidatorProvider attributes from all referenced assemblies |
| | 13 | 225 | | var validatorBaseTypes = new HashSet<string>(); |
| | | 226 | | |
| | 4426 | 227 | | foreach (var reference in compilation.References) |
| | | 228 | | { |
| | 2200 | 229 | | if (compilation.GetAssemblyOrModuleSymbol(reference) is not IAssemblySymbol assemblySymbol) |
| | | 230 | | continue; |
| | | 231 | | |
| | 86948 | 232 | | foreach (var attr in assemblySymbol.GetAttributes()) |
| | | 233 | | { |
| | 41287 | 234 | | if (attr.AttributeClass?.Name != "ValidatorProviderAttribute") |
| | | 235 | | continue; |
| | 3 | 236 | | if (attr.AttributeClass.ContainingNamespace?.ToDisplayString() != GeneratorsNamespace) |
| | | 237 | | continue; |
| | | 238 | | |
| | 2 | 239 | | if (attr.ConstructorArguments.Length > 0 && |
| | 2 | 240 | | attr.ConstructorArguments[0].Value is string baseTypeName) |
| | | 241 | | { |
| | 2 | 242 | | validatorBaseTypes.Add(baseTypeName); |
| | | 243 | | } |
| | | 244 | | } |
| | | 245 | | } |
| | | 246 | | |
| | | 247 | | // Check if validatorType inherits from any recognized base |
| | 13 | 248 | | return validatorBaseTypes.Any(baseTypeName => |
| | 15 | 249 | | InheritsFromByMetadataName(validatorType, baseTypeName)); |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | private static bool InheritsFromByMetadataName(INamedTypeSymbol type, string metadataName) |
| | | 253 | | { |
| | 2 | 254 | | var current = type.BaseType; |
| | 3 | 255 | | while (current != null) |
| | | 256 | | { |
| | 3 | 257 | | var fullName = current.OriginalDefinition.ContainingNamespace?.ToDisplayString() + "." + |
| | 3 | 258 | | current.OriginalDefinition.MetadataName; |
| | 3 | 259 | | if (fullName == metadataName) |
| | 2 | 260 | | return true; |
| | 1 | 261 | | current = current.BaseType; |
| | | 262 | | } |
| | 0 | 263 | | return false; |
| | | 264 | | } |
| | | 265 | | } |