2013-02-28 90 views
1

我試圖實現一個計算器或表達式,如使用Flex和Bison的true nor true nor (false nor false),但我不斷收到我的錯誤消息。這裏是我的.L文件:Flex和野牛計算器

%{ 
#include <stdlib.h> 
#include "y.tab.h" 
%} 

%% 
("true"|"false") {return BOOLEAN;} 

.|\n {yyerror();} 

%% 

int main(void) 
{ 
    yyparse(); 
    return 0; 
} 

int yywrap(void) 
{ 
    return 0; 
} 
int yyerror(void) 
{ 
    printf("Error\n"); 
} 

這裏是我的.Y文件:

/* Bison declarations. */ 
%token BOOLEAN 
%left 'nor' 

%% /* The grammar follows. */ 
input: 
    /* empty */ 
| input line 
; 

line: 
    '\n' 
| exp '\n' { printf ("%s",$1); } 
; 

exp: 
    BOOLEAN   { $$ = $1;   } 
| exp 'nor' exp  { $$ = !($1 || $3); } 
| '(' exp ')'  { $$ = $2;   } 
; 
%% 

有誰看到這個問題?

回答

1

簡單的方法來處理所有的單字符標記,其作爲@vitaut正確地說,你是不是在處理所有的呢,是返回yytext[0]爲圓點規則,讓解析器理清哪些是合法的。

你也失去了值的布爾值「真」和「假」,應分別存入的yylval爲1和0,那麼將在$1,$3等轉起來。如果你將有更長期的更多數據類型,您需要查看%union指令。

1

你得到錯誤的原因是你的詞法分析器只識別一種類型的令牌,即BOOLEAN,但不包括換行符,括號或nor(並且你爲其他所有內容產生錯誤)。對於單個字母令牌像括號和換行符您可以返回字符本身作爲一個記號類型:

\n { return '\n'; } 

對於nor以爲像你這樣爲BOOLEAN您應該引入一個令牌類型,並添加適當的規則詞法分析器。