I have implemented a parser and scanner using bison and flex. At first it read input from stdin and later I modified to read from a string. There are several posts on stackoverflow on this topic. Specifically, the at flex manual describing the use of multiple buffers and the use of in-memory string rather than a file as input helped.
So, I got the parser/lexer to work for a single string as in:
%{
//Bunch of includes, typedefs, etc..
extern char * yytext;
void yyerror(char *);
int yylex();
typedef struct yy_buffer_state * YY_BUFFER_STATE;
extern int yyparse();
extern int yylex_destroy(void);
extern YY_BUFFER_STATE yy_scan_string(char * str);
extern void yy_delete_buffer(YY_BUFFER_STATE buffer);
...
%%
int main(int argc, char **argv) {
char *string = "abcd\n\0";
YY_BUFFER_STATE buffer = yy_scan_buffer(string, sizeof(string));
yyparse();
}
This was the simple part. The grammar/lex rules are a bit lengthy to reproduce here. I want to implement a function that will be called repeatedly with a string param. Since the grammar/lex rules can take care of the output, I can handle it. Problem is to have a mechanism to implement a classic function to which is passed a string to parse and analyse. So, I tried this to test...
int main(int argc, char **argv) {
int i=10;
char *string;
string = malloc(16);
while (1) {
sprintf(string, "someString to be parsed...%d\n\0", i++);
YY_BUFFER_STATE buffer = yy_scan_buffer(string, sizeof(string));
yyparse();
yylex_destroy();
printf("%d\n", i);
}
}
It fails, after about 10000, with this error:
fatal flex scanner internal error--end of buffer missed
I am not looking at any multi-threaded environment. It will be a single-threaded process with strings coming from a socket to be parsed. As a string arrives, I call a function to parse it. I am unable to find any reference on implementing such functionality with Bison and Flex.
I tried different approaches but with no luck. Any simple approach to handle this?