From 03468ad89c9177871e5f094d9e116b2b5669d406 Mon Sep 17 00:00:00 2001 From: hzhang Date: Thu, 27 Feb 2025 15:39:27 +0000 Subject: [PATCH] redesign: Agents --- src/Generators/PoloniumFactoryGenerator.cs | 57 ++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/Generators/PoloniumFactoryGenerator.cs diff --git a/src/Generators/PoloniumFactoryGenerator.cs b/src/Generators/PoloniumFactoryGenerator.cs new file mode 100644 index 0000000..3c2615b --- /dev/null +++ b/src/Generators/PoloniumFactoryGenerator.cs @@ -0,0 +1,57 @@ +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Polonium.Generators.Generators; +[Generator] +public class PoloniumFactoryGenerator : AssetProcessGenerator +{ + public override void Execute(GeneratorExecutionContext context) + { + if (!(context.SyntaxReceiver is ClassSyntaxReceiver receiver)) + return; + StringBuilder sb = new(); + sb + .AppendLine("using System;") + .AppendLine("using Polonium.Attributes;") + .AppendLine("using Polonium.Interfaces;") + .AppendLine("using Polonium.Resources;") + .AppendLine("[AutoRegister]") + .AppendLine("public class PoloniumFactoryRegister") + .AppendLine("{") + .AppendLine(" public static void Register()") + .AppendLine(" {") + .AppendLine(" GlobalRegistry.PoloniumFactory = new PoloniumFactory();") + .AppendLine(" }") + .AppendLine(" public class PoloniumFactory : IPoloniumFactory") + .AppendLine(" {") + .AppendLine(" public SignalHeader CreateSignalHeader()") + .AppendLine(" {"); + Compilation compilation = context.Compilation; + INamedTypeSymbol? signalHeader = compilation.GetTypeByMetadataName("Polonium.Resources.SignalHeader"); + + bool founded = false; + foreach (ClassDeclarationSyntax cls in receiver.Classes) + { + SemanticModel semanticModel = compilation.GetSemanticModel(cls.SyntaxTree); + INamedTypeSymbol? nCls = semanticModel.GetDeclaredSymbol(cls) as INamedTypeSymbol; + if(nCls is null) + continue; + if (IsDerivedFrom(nCls, signalHeader) && !nCls.IsAbstract) + { + sb.AppendLine($" return new {nCls.ToDisplayString()}();"); + founded = true; + break; + } + } + if (!founded) + sb.AppendLine($" throw new NotImplementedException();"); + + sb + .AppendLine(" }") + .AppendLine(" }") + .AppendLine("}"); + + context.AddSource("PoloniumFactoryRegistry.g.cs", sb.ToString()); + } +} \ No newline at end of file