我有两个分别用Lex和Yacc编写的非常小的文件(试图删除所有其他混淆变量)。
Lex:
%{
#include <stdlib.h>
#include "y.tab.h"
void yyerror(char *);
%}
%%
[a] {
yylval = *yytext;
return VAR;
}
[ \t\n] ;
. yyerror("invalid character");
%%
int yywrap(void) {
return 1;
}
Yacc:
%token VAR
%{
void yyerror(char *);
int yylex(void);
#include <stdio.h>
%}
%%
butts:
VAR { printf("%d\n", $1); }
%%
void yyerror(char *s) {
fprintf(stderr, "%s\n", s);
}
int main(void) {
#if YYDEBUG
yydebug = 1;
#endif
yyparse();
return 0;
}
当我编译整个东西(使用-DYYDEBUG)时,我得到的输出是:
Starting parse
Entering state 0
Reading a token: a
Next token is token VAR ()
Shifting token VAR ()
Entering state 1
Reducing stack by rule 1 (line 12):
$1 = token VAR ()
97
-> $$ = nterm butts ()
Stack now 0
Entering state 2
Reading a token: a
Next token is token VAR ()
syntax error
Error: popping nterm butts ()
Stack now 0
Cleanup: discarding lookahead token VAR ()
Stack now 0
输入两次“ a”时。第一次询问Reading a token:
程序时,我按“ a”键似乎运行良好,但是第二次,它会呕吐。
我不知道为什么会这样。
这是因为您的语法文件说只允许一个“ a”。再有就是一个错误,因此您会得到一个错误。您的语法规则说:
butts: VAR
仅此而已。
因此,语法匹配的唯一有效程序是:
a
任何其他输入,例如:
aa
或者:
a
a
会导致语法错误。您的规则非常明确地只说一个VAR ;没有VARS序列;没有几个变量。只有一个VAR。
如果您希望它与输入中的多个匹配,则必须这样说。因此,语法必须描述允许的顺序:
butts: VAR | butts VAR
然后它将允许序列。
清楚点吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句