Not able to use %union?

Peng Yu <[email protected]>
Newsgroups gmane.comp.parsers.bison.general
Message-ID <CABrM6wmG=U-Un3Qfyc+SkxD-bYZ_eZvwbtjcrZqjEiROmLPiLA@mail.gmail.com>
Hi,

I have the following toy flex code to generate a lexer.

I use rapidstring to make the string operations use and use the Boehm
garbage collector so that I don't have to always remember to release
the memory.

https://github.com/boyerjohn/rapidstring

Because I want to use the previously allocated memory, I don't want to
call "rs_init(&yylval->str)" in any action. So YYSTYPE must be a
struct instead of a union. Is it a good practice to use struct instead
of union?

Since %union cannot be used in this case, how to deal with this
scenario in bison? Thanks.

%{
#define TOK_NUMBER 1000
#define TOK_STRING 1001
#include <gc.h>
#define RS_MALLOC GC_MALLOC
#define RS_REALLOC GC_REALLOC
#define RS_FREE GC_FREE
#include <rapidstring.h>
typedef struct {
    int num;
    rapidstring str;
} YYSTYPE;
%}
%option nodefault noinput nounput
%option reentrant bison-bridge

%%
[[:digit:]]+                    yylval->num=atoi(yytext); return TOK_NUMBER;
[[:alpha:]]+                    {
rs_cpy(&yylval->str, yytext);
return TOK_STRING;
}
.|\n
%%
int main() {
    GC_INIT();

    yyscan_t scanner;
    yylex_init(&scanner);
    int tok;
    YYSTYPE lval;
    rs_init(&lval.str);
    while((tok = yylex(&lval, scanner))) {
        if(tok == TOK_NUMBER) {
            printf("tok = %d, yylval= %d\n", tok,
                   yyget_lval(scanner)->num);
        }
        else if(tok == TOK_STRING) {
            printf("tok = %d, yylval= %s\n", tok,
                   rs_data(&yyget_lval(scanner)->str));
        }
    }
    yylex_destroy(scanner);
    return 0;
}


-- 
Regards,
Peng

_______________________________________________
[email protected] https://lists.gnu.org/mailman/listinfo/help-bison
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.