[antlr-interest] Looking for some simplifications in a tree grammar using StringTemplate output

Stefan Mätje (d) Stefan.Maetje at esd-electronics.com
Thu Oct 27 08:16:19 PDT 2011


Hi all,

I'm building a language to language translator with C++ as target language.  
I've built a
preliminary version of the language description and I try to produce some  
output using
StringTemplate. It works so far but I'm looking for some simplifications of my  
output
rules.

The first rule of interest is my "expr" rule that should build expressions. It  
looks like
this:

expr
     :(  ^(op=OP_EQ l=expr r=expr)
     |   ^(op=OP_NE l=expr r=expr)
     |   ^(OP_LT l=expr r=expr)
     |   ^(OP_GT l=expr r=expr)
     |   ^(OP_PLUS l=expr r=expr)
     |   ^(OP_MINUS l=expr r=expr)
     |   ^(OP_MUL l=expr r=expr)
     |   ^(OP_DIV l=expr r=expr)
     |   ^(OP_IDIV l=expr r=expr)
         )           -> dyadExpr(op={$$$$},left={$l.st},right={$r.st})
     |   ID          -> template(id={$ID.text}) "<id>"
     |   literal     -> dumpSt(stVal={$literal.st})
     ;

All the OP_* nodes could be handled by one template "dyadExpr" with the  
parameters "op",
"left" and "right". But I need a way to specify the needed operator. Putting  
"$op.type"
in the above rule at the point where "$$$$" is yield the lexer token number.  
Any ideas
how to connect the token number with the appropriate operator string? The maps  
in the
StringTemplate Group only support mapping strings to strings.


The second problem is that some rules simply need to deliver the output of  
another rule.
I solved this by introducing a helper template "dumpSt" that simply delivers  
the given
input. The helper template is defined in the *.stg file as follows:

// Simply dump the value of another string template call
dumpSt(stValue)    ::= "<stVal>"

An example of the rules that refer to this helper template is following:

/** Declarations allowed on MODULE level */
mod_dcl
     :   var_dcl    -> dumpSt(stVal={$var_dcl.st})
     |   func_dcl   -> dumpSt(stVal={$func_dcl.st})
     |   proc_dcl   -> dumpSt(stVal={$proc_dcl.st})
     ;

var_dcl:
     ^(VAR_DCL basicType (i+=ID)+)
     -> var_dcl(type={$basicType.st}, names={$i})
     ;

basicType
     :   'FIXED' -> dumpSt(stVal={"int16_t"})
     |   'FLOAT' -> dumpSt(stVal={"float"})
     ;

Could I get rid of the "dumpSt" template in "mod_dcl" rule and write that more  
directly.
In the "basicType" rule is it possible to get the "int16_t" down into the  
*.stg file?

Any hints appreciated. Thanks.

Best regards,
	Stefan Mätje


More information about the antlr-interest mailing list