문제

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.

도움이 되었습니까?

해결책

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); }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top