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