1

Possible Duplicate:
How to make YY_INPUT point to a string rather than stdin in Lex & Yacc (Solaris)

i want to parse from a string rather than a file. i know that v can use yy_scan_string fn to do it.but for me it's not working properly so pls help me

Community
  • 1
  • 1
ajai
  • 363
  • 3
  • 6
  • 14
  • 1
    Post some code that illustrates your problem. –  Dec 15 '09 at 17:54
  • YY_BUFFER_STATE my_string_buffer = yy_scan_string(my_string); yyparse(); yy_delete_buffer(my_string_buffer ); the parser errors out with a syntax error at the first token. I have verified that the grammar and the content of 'my_string' works using yyrestart(yyin) and also with yy_create_buffer() through a file. – ajai Dec 15 '09 at 18:26
  • See also: http://stackoverflow.com/q/1907847/15168. – Jonathan Leffler Sep 23 '12 at 17:25

1 Answers1

5

I fought through this problem myself very recently. The flex documentation on the subject leaves a bit to be desired.

I see two things right off the bat that might be tripping you up. First, note that your string needs to be double NULL terminated. That is, you need to take a regular, NULL terminated string and add ANOTHER NULL terminator at the end of it. That fact is buried in the flex documentation, and it took me a while to find as well.

Second, you've left off a call to "yy_switch_to_buffer". This is also not particularly clear from the documentation. If you change your code to something like this, it should work.

// add the second NULL terminator
int len = strlen(my_string);
char *temp = new char[ len + 2 ];
strcpy( temp, my_string );
temp[ len + 1 ] = 0; // The first NULL terminator is added by strcpy

YY_BUFFER_STATE my_string_buffer = yy_scan_string(temp); 
yy_switch_to_buffer( my_string_buffer ); // switch flex to the buffer we just created
yyparse(); 
yy_delete_buffer(my_string_buffer );
Russell Newquist
  • 2,656
  • 2
  • 16
  • 18