From 841c2f15e506fe9153ee32dc39eb9a0bdab480d8 Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Sat, 17 Feb 2018 12:55:50 -0800 Subject: [PATCH] Add function to free tree nodes. --- CMakeLists.txt | 2 +- include/tree.h | 8 ++++++++ src/tree.c | 22 ++++++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 src/tree.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 03c98d1..d21fff8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ project(libabacus) add_compile_options(-pedantic -Wall) -add_library(abacus STATIC src/lexer.c src/util.c src/table.c src/parser.c src/libabacus.c) +add_library(abacus STATIC src/lexer.c src/util.c src/table.c src/parser.c src/libabacus.c src/tree.c) add_executable(libabacus src/main.c) add_subdirectory(external/liblex) diff --git a/include/tree.h b/include/tree.h index 0ce7ebb..f9990c2 100644 --- a/include/tree.h +++ b/include/tree.h @@ -73,4 +73,12 @@ struct libab_tree_s { typedef enum libab_tree_variant_e libab_tree_variant; typedef struct libab_tree_s libab_tree; +/** + * Frees the given tree, using its + * variant as a hint as to what + * variables need to be freed. + * @param tree the tree to free. + */ +void libab_tree_free(libab_tree* tree); + #endif diff --git a/src/tree.c b/src/tree.c new file mode 100644 index 0000000..70f10d7 --- /dev/null +++ b/src/tree.c @@ -0,0 +1,22 @@ +#include "tree.h" +#include + +void libab_tree_free(libab_tree* tree) { + int free_string = 0; + int free_vector = 0; + if(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) { + free_vector = 1; + } + if(tree->variant == ID || tree->variant == STR || tree->variant == NUM || + tree->variant == KW || tree->variant == OP || tree->variant == UNARY_OP || + tree->variant == FUN || tree->variant == CALL) { + free_string = 1; + } + if(free_string) free(tree->string_value); + if(free_vector) vec_free(&tree->children); +}