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.hpp | 67 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) (limited to 'src/core/script/Function.hpp') diff --git a/src/core/script/Function.hpp b/src/core/script/Function.hpp index 35e2205..4c13dbc 100644 --- a/src/core/script/Function.hpp +++ b/src/core/script/Function.hpp @@ -46,6 +46,13 @@ public: */ virtual Variant call(const std::vector &args) const = 0; + /** + * Calls the underlying function with no arguments. + * + * @return a Variant containing the return value. + */ + Variant call() const { return call({}); } + }; /** @@ -70,7 +77,7 @@ struct ArgumentDescriptor { * ArgumentValidatorError is an exception type used to represent argument * validator errors. */ -class ArgumentValidatorError : std::exception { +class ArgumentValidatorError : public std::exception { public: @@ -110,6 +117,11 @@ private: */ std::string errorMessage; + std::pair> setError(int idx, + const std::string &msg, std::vector &res); + + void resetError(); + public: /** @@ -153,6 +165,59 @@ public: /** * The HostFunction class represents a function that resides in the script host. */ +template +class HostFunction : public Function { + +private: + T callback; + ArgumentValidator *validator; + void *data; + +public: + + HostFunction(T callback, std::vector signature, + void *data = nullptr) : + callback(callback), validator(new ArgumentValidator(signature)), + data(data) {} + + HostFunction(T callback, void *data = nullptr) : + callback(callback), validator(nullptr), data(data) {} + + ~HostFunction() + { + delete validator; + } + + virtual Variant call(const std::vector &args) const override + { + if (validator) { + std::pair> res = validator->validate(args); + if (!res.first) { + throw validator->error(); + } + return callback(res.second, data); + } else { + return callback(args, data); + } + } + + using Function::call; + +}; + +template +static HostFunction createHostFunction(T callback, + std::vector signature, void *data = nullptr) +{ + return HostFunction(callback, signature, data); +} + +template +static HostFunction createHostFunction(T callback, void *data = nullptr) +{ + return HostFunction(callback, data); +} + } } -- cgit v1.2.3