Search code examples
c++bisonbisonc++

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?


Solution

  • 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); }