【发布时间】:2021-04-12 19:56:57
【问题描述】:
所以基本上,在我的野牛文件中,如果 yyparse 失败(即存在语法错误),我想打印 'ERROR' 语句,而不是打印我在 fac stmt 部分的野牛文件上述部分中所做的任何其他事情。如果 yyparse 返回 1 有没有办法跳过野牛文件中间部分的内容?比如 idk 可能在 stmt 部分上面写 if 语句等?我将不胜感激任何帮助!提前致谢。
如:
%{
#include "header.h"
#include <stdio.h>
void yyerror (const char *s)
{}
extern int line;
%}
%token ...///
%// some tokens types etc...
%union
{
St class;
int value;
char* str;
int line_num;
float float_value;
}
%start prog
%%
prog: '[' stmtlst ']'
;
stmtlst: stmtlst stmt |
;
stmt: setStmt | if | print | unaryOperation | expr
{
if ($1.type==flt && $1.line_num!=0) {
printf("Result of expression on %d is (",$1.line_num);
printf( "%0.1f)\n", $1.float_value);
$$.type=flt;
}
else if ($1.type==integer && $1.line_num!=0){
$$.type=integer;
printf("Result of expression on %d is (%d)\n",$1.line_num,$1.value);
}
else if ($1.type==string && $1.line_num!=0) {
$$.type=string;
printf("Result of expression on %d is (%s)\n",$1.line_num,$1.str);
}
else if ($1.type==mismatch && $1.line_num!=0)
{
$$.type=mismatch;
printf("Type mismatch on %d \n",$1.line_num);
}
else{ }
}
%%
int main ()
{
if (yyparse()) {
// if parse error happens only print this printf and not above stmt part
printf("ERROR\n");
return 1;
}
else {
// successful parsing
return 0;
}
}
【问题讨论】:
-
您是否阅读过有关错误恢复的文档 (gnu.org/software/bison/manual/html_node/…)
-
@SornelHaetir 好吧,我不想在这里恢复错误,我想跳过除 yyparse 部分中的其他 printf 语句