summaryrefslogtreecommitdiff
path: root/graphs/cpp/visitor/compute_visitor.cc
diff options
context:
space:
mode:
Diffstat (limited to 'graphs/cpp/visitor/compute_visitor.cc')
-rw-r--r--graphs/cpp/visitor/compute_visitor.cc62
1 files changed, 62 insertions, 0 deletions
diff --git a/graphs/cpp/visitor/compute_visitor.cc b/graphs/cpp/visitor/compute_visitor.cc
new file mode 100644
index 0000000..1e4e6dd
--- /dev/null
+++ b/graphs/cpp/visitor/compute_visitor.cc
@@ -0,0 +1,62 @@
+//
+// Created by martial.simon on 2/27/25.
+//
+
+#include "compute_visitor.hh"
+
+#include <stdexcept>
+
+#include "add.hh"
+#include "div.hh"
+#include "leaf.hh"
+#include "mul.hh"
+#include "sub.hh"
+void visitor::ComputeVisitor::visit(const tree::Tree& e)
+{
+ Visitor::visit(e);
+ value_ = get_value();
+}
+void visitor::ComputeVisitor::visit(const tree::Node& e)
+{
+ visit(*e.get_lhs());
+ visit(*e.get_rhs());
+ value_ = get_value();
+}
+void visitor::ComputeVisitor::visit(const tree::AddNode& e)
+{
+ visit(*e.get_lhs());
+ int lhs = get_value();
+ Visitor::visit(*e.get_rhs());
+ value_ = lhs + get_value();
+}
+void visitor::ComputeVisitor::visit(const tree::SubNode& e)
+{
+ visit(*e.get_lhs());
+ int lhs = get_value();
+ Visitor::visit(*e.get_rhs());
+ value_ = lhs - get_value();
+}
+void visitor::ComputeVisitor::visit(const tree::MulNode& e)
+{
+ visit(*e.get_lhs());
+ int lhs = get_value();
+ Visitor::visit(*e.get_rhs());
+ value_ = lhs * get_value();
+}
+void visitor::ComputeVisitor::visit(const tree::DivNode& e)
+{
+ visit(*e.get_lhs());
+ int lhs = get_value();
+ visit(*e.get_rhs());
+ if (get_value() == 0)
+ throw std::overflow_error{ "Divide by zero exception" };
+ value_ = lhs / get_value();
+}
+void visitor::ComputeVisitor::visit(const tree::Leaf& e)
+{
+ value_ = std::stoi(e.get_value());
+}
+int visitor::ComputeVisitor::get_value()
+{
+ return value_;
+}