I'm doing an exercise using Yacc and Lex. The exercise is this:
After created and compiled file .y and .lex i have no error with these 2 commands:
bison -vd -o parser.c es.y
flex es.lex
After these i compile the parser.c with:
gcc -g -c parser.c
and i have these errors:
In function yyparse:
parser.c:1304: error: incompatible types in assignment
parser.c:1334: error: incompatible types in assignment
parser.c:1436: error: incompatible types in assignment
parser.c:1576: error: incompatible types in assignment
and other warnings. My lex file is this:
%{
#include "parser.h"
#include "def.h"
Value lexval;
%}
%option noyywrap
delimiter [ \t\n]
spacing {delimiter}+
digit [0-9]
num {digit}+
id [a-zA-Z]+
sugar [()*+=;]
%%
{spacing} ;
{sugar} {return(yytext[0]);}
if {return(IF);}
else {return(ELSE);}
then {return(THEN);}
end {return(END);}
write {return(WRITE);}
{id} {lexval.name = newstring(yytext); return(ID);}
{num} {lexval.val=atoi(yytext); return(NUM);}
. {return(ERROR);}
%%
char *newstring(char *s)
{
char *p;
p = malloc(sizeof(strlen(s)+1));
strcpy(p, s);
return(p);
}
my yacc file is:
%{
#include "def.h"
#define YYSTYPE struct{char *name; int val;}
#define NIL -1
extern Value lexval;
struct SymbTab{char label[30];int value;};
struct SymbTab tab[1000];
int val;
int size=0;
%}
%token ID NUM IF THEN ELSE END WRITE ERROR
%%
program : stat_list
;
stat_list : stat ';' stat_list
| stat
;
stat : assign_stat
| write_stat
;
assign_stat : ID {$$.name = lexval.name;} '=' expr {assign($2.name, $4.val);}
;
expr : expr '+' term {$$.val = $1.val + $3.val;}
| term {$$.val = $1.val;}
;
term : term '*' factor {$$.val = $1.val * $3.val;}
| factor {$$.val = $1.val;}
;
factor : '(' expr ')' {$$.val = $2.val;}
| if_expr {$$.val = $1.val;}
| ID {if((val =lookup(lexval.name)) == NIL) error(); else $$.val = val;}
| NUM {$$.val = lexval.val;}
;
if_expr : IF expr THEN expr ELSE expr END {$$.val = ($2.val ? $4.val : $6.val);}
;
write_stat : WRITE expr {printf("%d\n", $2.val);}
;
%%
int isPresent(char *lab)
{
int i;
for(i=0; i<size; i++)
if(strcmp(tab[i].label,lab)==0)
return i;
return -1000;
}
void assign(char *l,int n)
{
if(isPresent(l)==-1000)
{
strcpy(tab[size].label,l);
tab[size].value=n;
size++;
}
else
tab[isPresent(l)].value=n;
}
int lookup(char *lab)
{
int i;
for(i=0; i<size; i++)
if(strcmp(tab[i].label,lab)==0)
return tab[i].value;
return NIL;
}
void error(){ fprintf(stderr, "Syntax error\n"); }
int main(){ yyparse(); return 0; }
and my def.h is:
#include <stdio.h>
#include <stdlib.h>
char *newstring(char*),
*strcpy(char*, const char*);
void error(),assign(char *l,int n);
int lookup(char *lab),isPresent(char *lab),yylex(),main();
typedef union
{
int val;
char *name;
} Value;
I don't know how to resolve the errors that i get in parser.c