[antlr-interest] pretty printing in the c target

Andy Tripp antlr at jazillian.com
Tue Dec 16 10:51:46 PST 2008


You could start with plain Java code that prints a Java AST:
http://www.jazillian.com/antlr/emitter.html
...and just change the "case" statements in JavaEmitter.print() to
their C equivalents.

Andy


Robert Soule wrote:
> Hi,
> 
> I am trying to write a pretty printer for my input language. In java,
> I read in the source, convert to the AST, then use a tree grammar
> to call the StringTemplates, and everything works fine. However,
> I need to use C as the target language, and there isn't a StringTemplate
> implementation in C.
> 
> I looked at the examples that are available on the antlr.org website,
> but the only ones that pretty print are toy examples, and simple append
> the character strings to the text contained in the token literals. This
> isn't really a feasible approach in my language. So, what I've ended up
> doing is following a pattern more or less like the following:
> 
> someRule
> returns [pANTLR3_STRING result]
> @init {result = factory->newRaw(factory);}
> : ^(SOMETOKEN anotherRule thirdRule)
> {
>   $result->append($result, "Start\n");
>   $result->appendS($result, $anotherRule.result);
>   factory->destroy(factory, $aotherRule.result);
>   $result->appendS($result, $thirdRule.result);
>   factory->destroy(factory, $thirdRule.result);
>   $result->append($result, "\n\n");
> }
> 
> However, I've encountered a few problems with this approach. First,
> when I call factory->close(..) at the end of my program, I get a double
> free problem, and I don't see in the API where I can call remove on
> the string from the factory. However, more troubling is that when the
> return of one of the rules like anotherRule is composed of only
> small literal strings (like "()"),  then calling destroy on the result sometimes
> frees too much memory, so that I cause problems for "thirdRule".
> Moreover, this just seems like an awkward way to build up my output
> string.
> 
> Since this seems like a pretty common task, I was wondering if
> there is a common, recommended way of doing this?
> 
> thank you,
> Robert
> thank you,
> Robert
> 
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address
> 



More information about the antlr-interest mailing list