diff --git a/packToken.cpp b/packToken.cpp index 7114e18..1687d8f 100644 --- a/packToken.cpp +++ b/packToken.cpp @@ -17,6 +17,18 @@ packToken& packToken::operator=(double t) { return *this; } +packToken& packToken::operator=(const char* t) { + if(base) delete base; + base = new Token(t, STR); + return *this; +} + +packToken& packToken::operator=(const std::string& t) { + if(base) delete base; + base = new Token(t, STR); + return *this; +} + packToken& packToken::operator=(const packToken& t) { if(base) delete base; if(t.base) { @@ -49,16 +61,65 @@ std::ostream& operator<<(std::ostream &os, const packToken& t) { return os << t.str(); } +packToken& packToken::operator[](const std::string& key){ + if(!base || base->type != MAP) { + throw bad_cast( + "The Token is not a map!"); + } + return (*static_cast*>(base)->val)[key]; +} +const packToken& packToken::operator[](const std::string& key) const { + if(!base || base->type != MAP) { + throw bad_cast( + "The Token is not a map!"); + } + return (*static_cast*>(base)->val)[key]; +} +packToken& packToken::operator[](const char* key){ + if(!base || base->type != MAP) { + throw bad_cast( + "The Token is not a map!"); + } + return (*static_cast*>(base)->val)[key]; +} +const packToken& packToken::operator[](const char* key) const { + if(!base || base->type != MAP) { + throw bad_cast( + "The Token is not a map!"); + } + return (*static_cast*>(base)->val)[key]; +} + double packToken::asDouble() const { - if(base->type != NUM || !base) { + if(!base || base->type != NUM) { throw bad_cast( "The Token is not a number!"); } return static_cast*>(base)->val; } +std::string packToken::asString() const { + if(!base || + (base->type != STR && base->type != VAR && base->type != OP)) { + throw bad_cast( + "The Token is not a string!"); + } + return static_cast*>(base)->val; +} + +TokenMap_t* packToken::asMap() const { + if(!base || base->type != MAP) { + throw bad_cast( + "The Token is not a map!"); + } + return static_cast*>(base)->val; +} + std::string packToken::str() const { std::stringstream ss; + TokenMap_t* tmap; + TokenMap_t::iterator it; + if(!base) return "undefined"; switch(base->type) { case NONE: @@ -70,6 +131,18 @@ std::string packToken::str() const { case NUM: ss << asDouble(); return ss.str(); + case STR: + return "\"" + asString() + "\""; + case MAP: + tmap = static_cast*>(base)->val; + if(tmap->size() == 0) return "{}"; + ss << "{"; + for(it = tmap->begin(); it != tmap->end(); ++it) { + ss << (it == tmap->begin() ? "" : ","); + ss << " \"" << it->first << "\": " << it->second.str(); + } + ss << " }"; + return ss.str(); default: return "unknown_type"; } diff --git a/packToken.h b/packToken.h index ab30072..b0a4829 100644 --- a/packToken.h +++ b/packToken.h @@ -14,14 +14,25 @@ public: packToken(C c, tokType type) : base(new Token(c, type)) {} packToken(int d) : base(new Token(d, NUM)) {} packToken(double d) : base(new Token(d, NUM)) {} + packToken(const char* s) : base(new Token(s, STR)) {} + packToken(const std::string& s) : base(new Token(s, STR)) {} + packToken(TokenMap_t* tmap) : base(new Token(tmap, MAP)) {} ~packToken(){ if(base) delete base; } packToken& operator=(int t); packToken& operator=(double t); + packToken& operator=(const char* t); + packToken& operator=(const std::string& t); TokenBase* operator->() const; bool operator==(const packToken& t) const; + packToken& operator[](const std::string& key); + packToken& operator[](const char* key); + const packToken& operator[](const std::string& key) const; + const packToken& operator[](const char* key) const; double asDouble() const; + std::string asString() const; + TokenMap_t* asMap() const; std::string str() const; }; diff --git a/shunting-yard.cpp b/shunting-yard.cpp index cfbad39..a8ad50e 100644 --- a/shunting-yard.cpp +++ b/shunting-yard.cpp @@ -9,28 +9,58 @@ #include #include "shunting-yard.h" +#include "shunting-yard-exceptions.h" OppMap_t calculator::buildOpPrecedence() { OppMap_t opp; // Create the operator precedence map based on C++ default // precedence order as described on cppreference website: - // http://en.cppreference.com/w/c/language/operator_precedence - opp["^"] = 2; - opp["*"] = 3; opp["/"] = 3; opp["%"] = 3; - opp["+"] = 4; opp["-"] = 4; - opp["<<"] = 5; opp[">>"] = 5; - opp["<"] = 6; opp["<="] = 6; opp[">="] = 6; opp[">"] = 6; - opp["=="] = 7; opp["!="] = 7; - opp["&&"] = 11; - opp["||"] = 12; - opp["("] = 16; + // http://en.cppreference.com/w/cpp/language/operator_precedence + opp["[]"] = 2; opp["."] = 2; + opp["^"] = 3; + opp["*"] = 5; opp["/"] = 5; opp["%"] = 5; + opp["+"] = 6; opp["-"] = 6; + opp["<<"] = 7; opp[">>"] = 7; + opp["<"] = 8; opp["<="] = 8; opp[">="] = 8; opp[">"] = 8; + opp["=="] = 9; opp["!="] = 9; + opp["&&"] = 13; + opp["||"] = 14; + opp["("] = 17; opp["["] = 17; return opp; } // Builds the opPrecedence map only once: OppMap_t calculator::_opPrecedence = calculator::buildOpPrecedence(); +// Check for unary operators and "convert" them to binary: +void calculator::handle_unary(const std::string& str, + TokenQueue_t& rpnQueue, bool& lastTokenWasOp, + OppMap_t& opPrecedence) { + if (lastTokenWasOp) { + // Convert unary operators to binary in the RPN. + if (!str.compare("-") || !str.compare("+")) { + rpnQueue.push(new Token(0, NUM)); + } else { + throw std::domain_error( + "Unrecognized unary operator: '" + str + "'."); + } + } +} + +// Consume operators with precedence >= than op then add op +void calculator::handle_op(const std::string& str, + TokenQueue_t& rpnQueue, + std::stack& operatorStack, + OppMap_t& opPrecedence) { + while (!operatorStack.empty() && + opPrecedence[str] >= opPrecedence[operatorStack.top()]) { + rpnQueue.push(new Token(operatorStack.top(), OP)); + operatorStack.pop(); + } + operatorStack.push(str); +} + #define isvariablechar(c) (isalpha(c) || c == '_') TokenQueue_t calculator::toRPN(const char* expr, TokenMap_t* vars, OppMap_t opPrecedence) { @@ -48,6 +78,18 @@ TokenQueue_t calculator::toRPN(const char* expr, rpnQueue.push(new Token(digit, NUM)); expr = nextChar; lastTokenWasOp = false; + } else if(isvariablechar(*expr) && lastTokenWasOp + && operatorStack.size() > 0 && !operatorStack.top().compare(".")) { + // If it is a member access key (e.g. `map.name`) + // parse it and add to the output queue. + std::stringstream ss; + while( isvariablechar(*expr ) || isdigit(*expr) ) { + ss << *expr; + ++expr; + } + + rpnQueue.push(new Token(ss.str(), STR)); + lastTokenWasOp = false; } else if (isvariablechar(*expr )) { // If the function is a variable, resolve it and // add the parsed number to the output queue. @@ -81,6 +123,28 @@ TokenQueue_t calculator::toRPN(const char* expr, rpnQueue.push(new Token(key, VAR)); } + lastTokenWasOp = false; + } else if(*expr == '\'' || *expr == '"') { + // If it is a string literal, parse it and + // add to the output queue. + char quote = *expr; + + ++expr; + std::stringstream ss; + while(*expr && *expr != quote && *expr != '\n') { + if(*expr == '\\') ++expr; + ss << *expr; + ++expr; + } + + if(*expr != quote) { + std::string squote = (quote == '"' ? "\"": "'"); + throw syntax_error( + "Expected quote (" + squote + + ") at end of string declaration: " + squote + ss.str() + "."); + } + ++expr; + rpnQueue.push(new Token(ss.str(), STR)); lastTokenWasOp = false; } else { // Otherwise, the variable is an operator or paranthesis. @@ -89,6 +153,14 @@ TokenQueue_t calculator::toRPN(const char* expr, operatorStack.push("("); ++expr; break; + case '[': + // This counts as a bracket and as an operator: + handle_unary("[]", rpnQueue, lastTokenWasOp, opPrecedence); + handle_op("[]", rpnQueue, operatorStack, opPrecedence); + // Add it as a bracket to the op stack: + operatorStack.push("["); + ++expr; + break; case ')': while (operatorStack.top().compare("(")) { rpnQueue.push(new Token(operatorStack.top(), OP)); @@ -97,6 +169,14 @@ TokenQueue_t calculator::toRPN(const char* expr, operatorStack.pop(); ++expr; break; + case ']': + while (operatorStack.top().compare("[")) { + rpnQueue.push(new Token(operatorStack.top(), OP)); + operatorStack.pop(); + } + operatorStack.pop(); + ++expr; + break; default: { // The token is an operator. @@ -120,22 +200,10 @@ TokenQueue_t calculator::toRPN(const char* expr, std::string str; ss >> str; - if (lastTokenWasOp) { - // Convert unary operators to binary in the RPN. - if (!str.compare("-") || !str.compare("+")) { - rpnQueue.push(new Token(0, NUM)); - } else { - throw std::domain_error( - "Unrecognized unary operator: '" + str + "'."); - } - } + handle_unary(str, rpnQueue, lastTokenWasOp, opPrecedence); + + handle_op(str, rpnQueue, operatorStack, opPrecedence); - while (!operatorStack.empty() && - opPrecedence[str] >= opPrecedence[operatorStack.top()]) { - rpnQueue.push(new Token(operatorStack.top(), OP)); - operatorStack.pop(); - } - operatorStack.push(str); lastTokenWasOp = true; } } @@ -240,9 +308,9 @@ TokenBase* calculator::calculate(TokenQueue_t _rpn, if (!str.compare("+")) { evaluation.push(new Token(left + right, STR)); } else if (!str.compare("==")) { - evaluation.push(new Token(!left.compare(right), NUM)); + evaluation.push(new Token(left.compare(right) == 0, NUM)); } else if (!str.compare("!=")) { - evaluation.push(new Token(left.compare(right), NUM)); + evaluation.push(new Token(left.compare(right) != 0, NUM)); } else { throw std::domain_error("Unknown operator: '" + str + "'."); } @@ -272,6 +340,24 @@ TokenBase* calculator::calculate(TokenQueue_t _rpn, } else { throw std::domain_error("Unknown operator: '" + str + "'."); } + } else if(b_left->type == MAP && b_right->type == STR) { + TokenMap_t* left = static_cast*>(b_left)->val; + std::string right = static_cast*>(b_right)->val; + delete b_left; + delete b_right; + + if (!str.compare("[]") || !str.compare(".")) { + TokenMap_t::iterator it = left->find(right); + + if (it == left->end()) { + throw std::domain_error( + "Unable to find the variable '" + right + "'."); + } + + evaluation.push(it->second->clone()); + } else { + throw std::domain_error("Unknown operator: '" + str + "'."); + } } } else if (base->type == VAR) { // Variable if (!vars) { diff --git a/shunting-yard.h b/shunting-yard.h index 8706dbc..b2752a8 100644 --- a/shunting-yard.h +++ b/shunting-yard.h @@ -10,7 +10,7 @@ #include #include -enum tokType { NONE, OP, VAR, NUM, STR }; +enum tokType { NONE, OP, VAR, NUM, STR, MAP }; struct TokenBase { tokType type; @@ -27,12 +27,13 @@ public: } }; -#include "packToken.h" - +class packToken; typedef std::queue TokenQueue_t; typedef std::map TokenMap_t; typedef std::map OppMap_t; +#include "packToken.h" + class calculator { private: static OppMap_t _opPrecedence; @@ -48,6 +49,14 @@ private: TokenMap_t* vars, OppMap_t opPrecedence=_opPrecedence); + static void handle_unary(const std::string& str, + TokenQueue_t& rpnQueue, bool& lastTokenWasOp, + OppMap_t& opPrecedence); + static void handle_op(const std::string& str, + TokenQueue_t& rpnQueue, + std::stack& operatorStack, + OppMap_t& opPrecedence); + private: TokenQueue_t RPN; public: diff --git a/test-shunting-yard.cpp b/test-shunting-yard.cpp index 3617435..d8e579a 100644 --- a/test-shunting-yard.cpp +++ b/test-shunting-yard.cpp @@ -6,19 +6,17 @@ #include "shunting-yard.h" -double toDouble(TokenBase* base) { - if(base->type == NUM) { - return static_cast*>(base)->val; - } else { - throw std::domain_error( - "Cannot convert non numeric types to double!"); +void assert(packToken actual, packToken expected, const char* expr = 0) { + bool match = false; + if(actual->type == expected->type && actual->type == NUM) { + double diff = actual.asDouble() - expected.asDouble(); + if (diff < 0) diff *= -1; + if (diff < 1e-15) match = true; + } else if(actual == expected) { + match = true; } -} -void assert(double actual, double expected, const char* expr = 0) { - double diff = actual - expected; - if (diff < 0) diff *= -1; - if (diff < 1e-15) { + if(match) { if(expr) { std::cout << " '" << expr << "' indeed evaluated to " << expected << "." << std::endl; @@ -37,9 +35,9 @@ void assert(double actual, double expected, const char* expr = 0) { } } } -void assert(const char* expr, double expected, +void assert(const char* expr, packToken expected, TokenMap_t* vars = 0) { - double actual = toDouble(calculator::calculate(expr, vars)); + packToken actual = calculator::calculate(expr, vars); assert(actual, expected, expr); } @@ -75,19 +73,19 @@ int main(int argc, char** argv) { calculator c1; c1.compile("-pi+1", &vars); - assert(toDouble(c1.eval()), -2.14); + assert(c1.eval(), -2.14); calculator c2("pi+4", &vars); - assert(toDouble(c2.eval()), 7.14); - assert(toDouble(c2.eval()), 7.14); + assert(c2.eval(), 7.14); + assert(c2.eval(), 7.14); calculator c3("pi+b1+b2", &vars); vars["b2"] = 1; - assert(toDouble(c3.eval(&vars)), 4.14); + assert(c3.eval(&vars), 4.14); vars["b2"] = .86; - assert(toDouble(c3.eval(&vars)), 4); + assert(c3.eval(&vars), 4); std::cout << "\nTesting boolean expressions\n" << std::endl; @@ -116,6 +114,32 @@ int main(int argc, char** argv) { assert("str1 + 10 == str4", true, &vars); assert("10 + str2 == str5", true, &vars); + assert("'foo' + \"bar\" == str3", true, &vars); + assert("'foo' + \"bar\" != 'foobar\"'", true, &vars); + assert("'foo' + \"bar\\\"\" == 'foobar\"'", true, &vars); + + assert(vars["str1"].asString(), "foo"); + + std::cout << "\nTesting map access expressions\n" << std::endl; + + + TokenMap_t tmap; + vars["map"] = new Token(&tmap, MAP); + tmap["key"] = "mapped value"; + tmap["key1"] = "second mapped value"; + tmap["key2"] = 10; + tmap["key3"] = new TokenMap_t; + + assert("map[\"key\"]", "mapped value", &vars); + assert("map[\"key\"+1]", "second mapped value", &vars); + assert("map[\"key\"+2] + 3 == 13", true, &vars); + assert("map.key1", "second mapped value", &vars); + tmap["key3"]["map1"] = "inseption1"; + tmap["key3"]["map2"] = "inseption2"; + assert("map.key3.map1", "inseption1", &vars); + assert("map.key3['map2']", "inseption2", &vars); + assert_throws(calculator::calculate("map[\"no_key\"]", &vars)); + std::cout << "\nTesting exception management\n" << std::endl; assert_throws(c3.eval());