1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef GIN_FUNCTION_TEMPLATE_H_
6 #define GIN_FUNCTION_TEMPLATE_H_
12 #include "base/check.h"
13 #include "base/functional/callback.h"
14 #include "base/memory/raw_ptr.h"
15 #include "base/strings/strcat.h"
16 #include "gin/arguments.h"
17 #include "gin/converter.h"
18 #include "gin/gin_export.h"
19 #include "v8/include/v8-external.h"
20 #include "v8/include/v8-forward.h"
21 #include "v8/include/v8-persistent-handle.h"
22 #include "v8/include/v8-template.h"
26 struct InvokerOptions {
27 bool holder_is_first_argument = false;
28 const char* holder_type = nullptr; // Null if unknown or not applicable.
34 struct CallbackParamTraits {
38 struct CallbackParamTraits<const T&> {
42 struct CallbackParamTraits<const T*> {
46 // CallbackHolder and CallbackHolderBase are used to pass a
47 // base::RepeatingCallback from CreateFunctionTemplate through v8 (via
48 // v8::FunctionTemplate) to DispatchToCallback, where it is invoked.
50 // This simple base class is used so that we can share a single object template
51 // among every CallbackHolder instance.
52 class GIN_EXPORT CallbackHolderBase {
54 CallbackHolderBase(const CallbackHolderBase&) = delete;
55 CallbackHolderBase& operator=(const CallbackHolderBase&) = delete;
57 v8::Local<v8::External> GetHandle(v8::Isolate* isolate);
60 explicit CallbackHolderBase(v8::Isolate* isolate);
61 virtual ~CallbackHolderBase();
64 static void FirstWeakCallback(
65 const v8::WeakCallbackInfo<CallbackHolderBase>& data);
66 static void SecondWeakCallback(
67 const v8::WeakCallbackInfo<CallbackHolderBase>& data);
69 v8::Global<v8::External> v8_ref_;
72 template<typename Sig>
73 class CallbackHolder : public CallbackHolderBase {
75 CallbackHolder(v8::Isolate* isolate,
76 base::RepeatingCallback<Sig> callback,
77 InvokerOptions invoker_options)
78 : CallbackHolderBase(isolate),
79 callback(std::move(callback)),
80 invoker_options(std::move(invoker_options)) {}
81 CallbackHolder(const CallbackHolder&) = delete;
82 CallbackHolder& operator=(const CallbackHolder&) = delete;
84 base::RepeatingCallback<Sig> callback;
85 InvokerOptions invoker_options;
88 ~CallbackHolder() override = default;
92 bool GetNextArgument(Arguments* args,
93 const InvokerOptions& invoker_options,
96 if (is_first && invoker_options.holder_is_first_argument) {
97 return args->GetHolder(result);
99 return args->GetNext(result);
103 // For advanced use cases, we allow callers to request the unparsed Arguments
104 // object and poke around in it directly.
105 inline bool GetNextArgument(Arguments* args,
106 const InvokerOptions& invoker_options,
112 inline bool GetNextArgument(Arguments* args,
113 const InvokerOptions& invoker_options,
115 Arguments** result) {
120 // It's common for clients to just need the isolate, so we make that easy.
121 inline bool GetNextArgument(Arguments* args,
122 const InvokerOptions& invoker_options,
124 v8::Isolate** result) {
125 *result = args->isolate();
129 // Throws an error indicating conversion failure.
130 GIN_EXPORT void ThrowConversionError(Arguments* args,
131 const InvokerOptions& invoker_options,
134 // Class template for extracting and storing single argument for callback
135 // at position |index|.
136 template <size_t index, typename ArgType, typename = void>
137 struct ArgumentHolder {
138 using ArgLocalType = typename CallbackParamTraits<ArgType>::LocalType;
143 ArgumentHolder(Arguments* args, const InvokerOptions& invoker_options)
144 : ok(GetNextArgument(args, invoker_options, index == 0, &value)) {
146 ThrowConversionError(args, invoker_options, index);
150 // This is required for types such as v8::LocalVector<T>, which don't have
151 // a default constructor. To create an element of such a type, the isolate
152 // has to be provided.
153 template <size_t index, typename ArgType>
154 struct ArgumentHolder<
157 std::enable_if_t<!std::is_default_constructible_v<
158 typename CallbackParamTraits<ArgType>::LocalType> &&
159 std::is_constructible_v<
160 typename CallbackParamTraits<ArgType>::LocalType,
162 using ArgLocalType = typename CallbackParamTraits<ArgType>::LocalType;
167 ArgumentHolder(Arguments* args, const InvokerOptions& invoker_options)
168 : value(args->isolate()),
169 ok(GetNextArgument(args, invoker_options, index == 0, &value)) {
171 ThrowConversionError(args, invoker_options, index);
176 // Class template for converting arguments from JavaScript to C++ and running
177 // the callback with them.
178 template <typename IndicesType, typename... ArgTypes>
181 template <size_t... indices, typename... ArgTypes>
182 class Invoker<std::index_sequence<indices...>, ArgTypes...>
183 : public ArgumentHolder<indices, ArgTypes>... {
185 // Invoker<> inherits from ArgumentHolder<> for each argument.
186 // C++ has always been strict about the class initialization order,
187 // so it is guaranteed ArgumentHolders will be initialized (and thus, will
188 // extract arguments from Arguments) in the right order.
189 Invoker(Arguments* args, const InvokerOptions& invoker_options)
190 : ArgumentHolder<indices, ArgTypes>(args, invoker_options)...,
194 return And(ArgumentHolder<indices, ArgTypes>::ok...);
197 template <typename ReturnType>
198 void DispatchToCallback(
199 base::RepeatingCallback<ReturnType(ArgTypes...)> callback) {
201 callback.Run(std::move(ArgumentHolder<indices, ArgTypes>::value)...));
204 // In C++, you can declare the function foo(void), but you can't pass a void
205 // expression to foo. As a result, we must specialize the case of Callbacks
206 // that have the void return type.
207 void DispatchToCallback(base::RepeatingCallback<void(ArgTypes...)> callback) {
208 callback.Run(std::move(ArgumentHolder<indices, ArgTypes>::value)...);
212 static bool And() { return true; }
213 template <typename... T>
214 static bool And(bool arg1, T... args) {
215 return arg1 && And(args...);
218 raw_ptr<Arguments> args_;
221 // DispatchToCallback converts all the JavaScript arguments to C++ types and
222 // invokes the base::RepeatingCallback.
223 template <typename Sig>
224 struct Dispatcher {};
226 template <typename ReturnType, typename... ArgTypes>
227 struct Dispatcher<ReturnType(ArgTypes...)> {
228 static void DispatchToCallbackImpl(Arguments* args) {
229 v8::Local<v8::External> v8_holder;
230 CHECK(args->GetData(&v8_holder));
231 CallbackHolderBase* holder_base = reinterpret_cast<CallbackHolderBase*>(
234 typedef CallbackHolder<ReturnType(ArgTypes...)> HolderT;
235 HolderT* holder = static_cast<HolderT*>(holder_base);
237 using Indices = std::index_sequence_for<ArgTypes...>;
238 Invoker<Indices, ArgTypes...> invoker(args, holder->invoker_options);
240 invoker.DispatchToCallback(holder->callback);
243 static void DispatchToCallback(
244 const v8::FunctionCallbackInfo<v8::Value>& info) {
245 Arguments args(info);
246 DispatchToCallbackImpl(&args);
249 static void DispatchToCallbackForProperty(
251 const v8::PropertyCallbackInfo<v8::Value>& info) {
252 Arguments args(info);
253 DispatchToCallbackImpl(&args);
257 } // namespace internal
259 // CreateFunctionTemplate creates a v8::FunctionTemplate that will create
260 // JavaScript functions that execute a provided C++ function or
261 // base::RepeatingCallback. JavaScript arguments are automatically converted via
262 // gin::Converter, as is the return value of the C++ function, if any.
263 // |invoker_options| contains additional parameters. If it contains a
264 // holder_type, it will be used to provide a useful conversion error if the
265 // holder is the first argument. If not provided, a generic invocation error
268 // NOTE: V8 caches FunctionTemplates for a lifetime of a web page for its own
269 // internal reasons, thus it is generally a good idea to cache the template
270 // returned by this function. Otherwise, repeated method invocations from JS
271 // will create substantial memory leaks. See http://crbug.com/463487.
272 template <typename Sig>
273 v8::Local<v8::FunctionTemplate> CreateFunctionTemplate(
274 v8::Isolate* isolate,
275 base::RepeatingCallback<Sig> callback,
276 InvokerOptions invoker_options = {}) {
277 typedef internal::CallbackHolder<Sig> HolderT;
279 new HolderT(isolate, std::move(callback), std::move(invoker_options));
281 v8::Local<v8::FunctionTemplate> tmpl = v8::FunctionTemplate::New(
282 isolate, &internal::Dispatcher<Sig>::DispatchToCallback,
283 ConvertToV8<v8::Local<v8::External>>(isolate, holder->GetHandle(isolate)),
284 v8::Local<v8::Signature>(), 0, v8::ConstructorBehavior::kThrow);
288 // CreateDataPropertyCallback creates a v8::AccessorNameGetterCallback and
289 // corresponding data value that will hold and execute the provided
290 // base::RepeatingCallback, using automatic conversions similar to
291 // |CreateFunctionTemplate|.
293 // It is expected that these will be passed to v8::Template::SetLazyDataProperty
294 // or another similar function.
295 template <typename Sig>
296 std::pair<v8::AccessorNameGetterCallback, v8::Local<v8::Value>>
297 CreateDataPropertyCallback(v8::Isolate* isolate,
298 base::RepeatingCallback<Sig> callback,
299 InvokerOptions invoker_options = {}) {
300 typedef internal::CallbackHolder<Sig> HolderT;
302 new HolderT(isolate, std::move(callback), std::move(invoker_options));
303 return {&internal::Dispatcher<Sig>::DispatchToCallbackForProperty,
304 ConvertToV8<v8::Local<v8::External>>(isolate,
305 holder->GetHandle(isolate))};
310 #endif // GIN_FUNCTION_TEMPLATE_H_