lex和yacc例子

cal.l

%{
#include <stdlib.h> /* for atoi call */
#define DEBUG /* for debuging: print tokens and their line numbers */
#define NUMBER 258 /* copy this from cal.tab.c */


typedef union { /* copy this from cal.tab.c */
int d;
} YYSTYPE;


YYSTYPE yylval; /* for passing value to parser */
extern int lineNum; /* line number from cal.tab.c */


%}


%%
[ \t]+ {}


[\n] { lineNum++; }


"(" {
#ifdef DEBUG
printf("token '(' at line %d\n", lineNum);
#endif
return '(';
}


")" {
#ifdef DEBUG
printf("token ')' at line %d\n", lineNum);
#endif
return ')';
}


"+" {
#ifdef DEBUG
printf("token '+' at line %d\n", lineNum);
#endif
return '+';
}


"*" {
#ifdef DEBUG
printf("token '*' at line %d\n", lineNum);
#endif
return '*';
}


[0-9]+ {
#ifdef DEBUG
printf("token %s at line %d\n", yytext, lineNum);
#endif
yylval.d = atoi(yytext);
return NUMBER;
}


%%
int yywrap() { /* need this to avoid link problem */
return 1;
}


cal.y

%{
#include <stdio.h>
#include <ctype.h>
int lineNum = 1;
void yyerror(char *ps, ...) { /* need this to avoid link problem */
printf("%s\n", ps);
}
%}


%union {
int d;
}


// need to choose token type from union above
%token <d> NUMBER
%token '(' ')'
%left '+'
%left '*'
%type <d> exp factor term
%start cal




%%
cal : exp
{ printf("The result is %d\n", $1); }
;


exp : exp '+' factor
{ $$ = $1 + $3; }
    | factor
{ $$ = $1; }
;


factor : factor '*' term
{ $$ = $1 * $3; }
       | term
{ $$ = $1; }
;


term : NUMBER
{ $$ = $1; }
     | '(' exp ')'
{ $$ = $2; }
;


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


Makefile

cal: lex.yy.o cal.tab.o
gcc -o cal lex.yy.o cal.tab.o


lex.yy.o: cal.l
flex cal.l; gcc -c lex.yy.c


cal.tab.o: cal.y
bison -d cal.y; gcc -c cal.tab.c


clean:
rm -f p2 cal.output *.o cal.tab.c lex.yy.c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值