added "out" instruction; fixed comparison bugs by converting values to int first

This commit is contained in:
Bob Polis 2020-09-13 16:55:02 +02:00
parent bd026a21d5
commit 91d6d59c1b
2 changed files with 20 additions and 8 deletions

View File

@ -9,6 +9,7 @@
#include "interpreter.hpp"
#include <cctype>
#include <algorithm>
#include <iostream>
int to_int(const std::string& val) {
std::istringstream iss {val};
@ -120,6 +121,7 @@ void interpreter::exec_instruction(const std::string& code, bool& done) {
else if (code == "fun") fun();
else if (code == "ret") ret();
else if (code == "enl") enl();
else if (code == "out") out(); // for debugging
else throw syntax_error {code};
}
@ -318,9 +320,9 @@ void interpreter::gne() {
void interpreter::glt() {
std::string label {_stack.back()};
_stack.pop_back();
std::string val2 {_stack.back()};
int val2 {to_int(_stack.back())};
_stack.pop_back();
std::string val1 {_stack.back()};
int val1 {to_int(_stack.back())};
_stack.pop_back();
if (val1 < val2) {
_pc = _labels[label];
@ -332,9 +334,9 @@ void interpreter::glt() {
void interpreter::gle() {
std::string label {_stack.back()};
_stack.pop_back();
std::string val2 {_stack.back()};
int val2 {to_int(_stack.back())};
_stack.pop_back();
std::string val1 {_stack.back()};
int val1 {to_int(_stack.back())};
_stack.pop_back();
if (val1 <= val2) {
_pc = _labels[label];
@ -346,9 +348,9 @@ void interpreter::gle() {
void interpreter::ggt() {
std::string label {_stack.back()};
_stack.pop_back();
std::string val2 {_stack.back()};
int val2 {to_int(_stack.back())};
_stack.pop_back();
std::string val1 {_stack.back()};
int val1 {to_int(_stack.back())};
_stack.pop_back();
if (val1 > val2) {
_pc = _labels[label];
@ -360,9 +362,9 @@ void interpreter::ggt() {
void interpreter::gge() {
std::string label {_stack.back()};
_stack.pop_back();
std::string val2 {_stack.back()};
int val2 {to_int(_stack.back())};
_stack.pop_back();
std::string val1 {_stack.back()};
int val1 {to_int(_stack.back())};
_stack.pop_back();
if (val1 >= val2) {
_pc = _labels[label];
@ -382,3 +384,10 @@ void interpreter::ret() {
_pc = _calls.back();
_calls.pop_back();
}
// debugging --------------------------------------------------------------
void interpreter::out() {
std::cout << _stack.back() << '\n';
_pc++;
}

View File

@ -71,6 +71,9 @@ class interpreter {
// subroutines
void fun();
void ret();
// debugging
void out();
};
#endif // _interpreter_H_