-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathMatchingInputOutputTypeActivityAnalyzer.cs
More file actions
405 lines (337 loc) · 19.3 KB
/
MatchingInputOutputTypeActivityAnalyzer.cs
File metadata and controls
405 lines (337 loc) · 19.3 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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.DurableTask.Analyzers.Activities;
/// <summary>
/// Analyzer that checks for mismatches between the input and output types of Activities invocations and their definitions.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class MatchingInputOutputTypeActivityAnalyzer : DiagnosticAnalyzer
{
/// <summary>
/// The diagnostic ID for the diagnostic that reports when the input argument type of an Activity invocation does not match the input parameter type of the Activity definition.
/// </summary>
public const string InputArgumentTypeMismatchDiagnosticId = "DURABLE2001";
/// <summary>
/// The diagnostic ID for the diagnostic that reports when the output argument type of an Activity invocation does not match the return type of the Activity definition.
/// </summary>
public const string OutputArgumentTypeMismatchDiagnosticId = "DURABLE2002";
static readonly LocalizableString InputArgumentTypeMismatchTitle = new LocalizableResourceString(nameof(Resources.InputArgumentTypeMismatchAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
static readonly LocalizableString InputArgumentTypeMismatchMessageFormat = new LocalizableResourceString(nameof(Resources.InputArgumentTypeMismatchAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
static readonly LocalizableString OutputArgumentTypeMismatchTitle = new LocalizableResourceString(nameof(Resources.OutputArgumentTypeMismatchAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
static readonly LocalizableString OutputArgumentTypeMismatchMessageFormat = new LocalizableResourceString(nameof(Resources.OutputArgumentTypeMismatchAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
static readonly DiagnosticDescriptor InputArgumentTypeMismatchRule = new(
InputArgumentTypeMismatchDiagnosticId,
InputArgumentTypeMismatchTitle,
InputArgumentTypeMismatchMessageFormat,
AnalyzersCategories.Activity,
DiagnosticSeverity.Warning,
customTags: [WellKnownDiagnosticTags.CompilationEnd],
isEnabledByDefault: true);
static readonly DiagnosticDescriptor OutputArgumentTypeMismatchRule = new(
OutputArgumentTypeMismatchDiagnosticId,
OutputArgumentTypeMismatchTitle,
OutputArgumentTypeMismatchMessageFormat,
AnalyzersCategories.Activity,
DiagnosticSeverity.Warning,
customTags: [WellKnownDiagnosticTags.CompilationEnd],
isEnabledByDefault: true);
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [InputArgumentTypeMismatchRule, OutputArgumentTypeMismatchRule];
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(context =>
{
KnownTypeSymbols knownSymbols = new(context.Compilation);
if (knownSymbols.ActivityTriggerAttribute == null || knownSymbols.FunctionNameAttribute == null ||
knownSymbols.DurableTaskRegistry == null || knownSymbols.TaskActivityBase == null ||
knownSymbols.Task == null || knownSymbols.TaskT == null)
{
// symbols not available in this compilation, skip analysis
return;
}
IMethodSymbol taskActivityRunAsync = knownSymbols.TaskActivityBase.GetMembers("RunAsync").OfType<IMethodSymbol>().Single();
INamedTypeSymbol voidSymbol = context.Compilation.GetSpecialType(SpecialType.System_Void);
// Get common DI types that should not be treated as activity input
INamedTypeSymbol? functionContextSymbol = context.Compilation.GetTypeByMetadataName("Microsoft.Azure.Functions.Worker.FunctionContext");
// Search for Activity invocations
ConcurrentBag<ActivityInvocation> invocations = [];
context.RegisterOperationAction(
ctx =>
{
ctx.CancellationToken.ThrowIfCancellationRequested();
if (ctx.Operation is not IInvocationOperation invocationOperation)
{
return;
}
IMethodSymbol targetMethod = invocationOperation.TargetMethod;
if (!targetMethod.IsEqualTo(knownSymbols.TaskOrchestrationContext, "CallActivityAsync"))
{
return;
}
Debug.Assert(invocationOperation.Arguments.Length is 2 or 3, "CallActivityAsync has 2 or 3 parameters");
Debug.Assert(invocationOperation.Arguments[0].Parameter?.Name == "name", "First parameter of CallActivityAsync is name");
IArgumentOperation activityNameArgumentOperation = invocationOperation.Arguments[0];
// extracts the constant value from the argument (e.g.: it can be a nameof, string literal or const field)
Optional<object?> constant = ctx.Operation.SemanticModel!.GetConstantValue(activityNameArgumentOperation.Value.Syntax);
if (!constant.HasValue)
{
// not a constant value, we cannot correlate this invocation to an existent activity in compile time
return;
}
string activityName = constant.Value!.ToString();
// Try to extract the input argument from the invocation
ITypeSymbol? inputType = null;
IArgumentOperation? inputArgumentParameter = invocationOperation.Arguments.SingleOrDefault(a => a.Parameter?.Name == "input");
if (inputArgumentParameter != null && inputArgumentParameter.ArgumentKind != ArgumentKind.DefaultValue)
{
// if the argument is not null or a default value provided by the compiler, get the type before the conversion to object
TypeInfo inputTypeInfo = ctx.Operation.SemanticModel.GetTypeInfo(inputArgumentParameter.Value.Syntax, ctx.CancellationToken);
inputType = inputTypeInfo.Type;
}
// If the CallActivityAsync<TOutput> method is used, we extract the output type from TypeArguments
ITypeSymbol? outputType = targetMethod.OriginalDefinition.Arity == 1 && targetMethod.TypeArguments.Length == 1 ?
targetMethod.TypeArguments[0] : null;
invocations.Add(new ActivityInvocation()
{
Name = activityName,
InputType = inputType,
OutputType = outputType,
InvocationSyntaxNode = invocationOperation.Syntax,
});
},
OperationKind.Invocation);
// Search for Durable Functions Activities definitions
ConcurrentBag<ActivityDefinition> activities = [];
context.RegisterSymbolAction(
ctx =>
{
ctx.CancellationToken.ThrowIfCancellationRequested();
if (ctx.Symbol is not IMethodSymbol methodSymbol)
{
return;
}
if (!methodSymbol.ContainsAttributeInAnyMethodArguments(knownSymbols.ActivityTriggerAttribute))
{
return;
}
if (!methodSymbol.TryGetSingleValueFromAttribute(knownSymbols.FunctionNameAttribute, out string functionName))
{
return;
}
IParameterSymbol? inputParam = methodSymbol.Parameters.SingleOrDefault(
p => p.GetAttributes().Any(a => knownSymbols.ActivityTriggerAttribute.Equals(a.AttributeClass, SymbolEqualityComparer.Default)));
if (inputParam == null)
{
// Azure Functions Activity methods must have an input parameter
return;
}
// If the parameter is FunctionContext, skip validation for this activity (it's a DI parameter, not real input)
if (functionContextSymbol != null && SymbolEqualityComparer.Default.Equals(inputParam.Type, functionContextSymbol))
{
return;
}
ITypeSymbol? inputType = inputParam.Type;
ITypeSymbol? outputType = methodSymbol.ReturnType;
if (outputType.Equals(voidSymbol, SymbolEqualityComparer.Default) ||
outputType.Equals(knownSymbols.Task, SymbolEqualityComparer.Default))
{
// If the method returns void or Task, we consider it as having no output
outputType = null;
}
else if (outputType.OriginalDefinition.Equals(knownSymbols.TaskT, SymbolEqualityComparer.Default) &&
outputType is INamedTypeSymbol outputNamedType)
{
// If the method is Task<T>, we consider T as the output type
Debug.Assert(outputNamedType.TypeArguments.Length == 1, "Task<T> has one type argument");
outputType = outputNamedType.TypeArguments[0];
}
activities.Add(new ActivityDefinition()
{
Name = functionName,
InputType = inputType,
OutputType = outputType,
});
},
SymbolKind.Method);
// Search for TaskActivity<TInput, TOutput> definitions
context.RegisterSyntaxNodeAction(
ctx =>
{
ctx.CancellationToken.ThrowIfCancellationRequested();
if (ctx.ContainingSymbol is not INamedTypeSymbol classSymbol)
{
return;
}
if (classSymbol.IsAbstract)
{
return;
}
// Check if the class has a method that overrides TaskActivity.RunAsync
IMethodSymbol? methodOverridingRunAsync = null;
INamedTypeSymbol? baseType = classSymbol; // start from the current class
while (baseType != null)
{
foreach (IMethodSymbol method in baseType.GetMembers().OfType<IMethodSymbol>())
{
if (SymbolEqualityComparer.Default.Equals(method.OverriddenMethod?.OriginalDefinition, taskActivityRunAsync))
{
methodOverridingRunAsync = method.OverriddenMethod;
break;
}
}
baseType = baseType.BaseType;
}
// TaskActivity.RunAsync method not found in the class hierarchy
if (methodOverridingRunAsync == null)
{
return;
}
// gets the closed constructed TaskActivity<TInput, TOutput> type, so we can extract TInput and TOutput
INamedTypeSymbol closedConstructedTaskActivity = methodOverridingRunAsync.ContainingType;
Debug.Assert(closedConstructedTaskActivity.TypeArguments.Length == 2, "TaskActivity has TInput and TOutput");
activities.Add(new ActivityDefinition()
{
Name = classSymbol.Name,
InputType = closedConstructedTaskActivity.TypeArguments[0],
OutputType = closedConstructedTaskActivity.TypeArguments[1],
});
},
SyntaxKind.ClassDeclaration);
// Search for Func/Action activities directly registered through DurableTaskRegistry
context.RegisterOperationAction(
ctx =>
{
ctx.CancellationToken.ThrowIfCancellationRequested();
if (ctx.Operation is not IInvocationOperation invocation)
{
return;
}
if (!SymbolEqualityComparer.Default.Equals(invocation.Type, knownSymbols.DurableTaskRegistry))
{
return;
}
// there are 8 AddActivityFunc overloads, with combinations of Activity Name, TInput and TOutput
if (invocation.TargetMethod.Name != "AddActivityFunc")
{
return;
}
// all overloads have the parameter 'name', either as an Action or a Func
IArgumentOperation? activityNameArgumentOperation = invocation.Arguments.SingleOrDefault(a => a.Parameter!.Name == "name");
if (activityNameArgumentOperation == null)
{
return;
}
// extracts the constant value from the argument (e.g.: it can be a nameof, string literal or const field)
Optional<object?> constant = ctx.Operation.SemanticModel!.GetConstantValue(activityNameArgumentOperation.Value.Syntax);
if (!constant.HasValue)
{
// not a constant value, we cannot correlate this invocation to an existent activity in compile time
return;
}
string activityName = constant.Value!.ToString();
ITypeSymbol? inputType = invocation.TargetMethod.GetTypeArgumentByParameterName("TInput");
ITypeSymbol? outputType = invocation.TargetMethod.GetTypeArgumentByParameterName("TOutput");
activities.Add(new ActivityDefinition()
{
Name = activityName,
InputType = inputType,
OutputType = outputType,
});
},
OperationKind.Invocation);
// At the end of the compilation, we correlate the invocations with the definitions
context.RegisterCompilationEndAction(ctx =>
{
// index by name for faster lookup
Dictionary<string, ActivityDefinition> activitiesByName = activities.ToDictionary(a => a.Name, a => a);
foreach (ActivityInvocation invocation in invocations)
{
if (!activitiesByName.TryGetValue(invocation.Name, out ActivityDefinition activity))
{
// Activity not found, we cannot correlate this invocation to an existent activity in compile time.
// We could add a diagnostic here if we want to enforce that, but while we experiment with this analyzer,
// we should prevent false positives.
continue;
}
// Check input type compatibility
if (!AreTypesCompatible(ctx.Compilation, invocation.InputType, activity.InputType))
{
string actual = invocation.InputType?.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat) ?? "none";
string expected = activity.InputType?.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat) ?? "none";
string activityName = invocation.Name;
Diagnostic diagnostic = RoslynExtensions.BuildDiagnostic(InputArgumentTypeMismatchRule, invocation.InvocationSyntaxNode, actual, expected, activityName);
ctx.ReportDiagnostic(diagnostic);
}
// Check output type compatibility
if (!AreTypesCompatible(ctx.Compilation, activity.OutputType, invocation.OutputType))
{
string actual = invocation.OutputType?.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat) ?? "none";
string expected = activity.OutputType?.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat) ?? "none";
string activityName = invocation.Name;
Diagnostic diagnostic = RoslynExtensions.BuildDiagnostic(OutputArgumentTypeMismatchRule, invocation.InvocationSyntaxNode, actual, expected, activityName);
ctx.ReportDiagnostic(diagnostic);
}
}
});
});
}
/// <summary>
/// Checks if the source type is compatible with (can be assigned to) the target type.
/// This handles polymorphism, interface implementation, inheritance, and collection type compatibility.
/// </summary>
static bool AreTypesCompatible(Compilation compilation, ITypeSymbol? sourceType, ITypeSymbol? targetType)
{
// Both null = compatible (no input/output on both sides)
if (sourceType == null && targetType == null)
{
return true;
}
// Special case: null (no input/output provided) can be passed to explicitly nullable parameters
// This handles nullable value types (int?) and nullable reference types (string?)
if (sourceType == null && targetType != null)
{
// Check if target is a nullable value type (Nullable<T>)
if (targetType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
return true;
}
// Check if target is a nullable reference type (string?)
if (targetType.NullableAnnotation == NullableAnnotation.Annotated)
{
return true;
}
// Not nullable, so null input is incompatible
return false;
}
// If targetType is null but sourceType is not, they're incompatible
if (targetType == null && sourceType != null)
{
return false;
}
var conversion = compilation.ClassifyConversion(sourceType!, targetType!);
return conversion.IsImplicit || conversion.IsIdentity;
}
struct ActivityInvocation
{
public string Name { get; set; }
public ITypeSymbol? InputType { get; set; }
public ITypeSymbol? OutputType { get; set; }
public SyntaxNode InvocationSyntaxNode { get; set; }
}
struct ActivityDefinition
{
public string Name { get; set; }
public ITypeSymbol? InputType { get; set; }
public ITypeSymbol? OutputType { get; set; }
}
}