From 4a9912f516bf096c6f8c6259b3fc6ba4b95b8d69 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 24 Oct 2014 13:25:04 +0000 Subject: finished implementation of HostFunction git-svn-id: file:///var/local/svn/basicwriter@74 daaaf23c-2e50-4459-9457-1e69db5a47bf --- src/core/script/Function.cpp | 52 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) (limited to 'src/core/script/Function.cpp') diff --git a/src/core/script/Function.cpp b/src/core/script/Function.cpp index d72df4c..ce6e6b6 100644 --- a/src/core/script/Function.cpp +++ b/src/core/script/Function.cpp @@ -21,9 +21,57 @@ namespace ousia { namespace script { -std::pair> validate(const std::vector &args) +std::pair> ArgumentValidator::setError(int idx, + const std::string &msg, std::vector &res) { - return std::make_pair(true, std::vector{}); + errorIndex = idx; + errorMessage = msg; + return std::make_pair(false, res); +} + +void ArgumentValidator::resetError() +{ + errorIndex = -1; + errorMessage = ""; +} + +std::pair> ArgumentValidator::validate( + const std::vector &args) +{ + std::vector res; + + // Reset any old error + resetError(); + + // Sanity check: Do not allow too many arguments + if (args.size() > descriptors.size()) { + return setError(descriptors.size(), "Expected " + std::to_string(descriptors.size()) + + " arguments but got " + std::to_string(args.size()), res); + } + + // Iterate over the given arguments and check their type + res.reserve(descriptors.size()); + for (unsigned int i = 0; i < args.size(); i++) { + // TODO: Implicit type conversion + const VariantType tGiven = args[i].getType(); + const VariantType tExpected = descriptors[i].type; + if (tGiven != tExpected) { + return setError(i, std::string("Expected type ") + Variant::getTypeName(tExpected) + + " but got " + Variant::getTypeName(tGiven), res); + } + res.push_back(args[i]); + } + + // Make sure the remaining arguments have a default value, and if they have + // one, add it to the result + for (unsigned int i = args.size(); i < descriptors.size(); i++) { + if (!descriptors[i].hasDefault) { + return setError(i, "Expected argument " + std::to_string(i), res); + } + res.push_back(descriptors[i].defaultValue); + } + + return std::make_pair(true, res); } } -- cgit v1.2.3