在flex,bison,c ++中实现Wolfram语言

时间:2015-01-27 03:50:39

标签: c++ bison flex-lexer wolfram-language

在看到像mathicssymja之类的项目后,我正在尝试使用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文件供参考

lexer.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;
}

parser.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;
}

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

yylex在生成的扫描程序中定义,并在生成的解析器中自动使用。由于结果只是普通的C(++),所以没有魔力;如果在文件中使用yylex,则需要在该文件中声明它。

您可能希望野牛自动包含声明,但事实并非如此。首先,它不知道你想要(不必要地,可能是徒劳地)将声明包装在extern "C" {...}中。


此外,您将遇到C ++接口问题。 yylex是flex C ++ API中的成员函数,因此您不能将其声明为extern "C",也不能在外部文件中将其称为yylex。< / p>

YMMV,但我个人更喜欢使用普通的(稳定且记录良好的)C API,它可以很好地编译为C ++,从而无需任何extern "C"声明。

如果要避免使用全局变量,请使用可重入扫描器/纯解析器接口。

最后,flex带有一个非常好的调试选项,只需在命令行中指定-d,几乎为零成本。使用该标志生成的扫描程序将自动输出有关扫描的每个标记的信息性消息,删除命令行标志比编辑整个弹性描述要容易得多。

bison有一个类似的机制,但它不是那么自动:你需要在生成解析器时启用它,然后你需要通过设置运行时标志来打开它。两者都在各自的手册中有详细记载。

相关问题