FLex与Bison实现简易计算器

计算器主要实现了整数的加、减、乘、除、括号以及绝对值运算。其中,绝对值符号用|表示。

FLex词法分析

calculator.l

%{
    #include "calculator.tab.h"
%}
%option noyywrap

%%
"+"	{ return ADD; }
"-"	{ return SUB; }
"*"	{ return MUL; }
"/"	{ return DIV; }
"|"     { return ABS; }
"("     { return OP; }
")"     { return CP; }
[0-9]+	{ yylval = atoi(yytext); return NUMBER; }

\n      { return EOL; }
"//".*  
[ \t]   { /* ignore white space */ }
.	{ fprintf(stderr, "Mystery character %c\n", *yytext); }

%%

Bison语法分析

calculator.y

%{
    #include <stdio.h>
    int yylex (void);
    void yyerror (const char *);
%}

/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token OP CP
%token EOL

%%
calclist: /* nothing */
    | calclist exp EOL { printf("= %d\n> ", $2); }
    | calclist EOL { printf("> "); } /* blank line or a comment */
    ;

exp: factor
    | exp ADD exp { $$ = $1 + $3; }
    | exp SUB factor { $$ = $1 - $3; }
    | exp ABS factor { $$ = $1 | $3; }
    ;

factor: term
    | factor MUL term { $$ = $1 * $3; }
    | factor DIV term { $$ = $1 / $3; }
    ;

term: NUMBER
    | ABS term { $$ = $2 >= 0? $2 : - $2; }
    | OP exp CP { $$ = $2; }
    ;

%%
int main()
{
  printf("> "); 
  return yyparse();
}

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

gcc编译

bison -d calculator.y
flex calculator.l
gcc -o calculator lex.yy.c calculator.tab.c

在这里插入图片描述

计算器测试

在这里插入图片描述
参考资料:flex与bison(中文版)

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值