2016-10-17 25 views
1

我正在測試使用bison flex編寫中綴計算器的示例。我發現除了方括號「()」之外,一切都是正確的。我發現當我用括號輸入一個計算時,計算結果是不正確的。下面是文件的「綴calc.y」如何實現具有優先級和關聯性的中綴計算器

/* bison grammar file for infix notation calculator */ 
%{ 
#define YYSTYPE double 
#include <math.h> 
#include <stdio.h> 


int yyerror(const char *s); 
int yylex(void); 


%} 

%token NUM 
%left '-' '+' 
%left '*' '/' 
%left NEG 
%right '^' 

%% /* Grammer rules and actions follow */ 

input: /* empty */ 
    | input line 
    ; 

line: '\n' 
    | exp '\n' { printf("\t%.10g\n", $1); } 
    ; 

exp: NUM { $$ = $1; } 
    | exp '+' exp { $$ = $1 + $3; } 
    | exp '-' exp { $$ = $1 - $3; } 
    | exp '*' exp { $$ = $1 * $3; } 
    | exp '/' exp { $$ = $1/$3; } 
    | '-' exp %prec NEG { $$ = -$2; } 
    | exp '^' exp { $$ = pow($1, $3); } 
    | '(' exp ')' { $$ = $2; } 
    ; 

%% 

/* Additional C code */ 

int main() { return yyparse(); } 

int yyerror(const char* s) 
{ 
    printf("%s\n", s); 
    return 0; 
} 

的代碼,這裏是文件的「綴calc.lex」代碼

/* lex file for infix notation calculator */ 
%option noyywrap 

%{ 
#define YYSTYPE double  /* type for bison's var: yylval */ 
#include <stdlib.h>  /* for atof(const char*) */ 
#include "infix-calc.tab.h" 
%} 


digits [0-9] 
rn  (0|[1-9]+{digits}*)\.?{digits}* 
op  [+*^/\-] 
ws  [ \t]+ 


%% 

{rn} yylval = atof(yytext); return NUM; 
{op} | 
\n  return *yytext; 
{ws} /* eats up white spaces */ 

%% 

的問題是,當我輸入,說「2 *(3 + 4)」,我應該收到輸出「14」。但輸入是「()10」。看來括號在這種情況下不起作用。代碼有什麼問題? 非常感謝你幫助我!

+0

yacc規則看起來不錯。也許lex?在每個規則中使用printf語句來打印哪些規則會觸發。 –

回答

0

看起來你必須聲明()作爲令牌才能工作。

添加最終%%之前,以下兩行的文件法:

"(" return LEFT; 
")" return RIGHT; 

然後加入

%token LEFT RIGHT 

到綴calc.y的頂部,並更換

| '(' exp ')' { $$ = $2; } 

| LEFT exp RIGHT { $$ = $2; } 
+0

謝謝!有用!!! – pfc

+0

只需要在單個字符標記的規則中添加括號,儘管普通樣式是爲任何無法識別的輸入發送單字符標記。 – rici

相關問題