Include struct in the %union def with Bison/Yacc
Asked Answered
L

3

21

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?

Lazarolazaruk answered 16/9, 2009 at 1:1 Comment(0)
B
31

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.
Boneyard answered 9/2, 2011 at 4:54 Comment(0)
G
16

It comes down to the lame y.tab.h output you get.

You need to fix this by ensuring that "struct node" is defined before you include y.tab.h anywhere.

To do this create a file node.h with the struct definition.

Then include node.h before y.tab.h in your parser.l file, parser.y file as well as any c files you have which include y.tab.h. This is a little annoying.

Alternatively you could change "struct node args" to "struct node* args" since you would not need to know the full type until you go to use it somewhere. Not sure if this would fit with your code.

Either one should work.

Grum answered 16/9, 2009 at 1:49 Comment(0)
E
2

Maybe simpler (I think) - used this myself:

%union {
  char   c; 
  struct {
     char name[30];
     int  type;
  } s;
}

Then, in flex you can use "yylval.s.name" , or "yylval.s.type", etc.. while in bison, instead of $$=0, $1=bla... you can now write $<s.type>$=0 , $<s.type>1=bla...

Ethel answered 23/1, 2016 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.