Please bear with me as this is the first time I've posted on a forum so I'm sorry if I break any rules.
I am writing a compiler for a C-like language and I'm having a bit of trouble and can't see where I'm going wrong. Whenever I test it with variable declaration, my variables won't declare. I've narrowed down the problem in that whenever I try to compile 'int Var1;', it declares a variable called 'Var1;' instead of 'Var1'.
It does the same when compiling multiple integers. It first declares 'Var1, Var2;' then 'Var2;'. I know everything is being tokenised by the lexer just fine, and when I try and insert printf statements in the parser, the rule 'variable_list -> variable' runs just fine, it's where the 'goal -> int variable_list ;' occurs that the problem is. I will post some of my code below, along with some typedefs from my headers, I would really appreciate some help ASAP.
Code:
typedef struct token
{
struct token *next;
struct token *listnext;
char *lexeme;
int type;
int ivalue;
double dvalue;
int declared;
} TOKEN;
typedef struct tree
{
char *root;
char *lexeme;
int type;
int ivalue;
double dvalue;
int branches;
struct tree *branch1;
struct tree *branch2;
struct tree *branch3;
struct tree *branch4;
struct tree *branch5;
struct tree *branch6;
struct tree *branch7;
} TREE;
goal : INT variable_list SCOLON
{ $$=(TREE *)safe_malloc(sizeof(TREE));
$$->root="goal";
$$->branches=3;
$$->branch1=(TREE *)safe_malloc(sizeof(TREE));
$$->branch1->root="int";
$$->branch1->branches=0;
$$->branch2=$2;
$$->branch3=(TREE *)safe_malloc(sizeof(TREE));
$$->branch3->root=";";
$$->branch3->branches=0;
while(var_list)
{
if(var_list->type==TYPENIL)
{
var_list->declared=1;
var_list->type=TYPEINT;
var_list->ivalue=0;
}
else if(var_list->type==TYPEINT) printf("%s already declared\n",var_list->lexeme);
else printf("%s already declared in another type\n",var_list->lexeme);
var_list=var_list->listnext;
}
var_list=(TOKEN *)safe_malloc(sizeof(TOKEN)); }
variable_list : T_VRBL
{ $$=(TREE *)safe_malloc(sizeof(TREE));
$$->root="variable_list";
$$->type=$1->type;
$$->branches=1;
$$->branch1=(TREE *)safe_malloc(sizeof(TREE));
$$->branch1->root="variable";
$$->branch1->branches=1;
$$->branch1->branch1=(TREE *)safe_malloc(sizeof(TREE));
$$->branch1->branch1->root=$1->lexeme;
$$->branch1->branch1->branches=0;
$1->listnext=var_list;
var_list=$1; }
I have declared var_list as a TOKEN * in my header, and my makevar function turns variables into a TOKEN * with the variable name as the lexeme and the type as TYPENIL (which is defined as 0, TYPEINT is 1 and TYPEDBL is 2). Please help.