ntrolls
ntrolls

Reputation: 25

Generating if-then-else evaluator with Antlr V3 tree parser

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?

Upvotes: 1

Views: 2085

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170158

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:

Upvotes: 1

Related Questions