1 | using System.Collections.Immutable;
|
---|
2 | using System.Linq;
|
---|
3 | using Microsoft.CodeAnalysis;
|
---|
4 | using Microsoft.CodeAnalysis.Diagnostics;
|
---|
5 |
|
---|
6 | namespace PersistenceCodeFix {
|
---|
7 | [DiagnosticAnalyzer(LanguageNames.CSharp)]
|
---|
8 | public sealed class MissingStorableConstructorAnalyzer : DiagnosticAnalyzer {
|
---|
9 | public const string DiagnosticId = "MissingStorableConstructor";
|
---|
10 |
|
---|
11 | private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.MissingStorableConstructorAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
|
---|
12 | private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.MissingStorableConstructorAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
|
---|
13 | private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.MissingStorableConstructorAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
|
---|
14 | private const string Category = nameof(DiagnosticCategory.Persistence);
|
---|
15 |
|
---|
16 | private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
|
---|
17 |
|
---|
18 | public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
|
---|
19 |
|
---|
20 | public override void Initialize(AnalysisContext context) {
|
---|
21 | context.RegisterSymbolAction(AnalyzeNamedType, SymbolKind.NamedType);
|
---|
22 | }
|
---|
23 |
|
---|
24 | private static void AnalyzeNamedType(SymbolAnalysisContext context) {
|
---|
25 | var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;
|
---|
26 | if (namedTypeSymbol.IsStatic) return;
|
---|
27 | if (namedTypeSymbol.TypeKind == TypeKind.Delegate || namedTypeSymbol.TypeKind == TypeKind.Enum || namedTypeSymbol.TypeKind == TypeKind.Struct || namedTypeSymbol.TypeKind == TypeKind.Interface) return;
|
---|
28 |
|
---|
29 | var attr = context.Symbol.GetAttributes();
|
---|
30 | if (attr.Any(a => a.AttributeClass.Name == "StorableTypeAttribute")) {
|
---|
31 | var ctors = namedTypeSymbol.InstanceConstructors;
|
---|
32 | if (!ctors.Any(x => x.GetAttributes().Any(y => y.AttributeClass.Name == "StorableConstructorAttribute"))) {
|
---|
33 | var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name);
|
---|
34 | context.ReportDiagnostic(diagnostic);
|
---|
35 | }
|
---|
36 | }
|
---|
37 | }
|
---|
38 | }
|
---|
39 | }
|
---|