SparkyNZ
SparkyNZ

Reputation: 6676

Bison Grammar %type and %token

Why is it that I have to use $<nVal>4 explicitly in the below grammar snippet?

I thought the %type <nVal> expr line would remove the need so that I can simply put $4?

Is it not possible to use a different definition for expr so that I can?

%union
{
  int   nVal;
  char *pszVal;
}

%token <nVal>   tkNUMBER
%token <pszVal> tkIDENT
%type  <nVal>   expr

%%

for_statement : tkFOR 
                tkIDENT   { printf( "I:%s\n", $2 );  }
                tkEQUALS 
                expr      { printf( "A:%d\n", $<nVal>4 );    }  // Why not just $4?
                tkTO 
                expr      { printf( "B:%d\n", $<nVal>6 );    }  // Why not just $6?
                step-statement 
                list 
                next-statement;

expr : tkNUMBER { $$ = $1; }
;

Update following rici's answer. This now works a treat:

for_statement : tkFOR 
                tkIDENT   { printf( "I:%s\n", $2 );  }
                tkEQUALS 
                expr      { printf( "A:%d\n", $5 /* $<nVal>5 */ );    }
                tkTO 
                expr      { printf( "A:%d\n", $8 /* $<nVal>8 */ );    }
                step-statement 
                list 
                next-statement;

Upvotes: 1

Views: 4530

Answers (1)

rici
rici

Reputation: 241931

Why is it that I have to use $<nVal>4 explicitly in the below grammar snippet?

Actually, you should use $5 if you want to refer to the expr. $4 is the tkEQUALS, which has no declared type, so any use must be explicitly typed. $3 is the previous midrule action, which has no value since $$ is not assigned in that action.

By the same logic, the second expr is $8; $6 is the second midrule action, which also has no value (and no type).

See the Bison manual:

The mid-rule action itself counts as one of the components of the rule. This makes a difference when there is another action later in the same rule (and usually there is another at the end): you have to count the actions along with the symbols when working out which number n to use in $n.

Upvotes: 4

Related Questions