diff --git a/src/vm/stack.cc b/src/vm/stack.cc index 1a298f0..95908f2 100644 --- a/src/vm/stack.cc +++ b/src/vm/stack.cc @@ -16,7 +16,7 @@ void Stack::push(Value const& value) Value Stack::pop() { - if (stack_.size() <= fps_.size()) + if (stack_.size() <= fps_.top()) throw VMStackUnderflow(); Value v = stack_.back(); @@ -58,4 +58,15 @@ void Stack::pop_fp() fps_.pop(); } +std::string Stack::debug() const +{ + if (stack_.empty()) + return "empty"; + + std::string out; + for (size_t i = 0; i < stack_.size(); ++i) + out += "[" + stack_.at(i).to_string() + "] "; + return out; +} + } // tyche diff --git a/src/vm/stack.hh b/src/vm/stack.hh index f42990b..775e902 100644 --- a/src/vm/stack.hh +++ b/src/vm/stack.hh @@ -23,6 +23,8 @@ public: [[nodiscard]] size_t fp_level() const { return fps_.size(); } + [[nodiscard]] std::string debug() const; + private: std::vector stack_; std::stack fps_; diff --git a/src/vm/tests.cc b/src/vm/tests.cc index 47b29fe..98f809e 100644 --- a/src/vm/tests.cc +++ b/src/vm/tests.cc @@ -84,7 +84,9 @@ TEST(VM, BasicCode) VM vm; vm.load_bytecode(std::move(ba)); + printf("%s\n", vm.debug_stack().c_str()); vm.call(0); + printf("%s\n", vm.debug_stack().c_str()); int32_t result = vm.to_integer(-1); ASSERT_EQ(result, 5); diff --git a/src/vm/value.cc b/src/vm/value.cc index b051120..40d4f91 100644 --- a/src/vm/value.cc +++ b/src/vm/value.cc @@ -15,4 +15,15 @@ Type Value::type() const }, value_); } +std::string Value::to_string() const +{ + return std::visit(overloaded { + [](std::monostate) { return std::string("nil"); }, + [](int32_t i) { return std::to_string(i); }, + [](float f) { return std::to_string(f); }, + [](std::string const& s) { return s; }, + [](Function const& f) { return "@" + std::to_string(f.f_id); } + }, value_); +} + } diff --git a/src/vm/value.hh b/src/vm/value.hh index 4b7ef4a..7aed983 100644 --- a/src/vm/value.hh +++ b/src/vm/value.hh @@ -33,6 +33,8 @@ public: [[nodiscard]] std::string as_string() const { return std::get(value_); } [[nodiscard]] FunctionId as_function_id() const { return std::get(value_).f_id; } + [[nodiscard]] std::string to_string() const; + private: using Internal = std::variant; Internal value_; diff --git a/src/vm/vm.hh b/src/vm/vm.hh index ef8554b..151dc65 100644 --- a/src/vm/vm.hh +++ b/src/vm/vm.hh @@ -17,6 +17,8 @@ public: void push_integer(int32_t value); + [[nodiscard]] std::string debug_stack() const { return stack_.debug(); } + private: void run_until_return(); void step();