]> git.mdlowis.com Git - archive/parse-utils.git/commitdiff
Added ASTPrinter utility class for printing out arbitrary syntax trees
authorMike D. Lowis <mike@mdlowis.com>
Mon, 5 Mar 2012 19:37:03 +0000 (14:37 -0500)
committerMike D. Lowis <mike@mdlowis.com>
Mon, 5 Mar 2012 19:37:03 +0000 (14:37 -0500)
source/visitor/astprinter/astprinter.cpp [new file with mode: 0644]
source/visitor/astprinter/astprinter.h [new file with mode: 0644]

diff --git a/source/visitor/astprinter/astprinter.cpp b/source/visitor/astprinter/astprinter.cpp
new file mode 100644 (file)
index 0000000..e72dc60
--- /dev/null
@@ -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 (file)
index 0000000..e7bfda2
--- /dev/null
@@ -0,0 +1,23 @@
+#ifndef ASTPRINTER_H
+#define ASTPRINTER_H
+
+#include "ivisitor.h"
+#include <iostream>
+#include <sstream>
+
+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