7

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?

Amumu
  • 17,924
  • 31
  • 84
  • 131

4 Answers4

10

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
6

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
4

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.

Sam Hobbs
  • 2,594
  • 3
  • 21
  • 32
1

$$ represents the result reference of the current expression's evaluation. In other word, its result.Therefore, there's no particular usage after its assignation.

Bye !

Maxime
  • 1,776
  • 1
  • 16
  • 29