From 0c7e778c851e2ee22ea693b8eb82b12b66c4307a Mon Sep 17 00:00:00 2001 From: "Mike D. Lowis" Date: Mon, 5 Mar 2012 14:37:03 -0500 Subject: [PATCH] Added ASTPrinter utility class for printing out arbitrary syntax trees --- source/visitor/astprinter/astprinter.cpp | 41 ++++++++++++++++++++++++ source/visitor/astprinter/astprinter.h | 23 +++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 source/visitor/astprinter/astprinter.cpp create mode 100644 source/visitor/astprinter/astprinter.h 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 -- 2.54.0