loading external files flex bison - yyin?

老子叫甜甜 提交于 2019-12-29 08:23:15

问题


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(); }
        }


来源:https://stackoverflow.com/questions/31839746/loading-external-files-flex-bison-yyin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!