print_tree.cpp100600 2303 13 3607 6742527220 12363 0ustar iankmosaic #include #include #include "MyTinyCParser.hpp" #include "print_tree.hpp" /* * pr_name * Print the character string associated with an ANTLR tree node. */ void print_tree::pr_name( RefAST node ) { std::string str; str = node->getText(); printf("%s ", str.c_str()); } // pr_name /* * pr_indent * Print indentation for a node. */ void print_tree::pr_indent(void) { const size_t BUFSIZE = 127; char buf[ BUFSIZE+1 ]; int i; for (i = 0; i < indent_level && i < BUFSIZE; i++) { buf[i] = ' '; } buf[i] = '\0'; printf("%s", buf ); } // pr_indent void print_tree::pr_open_angle(void) { if ( indent_level ) printf("\n"); pr_indent(); printf("<"); indent_level += INDENT; } // pr_open_angle /* * pr_close_angle * Print the ">" bracket to show the close of a tree production. */ void print_tree::pr_close_angle(Boolean first) { assert( indent_level > 0 ); indent_level -= INDENT; if (!first) { printf("\n"); pr_indent(); } printf(">"); } // pr_close_angle /* * pr_leaves * Print the leaves of an AST node */ void print_tree::pr_leaves( RefAST top ) { RefAST t; For_each_kid(t, top) { if (is_nonleaf( t )) pr_top( t ); else pr_name( t ); } } // pr_leaves /* * pr_top * Recursively print a tree (or a sub-tree) from the top down. */ void print_tree::pr_top( RefAST top ) { RefAST tmp; Boolean first = TRUE; pr_open_angle(); pr_name( top ); if (is_nonleaf( top )) { For_each_kid( tmp, top ) { if (is_nonleaf( tmp )) first = FALSE; } pr_leaves( top ); } pr_close_angle( first ); } // pr_top /* * pr_tree * Main entry point for tree print. */ void print_tree::pr_tree( RefAST top ) { RefAST t; for (t = top; t != NULL; t = t->getNextSibling()) { indent_level = 0; pr_top( t ); printf("\n"); } } // pr_tree print_tree.hpp100600 2303 13 1441 6742527213 12364 0ustar iankmosaic #ifndef _PRINT_TREE_HPP_ #define _PRINT_TREE_HPP_ /* print_tree Print an ANTLR abstract syntax tree in operator prefix form. */ typedef enum { FALSE = 0, TRUE = 1 } Boolean; #define For_each_kid(t,top) for(t=( (top && is_nonleaf(top)) ? top->getFirstChild() : (RefAST)NULL ); t; t = t->getNextSibling() ) class print_tree { private: typedef enum { INDENT = 2 } bogus; int indent_level; private: void pr_name( RefAST node ); void pr_indent(); void pr_top( RefAST top ); void pr_open_angle(void); void pr_close_angle(Boolean first); void pr_leaves( RefAST top ); Boolean is_nonleaf( RefAST node ) { Boolean rslt; rslt = (Boolean)(node->getFirstChild() != NULL); return rslt; } public: void pr_tree( const RefAST top ); }; // print_tree #endif