Tanya
Tanya

Reputation: 21

yacc showing syntax error at the wrong position

this is just an example

YACC grammar:

abc:ABC STRING NEWLINE

end:END

.

.

lex file:

int lineno=1;

.

.

string [a-zA-Z]+

%%

ABC   {return ABC;}

END   {return END;}

[\n]  {lineno++;return NEWLINE;}

{string} {return STRING;}

%%

and at every occurence of NEWLINE lineno is being incremented if input file is:

ABC xyz

END

yacc parses this successfully

if input file is:

ABC 123

END

it shows line1:syntax error

which was as expected

but if input file is:

ABC

END

then it shows line2:syntax error

however the error is in line 1 not in line 2.

what can be done so that correct line no is shown?

Upvotes: 1

Views: 1520

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

Because the parser doesn't find the error until it receives the NEWLINE token from the lexer, and by then you have already increased the line number.

This is actually not an uncommon problem, showing errors on the wrong line. One good example if is you forget to put a semicolon (;) at the end of a statement in a C source file. The error will most likely be on the next line.

Edit: Error recovery handling in Yacc.

Yacc have a special terminal symbol error which can be used for error recovery. In your case it may be used like this:

abc:ABC STRING NEWLINE
   |error NEWLINE
   ;

You can add a block of code between the error and NEWLINE symbols to print an error message, but it might not work anyway as the parser doesn't know there is an error until it has seen the NEWLINE symbol anyway.

Upvotes: 3

David Gorsline
David Gorsline

Reputation: 5018

You can conservatively word your syntax error message to say something like "syntax error near line number %d".

Upvotes: 0

Related Questions