%{ #include <ctype.h> #include <stdio.h> #include <type.h> tNode *buildNumber(int number) { tNode *ptr; ptr = (tNode*)malloc(sizeof(tNode)); (*ptr).type = t_number; (*ptr).number = number; return ( ptr ); } tNode *buildId(char id) { tNode *ptr; ptr = (tNode*)malloc(sizeof(tNode)); ptr->type = t_id; ptr->id = id; return ( ptr ); } tNode *buildOperator(tNodeType t, tNode *l, tNode *r) { tNode *ptr; ptr = (tNode*)malloc(sizeof(tNode)); ptr->type = t; ptr->left = l; ptr->right = r; return ( ptr ); } void printTree(tNode *node) { switch (node->type) { case t_number : { printf("%d", node->number); break; } case t_id : { printf("%c", node->id); break; } case t_times : { printf("(* "); printTree(node->left); printf(" "); printTree(node->right); printf(")"); break; } case t_plus : { printf("(+ "); printTree(node->left); printf(" "); printTree(node->right); printf(")"); break; } } } void freeTree(tNode *node) { if ((node->type == t_number)||(node->type == t_id)) { free(node); } else { freeTree(node->left); freeTree(node->right); free(node); } } void yyerror(const char *str) { fprintf(stderr,"error: %s\n",str); } int yywrap() { return 1; } int main() { yyparse(); return 0; } %} %union { int intvalue; char charvalue; tNode *nodevalue; }; %token TOK_NUMBER TOK_ID TOK_PLUS TOK_TIMES TOK_LP TOK_RP %type <intvalue> TOK_NUMBER %type <charvalue> TOK_ID %type <nodevalue> expr term factor %% line : line expr '\n' { printTree( $2 ); printf("\n"); freeTree( $2 ); } | /* empty word */ ; expr : expr TOK_PLUS term { $$ = buildOperator(t_plus, $1, $3 ); } | term {$$ = $1; } ; term : factor TOK_TIMES term {$$ = buildOperator(t_times, $1, $3); } | factor {$$ = $1; } ; factor : TOK_LP expr TOK_RP {$$ = $2; } | TOK_ID {$$ = buildId( $1 ); } | TOK_NUMBER {$$ = buildNumber( $1 ); } ; %%