2

我试图弄清楚 Lemon 解析器生成器,所以我写了一个小测试来帮助自己完全理解。文件生成没有问题,编译器没有抱怨,但是当我尝试运行它时,我得到一个分段错误。我究竟做错了什么?

词典.l:

%{
#include "grammar.h"
%}

%option noyywrap

%%

[A-Za-z_][A-Za-z0-9]*   return IDENTIFIER;
\".*\"                  return STRING;
[0-9]+                  return NUMBER;
"="                     return EQUALS;
\n                      return NEWLINE;
%%

语法.y:

%include {
#include <vector>
#include <iostream>
#include <cassert>
#include <sstream>
#include "AST.h"
}

%token_type {char *}
%extra_argument {std::vector<Identifier>& identifiers}

start ::= assignments. {
    std::cout << "start resolved" << std::endl;
}

assignments ::= assignment.
{
    std::cout << "assignments resolved" << std::endl;
}
assignments ::= assignments NEWLINE assignment.

assignment ::= IDENTIFIER(id) EQUALS STRING(str).
{
    std::cout << "I get here too" << std::endl;
    identifiers.push_back(Identifier(id, str));
}

assignment ::= IDENTIFIER(id) EQUALS NUMBER(num).
{
    std::stringstream ss;
    ss << num;
    identifiers.push_back(Identifier(id, ss.str()));
}

主.cpp:

#include "AST.h"

using namespace std;

void* ParseAlloc(void* (*allocProc)(size_t));
void Parse(void*, int, char *, vector<Identifier>&);
void ParseFree(void*, void(*freeProc)(void*));

int yylex();
extern char * yytext;

int main() {
    vector<Identifier> identifiers;
    void* parser = ParseAlloc(malloc);
    cout << "Line 20" << endl;
    while (int lexcode = yylex()) {
        cout << "Getting in the loop: " << yytext << endl;
        Parse(parser, lexcode, yytext, identifiers);
    }
    Parse(parser, 0, NULL, identifiers);
    cout << "Line 25" << endl;
    ParseFree(parser, free);

    return 0;
}

AST.h:

#include <string>
#include <iostream>

class Identifier {
    std::string name;
    std::string value;
public:
    Identifier(std::string _name, std::string _value)
    : name(_name),
      value(_value) {
        std::cout << "Initializing " << name << " as " << value << std::endl;
    }

    std::string getName();
    std::string getValue();
    void setValue(std::string _value);
};

AST.cpp:

#include "AST.h"

std::string Identifier::getName() {
    return name;
}

std::string Identifier::getValue() {
    return value;
}

void Identifier::setValue(std::string _value) {
    value = _value;
}

最后是测试输入:

alpha = "Hello"
beta = "World"
gamma = 15

和输出:

mikidep@mikidep-virtual:~/Scrivania/bison test$ cat text | ./parserLine 20
Getting in the loop: alpha
Segmentation Fault
4

1 回答 1

0

使用指针来表示std::vector标识符。我不确定它是如何在编译错误中发生的,但在代码中的某处它会尝试对 type 的变量进行归因std::vector<Identifier>&。如果我没记错的话,您不能对参考文献进行归因。

因此,更改为std::vector<Identifier>*解决您的问题。

于 2015-02-02T20:34:41.907 回答