Skip to content

Commit

Permalink
Made example for tree traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
petermlm committed Apr 19, 2016
1 parent 719ca68 commit e99b357
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
29 changes: 28 additions & 1 deletion examples/tree_traversal.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ int main(int argc, char *argv[]) {
mpc_parser_t *Input = mpc_new("input");
mpc_parser_t *Node = mpc_new("node");
mpc_parser_t *Leaf = mpc_new("leaf");
mpc_ast_t *ast, *tree, *child, *child_sub;
mpc_ast_t *ast, *tree, *child, *child_sub, *ast_next;
mpc_ast_trav_t *trav;
mpc_result_t r;
int index, lb;

Expand Down Expand Up @@ -65,6 +66,32 @@ int main(int argc, char *argv[]) {
child_sub = mpc_ast_get_child_lb(child, "node|leaf|regex", lb);
}

/* Traversal */
printf("Pre order tree traversal.\n");
trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_pre);

ast_next = mpc_ast_traverse_next(&trav);

while(ast_next != NULL) {
printf("Tag: %s; Contents: %s\n",
ast_next->tag,
ast_next->contents);
ast_next = mpc_ast_traverse_next(&trav);
}

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

trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_post);

ast_next = mpc_ast_traverse_next(&trav);

while(ast_next != NULL) {
printf("Tag: %s; Contents: %s\n",
ast_next->tag,
ast_next->contents);
ast_next = mpc_ast_traverse_next(&trav);
}

/* Clean up and return */
mpc_cleanup(3, Node, Leaf, Input);
mpc_ast_delete(ast);
Expand Down
8 changes: 8 additions & 0 deletions mpc.c
Original file line number Diff line number Diff line change
Expand Up @@ -2841,6 +2841,10 @@ mpc_ast_trav_t *mpc_ast_traverse_start(mpc_ast_t *ast,
}

break;

default:
/* Unreachable, but compiler complaints */
break;
}

return trav;
Expand Down Expand Up @@ -2920,6 +2924,10 @@ mpc_ast_t *mpc_ast_traverse_next(mpc_ast_trav_t **trav) {

*trav = n_trav;
}

default:
/* Unreachable, but compiler complaints */
break;
}

return ret;
Expand Down

0 comments on commit e99b357

Please sign in to comment.