Infinity Calculator implementation for Assignment 2 in Computer Organization.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

#### 69 lines 1.7 KiB Raw Permalink Blame History

 `#include "expr.h"` `expr_t *bubble_expr(expr_t *t, expr_t *n) {` ` // Is the opcode at the current node in the tree of a higher priority?` ` if (t->opcode > n->opcode || t->flags & EXFLAG_PAREN) {` ` // Yes, shift the tree downwards.` ` n->left.expr = t;` ` n->par = t->par;` ` t->par = n;` ` n->flags |= EXFLAG_LEXP;` ` return n;` ` }` ` // Or is the current node the initial node?` ` else if (t->opcode == EXPR_NULL) {` ` n->left.data = t->right.data;` ` n->flags |= t->flags & EXFLAG_RNEG ? EXFLAG_LNEG : 0;` ` free(t);` ` return n;` ` }` ` else {` ` // No, descend rightward. Check if it is a leaf or another node first.` ` if (t->flags & EXFLAG_REXP) {` ` // There is an expression to the right.` ` t->right.expr = bubble_expr(t->right.expr, n);` ` return t;` ` }` ` else {` ` // There is a leaf to the right.` ` n->left.data = t->right.data;` ` n->par = t;` ` t->right.expr = n;` ` t->flags |= EXFLAG_REXP;` ` n->flags |= t->flags & EXFLAG_RNEG ? EXFLAG_LNEG : 0;` ` t->flags &= ~EXFLAG_RNEG;` ` return t;` ` }` ` }` `}` ``` ``` ``` ``` `void print_expr_tree(expr_t *t, int depth) {` ` fprintf(stderr, "%d (0x%X)\n", t->opcode, t->flags);` ` for(register int i = depth; i > 0; --i) fputs(" ", stderr);` ` fprintf(stderr, "├ ");` ` if (t->flags & EXFLAG_LEXP) {` ` print_expr_tree(t->left.expr, depth + 1);` ` }` ` else {` ` fprintf(stderr, "%hhu\n", t->left.data);` ` }` ` for(register int i = depth; i > 0; --i) fputs(" ", stderr);` ` fprintf(stderr, "└ ");` ` if (t->flags & EXFLAG_REXP) {` ` print_expr_tree(t->right.expr, depth + 1);` ` }` ` else {` ` fprintf(stderr, "%hhu\n", t->right.data);` ` }` `}` ``` ``` `void destroy_expr(expr_t *e) {` ` if (e->flags & EXFLAG_LEXP) {` ` destroy_expr(e->left.expr);` ` }` ` if (e->flags & EXFLAG_REXP) {` ` destroy_expr(e->right.expr);` ` }` ` free(e);` ```} ```