parsingnewlinebisonerror-recovery

bison error recovery


I have found out that I can use 'error' in the grammar rule as a mechanism for error recovery. So if there was an error, the parser must discard the current line and resume parsing from the next line. An example from bison manual to achieve this could be something like this:

stmts:
      exp
      |stmts exp
      | error '\n'

But I cannot use that; because I had to make flex ignores '\n' in my scannar, so that an expression is not restricted to be expressed in one line. How can I make the parser -when encountering an error- continue parsing to the following line, given that there is no special character (i.e. semicolon) to indicate an end of expression and there is no 'newline' token?

Thanks..


Solution

  • Since you've eliminated the marker used by the example, you're going to have to pull a stunt to get the equivalent effect.

    I think you can use this:

    stmts:
          exp
        | stmts exp
        | error { eat_to_newline(); }
    

    Where eat_to_newline() is a function in the scanner (source file) that arranges to discard any saved tokens and read up to the next newline.

    extern void eat_to_newline(void);
    
    void eat_to_newline(void)
    {
        int c;
        while ((c = getchar()) != EOF && c != '\n')
            ;
    }
    

    It probably needs to be a little more complex than that, but not a lot more complex than that. You might need to use yyerrok; (and, as the comment reminds me, yyclearin; too) after calling eat_to_newline().