您尚未登录。

楼主 #1 2018-05-09 21:01:00

bunny
会员
注册时间: 2020-05-23
已发帖子: 152
积分: 152

一步一步写一个超级简陋的C编译器——开篇通过一个计算器demo初识flex&yacc

先上cal.l代码:

%{
#include <string.h>
#include "cal.tab.h"

#define YY_SKIP_YYWRAP

extern int yylval;
int yylex(void);
%}

numbers ([0-9])+
plus "+"
minus "-"
times "*"
divide "/"
lp "("
rp ")"
delim [ \n\t]
ws {delim}*

%%
{numbers} {
	sscanf(yytext, "%d", &yylval);
	return INTEGER;
}

{plus} {
	return PLUS;
}

{minus} {
	return MINUS;
}

{times} {
	return TIMES;
}

{divide} {
	return DIVIDE;
}

{lp} {
	return LP;
}

{rp} {
	return RP;
}

{ws} {
}

. {
}
%%

再上cal.y代码:

%{
#include <stdio.h>
#include "lex.yy.c"
#define YYSTYPE int
int yyparse(void);
void yyerror(char* s);
%}

%token PLUS MINUS TIMES DIVIDE INTEGER LP RP

%%
command: exp {printf("%d\n", $1);}

exp: exp PLUS term {$$ = $1 + $3;}
   | exp MINUS term {$$ = $1 - $3;}
   | term {$$ = $1;}
   ;

term: term TIMES factor {$$ = $1 * $3;}
    | term DIVIDE factor {$$ = $1 / $3;}
    | factor {$$ = $1;}
	;

factor: INTEGER {$$ = $1;}
      | LP exp RP {$$ = $2;}
	  ;
%%

int main(int argc, char *argv[]) {
	return yyparse();
}

int yywrap() {
	return 1;
}

void yyerror(char* s) {
	printf("error: %s\n", s);
}

编译出c代码:
bison.exe -d cal.y
flex cal.l

再编译cal.tab.c得到exe文件,测试:
TIM20180509205944.png

离线

页脚

工信部备案:粤ICP备20025096号 Powered by FluxBB

感谢为中文互联网持续输出优质内容的各位老铁们。 QQ: 516333132, 微信(wechat): whycan_cn (哇酷网/挖坑网/填坑网) service@whycan.cn