Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / gin / function_template.h
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef GIN_FUNCTION_TEMPLATE_H_
6 #define GIN_FUNCTION_TEMPLATE_H_
7
8 #include "base/callback.h"
9 #include "base/logging.h"
10 #include "gin/arguments.h"
11 #include "gin/converter.h"
12 #include "gin/gin_export.h"
13 #include "v8/include/v8.h"
14
15 namespace gin {
16
17 class PerIsolateData;
18
19 enum CreateFunctionTemplateFlags {
20   HolderIsFirstArgument = 1 << 0,
21 };
22
23 namespace internal {
24
25 template<typename T>
26 struct CallbackParamTraits {
27   typedef T LocalType;
28 };
29 template<typename T>
30 struct CallbackParamTraits<const T&> {
31   typedef T LocalType;
32 };
33 template<typename T>
34 struct CallbackParamTraits<const T*> {
35   typedef T* LocalType;
36 };
37
38
39 // CallbackHolder and CallbackHolderBase are used to pass a base::Callback from
40 // CreateFunctionTemplate through v8 (via v8::FunctionTemplate) to
41 // DispatchToCallback, where it is invoked.
42
43 // This simple base class is used so that we can share a single object template
44 // among every CallbackHolder instance.
45 class GIN_EXPORT CallbackHolderBase {
46  public:
47   v8::Handle<v8::External> GetHandle(v8::Isolate* isolate);
48
49  protected:
50   explicit CallbackHolderBase(v8::Isolate* isolate);
51   virtual ~CallbackHolderBase();
52
53  private:
54   static void WeakCallback(
55       const v8::WeakCallbackData<v8::External, CallbackHolderBase>& data);
56
57   v8::Persistent<v8::External> v8_ref_;
58
59   DISALLOW_COPY_AND_ASSIGN(CallbackHolderBase);
60 };
61
62 template<typename Sig>
63 class CallbackHolder : public CallbackHolderBase {
64  public:
65   CallbackHolder(v8::Isolate* isolate,
66                  const base::Callback<Sig>& callback,
67                  int flags)
68       : CallbackHolderBase(isolate), callback(callback), flags(flags) {}
69   base::Callback<Sig> callback;
70   int flags;
71  private:
72   virtual ~CallbackHolder() {}
73
74   DISALLOW_COPY_AND_ASSIGN(CallbackHolder);
75 };
76
77 template<typename T>
78 bool GetNextArgument(Arguments* args, int create_flags, bool is_first,
79                      T* result) {
80   if (is_first && (create_flags & HolderIsFirstArgument) != 0) {
81     return args->GetHolder(result);
82   } else {
83     return args->GetNext(result);
84   }
85 }
86
87 // For advanced use cases, we allow callers to request the unparsed Arguments
88 // object and poke around in it directly.
89 inline bool GetNextArgument(Arguments* args, int create_flags, bool is_first,
90                             Arguments* result) {
91   *result = *args;
92   return true;
93 }
94 inline bool GetNextArgument(Arguments* args, int create_flags, bool is_first,
95                             Arguments** result) {
96   *result = args;
97   return true;
98 }
99
100 // It's common for clients to just need the isolate, so we make that easy.
101 inline bool GetNextArgument(Arguments* args, int create_flags,
102                             bool is_first, v8::Isolate** result) {
103   *result = args->isolate();
104   return true;
105 }
106
107 // Classes for generating and storing an argument pack of integer indices
108 // (based on well-known "indices trick", see: http://goo.gl/bKKojn):
109 template <size_t... indices>
110 struct IndicesHolder {};
111
112 template <size_t requested_index, size_t... indices>
113 struct IndicesGenerator {
114   using type = typename IndicesGenerator<requested_index - 1,
115                                          requested_index - 1,
116                                          indices...>::type;
117 };
118 template <size_t... indices>
119 struct IndicesGenerator<0, indices...> {
120   using type = IndicesHolder<indices...>;
121 };
122
123 // Class template for extracting and storing single argument for callback
124 // at position |index|.
125 template <size_t index, typename ArgType>
126 struct ArgumentHolder {
127   using ArgLocalType = typename CallbackParamTraits<ArgType>::LocalType;
128
129   ArgLocalType value;
130   bool ok;
131
132   ArgumentHolder(Arguments* args, int create_flags)
133       : ok(GetNextArgument(args, create_flags, index == 0, &value)) {
134     if (!ok)
135       args->ThrowError();
136   }
137 };
138
139 // Class template for converting arguments from JavaScript to C++ and running
140 // the callback with them.
141 template <typename IndicesType, typename... ArgTypes>
142 class Invoker {};
143
144 template <size_t... indices, typename... ArgTypes>
145 class Invoker<IndicesHolder<indices...>, ArgTypes...>
146     : public ArgumentHolder<indices, ArgTypes>... {
147  public:
148   // Invoker<> inherits from ArgumentHolder<> for each argument.
149   // C++ has always been strict about the class initialization order,
150   // so it is guaranteed ArgumentHolders will be initialized (and thus, will
151   // extract arguments from Arguments) in the right order.
152   Invoker(Arguments* args, int create_flags)
153       : ArgumentHolder<indices, ArgTypes>(args, create_flags)..., args_(args) {
154     // GCC thinks that create_flags is going unused, even though the
155     // expansion above clearly makes use of it. Per jyasskin@, casting
156     // to void is the commonly accepted way to convince the compiler
157     // that you're actually using a parameter/varible.
158     (void)create_flags;
159   }
160
161   bool IsOK() {
162     return And(ArgumentHolder<indices, ArgTypes>::ok...);
163   }
164
165   template <typename ReturnType>
166   void DispatchToCallback(base::Callback<ReturnType(ArgTypes...)> callback) {
167     args_->Return(callback.Run(ArgumentHolder<indices, ArgTypes>::value...));
168   }
169
170   // In C++, you can declare the function foo(void), but you can't pass a void
171   // expression to foo. As a result, we must specialize the case of Callbacks
172   // that have the void return type.
173   void DispatchToCallback(base::Callback<void(ArgTypes...)> callback) {
174     callback.Run(ArgumentHolder<indices, ArgTypes>::value...);
175   }
176
177  private:
178   static bool And() { return true; }
179   template <typename... T>
180   static bool And(bool arg1, T... args) {
181     return arg1 && And(args...);
182   }
183
184   Arguments* args_;
185 };
186
187 // DispatchToCallback converts all the JavaScript arguments to C++ types and
188 // invokes the base::Callback.
189 template <typename Sig>
190 struct Dispatcher {};
191
192 template <typename ReturnType, typename... ArgTypes>
193 struct Dispatcher<ReturnType(ArgTypes...)> {
194   static void DispatchToCallback(
195       const v8::FunctionCallbackInfo<v8::Value>& info) {
196     Arguments args(info);
197     v8::Handle<v8::External> v8_holder;
198     CHECK(args.GetData(&v8_holder));
199     CallbackHolderBase* holder_base = reinterpret_cast<CallbackHolderBase*>(
200         v8_holder->Value());
201
202     typedef CallbackHolder<ReturnType(ArgTypes...)> HolderT;
203     HolderT* holder = static_cast<HolderT*>(holder_base);
204
205     using Indices = typename IndicesGenerator<sizeof...(ArgTypes)>::type;
206     Invoker<Indices, ArgTypes...> invoker(&args, holder->flags);
207     if (invoker.IsOK())
208       invoker.DispatchToCallback(holder->callback);
209   }
210 };
211
212 }  // namespace internal
213
214
215 // CreateFunctionTemplate creates a v8::FunctionTemplate that will create
216 // JavaScript functions that execute a provided C++ function or base::Callback.
217 // JavaScript arguments are automatically converted via gin::Converter, as is
218 // the return value of the C++ function, if any.
219 template<typename Sig>
220 v8::Local<v8::FunctionTemplate> CreateFunctionTemplate(
221     v8::Isolate* isolate, const base::Callback<Sig> callback,
222     int callback_flags = 0) {
223   typedef internal::CallbackHolder<Sig> HolderT;
224   HolderT* holder = new HolderT(isolate, callback, callback_flags);
225
226   return v8::FunctionTemplate::New(
227       isolate,
228       &internal::Dispatcher<Sig>::DispatchToCallback,
229       ConvertToV8<v8::Handle<v8::External> >(isolate,
230                                              holder->GetHandle(isolate)));
231 }
232
233 // CreateFunctionHandler installs a CallAsFunction handler on the given
234 // object template that forwards to a provided C++ function or base::Callback.
235 template<typename Sig>
236 void CreateFunctionHandler(v8::Isolate* isolate,
237                            v8::Local<v8::ObjectTemplate> tmpl,
238                            const base::Callback<Sig> callback,
239                            int callback_flags = 0) {
240   typedef internal::CallbackHolder<Sig> HolderT;
241   HolderT* holder = new HolderT(isolate, callback, callback_flags);
242   tmpl->SetCallAsFunctionHandler(&internal::Dispatcher<Sig>::DispatchToCallback,
243                                  ConvertToV8<v8::Handle<v8::External> >(
244                                      isolate, holder->GetHandle(isolate)));
245 }
246
247 }  // namespace gin
248
249 #endif  // GIN_FUNCTION_TEMPLATE_H_