Bison试图在解析器上使用免费的yylex()函数C++

Bison trying to use free yylex() function on C++ parser

本文关键字:yylex 免费 C++ 函数 Bison      更新时间:2023-10-16

我正在使用 Flex+Bison 生成一个C++扫描器/解析器,但遇到了生成的代码和包含的标头中缺少 flex 函数的问题。

使用 g++ 进行编译失败,并显示以下内容:

parser.cxx: In member function 'virtual int yy::parser::parse()':
parser.cxx:465:38: error: 'yylex' was not declared in this scope
symbol_type yylookahead (yylex (yylval, yylloc));

这是一个错误,因为它不应该使用全局自由函数yylex(...)而是使用我的扫描仪的yy::scanner::yylex(...)函数,实现如下:

#include <FlexLexer.h>
#include "parser.hxx"
#undef YY_DECL
#define YY_DECL yy::parser::symbol_type yy::scanner::yylex(yy::parser::semantic_type* yylval, yy::parser::location_type* yylloc)
namespace yy {
class scanner final: public yyFlexLexer
{
public:
scanner(std::istream *in, std::ostream* out): yyFlexLexer(in, out) {}
parser::symbol_type yylex(yy::parser::semantic_type* yylval, yy::parser::location_type* yylloc);
};

这些参数在 .y 文件中配置为:

%param {parser::semantic_type* yylval} {parser::location_type* yylloc}

flex (.l) 和 bison (.y) 文件都使用标志进行编译,以生成C++代码,并使用 g++ 编译为:

g++ -lfl parser.cxx scanner.cxx -o lang

生成的文件parser.cxxscanner.cxx。我错过了什么,如何修复解析器应该调用而不是yylex()函数?

答案如下

#undef yylex
#define yylex scanner.yylex  // bison's parse() invokes scanner.yylex(),