我使用 yy_scan_string 和 yyparse() 来解析一些文本。我想在出现语法错误时继续解析下一个字符串,但它不起作用。
yacc 文件片段:
set:SET PARENTHESIS reference EQUAL expression CLOSE_PARENTHESIS {$$ = set_directive($3,$5); }
|error { printf("set error abourt!");YYACCEPT;}//when appears error,I want to continue parsing the next string.I hava used YYABORT,but it not work as I want
;
...
int main(){
yy_scan_string("#set($b ==9)"); //this string has syntax error.
yyparse();
yylex_destroy();
printf("=====================11111========================\n");
traverse(snode); //print the ast
free_tree(snode); // release the memory
yy_scan_string("#if($r==5) wewqewqe #end"); //this string is right,I want to continue to parse this after paser the string on it: "#set($b ==9)"
yyparse();
yylex_destroy();
printf("=====================222222========================\n");
traverse(snode);
free_tree(snode);
return 1;
}
int yywrap(){
return 1;
}
int yyerror(char* s){
printf("=====================error %s========================\n",s);
//reset_input();
//yyclearin;
return 0;
}
我该怎么办,请帮帮我!
最佳答案
在错误恢复中,您应该了解一些原则:
- 我们应该添加
error
标记作为减少(完成)的替代方案 - 我们应该告诉解析器错误是正常的,我们调用该
yyerrok
(未完成) 您还可以使用 yyclearin 丢弃当前 token
PS;执行时间顺序:在错误情况下,yyerror 被称为 yyerrstate 等于 1,之后 yyerrok 被调用,它将错误状态重新初始化为 0,之后您显然可以调用任何宏...
|error { yyerrok; yyclearin;printf("set error abourt!");} ;
关于bison - 语法错误后如何继续解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16911792/