From ebdaaa13a7b7ffdbb5e820c43328b182c29cefca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Wed, 20 Apr 2016 13:05:05 -0300 Subject: [PATCH] Add quoted string literals, e.g.: "str" or 'str' --- shunting-yard.cpp | 23 +++++++++++++++++++++++ test-shunting-yard.cpp | 4 ++++ 2 files changed, 27 insertions(+) diff --git a/shunting-yard.cpp b/shunting-yard.cpp index 99c1209..babbd4b 100644 --- a/shunting-yard.cpp +++ b/shunting-yard.cpp @@ -9,6 +9,7 @@ #include #include "shunting-yard.h" +#include "shunting-yard-exceptions.h" OppMap_t calculator::buildOpPrecedence() { OppMap_t opp; @@ -81,6 +82,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. diff --git a/test-shunting-yard.cpp b/test-shunting-yard.cpp index 3617435..f3609bb 100644 --- a/test-shunting-yard.cpp +++ b/test-shunting-yard.cpp @@ -116,6 +116,10 @@ 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); + std::cout << "\nTesting exception management\n" << std::endl; assert_throws(c3.eval());