在野牛代码中使用 yytext

use yytext in bison code

当我试图在 yacc&lex 中编译我的代码时,我得到了这个错误:

yacc代码:

%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define YYSTYPE struct node*
typedef struct node{
    char *token;
    struct node *left;
    struct node *right;
} node;
node* mknode(char* token, node *left, node *right);
void Printtree(node *tree);
int yyerror();
%}
%token NUM PLUS MINUS
%left PLUS MINUS
%%
S:exp {printf("OK\n"); Printtree();};
exp:exp PLUS exp {$$=mknode("+",,);}
    | exp MINUS exp{$$=mknode("-",,);}
    | NUM {$$=mknode(yytext, NULL, NULL);};
%%
#include "lex.yy.c"
int main(){
    return yyparse();
}
node *mknode (char *token, node *left, node *right){
    node *newnode = (node*)malloc(sizeof(node));
    char *newstr = (char*)malloc(sizeof(token)+1);
    strcpy (newstr, token);
    newnode->left=left;
    newnode->right=right;
    newnode->token=newstr;
    return newnode;
}
void Printtree(node* tree){
    printf("%s\n", tree->token);
    if (tree->left)
        Printtree(tree->left);
    if (tree->right)
        Printtree(tree->right);
}
int yyerror(){
    printf("ERROR\n");
    return 0;
}

和 lex 代码

%%
[0-9]+ return NUM;
\+ return PLUS;
\- return MINUS;
%%

当我试图将 yytext 更改为 $1 时编译但是当我 运行 代码和类型例如 5+6 说:(分段错误(核心转储))

使用 ubuntu 64:

lex 使用 flex 版本 lex 2.6.0 编译:

lex subProject.lex

和 yacc 使用 bison 版本 bison(GNU Bison) 3.0.4 编译:

yacc subProject.yacc

和错误制造者:

cc subProject -o y.tab.c -ll -Ly

你根本不应该在语法规则中使用 yytext。它并不总是具有您认为可能具有的价值。您应该将其保存在扫描仪的 yyunion 中:

[0-9]+ { yylval.text = strdup(yytext); return NUM; }

对于其他需要它的规则也类似,然后像这样在解析器中使用它:

| NUM {$$=mknode(, NULL, NULL);}

使用常用技术声明 YYUNION 并键入节点。