using System.Text; using Microsoft.CodeAnalysis; namespace Hangman.SDK.Generators; [Generator] public class GlobalRegistryGenerator : ISourceGenerator { public void Initialize(GeneratorInitializationContext context) { } public void Execute(GeneratorExecutionContext context) { StringBuilder sb = new(); sb.AppendLine("using System;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Reflection;"); sb.AppendLine("using Hangman.SDK.Attributes;"); sb.AppendLine("public static partial class GlobalRegistry"); sb.AppendLine("{"); sb.AppendLine(" public static void Register()"); sb.AppendLine(" {"); sb.AppendLine(" Assembly assembly = Assembly.GetEntryAssembly();"); sb.AppendLine(" IEnumerable registerTypes = assembly.GetTypes()"); sb.AppendLine(" .Where(t => t.IsClass && t.GetCustomAttributes(typeof(AutoRegister), false).Any());"); sb.AppendLine(" foreach(Type t in registerTypes)"); sb.AppendLine(" {"); sb.AppendLine(" MethodInfo registerMethod = t.GetMethod(\"Register\", BindingFlags.Static | BindingFlags.Public);"); sb.AppendLine(" if (registerMethod != null)"); sb.AppendLine(" registerMethod.Invoke(null, null);"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine("}"); context.AddSource("GlobalRegistry.g.cs", sb.ToString()); } }