loa

Virtual machine for the Logic of Assumptions
git clone git://juanmeleiro.mat.br/loa
Log | Files | Refs

tree.c (1186B)


      1 #include <stdbool.h>
      2 #include <assert.h>
      3 
      4 #include "assoc.h"
      5 #include "tree.h"
      6 
      7 struct tree {
      8 	symbol head;
      9 	assoc *children;
     10 };
     11 
     12 bool
     13 is_leaf(tree* t)
     14 {
     15 	return (t->children == NULL);
     16 }
     17 
     18 tree*
     19 new_leaf(symbol s)
     20 {
     21 	tree *t = malloc(sizeof(tree));
     22 	t->head = s;
     23 	t->children = NULL;
     24 	return t;
     25 }
     26 
     27 tree*
     28 new_node(symbol h)
     29 {
     30 	tree *t = malloc(sizeof(tree));
     31 	t->head = h;
     32 	t->children = new_assoc();
     33 	return t;
     34 }
     35 
     36 void
     37 set_subtree(tree* t, symbol k, tree* v)
     38 {
     39 	if (t->children)
     40 		assoc_set(t->children, k, (void*) v);
     41 }
     42 
     43 tree*
     44 get_subtree(tree* t, symbol k)
     45 {
     46 	if (t->children)
     47 		return (tree*) assoc_get(t->children, k);
     48 	else
     49 		return NULL;
     50 }
     51 
     52 symbol
     53 get_head(tree* t)
     54 {
     55 	assert(t != NULL);
     56 	return t->head;
     57 }
     58 
     59 void
     60 display_tree(FILE* f, tree *t)
     61 {
     62 	if (is_leaf(t)) {
     63 		fprintf(f, "\"%s\"", repr(get_head(t)));
     64 	} else {
     65 		size_t num = get_amount_of_keys(t->children);
     66 		symbol *keys = get_keys(t->children);
     67 
     68 		fprintf(f, "{\"CONSTR\":\"%s\",", repr(get_head(t)));
     69 		fprintf(f, "\"KEYS\":{");
     70 		for (size_t i = 0; i < num; i++) {
     71 			fprintf(f, "\"%s\":", repr(keys[i]));
     72 			display_tree(f, get_subtree(t, keys[i]));
     73 			if (i < num - 1) fputc(',', f);
     74 		}
     75 		fprintf(f, "}}");
     76 
     77 	}
     78 }
     79 
     80