|
| 1 | +using System.Collections.Immutable; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 4 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 5 | + |
| 6 | +namespace Immediate.Cache.Analyzers; |
| 7 | + |
| 8 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 9 | +public sealed class OwnedDisposableScopeSuppressor : DiagnosticSuppressor |
| 10 | +{ |
| 11 | + public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => |
| 12 | + ImmutableArray.Create([ |
| 13 | + new SuppressionDescriptor( |
| 14 | + id: "OwnedDisposableScopeSuppression", |
| 15 | + suppressedDiagnosticId: "CA2000", |
| 16 | + justification: "Suppress disposable not being disposed when used from `Owned<T>.GetScope(out T)`." |
| 17 | + ), |
| 18 | + ]); |
| 19 | + public override void ReportSuppressions(SuppressionAnalysisContext context) |
| 20 | + { |
| 21 | + var token = context.CancellationToken; |
| 22 | + |
| 23 | + foreach (var diagnostic in context.ReportedDiagnostics) |
| 24 | + { |
| 25 | + token.ThrowIfCancellationRequested(); |
| 26 | + |
| 27 | + var syntaxTree = diagnostic.Location.SourceTree; |
| 28 | + |
| 29 | + if (syntaxTree |
| 30 | + ?.GetRoot(token) |
| 31 | + .FindNode(diagnostic.Location.SourceSpan) is not ArgumentSyntax |
| 32 | + { |
| 33 | + Parent.Parent: InvocationExpressionSyntax |
| 34 | + { |
| 35 | + Expression: MemberAccessExpressionSyntax |
| 36 | + { |
| 37 | + Name: IdentifierNameSyntax |
| 38 | + { |
| 39 | + Identifier.Text: "GetScope", |
| 40 | + }, |
| 41 | + |
| 42 | + Expression: { } expression, |
| 43 | + }, |
| 44 | + }, |
| 45 | + }) |
| 46 | + { |
| 47 | + continue; |
| 48 | + } |
| 49 | + |
| 50 | + var typeInfo = context.GetSemanticModel(syntaxTree).GetTypeInfo(expression, token); |
| 51 | + var symbol = typeInfo.Type ?? typeInfo.ConvertedType; |
| 52 | + |
| 53 | + if (symbol is not INamedTypeSymbol |
| 54 | + { |
| 55 | + Arity: 1, |
| 56 | + Name: "Owned", |
| 57 | + ContainingNamespace: |
| 58 | + { |
| 59 | + Name: "Cache", |
| 60 | + ContainingNamespace: |
| 61 | + { |
| 62 | + Name: "Immediate", |
| 63 | + ContainingNamespace.IsGlobalNamespace: true, |
| 64 | + }, |
| 65 | + }, |
| 66 | + }) |
| 67 | + { |
| 68 | + continue; |
| 69 | + } |
| 70 | + |
| 71 | + context.ReportSuppression( |
| 72 | + Suppression.Create( |
| 73 | + SupportedSuppressions[0], |
| 74 | + diagnostic |
| 75 | + ) |
| 76 | + ); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments