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

问题描述 投票:0回答:1

如标题中所述,我正在使用Bison和Flex来获取解析器,但是我需要处理错误并在找到错误后继续。因此,我使用:

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;}
;

但是,我总是收到一个味精“语法错误”,我不知道它来自哪里以及如何防止它,以便执行我自己的“错误代码”。我正在尝试在此处进行错误恢复,以便我的解析器将继续解析输入,直到EOF。

error-handling compiler-construction bison flex-lexer yacc
1个回答
2
投票

人们经常在yacc / bison中混淆error规则的目的-它们是错误恢复,而不是错误处理。因此,不会因错误而调用错误规则-发生错误,然后使用错误规则进行恢复。

[如果您想自己处理错误(因此避免打印“语法错误”消息),则需要定义自己的yyerror函数(即错误处理程序),该函数使用“语法错误”字符串而不是打印它。一种选择是不执行任何操作,然后在错误恢复规则中打印一条消息(例如,在调用yyerror的地方,将其更改为printf)。问题是,如果错误恢复失败,您将不会收到任何消息(您将从yyparse获得失败返回,因此可以在其中打印消息)。

© www.soinside.com 2019 - 2024. All rights reserved.