|
| 1 | +using System; |
| 2 | +using System.Collections.Immutable; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using Microsoft.CodeAnalysis; |
| 6 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 7 | + |
| 8 | +namespace Lagrange.Core.Generator; |
| 9 | + |
| 10 | +[Generator(LanguageNames.CSharp)] |
| 11 | +public sealed class EventLogicSourceGenerator : IIncrementalGenerator |
| 12 | +{ |
| 13 | + private const string LogicInterfaceFullName = "Lagrange.Core.Internal.Logic.ILogic"; |
| 14 | + private const string EventSubscribeAttributeNamespace = "Lagrange.Core.Internal.Events"; |
| 15 | + private const string EventSubscribeAttributeName = "EventSubscribeAttribute"; |
| 16 | + |
| 17 | + private static readonly SymbolDisplayFormat TypeDisplayFormat = SymbolDisplayFormat.FullyQualifiedFormat; |
| 18 | + |
| 19 | + public void Initialize(IncrementalGeneratorInitializationContext context) |
| 20 | + { |
| 21 | + var candidates = context.SyntaxProvider.CreateSyntaxProvider( |
| 22 | + static (node, _) => node is ClassDeclarationSyntax { BaseList: not null }, |
| 23 | + static (context, _) => ToEventLogicInfo(context) |
| 24 | + ); |
| 25 | + |
| 26 | + var logics = candidates.SelectMany(static (logic, _) => |
| 27 | + logic.HasValue ? [logic.GetValueOrDefault()] : ImmutableArray<EventLogicInfo>.Empty); |
| 28 | + |
| 29 | + context.RegisterSourceOutput(logics.Collect(), static (context, logics) => Output(context, logics)); |
| 30 | + } |
| 31 | + |
| 32 | + private static EventLogicInfo? ToEventLogicInfo(GeneratorSyntaxContext context) |
| 33 | + { |
| 34 | + if (context.SemanticModel.GetDeclaredSymbol(context.Node) is not INamedTypeSymbol { TypeKind: TypeKind.Class } typeSymbol || typeSymbol.IsAbstract) return null; |
| 35 | + |
| 36 | + var logicInterface = context.SemanticModel.Compilation.GetTypeByMetadataName(LogicInterfaceFullName); |
| 37 | + if (logicInterface is null || !typeSymbol.AllInterfaces.Any(type => SymbolEqualityComparer.Default.Equals(type, logicInterface))) return null; |
| 38 | + |
| 39 | + var events = ImmutableArray.CreateBuilder<EventSubscriptionInfo>(); |
| 40 | + foreach (var attribute in typeSymbol.GetAttributes()) |
| 41 | + { |
| 42 | + if (TryGetEventSubscription(attribute, out var subscription)) |
| 43 | + { |
| 44 | + events.Add(subscription); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + var location = typeSymbol.Locations.FirstOrDefault(static location => location.IsInSource); |
| 49 | + string sortPath = location?.SourceTree?.FilePath ?? string.Empty; |
| 50 | + int sortStart = location?.SourceSpan.Start ?? 0; |
| 51 | + |
| 52 | + return new EventLogicInfo( |
| 53 | + typeSymbol.ToDisplayString(TypeDisplayFormat), |
| 54 | + events.ToImmutable(), |
| 55 | + sortPath, |
| 56 | + sortStart |
| 57 | + ); |
| 58 | + } |
| 59 | + |
| 60 | + private static bool TryGetEventSubscription(AttributeData attribute, out EventSubscriptionInfo subscription) |
| 61 | + { |
| 62 | + subscription = default; |
| 63 | + |
| 64 | + if (attribute.AttributeClass is not { Name: EventSubscribeAttributeName } attributeClass || attributeClass.ContainingNamespace.ToDisplayString() != EventSubscribeAttributeNamespace) |
| 65 | + { |
| 66 | + return false; |
| 67 | + } |
| 68 | + |
| 69 | + ITypeSymbol? eventType; |
| 70 | + if (attributeClass.Arity == 1) |
| 71 | + { |
| 72 | + eventType = attributeClass.TypeArguments[0]; |
| 73 | + } |
| 74 | + else |
| 75 | + { |
| 76 | + if (attribute.ConstructorArguments.Length == 0) return false; |
| 77 | + eventType = attribute.ConstructorArguments[0].Value as ITypeSymbol; |
| 78 | + } |
| 79 | + |
| 80 | + if (eventType is null) return false; |
| 81 | + |
| 82 | + subscription = new EventSubscriptionInfo(eventType.ToDisplayString(TypeDisplayFormat)); |
| 83 | + return true; |
| 84 | + } |
| 85 | + |
| 86 | + private static void Output(SourceProductionContext context, ImmutableArray<EventLogicInfo> logics) |
| 87 | + { |
| 88 | + var orderedLogics = logics |
| 89 | + .OrderBy(static logic => logic.SortPath, StringComparer.Ordinal) |
| 90 | + .ThenBy(static logic => logic.SortStart) |
| 91 | + .ThenBy(static logic => logic.LogicType) |
| 92 | + .ToList(); |
| 93 | + |
| 94 | + var source = new StringBuilder(); |
| 95 | + source.AppendLine("#nullable enable"); |
| 96 | + source.AppendLine(); |
| 97 | + source.AppendLine("using System.Collections.Frozen;"); |
| 98 | + source.AppendLine(); |
| 99 | + source.AppendLine("namespace Lagrange.Core.Internal.Context;"); |
| 100 | + source.AppendLine(); |
| 101 | + source.AppendLine("internal static class EventLogicRegistry"); |
| 102 | + source.AppendLine("{"); |
| 103 | + source.AppendLine(" internal static (global::System.Collections.Frozen.FrozenDictionary<global::System.Type, global::System.Collections.Generic.List<global::Lagrange.Core.Internal.Logic.ILogic>> Events, global::System.Collections.Frozen.FrozenDictionary<global::System.Type, global::Lagrange.Core.Internal.Logic.ILogic> Logics) Create(global::Lagrange.Core.BotContext context)"); |
| 104 | + source.AppendLine(" {"); |
| 105 | + source.AppendLine(" var events = new global::System.Collections.Generic.Dictionary<global::System.Type, global::System.Collections.Generic.List<global::Lagrange.Core.Internal.Logic.ILogic>>();"); |
| 106 | + source.AppendLine(" var logics = new global::System.Collections.Generic.Dictionary<global::System.Type, global::Lagrange.Core.Internal.Logic.ILogic>();"); |
| 107 | + source.AppendLine(); |
| 108 | + |
| 109 | + for (int i = 0; i < orderedLogics.Count; i++) |
| 110 | + { |
| 111 | + source.Append(" Register").Append(i).AppendLine("(context, events, logics);"); |
| 112 | + } |
| 113 | + |
| 114 | + source.AppendLine(); |
| 115 | + source.AppendLine(" return (events.ToFrozenDictionary(), logics.ToFrozenDictionary());"); |
| 116 | + source.AppendLine(" }"); |
| 117 | + source.AppendLine(); |
| 118 | + source.AppendLine(" private static void AddEvent(global::System.Type eventType, global::Lagrange.Core.Internal.Logic.ILogic logic, global::System.Collections.Generic.Dictionary<global::System.Type, global::System.Collections.Generic.List<global::Lagrange.Core.Internal.Logic.ILogic>> events)"); |
| 119 | + source.AppendLine(" {"); |
| 120 | + source.AppendLine(" if (!events.TryGetValue(eventType, out var list))"); |
| 121 | + source.AppendLine(" {"); |
| 122 | + source.AppendLine(" list = [];"); |
| 123 | + source.AppendLine(" events.Add(eventType, list);"); |
| 124 | + source.AppendLine(" }"); |
| 125 | + source.AppendLine(); |
| 126 | + source.AppendLine(" list.Add(logic);"); |
| 127 | + source.AppendLine(" }"); |
| 128 | + |
| 129 | + for (int i = 0; i < orderedLogics.Count; i++) |
| 130 | + { |
| 131 | + AppendRegisterMethod(source, i, orderedLogics[i]); |
| 132 | + } |
| 133 | + |
| 134 | + source.AppendLine("}"); |
| 135 | + |
| 136 | + context.AddSource("Lagrange.Core.Internal.Context.EventLogicRegistry.g.cs", source.ToString()); |
| 137 | + } |
| 138 | + |
| 139 | + private static void AppendRegisterMethod(StringBuilder source, int index, EventLogicInfo logic) |
| 140 | + { |
| 141 | + source.AppendLine(); |
| 142 | + source.Append(" private static void Register").Append(index).AppendLine("(global::Lagrange.Core.BotContext context, global::System.Collections.Generic.Dictionary<global::System.Type, global::System.Collections.Generic.List<global::Lagrange.Core.Internal.Logic.ILogic>> events, global::System.Collections.Generic.Dictionary<global::System.Type, global::Lagrange.Core.Internal.Logic.ILogic> logics)"); |
| 143 | + source.AppendLine(" {"); |
| 144 | + source.Append(" var logic = new ").Append(logic.LogicType).AppendLine("(context);"); |
| 145 | + |
| 146 | + foreach (var subscription in logic.Subscriptions) |
| 147 | + { |
| 148 | + source.Append(" AddEvent(typeof(").Append(subscription.EventType).AppendLine("), logic, events);"); |
| 149 | + } |
| 150 | + |
| 151 | + source.Append(" logics[typeof(").Append(logic.LogicType).AppendLine(")] = logic;"); |
| 152 | + source.AppendLine(" }"); |
| 153 | + } |
| 154 | + |
| 155 | + private readonly record struct EventLogicInfo( |
| 156 | + string LogicType, |
| 157 | + ImmutableArray<EventSubscriptionInfo> Subscriptions, |
| 158 | + string SortPath, |
| 159 | + int SortStart |
| 160 | + ); |
| 161 | + |
| 162 | + private readonly record struct EventSubscriptionInfo(string EventType); |
| 163 | +} |
0 commit comments