What is $$ in bison?
Asked Answered
K

4

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?

Kremer answered 24/5, 2012 at 14:52 Comment(1)
+1 for me coming this page from the exact google search.Balefire
E
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.

Elwina answered 24/5, 2012 at 14:59 Comment(0)
S
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.

Strive answered 24/5, 2012 at 14:54 Comment(0)
X
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.

Xerosere answered 20/4, 2017 at 4:29 Comment(0)
F
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 !

Format answered 24/5, 2012 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.