Automatically Triggering Code Generation From A DSL Model

By Anoop Madhusudanan

Vote on HN
If you've used Microsoft DSL Tools, you know that normally the user has to click 'Transform Templates' button in the Solution Explorer - to start running text templates on your DSL Model. Well, what if you need to trigger the code generation automatically, when ever the model changes? Here is a simple solution.

Firs of all, create a code generator class in your DSL Project - inheriting the TemplatedCodeGenerator. Override the GenerateCodeMethod. The first parameter is the DSL model filename against which you need to generate the code, and the second parameter is the template file content you may execute against your model. You can substitute the templateFileContent with your own template code. Here, I'm loading the same from my resource file.
    public class MyModelCodeGenerator : TemplatedCodeGenerator

        protected override byte[] 
            GenerateCode(string modelFileName, string templateFileContent)
                    // Replace the supplied file contents 
                    // with the template we want to run
                    // Substitute the name of the current 
                    // model file into the template.
                    FileInfo fi = new FileInfo(modelFileName);
                    templateFileContent = templateFileContent.Replace
                                 ("%modelfile%", fi.Name);

                    // Now just delegate the rest of the 
                    //work to the base class
                    byte[] data = base.GenerateCode
                           (modelFileName, templateFileContent);
                    return data;

Interestingly, I'm replacing the token %modelfile% in my template content with the actual model file name. The template content I loaded from the resource file looks something like this.
<#@ template inherits="TextTemplating.VSHost.ModelingTextTransformation" #>
<#@ output extension=".cs" #>
<#@ MyDSL processor="MyDSLDirectiveProcessor" 
                requires="fileName='%modelfile%'" #>

//--- More Template Code --//

As the final step, we should specify our MyModelCodeGenerator as the code generator of our DSL Package, using the ProvideCodeGenerator attribute.

For this, create a partial class of your package in your DSLPackage project, and use the ProvideCodeGenerator attribute to register your generator.
         "MyModelCodeGenerator", "Generates code from the model", true)]
    internal sealed partial class MyDSLPackage

And you are done!!

No comments:

Post a Comment

Please keep your comments clean.

© 2012. All Rights Reserved.