forked from Azure/azure-functions-host
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebJobsAttributeAnalyzer.cs
297 lines (260 loc) · 12.6 KB
/
WebJobsAttributeAnalyzer.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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System;
using System.Collections.Immutable;
using System.Reflection;
namespace Microsoft.Azure.Functions.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class WebJobsAttributeAnalyzer : DiagnosticAnalyzer
{
JobHostMetadataProvider _tooling;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(
DiagnosticDescriptors.IllegalFunctionName,
DiagnosticDescriptors.BadBindingExpressionSyntax,
DiagnosticDescriptors.FailedValidation);
}
}
public override void Initialize(AnalysisContext context)
{
// https://stackoverflow.com/questions/62638455/analyzer-with-code-fix-project-template-is-broken
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
// Analyze method signatures.
context.RegisterSyntaxNodeAction(AnalyzeMethodDeclarationNode, SyntaxKind.MethodDeclaration);
// Hook compilation to get the assemblies' references and build the WebJob tooling interfaces.
context.RegisterCompilationStartAction(AnalyzeCompilation);
}
private void AnalyzeCompilation(CompilationStartAnalysisContext context)
{
var compilation = context.Compilation;
AssemblyCache.Instance.Build(compilation);
_tooling = AssemblyCache.Instance.Tooling;
}
// This is called extremely frequently
// Analyze the method signature to validate binding attributes + types on the parameters
private void AnalyzeMethodDeclarationNode(SyntaxNodeAnalysisContext context)
{
if (_tooling == null) // Not yet initialized
{
return;
}
var methodDecl = (MethodDeclarationSyntax)context.Node;
CheckForFunctionNameAttributeAndReport(context, methodDecl);
// Go through
var parameterList = methodDecl.ParameterList;
foreach (ParameterSyntax parameterSyntax in parameterList.Parameters)
{
// No symbol for the parameter; just the parameter's type
// Lazily do this - only do this if we're actually looking at a webjobs parameter.
Type parameterType = null;
// Now validate each parameter in the method.
foreach (var attrListSyntax in parameterSyntax.AttributeLists)
{
foreach (AttributeSyntax attributeSyntax in attrListSyntax.Attributes)
{
var symbolInfo = context.SemanticModel.GetSymbolInfo(attributeSyntax);
var symbol = symbolInfo.Symbol;
if (symbol == null)
{
return; // compilation error
}
try
{
// Major call to instantiate a reflection Binding attribute from a symbol.
// Need this so we can pass the attribute to WebJobs's binding engine.
// throws if fails to instantiate
Attribute attribute = ReflectionHelpers.MakeAttr(_tooling, context.SemanticModel, attributeSyntax);
if (attribute == null)
{
continue;
}
// At this point, we know we're looking at a webjobs parameter.
if (parameterType == null)
{
parameterType = ReflectionHelpers.GetParameterType(context, parameterSyntax);
if (parameterType == null)
{
return; // errors in signature
}
}
// Report errors from invalid attribute properties.
ValidateAttribute(context, attribute, attributeSyntax);
}
catch (Exception e)
{
return;
}
}
}
}
}
// First argument to the FunctionName ctor.
private string GetFunctionNameFromAttribute(SemanticModel semantics, AttributeSyntax attributeSyntax)
{
if (attributeSyntax.ArgumentList.Arguments.Count == 0)
{
return null;
}
var firstArg = attributeSyntax.ArgumentList.Arguments[0];
var val = semantics.GetConstantValue(firstArg.Expression);
return val.Value as string;
}
// Quick check for [FunctionName] attribute on a method.
// Reports a diagnostic if the name doesn't meet requirements.
private void CheckForFunctionNameAttributeAndReport(SyntaxNodeAnalysisContext context, MethodDeclarationSyntax methodDeclarationSyntax)
{
foreach (var attrListSyntax in methodDeclarationSyntax.AttributeLists)
{
foreach (AttributeSyntax attributeSyntax in attrListSyntax.Attributes)
{
// Perf - Can we get the name without doing a symbol resolution?
var symAttributeCtor = context.SemanticModel.GetSymbolInfo(attributeSyntax).Symbol;
if (symAttributeCtor != null)
{
var attrType = symAttributeCtor.ContainingType;
if (attrType.Name != nameof(FunctionNameAttribute))
{
return;
}
// Validate the FunctionName
var functionName = GetFunctionNameFromAttribute(context.SemanticModel, attributeSyntax);
bool match = !string.IsNullOrEmpty(functionName) && FunctionNameAttribute.FunctionNameValidationRegex.IsMatch(functionName);
if (!match)
{
var error = Diagnostic.Create(DiagnosticDescriptors.IllegalFunctionName, attributeSyntax.GetLocation(), functionName);
context.ReportDiagnostic(error);
}
}
}
}
}
// Given an instantiated attribute, run the validators on it and report back any errors.
// Attribute is the live attribute, constructed from the attributeSyntax node in the user's source code.
private void ValidateAttribute(SyntaxNodeAnalysisContext context, Attribute attribute, AttributeSyntax attributeSyntax)
{
SemanticModel semantics = context.SemanticModel;
Type attributeType = attribute.GetType();
IMethodSymbol symAttributeCtor = (IMethodSymbol)semantics.GetSymbolInfo(attributeSyntax).Symbol;
var syntaxParams = symAttributeCtor.Parameters;
int idx = 0;
if (attributeSyntax.ArgumentList != null)
{
foreach (AttributeArgumentSyntax arg in attributeSyntax.ArgumentList.Arguments)
{
string argName = null;
if (arg.NameColon != null)
{
argName = arg.NameColon.Name.ToString();
}
else if (arg.NameEquals != null)
{
argName = arg.NameEquals.Name.ToString();
}
else
{
argName = syntaxParams[idx].Name; // Positional
}
PropertyInfo propInfo = attributeType.GetProperty(argName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
if (propInfo != null)
{
ValidateAttributeProperty(context, attribute, propInfo, arg);
}
idx++;
}
}
}
// Validate an individual property on the attribute
// propInfo is a property on the attribute.
private void ValidateAttributeProperty(SyntaxNodeAnalysisContext context, Attribute attribute, PropertyInfo propInfo, AttributeArgumentSyntax attributeSyntax)
{
var propValue = propInfo.GetValue(attribute);
var propertyAttributes = propInfo.GetCustomAttributes();
// First validate [AutoResolve] and [AppSetting].
// Then do validators.
bool isAutoResolve = false;
bool isAppSetting = false;
MethodInfo validator = null;
Attribute validatorAttribute = null;
foreach (Attribute propertyAttribute in propertyAttributes)
{
// AutoResolve and AppSetting are exclusive.
var propAttrType = propertyAttribute.GetType();
if (propAttrType == typeof(Microsoft.Azure.WebJobs.Description.AutoResolveAttribute))
{
isAutoResolve = true;
}
if (propAttrType == typeof(Microsoft.Azure.WebJobs.Description.AppSettingAttribute))
{
isAppSetting = true;
}
if (validator == null)
{
validator = propAttrType.GetMethod("Validate", new Type[] { typeof(object), typeof(string) });
validatorAttribute = propertyAttribute;
}
}
// Now apply error checks in order.
if (isAutoResolve)
{
// Value should parse with { } and %%
try
{
if (propValue is string valueStr)
{
var template = Microsoft.Azure.WebJobs.Host.Bindings.Path.BindingTemplate.FromString(valueStr);
if (template.HasParameters)
{
// The validator runs after the { } and %% are substituted.
// But {} and %% may be illegal characters, so we can't validate with them.
// So skip validation.
// TODO - could we have some "dummy" substitution so that we can still do validation?
return;
}
}
}
catch (FormatException e)
{
// Parse error
var error = Diagnostic.Create(DiagnosticDescriptors.BadBindingExpressionSyntax, attributeSyntax.GetLocation(), propInfo.Name, propValue, e.Message);
context.ReportDiagnostic(error);
return;
}
}
else if (isAppSetting)
{
// TODO - validate the appsetting. In local.json? etc?
}
if (validator != null)
{
// Run Validators.
// If this is an autoresolve/appsetting, technically we should do the runtime substitution
// for the %appsetting% and {key} tokens.
// We'd like to get all attributes deriving from ValidationAttribute.
// But that's net20, and the analyzer is net451, so we can't reference the right type.
// Need to do a dynamic dispatch to ValidationAttribute.Validate(object,string).
try
{
// attr.Validate(value, propInfo.Name);
validator.Invoke(validatorAttribute, new object[] { propValue, propInfo.Name });
}
catch (TargetInvocationException te)
{
var ex = te.InnerException;
var diagnostic = Diagnostic.Create(DiagnosticDescriptors.FailedValidation, attributeSyntax.GetLocation(), propInfo.Name, propValue, ex.Message);
context.ReportDiagnostic(diagnostic);
}
}
}
}
}