TejGop TejGop - 3 months ago 24
C Question

How to parse a C string with Bison

I have a string in a C file like this:

char *test = "print x";


I want to parse that with a Bison parser I've written. Is it possible?

Answer

Bison parsers don't read input at all. They simply obtains a series of tokens by repeatedly calling yylex. (Or, with modern bison, you can create a "push parser" which is given tokens in successive calls.) So whatever implements yylex is responsible for the input.

If you use flex to create a lexical scanner, you can use yy_scan_string (or yy_scan_bytes if you know how long the string is) to scan a string instead of scanning from a file. See the Flex manual for details on these functions.

For a simple example, you could put the following two functions at the end of your flex definition file, after the second %%:

void set_input_string(const char* in) {
  yy_scan_string(in);
}

void end_lexical_scan(void) {
  yy_free_buffer(YY_CURRENT_BUFFER);
}

And put this at the end of your bison definition file, again after the second %%:

/* Declarations */
void set_input_string(const char* in);
void end_lexical_scan(void);

/* This function parses a string */
int parse_string(const char* in) {
  set_input_string(in);
  int rv = yyparse();
  end_lexical_scan();
  return rv;
}

Then you can declare and use parse_string to parse a string.