简体   繁体   English

野牛中的哈希查找麻烦

[英]Trouble with hash lookup in bison

I'm working on a sort of the classic bison/flex calculator implementation problem. 我正在研究一种经典的野牛/弹性计算器实现问题。 The issue that I've run is with variable assignment. 我遇到的问题是变量分配。 It seems to work at first; 起初它似乎起作用; only declared variables can be referenced, it remembers the value that I've assigned... except that all variables seem to share a single value, rather than each having its own. 只有声明的变量可以被引用,它会记住我已分配的值...只是所有变量似乎共享一个值,而不是每个变量都有自己的值。 So if I do "x=3; y=5;" 因此,如果我执行“ x = 3; y = 5;” then both x and y have the value of 5. 那么x和y的值都是5。

Obviously I'm doing something wrong, but I'm not sure if this is a failure in my understanding of bison, c++, or how the unordered_map data structure works. 显然我在做错事,但是我不确定这是否是对bison,c ++或unordered_map数据结构如何工作的理解失败。 (Or perhaps, all 3) (或者可能是全部3个)

I believe I have included all the relevant parts of the code below, but if there is some missing, let me know. 我相信我已经在下面的代码中包含了所有相关的部分,但是如果有一些遗漏,请告诉我。

%{

    #include <iostream>
    #include <string>
    #include <unordered_map>
    using namespace std;

    unordered_map<string, double> dict;
%}    

%union {
    double dval;
    char *sval;
}

%token <sval> VARIABLE
%token <dval> NUMBER
%type<dval> expr

%%

assign: 
     VARIABLE '=' expr {dict[$1] = $3; cout << $1<< "="<<dict[$1]<<endl; }
expr: VARIABLE {
    if(dict.find($1) == dict.end())
    {
        yyerror("Bad Var");
    }

You should really show your flex code as well, but I'm guessing that the relevant bit looks something like this: 您也应该真正显示您的flex代码,但是我猜测相关的部分看起来像这样:

{id}     { yylval.sval = yytext; return VARIABLE; }

What you need to do is: 您需要做的是:

{id}     { yylval.sval = strdup(yytext); return VARIABLE; }

And then you need to make sure that you don't leak memory, by freeing the allocated string after you use it in your bison action. 然后,您需要通过在野牛操作中使用分配的字符串后释放它来确保不泄漏内存。

See the flex manual and the bison manual . 请参阅flex手册bison手册

So my problem turned out to be not in how I was storing the data, but just in retrieving it. 因此,我的问题并不在于我如何存储数据,而在于检索数据。 I needed to add the else statement below to actually set the value of expr. 我需要在下面添加else语句以实际设置expr的值。

expr: VARIABLE {
    if(dict.find($1) == dict.end())
    {
        yyerror("Bad Var");
    }
    else { //Needed this section
        $$ = dict[$1]
    }
}    

I think I knew I needed to do that and just forgot, but the behavior of expr taking the value of whatever the most recently assigned variable is threw me off. 我想我知道我需要这样做,只是忘记了,但是expr取任何最近分配的变量的值的行为使我失望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM