Hi,
I have the following yacc code, and need to print out the parse tree created using the newnode. I need to print the tree using a printtree function.
Can anyone help me to create the printtree function?
This is my lex code:
Code:
%%
[01] return(CONST);
[a-z] return(VARIA);
"<=>" return(EQUIV);
"=>" return(IMPLY);
"|" return(OR);
"&" return(AND);
"~" return(NOT);
[PRE] return(KEY);
[C][1-7] return(LEVEL);
[ \t\n] ;
"(" return(LBRAC);
")" return(RBRAC);
";" return(END);
"{" return(LCURL);
"}" return(RCURL);
. printf( "Unexpected: %s\n", yytext);
%%
This is my yacc code:
Code:
typedef struct node *noderef;
union nodeorval {
noderef nodeval;
int intval;
char *strval;
};
struct node {
char nodetype;
union nodeorval leftarg, rightarg;
};
#define NIL (noderef) 0
noderef newnode(char sym, noderef l, noderef r)
{
noderef new;
new = (noderef) malloc (sizeof (struct node));
new -> nodetype = sym;
new -> leftarg.nodeval = l;
new -> rightarg.nodeval = r;
return new;
};
%start task
%union {
int tokenval;
noderef nodeval;
}
%token LEVEL KEY CONST VARIA LCURL RCURL END LBRAC RBRAC
%left EQUIV
%right IMPLY
%left AND OR
%nonassoc NOT
%type <nodeval> wff expr
%%
task : taskid LCURL wfflist RCURL
| error {printf("TASK-P>Error\n");}
;
taskid : LEVEL
| KEY
| error {printf("TASK-P>Error\n");}
;
wfflist : wff wfflist
| wff
;
wff : expr END {printf("TASK-P>Success\n");
printtree($1);}
| error END {printf("TASK-P>Error\n");}
;
expr : CONST
{$$ = newnode(yytext[0],NIL,NIL);}
| VARIA
{$$ = newnode(yytext[0],NIL,NIL);}
| expr EQUIV expr
{$$ = newnode('E',$1,$3);}
| expr IMPLY expr
{$$ = newnode('I',$1,$3);}
| expr OR expr
{$$ = newnode('|',$1,$3);}
| expr AND expr
{$$ = newnode('&',$1,$3);}
| NOT expr
{$$ = newnode('~',NIL,$2);}
| LBRAC expr RBRAC
{$$ = $2;}
;
%%
/*void yyerror(char *err){
fprintf(stderr, "%s\n", err);
}
int main(void){
return yyparse();
}*/
#include "lex.yy.c"