Include struct in the %union def with Bison/Yacc

Kyle Brandt picture Kyle Brandt · Sep 16, 2009 · Viewed 18.1k times · Source

I am trying to include a struct as part of the union with Bison, but I get an error on the 'struct node args' in %union:

parser.y:17: error: field ‘args’ has incomplete type

The Code:

struct node {
    char * val;
    struct node * next;
};

%}

%union {
    char * string;
    struct node args;
}

%token <string> CD WORD PWD EXIT

%type <args> arg_list

Anyone know what I am doing wrong?

Answer

Mark picture Mark · Feb 9, 2011

Even better, use the %code directive with the "requires" option, i.e.:

%code requires {
    struct node {
        char * val;
        struct node * next;
    };
}

%union {
    char * string;
    struct node args;
}

This will include the code in the "requires" block in the tab.h file as well as the parser source file.

From the documentation: http://www.gnu.org/software/bison/manual/html_node/Decl-Summary.html#Decl-Summary

  • requires
    • Purpose: This is the best place to write dependency code required for YYSTYPE and YYLTYPE. In other words, it's the best place to define types referenced in %union directives, and it's the best place to override Bison's default YYSTYPE and YYLTYPE definitions.