Free cookie consent management tool by TermsFeed Policy Generator

source: misc/tools/PersistenceCodeFix/PersistenceCodeFix/PersistenceCodeFix/Analyzers/MissingStorableConstructor/MissingStorableConstructorAnalyzer.cs

Last change on this file was 16475, checked in by jkarder, 5 years ago

#2520: added analyzer and fix for adapting storable ctor signature

File size: 2.4 KB
Line 
1using System.Collections.Immutable;
2using System.Linq;
3using Microsoft.CodeAnalysis;
4using Microsoft.CodeAnalysis.Diagnostics;
5
6namespace 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(
12      nameof(Resources.MissingStorableConstructorAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
13
14    private static readonly LocalizableString MessageFormat = new LocalizableResourceString(
15      nameof(Resources.MissingStorableConstructorAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
16
17    private static readonly LocalizableString Description = new LocalizableResourceString(
18      nameof(Resources.MissingStorableConstructorAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
19
20    private const string Category = nameof(DiagnosticCategory.Persistence);
21
22    private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
23      DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
24
25    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
26
27    public override void Initialize(AnalysisContext context) {
28      context.RegisterSymbolAction(AnalyzeNamedType, SymbolKind.NamedType);
29    }
30
31    private static void AnalyzeNamedType(SymbolAnalysisContext context) {
32      var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;
33      if (namedTypeSymbol.IsStatic) return;
34      if (namedTypeSymbol.TypeKind == TypeKind.Delegate || namedTypeSymbol.TypeKind == TypeKind.Enum || namedTypeSymbol.TypeKind == TypeKind.Struct || namedTypeSymbol.TypeKind == TypeKind.Interface) return;
35
36      var attr = context.Symbol.GetAttributes();
37      if (attr.Any(a => a.AttributeClass.Name == "StorableTypeAttribute")) {
38        var ctors = namedTypeSymbol.InstanceConstructors;
39        if (!ctors.Any(x => x.GetAttributes().Any(y => y.AttributeClass.Name == "StorableConstructorAttribute"))) {
40          var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name);
41          context.ReportDiagnostic(diagnostic);
42        }
43      }
44    }
45  }
46}
Note: See TracBrowser for help on using the repository browser.