编译原理:利用yacc/bison进行语法分析

YACC(Yet Another Compiler-Compiler)是一个LALR(1)分析器自动生成器,是贝尔实验室在UNIX上首次实现,与LEX有直接的接口。此外GNU(GNU is not UNIX)的Bison是对YACC的兼容性扩充。

YACC自动构造分析器的模式及作用图:


其步骤如下:


YACC源程序结构:

说明部分
%%
翻译规则
%%
用C语言编写的辅助例程

给出一个源程序:https://blog.csdn.net/u014708761/article/details/50153141

%{
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
%}
%token DIGIT
%%
line    :expr'\n' { printf("%d\n",$1);return;}
        ;
expr    :expr'+'term { $$=$1+$3;}
		|expr'-'term { $$=$1-$3;}
		|term
		;
term	:term'*'factor {$$=$1*$3;}
		|factor
		;
factor	:'('expr')' {$$=$2;}
        |DIGIT
        ;
%%
main(){
    return yyparse();
}

int yylex(){
    int c;
    while ((c=getchar())==' ');
    if(isdigit(c)){
        yylval=c-'0';
        return DIGIT;
    }
    return c;
}
int yyerror(char *s){
    fprintf(stderr,"%s\n",s);
    return 1;
}

我的运行环境是cygwin下的bison或yacc:

Toa@DESKTOP-499IG24 ~
$ yacc --version
bison (GNU Bison) 3.0.4
由 Robert Corbett 和 Richard Stallman 编写。

版权所有 (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Toa@DESKTOP-499IG24 ~
$ bison --version
bison (GNU Bison) 3.0.4
由 Robert Corbett 和 Richard Stallman 编写。

版权所有 (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

编译与运行:

Toa@DESKTOP-499IG24 ~
$ yacc a.y

Toa@DESKTOP-499IG24 ~
$ gcc y.tab.c -w

Toa@DESKTOP-499IG24 ~
$ ./a.exe
3+4*2*(2+3)
43

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值