I'm attempting to get the name of a token in C++ Bison:
E.g. %token <int> TPLUS "+" TMINUS "-" TMUL "*" TDIV "/"
However in the C++ variant of Bison, %token-table does not do anything.
I have noticed that there is a token mapping in the generated bison code: const char* const parser::yytname_[]; however it is private.
Does anyone have any idea of how to get the names of these tokens in C++ Bison? Is this even possible using the C++ variant?
I know this question was asked here, but there is no accepted answer.
Using version 3.4.3
First, ensure that you have a recent version of Bison (I believe the minimum is v3.6, but the v3.7 versions have several useful bug fixes).
That will generate a static member function named
symbol_namewith one of the following prototypes. Note that `token_symbol_kind is an internal token number, not the value produced by the scanner. (See below)If the option
parse.erroris not defined, then you can still get thesymbol_namedefinition by using the deprecated%token-tabledirective, or if you arrange for#define YYDEBUGto be inserted in the generated code (see the-dflag, for example). I have no idea why the return type differs depending on the definition ofparse.error.As noted, the argument to
symbol_nameis a bison internal token number, rather than the token type returned by the scanner. You can get the internal token number for a token type using theparsermember classby_kind, with an expression likeyy::parser::by_kind(yy::parser::token::«token-type-name»).type_get().