From e87b32d72aca15a8c13d7ed5bfb205fc9736f2c0 Mon Sep 17 00:00:00 2001 From: Bob Polis Date: Tue, 22 Sep 2020 15:03:00 +0200 Subject: [PATCH] moved to_int into pop_int; compacted second pass by removing continues and changing to else-if --- interpreter.cpp | 50 +++++++++++-------------------------------------- 1 file changed, 11 insertions(+), 39 deletions(-) diff --git a/interpreter.cpp b/interpreter.cpp index 52adab9..2da3be1 100644 --- a/interpreter.cpp +++ b/interpreter.cpp @@ -11,13 +11,6 @@ #include #include -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,44 +43,22 @@ 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; + } else { + exec_instruction(code, done); } - - // exec instruction - exec_instruction(code, done); } if (_values.size()) { @@ -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;