loading external files flex bison - yyin?

2019-01-27 10:38发布

问题:

I am writing a basic language in flex + bison for my own personal research / to run simple scripts for fun.

It takes user input via the command line, parses it, and executes the desired result. I would like to add functionality load files.

for example, when the "load file 'somefile.src'" the file is loaded and automatically parsed, then the parser switches back to waiting for command line inputs.

I haven't been able to make sense of the documentation and am pretty lost. It doesn't help that I am new to flex, bison, and C as a whole.

I am following this pdf: http://epaperpress.com/lexandyacc/ (using the complex calculator as a skeleton and adding functionality on top of it) as well as looking through bison documentation http://www.gnu.org/software/bison/manual/bison.html.

Any advice would be appreciated.

回答1:

Input handling is done by flex, so you need to read the flex manual for details.

The section on multiple input buffers (linked above) has example code for handling "include"-like constructs. In fact, there are two sample implementations; one using the built-in buffer stack (recommended) and the other with an explicit buffer stack.

Really, it is not very complicated. To start reading a new file, all you need to do is this:

yyin = fopen(filename, "r");
if ( !yyin ) /* Handle the error */
yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE ));

You pop the buffer state in your EOF rule:

<<EOF>> { yypop_buffer_state();
          /* Make sure we stop if the EOF is the original input. */
          if (!YY_CURRENT_BUFFER) { yyterminate(); }
        }