10.5. Actions

After a production, you can write an action that is performed when the parser does a reduce by that production. Write it in C, surrounded by braces. For example,

expression : expression '+' expression
                 {printf("Reducing by production E -> E + E\n");
                 }

Getting token attributes in actions

Type YYSTYPE is a union type. Suppose that it is defined by

  typedef union
  {
    int         ival;
    const char* strval;
  } YYSTYPE;
You will want to tell which field of the union is used for each token. Lines
%token <ival>   TOK_NUMBER
%token <strval> TOK_IDENTIFIER
tell Bison that TOK_NUMBER uses field ival and TOK_IDENTIFIER uses field strval.

In an action, refer to a token by its position on the right-hand side of the production, numbering from 1. The attribute of the first thing is $1, of the second thing is $2, etc.

For example, in

expression : TOK_LET TOK_IDENTIFIER
             '=' expression TOK_IN
             expression TOK_END
                  {const char* id = $2;
		   printf("I see a let of %s\n", id);
                  }

the action shows the attribute of the TOK_IDENTIFIER token.

Notice that you don't explicitly write .strval. Bison adds that automatically.