In the bison manual in section 2.1.2 Grammar Rules for rpcalc, it is written that:
In each action, the pseudo-variable $$ stands for the semantic value for the grouping that the rule is going to construct. Assigning a value to $$ is the main job of most actions
Does that mean $$
is used for holding the result from a rule? like:
exp exp '+' { $$ = $1 + $2; }
And what's the typical usage of $$
after begin assigned to?
The conversion value for 1 USD to 42.528 BISON.
Bison is a general-purpose parser generator that converts an annotated context-free grammar into a deterministic LR or generalized LR (GLR) parser employing LALR (1) parser tables. As an experimental feature, Bison can also generate IELR (1) or canonical LR(1) parser tables.
Here nonterminal is the name of a nonterminal symbol, and type is the name given in the %union to the alternative that you want (see The Union Declaration). You can give any number of nonterminal symbols in the same %type declaration, if they have the same value type.
Yes, $$
is used to hold the result of the rule. After being assigned to, it typically becomes a $x
in some higher-level (or lower precedence) rule.
Consider (for example) input like 2 * 3 + 4
. Assuming you follow the normal precedence rules, you'd have an action something like: { $$ = $1 * $3; }
. In this case, that would be used for the 2 * 3
part and, obviously enough, assign 6
to $$
. Then you'd have your { $$ = $1 + $3; }
to handle the addition. For this action, $1
would be given the value 6
that you assigned to $$
in the multiplication rule.
Does that mean
$$
is used for holding the result from a rule? like:
Yes.
And what's the typical usage of
$$
after begin assigned to?
Typically you won’t need that value again. Bison uses it internally to propagate the value. In your example, $1
and $2
are the respective semantic values of the two exp
productions, that is, their values were set somewhere in the semantic rule for exp
by setting its $$
variable.
Try this. Create a YACC file with:
%token NUMBER
%%
exp: exp '+' NUMBER { $$ = $1 + $3; }
| exp '-' NUMBER { $$ = $1 - $3; }
| NUMBER { $$ = $1; }
;
Then process it using Bison or YACC. I am using Bison but I assume YACC is the same. Then just find the "#line" directives. Let us find the "#line 3" directive; it and the relevant code will look like:
#line 3 "DollarDollar.y"
{ (yyval) = (yyvsp[(1) - (3)]) + (yyvsp[(3) - (3)]); }
break;
And then we can quickly see that "$$" expands to "yyval". That other stuff, such as "yyvsp", is not so obvious but at least "yyval" is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With