-
Notifications
You must be signed in to change notification settings - Fork 1k
Python: .NET: Executor source gen for workflow executor routing #3131
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
Open
alliscode
wants to merge
6
commits into
microsoft:main
Choose a base branch
from
alliscode:wf-source-gen
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.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
90a2ab0
Roslyn Source Generators for Workflow Executor Routing.
d40ed1b
Update dotnet/src/Microsoft.Agents.AI.Workflows.Generators/ExecutorRo…
alliscode b9c2588
WIP.
27824ed
All fixed up except dangling sends/yields attriutes, working on that …
7878562
Add protocol-only generation for SendsMessage/YieldsOutput attributes
8acbd99
Ensuring collections that can change order are sorted to enable pipel…
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
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
693 changes: 693 additions & 0 deletions
693
dotnet/src/Microsoft.Agents.AI.Workflows.Generators/Analysis/SemanticAnalyzer.cs
Large diffs are not rendered by default.
Oops, something went wrong.
107 changes: 107 additions & 0 deletions
107
dotnet/src/Microsoft.Agents.AI.Workflows.Generators/Diagnostics/DiagnosticDescriptors.cs
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,107 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System.Collections.Generic; | ||
| using Microsoft.CodeAnalysis; | ||
|
|
||
| namespace Microsoft.Agents.AI.Workflows.Generators.Diagnostics; | ||
|
|
||
| /// <summary> | ||
| /// Diagnostic descriptors for the executor route source generator. | ||
| /// </summary> | ||
| internal static class DiagnosticDescriptors | ||
| { | ||
| private const string Category = "Microsoft.Agents.AI.Workflows.Generators"; | ||
|
|
||
| private static readonly Dictionary<string, DiagnosticDescriptor> s_descriptorsById = new(); | ||
|
|
||
| /// <summary> | ||
| /// Gets a diagnostic descriptor by its ID. | ||
| /// </summary> | ||
| public static DiagnosticDescriptor? GetById(string id) | ||
| { | ||
| return s_descriptorsById.TryGetValue(id, out var descriptor) ? descriptor : null; | ||
| } | ||
|
|
||
| private static DiagnosticDescriptor Register(DiagnosticDescriptor descriptor) | ||
| { | ||
| s_descriptorsById[descriptor.Id] = descriptor; | ||
| return descriptor; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// MAFGENWF001: Handler method must have IWorkflowContext parameter. | ||
| /// </summary> | ||
| public static readonly DiagnosticDescriptor MissingWorkflowContext = Register(new( | ||
| id: "MAFGENWF001", | ||
| title: "Handler missing IWorkflowContext parameter", | ||
| messageFormat: "Method '{0}' marked with [MessageHandler] must have IWorkflowContext as the second parameter", | ||
| category: Category, | ||
| defaultSeverity: DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true)); | ||
|
|
||
| /// <summary> | ||
| /// MAFGENWF002: Handler method has invalid return type. | ||
| /// </summary> | ||
| public static readonly DiagnosticDescriptor InvalidReturnType = Register(new( | ||
| id: "MAFGENWF002", | ||
| title: "Handler has invalid return type", | ||
| messageFormat: "Method '{0}' marked with [MessageHandler] must return void, ValueTask, or ValueTask<T>", | ||
| category: Category, | ||
| defaultSeverity: DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true)); | ||
|
|
||
| /// <summary> | ||
| /// MAFGENWF003: Executor with [MessageHandler] must be partial. | ||
| /// </summary> | ||
| public static readonly DiagnosticDescriptor ClassMustBePartial = Register(new( | ||
| id: "MAFGENWF003", | ||
| title: "Executor with [MessageHandler] must be partial", | ||
| messageFormat: "Class '{0}' contains [MessageHandler] methods but is not declared as partial", | ||
| category: Category, | ||
| defaultSeverity: DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true)); | ||
|
|
||
| /// <summary> | ||
| /// MAFGENWF004: [MessageHandler] on non-Executor class. | ||
| /// </summary> | ||
| public static readonly DiagnosticDescriptor NotAnExecutor = Register(new( | ||
| id: "MAFGENWF004", | ||
| title: "[MessageHandler] on non-Executor class", | ||
| messageFormat: "Method '{0}' is marked with [MessageHandler] but class '{1}' does not derive from Executor", | ||
| category: Category, | ||
| defaultSeverity: DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true)); | ||
|
|
||
| /// <summary> | ||
| /// MAFGENWF005: Handler method has insufficient parameters. | ||
| /// </summary> | ||
| public static readonly DiagnosticDescriptor InsufficientParameters = Register(new( | ||
| id: "MAFGENWF005", | ||
| title: "Handler has insufficient parameters", | ||
| messageFormat: "Method '{0}' marked with [MessageHandler] must have at least 2 parameters (message and IWorkflowContext)", | ||
| category: Category, | ||
| defaultSeverity: DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true)); | ||
|
|
||
| /// <summary> | ||
| /// MAFGENWF006: ConfigureRoutes already defined. | ||
| /// </summary> | ||
| public static readonly DiagnosticDescriptor ConfigureRoutesAlreadyDefined = Register(new( | ||
| id: "MAFGENWF006", | ||
| title: "ConfigureRoutes already defined", | ||
| messageFormat: "Class '{0}' already defines ConfigureRoutes; [MessageHandler] methods will be ignored", | ||
| category: Category, | ||
| defaultSeverity: DiagnosticSeverity.Info, | ||
| isEnabledByDefault: true)); | ||
|
|
||
| /// <summary> | ||
| /// MAFGENWF007: Handler method is static. | ||
| /// </summary> | ||
| public static readonly DiagnosticDescriptor HandlerCannotBeStatic = Register(new( | ||
| id: "MAFGENWF007", | ||
| title: "Handler cannot be static", | ||
| messageFormat: "Method '{0}' marked with [MessageHandler] cannot be static", | ||
| category: Category, | ||
| defaultSeverity: DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true)); | ||
| } | ||
18 changes: 18 additions & 0 deletions
18
dotnet/src/Microsoft.Agents.AI.Workflows.Generators/Directory.Build.targets
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,18 @@ | ||
| <Project> | ||
| <!-- Import parent Directory.Build.targets if it exists --> | ||
| <PropertyGroup> | ||
| <_ParentTargetsPath>$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets, $(MSBuildThisFileDirectory)..))</_ParentTargetsPath> | ||
| </PropertyGroup> | ||
| <Import Project="$(_ParentTargetsPath)" Condition="'$(_ParentTargetsPath)' != ''" /> | ||
|
|
||
| <!-- Since the generators project must target netstandard2.0, if any other TFM is specified we flag it silently --> | ||
| <PropertyGroup Condition="'$(TargetFramework)' != 'netstandard2.0'"> | ||
| <_SkipIncompatibleBuild>true</_SkipIncompatibleBuild> | ||
| <!-- Bypass NETSDK1005 by clearing assets file path --> | ||
| <ProjectAssetsFile /> | ||
| <ResolveAssemblyReferencesSilentlySkip>true</ResolveAssemblyReferencesSilentlySkip> | ||
| </PropertyGroup> | ||
|
|
||
| <!-- Since the generators project must target netstandard2.0, if any other TFM is specified we skip the build. --> | ||
| <Import Project="SkipIncompatibleBuild.targets" Condition="'$(_SkipIncompatibleBuild)' == 'true'" /> | ||
| </Project> |
161 changes: 161 additions & 0 deletions
161
dotnet/src/Microsoft.Agents.AI.Workflows.Generators/ExecutorRouteGenerator.cs
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,161 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System.Collections.Generic; | ||
| using System.Collections.Immutable; | ||
| using System.Linq; | ||
| using System.Text; | ||
| using Microsoft.Agents.AI.Workflows.Generators.Analysis; | ||
| using Microsoft.Agents.AI.Workflows.Generators.Generation; | ||
| using Microsoft.Agents.AI.Workflows.Generators.Models; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Text; | ||
|
|
||
| namespace Microsoft.Agents.AI.Workflows.Generators; | ||
|
|
||
| /// <summary> | ||
| /// Roslyn incremental source generator that generates ConfigureRoutes implementations | ||
| /// for executor classes with [MessageHandler] attributed methods, and/or ConfigureSentTypes/ConfigureYieldTypes | ||
| /// overrides for classes with [SendsMessage]/[YieldsOutput] attributes. | ||
| /// </summary> | ||
| [Generator] | ||
| public sealed class ExecutorRouteGenerator : IIncrementalGenerator | ||
| { | ||
| private const string MessageHandlerAttributeFullName = "Microsoft.Agents.AI.Workflows.MessageHandlerAttribute"; | ||
| private const string SendsMessageAttributeFullName = "Microsoft.Agents.AI.Workflows.SendsMessageAttribute"; | ||
| private const string YieldsOutputAttributeFullName = "Microsoft.Agents.AI.Workflows.YieldsOutputAttribute"; | ||
|
|
||
| /// <inheritdoc/> | ||
| public void Initialize(IncrementalGeneratorInitializationContext context) | ||
| { | ||
| // Pipeline 1: Methods with [MessageHandler] attribute | ||
| IncrementalValuesProvider<MethodAnalysisResult> methodAnalysisResults = context.SyntaxProvider | ||
| .ForAttributeWithMetadataName( | ||
| fullyQualifiedMetadataName: MessageHandlerAttributeFullName, | ||
| predicate: static (node, _) => node is MethodDeclarationSyntax, | ||
| transform: static (ctx, ct) => SemanticAnalyzer.AnalyzeHandlerMethod(ctx, ct)) | ||
| .Where(static result => !string.IsNullOrEmpty(result.ClassKey)); | ||
|
|
||
| // Pipeline 2: Classes with [SendsMessage] attribute | ||
| IncrementalValuesProvider<ClassProtocolInfo> sendProtocolResults = context.SyntaxProvider | ||
| .ForAttributeWithMetadataName( | ||
| fullyQualifiedMetadataName: SendsMessageAttributeFullName, | ||
| predicate: static (node, _) => node is ClassDeclarationSyntax, | ||
| transform: static (ctx, ct) => SemanticAnalyzer.AnalyzeClassProtocolAttribute(ctx, ProtocolAttributeKind.Send, ct)) | ||
| .SelectMany(static (results, _) => results); | ||
|
|
||
| // Pipeline 3: Classes with [YieldsOutput] attribute | ||
| IncrementalValuesProvider<ClassProtocolInfo> yieldProtocolResults = context.SyntaxProvider | ||
| .ForAttributeWithMetadataName( | ||
| fullyQualifiedMetadataName: YieldsOutputAttributeFullName, | ||
| predicate: static (node, _) => node is ClassDeclarationSyntax, | ||
| transform: static (ctx, ct) => SemanticAnalyzer.AnalyzeClassProtocolAttribute(ctx, ProtocolAttributeKind.Yield, ct)) | ||
| .SelectMany(static (results, _) => results); | ||
|
|
||
| // Combine all protocol results (Send + Yield) | ||
| IncrementalValuesProvider<ClassProtocolInfo> allProtocolResults = sendProtocolResults | ||
| .Collect() | ||
| .Combine(yieldProtocolResults.Collect()) | ||
| .SelectMany(static (tuple, _) => tuple.Left.AddRange(tuple.Right)); | ||
|
|
||
| // Combine all pipelines and produce AnalysisResults grouped by class | ||
| IncrementalValuesProvider<AnalysisResult> combinedResults = methodAnalysisResults | ||
| .Collect() | ||
| .Combine(allProtocolResults.Collect()) | ||
| .SelectMany(static (tuple, _) => CombineAllResults(tuple.Left, tuple.Right)); | ||
|
|
||
| // Generate source for valid executors | ||
| context.RegisterSourceOutput( | ||
| combinedResults.Where(static r => r.ExecutorInfo is not null), | ||
| static (ctx, result) => | ||
| { | ||
| string source = SourceBuilder.Generate(result.ExecutorInfo!); | ||
| string hintName = GetHintName(result.ExecutorInfo!); | ||
| ctx.AddSource(hintName, SourceText.From(source, Encoding.UTF8)); | ||
| }); | ||
|
|
||
| // Report diagnostics | ||
| context.RegisterSourceOutput( | ||
| combinedResults.Where(static r => !r.Diagnostics.IsEmpty), | ||
| static (ctx, result) => | ||
| { | ||
| foreach (Diagnostic diagnostic in result.Diagnostics) | ||
| { | ||
| ctx.ReportDiagnostic(diagnostic); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Combines method analysis results with class protocol results, grouping by class key. | ||
| /// Classes with [MessageHandler] methods get full generation; classes with only protocol | ||
| /// attributes get protocol-only generation. | ||
| /// </summary> | ||
| private static IEnumerable<AnalysisResult> CombineAllResults( | ||
| ImmutableArray<MethodAnalysisResult> methodResults, | ||
| ImmutableArray<ClassProtocolInfo> protocolResults) | ||
| { | ||
| // Group method results by class | ||
| Dictionary<string, List<MethodAnalysisResult>> methodsByClass = methodResults | ||
| .GroupBy(r => r.ClassKey) | ||
| .ToDictionary(g => g.Key, g => g.ToList()); | ||
|
|
||
| // Group protocol results by class | ||
| Dictionary<string, List<ClassProtocolInfo>> protocolsByClass = protocolResults | ||
| .GroupBy(r => r.ClassKey) | ||
| .ToDictionary(g => g.Key, g => g.ToList()); | ||
|
|
||
| // Track which classes we've processed | ||
| HashSet<string> processedClasses = new(); | ||
|
|
||
| // Process classes that have [MessageHandler] methods | ||
| foreach (KeyValuePair<string, List<MethodAnalysisResult>> kvp in methodsByClass) | ||
| { | ||
| processedClasses.Add(kvp.Key); | ||
| yield return SemanticAnalyzer.CombineHandlerMethodResults(kvp.Value); | ||
| } | ||
|
|
||
| // Process classes that only have protocol attributes (no [MessageHandler] methods) | ||
| foreach (KeyValuePair<string, List<ClassProtocolInfo>> kvp in protocolsByClass) | ||
| { | ||
| if (!processedClasses.Contains(kvp.Key)) | ||
| { | ||
| yield return SemanticAnalyzer.CombineProtocolOnlyResults(kvp.Value); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Generates a hint (virtual file) name for the generated source file based on the ExecutorInfo. | ||
| /// </summary> | ||
| private static string GetHintName(ExecutorInfo info) | ||
| { | ||
| var sb = new StringBuilder(); | ||
|
|
||
| if (!string.IsNullOrEmpty(info.Namespace)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: Probably better to use IsNullOrWhitespace or is whitespace a valid namespace? |
||
| { | ||
| sb.Append(info.Namespace) | ||
| .Append('.'); | ||
| } | ||
|
|
||
| if (info.IsNested) | ||
| { | ||
| sb.Append(info.ContainingTypeChain) | ||
| .Append('.'); | ||
| } | ||
|
|
||
| sb.Append(info.ClassName); | ||
|
|
||
| // Handle generic type parameters in hint name | ||
| if (!string.IsNullOrEmpty(info.GenericParameters)) | ||
| { | ||
| // Replace < > with underscores for valid file name | ||
| sb.Append('_') | ||
| .Append(info.GenericParameters!.Length - 2); // Number of type params approximation | ||
| } | ||
|
|
||
| sb.Append(".g.cs"); | ||
|
|
||
| return sb.ToString(); | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't need to localize these strings, right?