-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathClrMethodDeclarationAnalyzer.cs
More file actions
280 lines (261 loc) · 16.4 KB
/
ClrMethodDeclarationAnalyzer.cs
File metadata and controls
280 lines (261 loc) · 16.4 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
namespace WpfAnalyzers;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Gu.Roslyn.AnalyzerExtensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class ClrMethodDeclarationAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
Descriptors.WPF0004ClrMethodShouldMatchRegisteredName,
Descriptors.WPF0013ClrMethodMustMatchRegisteredType,
Descriptors.WPF0033UseAttachedPropertyBrowsableForTypeAttribute,
Descriptors.WPF0034AttachedPropertyBrowsableForTypeAttributeArgument,
Descriptors.WPF0042AvoidSideEffectsInClrAccessors,
Descriptors.WPF0061DocumentClrMethod);
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(x => Handle(x), SyntaxKind.MethodDeclaration);
}
private static void Handle(SyntaxNodeAnalysisContext context)
{
if (!context.IsExcludedFromAnalysis() &&
context is { Node: MethodDeclarationSyntax methodDeclaration, ContainingSymbol: IMethodSymbol { IsStatic: true } method } &&
method.Parameters.TryElementAt(0, out var element) &&
element.Type.IsAssignableTo(KnownSymbols.DependencyObject, context.SemanticModel.Compilation))
{
if (GetAttached.Match(methodDeclaration, context.SemanticModel, context.CancellationToken) is { GetValue.Invocation: { } getValue, Backing: { } backingGet })
{
if (backingGet.RegisteredName(context.SemanticModel, context.CancellationToken) is { Value: { } registeredName })
{
if (!method.Name.IsParts("Get", registeredName))
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0004ClrMethodShouldMatchRegisteredName,
methodDeclaration.Identifier.GetLocation(),
ImmutableDictionary<string, string?>.Empty.Add("ExpectedName", "Get" + registeredName),
method.Name,
"Get" + registeredName));
}
if (method.DeclaredAccessibility.IsEither(Accessibility.Protected, Accessibility.Internal, Accessibility.Public))
{
var summaryFormat = "<summary>Helper for getting <see cref=\"{backing}\"/> from <paramref name=\"{element}\"/>.</summary>";
var paramFormat = "<param name=\"{element}\"><see cref=\"{element.type}\"/> to read <see cref=\"{backing}\"/> from.</param>";
var returnsFormat = "<returns>{registered_name} property value.</returns>";
if (methodDeclaration.TryGetDocumentationComment(out var comment))
{
if (comment.VerifySummary(summaryFormat, backingGet.Symbol.Name, element.Name) is { } summaryError)
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0061DocumentClrMethod,
summaryError.Location,
ImmutableDictionary<string, string?>.Empty.Add(nameof(DocComment), summaryError.Text)));
}
if (comment.VerifyParameter(paramFormat, element, element.ToCrefType(), backingGet.Symbol.Name) is { } paramError)
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0061DocumentClrMethod,
paramError.Location,
ImmutableDictionary<string, string?>.Empty.Add(nameof(DocComment), paramError.Text)));
}
if (comment.VerifyReturns(returnsFormat, registeredName) is { } returnsError)
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0061DocumentClrMethod,
returnsError.Location,
ImmutableDictionary<string, string?>.Empty.Add(nameof(DocComment), returnsError.Text)));
}
}
else
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0061DocumentClrMethod,
methodDeclaration.Identifier.GetLocation(),
ImmutableDictionary<string, string?>.Empty.Add(
nameof(DocComment),
#pragma warning disable SA1118 // Parameter should not span multiple lines
$"/// {DocComment.Format(summaryFormat, backingGet.Symbol.Name, element.Name)}\n" +
$"/// {DocComment.Format(paramFormat, element.Name, element.ToCrefType(), backingGet.Name)}\n" +
$"/// {DocComment.Format(returnsFormat, registeredName)}\n")));
#pragma warning restore SA1118 // Parameter should not span multiple lines
}
}
}
if (backingGet.RegisteredType(context.SemanticModel, context.CancellationToken) is { Value: { } registeredType } &&
!TypeSymbolComparer.Equal(method.ReturnType, registeredType))
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0013ClrMethodMustMatchRegisteredType,
methodDeclaration.ReturnType.GetLocation(),
ImmutableDictionary<string, string?>.Empty.Add(nameof(TypeSyntax), registeredType.ToMinimalDisplayString(context.SemanticModel, context.Node.SpanStart)),
"Return type",
registeredType));
}
if (Attribute.TryFind(methodDeclaration, KnownSymbols.AttachedPropertyBrowsableForTypeAttribute, context.SemanticModel, context.CancellationToken, out var attribute))
{
if (attribute.TrySingleArgument(out var argument) &&
argument.Expression is TypeOfExpressionSyntax typeOf &&
TypeSymbol.TryGet(typeOf, method.ContainingType, context.SemanticModel, context.CancellationToken, out var argumentType) &&
!argumentType.IsAssignableTo(element.Type, context.SemanticModel.Compilation))
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0034AttachedPropertyBrowsableForTypeAttributeArgument,
argument.GetLocation(),
element.Type.ToMinimalDisplayString(
context.SemanticModel,
argument.SpanStart)));
}
}
else
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0033UseAttachedPropertyBrowsableForTypeAttribute,
methodDeclaration.Identifier.GetLocation(),
element.Type.ToMinimalDisplayString(context.SemanticModel, methodDeclaration.SpanStart)));
}
if (methodDeclaration.Body is { } body &&
TryGetSideEffect(body, getValue, out var sideEffect))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptors.WPF0042AvoidSideEffectsInClrAccessors, sideEffect.GetLocation()));
}
}
else if (method.Parameters.TryElementAt(1, out var value) &&
SetAttached.Match(methodDeclaration, context.SemanticModel, context.CancellationToken) is { SetValue.Invocation: { } setValue, Backing: { } backingSet })
{
if (backingSet.RegisteredName(context.SemanticModel, context.CancellationToken) is { Value: { } registeredName })
{
if (!method.Name.IsParts("Set", registeredName))
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0004ClrMethodShouldMatchRegisteredName,
methodDeclaration.Identifier.GetLocation(),
ImmutableDictionary<string, string?>.Empty.Add("ExpectedName", "Set" + registeredName),
method.Name,
"Set" + registeredName));
}
if (method.DeclaredAccessibility.IsEither(Accessibility.Protected, Accessibility.Internal, Accessibility.Public))
{
var summaryFormat = "<summary>Helper for setting <see cref=\"{backing}\"/> on <paramref name=\"{element}\"/>.</summary>";
var elementFormat = "<param name=\"{element}\"><see cref=\"{element_type}\"/> to set <see cref=\"{backing}\"/> on.</param>";
var valueFormat = "<param name=\"{value}\">{registered_name} property value.</param>";
if (methodDeclaration.TryGetDocumentationComment(out var comment))
{
if (comment.VerifySummary(summaryFormat, backingSet.Symbol.Name, element.Name) is { } summaryError)
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0061DocumentClrMethod,
summaryError.Location,
ImmutableDictionary<string, string?>.Empty.Add(nameof(DocComment), summaryError.Text)));
}
if (comment.VerifyParameter(elementFormat, element, element.ToCrefType(), backingSet.Symbol.Name) is { } elementError)
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0061DocumentClrMethod,
elementError.Location,
ImmutableDictionary<string, string?>.Empty.Add(nameof(DocComment), elementError.Text)));
}
if (comment.VerifyParameter(valueFormat, value, registeredName) is { } valueError)
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0061DocumentClrMethod,
valueError.Location,
ImmutableDictionary<string, string?>.Empty.Add(nameof(DocComment), valueError.Text)));
}
}
else
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0061DocumentClrMethod,
methodDeclaration.Identifier.GetLocation(),
ImmutableDictionary<string, string?>.Empty.Add(
nameof(DocComment),
#pragma warning disable SA1118 // Parameter should not span multiple lines
$"/// {DocComment.Format(summaryFormat, backingSet.Symbol.Name, element.Name)}\n" +
$"/// {DocComment.Format(elementFormat, element.Name, element.ToCrefType(), backingSet.Name)}\n" +
$"/// {DocComment.Format(valueFormat, value.Name, registeredName)}\n")));
#pragma warning restore SA1118 // Parameter should not span multiple lines
}
}
}
if (backingSet.RegisteredType(context.SemanticModel, context.CancellationToken) is { Value: { } registeredType } &&
method.Parameters.TryElementAt(1, out var valueParameter) &&
!TypeSymbolComparer.Equal(valueParameter.Type, registeredType))
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.WPF0013ClrMethodMustMatchRegisteredType,
methodDeclaration.ParameterList.Parameters[1].Type!.GetLocation(),
ImmutableDictionary<string, string?>.Empty.Add(nameof(TypeSyntax), registeredType.ToMinimalDisplayString(context.SemanticModel, context.Node.SpanStart)),
"Value type",
registeredType));
}
if (methodDeclaration.Body is { } body &&
TryGetSideEffect(body, setValue, out var sideEffect))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptors.WPF0042AvoidSideEffectsInClrAccessors, sideEffect.GetLocation()));
}
}
}
}
private static bool TryGetSideEffect(BlockSyntax body, InvocationExpressionSyntax getOrSet, [NotNullWhen(true)] out StatementSyntax? sideEffect)
{
foreach (var statement in body.Statements)
{
switch (statement)
{
case ExpressionStatementSyntax { Expression: { } expression }
when NullCheck.IsNullCheck(expression, null, CancellationToken.None, out _):
continue;
case ExpressionStatementSyntax { Expression: InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax { Expression: IdentifierNameSyntax { } name } expression } }
when name.ToString() == nameof(System.ArgumentNullException) &&
expression.Name.ToString() == "ThrowIfNull":
continue;
case ExpressionStatementSyntax { Expression: { } expression }
when expression == getOrSet:
continue;
case ReturnStatementSyntax { Expression: { } expression }
when expression == getOrSet:
continue;
case ReturnStatementSyntax { Expression: CastExpressionSyntax { Expression: { } expression } }
when expression == getOrSet:
continue;
case IfStatementSyntax { Condition: { } condition, Statement: ThrowStatementSyntax { }, Else: null }
when NullCheck.IsNullCheck(condition, null, CancellationToken.None, out _):
continue;
case IfStatementSyntax { Condition: { } condition, Statement: BlockSyntax { Statements.Count: 0 }, Else: null }
when NullCheck.IsNullCheck(condition, null, CancellationToken.None, out _):
continue;
case IfStatementSyntax { Condition: { } condition, Statement: BlockSyntax { Statements: { Count: 1 } statements }, Else: null }
when statements[0] is ThrowStatementSyntax &&
NullCheck.IsNullCheck(condition, null, CancellationToken.None, out _):
continue;
case IfStatementSyntax { Statement: null, Else: null }:
continue;
default:
sideEffect = statement;
return true;
}
}
sideEffect = null;
return false;
}
}