[英]How to skip parts of bison if yyparse fails
所以基本上,在我的野牛文件中,如果 yyparse 失敗(即存在語法錯誤),我想打印“錯誤”語句,而不是打印我在 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;
}
}
不幸的是,時間旅行不是一種選擇。 在檢測到錯誤時,printf 調用已經發生。 你不能讓它們不發生。
您可以這樣做(如果您正在編寫編譯器而不是計算器,則必須這樣做)是創建一些表示已解析程序的數據結構,而不是嘗試立即執行它。 該數據結構——可以是抽象語法樹(AST)或三地址指令列表,或其他任何東西,將用於生成編譯程序。 只有在運行編譯的程序時才會評估語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.