|
| 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 ClassDeclarationAnalyzer : DiagnosticAnalyzer |
| 12 | + { |
| 13 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( |
| 14 | + Descriptors.IDISP025SealDisposable); |
| 15 | + |
| 16 | + public override void Initialize(AnalysisContext context) |
| 17 | + { |
| 18 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 19 | + context.EnableConcurrentExecution(); |
| 20 | + context.RegisterSyntaxNodeAction(c => Handle(c), SyntaxKind.ClassDeclaration); |
| 21 | + } |
| 22 | + |
| 23 | + private static void Handle(SyntaxNodeAnalysisContext context) |
| 24 | + { |
| 25 | + if (context.Node is ClassDeclarationSyntax { } classDeclaration && |
| 26 | + context.ContainingSymbol is INamedTypeSymbol { IsSealed: false } type && |
| 27 | + type.IsAssignableTo(KnownSymbol.IDisposable, context.SemanticModel.Compilation) && |
| 28 | + DisposeMethod.TryFindIDisposableDispose(type, context.Compilation, Search.TopLevel, out var disposeMethod) && |
| 29 | + disposeMethod is { IsVirtual: false, IsOverride: false } && |
| 30 | + !DisposeMethod.TryFindVirtualDispose(type, context.Compilation, Search.TopLevel, out _)) |
| 31 | + { |
| 32 | + context.ReportDiagnostic( |
| 33 | + Diagnostic.Create( |
| 34 | + Descriptors.IDISP025SealDisposable, |
| 35 | + classDeclaration.Identifier.GetLocation(), |
| 36 | + additionalLocations: new[] { disposeMethod.Locations[0] })); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | +} |
0 commit comments