|
| 1 | +using System.Collections.Immutable; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 4 | +using Microsoft.CodeAnalysis.Operations; |
| 5 | + |
| 6 | +namespace Architect.DomainModeling.Analyzer.Analyzers; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Prevents attempts to implicilty convert from a non-constant TEnum value to DefinedEnum<TEnum> or DefinedEnum<TEnum, TPrimitive>. |
| 10 | +/// </summary> |
| 11 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 12 | +public sealed class ImplicitDefinedEnumConversionFromNonConstantAnalyzer : DiagnosticAnalyzer |
| 13 | +{ |
| 14 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "False positive.")] |
| 15 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("MicrosoftCodeAnalysisReleaseTracking", "RS2008:Enable analyzer release tracking", Justification = "Not yet implemented.")] |
| 16 | + private static readonly DiagnosticDescriptor DiagnosticDescriptor = new DiagnosticDescriptor( |
| 17 | + id: "ImplicitConversionFromUnvalidatedEnumToDefinedEnum", |
| 18 | + title: "Implicit conversion from unvalidated enum to DefinedEnum", |
| 19 | + messageFormat: "Only a defined enum constant may be implicitly converted to DefinedEnum. For non-constant values, use DefinedEnum.Create(), a constructor, or an explicit conversion.", |
| 20 | + category: "Usage", |
| 21 | + defaultSeverity: DiagnosticSeverity.Error, |
| 22 | + isEnabledByDefault: true); |
| 23 | + |
| 24 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [DiagnosticDescriptor]; |
| 25 | + |
| 26 | + public override void Initialize(AnalysisContext context) |
| 27 | + { |
| 28 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.ReportDiagnostics); |
| 29 | + context.EnableConcurrentExecution(); |
| 30 | + |
| 31 | + context.RegisterOperationAction(AnalyzeConversion, OperationKind.Conversion); |
| 32 | + } |
| 33 | + |
| 34 | + private static void AnalyzeConversion(OperationAnalysisContext context) |
| 35 | + { |
| 36 | + var conversion = (IConversionOperation)context.Operation; |
| 37 | + |
| 38 | + // Only implicit conversions are relevant to us |
| 39 | + if (!conversion.IsImplicit) |
| 40 | + return; |
| 41 | + |
| 42 | + var from = conversion.Operand.Type; |
| 43 | + var to = conversion.Type; |
| 44 | + |
| 45 | + // Dig through nullables |
| 46 | + if (from.IsNullable(out var nullableUnderlyingType)) |
| 47 | + from = nullableUnderlyingType; |
| 48 | + if (to.IsNullable(out nullableUnderlyingType)) |
| 49 | + to = nullableUnderlyingType; |
| 50 | + |
| 51 | + // Only from enum is relevant to us |
| 52 | + if (from is not { TypeKind: TypeKind.Enum } enumType) |
| 53 | + return; |
| 54 | + |
| 55 | + // Only to DefinedEnum is relevant to us |
| 56 | + if (to is not |
| 57 | + INamedTypeSymbol |
| 58 | + { |
| 59 | + IsGenericType: true, Arity: 1 or 2, Name: "DefinedEnum", |
| 60 | + ContainingNamespace: { Name: "DomainModeling", ContainingNamespace: { Name: "Architect", ContainingNamespace.IsGlobalNamespace: true } } |
| 61 | + }) |
| 62 | + return; |
| 63 | + |
| 64 | + // Produce an error if the implicit conversion is not coming from a defined constant value of the enum's type |
| 65 | + if (!IsDefinedEnumConstant(enumType, conversion.Operand.ConstantValue)) |
| 66 | + { |
| 67 | + var diagnostic = Diagnostic.Create( |
| 68 | + DiagnosticDescriptor, |
| 69 | + conversion.Syntax.GetLocation()); |
| 70 | + |
| 71 | + context.ReportDiagnostic(diagnostic); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + private static bool IsDefinedEnumConstant(ITypeSymbol enumType, Optional<object?> constantValue) |
| 76 | + { |
| 77 | + if (!constantValue.HasValue) |
| 78 | + return false; |
| 79 | + |
| 80 | + if (enumType is not INamedTypeSymbol { EnumUnderlyingType: { } } namedEnumType) |
| 81 | + return false; |
| 82 | + |
| 83 | + var binaryValue = GetBinaryValue(namedEnumType.EnumUnderlyingType, constantValue.Value); |
| 84 | + |
| 85 | + var valueIsDefined = namedEnumType.GetMembers().Any(member => |
| 86 | + member is IFieldSymbol { ConstantValue: var value } && GetBinaryValue(namedEnumType.EnumUnderlyingType, value) == binaryValue); |
| 87 | + |
| 88 | + return valueIsDefined; |
| 89 | + } |
| 90 | + |
| 91 | + private static ulong? GetBinaryValue(ITypeSymbol enumUnderlyingType, object? value) |
| 92 | + { |
| 93 | + if (value is null) |
| 94 | + return null; |
| 95 | + |
| 96 | + return (enumUnderlyingType.SpecialType, Type.GetTypeCode(value.GetType())) switch |
| 97 | + { |
| 98 | + (SpecialType.System_Byte, TypeCode.Byte) => Convert.ToByte(value), |
| 99 | + (SpecialType.System_SByte, TypeCode.SByte) => (ulong)Convert.ToSByte(value), |
| 100 | + (SpecialType.System_UInt16, TypeCode.UInt16) => Convert.ToUInt16(value), |
| 101 | + (SpecialType.System_Int16, TypeCode.Int16) => (ulong)Convert.ToInt16(value), |
| 102 | + (SpecialType.System_UInt32, TypeCode.UInt32) => Convert.ToUInt32(value), |
| 103 | + (SpecialType.System_Int32, TypeCode.Int32) => (ulong)Convert.ToInt32(value), |
| 104 | + (SpecialType.System_UInt64, TypeCode.UInt64) => Convert.ToUInt64(value), |
| 105 | + (SpecialType.System_Int64, TypeCode.Int64) => (ulong)Convert.ToInt64(value), |
| 106 | + _ => null, |
| 107 | + }; |
| 108 | + } |
| 109 | +} |
0 commit comments