|
| 1 | +using Microsoft.CodeAnalysis; |
| 2 | +using Microsoft.CodeAnalysis.CSharp; |
| 3 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 4 | +using Microsoft.CodeAnalysis.Text; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Linq; |
| 7 | +using System.Text; |
| 8 | + |
| 9 | +namespace Riverside.Extensions.WinUI |
| 10 | +{ |
| 11 | + [Generator] |
| 12 | + public partial class InitializeComponentGenerator : ISourceGenerator |
| 13 | + { |
| 14 | + public void Initialize(GeneratorInitializationContext context) |
| 15 | + { |
| 16 | + // No initialization required for this source generator |
| 17 | + } |
| 18 | + |
| 19 | + public void Execute(GeneratorExecutionContext context) |
| 20 | + { |
| 21 | + // Find all classes with the InitializeComponentAttribute |
| 22 | + var classesWithAttribute = context.Compilation.SyntaxTrees |
| 23 | + .SelectMany(syntaxTree => syntaxTree.GetRoot().DescendantNodes()) |
| 24 | + .OfType<ClassDeclarationSyntax>() |
| 25 | + .Where(classDeclaration => classDeclaration.AttributeLists |
| 26 | + .SelectMany(attributeList => attributeList.Attributes) |
| 27 | + .Any(attribute => attribute.Name.ToString() == "InitializeComponent")); |
| 28 | + |
| 29 | + foreach (var classDeclaration in classesWithAttribute) |
| 30 | + { |
| 31 | + var namespaceDeclaration = classDeclaration.Ancestors().OfType<NamespaceDeclarationSyntax>().FirstOrDefault(); |
| 32 | + var namespaceName = namespaceDeclaration?.Name.ToString() ?? "GlobalNamespace"; |
| 33 | + var className = classDeclaration.Identifier.Text; |
| 34 | + |
| 35 | + var source = $@" |
| 36 | +namespace {namespaceName} |
| 37 | +{{ |
| 38 | + public partial class {className} |
| 39 | + {{ |
| 40 | + public {className}() |
| 41 | + {{ |
| 42 | + this.InitializeComponent(); |
| 43 | + }} |
| 44 | + }} |
| 45 | +}}"; |
| 46 | + context.AddSource($"{className}_InitializeComponent.g.cs", SourceText.From(source, Encoding.UTF8)); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments