shengyushen
shengyushen

Reputation: 289

how to elegantly handle rule with multiple components in bison

I use to program in ocaml and use ocalmyacc to generate parser. One very useful feather of ocaml is its variant type like this:

type exp = Number of int
| Addexp of exp*exp

with such a type, I can construct an AST data structure very elegantly in the parser to represent an exp like this:

exp :
number {Number($1)}
| exp1 + exp2 {Addexp($1,$3)}

So if there exist similar mechanism in C++ and bison?

Upvotes: 0

Views: 199

Answers (1)

Leandro T. C. Melo
Leandro T. C. Melo

Reputation: 4032

Yes, just match against exp + exp. Notice that for a given rule all its actions must have the same declared %type assigned to $$. In your case it would look something like this:

exp: number      { $$ = PrimaryExp($1); }
|    exp '+' exp { $$ = AddExp($1, $2); }

Upvotes: 1

Related Questions