初步学习lex和yacc

因为是非计算机本科,所以没有学编译原理,进来想补补课,于是买了本《自制编程语言》,里面介绍了lex和yacc工具,于是装起来试了下。


原来用工具来解析字符串还是挺方便的,以前知道正则以后,就觉得这东西很好,现在有了lex和yacc,把正则能做的事情又放大了,能够做更丰富的事情。


例如,写一个简单的把字符串里的数字相加,其他忽略的程序(说是简单是指功能,其实调通很不简单,哈哈,特别是把%type写成了%token的笔误后,纠结了很久)


下面贴上代码

test.l

%{
#include <stdio.h>
#include "y.tab.h"
int
yywrap(void)
{ return 1; }
%}
%%
"\n"  return CR;
[0-9]+ {
    int temp;
    sscanf(yytext, "%d", &temp);
    yylval.int_value = temp;
    return A;
}
[ \t] ;
. {
		//other words
		yylval.int_value = 0;
    return ERR;
}
%%

test.y

%{
#include <stdio.h>
#include <stdlib.h>
%}
%union {
	int int_value;
}
%token <int_value> A B
%token CR ERR
//!!this is %type!!
%type <int_value> expression other
%%
line_list : line | line_list line;
line : expression CR {
	printf("%d\n", $1);
} | CR {
	printf("exit.\n");
	exit(0);
};
expression : A | other | expression A {
	$$ = $1 + $2;
} | expression other {
	$$ = $1 + $2;
};
other: ERR {
	printf(".");
};
%%
int
yyerror(char const *str) {
    extern char *yytext;
    fprintf(stderr, "parser error near %s\n", yytext);
    return 0;
}

int main(void) {
    extern int yyparse(void);
    extern FILE *yyin;

    yyin = stdin;
    if (yyparse()) {
        fprintf(stderr, "Error ! Error ! Error !\n");
        exit(1);
    }
}

然后利用lex和yacc来生成一个可执行文件

yacc -dv test.y
lex test.l
cc *.c

来看看执行效果吧



还不错哦~~


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值