Add a recursive tree freeing function.
This commit is contained in:
27
src/tree.c
27
src/tree.c
@@ -1,15 +1,19 @@
|
||||
#include "tree.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
void libab_tree_free(libab_tree* tree) {
|
||||
int free_string = 0;
|
||||
int free_vector = 0;
|
||||
if(tree->variant == BASE || tree->variant == OP ||
|
||||
int _tree_has_vector(libab_tree* tree) {
|
||||
return tree->variant == BASE || tree->variant == OP ||
|
||||
tree->variant == UNARY_OP || tree->variant == BLOCK ||
|
||||
tree->variant == FUN || tree->variant == IF ||
|
||||
tree->variant == WHILE || tree->variant == DOWHILE ||
|
||||
tree->variant == FOR || tree->variant == CALL ||
|
||||
tree->variant == RETURN) {
|
||||
tree->variant == RETURN;
|
||||
}
|
||||
|
||||
void libab_tree_free(libab_tree* tree) {
|
||||
int free_string = 0;
|
||||
int free_vector = 0;
|
||||
if(_tree_has_vector(tree)) {
|
||||
free_vector = 1;
|
||||
}
|
||||
if(tree->variant == ID || tree->variant == STR || tree->variant == NUM ||
|
||||
@@ -20,3 +24,16 @@ void libab_tree_free(libab_tree* tree) {
|
||||
if(free_string) free(tree->string_value);
|
||||
if(free_vector) vec_free(&tree->children);
|
||||
}
|
||||
|
||||
int _tree_foreach_free(void* data, va_list args) {
|
||||
libab_tree_free_recursive(data);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void libab_tree_free_recursive(libab_tree* tree) {
|
||||
if(_tree_has_vector(tree)) {
|
||||
vec_foreach(&tree->children, NULL, compare_always, _tree_foreach_free);
|
||||
}
|
||||
libab_tree_free(tree);
|
||||
free(tree);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user