-1

I wonder what is the language used in the curly braces of the rule section in yacc/bison files like the following and if there is any good reference about it.

stmts : stmt { $$ = new NBlock(); $$->statements.push_back($<stmt>1); }
  | stmts stmt { $1->statements.push_back($<stmt>2); }
  ;

and in the above code, for example, why it is written $<stmt>$2 not just $2

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rational Rose
  • 73
  • 1
  • 10

1 Answers1

1

It's actually C code with a custom macro preprocessor.

yacc/bison replaces all occurence of $$ with C code that refers to the semantic value of the rule's target component, and $n with the semantic value of rule element #n.

The code is actually C (and by extension, C++), and $$ and $n get replaced by bison itself, with C code that refers to the rule target's, or rule element's semantic value.

See this chapter of bison's documentation for more information.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • I will read the reference. Could you please answer the second part ? I did not see any difference between { $1->statements.push_back($2); } and { $1->statements.push_back($2); } . In many codes I have seen , they use them differently. – Rational Rose Jan 10 '17 at 02:24
  • 1
    This is fully explained in Bison's documentation, in the link that I provided. Copy-pasting contents of other web sites into stackoverflow.com does not accomplish anything useful. – Sam Varshavchik Jan 10 '17 at 04:02
  • I'm not sure that "custom macro-processor" is the best possible description of the process. Bison uses `m4` as a macro processor (or perhaps it would be better to say templating language). `m4` is a more-or-less standard macro language. The substitution of `$` and `@` tokens into the appropriate macros is done during the lexical scan of the code, see the function `handle_action_dollar` in `scan-code.l`. I suppose you could call that a macro-substitution, but it seems to me more like a transpilacion, fwiw. Anyway, upvoted. – rici Jan 10 '17 at 16:46