TejGop TejGop -4 years ago 206
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 Source

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) {

void end_lexical_scan(void) {

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) {
  int rv = yyparse();
  return rv;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download