0
votes

I have an H.W assignment in which I need to use Bison and flex.

I need to write a yyerror function in the Bison file that will write to the screen the line number in which there was problem (from the input file) and it needs to tell the token on which the Bison has stopped (from the stack it is building)

is there a simple way to do it?

I tried to use the yylineno from the lex file but got errors. every search option for a solution came empty handed :(

3

3 Answers

2
votes

OK, found a pratical answer. to get the

extern int yylineno;

in the first part of the Bison file

Edit- the same way can help with getting the token from the lex file, just write in the Bison file: extern NODEPTR yylval;

*yylval in my project is defined as NODEPTR, if you did not change it you should use int (the default declaration for it)

0
votes

You can get the line number by creating a variable to keep track of the line number and then increment that variable in your scanner (.l file).

To get the token information that you need I would just add an %option debug declaration with your regular expressions.

Examples of both can be seen in the sample sudo-code below.

%{

    //Create variable to keep track of line number
    int linenum = 0;

%}

/*
 *  Definitions of regular expressions
 *  Note: You capture newlines here...
 */

%%
 %option debug

 /*Token definitions*/
 NEWLINE      \n 

 ...

%%
{NEWLINE}   {   
              linenum++;
            }
...

int main(void) {
   ...
   return 0;

}
0
votes

Apart form using yylineno if you want to trap the error at specific production you may put error option to that production. E.g.

someproduction:
      option_one clause_1 
    | option_two clause_2
    | error { printf("Error in some production \n"); }
    ;

you may implement the error in option_one and option_two as well in order to trap specific error.