我想弄清楚Lemon解析器生成器,所以我写了一个小测试来帮助自己完全理解。 文件生成没有问题,编译器没有抱怨,但当我尝试运行它时,我得到一个分段错误。 我做错了什么?
lexicon.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;
%%
grammar.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()));
}
main.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
答案 0 :(得分:0)
使用指针表示标识符的std::vector
。我不确定它是如何在编译错误中发生的,但在代码中的某处,它会尝试将属性归因于std::vector<Identifier>&
类型的变量。如果我没记错的话,你不能归因于参考文献。
因此,更改为std::vector<Identifier>*
可以解决您的问题。