Aserre Aserre - 3 months ago 17
C Question

Execute an action for all component of a rule in bison

I have the following rule in my bison file :

affectation: VAR '=' expr ';'
| VAR PLUSEQ expr ';'
| VAR MINUSEQ expr ';'
;


I would like the parser to display the variable name and its content every time an affectation is done. For that, I use the action
{printf("%s:%s\n",$1, $3);}
. However, as there are 3 forms of affectation, is there a way to apply this action to all the components without writting :

affectation: VAR '=' expr ';'
{printf("%s:%s\n",$1, $3);}
| VAR PLUSEQ expr ';'
{printf("%s:%s\n",$1, $3);}
| VAR MINUSEQ expr ';'
{printf("%s:%s\n",$1, $3);}
;

Answer

Basically, the answer is no. In most use cases, the three productions would have different semantics, so it would be normal for their to be three different actions, although they might share code. (As always, refactoring the shared code can reduce the need for duplication.)

If the three rules were really semantically identical, you could collect the different operators into a prefix rule:

aff_pfx: VAR '=' | VAR PLUSEQ | VAR MINUSEQ
affectation: aff_pfx expr ';' { handle($1, $2); }

That relies on the default action copying $$ = $1 in all the productions for aff_pfx, so it is not fully general. Also, it completely erases any distinction between the three syntaxes, which seems unlikely to be correct.

If you are just trying to produce a trace of the parse,take a look at bison's built-in debugging features.

Comments