/
ImplementExceptionConstructorsAnalyzer.cs
81 lines (59 loc) · 2.75 KB
/
ImplementExceptionConstructorsAnalyzer.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
// Copyright (c) .NET Foundation and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Roslynator.CSharp.Analysis;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class ImplementExceptionConstructorsAnalyzer : BaseDiagnosticAnalyzer
{
private static ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
if (_supportedDiagnostics.IsDefault)
Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.ImplementExceptionConstructors);
return _supportedDiagnostics;
}
}
public override void Initialize(AnalysisContext context)
{
base.Initialize(context);
context.RegisterCompilationStartAction(startContext =>
{
INamedTypeSymbol exceptionSymbol = startContext.Compilation.GetTypeByMetadataName("System.Exception");
if (exceptionSymbol is null)
return;
startContext.RegisterSymbolAction(f => AnalyzeNamedType(f, exceptionSymbol), SymbolKind.NamedType);
});
}
private static void AnalyzeNamedType(SymbolAnalysisContext context, INamedTypeSymbol exceptionSymbol)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.TypeKind != TypeKind.Class)
return;
if (symbol.IsStatic)
return;
if (symbol.IsImplicitClass)
return;
if (symbol.IsImplicitlyDeclared)
return;
INamedTypeSymbol baseType = symbol.BaseType;
if (baseType?.IsObject() != false)
return;
if (!baseType.EqualsOrInheritsFrom(exceptionSymbol))
return;
if (!GenerateBaseConstructorsAnalysis.IsAnyBaseConstructorMissing(symbol, baseType, f => !IsSerializationConstructor(f)))
return;
var classDeclaration = (ClassDeclarationSyntax)symbol.GetSyntax(context.CancellationToken);
DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.ImplementExceptionConstructors, classDeclaration.Identifier);
}
private static bool IsSerializationConstructor(IMethodSymbol methodSymbol)
{
ImmutableArray<IParameterSymbol> parameters = methodSymbol.Parameters;
return parameters.Length == 2
&& parameters[0].Type.HasMetadataName(MetadataNames.System_Runtime_Serialization_SerializationInfo)
&& parameters[1].Type.HasMetadataName(MetadataNames.System_Runtime_Serialization_StreamingContext);
}
}