Reputation: 2330
I'm doing a compiler for study purpose.
It uses Antlr tool targeted for c# code generation.
So far, i can handle the gramar. Lexical, Sintatic, my tests are ok.
My aim is to generate CIL bytecode, i'm kinda familiar with it.
The problem is... I don't know a good way to "output" the code. I'd like some advice, example to generate it.
One thought i have, is to create a Class "compiler" with tons of method related to the node and call the method as the tree is iterated.
Ideia:
Class Compiler
{
private AppededStrings = "";
void CreateClass();
void EndClass();
void AddParam();
void setAtributeToTheClass("public");
... and so on ...
}
Is this a good approach? I could not find a topic talking specific about this.
Upvotes: 3
Views: 577
Reputation: 24976
Here is an example from ANTLR 3.x.
Once you have an AST from ANTLR, per this question, the next task is to convert that into a set of executable instructions. Since the author is not requesting assembly as the output but CIL and is working with ANTLR, the best example on the web comes from the author of ANTLR. On this page Ter talks about how one uses the StringTemplate tool to generate the output that becomes the instructions. While Ter uses the popular LLVM for his demonstration, the same concepts apply for generating CIL as the author request.
Another option.
When I worked with Mercury, originally they generated CIL code. In the years that passed the CIL was not maintained but people still wanted to use Mercury with the .Net world. Since in the .NET world any .NET language compiles to CIL, by generating C# as the output of the Mercury compiler and then compiling the C# to CIL they achieved the same result of compiling Mercury to CIL but just via an intermediate language. Nowhere is it a rule that an intermediate language has to be a low level language.
Upvotes: 0
Reputation: 407
Some parts of the page http://msdn.microsoft.com/en-us/magazine/cc136756.aspx will work for you :)
Upvotes: 1