Skip to content

Customize a CodeGenerator

tremaluca edited this page Jun 5, 2018 · 1 revision

It is possible to modify the behaviour of an existing ChainOfResponsibilityHandlerCodeGenerator by adding new ICodeObjectHandler{T}s to it. During code generation handlers will be called starting from the most recently added, so you can add new handlers not only to generate new types of nodes, but also to modify how already existing nodes will be generated.
Let's say for example that you want to add a new expression that simply generates Foo. You'll need to create the CodeExpression and the Handler for the target language(s).

public class CodeFooExpression : CodeExpression {
}
public class FooExpressionHandler : ICodeObjectHandler<CodeExpression> {
    public bool Handle(CodeExpression obj, Context ctx)
    {
        if (obj is CodeFooExpression)
        {
            ctx.Writer.Write("Foo");
            return true;
        }
        return false;
    }
}

You'll then need to add an instance of the newly created handler to the code generator you are going to use, then every time a CodeFooExpression is encountered during generation it will be handled by the new handler.

var codeGenerator = CodeGeneratorFactory.GetCodeGenerator(Language.CSharp);
codeGenerator.AddExpressionHandler(new FooExpressionHandler());
Clone this wiki locally