44 lines
1.4 KiB
C#
44 lines
1.4 KiB
C#
using Microsoft.CodeAnalysis;
|
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
|
using System.Collections.Immutable;
|
|
|
|
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> classDeclarationSyntax) compilationProvider)
|
|
{
|
|
const string hintName = "HelloWorld.g.cs";
|
|
const string sourceText = """
|
|
namespace HelloNamespace
|
|
{
|
|
abcd
|
|
public static class HelloWorld
|
|
{
|
|
public static void SayHello()
|
|
{
|
|
Console.WriteLine(\"Hello, World!\");
|
|
}
|
|
}
|
|
invalidtexthere
|
|
}
|
|
""";
|
|
|
|
//(Compilation compilation, ImmutableArray<ClassDeclarationSyntax> classDeclarationSyntax) = compilationProvider;
|
|
context.AddSource(hintName, sourceText);
|
|
}
|
|
}
|