yacc actions
With each grammar rule, you can specify actions to be performed each time the parser recognizes the rule in the input stream. An action is a C language statement that does input and output, calls subprograms, and alters external vectors and variables.
Actions return values and obtain the values returned by previous actions. The lexical analyzer can also return values for tokens.
A : '('B')'
{
hello(1, "abc" );
}
XXX : YYY ZZZ
{
printf("a message\n");
flag = 25;
}
Passing Values between Actions
A : B C D ;
then $1 has the value returned by the rule that recognized B, $2 has the value returned by the rule that recognized C, and $3 the value returned by the rule that recognized D.
{ $$ = 1;}
A : B ;
The following additional yacc parameter keywords beginning with a $ (dollar sign) allow for type-checking:
- $<Tag>$
- $<Tag>Number
$<Tag>Number imposes on the reference the type of the union member referenced by <Tag>. This adds .tag to the reference so that the union member identified by Tag is accessed. This construct is equivalent to specifying $$.Tag or $1.Tag. You can use this construct when you use actions in the middle of rules where the return type cannot be specified through a %type declaration. If a %type has been declared for a nonterminal name, do not use the <Tag> construct; the union reference will be done automatically.
Putting actions in the middle of rules
A : B
{
$$ =1;
}
C
{
x = $2;
y = $3;
}
;
$ACT : /* empty */
{
$$ = 1;
}
;
A : B $ACT C
{
x = $2;
y = $3;
}
;
where $ACT is an empty action.