xeL dna ccaY 又是计算器

%{
#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;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的横打

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值