String input to flex lexer

前端 未结 8 573
梦如初夏
梦如初夏 2020-11-29 04:42

I want to create a read-eval-print loop using flex/bison parser. Trouble is, the flex generated lexer wants input of type FILE* and i would like it to be char*. Is there an

8条回答
  •  暖寄归人
    2020-11-29 04:45

    flex can parse char * using any one of three functions: yy_scan_string(), yy_scan_buffer(), and yy_scan_bytes() (see the documentation). Here's an example of the first:

    typedef struct yy_buffer_state * YY_BUFFER_STATE;
    extern int yyparse();
    extern YY_BUFFER_STATE yy_scan_string(char * str);
    extern void yy_delete_buffer(YY_BUFFER_STATE buffer);
    
    int main(){
        char string[] = "String to be parsed.";
        YY_BUFFER_STATE buffer = yy_scan_string(string);
        yyparse();
        yy_delete_buffer(buffer);
        return 0;
    }
    

    The equivalent statements for yy_scan_buffer() (which requires a doubly null-terminated string):

    char string[] = "String to be parsed.\0";
    YY_BUFFER_STATE buffer = yy_scan_buffer(string, sizeof(string));
    

    My answer reiterates some of the information provided by @dfa and @jlholland, but neither of their answers' code seemed to be working for me.

提交回复
热议问题