Search code examples
compiler-constructionbisonflex-lexeryaccbisonc++

Bison mid rule actions are not working


This is my parser.y

stmt : type var { insertVar($2); cout<< "inserted"<<endl;} LCURL other RCURL {
             //other jobs
     }
     ;

and lex.l

"{"  { cout<<"after insertion"<<endl; return LCURL;} 

when i run these with a .c file , the output is the following:

 after insertion
 inserted

where my expected output is:

 inserted
 after insertion

why is it happening?


Solution

  • Yacc/bison grammars use one lookahead token (the 1 in LALR(1)) to decide which parsing action to take. So the parser and the lexer are not in sync; the lexer action for the lookahead token will often be executed before the parser reduction which immediately precedes it.

    I wrote "often" and not "always" because Bison (but not yacc) sometimes delays reading the lookahead token if it doesn't actually need to refer to it at that point in the parse. It is hard to predict when this optimisation might take place. The best rule is to avoid relying on the sequence of action execution between the parser and the lexer.