LCOV - code coverage report
Current view: top level - source/scriptinterface - FunctionWrapper.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 127 143 88.8 %
Date: 2026-12-03 01:19:39 Functions: 257 904 28.4 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #ifndef INCLUDED_FUNCTIONWRAPPER
      19             : #define INCLUDED_FUNCTIONWRAPPER
      20             : 
      21             : #include "scriptinterface/Conversions.h"
      22             : #include "scriptinterface/Exceptions.h"
      23             : #include "scriptinterface/Request.h"
      24             : 
      25             : #include <cstddef>
      26             : #include <cstdint>
      27             : #include <exception>
      28             : #include <fmt/format.h>
      29             : #include <js/CallAndConstruct.h>
      30             : #include <js/CallArgs.h>
      31             : #include <js/Class.h>
      32             : #include <js/GCVector.h>
      33             : #include <js/Object.h>
      34             : #include <js/PropertyAndElement.h>
      35             : #include <js/PropertyDescriptor.h>
      36             : #include <js/PropertySpec.h>
      37             : #include <js/RootingAPI.h>
      38             : #include <js/TypeDecls.h>
      39             : #include <js/Value.h>
      40             : #include <jsapi.h>
      41             : #include <memory>
      42             : #include <stdexcept>
      43             : #include <string>
      44             : #include <tuple>
      45             : #include <type_traits>
      46             : #include <utility>
      47             : 
      48             : class JSFunction;
      49             : class JSObject;
      50             : namespace JS { class GCContext; }
      51             : namespace Script { class Interface; }
      52             : struct JSContext;
      53             : 
      54             : /**
      55             :  * This class introduces templates to conveniently wrap C++ functions in JSNative functions.
      56             :  * This _is_ rather template heavy, so compilation times beware.
      57             :  * The C++ code can have arbitrary arguments and arbitrary return types, so long
      58             :  * as they can be converted to/from JS using ToJSVal (FromJSVal respectively),
      59             :  * and they are default-constructible (TODO: that can probably changed).
      60             :  * (This could be a namespace, but I like being able to specify public/private).
      61             :  */
      62             : 
      63             : namespace Script
      64             : {
      65             : 
      66             : class Function
      67             : {
      68             : private:
      69             :     Function() = delete;
      70             :     Function(const Function&) = delete;
      71             :     Function(Function&&) = delete;
      72             : 
      73             :     /**
      74             :      * In JS->C++ calls, types are converted using FromJSVal,
      75             :      * and this requires them to be default-constructible (as that function takes an out parameter)
      76             :      * thus constref needs to be removed when defining the tuple.
      77             :      * Exceptions are:
      78             :      *  - const Request& (as the first argument only, for implementation simplicity).
      79             :      *  - const Interface& (as the first argument only, for implementation simplicity).
      80             :      *  - JS::HandleValue
      81             :      */
      82             :     template<typename T>
      83             :     using type_transform = std::conditional_t<
      84             :         std::is_same_v<const Request&, T> || std::is_same_v<const Interface&, T>,
      85             :         T,
      86             :         std::remove_const_t<typename std::remove_reference_t<T>>
      87             :     >;
      88             : 
      89             :     /**
      90             :      * Convenient struct to get info on a [class] [const] function pointer.
      91             :      */
      92             :     template <class T> struct args_info_t;
      93             :     template <auto T> using args_info = args_info_t<decltype(T)>;
      94             : 
      95             :     template<typename R, typename ...Types>
      96             :     struct args_info_t<R(*)(Types ...)>
      97             :     {
      98             :         static constexpr const size_t nb_args = sizeof...(Types);
      99             :         using return_type = R;
     100             :         using object_type = void;
     101             :         using arg_types = std::tuple<type_transform<Types>...>;
     102             :     };
     103             : 
     104             :     template<typename C, typename R, typename ...Types>
     105             :     struct args_info_t<R(C::*)(Types ...)> : public args_info_t<R(*)(Types ...)> { using object_type = C; };
     106             :     template<typename C, typename R, typename ...Types>
     107             :     struct args_info_t<R(C::*)(Types ...) const> : public args_info_t<R(C::*)(Types ...)> {};
     108             : 
     109             :     struct IteratorResultError : std::runtime_error
     110             :     {
     111             :         IteratorResultError(const std::string& property) :
     112             :             IteratorResultError{property.c_str()}
     113             :         {}
     114           0 :         IteratorResultError(const char* property) :
     115           0 :             std::runtime_error{fmt::format("Failed to get `{}` from an `IteratorResult`.", property)}
     116           0 :         {}
     117             :         using std::runtime_error::runtime_error;
     118             :     };
     119             : 
     120             :     ///////////////////////////////////////////////////////////////////////////
     121             :     ///////////////////////////////////////////////////////////////////////////
     122             : 
     123             :     /**
     124             :      * DoConvertFromJS takes a type, a JS argument, and converts.
     125             :      * The type T must be default constructible (except for HandleValue, which is handled specially).
     126             :      * (possible) TODO: this could probably be changed if FromJSVal had a different signature.
     127             :      * @param wentOk - true if the conversion succeeded and wentOk was true before, false otherwise.
     128             :      */
     129             :     template<size_t idx, typename T>
     130      264300 :     static T DoConvertFromJS([[maybe_unused]] const Request& rq,
     131             :         [[maybe_unused]] JS::CallArgs& args, [[maybe_unused]] bool& wentOk)
     132             :     {
     133             :         // No need to convert JS values.
     134             :         if constexpr (std::is_same_v<T, JS::HandleValue>)
     135             :         {
     136             :             // Default-construct values that aren't passed by JS.
     137             :             // TODO: this should perhaps be removed, as it's distinct from C++ default values and kind of tricky.
     138        1531 :             if (idx >= args.length())
     139         193 :                 return JS::UndefinedHandleValue;
     140             :             else
     141        3343 :                 return args[idx]; // This passes the null handle value if idx is beyond the length of args.
     142             :         }
     143             :         else
     144             :         {
     145             :             // Default-construct values that aren't passed by JS.
     146             :             // TODO: this should perhaps be removed, as it's distinct from C++ default values and kind of tricky.
     147      259559 :             if (idx >= args.length())
     148        5532 :                 return {};
     149             :             else
     150             :             {
     151       19230 :                 T ret;
     152      259822 :                 wentOk &= FromJSVal<T>(rq, args[idx], ret);
     153      259821 :                 return ret;
     154        6108 :             }
     155             :         }
     156             :     }
     157             : 
     158             :     /**
     159             :      * Wrapper: calls DoConvertFromJS for each element in T.
     160             :      */
     161             :     template<typename... T, size_t... idx>
     162      127620 :     static std::tuple<T...> DoConvertFromJS(std::index_sequence<idx...>, const Request& rq,
     163             :         JS::CallArgs& args, bool& wentOk)
     164             :     {
     165      131718 :         return {DoConvertFromJS<idx, T>(rq, args, wentOk)...};
     166             :     }
     167             : 
     168             :     /**
     169             :      * ConvertFromJS is a wrapper around DoConvertFromJS, and handles specific cases for the
     170             :      * first argument (Request, ...).
     171             :      *
     172             :      * Trick: to unpack the types of the tuple as a parameter pack, we deduce them from the function signature.
     173             :      * To do that, we want the tuple in the arguments, but we don't want to actually have to default-instantiate,
     174             :      * so we'll pass a nullptr that's static_cast to what we want.
     175             :      */
     176             :     template<typename ...Types>
     177      124656 :     static std::tuple<Types...> ConvertFromJS(const Request& rq, JS::CallArgs& args, bool& wentOk,
     178             :         std::tuple<Types...>*)
     179             :     {
     180      124656 :         return DoConvertFromJS<Types...>(std::index_sequence_for<Types...>(), rq, args, wentOk);
     181             :     }
     182             : 
     183             :     // Overloads for Request& first argument.
     184             :     template<typename ...Types>
     185         611 :     static std::tuple<const Request&, Types...> ConvertFromJS(const Request& rq,
     186             :         JS::CallArgs& args, bool& wentOk, std::tuple<const Request&, Types...>*)
     187             :     {
     188           0 :         return std::tuple_cat(std::tie(rq), DoConvertFromJS<Types...>(
     189         635 :             std::index_sequence_for<Types...>(), rq, args, wentOk));
     190             :     }
     191             : 
     192             :     // Overloads for Interface& first argument.
     193             :     template<typename ...Types>
     194        2353 :     static std::tuple<const Interface&, Types...> ConvertFromJS(const Request& rq,
     195             :         JS::CallArgs& args, bool& wentOk, std::tuple<const Interface&, Types...>*)
     196             :     {
     197             :         return std::tuple_cat(std::tie(rq.GetScriptInterface()),
     198        2353 :             DoConvertFromJS<Types...>(std::index_sequence_for<Types...>(), rq, args, wentOk));
     199             :     }
     200             : 
     201             :     ///////////////////////////////////////////////////////////////////////////
     202             :     ///////////////////////////////////////////////////////////////////////////
     203             : 
     204             :     /**
     205             :      * Wrap std::apply for the case where we have an object method or a regular function.
     206             :      */
     207             :     template <auto callable, typename T, typename tuple>
     208      125533 :     static typename args_info<callable>::return_type call([[maybe_unused]] T* object, tuple& args)
     209             :     {
     210             :         if constexpr(std::is_same_v<T, void>)
     211         565 :             return std::apply(callable, args);
     212             :         else
     213      155765 :             return std::apply(callable, std::tuple_cat(std::forward_as_tuple(*object), args));
     214             :     }
     215             : 
     216             :     ///////////////////////////////////////////////////////////////////////////
     217             :     ///////////////////////////////////////////////////////////////////////////
     218             : 
     219             :     struct IgnoreResult_t {};
     220             :     static inline IgnoreResult_t IgnoreResult;
     221             : 
     222             :     /**
     223             :      * Converts any number of arguments to a `JS::MutableHandleValueVector`.
     224             :      * If `idx` is empty this function does nothing. For that case there is a
     225             :      * `[[maybe_unused]]` on `argv`. GCC would issue a
     226             :      * "-Wunused-but-set-parameter" warning.
     227             :      * For references like `rq` this warning isn't issued.
     228             :      */
     229             :     template<typename... Types, size_t... idx>
     230       24248 :     static void ToJSValVector(std::index_sequence<idx...>, const Request& rq,
     231             :         [[maybe_unused]] JS::MutableHandleValueVector argv, const Types&... params)
     232             :     {
     233       24263 :         (ToJSVal(rq, argv[idx], params), ...);
     234        3903 :     }
     235             : 
     236             :     /**
     237             :      * Wrapper around calling a JS function from C++.
     238             :      * Arguments are const& to avoid lvalue/rvalue issues, and so can't be used as out-parameters.
     239             :      * In particular, the problem is that Rooted are deduced as Rooted, not Handle, and so can't be copied.
     240             :      * This could be worked around with more templates, but it doesn't seem particularly worth doing.
     241             :      */
     242             :     template<typename R, typename ...Args>
     243       36553 :     static bool Call_(const Request& rq, JS::HandleValue val, const char* name,
     244             :         [[maybe_unused]] R& ret, const Args&... args)
     245             :     {
     246       36553 :         JS::RootedObject obj(rq.cx);
     247       36553 :         if (!JS_ValueToObject(rq.cx, val, &obj) || !obj)
     248          13 :             return false;
     249             : 
     250             :         // Fetch the property explicitly - this avoids converting the arguments if it doesn't exist.
     251       36540 :         JS::RootedValue func(rq.cx);
     252       36540 :         if (!JS_GetProperty(rq.cx, obj, name, &func) || func.isUndefined())
     253        4339 :             return false;
     254             : 
     255       32201 :         JS::RootedValueVector argv(rq.cx);
     256       32201 :         std::ignore = argv.resize(sizeof...(Args));
     257       32201 :         ToJSValVector(std::index_sequence_for<Args...>{}, rq, &argv, args...);
     258             : 
     259             :         bool success;
     260             :         if constexpr (std::is_same_v<R, JS::MutableHandleValue>)
     261        3222 :             success = JS_CallFunctionValue(rq.cx, obj, func, argv, ret);
     262             :         else
     263             :         {
     264       28979 :             JS::RootedValue jsRet(rq.cx);
     265       28979 :             success = JS_CallFunctionValue(rq.cx, obj, func, argv, &jsRet);
     266             :             if constexpr (!std::is_same_v<R, IgnoreResult_t>)
     267             :             {
     268        5074 :                 if (success)
     269        5074 :                     success = FromJSVal(rq, jsRet, ret);
     270             :             }
     271           0 :         }
     272             :         // Even if everything succeeded, there could be pending exceptions
     273       32201 :         return !Exception::CatchPending(rq) && success;
     274       36553 :     }
     275             : 
     276             :     struct StatefullCallbackPrivateSlot
     277             :     {
     278             :         static constexpr size_t callback{0};
     279             :         static constexpr size_t classInfo{1};
     280             :         static constexpr uint32_t count{2};
     281             :     };
     282             : 
     283             :     ///////////////////////////////////////////////////////////////////////////
     284             :     ///////////////////////////////////////////////////////////////////////////
     285             : public:
     286             :     template <typename T>
     287             :     using ObjectGetter = T*(*)(const Request&, JS::CallArgs&);
     288             : 
     289             :     template <auto callable>
     290             :     using GetterFor = ObjectGetter<typename args_info<callable>::object_type>;
     291             : 
     292             :     /**
     293             :      * The meat of this file. This wraps a C++ function into a JSNative,
     294             :      * so that it can be called from JS and manipulated in Spidermonkey.
     295             :      * Most C++ functions can be directly wrapped, so long as their arguments are
     296             :      * convertible from JS::Value and their return value is convertible to JS::Value (or void)
     297             :      * The C++ function may optionally take const Request& or Interface& as its first argument.
     298             :      * The function may be an object method, in which case you need to pass an appropriate getter
     299             :      *
     300             :      * Optimisation note: the Request object is created even without arguments,
     301             :      * as it's necessary for IsExceptionPending.
     302             :      *
     303             :      * @param thisGetter to get the object, if necessary.
     304             :      */
     305             :     template <auto callable, GetterFor<callable> thisGetter = nullptr>
     306      155197 :     static bool ToJSNative(JSContext* cx, unsigned argc, JS::Value* vp)
     307             :     {
     308             :         using ObjType = typename args_info<callable>::object_type;
     309             : 
     310      155197 :         JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
     311      155197 :         Request rq(cx);
     312             : 
     313             :         // If the callable is an object method, we must specify how to fetch the object.
     314             :         static_assert(std::is_same_v<typename args_info<callable>::object_type, void> || thisGetter != nullptr,
     315             :                       "Function::Register - No getter specified for object method");
     316             : 
     317             : // GCC 7 triggers spurious warnings
     318             : #ifdef __GNUC__
     319             : #pragma GCC diagnostic push
     320             : #pragma GCC diagnostic ignored "-Waddress"
     321             : #endif
     322      155197 :         ObjType* obj = nullptr;
     323             :         if constexpr (thisGetter != nullptr)
     324             :         {
     325      152209 :             obj = thisGetter(rq, args);
     326      152208 :             if (!obj)
     327             :             {
     328           1 :                 Exception::ReportUncatchable(rq);
     329             :                 return false;
     330             :             }
     331             :         }
     332             : #ifdef __GNUC__
     333             : #pragma GCC diagnostic pop
     334             : #endif
     335             : 
     336      155196 :         bool wentOk = true;
     337      127620 :         typename args_info<callable>::arg_types outs = ConvertFromJS(rq, args, wentOk,
     338             :             static_cast<typename args_info<callable>::arg_types*>(nullptr));
     339      126685 :         if (!wentOk)
     340             :         {
     341           0 :             Exception::ReportUncatchable(rq);
     342             :             return false;
     343             :         }
     344             : 
     345             :         try
     346             :         {
     347             :             if constexpr (std::is_same_v<void, typename args_info<callable>::return_type>)
     348        8890 :                 call<callable>(obj, outs);
     349             :             else if constexpr (std::is_same_v<JS::Value, typename args_info<callable>::return_type>)
     350        2565 :                 args.rval().set(call<callable>(obj, outs));
     351             :             else
     352      143739 :                 ToJSVal(rq, args.rval(), call<callable>(obj, outs));
     353             : 
     354      155194 :             return !Exception::IsPending(rq);
     355             :         }
     356           4 :         catch (const std::exception& e)
     357             :         {
     358           2 :             Exception::Raise(rq, "%s", e.what());
     359             :         }
     360           0 :         catch (...)
     361             :         {
     362           0 :             Exception::Raise(rq, "Unknown error occured in an Engine callback.");
     363             :         }
     364             :         return false;
     365      155197 :     }
     366             : 
     367             :     /**
     368             :      * Call a JS function @a name, property of object @a val, with the arguments @a args.
     369             :      * @a ret will be updated with the return value, if any.
     370             :      * @return the success (or failure) thereof.
     371             :      */
     372             :     template<typename R, typename ...Args>
     373       33324 :     static bool Call(const Request& rq, JS::HandleValue val, const char* name, R& ret, const Args&... args)
     374             :     {
     375       33314 :         return Call_(rq, val, name, ret, std::forward<const Args>(args)...);
     376             :     }
     377             : 
     378             :     // Specialisation for MutableHandleValue return.
     379             :     template<typename ...Args>
     380        3229 :     static bool Call(const Request& rq, JS::HandleValue val, const char* name, JS::MutableHandleValue ret, const Args&... args)
     381             :     {
     382        3221 :         return Call_(rq, val, name, ret, std::forward<const Args>(args)...);
     383             :     }
     384             : 
     385             :     /**
     386             :      * Call a JS function @a name, property of object @a val, with the arguments @a args.
     387             :      * @return the success (or failure) thereof.
     388             :      */
     389             :     template<typename ...Args>
     390       28247 :     static bool CallVoid(const Request& rq, JS::HandleValue val, const char* name, const Args&... args)
     391             :     {
     392       28247 :         return Call(rq, val, name, IgnoreResult, std::forward<const Args>(args)...);
     393             :     }
     394             : 
     395             :     /**
     396             :      * Call a JS function @a name, property of object @a val, with the argument @a args. Repeatetly
     397             :      * invokes @a yieldCallback with the yielded value.
     398             :      * @return the final value of the generator.
     399             :      */
     400             :     template<typename Callback>
     401           8 :     static JS::Value RunGenerator(const Request& rq, JS::HandleValue val, const char* name,
     402             :         JS::HandleValue arg, Callback yieldCallback)
     403             :     {
     404           8 :         JS::RootedValue generator{rq.cx};
     405           8 :         if (!Function::Call(rq, val, name, &generator, arg))
     406           0 :             throw std::runtime_error{fmt::format("Failed to call the generator `{}`.", name)};
     407             : 
     408           8 :         const auto continueGenerator = [&](const char* property, auto... args) -> JS::Value
     409             :             {
     410          16 :                 JS::RootedValue iteratorResult{rq.cx};
     411          16 :                 if (!Function::Call(rq, generator, property, &iteratorResult, args...))
     412           0 :                     throw std::runtime_error{fmt::format("Failed to call `{}`.", name)};
     413          16 :                 return iteratorResult;
     414          16 :             };
     415             : 
     416           8 :         JS::PersistentRootedValue error{rq.cx, JS::UndefinedValue()};
     417           8 :         while (true)
     418             :         {
     419          16 :             JS::RootedValue iteratorResult{rq.cx, error.isUndefined() ? continueGenerator("next") :
     420          16 :                 continueGenerator("throw", std::exchange(error, JS::UndefinedValue()))};
     421             : 
     422             :             try
     423             :             {
     424          16 :                 JS::RootedObject iteratorResultObject{rq.cx, &iteratorResult.toObject()};
     425             : 
     426             :                 bool done;
     427          17 :                 if (!FromJSProperty(rq, iteratorResult, "done", done, true))
     428           0 :                     throw IteratorResultError{"done"};
     429             : 
     430          16 :                 JS::RootedValue value{rq.cx};
     431          16 :                 if (!JS_GetProperty(rq.cx, iteratorResultObject, "value", &value))
     432           0 :                     throw IteratorResultError{"value"};
     433             : 
     434          16 :                 if (done)
     435          16 :                     return value;
     436             : 
     437           8 :                 yieldCallback(value);
     438          16 :             }
     439           1 :             catch (const std::exception& e)
     440             :             {
     441           1 :                 JS::RootedValue global{rq.cx, rq.globalValue()};
     442           1 :                 if (!Function::Call(rq, global, "Error", &error, e.what()))
     443           0 :                     throw std::runtime_error{"Failed to construct `Error`."};
     444           1 :             }
     445             :         }
     446           8 :     }
     447             : 
     448             :     /**
     449             :      * Return a function spec from a C++ function.
     450             :      */
     451             :     template <auto callable, GetterFor<callable> thisGetter = nullptr>
     452             :     static JSFunctionSpec Wrap(const char* name,
     453             :         const std::uint16_t flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)
     454             :     {
     455             :         return JS_FN(name, (&ToJSNative<callable, thisGetter>), args_info<callable>::nb_args, flags);
     456             :     }
     457             : 
     458             :     /**
     459             :      * Return a JSFunction from a C++ function.
     460             :      */
     461             :     template <auto callable, GetterFor<callable> thisGetter = nullptr>
     462         817 :     static JSFunction* Create(const Request& rq, const char* name,
     463             :         const std::uint16_t flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)
     464             :     {
     465         817 :         return JS_NewFunction(rq.cx, &ToJSNative<callable, thisGetter>, args_info<callable>::nb_args, flags, name);
     466             :     }
     467             : 
     468             :     /**
     469             :      * Register a function on the native scope (usually 'Engine').
     470             :      */
     471             :     template <auto callable, GetterFor<callable> thisGetter = nullptr>
     472        8159 :     static void Register(const Request& rq, const char* name,
     473             :         const std::uint16_t flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)
     474             :     {
     475        2233 :         JS_DefineFunction(rq.cx, rq.nativeScope, name, &ToJSNative<callable, thisGetter>, args_info<callable>::nb_args, flags);
     476        1597 :     }
     477             : 
     478             :     /**
     479             :      * Register a function on @param scope.
     480             :      * Prefer the version taking Request unless you have a good reason not to.
     481             :      * @see Register
     482             :      */
     483             :     template <auto callable, GetterFor<callable> thisGetter = nullptr>
     484        1885 :     static void Register(JSContext* cx, JS::HandleObject scope, const char* name,
     485             :         const std::uint16_t flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)
     486             :     {
     487        1885 :         JS_DefineFunction(cx, scope, name, &ToJSNative<callable, thisGetter>, args_info<callable>::nb_args, flags);
     488        1885 :     }
     489             : 
     490             :     template<typename Callable>
     491             :     class StatefulCallback
     492             :     {
     493           2 :         class ClassInfo
     494             :         {
     495             :         public:
     496           2 :             ClassInfo(std::string className) :
     497           2 :                 name{std::move(className)}
     498           2 :             {}
     499             : 
     500             :             JSClassOps classOps{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
     501           0 :                 /*.finalize = */finalize, /*.call = */&ToJSNative<&Callable::operator(), getter>,
     502             :                 nullptr, nullptr};
     503             :             std::string name;
     504             :             JSClass jsClass{name.c_str(),
     505             :                 JSCLASS_HAS_RESERVED_SLOTS(StatefullCallbackPrivateSlot::count) |
     506             :                     JSCLASS_BACKGROUND_FINALIZE,
     507             :                 &classOps};
     508             :         };
     509             :     public:
     510           2 :         explicit StatefulCallback(const Request& rq, std::string name, Callable callable) :
     511             :             StatefulCallback{rq, std::move(name),
     512           2 :                 JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT, std::move(callable)}
     513           2 :         {}
     514             : 
     515           2 :         explicit StatefulCallback(const Request& rq, std::string name, const unsigned flags,
     516             :             Callable callable) :
     517           1 :             callback{std::move(callable)},
     518           2 :             functionObject{rq.cx}
     519             :         {
     520           2 :             auto classInfo = std::make_unique<ClassInfo>(std::move(name));
     521           2 :             functionObject.set(JS_NewObject(rq.cx, &classInfo->jsClass));
     522           2 :             JS::RootedValue functionValue{rq.cx, JS::ObjectValue(*functionObject)};
     523           2 :             if (!JS_DefineProperty(rq.cx, rq.nativeScope, classInfo->name.c_str(), functionValue,
     524             :                 flags))
     525             :             {
     526           0 :                 throw std::runtime_error{fmt::format(
     527           0 :                     "Failed defining function {:?} on the native scope.", classInfo->name)};
     528             :             }
     529           2 :             JS::SetReservedSlot(functionObject, StatefullCallbackPrivateSlot::classInfo,
     530           2 :                 JS::PrivateValue(classInfo.release()));
     531           2 :             JS::SetReservedSlot(functionObject, StatefullCallbackPrivateSlot::callback,
     532           2 :                 JS::PrivateValue(&callback));
     533           2 :         }
     534             :         StatefulCallback(const StatefulCallback&) = delete;
     535             :         StatefulCallback& operator=(const StatefulCallback&) = delete;
     536             :         StatefulCallback(StatefulCallback&&) = delete;
     537             :         StatefulCallback& operator=(StatefulCallback&&) = delete;
     538             : 
     539           2 :         ~StatefulCallback()
     540             :         {
     541           2 :             JS::SetReservedSlot(functionObject, StatefullCallbackPrivateSlot::callback,
     542           2 :                 JS::UndefinedValue());
     543           2 :         }
     544             : 
     545             :     private:
     546           3 :         static Callable* getter(const Request&, JS::CallArgs& args)
     547             :         {
     548           6 :             return JS::GetMaybePtrFromReservedSlot<Callable>(&args.callee(),
     549             :                 StatefullCallbackPrivateSlot::callback);
     550             :         }
     551             : 
     552           2 :         static void finalize(JS::GCContext*, JSObject* obj)
     553             :         {
     554           4 :             delete JS::GetMaybePtrFromReservedSlot<ClassInfo>(obj,
     555             :                 StatefullCallbackPrivateSlot::classInfo);
     556           2 :         }
     557             : 
     558             :         Callable callback;
     559             :         JS::RootedObject functionObject;
     560             :     };
     561             : 
     562             :     template<typename Callable>
     563             :     static StatefulCallback<Callable> Register(const Request& rq, std::string name,
     564             :         const unsigned flags, Callable callable)
     565             :     {
     566             :         return StatefulCallback{rq, std::move(name), flags, std::move(callable)};
     567             :     }
     568             : 
     569             :     template<typename Callable>
     570           2 :     static StatefulCallback<Callable> Register(const Request& rq, std::string name,
     571             :         Callable callable)
     572             :     {
     573           4 :         return StatefulCallback{rq, std::move(name), std::move(callable)};
     574             :     }
     575             : };
     576             : 
     577             : }
     578             : 
     579             : #endif // INCLUDED_FUNCTIONWRAPPER

Generated by: LCOV version 1.16