编译与解释实践(1)-flex and bison 配置安装
生活随笔
收集整理的這篇文章主要介紹了
编译与解释实践(1)-flex and bison 配置安装
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
sudo dnf instal flex bison
下面先開始測(cè)試flex
編輯test.l
形成詞法分析
$ ./a.out hello world good this book 4,5,28 (base) [myhaspl@localhost flexbison]$ flex test.l (base) [myhaspl@localhost flexbison]$ gcc lex.yy.c (base) [myhaspl@localhost flexbison]$ ./a.outhello world good this book 4,5,28$vim testcalc.l
%option noyywrap %{enum yytokentype{NUMBER=258,ADD=259,SUB=260,MUL=261,DIV=262,ABS=263,EOL=264}; int yylval; %} %% "+" {return ADD;} "-" {return SUB;} "*" {return MUL;} "/" {return DIV;} "|" {return ABS;} [0-9]+ {yylval = atoi(yytext); return NUMBER;} \n {return EOL;} [ \t] {return EOL;} . {printf("Mystery character %c\n", *yytext);} %% int main(int argc,char **argv) {int tok;while(tok=yylex()){printf("%d",tok);if(tok==NUMBER) printf(" = %d\n",yylval);else printf("\n");} } $cc lex.yy.c $ ./a.out a /31 + |19 Mystery character a 264 262 258 = 31 264 259 264 263 258 = 19 264編輯testcalc.y和testcalc.l文件
(base) [myhaspl@localhost flexbison]$ cat testcalc.l %{ #include"testcalc.tab.h" %} %option noyywrap %% "+" {return ADD;} "-" {return SUB;} "*" {return MUL;} "/" {return DIV;} "|" {return ABS;} [0-9]+ {yylval = atoi(yytext); return NUMBER;} \n {return EOL;} [ \t] {return EOL;} . {printf("Mystery character %c\n", *yytext);} %% (base) [myhaspl@localhost flexbison]$ cat testcalc.y %{ #include<stdio.h> %} %token NUMBER %token ADD SUB MUL DIV ABS %token EOL %%calclist:| calclist exp EOL {printf("=%d\n", $2);}; exp: factor | exp ADD factor {$$ = $1 + $3;}| exp SUB factor {$$ = $1 - $3;}; factor: term | factor MUL factor {$$ = $1 * $3;}| factor DIV term {$$ = $1 / $3;}; term:NUMBER | ABS term {$$ = $2 >= 0? $2 : -$2;}; %% main(int argc, int **argv){ yyparse(); } yyerror(char *s) { fprintf(stderr, "error:%s\n", s); }生成可執(zhí)行文件
(base) [myhaspl@localhost flexbison]$ bison -d testcalc.y testcalc.y: 警告: 2 項(xiàng)偏移/歸約沖突 [-Wconflicts-sr] (base) [myhaspl@localhost flexbison]$ flex testcalc.l (base) [myhaspl@localhost flexbison]$ cc -o testcalc testcalc.tab.c lex.yy.c (base) [myhaspl@localhost flexbison]$ ./testcalc 2*3+4 =10 5+6*9 =59 與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的编译与解释实践(1)-flex and bison 配置安装的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: npm的镜像替换淘宝
- 下一篇: @Transactional 实现原理