Search code examples
compiler-constructionbisonlalrbisonc++

how to give action for every rule bison


I am trying to make a small compiler using flex and bison but i was not getting how to give action for every rule

my grammar is like:

     %union{
            std::string *s;
    };

%start program
%type <s> expr

%token <s> KEYWORD
%token <s> VARIABLE

%%

program : KEYWORD {std::cout << "A"; } 
| KEYWORD VARIABLE {std::cout << "B"; }

Variable regex is [a-zA-Z0-9]

"caps" is my keyword

if i give input as "caps lock" (caps =KEYWORD and lock =VARIABLE) i was getting output as "B"

if i give input as caps then it waits until i enter next word and after entering any next word it prints " Asyntax error" if the next input is caps.

Issue is it waits until next input is given to print A and it still prints A if an error is present with syntax error

I was not getting what is wrong with it can someone find the mistake in it.


Solution

  • Bison requires an "end of input" token to mark the end of the input and return a successful parse. Normally, you give it this token on reading EOF (this is what lex/flex will do). So if you enter an EOF (generally by hitting ctrlD or ctrlZ) after your input, it should work.