|
| 1 | +using System.Collections.Immutable; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.CSharp; |
| 4 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 5 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 6 | + |
| 7 | +namespace Architect.DomainModeling.Analyzer.Analyzers; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// In [Wrapper]ValueObjects, this analyzer warns against the use of property/field initializers in classes without a default constructor (such as when a primary constructor is used). |
| 11 | +/// Without a default constructor, deserialization uses GetUninitializedObject(), which skips property/field initializers, likely to the developer's surprise. |
| 12 | +/// </summary> |
| 13 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 14 | +public sealed class ValueObjectFieldInitializerWithoutDefaultCtorAnalyzer : DiagnosticAnalyzer |
| 15 | +{ |
| 16 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "False positive.")] |
| 17 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("MicrosoftCodeAnalysisReleaseTracking", "RS2008:Enable analyzer release tracking", Justification = "Not yet implemented.")] |
| 18 | + private static readonly DiagnosticDescriptor DiagnosticDescriptor = new DiagnosticDescriptor( |
| 19 | + id: "ValueObjectFieldInitializerWithoutDefaultConstructor", |
| 20 | + title: "ValueObject has field initializers but no default constructor", |
| 21 | + messageFormat: "Field initializer on value object with no default constructor. Lack of a default constructor forces deserialization to use GetUninitializedObject(), which skips field initializers. Consider a calculated property (=> syntax) to avoid field initializers.", |
| 22 | + category: "Design", |
| 23 | + defaultSeverity: DiagnosticSeverity.Warning, |
| 24 | + isEnabledByDefault: true); |
| 25 | + |
| 26 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [DiagnosticDescriptor]; |
| 27 | + |
| 28 | + public override void Initialize(AnalysisContext context) |
| 29 | + { |
| 30 | + context.EnableConcurrentExecution(); |
| 31 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze); |
| 32 | + |
| 33 | + context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); |
| 34 | + context.RegisterSyntaxNodeAction(AnalyzePropertyDeclaration, SyntaxKind.PropertyDeclaration); |
| 35 | + } |
| 36 | + |
| 37 | + private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) |
| 38 | + { |
| 39 | + var field = (FieldDeclarationSyntax)context.Node; |
| 40 | + var semanticModel = context.SemanticModel; |
| 41 | + |
| 42 | + if (!IsMemberOfRelevantType(field, semanticModel, context.CancellationToken)) |
| 43 | + return; |
| 44 | + |
| 45 | + // A field declaration can actually define multiple fields at once: private int One, Two = 1, 2; |
| 46 | + foreach (var fieldVariable in field.Declaration.Variables) |
| 47 | + { |
| 48 | + if (fieldVariable.Initializer?.Value is not { } initializer) |
| 49 | + continue; |
| 50 | + |
| 51 | + // When using a primary constructor, then we use field initializers to assign its parameters |
| 52 | + // Such initializers are fine |
| 53 | + // It is only OTHER (non-parameterized) initalizers that are likely to cause confusion |
| 54 | + if (InitializerReferencesAnyConstructorParameter(initializer, semanticModel, context.CancellationToken)) |
| 55 | + return; |
| 56 | + |
| 57 | + context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptor, fieldVariable.Initializer.GetLocation())); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) |
| 62 | + { |
| 63 | + var property = (PropertyDeclarationSyntax)context.Node; |
| 64 | + var semanticModel = context.SemanticModel; |
| 65 | + |
| 66 | + if (!IsMemberOfRelevantType(property, semanticModel, context.CancellationToken)) |
| 67 | + return; |
| 68 | + |
| 69 | + if (property.Initializer?.Value is not { } initializer) |
| 70 | + return; |
| 71 | + |
| 72 | + // When using a primary constructor, then we use field initializers to assign its parameters |
| 73 | + // Such initializers are fine |
| 74 | + // It is only OTHER (non-parameterized) initalizers that are likely to cause confusion |
| 75 | + if (InitializerReferencesAnyConstructorParameter(initializer, semanticModel, context.CancellationToken)) |
| 76 | + return; |
| 77 | + |
| 78 | + context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptor, property.Initializer.GetLocation())); |
| 79 | + } |
| 80 | + |
| 81 | + private static bool IsMemberOfRelevantType(MemberDeclarationSyntax member, SemanticModel semanticModel, CancellationToken cancellationToken) |
| 82 | + { |
| 83 | + if (member.Parent is not TypeDeclarationSyntax tds) |
| 84 | + return false; |
| 85 | + |
| 86 | + if (semanticModel.GetDeclaredSymbol(tds, cancellationToken) is not { } type) |
| 87 | + return false; |
| 88 | + |
| 89 | + // Only in reference types with the [Wrapper]ValueObjectAttributes |
| 90 | + if (type.IsValueType || !type.GetAttributes().Any(attr => attr.AttributeClass is |
| 91 | + { |
| 92 | + Name: "ValueObjectAttribute" or "WrapperValueObjectAttribute", |
| 93 | + ContainingNamespace: { Name: "DomainModeling", ContainingNamespace: { Name: "Architect", ContainingNamespace.IsGlobalNamespace: true, } }, |
| 94 | + })) |
| 95 | + return false; |
| 96 | + |
| 97 | + // Only without a default ctor |
| 98 | + if (type.InstanceConstructors.Any(ctor => ctor.Parameters.Length == 0)) |
| 99 | + return false; |
| 100 | + |
| 101 | + return true; |
| 102 | + } |
| 103 | + |
| 104 | + private static bool InitializerReferencesAnyConstructorParameter(ExpressionSyntax initializer, SemanticModel semanticModel, CancellationToken cancellationToken) |
| 105 | + { |
| 106 | + // The initializer might reference constructor parameters |
| 107 | + // However, it might also DECLARE parameters and then reference them, which is irrelevant to us |
| 108 | + // To see the distinction, first observe which parameters are declared INSIDE the initializer |
| 109 | + var parametersDeclaredInsideInitializer = new HashSet<IParameterSymbol>(SymbolEqualityComparer.Default); |
| 110 | + foreach (var parameterSyntax in initializer.DescendantNodesAndSelf().OfType<ParameterSyntax>()) |
| 111 | + if (semanticModel.GetDeclaredSymbol(parameterSyntax, cancellationToken) is { } parameterSymbol) |
| 112 | + parametersDeclaredInsideInitializer.Add(parameterSymbol); |
| 113 | + |
| 114 | + foreach (var id in initializer.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>()) |
| 115 | + { |
| 116 | + var symbol = semanticModel.GetSymbolInfo(id, cancellationToken).Symbol; |
| 117 | + if (symbol is IParameterSymbol parameterSymbol && !parametersDeclaredInsideInitializer.Contains(parameterSymbol)) |
| 118 | + { |
| 119 | + // Parameter originates outside initializer |
| 120 | + // This initializer uses primary ctor params |
| 121 | + return true; |
| 122 | + } |
| 123 | + } |
| 124 | + return false; |
| 125 | + } |
| 126 | +} |
0 commit comments