c++ - lex 和 yacc 中的词法分析器没有输出

标签 c++ token flex-lexer lex

我在使用 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 中得到输出:-

output

为什么会这样?为什么 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/

相关文章:

c++ - 编译命令有效,但运行命令没有响应

c++ - strcpy_s缓冲区L缓冲区太小&& 0

c++ - 尝试使用 C++ 创建工厂方法时出错

android - 静默登录成功后能否通过authAccount.getAccessToken()方法获取AccessToken

c - c 中的字符串分词器直到制表符和换行符

c++ - Malloc 和自由多指针

html - Zing Chart 堆积图

c++ - 对包含连字符和斜杠的字母数字字符串进行积极前瞻断言的 Flex 词法分析器规则

c - 弹性 "Unrecognized Error"

compiler-construction - 如何使用缩进作为带有 bison 和 flex 的 block 分隔符