【问题标题】:Flex and Lemon ParserFlex 和柠檬解析器
【发布时间】:2013-10-14 11:57:49
【问题描述】:

我正在尝试学习 flex 和 lemon,以便解析(适度)复杂的文件格式。到目前为止,我有我的语法和 lex 文件,我相信它可以正确解析示例文件。现在,我想将使用 flex 扫描的令牌文本传递给柠檬。

flex YYSTYPE 定义为

#define YYSTYPE char*

柠檬令牌类型是

%token_type {char *}

但是,如果我在柠檬中有一套规则:

start ::= MATDEF IDENTIFIER(matName) LEFT_CURLY_BRACE(left) materialDefinitionBody(mBody) RIGHT_CURLY_BRACE(right) .
{
std::string r = std::string(matName) + std::string(left) + mBody + std::string(right);
std::cout << "result " << r << std::endl;
}

materialDefinitionBody(r) ::= techniqueList .
{
r = "a";
}

输出将是

result a

什么时候应该是这样的

mat1 { a }

我的主要解析循环是:

void parse(const string& commandLine) {
    // Set up the scanner
    yyscan_t scanner;
    yylex_init(&scanner);
    YY_BUFFER_STATE bufferState = yy_scan_string(commandLine.c_str(), scanner);

    // Set up the parser
    void* shellParser = ParseAlloc(malloc);

    yylval = new char[512];
    int lexCode;
    do {
        yylval[0] = 0;
        lexCode = yylex(scanner);
        cout << lexCode << " : " << yylval << std::endl;
        Parse(shellParser, lexCode, yylval);
    }
    while (lexCode > 0);

    if (-1 == lexCode) {
        cerr << "The scanner encountered an error.\n";
    }

    // Cleanup the scanner and parser
    yy_delete_buffer(bufferState, scanner);
    yylex_destroy(scanner);
    ParseFree(shellParser, free);
}

cout 行正在打印正确的 lexCode/yylval 组合。

最好的方法是什么?我找不到任何有用的东西。

【问题讨论】:

    标签: lex lemon


    【解决方案1】:

    你需要有

    yylval = new char[512];
    

    在 do-while 循环内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多