using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Immutable; using System.Text; namespace GeneratorLib; [Generator(LanguageNames.CSharp)] public class HelloWorldGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { var provider = context.SyntaxProvider.CreateSyntaxProvider( static (syntaxNode, _) => syntaxNode is ClassDeclarationSyntax, static (generatorSyntaxContext, _) => (ClassDeclarationSyntax)generatorSyntaxContext.Node) .Where(static node => node != null); var compilation = context.CompilationProvider.Combine(provider.Collect()); context.RegisterSourceOutput(compilation, ExecuteHelloWorldGeneration); } private static void ExecuteHelloWorldGeneration(SourceProductionContext context, (Compilation compilation, ImmutableArray classDeclarationSyntax) compilationProvider) { const string hintName = "HelloWorld.g.cs"; string sourceText = new StringBuilder() .AppendLine("namespace HelloNamespace") .AppendLine("{") .AppendLine("\tpublic class HelloWorld") .AppendLine("\t{") .AppendLine("\t\tpublic static void SayHello()") .AppendLine("\t\t{") .AppendLine("\t\t\tConsole.WriteLine(\"Hello, World!\");") .AppendLine("\t\t}") .AppendLine("\t}") .AppendLine("}") .ToString(); context.AddSource(hintName, sourceText); } }