【发布时间】:2011-10-10 13:52:24
【问题描述】:
让我们定义一种语言:
VAR := [0-9A-Za-z_]+
Exp := VAR
| VAR,'=',VAR
| '(', Exp, ')'
| Exp, '&', Exp
| Exp ,'|', Exp
例如:“( a = b ) & ( c | (d=e) ) ”是合法的
我已经阅读了 YASS 和 Lex 手册,但我很困惑,我只想要可以解析这种语言的编译器
你能告诉我如何为这种语言编写 flex&bison 配置文件吗?
到目前为止我已经完成了:
文件 a.l:
%{
#include <string.h>
#include "stdlib.h"
#include "stdio.h"
#include "y.tab.h"
%}
%%
("&"|"and"|"AND") { return AND; }
("|"|"or"|"OR") { return OR; }
("="|"eq"|"EQ") { return EQ; }
([A-Za-z0-9_]+) { return VAR;}
("(") { return LB ;}
(")") { return RB ;}
("\n") { return LN ;}
%%
int main(void)
{
yyparse();
return 0;
}
int yywrap(void)
{
return 0;
}
int yyerror(void)
{
printf("Error\n");
exit(1);
}
文件 a.y
%{
#include <stdio.h>
%}
%token AND OR EQ VAR LB RB LN
%left AND OR
%left EQ
%%
line :
| exp LN{ printf("LN: %s",$1);}
;
exp: VAR { printf("var:%s",$1);}
| VAR EQ VAR { printf("var=:%s %s %s",$1,$2,$3);}
| exp AND exp { printf("and :%s %s %s",$1,$2,$3);}
| exp OR exp { printf("or :%s %s %s",$1,$2,$3);}
| LB exp RB { printf("abstract :%s %s %s",$1,$2,$3);}
;
现在我在 Chris Dodd 的指导下编辑了文件,看起来好多了(至少 lex 工作得很好),但是我得到了这样的输出:
disk_path>myprogram
a=b
var=:(null) (null) (null)LN: (null)ab=b
Error
那么,为什么函数 printf 输出 null 呢?输入第二个后提示Error并退出程序?
【问题讨论】:
-
向我们展示您的尝试。我会在回复中给出一些提示,但您确实应该首先展示您尝试过的内容