添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

yyerror prints the "syntax error" in default case. I want to change the parameter of yyerror function. By this way I can print more informative error messages to user. For example in function decleration user did wrong thing. If I could change the parameter of yyerror function, I can print more meaningful messages to user.

func_Dec: error_code=1 .... var_dec: error_code=2 ....

according to error_code value. I can print the error message like this in yyerror function:

void yyerror(int x){
if(x==1){printf("error while function decleration");};
if(x==2){printf("error while variable decleration ");};

That will be very difficult/impossible.

When yacc encounters a token that is not in its look ahead set, it reduces until a state on the stack becomes visible in which the token is valid. Once it has reduced (popped) all states and the stack has become empty, it concludes it cannot match the token and reports Syntax error.

What you can do is maintain yourself some state information of what was going on and use that in yyerror.

You can write a yyerror function yourself. Normally, if no yyerror function is provided, yacc uses a default function from the library. But you are free to write one yourself, e.g.:

int yyerror(void) {
    if (gMyState== ERR_DECL) printf("Error in function declaration\n);
    else ...

If you are using Gnu Bison as your yacc implementation, you can request more informative error messages with

%define parse.error verbose

Normally, you will also want to request "LAC" (Lookahead Correction), which improves token prediction, although there is an efficiency cost:

%define parse.lac full

You could also use error productions to produce context-dependent error messages, but be aware that yyerror will already be invoked before the error action. So either you need to suppress printout in yyerror, or arrange for the yyerror output and the output from the error action to complement each other.

Finally, consider using (f)lex's location tracking mechanism so that you can at least add line numbers to your error messages.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.