简体   繁体   English

如何防止 Bison 中的默认“语法错误”

[英]How to prevent default "syntax error" in Bison

As described in the header, I am using Bison and Flex to get a parser, yet I need to handle the error and continue after I find one.如标题中所述,我使用 Bison 和 Flex 来获取解析器,但我需要处理错误并在找到错误后继续。 Thus I use:因此我使用:

Stmt:   Reference '=' Expr ';'                                { printf(" Reference = Expr ;\n");}
|       '{' Stmts '}'                                         { printf("{ Stmts }");}
|       WHILE '(' Bool ')' '{' Stmts '}'                      { printf(" WHILE ( Bool ) { Stmts } ");}
|       FOR NAME '=' Expr TO Expr BY Expr '{' Stmts '}'       { printf(" FOR NAME = Expr TO Expr BY Expr { Stmts } ");}
|       IF '(' Bool ')' THEN Stmt                             { printf(" IF ( Bool ) THEN Stmt ");}
|       IF '(' Bool ')' THEN Stmt ELSE Stmt                   { printf(" IF ( Bool ) THEN Stmt ELSE Stmt ");}
|       READ Reference ';'                                    { printf(" READ Reference ;");}
|       WRITE Expr ';'                                        { printf(" WRITE Expr ;");}
|       error ';'                                             { yyerror("Statement is not valid"); yyclearin; yyerrok;}
;

however, I always get a msg "syntax error" and I do not know where does it come from and how to prevent it so that my own "error code" will be executed.但是,我总是收到一个味精“语法错误”,我不知道它来自哪里以及如何防止它以便执行我自己的“错误代码”。 I am trying to do an error recovery here so that my parser will continue to parse the input till the EOF.我试图在这里进行错误恢复,以便我的解析器将继续解析输入直到 EOF。

People often confuse the purpose of error rules in yacc/bison -- they are for error RECOVERY, not for error HANDLING.人们经常混淆 yacc/bison 中error规则的目的——它们用于错误恢复,而不是用于错误处理。 So an error rule is not called in response to an error -- the error happens and then the error rule is used to recover.因此,不会调用错误规则来响应错误——错误发生,然后错误规则用于恢复。

If you want to handle the error yourself (so avoid printing a "syntax error" message), you need to define your own yyerror function (that is the error handler) that does something with "syntax error" string other than printing it.如果您想自己处理错误(因此避免打印“语法错误”消息),则需要定义自己的yyerror函数(即错误处理程序),该函数对“语法错误”字符串执行某些操作而不是打印它。 One option is to do nothing, and then print a message in your error recovery rule (eg, where you call yyerror, change it to printf instead).一种选择是什么都不做,然后在您的错误恢复规则中打印一条消息(例如,在您调用 yyerror 的地方,将其改为 printf)。 The problem being that if error recovery fails, you won't get any message (you will get a failure return from yyparse, so could print a message there).问题是,如果错误恢复失败,您将不会收到任何消息(您将从 yyparse 获得失败返回,因此可以在那里打印一条消息)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM