Question

I explore Bison's syntax and there is a question about some construction like

       bodystmt:
       {
           $<num>$ = parser->line;
       }

I know about $$ and $1 and that num is a type.. but this is something new for me

Was it helpful?

Solution

That's an explicit type tag that overrides the declared type for that value. So if you have:

%union {
    int  num;
    char *str;
}

%type<str> bodystmt

%%

bodystmt: { $<num>$ = ... }

it sets the num field in the union instead of the str field as declared by the %type delcaration in the header. Of course, other uses of the value (eg, as $1 in some other rule that uses bodystmt on the rhs) will access the str field, so they'd need be changed to be $<num>1 instead to avoid undefined behavior.

Where this is useful is when you have embedded actions that have different types:

%type<num> foo baz
%%
rule: { $<num>$ = 5; } foo { $<str>$ = "bar" } baz {
                     x = $<num>1;  /* gets the 5 stored in the first action */
                     y = $2;       /* the result of rule 'foo' */
                     z = $<str>3;  /* the string '"bar"' */
                     printf("%d %d\n", $2, $4); }

foo: A B { $$ = $<num>0; /* gets the value stored by the action just before the 'foo' in the rule that triggers this rule }

baz: { $<num>$ = strlen($<str>0); } foo  /* the <num> here is redundant and has no effect */

So the above code (besides doing a bunch of useless stuff for illustration) will, if it gets the input ABAB, print 5 3

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top