Bison / Flex创建列表

时间:2015-10-29 07:38:14

标签: c bison

我试图从中缀转换为后缀并使用列表以正确的顺序捕获char。这是我的野牛档案:

%{
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <string.h>
%}
%union{
    char list[100];
    int integer;
};

%token <integer> NUM
%token ENDOFLINE
%left '+' '-'
%left '*' '/'
%right NEGATIVE
%type <list> Exp
%%

Statement: 
    | Statement Line
;
Line: Exp ENDOFLINE{ printf("Result -> %s\n", $1);  }
    | ENDOFLINE
;
Exp:  Exp '+' Exp {add($$,(char)$2);}
    |   Exp '*' Exp {add($$,(char)$2);}
    |   Exp '-' Exp {add($$,(char)$2);}
    |   Exp '/' Exp {add($$,(char)$2);}
    |   '-' Exp %prec NEGATIVE {add($$,(char) $1);}
    |   NUM     {$$ = create_list(); add($$,(char) $1);}
;
%%
char * create_list(){
    char expList [100];
    return expList;
}
void add(char* array, char input){
    int length = stlen(array);
    array[length] = input;
}
int main(){
    yyparse();

}

int yyerror (char *msg) {
    return printf ("error YACC: %s\n", msg);
}

我有多个问题,一个是它说我不能在char []中添加一个int,另一个说成员请求添加不是结构或联合的东西。我是Bison / Flex的新手,如果我想存储这些值,这是正确的实现,所以我可以在main中使用它们(在某些时候)?

编辑:这是我最新的代码。我更新了我的lex文件以识别各个操作符并返回该标记,并将正确的函数及其原型添加到我的bison文件中(a4grammer2.y)。

%{
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <string.h>

    char * create_list();
    void add(char* array, char input);
    int yyerror(char* s);
    int main(void);
%}
%union{
    char list[100];
    char character;
    int integer;
};

%token <integer> NUM
%token <character> PLUS
%token <character> MINUS
%token <character> MULTIPLY
%token <character> DIVIDE
%token ENDOFLINE
%right NEGATIVE
%type <list> Exp
%%

Statement: 
    | Statement Line
;
Line: Exp ENDOFLINE{ printf("Result -> %s\n", $1);  }
    | ENDOFLINE
;
Exp:  Exp PLUS Exp {add($$,$2);}
    |   Exp MULTIPLY Exp {add($$,$2);}
    |   Exp MINUS Exp {add($$,$2);}
    |   Exp DIVIDE Exp {add($$,$2);}
    |   MINUS Exp %prec NEGATIVE {add($$,$1);}
    |   NUM     {strcpy($$,create_list()); add($$, $1);}
;
%%
char * create_list(){
    char expList [100];
    return expList;
}
void add(char* array, char input){
    int length = stlen(array);
    array[length] = input +'0';
}
int main(){
    yyparse();

}

int yyerror (char *msg) {
    return printf ("error YACC: %s\n", msg);
}

现在当我使用:

进行编译时
yacc -d a4grammer2.y

我收到此错误

warning: 20 shift/reduce conflicts [-Wconflicts-sr]

当我尝试使用gcc进行编译时,我得到了这个:

a4grammer2.y: In function ‘create_list’:
a4grammer2.y:44:5: warning: function returns address of local variable [-Wreturn-local-addr]
     return expList;

1 个答案:

答案 0 :(得分:0)

除了评论中提到的内容外:

Exp:  Exp '+' Exp {add($$,(char)$2);}

这和所有类似的制作应该是一般形式

Exp:  Exp '+' Exp {$$ = add($1,$3);}

我不知道是什么让你认为每个Exp都可以投射到char.生活会非常无趣,如果是这样的话你的程序完全没必要。