This assembly provides the ability to define CompilationEditor
s that will be used by Cometary to edit the assembly in which they are defined.
Install-Package Cometary.Metaprogramming
For example, the following CompilationEditor
adds a simple class to the final compilation.
using Cometary;
internal class CustomEditor : CompilationEditor
{
/// <inheritdoc />
public override void Initialize(CSharpCompilation _compilation, CancellationToken _cancellationToken)
{
RegisterEdit((compilation, cancellationToken) => {
var tree = SyntaxFactory.ParseSyntaxTree(@"
namespace Tests {
public static class Answers {
public static int LifeTheUniverseAndEverything => 42;
}
}
");
return compilation.AddSyntaxTrees(tree);
});
}
}
In any C# file, add the following lines.
using Cometary;
[assembly: EditSelf(typeof(CustomEditor))] // Or whatever your editor is named.
That's it.
You may want some code to only be compiled during the Metaprogramming phase. This can easily be done with the META
preprocessor symbol name.
#if META
// Only apply an attribute when editing the declaring assembly.
[assembly: SomeAttribute]
#endif
#if !META
// Only declare a type in the end result.
public class MyClass
{
}
#endif