Skip to content

Commit

Permalink
Made traversal free
Browse files Browse the repository at this point in the history
  • Loading branch information
petermlm committed May 31, 2016
1 parent 38764e5 commit 913cc58
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
21 changes: 20 additions & 1 deletion examples/tree_traversal.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ int main(int argc, char *argv[]) {
mpc_ast_t *ast, *tree, *child, *child_sub, *ast_next;
mpc_ast_trav_t *trav;
mpc_result_t r;
int index, lb;
int index, lb, i;

mpca_lang(MPCA_LANG_PREDICTIVE,
" node : '(' <node> ',' /foo/ ',' <node> ')' | <leaf>;"
Expand Down Expand Up @@ -79,6 +79,8 @@ int main(int argc, char *argv[]) {
ast_next = mpc_ast_traverse_next(&trav);
}

mpc_ast_traverse_free(&trav);

printf("Post order tree traversal.\n");

trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_post);
Expand All @@ -92,6 +94,23 @@ int main(int argc, char *argv[]) {
ast_next = mpc_ast_traverse_next(&trav);
}

mpc_ast_traverse_free(&trav);

printf("Partial traversal.\n");

trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_post);

ast_next = mpc_ast_traverse_next(&trav);

for(i=0; i<2 && ast_next != NULL; i++) {
printf("Tag: %s; Contents: %s\n",
ast_next->tag,
ast_next->contents);
ast_next = mpc_ast_traverse_next(&trav);
}

mpc_ast_traverse_free(&trav);

/* Clean up and return */
mpc_cleanup(3, Node, Leaf, Input);
mpc_ast_delete(ast);
Expand Down
11 changes: 11 additions & 0 deletions mpc.c
Original file line number Diff line number Diff line change
Expand Up @@ -2933,6 +2933,17 @@ mpc_ast_t *mpc_ast_traverse_next(mpc_ast_trav_t **trav) {
return ret;
}

void mpc_ast_traverse_free(mpc_ast_trav_t **trav) {
mpc_ast_trav_t *n_trav;

/* Go through parents until all are free */
while(*trav != NULL) {
n_trav = (*trav)->parent;
free(*trav);
*trav = n_trav;
}
}

mpc_val_t *mpcf_fold_ast(int n, mpc_val_t **xs) {

int i, j;
Expand Down
2 changes: 2 additions & 0 deletions mpc.h
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,8 @@ mpc_ast_trav_t *mpc_ast_traverse_start(mpc_ast_t *ast,

mpc_ast_t *mpc_ast_traverse_next(mpc_ast_trav_t **trav);

void mpc_ast_traverse_free(mpc_ast_trav_t **trav);

/*
** Warning: This function currently doesn't test for equality of the `state` member!
*/
Expand Down

0 comments on commit 913cc58

Please sign in to comment.