Re: %union in Bison

wicklund@eskimo.com (Thomas Wicklund)
17 Jan 2003 20:05:01 -0500

          From comp.compilers

Related articles
%union in Bison belgioioso@libero.it (Davide Rizzo) (2003-01-12)
Re: %union in Bison haberg@math.su.se (2003-01-17)
Re: %union in Bison j.rauser@science-factory.com (James Rauser) (2003-01-17)
Re: %union in Bison wicklund@eskimo.com (2003-01-17)
Re: %union in Bison basireddym@rediffmail.com (2003-01-25)
| List of all articles for this month |
From: wicklund@eskimo.com (Thomas Wicklund)
Newsgroups: comp.compilers
Date: 17 Jan 2003 20:05:01 -0500
Organization: http://groups.google.com/
References: 03-01-048
Keywords: yacc, C++
Posted-Date: 17 Jan 2003 20:05:01 EST

Regarding Davide Rizzo's question about Bison and %union, I've seen
this come up periodically over the years. While Bison works well with
C++ code, handling semantic information in a C++ context runs into the
problem that unions can't contain types which require constructors. A
bit of thought about how Bison handles semantic information (as an
array of the union type) shows that there's no simple answer.


The two methods I've used and heard about are:


1. Define the semantic type as a "struct" (so there's no overlapping members)
        and explicitly specify YYSTYPE, e.g. do the following manually:


            struct my_yystype {
                string str;
                int integer;
            };
            #define YYSTYPE my_yystype


        Note you must use the #define since Bison will declare its own YYSTYPE if
        one is not already #define'd. Don't use %union, just specify token types
        of "str" or "integer" as needed (Bison doesn't check token types, it relies
        on the compiler to flag any invalid values).


        For something like this example, the extra overhead of a structure isn't
        that great and it works well.


2. The second method is to make "str" a pointer in the above example. This
        requires doing some memory management.


Note that either approach is more likely to leave stuff laying around
in memory when an error occurs in the parse since destructors won't be
called at the right times.


Thomas Wicklund


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.