forked from dotnet/roslyn-analyzers
-
Notifications
You must be signed in to change notification settings - Fork 1
/
DoNotCatchGeneralUnlessRethrown.cs
168 lines (138 loc) · 7.26 KB
/
DoNotCatchGeneralUnlessRethrown.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#if HAS_IOPERATION
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Analyzer.Utilities
{
internal abstract class DoNotCatchGeneralUnlessRethrownAnalyzer : DiagnosticAnalyzer
{
private readonly bool _shouldCheckLambdas;
private readonly string? _enablingMethodAttributeFullyQualifiedName;
private bool RequiresAttributeOnMethod => !string.IsNullOrEmpty(_enablingMethodAttributeFullyQualifiedName);
protected DoNotCatchGeneralUnlessRethrownAnalyzer(bool shouldCheckLambdas, string? enablingMethodAttributeFullyQualifiedName = null)
{
_shouldCheckLambdas = shouldCheckLambdas;
_enablingMethodAttributeFullyQualifiedName = enablingMethodAttributeFullyQualifiedName;
}
protected abstract Diagnostic CreateDiagnostic(IMethodSymbol containingMethod, SyntaxToken catchKeyword);
protected virtual bool IsConfiguredDisallowedExceptionType(INamedTypeSymbol namedTypeSymbol, Compilation compilation, AnalyzerOptions analyzerOptions, CancellationToken cancellationToken)
{
return false;
}
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
analysisContext.RegisterCompilationStartAction(compilationStartAnalysisContext =>
{
INamedTypeSymbol? requiredAttributeType = null;
if (RequiresAttributeOnMethod && (requiredAttributeType = GetRequiredAttributeType(compilationStartAnalysisContext.Compilation)) == null)
{
return;
}
var disallowedCatchTypes = GetDisallowedCatchTypes(compilationStartAnalysisContext.Compilation);
bool IsDisallowedCatchType(INamedTypeSymbol type) =>
disallowedCatchTypes.Contains(type) ||
IsConfiguredDisallowedExceptionType(type, compilationStartAnalysisContext.Compilation,
compilationStartAnalysisContext.Options, compilationStartAnalysisContext.CancellationToken);
compilationStartAnalysisContext.RegisterOperationBlockAction(operationBlockAnalysisContext =>
{
if (operationBlockAnalysisContext.OwningSymbol.Kind != SymbolKind.Method)
{
return;
}
var method = (IMethodSymbol)operationBlockAnalysisContext.OwningSymbol;
if (RequiresAttributeOnMethod && !MethodHasAttribute(method, requiredAttributeType!))
{
return;
}
foreach (var operation in operationBlockAnalysisContext.OperationBlocks)
{
var walker = new DisallowGeneralCatchUnlessRethrowWalker(IsDisallowedCatchType, _shouldCheckLambdas);
walker.Visit(operation);
foreach (var catchClause in walker.CatchClausesForDisallowedTypesWithoutRethrow)
{
operationBlockAnalysisContext.ReportDiagnostic(CreateDiagnostic(method, catchClause.Syntax.GetFirstToken()));
}
}
});
});
}
private INamedTypeSymbol? GetRequiredAttributeType(Compilation compilation)
{
return compilation.GetOrCreateTypeByMetadataName(_enablingMethodAttributeFullyQualifiedName!);
}
private bool MethodHasAttribute(IMethodSymbol method, INamedTypeSymbol attributeType)
{
return method.GetAttributes().Any(attribute => attribute.AttributeClass.Equals(attributeType));
}
private static IReadOnlyCollection<INamedTypeSymbol> GetDisallowedCatchTypes(Compilation compilation)
{
return ImmutableHashSet.CreateRange(
new[] {
compilation.GetSpecialType(SpecialType.System_Object),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemException),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSystemException)
}.WhereNotNull());
}
/// <summary>
/// Walks an IOperation tree to find catch blocks that handle general types without rethrowing them.
/// </summary>
private class DisallowGeneralCatchUnlessRethrowWalker : OperationWalker
{
private readonly Func<INamedTypeSymbol, bool> _isDisallowedCatchType;
private readonly bool _checkAnonymousFunctions;
private readonly Stack<bool> _seenRethrowInCatchClauses = new Stack<bool>();
public ISet<ICatchClauseOperation> CatchClausesForDisallowedTypesWithoutRethrow { get; } = new HashSet<ICatchClauseOperation>();
public DisallowGeneralCatchUnlessRethrowWalker(Func<INamedTypeSymbol, bool> isDisallowedCatchType, bool checkAnonymousFunctions)
{
_isDisallowedCatchType = isDisallowedCatchType;
_checkAnonymousFunctions = checkAnonymousFunctions;
}
public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation)
{
if (_checkAnonymousFunctions)
{
base.VisitAnonymousFunction(operation);
}
}
public override void VisitCatchClause(ICatchClauseOperation operation)
{
_seenRethrowInCatchClauses.Push(false);
Visit(operation.Filter);
Visit(operation.Handler);
bool seenRethrow = _seenRethrowInCatchClauses.Pop();
if (!seenRethrow && IsDisallowedCatch(operation) && !MightBeFilteringBasedOnTheCaughtException(operation))
{
CatchClausesForDisallowedTypesWithoutRethrow.Add(operation);
}
}
public override void VisitThrow(IThrowOperation operation)
{
if (_seenRethrowInCatchClauses.Count > 0 && !_seenRethrowInCatchClauses.Peek())
{
_seenRethrowInCatchClauses.Pop();
_seenRethrowInCatchClauses.Push(true);
}
base.VisitThrow(operation);
}
private bool IsDisallowedCatch(ICatchClauseOperation operation)
{
return operation.ExceptionType is INamedTypeSymbol exceptionType &&
_isDisallowedCatchType(exceptionType);
}
private static bool MightBeFilteringBasedOnTheCaughtException(ICatchClauseOperation operation)
{
return operation.ExceptionDeclarationOrExpression != null && operation.Filter != null;
}
}
}
}
#endif