/
MarkAttributesWithAttributeUsage.cs
74 lines (64 loc) · 3.16 KB
/
MarkAttributesWithAttributeUsage.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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
using static MicrosoftCodeQualityAnalyzersResources;
/// <summary>
/// CA1018: <inheritdoc cref="MarkAttributesWithAttributeUsageTitle"/>
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class MarkAttributesWithAttributeUsageAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1018";
internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(
RuleId,
CreateLocalizableResourceString(nameof(MarkAttributesWithAttributeUsageTitle)),
CreateLocalizableResourceString(nameof(MarkAttributesWithAttributeUsageMessageDefault)),
DiagnosticCategory.Design,
RuleLevel.IdeSuggestion,
description: null,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(compilationContext =>
{
INamedTypeSymbol? attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
INamedTypeSymbol? attributeUsageAttributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute);
if (attributeType == null || attributeUsageAttributeType == null)
{
return;
}
compilationContext.RegisterSymbolAction(context =>
{
AnalyzeSymbol(
(INamedTypeSymbol)context.Symbol,
attributeType,
attributeUsageAttributeType,
static (context, diagnostic) => context.ReportDiagnostic(diagnostic),
context);
},
SymbolKind.NamedType);
});
}
private static void AnalyzeSymbol<TContext>(INamedTypeSymbol symbol, INamedTypeSymbol attributeType, INamedTypeSymbol attributeUsageAttributeType, Action<TContext, Diagnostic> addDiagnostic, TContext context)
{
if (symbol.IsAbstract || symbol.BaseType == null || !symbol.BaseType.Equals(attributeType))
{
return;
}
if (!symbol.HasAnyAttribute(attributeUsageAttributeType))
{
addDiagnostic(context, symbol.CreateDiagnostic(Rule, symbol.Name));
}
}
}
}