Search code examples
bisonflex-lexerparse-tree

How to reset a parse tree


I created simple grammar for addition and substraction:

S : EXPRESSION ENDLINE      {printf("Result: %d\n",$1);}    
  ;

EXPRESSION  
    : NUMBER '+' NUMBER     {$$ = $1 + $3;}           
    | NUMBER '-' NUMBER         {$$ = $1 - $3;}      
    ;

NUMBER : NUM            {$$ = $1;}
       ;

%%

After reaching S terminal I would like to write new input after first result is printed. Unfortunately I received a syntax error after inserting a second formula. How can I achieve this? I would be grateful for help.


Solution

  • It's not about resetting the parse tree; you need to expand the grammar to permit any number of lines containing expressions. Just expand the rule S to include recursive invocations, like this:

    S : EXPRESSION ENDLINE      {printf("Result: %d\n",$1);}  
      | S EXPRESSION ENDLINE     {printf("Result: %d\n",$2);}
      ;
    

    That might be a bit tacky, so you could add a new rule to the same effect:

    S: RESULT
     | S RESULT
     ;
    
    RESULT : EXPRESSION ENDLINE      {printf("Result: %d\n",$1);}