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

Last change on this file since 16469 was 16469, checked in by gkronber, 4 years ago

#2520: Adapted VS code fixes:

  • using HeuristicLab.Persistence -> using HEAL.Fossil
  • Made missing StorableCtor a Warning
  • Ignore StorableCtor for structs and interfaces
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(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}
Note: See TracBrowser for help on using the repository browser.