在看到mathics和symja等项目之后,我正在尝试使用 C++ 中的 flex 和 bison 实现 Wolfram 语言的开源解析器。调用 bison -d 和 flex++ 不会引发任何问题,但是当我使用 g++ 时,会收到以下错误消息:
parser.tab.cpp:1242:16: error: use of undeclared identifier 'yylex'
yychar = YYLEX;
^
parser.tab.cpp:598:16: note: expanded from macro 'YYLEX'
# define YYLEX yylex ()
^
1 error generated.
这是我的 .lpp 和 .ypp 文件供参考
词法分析器.lpp
%{
#include <iostream>
#include "parser.tab.hpp"
using namespace std;
extern "C"
{
int yylex(void);
}
%}
%option c++
%option noyywrap
%%
[1-9][0-9]*(.[0-9]*)? { return NUM; }
"\[" { return LBRACE; }
"\]" cout << "rBrace" << endl;
"\(" cout << "lParen" << endl;
"\)" cout << "rParen" << endl;
"\{" cout << "lBracket" << endl;
"\}" cout << "rBracket" << endl;
"," cout << "comma" << endl;
"@@" cout << "apply" << endl;
"Apply\[" cout << "apply" << endl;
"/@" cout << "map" << endl;
"Map\[" cout << "map" << endl;
"/." cout << "rule" << endl;
"===" cout << "sameQ" << endl;
"SameQ\[" cout << "sameQ" << endl;
"+" cout << "plus" << endl;
"-" cout << "minus" << endl;
"*" cout << "times" << endl;
"/" cout << "divide" << endl;
"^" cout << "power" << endl;
"Power\[" cout << "power" << endl;
--Abbreviated--
. ECHO;
%%
int main()
{
FlexLexer* lexer = new yyFlexLexer;
while(lexer->yylex() != 0)
;
return 0;
}
解析器.ypp
%{
#include <iostream>
#include <string>
using namespace std;
extern "C"
{
int yyparse(void);
}
void yyerror(const char *s);
%}
%union {
double dval;
char *str;
}
%token <dval> NUM;
%token <str> RBRACE;
%token <str> LBRACE;
%%
expr:
NUM { cout << $1 << endl;}
| NUM "+" NUM { cout << $1 + $3}
| NUM "-" NUM { cout << $1 - $3}
| NUM "*" NUM { cout << $1 * $3}
| NUM "/" NUM { cout << $1 / $3}
;
%%
int main(int argc, char **argv)
{
yyparse();
}
void yyerror(const char *s)
{
cout << s << endl;
}
任何帮助,将不胜感激。谢谢!