Next: , Previous: , Up: Semantics   [Contents][Index]

3.4.3 Generating the Semantic Value Type

The special value union of the %define variable api.value.type instructs Bison that the tags used with the %token and %type directives are genuine types, not names of members of YYSTYPE.

For example:

%define api.value.type union
%token <int> INT "integer"
%token <int> 'n'
%type <int> expr
%token <char const *> ID "identifier"

generates an appropriate value of YYSTYPE to support each symbol type. The name of the member of YYSTYPE for tokens than have a declared identifier id (such as INT and ID above, but not 'n') is id. The other symbols have unspecified names on which you should not depend; instead, relying on C casts to access the semantic value with the appropriate type:

/* For an "integer".  */
yylval.INT = 42;
return INT;

/* For an 'n', also declared as int.  */
*((int*)&yylval) = 42;
return 'n';

/* For an "identifier".  */
yylval.ID = "42";
return ID;

If the %define variable api.token.prefix is defined (see api.token.prefix), then it is also used to prefix the union member names. For instance, with ‘%define api.token.prefix {TOK_}’:

/* For an "integer".  */
yylval.TOK_INT = 42;
return TOK_INT;

This Bison extension cannot work if %yacc (or -y/--yacc) is enabled, as POSIX mandates that Yacc generate tokens as macros (e.g., ‘#define INT 258’, or ‘#define TOK_INT 258’).

This feature is new, and user feedback would be most welcome.

A similar feature is provided for C++ that in addition overcomes C++ limitations (that forbid non-trivial objects to be part of a union): ‘%define api.value.type variant’, see C++ Variants.

Next: , Previous: , Up: Semantics   [Contents][Index]