|
| 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 | +/// Prevents accidental equality/comparison operator usage between unrelated types, where implicit conversions inadvertently make the operation compile. |
| 11 | +/// </summary> |
| 12 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 13 | +public sealed class ValueObjectImplicitConversionOnBinaryOperatorAnalyzer : DiagnosticAnalyzer |
| 14 | +{ |
| 15 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "False positive.")] |
| 16 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("MicrosoftCodeAnalysisReleaseTracking", "RS2008:Enable analyzer release tracking", Justification = "Not yet implemented.")] |
| 17 | + private static readonly DiagnosticDescriptor DiagnosticDescriptor = new DiagnosticDescriptor( |
| 18 | + id: "ComparisonBetweenUnrelatedValueObjects", |
| 19 | + title: "Comparison between unrelated value objects", |
| 20 | + messageFormat: "Possible unintended '{0}' comparison between unrelated value objects {1} and {2}. Either compare value objects of the same type, implement a dedicated operator overload, or compare underlying values directly.", |
| 21 | + category: "Usage", |
| 22 | + defaultSeverity: DiagnosticSeverity.Warning, |
| 23 | + isEnabledByDefault: true); |
| 24 | + |
| 25 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [DiagnosticDescriptor]; |
| 26 | + |
| 27 | + public override void Initialize(AnalysisContext context) |
| 28 | + { |
| 29 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.ReportDiagnostics); |
| 30 | + context.EnableConcurrentExecution(); |
| 31 | + |
| 32 | + context.RegisterSyntaxNodeAction( |
| 33 | + AnalyzeBinaryExpression, |
| 34 | + SyntaxKind.EqualsExpression, |
| 35 | + SyntaxKind.NotEqualsExpression, |
| 36 | + SyntaxKind.LessThanExpression, |
| 37 | + SyntaxKind.LessThanOrEqualExpression, |
| 38 | + SyntaxKind.GreaterThanExpression, |
| 39 | + SyntaxKind.GreaterThanOrEqualExpression); |
| 40 | + } |
| 41 | + |
| 42 | + private static void AnalyzeBinaryExpression(SyntaxNodeAnalysisContext context) |
| 43 | + { |
| 44 | + if (context.Node is not BinaryExpressionSyntax binaryExpression) |
| 45 | + return; |
| 46 | + |
| 47 | + var semanticModel = context.SemanticModel; |
| 48 | + var cancellationToken = context.CancellationToken; |
| 49 | + |
| 50 | + var leftTypeInfo = semanticModel.GetTypeInfo(binaryExpression.Left, cancellationToken); |
| 51 | + var rightTypeInfo = semanticModel.GetTypeInfo(binaryExpression.Right, cancellationToken); |
| 52 | + |
| 53 | + // Not if either operand is typeless (e.g. null) |
| 54 | + if (leftTypeInfo.Type is null || rightTypeInfo.Type is null) |
| 55 | + return; |
| 56 | + |
| 57 | + // If either operand was implicitly converted FROM some IValueObject to something else, then the comparison is ill-advised |
| 58 | + if (OperandWasImplicitlyConvertedFromIValueObject(leftTypeInfo) || OperandWasImplicitlyConvertedFromIValueObject(rightTypeInfo)) |
| 59 | + { |
| 60 | + var diagnostic = Diagnostic.Create( |
| 61 | + DiagnosticDescriptor, |
| 62 | + context.Node.GetLocation(), |
| 63 | + binaryExpression.OperatorToken.ValueText, |
| 64 | + IsNullable(leftTypeInfo.Type, out var nullableUnderlyingType) ? nullableUnderlyingType.Name + '?' : leftTypeInfo.Type.Name, |
| 65 | + IsNullable(rightTypeInfo.Type, out nullableUnderlyingType) ? nullableUnderlyingType.Name + '?' : rightTypeInfo.Type.Name); |
| 66 | + |
| 67 | + context.ReportDiagnostic(diagnostic); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + private static bool OperandWasImplicitlyConvertedFromIValueObject(TypeInfo operandTypeInfo) |
| 72 | + { |
| 73 | + var from = operandTypeInfo.Type; |
| 74 | + var to = operandTypeInfo.ConvertedType; |
| 75 | + |
| 76 | + // If no type available or no implicit conversion took place, return false |
| 77 | + if (from is null || from.Equals(to, SymbolEqualityComparer.Default)) |
| 78 | + return false; |
| 79 | + |
| 80 | + // Do not flag nullable lifting (where a nullable and a non-nullable are compared) |
| 81 | + // Note that it LOOKS as though the nullable is converted to non-nullable, but the opposite is true |
| 82 | + if (IsNullable(to, out var nullableUnderlyingType) && nullableUnderlyingType.Equals(from, SymbolEqualityComparer.Default)) |
| 83 | + return false; |
| 84 | + |
| 85 | + // Dig through nullables |
| 86 | + if (IsNullable(from, out nullableUnderlyingType)) |
| 87 | + from = nullableUnderlyingType; |
| 88 | + if (IsNullable(to, out nullableUnderlyingType)) |
| 89 | + to = nullableUnderlyingType; |
| 90 | + |
| 91 | + // Backwards compatibility: If converting to ValueObject, then ignore, because the ValueObject base class implements ==(ValueObject, ValueObject) |
| 92 | + if (to is { Name: "ValueObject", ContainingNamespace: { Name: "DomainModeling", ContainingNamespace: { Name: "Architect", ContainingNamespace.IsGlobalNamespace: true } } }) |
| 93 | + return false; |
| 94 | + |
| 95 | + var isConvertedFromIValueObject = from.AllInterfaces.Any(interf => |
| 96 | + interf is { Name: "IValueObject", ContainingNamespace: { Name: "DomainModeling", ContainingNamespace: { Name: "Architect", ContainingNamespace.IsGlobalNamespace: true } } }); |
| 97 | + |
| 98 | + return isConvertedFromIValueObject; |
| 99 | + } |
| 100 | + |
| 101 | + private static bool IsNullable(ITypeSymbol? potentialNullable, out ITypeSymbol underlyingType) |
| 102 | + { |
| 103 | + if (potentialNullable is not INamedTypeSymbol { ConstructedFrom.SpecialType: SpecialType.System_Nullable_T } namedTypeSymbol) |
| 104 | + { |
| 105 | + underlyingType = null!; |
| 106 | + return false; |
| 107 | + } |
| 108 | + |
| 109 | + underlyingType = namedTypeSymbol.TypeArguments[0]; |
| 110 | + return true; |
| 111 | + } |
| 112 | +} |
0 commit comments