summaryrefslogtreecommitdiff
path: root/tree.c
blob: 00d5eb94fb0433e03e58628bafdd099db00df8c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "tree.h"

int strichar(const char *str, char c){
  for(int i=0; str[i]!='\0';i++){
    if(str[i] == c) return i;
  }
  return -1; //char not found
}
const char ops[] = {'+','*','!'}; //ordem inversa
const int opsize = sizeof(ops)/sizeof(char);
node * parse(char *str) { //expects a string with no whitespace

  int j,i;
  for(i=0; i<opsize; i++){
    j=strichar(str,ops[i]);
    if(j>=0) break;
  }

  node *this = (node *)malloc(sizeof(node));

  if(j<0) {
    this->type = LTTR;
    this->el = str[0];
  }

  else{
    this->el = ops[i];
    if(i==2) {
      this->type = UNOP;
      this->child[0] = parse(str+j+1);
    }
    else {
      str[j] = '\0';
      this->type = BIOP;
      this->child[0] = parse(str);
      this->child[1] = parse(str+j+1);
    }
  }
  return this;
}

void fprintTree(FILE *stream, node *root, int level) {
  if (root == NULL)
    return;

  if (level) {
    for (int i = 1; i < level; i++) {
      fprintf(stream, "│  ");
    }
    fprintf(stream, "├─ ");
  }
  fprintf(stream, "%c\n", root->el);
  for (int i = 0; i < 2; i++) {
    if (root->child[i] != NULL) {
      fprintTree(stream, root->child[i], level + 1);
    }
  }
}

void printTree(node *root, int level) {
  fprintTree(stdout, root, level);
}

void free_node(node *n) {
  if (n->lhs) free_node(n->lhs);
  if (n->rhs) free_node(n->rhs);
  free(n);
}

char eval_tree(node *root, uint32_t alph_bools) {
  switch (root->type) {
    case BIOP: {
      char lhs = eval_tree(root->lhs, alph_bools);
      char rhs = eval_tree(root->rhs, alph_bools);
      switch (root->el) {
        case '+': return lhs || rhs;
        case '*': return lhs && rhs;
        default: fprintf(stderr, "%s: unknown binary operation \"%c\"\n", __func__, root->el);
      }
    }
    case UNOP: {
      // We only have the not, FIXME if more are added
      return !eval_tree(root->value, alph_bools);
    }
    case LTTR: {
      char alph_pos = root->el - 'a';
      return (alph_bools & (1 << alph_pos)) > 0;
    }
  }
}