Question

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.

Était-ce utile?

La solution

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); }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top