help-bison
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Not able to use %union?


From: Peng Yu
Subject: Not able to use %union?
Date: Sun, 17 Feb 2019 21:37:26 -0600

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



reply via email to

[Prev in Thread] Current Thread [Next in Thread]