user1538392
user1538392

Reputation: 91

How do I convince Bison to parse part of a file?

If a have a input file of the form:

BEGIN
  stuff....
END

BEGIN
  stuff ...
END

and my .y file is of the form

%token BEGIN
%token END
%start begin

begin:  BEGIN stuff END

and what I want to do is call yyparse repeatedly, parsing a single BEGIN/END, until eof.

The first call to yyparse reports:

syntax error, unexpected BEGIN, expecting $end.

which makes sense; bison wants to parse the entire file. Is there a way to have bison be more flexible in it's defintion of $end?

Upvotes: 2

Views: 1391

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126243

The easiest way is to add a (pair of) productions to the top of the .y file:

input: begin | input begin;

Now yyparse will parse multiple inputs. If your REALLY want to have to call yyparse multiple times, you could instead probably get away with:

begin: BEGIN stuff END { YYACCEPT; } ;

YYACCEPT is a special builtin that causes yyparse to return immediately with 0 (after doing any needed internal cleanup). I say "probably" as this will only work if bison reduces begin with a default reduction (no lookahead). That will be the case if this is the only rule for begin and begin is not used in a context where recognizing it requires lookahead.

Upvotes: 4

David Gorsline
David Gorsline

Reputation: 5018

Add this to your grammar:

all_begins: begins
          ;

begins: begins begin
      | begin
      ;

Replace the %start with:

%start all_begins

And just call yyparse() once.

Upvotes: 1

Related Questions