Bison读取char *符号的语义值,直到规则结束

时间:2015-01-07 10:29:54

标签: bison semantics flex-lexer

任何人都可以帮我解决这些简单的问题。我在Bison中有这些微小的语法规则:

pair_list
 : pair_list pair               
 | pair                         
; 

pair
 : KEY ':' VAR ';'          { $$ = new_sym($1, $3); add_entry($$);}
;

我有这些类型的声明:

%union {
    struct symbol *symbl;
    char *key;
    int val;
    int token;
}

%token <key> KEY
%token <val> VAL
%token <token> EOL

%type <symbl> pair
%type <key> id

我的问题是,Bison分配给$1的值是规则的字符串值,从“$ 1”到规则结尾。例如,如果Flex为"hello"返回KEY23返回VAL,则$1的值将变为"hello:23;"。如何让野牛让$1成为"hello"

以下是我的弹性规则:

[ \t\n]+                {/*Ignore*/}
[0-9]+                  {yylval.val = atoi(yytext); return VAL;}
":"                     {return ':';}
";"                     {return ';';}
[A-Za-z][A-Za-z0-9_]*   {yylval.key = yytext; return KEY;}

为了证明Flex规则是正确的,我编辑了我的语法:

/*Edited grammar to show that yylex returns correct value yylval.key for KEY which is assigned to    id. However, when evaluated in rule pair: KEY ':' VAR ';', the value of $1 became the string representation of KEY + ":" + VAR + ";" (where + is for concatenation).
*/
pair_list
 : pair_list pair               
 | pair                         
; 

pair
 : id ':' VAR ';'           { $$ = new_sym($1, $3); add_entry($$);}
;

id
 : KEY                      {printf("%s\n", $1); /*This prints the id correctly*/}
;

0 个答案:

没有答案