我在使用 lex 和 yacc 时观察到一个奇怪的行为。
这是我的 lex 文件 -- ex.l
%option noyywrap
%option yylineno
%{
#include <iostream>
using namespace std;
#include "y.tab.h"
void yyerror(char *); // to get the token types that we return
%}
%%
[ \t] ;
[0-9]+\.[0-9]+ { yylval.fval = atof(yytext); //this is not working
cout << "lex found an float: "; return FLOATS; }
[0-9]+ { cout << "lex found an int: "; yylval.ival = atoi(yytext); return INTS; }
[a-zA-Z0-9]+ {
char *res = new char[strlen(yytext) + 1];
strcpy(res, yytext);
yylval.sval = res;
return STRINGS;
}
. ;
%%
hHre 是我的 yacc 文件 -- ex.y
%{
#include <iostream>
using namespace std ;
extern int yylex();
extern int yyparse();
extern FILE *yyin;
extern int yynerrs;
extern void yyerror(char *s);
%}
%union {
int ival;
float fval;
char *sval;
}
%token <ival> INTS
%token <fval> FLOATS
%token <sval> STRINGS
%%
grammar:
INTS grammar { cout << "yacc found an int: " << $1 << endl; }
| FLOATS grammar { cout << "yacc found a float: " << $1 << endl; }
| STRINGS grammar { cout << "yacc found a string: " << $1 << endl; }
| INTS { cout << "yacc found an int: " << $1 << endl; }
| FLOATS { cout << "yacc found a float: " << $1 << endl; }
| STRINGS { cout << "yacc found a string: " << $1 << endl; }
;
%%
#include <stdio.h>
main() {
yyin = stdin;
do {
yyparse();
} while (!feof(yyin));
}
void yyerror(char *s) {
cout << "EEK, parse error! Message: " << s << endl;
exit(-1);
}
在编译这两个并运行它们之后,我没有从 ex 的 lex 中得到输出:-
为什么会这样?为什么 lex 的 cout 语句不起作用?
最佳答案
问题是我认为 ex.y 中有以下代码。
%token <ival> INTS
%token <fval> FLOATS
%token <sval> STRINGS
使用内置 token 。这会覆盖 ex.l 文件中定义的标记。从某种意义上说,执行永远不会到达 ex.l 文件中的 cout 行。
尝试只编写以下代码,它应该可以工作。
%token INTS
%token FLOATS
%token STRINGS
希望这对您有所帮助。
注意:我还没有测试代码。所以这样做之后你可能会得到其他错误。
关于c++ - lex 和 yacc 中的词法分析器没有输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22575067/