|
| 1 | +namespace IDisposableAnalyzers |
| 2 | +{ |
| 3 | + using System.Collections.Immutable; |
| 4 | + using Gu.Roslyn.AnalyzerExtensions; |
| 5 | + using Microsoft.CodeAnalysis; |
| 6 | + using Microsoft.CodeAnalysis.CSharp; |
| 7 | + using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 8 | + using Microsoft.CodeAnalysis.Diagnostics; |
| 9 | + |
| 10 | + [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 11 | + internal class SuppressFinalizeAnalyzer : DiagnosticAnalyzer |
| 12 | + { |
| 13 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( |
| 14 | + Descriptors.IDISP024DoNotCallSuppressFinalizeIfSealedAndNoFinalizer); |
| 15 | + |
| 16 | + public override void Initialize(AnalysisContext context) |
| 17 | + { |
| 18 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 19 | + context.EnableConcurrentExecution(); |
| 20 | + context.RegisterSyntaxNodeAction(c => Handle(c), SyntaxKind.InvocationExpression); |
| 21 | + } |
| 22 | + |
| 23 | + private static void Handle(SyntaxNodeAnalysisContext context) |
| 24 | + { |
| 25 | + if (context.Node is InvocationExpressionSyntax { ArgumentList: { Arguments: { Count: 1 } arguments } } invocation && |
| 26 | + invocation.IsSymbol(KnownSymbol.GC.SuppressFinalize, context.SemanticModel, context.CancellationToken) && |
| 27 | + context.SemanticModel.TryGetNamedType(arguments[0].Expression, context.CancellationToken, out var type) && |
| 28 | + type.IsSealed && |
| 29 | + !type.TryFindFirstMethod(x => x.MethodKind == MethodKind.Destructor, out _)) |
| 30 | + { |
| 31 | + context.ReportDiagnostic( |
| 32 | + Diagnostic.Create( |
| 33 | + Descriptors.IDISP024DoNotCallSuppressFinalizeIfSealedAndNoFinalizer, |
| 34 | + invocation.GetLocation())); |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | +} |
0 commit comments