2

I have the following bison's rule on my .y:

constant_definition: T_ID T_EQUAL T_INT_CONST T_SEMICOLON
{
    if(!insert_const($1, T_INTEGER))
    {
        printf("ERROR:... ");
    }       
};

my token's:

%token T_ID                   1
%token T_EQUAL                42
%token T_INT_CONST            2
%token T_SEMICOLON            33

...

my union:

%union
{
    int token1;
    int token2;
    int token_int_value;
    float token_float_value;
    int token_boolean_value;
}

%type<token2> T_ID 
%type<token_valor_real> T_REAL_CONST
%type<token_valor_int> T_INT_CONST
%type<token_valor_boolean> T_BOOLEAN_CONST

my yylex:

int yylex(void)
{
    token token_read = next_token();

    switch(token_read .token1)
    {
    case T_ID :
        yyval.token2 = token_read.token2;
        break;
    case T_INT_CONST:
        yyval.token_int_value = token_read.token_int_value;
        break;
    case T_REAL_CONST:
        yyval.token_float_value = token_read.token_float_value ;
        break;
    case T_BOOLEAN_CONST:
        yyval.token_boolean_value = token_read.token_boolean_value ;
        break;
    default:
        yylval.token1 = token_read.token1;
        break;
    }

    return token_read.token1;
}

Suppose I have the following sequence of token (token1) read: 5 1 33 39 1(4) 42 2 33 1(5) 42 2 33...

Ever time that bison's rule matches, $1 returns the previous token1's value instead of the secondary token related to T_ID.

For example: This sequence "1 42 2 33" matches, but $1 is returning "39"

Does anyone know why this could be happening?

Thanks in advance!

4

1 回答 1

0

为了让答案出现在答案中而不是在评论中(通过@librik):

yylex中,分配给的值应该是yylval,而不是yyval

yyval存储语义动作左侧的当前值。 yylval存储当前读取的令牌的值。

它们都是相同的类型 (YYSTYPE),因此错误分配不会引发错误。

当您未设置yylvalinyylex时, yylval 中的值将保留由已设置的最后一个令牌读取的值(在您的情况下,最后一个令牌读取不是 T_INT_CONST/T_REAL_CONST/T_BOOL_CONST/T_ID)。因此,使用 yylval 而不是 yyval 将修复它。

于 2013-11-03T03:10:28.617 回答