moved to_int into pop_int; compacted second pass by removing continues and changing to else-if

This commit is contained in:
Bob Polis 2020-09-22 15:03:00 +02:00
parent a20f002341
commit e87b32d72a

View File

@ -11,13 +11,6 @@
#include <algorithm>
#include <sstream>
int to_int(const std::string& val) {
std::istringstream iss {val};
int result;
iss >> result;
return result;
}
void interpreter::reset() {
_prog.clear();
_values.clear();
@ -50,45 +43,23 @@ std::string interpreter::eval(std::istream& in, bool& done) {
// fetch next instruction
std::string code {_prog[_pc]};
// check literal int
if (std::isdigit(code[0])) {
if (std::isdigit(code[0])) { // check literal int
_values.push_back(code);
_pc++;
continue;
}
// check literal string
if (code[0] == '\\') {
} else if (code[0] == '\\' || code[0] == '>') { // check literal string or label ref
_values.push_back(code.substr(1));
_pc++;
continue;
}
// check label ref
if (code[0] == '>') {
_values.push_back(code.substr(1));
_pc++;
continue;
}
// check var assignment
if (code[0] == '=') {
} else if (code[0] == '=') { // check var assignment
_vars[code.substr(1)] = _values.back();
_values.pop_back();
_pc++;
continue;
}
// check var ref
if (code[0] == '$') {
} else if (code[0] == '$') { // check var ref
_values.push_back(_vars[code.substr(1)]);
_pc++;
continue;
}
// exec instruction
} else {
exec_instruction(code, done);
}
}
if (_values.size()) {
result = _values.back();
@ -136,9 +107,10 @@ void interpreter::exec_instruction(const std::string& code, bool& done) {
}
inline int interpreter::pop_int() {
int val {to_int(_values.back())};
_values.pop_back();
return val;
std::istringstream iss {pop_str()};
int result;
iss >> result;
return result;
}
inline std::string interpreter::pop_str() {
@ -362,7 +334,7 @@ void interpreter::ret() {
_calls.pop_back();
}
// debugging --------------------------------------------------------------
// I/O --------------------------------------------------------------------
void interpreter::inp() {
std::string val;