AArnott / CodeGeneration.Roslyn

Assists in performing Roslyn-based code generation during a build.
Microsoft Public License
408 stars 60 forks source link

Support C# Code Snippets to generate code. #175

Closed Corniel closed 4 years ago

Corniel commented 4 years ago

Using code snippets as starting point for code generation can make the code generator much easier to read/maintain. Writing code with the SyntaxTreeFactory can be hard.

So how does should this work?

We have some file (embedded, or disk)

public struct @Name
{
    public @Name(int count) => Count = count;
    public int Count { get; }
}

With some simple generator files. What kind of transform you want to apply should be as free as possible, so let the generator decide for its own. In this example its a simple string replace.

class SimpleCodeSnippet : CSharpCodeSnippet<TransformArguments>
{
    public SimpleCodeSnippet(string text)
        : base(text, "test.cs", null) { }

    protected override string TransformText(TransformArguments arguments)
    {
        return Text.Replace("@Name", arguments.Name);
    }
}
class TransformArguments
{
    public string Name { get; set; }
}

This can be used like this:

SimpleCodeSnippet snippet = GetCodeSnippet(); // embedded resource, disk, whatever.
var syntax = await snippet.ParseAysnc<StructDeclarationSyntax>(new TransformArguments { Name = "TestStruct" });
amis92 commented 4 years ago

Hi! It is a very interesting idea, however I don't think it has a place in this project. I'd much more likely see this as an actual plugin project.

This project only delivers bare minimum framework to run your generators with.

Of course, if such a plugin would be written, we could feature it as a good starting point.

amis92 commented 4 years ago

@AArnott what do you think?

AArnott commented 4 years ago

I agree.