xeL dna ccaY 又是计算器

来源:互联网 发布:美女聊天软件 编辑:程序博客网 时间:2024/05/03 23:20

%{
#include "parser.h"
%}

%%

"+" {
 return PLUS;
}

"-" {
 return MINUS;
}

"/" {
 return DIV;
}

"*" {
 return MULT;
}

"(" {
 return L_PAR;
}

")" {
 return R_PAR;
}

[0-9]+ {
 yylval = atoi(yytext);

 return INTEGER;
}

"/n" {
 return NL;
}

. ;
%%

 

--------------------------------------------------------------------------------------------------------------------------------------------------- 

%{
int tempCount1 = -1;
int tempCount2 = -1;
int tempCount3 = -1;
int tempCount4 = -1;
int tempCount5 = -1;
int tempCount6 = -1;
int tempCount7 = -1;
%}
%token PLUS
%token MINUS
%token DIV
%token MULT
%token L_PAR
%token R_PAR
%token INTEGER
%token NL

%%

calc
 : calc expression NL { printf("%d/n", $2); }
 | expression NL { printf("%d/n", $1); }
 ;

expression
 : term { $$ = $1; }
 | expression PLUS term {tempCount6 = $1 + $3;  $$ = $1 + $3; }
 | expression MINUS term { tempCount7 = $1 - $3; $$ = $1 - $3; }
 ;

term
 : factor { $$ = $1; }
 | term MULT factor {tempCount4 = $1 * $3;   $$ = $1 * $3; }
 | term DIV factor { tempCount5 =$1 / $3; $$ = $1 / $3; }
 ;

factor
 : L_PAR expression R_PAR { tempCount1 = $2; $$ = $2; }
 | INTEGER { tempCount2 = $1; $$ = $1; }
 | MINUS factor { tempCount3 =  -$2; $$ = -$2; }

%%

int yyerror(char *str){
 printf("%s/n", str);
}

 

输入2*(4-1)

tempCount2 = 2

tempCount2 = 4

tempCount2 = 1

tempCount7 = 3

tempCount1 = 3

tempCount4 = 6

读进2→读进乘号→INTEGER(factor)匹配

factor(term)→读进左阔号→读进4→读进减

INTEGER(factor)匹配→factor(term)→term(expression)

读进1→读进右阔号→INTEGER(factor)匹配→factor(term)

L_PAR expression R_PAR匹配→term MULT factor匹配→term(expression)

 ----------------------------------

可以定义终结符和非终结符的类型,

%token PLUS
%token MINUS
%token DIV
%token MULT
%token L_PAR
%token R_PAR
%token <value> INTEGER
%token NL

%type <node> calc
%type <node> expression
%type <node> term
%type <node> factor

%union{
 int value;
 CNode *node;
};