1

I'm writing an interpreter for a simple DSL and wondering how to implement if-then-else evaluator elegantly. I found one example online from antlr.org but it actually used getNodeIndex() from CommonTreeNodeStream, which is protected, so no use. The best I could do was the following:

ifblock
@init
{
  int t = 0;
  int f = 0;
}
@after
{
  if(c)
    stream.push(t);
  else
    stream.push(f);
  statements(); // handle the statements in then or else branch
  stream.pop()
}
  : ^(IF c=condition {t = input.mark();}. {f = input.mark();}.)
;

This is working, but I am not really satisfied somehow. Is there a better way?

ntrolls
  • 25
  • 4

1 Answers1

1

I would separate the logic from your tree grammar and create custom node-classes that are responsible for evaluating the input. If you keep it all inside the grammar, it will soon become a big pile of spaghetti, which is hard to maintain, IMO. Especially when you extend the language.

For an example of how to do this, see thie previous Q&A: if then else conditional evaluation

Some more related links:

Community
  • 1
  • 1
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • Thanks. I actually wrote my own evaluator using visitor pattern to begin with, but decided to have a go with tree grammar, just to see if it is possible really. I can see the pros and cons more clearly now. A lot of "how to do X properly" is convention rather than hard rules, and I definitely needed to learn that with Antlr :) – ntrolls Dec 14 '11 at 14:42