Lex 和 Yacc/Flex 以及 bison 语法错误
Lex and Yacc/Flex and bison Syntax Error
我最近发现了 lex 和 yacc(以及 flex 和 bison),当我试图判断是否给程序一个句子时出现错误。
这是 .lex 文件:
%{
#include <stdio.h>
#include "1.tab.h"
%}
%%
tweety|sylvester return NP;
a|the return AR;
cat|bird return NC;
run|fly return VI;
eat|hate return VT;
"." return POINT;
.|\n
%%
和 .yacc :
%{
#include <stdio.h>
%}
%token NP AR NC VI VT POINT
%%
S: PH POINT {printf("Sentence found !\n");}
PH: GN VT GN|GN VI
GN: NP|AR NC
%%
main(){
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
这是我用来编译程序的命令:
lex file.lex
bison -d file.yacc
gcc lex.yy.c 1.tab.c -o test -lfl
当我尝试 运行 程序时,它在第一次输入时运行良好,但随后经常出现错误。这是一个例子:
./test
tweety fly.
Sentence found !
tweety hate sylvester.
error: syntax error
你有什么想法吗?
谢谢。
您的语法只允许输入一个句子。您需要一个新的第一条规则:
P : S | P S ;
其中 P 是新的目标符号('Program'、'Paragraph' 等,随您喜欢)。
我最近发现了 lex 和 yacc(以及 flex 和 bison),当我试图判断是否给程序一个句子时出现错误。
这是 .lex 文件:
%{
#include <stdio.h>
#include "1.tab.h"
%}
%%
tweety|sylvester return NP;
a|the return AR;
cat|bird return NC;
run|fly return VI;
eat|hate return VT;
"." return POINT;
.|\n
%%
和 .yacc :
%{
#include <stdio.h>
%}
%token NP AR NC VI VT POINT
%%
S: PH POINT {printf("Sentence found !\n");}
PH: GN VT GN|GN VI
GN: NP|AR NC
%%
main(){
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
这是我用来编译程序的命令:
lex file.lex
bison -d file.yacc
gcc lex.yy.c 1.tab.c -o test -lfl
当我尝试 运行 程序时,它在第一次输入时运行良好,但随后经常出现错误。这是一个例子:
./test
tweety fly.
Sentence found !
tweety hate sylvester.
error: syntax error
你有什么想法吗?
谢谢。
您的语法只允许输入一个句子。您需要一个新的第一条规则:
P : S | P S ;
其中 P 是新的目标符号('Program'、'Paragraph' 等,随您喜欢)。