How to Implement Type Checking in Yacc/Bison and C?

  • Thread starter Thread starter -EquinoX-
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 4K views
-EquinoX-
Messages
561
Reaction score
1
Ok, so first I want to do a type checking to my yacc code. The partial code I have is below:

What must I add to the code so that I can access $1.type? I already defined:

typedef struct Type{
int type;
} Type

%union{
int typ;
}

%type <typ> expr

However it still doesn't work


Code:
expr   : '-' expr %prec UNARY {$$ = -$2}
       | '!' expr %prec UNARY {$$ = !$2 }
       | expr '+' expr { 
          if ($1.type != INTEGER || $3.type != INTEGER)
          {
                fprintf(stderr, "Invalid type for addition, must be an integer\n");
          }
          else
                 $$.type = INTEGER;
        }
       | expr '-' expr {
          if ($1.type != INTEGER || $3.type != INTEGER)
          {
                fprintf(stderr, "Invalid type for substraction, must be an integer\n");
          }
          else
                 $$.type = INTEGER;
        }
       | expr '*' expr { 
          if ($1.type != INTEGER || $3.type != INTEGER)
          {
                fprintf(stderr, "Invalid type for multiplication, must be an integer\n");
          }
          else
                 $$.type = INTEGER;
        }
       | expr '/' expr { 
          if ($1.type != INTEGER || $3.type != INTEGER)
          {
                fprintf(stderr, "Invalid type for division, must be an integer\n");
          }
          else
                 $$.type = INTEGER;
        }
       | expr EQ expr 
       | expr NE expr
       | expr LE expr
       | expr '<' expr
       | expr GE expr
       | expr '>' expr
       | expr AND_OP expr
       | expr OR_OP expr
       | ID opt_idexpr
       | '(' expr ')'
        | '(' error {fprintf(stderr, "Missing expression after '(' \n");}
       | INTCON {
                  $1.type = INTEGER;
                  }
       | CHARCON {
                  $1.type = CHARMARK;
                  }
       | STRINGCON {
                $1.type = STRINGMARK;
                  } 
        
;


All I want to do here is so that I can do $1.type or $2.type, so therefore I know what type is $1 or $2 and the type is basically something that I have defined in top of the file, something like:

#define INTEGER 1
#define CHAR 2
 
Physics news on Phys.org
When you create %union, it's your yylval variable in lex. Hence when your make actions for the regular expressions in lex you can access the type as yylval.type.
The $'s are the parts of your recursive tree, for i.e.
S:EXPR ',' EXPR2
$1 = EXPR
$2 = ,
$3 = EXPR2
$$ = S

you receive those from lex not from yacc.