0

I'm using ANTLR 3.5. I would like to build a grammar that evaluates boolean expressions like

x=true;
b=false;
c=true;
a=x&&b||c;

and get back the evaluation result via a Java call (like ExprParser.eval() of the above entry will return true.)

I'll look forward for an example.

Iarek
  • 1,220
  • 15
  • 40
florins
  • 1,605
  • 1
  • 17
  • 33
  • http://www.antlr.org/wiki/display/ANTLR3/Expression+evaluator have a look at this sample. It prints results to console instead of returning them, and uses different operators, but the idea is roughly the same. – Iarek May 30 '13 at 15:06
  • @Iaroslav Thank you for your answer. I have followed this example, but I still don't get how to retrieve the result of the evaluation from the Java call. Basically, from the example, I would like that the call `parser.prog();` to return the evaluation of the expression meaning `int result=parser.prog();` – florins Jun 04 '13 at 12:24
  • prog() refers to a list of expressions, some of them can return value. Do you want to get only the last one or all the results? – Iarek Jun 04 '13 at 13:03

1 Answers1

1

You can do something like below (using the context of the grammar that I linked to in the comments to the question):

First of all, declare a member to store the latest evaluation result:

@members {
    private int __value;
}

Then, set it whenever you compute something

stat:   expr NEWLINE { __value = $expr.value; } | // rest of the stat entry

And, finally, return it when all the stats are computed:

// will return 0 if no expr blocks were evaluated
public prog returns [int value]:   stat+ {$value = __value;};

In C#, I used slightly different approach — I added an event to the parser and raised it when an expression result could computed. A client can subscribe to this event and receive all the computation results.

@members
{ 
    public event Action<int> Computed;
}

stat:   expr NEWLINE  { Computed($expr.value); }
Iarek
  • 1,220
  • 15
  • 40