-
Notifications
You must be signed in to change notification settings - Fork 52
Add Roslyn Analyzer to detect calls to non-existent functions (name mismatch) #530
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Copilot
wants to merge
7
commits into
main
Choose a base branch
from
copilot/add-roslyn-analyzer-function-check
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+688
−1
Draft
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
31ced09
Initial plan
Copilot 80abedc
Add FunctionNotFoundAnalyzer to detect calls to non-existent activiti…
Copilot ddea7ad
Address code review feedback: add null check for SemanticModel, use r…
Copilot 414c182
Merge branch 'main' into copilot/add-roslyn-analyzer-function-check
YunchuWang 7b66c06
Address code quality review comments: use LINQ Where/Any and combine …
Copilot 75abb0f
Merge branch 'main' into copilot/add-roslyn-analyzer-function-check
YunchuWang 864d8ae
Merge branch 'main' into copilot/add-roslyn-analyzer-function-check
YunchuWang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,304 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System.Collections.Concurrent; | ||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
|
|
||
| namespace Microsoft.DurableTask.Analyzers.Activities; | ||
|
|
||
| /// <summary> | ||
| /// Analyzer that detects calls to non-existent activities and sub-orchestrations. | ||
| /// </summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class FunctionNotFoundAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| /// <summary> | ||
| /// The diagnostic ID for the diagnostic that reports when an activity call references a function that doesn't exist. | ||
| /// </summary> | ||
| public const string ActivityNotFoundDiagnosticId = "DURABLE2003"; | ||
|
|
||
| /// <summary> | ||
| /// The diagnostic ID for the diagnostic that reports when a sub-orchestration call references a function that doesn't exist. | ||
| /// </summary> | ||
| public const string SubOrchestrationNotFoundDiagnosticId = "DURABLE2004"; | ||
|
|
||
| static readonly LocalizableString ActivityNotFoundTitle = new LocalizableResourceString(nameof(Resources.ActivityNotFoundAnalyzerTitle), Resources.ResourceManager, typeof(Resources)); | ||
| static readonly LocalizableString ActivityNotFoundMessageFormat = new LocalizableResourceString(nameof(Resources.ActivityNotFoundAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources)); | ||
|
|
||
| static readonly LocalizableString SubOrchestrationNotFoundTitle = new LocalizableResourceString(nameof(Resources.SubOrchestrationNotFoundAnalyzerTitle), Resources.ResourceManager, typeof(Resources)); | ||
| static readonly LocalizableString SubOrchestrationNotFoundMessageFormat = new LocalizableResourceString(nameof(Resources.SubOrchestrationNotFoundAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources)); | ||
|
|
||
| static readonly DiagnosticDescriptor ActivityNotFoundRule = new( | ||
| ActivityNotFoundDiagnosticId, | ||
| ActivityNotFoundTitle, | ||
| ActivityNotFoundMessageFormat, | ||
| AnalyzersCategories.Activity, | ||
| DiagnosticSeverity.Warning, | ||
| customTags: [WellKnownDiagnosticTags.CompilationEnd], | ||
| isEnabledByDefault: true); | ||
|
|
||
| static readonly DiagnosticDescriptor SubOrchestrationNotFoundRule = new( | ||
| SubOrchestrationNotFoundDiagnosticId, | ||
| SubOrchestrationNotFoundTitle, | ||
| SubOrchestrationNotFoundMessageFormat, | ||
| AnalyzersCategories.Orchestration, | ||
| DiagnosticSeverity.Warning, | ||
| customTags: [WellKnownDiagnosticTags.CompilationEnd], | ||
| isEnabledByDefault: true); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [ActivityNotFoundRule, SubOrchestrationNotFoundRule]; | ||
|
|
||
| /// <inheritdoc/> | ||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.EnableConcurrentExecution(); | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
|
|
||
| context.RegisterCompilationStartAction(context => | ||
| { | ||
| KnownTypeSymbols knownSymbols = new(context.Compilation); | ||
|
|
||
| if (knownSymbols.TaskOrchestrationContext == null || | ||
| knownSymbols.Task == null || knownSymbols.TaskT == null) | ||
| { | ||
| // Core symbols not available in this compilation, skip analysis | ||
| return; | ||
| } | ||
|
|
||
| // Activity-related symbols (may be null if activities aren't used) | ||
| IMethodSymbol? taskActivityRunAsync = knownSymbols.TaskActivityBase?.GetMembers("RunAsync").OfType<IMethodSymbol>().SingleOrDefault(); | ||
|
|
||
| // Search for Activity and Sub-Orchestrator invocations | ||
| ConcurrentBag<FunctionInvocation> activityInvocations = []; | ||
| ConcurrentBag<FunctionInvocation> subOrchestrationInvocations = []; | ||
|
|
||
| context.RegisterOperationAction( | ||
| ctx => | ||
| { | ||
| ctx.CancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| if (ctx.Operation is not IInvocationOperation invocationOperation) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| IMethodSymbol targetMethod = invocationOperation.TargetMethod; | ||
|
|
||
| // Check for CallActivityAsync | ||
| if (targetMethod.IsEqualTo(knownSymbols.TaskOrchestrationContext, "CallActivityAsync")) | ||
| { | ||
| string? activityName = ExtractFunctionName(invocationOperation, "name", ctx); | ||
| if (activityName != null) | ||
| { | ||
| activityInvocations.Add(new FunctionInvocation(activityName, invocationOperation.Syntax)); | ||
| } | ||
| } | ||
|
|
||
| // Check for CallSubOrchestratorAsync | ||
| if (targetMethod.IsEqualTo(knownSymbols.TaskOrchestrationContext, "CallSubOrchestratorAsync")) | ||
| { | ||
| string? orchestratorName = ExtractFunctionName(invocationOperation, "orchestratorName", ctx); | ||
| if (orchestratorName != null) | ||
| { | ||
| subOrchestrationInvocations.Add(new FunctionInvocation(orchestratorName, invocationOperation.Syntax)); | ||
| } | ||
| } | ||
| }, | ||
| OperationKind.Invocation); | ||
|
|
||
| // Search for Activity definitions | ||
| ConcurrentBag<string> activityNames = []; | ||
| ConcurrentBag<string> orchestratorNames = []; | ||
|
|
||
| // Search for Durable Functions Activities and Orchestrators definitions (via [Function] attribute) | ||
| context.RegisterSymbolAction( | ||
| ctx => | ||
| { | ||
| ctx.CancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| if (ctx.Symbol is not IMethodSymbol methodSymbol) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // Check for Activity defined via [ActivityTrigger] | ||
| if (knownSymbols.ActivityTriggerAttribute != null && | ||
| methodSymbol.ContainsAttributeInAnyMethodArguments(knownSymbols.ActivityTriggerAttribute) && | ||
| knownSymbols.FunctionNameAttribute != null && | ||
| methodSymbol.TryGetSingleValueFromAttribute(knownSymbols.FunctionNameAttribute, out string functionName)) | ||
| { | ||
| activityNames.Add(functionName); | ||
| } | ||
|
|
||
| // Check for Orchestrator defined via [OrchestrationTrigger] | ||
| if (knownSymbols.FunctionOrchestrationAttribute != null && | ||
| methodSymbol.ContainsAttributeInAnyMethodArguments(knownSymbols.FunctionOrchestrationAttribute) && | ||
| knownSymbols.FunctionNameAttribute != null && | ||
| methodSymbol.TryGetSingleValueFromAttribute(knownSymbols.FunctionNameAttribute, out string orchestratorFunctionName)) | ||
| { | ||
| orchestratorNames.Add(orchestratorFunctionName); | ||
| } | ||
| }, | ||
| SymbolKind.Method); | ||
|
|
||
| // Search for TaskActivity<TInput, TOutput> definitions (class-based syntax) | ||
| context.RegisterSyntaxNodeAction( | ||
| ctx => | ||
| { | ||
| ctx.CancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| if (ctx.ContainingSymbol is not INamedTypeSymbol classSymbol) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (classSymbol.IsAbstract) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // Check for TaskActivity<TInput, TOutput> derived classes | ||
| if (knownSymbols.TaskActivityBase != null && taskActivityRunAsync != null) | ||
| { | ||
| if (ClassOverridesMethod(classSymbol, taskActivityRunAsync)) | ||
| { | ||
| activityNames.Add(classSymbol.Name); | ||
| } | ||
| } | ||
|
|
||
| // Check for ITaskOrchestrator implementations (class-based orchestrators) | ||
| if (knownSymbols.TaskOrchestratorInterface != null && | ||
| classSymbol.AllInterfaces.Any(i => SymbolEqualityComparer.Default.Equals(i, knownSymbols.TaskOrchestratorInterface))) | ||
| { | ||
| orchestratorNames.Add(classSymbol.Name); | ||
| } | ||
| }, | ||
| 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 (knownSymbols.DurableTaskRegistry == null || | ||
| !SymbolEqualityComparer.Default.Equals(invocation.Type, knownSymbols.DurableTaskRegistry)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // Handle AddActivityFunc registrations | ||
| if (invocation.TargetMethod.Name == "AddActivityFunc") | ||
| { | ||
| string? name = ExtractFunctionName(invocation, "name", ctx); | ||
| if (name != null) | ||
| { | ||
| activityNames.Add(name); | ||
| } | ||
| } | ||
|
|
||
| // Handle AddOrchestratorFunc registrations | ||
| if (invocation.TargetMethod.Name == "AddOrchestratorFunc") | ||
| { | ||
| string? name = ExtractFunctionName(invocation, "name", ctx); | ||
| if (name != null) | ||
| { | ||
| orchestratorNames.Add(name); | ||
| } | ||
| } | ||
| }, | ||
| OperationKind.Invocation); | ||
|
|
||
| // At the end of the compilation, we correlate the invocations with the definitions | ||
| context.RegisterCompilationEndAction(ctx => | ||
| { | ||
| // Create lookup sets for faster searching | ||
| HashSet<string> definedActivities = new(activityNames); | ||
| HashSet<string> definedOrchestrators = new(orchestratorNames); | ||
|
|
||
| // Report diagnostics for activities not found | ||
| foreach (FunctionInvocation invocation in activityInvocations) | ||
| { | ||
| if (!definedActivities.Contains(invocation.Name)) | ||
| { | ||
| Diagnostic diagnostic = RoslynExtensions.BuildDiagnostic( | ||
| ActivityNotFoundRule, invocation.InvocationSyntaxNode, invocation.Name); | ||
| ctx.ReportDiagnostic(diagnostic); | ||
| } | ||
| } | ||
github-code-quality[bot] marked this conversation as resolved.
Fixed
Show fixed
Hide fixed
github-code-quality[bot] marked this conversation as resolved.
Fixed
Show fixed
Hide fixed
|
||
|
|
||
| // Report diagnostics for sub-orchestrators not found | ||
| foreach (FunctionInvocation invocation in subOrchestrationInvocations) | ||
| { | ||
| if (!definedOrchestrators.Contains(invocation.Name)) | ||
| { | ||
| Diagnostic diagnostic = RoslynExtensions.BuildDiagnostic( | ||
| SubOrchestrationNotFoundRule, invocation.InvocationSyntaxNode, invocation.Name); | ||
| ctx.ReportDiagnostic(diagnostic); | ||
| } | ||
| } | ||
github-code-quality[bot] marked this conversation as resolved.
Fixed
Show fixed
Hide fixed
github-code-quality[bot] marked this conversation as resolved.
Fixed
Show fixed
Hide fixed
|
||
| }); | ||
| }); | ||
| } | ||
|
|
||
| static string? ExtractFunctionName(IInvocationOperation invocationOperation, string parameterName, OperationAnalysisContext ctx) | ||
| { | ||
| IArgumentOperation? nameArgumentOperation = invocationOperation.Arguments.SingleOrDefault(a => a.Parameter?.Name == parameterName); | ||
| if (nameArgumentOperation == null) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| SemanticModel? semanticModel = ctx.Operation.SemanticModel; | ||
| if (semanticModel == null) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| // extracts the constant value from the argument (e.g.: it can be a nameof, string literal or const field) | ||
| Optional<object?> constant = semanticModel.GetConstantValue(nameArgumentOperation.Value.Syntax); | ||
| if (!constant.HasValue) | ||
| { | ||
| // not a constant value, we cannot correlate this invocation to an existent function in compile time | ||
| return null; | ||
| } | ||
|
|
||
| return constant.Value?.ToString(); | ||
| } | ||
|
|
||
| static bool ClassOverridesMethod(INamedTypeSymbol classSymbol, IMethodSymbol methodToFind) | ||
| { | ||
| INamedTypeSymbol? baseType = classSymbol; | ||
| while (baseType != null) | ||
| { | ||
| foreach (IMethodSymbol method in baseType.GetMembers().OfType<IMethodSymbol>()) | ||
| { | ||
| if (SymbolEqualityComparer.Default.Equals(method.OverriddenMethod?.OriginalDefinition, methodToFind)) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
github-code-quality[bot] marked this conversation as resolved.
Fixed
Show fixed
Hide fixed
|
||
|
|
||
| baseType = baseType.BaseType; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| readonly struct FunctionInvocation(string name, SyntaxNode invocationSyntaxNode) | ||
| { | ||
| public string Name { get; } = name; | ||
|
|
||
| public SyntaxNode InvocationSyntaxNode { get; } = invocationSyntaxNode; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,9 @@ | ||
| ; Unshipped analyzer release | ||
| ; https://github.com/dotnet/roslyn/blob/main/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md | ||
| ; https://github.com/dotnet/roslyn/blob/main/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md | ||
|
|
||
| ### New Rules | ||
|
|
||
| Rule ID | Category | Severity | Notes | ||
| --------|----------|----------|------- | ||
| DURABLE2003 | Activity | Warning | **FunctionNotFoundAnalyzer**: Warns when an activity function call references a name that does not match any defined activity in the compilation. | ||
| DURABLE2004 | Orchestration | Warning | **FunctionNotFoundAnalyzer**: Warns when a sub-orchestration call references a name that does not match any defined orchestrator in the compilation. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.