From: Mike D. Lowis Date: Mon, 5 Mar 2012 19:37:03 +0000 (-0500) Subject: Added ASTPrinter utility class for printing out arbitrary syntax trees X-Git-Url: https://git.mdlowis.com/?a=commitdiff_plain;h=0c7e778c851e2ee22ea693b8eb82b12b66c4307a;p=archive%2Fparse-utils.git Added ASTPrinter utility class for printing out arbitrary syntax trees --- diff --git a/source/visitor/astprinter/astprinter.cpp b/source/visitor/astprinter/astprinter.cpp new file mode 100644 index 0000000..e72dc60 --- /dev/null +++ b/source/visitor/astprinter/astprinter.cpp @@ -0,0 +1,41 @@ +#include "ASTPrinter.h" + +using namespace std; + +string ASTPrinter::str() +{ + return stream.str(); +} + +void ASTPrinter::beforeVisit(AST* cur, int depth) +{ +} + +void ASTPrinter::afterVisit(AST* cur, int depth) +{ + stream << endl; +} + +void ASTPrinter::beforeChildren(AST* cur, int depth) +{ + stream << "(" << cur->type() << " " << cur->text(); +} + +void ASTPrinter::afterChildren(AST* cur, int depth) +{ + stream << ")"; +} + +void ASTPrinter::beforeChild(AST* cur, int depth) +{ + stream << endl; + for(int i = 0; i< depth; i++) + { + stream << " "; + } +} + +void ASTPrinter::afterChild(AST* cur, int depth) +{ +} + diff --git a/source/visitor/astprinter/astprinter.h b/source/visitor/astprinter/astprinter.h new file mode 100644 index 0000000..e7bfda2 --- /dev/null +++ b/source/visitor/astprinter/astprinter.h @@ -0,0 +1,23 @@ +#ifndef ASTPRINTER_H +#define ASTPRINTER_H + +#include "ivisitor.h" +#include +#include + +class ASTPrinter : public IVisitor { + protected: + ostringstream stream; + public: + ASTPrinter(AST* root) : IVisitor(root) {}; + string str(); + private: + void beforeVisit(AST* cur, int depth); + void afterVisit(AST* cur, int depth); + void beforeChildren(AST* cur, int depth); + void afterChildren(AST* cur, int depth); + void beforeChild(AST* cur, int depth); + void afterChild(AST* cur, int depth); +}; + +#endif