|
| 1 | +using System.Collections.Immutable; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 4 | +using Microsoft.CodeAnalysis.Operations; |
| 5 | + |
| 6 | +namespace Funcky.Analyzers; |
| 7 | + |
| 8 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 9 | +public sealed class NonDefaultableAnalyzer : DiagnosticAnalyzer |
| 10 | +{ |
| 11 | + public static readonly DiagnosticDescriptor DoNotUseDefault = new DiagnosticDescriptor( |
| 12 | + id: $"{DiagnosticName.Prefix}{DiagnosticName.Usage}09", |
| 13 | + title: "Do not use default to instantiate this type", |
| 14 | + messageFormat: "Do not use default(...) to instantiate '{0}'", |
| 15 | + category: nameof(Funcky), |
| 16 | + DiagnosticSeverity.Error, |
| 17 | + isEnabledByDefault: true, |
| 18 | + description: "Values instantiated with default are in an invalid state; any member may throw an exception."); |
| 19 | + |
| 20 | + private const string AttributeFullName = "Funcky.CodeAnalysis.NonDefaultableAttribute"; |
| 21 | + |
| 22 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DoNotUseDefault); |
| 23 | + |
| 24 | + public override void Initialize(AnalysisContext context) |
| 25 | + { |
| 26 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); |
| 27 | + context.EnableConcurrentExecution(); |
| 28 | + context.RegisterCompilationStartAction(OnCompilationStart); |
| 29 | + } |
| 30 | + |
| 31 | + private static void OnCompilationStart(CompilationStartAnalysisContext context) |
| 32 | + { |
| 33 | + if (context.Compilation.GetTypeByMetadataName(AttributeFullName) is { } nonDefaultableAttribute) |
| 34 | + { |
| 35 | + context.RegisterOperationAction(AnalyzeDefaultValueOperation(nonDefaultableAttribute), OperationKind.DefaultValue); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + private static Action<OperationAnalysisContext> AnalyzeDefaultValueOperation(INamedTypeSymbol nonDefaultableAttribute) |
| 40 | + => context => |
| 41 | + { |
| 42 | + var operation = (IDefaultValueOperation)context.Operation; |
| 43 | + if (operation.Type is { } type && type.GetAttributes().Any(IsAttribute(nonDefaultableAttribute))) |
| 44 | + { |
| 45 | + context.ReportDiagnostic(Diagnostic.Create( |
| 46 | + DoNotUseDefault, |
| 47 | + operation.Syntax.GetLocation(), |
| 48 | + messageArgs: type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat))); |
| 49 | + } |
| 50 | + }; |
| 51 | + |
| 52 | + private static Func<AttributeData, bool> IsAttribute(INamedTypeSymbol attributeClass) |
| 53 | + => attribute => SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, attributeClass); |
| 54 | +} |
0 commit comments