Search code examples
yaccbisonlexical-analysis

How to use yylval with strings in yacc


I want to pass the actual string of a token. If I have a token called ID, then I want my yacc file to actually know what ID is called. I thing I have to pass a string using yylval to the yacc file from the flex file. How do I do that?


Solution

  • See the Flex manual section on Interfacing with YACC.

    15 Interfacing with Yacc

    One of the main uses of flex is as a companion to the yacc parser-generator. yacc parsers expect to call a routine named yylex() to find the next input token. The routine is supposed to return the type of the next token as well as putting any associated value in the global yylval. To use flex with yacc, one specifies the `-d' option to yacc to instruct it to generate the file y.tab.h containing definitions of all the %tokens appearing in the yacc input. This file is then included in the flex scanner. For example, if one of the tokens is TOK_NUMBER, part of the scanner might look like:

         %{
         #include "y.tab.h"
         %}
    
         %%
    
         [0-9]+        yylval = atoi( yytext ); return TOK_NUMBER;