c++ - 如何继承yyFlexLexer?

标签 c++ parsing flex-lexer lexer

我正在努力学习 flex/bison。我现在有一些基本的 c 示例,但我想继续做 C++ AST 树。 c++ 使这种类型的面向对象的程序比 C 更容易。但是,Flex 的 c++ 生成似乎存在问题,我不确定如何解决它。我想添加一些用于警告/错误报告的方法,所以我打算从 yyFlexLexer 继承并在我的“.l”文件中调用诸如 warning(const char* str) 和 error(const char* str) 在适当的地方。

但是,当我尝试按照我认为文档中所说的方式执行继承时,我遇到了“yyFlexLexer 重新定义”错误。

词法分析器.l

%option nounistd
%option noyywrap
%option c++
%option yyclass="NLexer"

%{
#include "NLexer.h"
#include <iostream>
using namespace std;
%}

%%
[ \t]+
\n  { return '\n';}
[0-9]+(\.[0-9]+)? { cout << "double: " << atof(YYText()) << endl;}
. {return YYText()[0];}
%%

int main(int , char**) 
{
    NLexer lexer;
    while(lexer.yylex() != 0) { };

    return 0;
}

NLexer.h

#ifndef NLEXER_H
#define NLEXER_H
#include <FlexLexer.h>

class NLexer : public yyFlexLexer
{
public:
    virtual int yylex();
};

#endif

很多错误:

错误 1 ​​error C2011: 'yyFlexLexer' : 'class' type redefinition c:\users\chase_l\documents\visual studio 2013\projects\nlanguage\nlanguage\include\flexlexer.h 112 1 NLanguage

错误 2 错误 C2504:“yyFlexLexer”:基类未定义 c:\users\chase_l\documents\visual studio 2013\projects\nlanguage\nlanguage\nlexer.h 6 1 NLanguage

大约 80 多个与 yyFlexLexer 中的标识符不存在。

我可以发布生成的 cpp 文件,但它是一个 1500 行的自动生成的乱七八糟的东西。

编辑:显然这是 yyFlexLexer 的宏定义问题,因此它可以生成不同的基类 xxFlexLexer 等等。如果您的项目中只需要 1 个词法分析器(可能),您只需执行以下操作即可使其正常工作。如果有人有比这更好的方法,请告诉我。

#ifndef NLEXER_H
#define NLEXER_H

#undef yyFlexLexer
#include <FlexLexer.h>

class NLexer : public yyFlexLexer
{
public:
    virtual int yylex();
};

#endif

最佳答案

在生成的 lexer.yy.cc 文件中,您可以找到关于您的问题的旧评论:

/* The c++ scanner is a mess. The FlexLexer.h header file relies on the * following macro. This is required in order to pass the c++-multiple-scanners * test in the regression suite. We get reports that it breaks inheritance. * We will address this in a future release of flex, or omit the C++ scanner * altogether. */

#define yyFlexLexer yyFlexLexer

yyFlexLexerOnce include guard 可以用来克服它。 NLexer.h:

#ifndef NLEXER_H
#define NLEXER_H

#if !defined(yyFlexLexerOnce)
#include <FlexLexer.h>
#endif

class NLexer : public yyFlexLexer
{
public:
    virtual int yylex();
};

#endif

关于c++ - 如何继承yyFlexLexer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40663527/

相关文章:

python - 解析 XML 异常

parsing - 如何在 Go lang 中转换 uint16 中的字符串值?

python - 使用python从文本文件中提取细节

regex - 使用正则表达式匹配utf-8编码中的任何中文字符

c++ - 弹性代币订单

c++ - Visual Studio 与 G++ 中的 Decltype 和友元函数

c++ - 使用 C/C++ 获取 HASP key (问题)

c++ - 当我的程序退出时静态数据被初始化

使用 Flex 和 Bison 指定前缀时编译错误

java - 如何将 java 函数指针传递给 C++ native 代码