Faraz Nomani
Faraz Nomani

Reputation: 41

How can I reference to same Rule being called more than once in ANTLR?

I have a grammar which is similar to the one below

E returns [String vals] : 
    E '+' E {$vals = $E.vals+$E.vals}|
    E '-' E {$vals = $E.vals+$E.vals}

I want to access two different 'E' values, but I am unable to do so. I want to differentiate between 3 'E' rules, one which is the base and other 2 which are being called.

I am creating a grammar which I will be using to evaluate certain expressions.

The operators '+' and '-' are some arbitraty operators.

Upvotes: 1

Views: 317

Answers (1)

sepp2k
sepp2k

Reputation: 370465

To refer to multiple uses of the same rule in actions, you can add labels to them like this:

e1=exp op=('+'|'-') e2=exp {
  // code that uses $e1 and $e2
}

Upvotes: 2

Related Questions