[antlr-interest] Generating if/else/else-if statements from an AST

pragmaik contact at maik-schmidt.de
Mon Jan 16 06:40:09 PST 2012


Hi!

At the moment I am working on a DSL that supports if/else statements. They
are very similar to the if/else statements in C except that my statements
only allow blocks, that is

if (x == 1)
  print("Hello");

is not allowed and has to be

if (x == 1) {
  print("Hello");
}

I also want to support if/else/else-if statements such as

if (x == 1) {
  print("Hello");
} else if (x == 2) {
  print("world");
}

So, in the AST I store if statements as follows:

^('if' condition trueBlock elseBlock)

The elseBlock can be a regular block or an ELSIF block, that is an if
statetement that belongs to an else block.

I want to translate my DSL to C and I use the following tree grammar:

ifStatement
    :   ^(n='if' expression b1=block b2=(block|ifStatement)?)
	    -> if(
		       node={$n},
			   cond={$expression.st},
		  	   block1={$b1.st},
			   block2={$b2},
			   isElsif={($n.Parent.Text == "ELSIF") ? "true" : null}
			)
	|   ^(ELSIF i=ifStatement) -> { $i.st }
	;

The StringTemplate looks like this:

if(node, cond, block1, block2, isElsif) ::= <<
<if(isElsif)>else <endif>if (<cond>) <block1>
<if(block2)>else <block2><endif>
>>

Unfortunately, it does not work, that is the grammar emits only the
trueBlock elements and not a single else. No matter if it's a regular
else or and else-if.

Does anybody see what I am doing wrong?

Cheers,
Maik


--
View this message in context: http://antlr.1301665.n2.nabble.com/Generating-if-else-else-if-statements-from-an-AST-tp7192682p7192682.html
Sent from the ANTLR mailing list archive at Nabble.com.


More information about the antlr-interest mailing list