Search code examples
compiler-constructionsemanticsbisonlexical-analysis

Multiple attributes in bison


I am doing semantic analysis in bison and i want to use multiple attribute associated with a token. A related part of my code is:

%union semrec
{
    int Type;
    char *id;

}

%start prog

%token <id>  tIDENT

Here, i can only use the "id" attribute witht the tIDENT token. I also want to associate the "Type" attribute with tIDENT token. To do this, i tried the following:

 %token <id>  tIDENT
 %token <Type>  tIDENT

But it gives me a redeclaration warning for token tIDENT. I also tried the following:

 %token <id> <Type> tIDENT

It also did not work. What can i do? I think this is just a little syntactic problem.

Thank you.


Solution

  • You cannot do it this way: you have to define your %union in such a way that all the symbols that have multiple "attributes" have a struct to define all these "attributes". Something like

    %union
    {
      struct
      {
        int type;
        char *id;
      } type_id;
    }
    %type <type_id> tIDENT
    

    and use $1.type or $1.id etc.

    Note however that I very much doubt that you're doing the right thing. Chances are high that you will need an AST (Abstract Syntax Tree). You should look for information about that.