tags:

views:

52

answers:

1

Is there a way in Bison to check the current token stack size?

I'd like to use $n with n as a negative number to access a semantic value of another rule but only if the stack is large enough.

Thank you.

A: 

Given a rule such as:

stmt:   ID '=' DIGIT
        { $$ = $3; }
    ;

The generated code fragment is:

{ (yyval) = (yyvsp[(3) - (3)]); }

The yyvsp 'array', therefore, is part of the answer. Further up the (regular - not the GLR) generated code, you find that yyvsp is actually a pointer, not an array. For example:

yyvsp = yyvs + yysize - 1;

It looks like yysize is the value you want; unfortunately, though, it is a variable local to a block which has terminated before the user actions are executed, so it is not directly available. However, you can also find code with:

yyvsp = yyvs;

Looking at the code, it seems that yyvs is a pointer to the base of the stack (which can be dynamically allocated), and yyvsp is a pointer part way up the stack. Those variables are both visible throughout the yyparse() function (and therefore, in particular, are visible within user actions. And the answer you need is:

int nrules = yyvsp - yyvs;

It isn't remotely clean to poke at the source code like this, but it does get you an answer.

If you use a GLR grammar, you would have to examine whether a Bison GLR grammar has the same variables with the same meanings; it may not.

Jonathan Leffler