I'm building a parser for an asset xchange format. And I'm including the %token-table directive in the bison file but, from the flex code I just can't access the table or the constants associated with it. That is when trying to compile this code:
Frame|FrameTransformMatrix|Mesh|MeshNormals|MeshMaterialList|Material {
printf("A keyword: %s\n", yytext);
yylval.charptr_type = yytext;
int i;
for (i = 0; i < YYNTOKENS; i++)
{
if (yytname[i] != 0
&& yytname[i][0] == '"'
&& !strncmp(yytname[i] + 1, yytext, strlen(yytext))
&& yytname[i][strlen(yytext) + 1] == '"'
&& yytname[i][strlen(yytext) + 2] == 0)
return i;
}
}
gcc says both YYNTOKENS and yytname are undeclared. So was the token table finally deprecated and wiped or what's the deal?
The Bison 2.6.2 manual says (on p82 in the PDF):
It looks like it is supposed to be there.
When I tried a trivial grammar, the table was present:
Notes: the table is static; if you are trying to access it from outside the file, that will not work.
There is an earlier stanza in the source:
This ensures that the token table is defined.
The easiest way to avoid the static symbol problem is to
#include
the lexer directly in the third section of the bison input file:Then you just compile the .tab.c file, and that's all you need.
There's a quick and easy way around the 'static' issue. I was trying to print a human readable abstract syntax tree with string representations of each non-terminal for my C to 6502 compiler. Here's what I did...
In your .y file in the last section, create a non-static variable called token_table
Now, in the main method that calls yyparse, assign yytname to token_table
Now, you can access token_table in any compilation unit simply by declaring it as an extern, as in:
For each node in your AST, if you assign it the yytokentype value found in y.tab.h, you simply subtract 258 and add 3 to index into token_table (yytname). You have to subtract 258 b/c that is where yytokentype starts enumerating at and you have to add 3 b/c yytname adds the three reserved symbols ("$end", "error", and "$undefined") at the start of the table.
For instance, my generated bison file has:
And, the defines header (run bison with the --defines=y.tab.h option):