v8  9.4.146 (node 16.13.0)
V8 is Google's open source JavaScript engine
v8-fast-api-calls.h
Go to the documentation of this file.
1 // Copyright 2020 the V8 project 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 /**
6  * This file provides additional API on top of the default one for making
7  * API calls, which come from embedder C++ functions. The functions are being
8  * called directly from optimized code, doing all the necessary typechecks
9  * in the compiler itself, instead of on the embedder side. Hence the "fast"
10  * in the name. Example usage might look like:
11  *
12  * \code
13  * void FastMethod(int param, bool another_param);
14  *
15  * v8::FunctionTemplate::New(isolate, SlowCallback, data,
16  * signature, length, constructor_behavior
17  * side_effect_type,
18  * &v8::CFunction::Make(FastMethod));
19  * \endcode
20  *
21  * By design, fast calls are limited by the following requirements, which
22  * the embedder should enforce themselves:
23  * - they should not allocate on the JS heap;
24  * - they should not trigger JS execution.
25  * To enforce them, the embedder could use the existing
26  * v8::Isolate::DisallowJavascriptExecutionScope and a utility similar to
27  * Blink's NoAllocationScope:
28  * https://source.chromium.org/chromium/chromium/src/+/master:third_party/blink/renderer/platform/heap/thread_state_scopes.h;l=16
29  *
30  * Due to these limitations, it's not directly possible to report errors by
31  * throwing a JS exception or to otherwise do an allocation. There is an
32  * alternative way of creating fast calls that supports falling back to the
33  * slow call and then performing the necessary allocation. When one creates
34  * the fast method by using CFunction::MakeWithFallbackSupport instead of
35  * CFunction::Make, the fast callback gets as last parameter an output variable,
36  * through which it can request falling back to the slow call. So one might
37  * declare their method like:
38  *
39  * \code
40  * void FastMethodWithFallback(int param, FastApiCallbackOptions& options);
41  * \endcode
42  *
43  * If the callback wants to signal an error condition or to perform an
44  * allocation, it must set options.fallback to true and do an early return from
45  * the fast method. Then V8 checks the value of options.fallback and if it's
46  * true, falls back to executing the SlowCallback, which is capable of reporting
47  * the error (either by throwing a JS exception or logging to the console) or
48  * doing the allocation. It's the embedder's responsibility to ensure that the
49  * fast callback is idempotent up to the point where error and fallback
50  * conditions are checked, because otherwise executing the slow callback might
51  * produce visible side-effects twice.
52  *
53  * An example for custom embedder type support might employ a way to wrap/
54  * unwrap various C++ types in JSObject instances, e.g:
55  *
56  * \code
57  *
58  * // Helper method with a check for field count.
59  * template <typename T, int offset>
60  * inline T* GetInternalField(v8::Local<v8::Object> wrapper) {
61  * assert(offset < wrapper->InternalFieldCount());
62  * return reinterpret_cast<T*>(
63  * wrapper->GetAlignedPointerFromInternalField(offset));
64  * }
65  *
66  * class CustomEmbedderType {
67  * public:
68  * // Returns the raw C object from a wrapper JS object.
69  * static CustomEmbedderType* Unwrap(v8::Local<v8::Object> wrapper) {
70  * return GetInternalField<CustomEmbedderType,
71  * kV8EmbedderWrapperObjectIndex>(wrapper);
72  * }
73  * static void FastMethod(v8::Local<v8::Object> receiver_obj, int param) {
74  * CustomEmbedderType* receiver = static_cast<CustomEmbedderType*>(
75  * receiver_obj->GetAlignedPointerFromInternalField(
76  * kV8EmbedderWrapperObjectIndex));
77  *
78  * // Type checks are already done by the optimized code.
79  * // Then call some performance-critical method like:
80  * // receiver->Method(param);
81  * }
82  *
83  * static void SlowMethod(
84  * const v8::FunctionCallbackInfo<v8::Value>& info) {
85  * v8::Local<v8::Object> instance =
86  * v8::Local<v8::Object>::Cast(info.Holder());
87  * CustomEmbedderType* receiver = Unwrap(instance);
88  * // TODO: Do type checks and extract {param}.
89  * receiver->Method(param);
90  * }
91  * };
92  *
93  * // TODO(mslekova): Clean-up these constants
94  * // The constants kV8EmbedderWrapperTypeIndex and
95  * // kV8EmbedderWrapperObjectIndex describe the offsets for the type info
96  * // struct and the native object, when expressed as internal field indices
97  * // within a JSObject. The existance of this helper function assumes that
98  * // all embedder objects have their JSObject-side type info at the same
99  * // offset, but this is not a limitation of the API itself. For a detailed
100  * // use case, see the third example.
101  * static constexpr int kV8EmbedderWrapperTypeIndex = 0;
102  * static constexpr int kV8EmbedderWrapperObjectIndex = 1;
103  *
104  * // The following setup function can be templatized based on
105  * // the {embedder_object} argument.
106  * void SetupCustomEmbedderObject(v8::Isolate* isolate,
107  * v8::Local<v8::Context> context,
108  * CustomEmbedderType* embedder_object) {
109  * isolate->set_embedder_wrapper_type_index(
110  * kV8EmbedderWrapperTypeIndex);
111  * isolate->set_embedder_wrapper_object_index(
112  * kV8EmbedderWrapperObjectIndex);
113  *
114  * v8::CFunction c_func =
115  * MakeV8CFunction(CustomEmbedderType::FastMethod);
116  *
117  * Local<v8::FunctionTemplate> method_template =
118  * v8::FunctionTemplate::New(
119  * isolate, CustomEmbedderType::SlowMethod, v8::Local<v8::Value>(),
120  * v8::Local<v8::Signature>(), 1, v8::ConstructorBehavior::kAllow,
121  * v8::SideEffectType::kHasSideEffect, &c_func);
122  *
123  * v8::Local<v8::ObjectTemplate> object_template =
124  * v8::ObjectTemplate::New(isolate);
125  * object_template->SetInternalFieldCount(
126  * kV8EmbedderWrapperObjectIndex + 1);
127  * object_template->Set(isolate, "method", method_template);
128  *
129  * // Instantiate the wrapper JS object.
130  * v8::Local<v8::Object> object =
131  * object_template->NewInstance(context).ToLocalChecked();
132  * object->SetAlignedPointerInInternalField(
133  * kV8EmbedderWrapperObjectIndex,
134  * reinterpret_cast<void*>(embedder_object));
135  *
136  * // TODO: Expose {object} where it's necessary.
137  * }
138  * \endcode
139  *
140  * For instance if {object} is exposed via a global "obj" variable,
141  * one could write in JS:
142  * function hot_func() {
143  * obj.method(42);
144  * }
145  * and once {hot_func} gets optimized, CustomEmbedderType::FastMethod
146  * will be called instead of the slow version, with the following arguments:
147  * receiver := the {embedder_object} from above
148  * param := 42
149  *
150  * Currently supported return types:
151  * - void
152  * - bool
153  * - int32_t
154  * - uint32_t
155  * - float32_t
156  * - float64_t
157  * Currently supported argument types:
158  * - pointer to an embedder type
159  * - JavaScript array of primitive types
160  * - bool
161  * - int32_t
162  * - uint32_t
163  * - int64_t
164  * - uint64_t
165  * - float32_t
166  * - float64_t
167  *
168  * The 64-bit integer types currently have the IDL (unsigned) long long
169  * semantics: https://heycam.github.io/webidl/#abstract-opdef-converttoint
170  * In the future we'll extend the API to also provide conversions from/to
171  * BigInt to preserve full precision.
172  * The floating point types currently have the IDL (unrestricted) semantics,
173  * which is the only one used by WebGL. We plan to add support also for
174  * restricted floats/doubles, similarly to the BigInt conversion policies.
175  * We also differ from the specific NaN bit pattern that WebIDL prescribes
176  * (https://heycam.github.io/webidl/#es-unrestricted-float) in that Blink
177  * passes NaN values as-is, i.e. doesn't normalize them.
178  *
179  * To be supported types:
180  * - TypedArrays and ArrayBuffers
181  * - arrays of embedder types
182  *
183  *
184  * The API offers a limited support for function overloads:
185  *
186  * \code
187  * void FastMethod_2Args(int param, bool another_param);
188  * void FastMethod_3Args(int param, bool another_param, int third_param);
189  *
190  * v8::CFunction fast_method_2args_c_func =
191  * MakeV8CFunction(FastMethod_2Args);
192  * v8::CFunction fast_method_3args_c_func =
193  * MakeV8CFunction(FastMethod_3Args);
194  * const v8::CFunction fast_method_overloads[] = {fast_method_2args_c_func,
195  * fast_method_3args_c_func};
196  * Local<v8::FunctionTemplate> method_template =
197  * v8::FunctionTemplate::NewWithCFunctionOverloads(
198  * isolate, SlowCallback, data, signature, length,
199  * constructor_behavior, side_effect_type,
200  * {fast_method_overloads, 2});
201  * \endcode
202  *
203  * In this example a single FunctionTemplate is associated to multiple C++
204  * functions. The overload resolution is currently only based on the number of
205  * arguments passed in a call. For example, if this method_template is
206  * registered with a wrapper JS object as described above, a call with two
207  * arguments:
208  * obj.method(42, true);
209  * will result in a fast call to FastMethod_2Args, while a call with three or
210  * more arguments:
211  * obj.method(42, true, 11);
212  * will result in a fast call to FastMethod_3Args. Instead a call with less than
213  * two arguments, like:
214  * obj.method(42);
215  * would not result in a fast call but would fall back to executing the
216  * associated SlowCallback.
217  */
218 
219 #ifndef INCLUDE_V8_FAST_API_CALLS_H_
220 #define INCLUDE_V8_FAST_API_CALLS_H_
221 
222 #include <stddef.h>
223 #include <stdint.h>
224 
225 #include <tuple>
226 #include <type_traits>
227 
228 #include "v8-internal.h" // NOLINT(build/include_directory)
229 #include "v8.h" // NOLINT(build/include_directory)
230 #include "v8config.h" // NOLINT(build/include_directory)
231 
232 namespace v8 {
233 
234 class Isolate;
235 
236 class CTypeInfo {
237  public:
238  enum class Type : uint8_t {
239  kVoid,
240  kBool,
241  kInt32,
242  kUint32,
243  kInt64,
244  kUint64,
245  kFloat32,
246  kFloat64,
247  kV8Value,
248  kApiObject, // This will be deprecated once all users have
249  // migrated from v8::ApiObject to v8::Local<v8::Value>.
250  };
251 
252  // kCallbackOptionsType is not part of the Type enum
253  // because it is only used internally. Use value 255 that is larger
254  // than any valid Type enum.
255  static constexpr Type kCallbackOptionsType = Type(255);
256 
257  enum class SequenceType : uint8_t {
258  kScalar,
259  kIsSequence, // sequence<T>
260  kIsTypedArray, // TypedArray of T or any ArrayBufferView if T
261  // is void
262  kIsArrayBuffer // ArrayBuffer
263  };
264 
265  enum class Flags : uint8_t {
266  kNone = 0,
267  kAllowSharedBit = 1 << 0, // Must be an ArrayBuffer or TypedArray
268  kEnforceRangeBit = 1 << 1, // T must be integral
269  kClampBit = 1 << 2, // T must be integral
270  kIsRestrictedBit = 1 << 3, // T must be float or double
271  };
272 
273  explicit constexpr CTypeInfo(
274  Type type, SequenceType sequence_type = SequenceType::kScalar,
275  Flags flags = Flags::kNone)
276  : type_(type), sequence_type_(sequence_type), flags_(flags) {}
277 
278  constexpr Type GetType() const { return type_; }
279  constexpr SequenceType GetSequenceType() const { return sequence_type_; }
280  constexpr Flags GetFlags() const { return flags_; }
281 
282  static constexpr bool IsIntegralType(Type type) {
283  return type == Type::kInt32 || type == Type::kUint32 ||
284  type == Type::kInt64 || type == Type::kUint64;
285  }
286 
287  static constexpr bool IsFloatingPointType(Type type) {
288  return type == Type::kFloat32 || type == Type::kFloat64;
289  }
290 
291  static constexpr bool IsPrimitive(Type type) {
292  return IsIntegralType(type) || IsFloatingPointType(type) ||
293  type == Type::kBool;
294  }
295 
296  private:
297  Type type_;
298  SequenceType sequence_type_;
299  Flags flags_;
300 };
301 
303  public:
304  // Returns the length in number of elements.
305  size_t V8_EXPORT length() const { return length_; }
306  // Checks whether the given index is within the bounds of the collection.
307  void V8_EXPORT ValidateIndex(size_t index) const;
308 
309  protected:
310  size_t length_ = 0;
311 };
312 
313 template <typename T>
315  public:
316  V8_INLINE T get(size_t index) const {
317 #ifdef DEBUG
318  ValidateIndex(index);
319 #endif // DEBUG
320  T tmp;
321  memcpy(&tmp, reinterpret_cast<T*>(data_) + index, sizeof(T));
322  return tmp;
323  }
324 
325  private:
326  // This pointer should include the typed array offset applied.
327  // It's not guaranteed that it's aligned to sizeof(T), it's only
328  // guaranteed that it's 4-byte aligned, so for 8-byte types we need to
329  // provide a special implementation for reading from it, which hides
330  // the possibly unaligned read in the `get` method.
331  void* data_;
332 };
333 
334 // Any TypedArray. It uses kTypedArrayBit with base type void
335 // Overloaded args of ArrayBufferView and TypedArray are not supported
336 // (for now) because the generic “any” ArrayBufferView doesn’t have its
337 // own instance type. It could be supported if we specify that
338 // TypedArray<T> always has precedence over the generic ArrayBufferView,
339 // but this complicates overload resolution.
341  void* data;
342  size_t byte_length;
343 };
344 
346  void* data;
347  size_t byte_length;
348 };
349 
351  public:
352  // Construct a struct to hold a CFunction's type information.
353  // |return_info| describes the function's return type.
354  // |arg_info| is an array of |arg_count| CTypeInfos describing the
355  // arguments. Only the last argument may be of the special type
356  // CTypeInfo::kCallbackOptionsType.
357  CFunctionInfo(const CTypeInfo& return_info, unsigned int arg_count,
358  const CTypeInfo* arg_info);
359 
360  const CTypeInfo& ReturnInfo() const { return return_info_; }
361 
362  // The argument count, not including the v8::FastApiCallbackOptions
363  // if present.
364  unsigned int ArgumentCount() const {
365  return HasOptions() ? arg_count_ - 1 : arg_count_;
366  }
367 
368  // |index| must be less than ArgumentCount().
369  // Note: if the last argument passed on construction of CFunctionInfo
370  // has type CTypeInfo::kCallbackOptionsType, it is not included in
371  // ArgumentCount().
372  const CTypeInfo& ArgumentInfo(unsigned int index) const;
373 
374  bool HasOptions() const {
375  // The options arg is always the last one.
376  return arg_count_ > 0 && arg_info_[arg_count_ - 1].GetType() ==
378  }
379 
380  private:
381  const CTypeInfo return_info_;
382  const unsigned int arg_count_;
383  const CTypeInfo* arg_info_;
384 };
385 
387  public:
388  constexpr CFunction() : address_(nullptr), type_info_(nullptr) {}
389 
390  const CTypeInfo& ReturnInfo() const { return type_info_->ReturnInfo(); }
391 
392  const CTypeInfo& ArgumentInfo(unsigned int index) const {
393  return type_info_->ArgumentInfo(index);
394  }
395 
396  unsigned int ArgumentCount() const { return type_info_->ArgumentCount(); }
397 
398  const void* GetAddress() const { return address_; }
399  const CFunctionInfo* GetTypeInfo() const { return type_info_; }
400 
402 
403  // Returns whether an overload between this and the given CFunction can
404  // be resolved at runtime by the RTTI available for the arguments or at
405  // compile time for functions with different number of arguments.
407  // Runtime overload resolution can only deal with functions with the
408  // same number of arguments. Functions with different arity are handled
409  // by compile time overload resolution though.
410  if (ArgumentCount() != other->ArgumentCount()) {
412  }
413 
414  // The functions can only differ by a single argument position.
415  int diff_index = -1;
416  for (unsigned int i = 0; i < ArgumentCount(); ++i) {
419  if (diff_index >= 0) {
421  }
422  diff_index = i;
423 
424  // We only support overload resolution between sequence types.
430  }
431  }
432  }
433 
435  }
436 
437  template <typename F>
438  static CFunction Make(F* func) {
439  return ArgUnwrap<F*>::Make(func);
440  }
441 
442  template <typename F>
443  V8_DEPRECATED("Use CFunctionBuilder instead.")
445  return ArgUnwrap<F*>::Make(func);
446  }
447 
448  CFunction(const void* address, const CFunctionInfo* type_info);
449 
450  private:
451  const void* address_;
452  const CFunctionInfo* type_info_;
453 
454  template <typename F>
455  class ArgUnwrap {
456  static_assert(sizeof(F) != sizeof(F),
457  "CFunction must be created from a function pointer.");
458  };
459 
460  template <typename R, typename... Args>
461  class ArgUnwrap<R (*)(Args...)> {
462  public:
463  static CFunction Make(R (*func)(Args...));
464  };
465 };
466 
467 struct V8_DEPRECATE_SOON("Use v8::Local<v8::Value> instead.") ApiObject {
468  uintptr_t address;
469 };
470 
471 /**
472  * A struct which may be passed to a fast call callback, like so:
473  * \code
474  * void FastMethodWithOptions(int param, FastApiCallbackOptions& options);
475  * \endcode
476  */
478  /**
479  * Creates a new instance of FastApiCallbackOptions for testing purpose. The
480  * returned instance may be filled with mock data.
481  */
483  return {false, {0}};
484  }
485 
486  /**
487  * If the callback wants to signal an error condition or to perform an
488  * allocation, it must set options.fallback to true and do an early return
489  * from the fast method. Then V8 checks the value of options.fallback and if
490  * it's true, falls back to executing the SlowCallback, which is capable of
491  * reporting the error (either by throwing a JS exception or logging to the
492  * console) or doing the allocation. It's the embedder's responsibility to
493  * ensure that the fast callback is idempotent up to the point where error and
494  * fallback conditions are checked, because otherwise executing the slow
495  * callback might produce visible side-effects twice.
496  */
497  bool fallback;
498 
499  /**
500  * The `data` passed to the FunctionTemplate constructor, or `undefined`.
501  * `data_ptr` allows for default constructing FastApiCallbackOptions.
502  */
503  union {
504  uintptr_t data_ptr;
506  };
507 };
508 
509 namespace internal {
510 
511 // Helper to count the number of occurances of `T` in `List`
512 template <typename T, typename... List>
513 struct count : std::integral_constant<int, 0> {};
514 template <typename T, typename... Args>
515 struct count<T, T, Args...>
516  : std::integral_constant<std::size_t, 1 + count<T, Args...>::value> {};
517 template <typename T, typename U, typename... Args>
518 struct count<T, U, Args...> : count<T, Args...> {};
519 
520 template <typename RetBuilder, typename... ArgBuilders>
522  static constexpr int kOptionsArgCount =
523  count<FastApiCallbackOptions&, ArgBuilders...>();
524  static constexpr int kReceiverCount = 1;
525 
526  static_assert(kOptionsArgCount == 0 || kOptionsArgCount == 1,
527  "Only one options parameter is supported.");
528 
529  static_assert(sizeof...(ArgBuilders) >= kOptionsArgCount + kReceiverCount,
530  "The receiver or the options argument is missing.");
531 
532  public:
533  constexpr CFunctionInfoImpl()
534  : CFunctionInfo(RetBuilder::Build(), sizeof...(ArgBuilders),
535  arg_info_storage_),
536  arg_info_storage_{ArgBuilders::Build()...} {
537  constexpr CTypeInfo::Type kReturnType = RetBuilder::Build().GetType();
538  static_assert(kReturnType == CTypeInfo::Type::kVoid ||
539  kReturnType == CTypeInfo::Type::kBool ||
540  kReturnType == CTypeInfo::Type::kInt32 ||
541  kReturnType == CTypeInfo::Type::kUint32 ||
542  kReturnType == CTypeInfo::Type::kFloat32 ||
543  kReturnType == CTypeInfo::Type::kFloat64,
544  "64-bit int and api object values are not currently "
545  "supported return types.");
546  }
547 
548  private:
549  const CTypeInfo arg_info_storage_[sizeof...(ArgBuilders)];
550 };
551 
552 template <typename T>
554  static_assert(sizeof(T) != sizeof(T), "This type is not supported");
555 };
556 
557 #define SPECIALIZE_GET_TYPE_INFO_HELPER_FOR(T, Enum)
558  template <>
559  struct TypeInfoHelper<T> {
560  static constexpr CTypeInfo::Flags Flags() {
561  return CTypeInfo::Flags::kNone;
562  }
563 
564  static constexpr CTypeInfo::Type Type() { return CTypeInfo::Type::Enum; }
565  static constexpr CTypeInfo::SequenceType SequenceType() {
566  return CTypeInfo::SequenceType::kScalar;
567  }
568  };
569 
570 template <CTypeInfo::Type type>
571 struct CTypeInfoTraits {};
572 
573 #define DEFINE_TYPE_INFO_TRAITS(CType, Enum)
574  template <>
575  struct CTypeInfoTraits<CTypeInfo::Type::Enum> {
576  using ctype = CType;
577  };
578 
579 #define PRIMITIVE_C_TYPES(V)
580  V(bool, kBool)
581  V(int32_t, kInt32)
582  V(uint32_t, kUint32)
583  V(int64_t, kInt64)
584  V(uint64_t, kUint64)
585  V(float, kFloat32)
586  V(double, kFloat64)
587 
588 // Same as above, but includes deprecated types for compatibility.
589 #define ALL_C_TYPES(V)
590  PRIMITIVE_C_TYPES(V)
591  V(void, kVoid)
592  V(v8::Local<v8::Value>, kV8Value)
593  V(v8::Local<v8::Object>, kV8Value)
594  V(ApiObject, kApiObject)
595 
596 // ApiObject was a temporary solution to wrap the pointer to the v8::Value.
597 // Please use v8::Local<v8::Value> in new code for the arguments and
598 // v8::Local<v8::Object> for the receiver, as ApiObject will be deprecated.
599 
602 
603 #undef PRIMITIVE_C_TYPES
604 #undef ALL_C_TYPES
605 
606 #define SPECIALIZE_GET_TYPE_INFO_HELPER_FOR_TA(T, Enum)
607  template <>
608  struct TypeInfoHelper<const FastApiTypedArray<T>&> {
609  static constexpr CTypeInfo::Flags Flags() {
610  return CTypeInfo::Flags::kNone;
611  }
612 
613  static constexpr CTypeInfo::Type Type() { return CTypeInfo::Type::Enum; }
614  static constexpr CTypeInfo::SequenceType SequenceType() {
615  return CTypeInfo::SequenceType::kIsTypedArray;
616  }
617  };
618 
619 #define TYPED_ARRAY_C_TYPES(V)
620  V(int32_t, kInt32)
621  V(uint32_t, kUint32)
622  V(int64_t, kInt64)
623  V(uint64_t, kUint64)
624  V(float, kFloat32)
625  V(double, kFloat64)
626 
628 
629 #undef TYPED_ARRAY_C_TYPES
630 
631 template <>
633  static constexpr CTypeInfo::Flags Flags() { return CTypeInfo::Flags::kNone; }
634 
635  static constexpr CTypeInfo::Type Type() { return CTypeInfo::Type::kVoid; }
636  static constexpr CTypeInfo::SequenceType SequenceType() {
638  }
639 };
640 
641 template <>
643  static constexpr CTypeInfo::Flags Flags() { return CTypeInfo::Flags::kNone; }
644 
645  static constexpr CTypeInfo::Type Type() { return CTypeInfo::Type::kUint32; }
646  static constexpr CTypeInfo::SequenceType SequenceType() {
648  }
649 };
650 
651 template <>
653  static constexpr CTypeInfo::Flags Flags() { return CTypeInfo::Flags::kNone; }
654 
655  static constexpr CTypeInfo::Type Type() {
657  }
658  static constexpr CTypeInfo::SequenceType SequenceType() {
660  }
661 };
662 
663 #define STATIC_ASSERT_IMPLIES(COND, ASSERTION, MSG)
664  static_assert(((COND) == 0) || (ASSERTION), MSG)
665 
666 template <typename T, CTypeInfo::Flags... Flags>
668  public:
669  using BaseType = T;
670 
671  static constexpr CTypeInfo Build() {
672  constexpr CTypeInfo::Flags kFlags =
673  MergeFlags(TypeInfoHelper<T>::Flags(), Flags...);
674  constexpr CTypeInfo::Type kType = TypeInfoHelper<T>::Type();
675  constexpr CTypeInfo::SequenceType kSequenceType =
676  TypeInfoHelper<T>::SequenceType();
677 
679  uint8_t(kFlags) & uint8_t(CTypeInfo::Flags::kAllowSharedBit),
680  (kSequenceType == CTypeInfo::SequenceType::kIsTypedArray ||
681  kSequenceType == CTypeInfo::SequenceType::kIsArrayBuffer),
682  "kAllowSharedBit is only allowed for TypedArrays and ArrayBuffers.");
684  uint8_t(kFlags) & uint8_t(CTypeInfo::Flags::kEnforceRangeBit),
686  "kEnforceRangeBit is only allowed for integral types.");
688  uint8_t(kFlags) & uint8_t(CTypeInfo::Flags::kClampBit),
690  "kClampBit is only allowed for integral types.");
692  uint8_t(kFlags) & uint8_t(CTypeInfo::Flags::kIsRestrictedBit),
694  "kIsRestrictedBit is only allowed for floating point types.");
696  kType == CTypeInfo::Type::kVoid,
697  "Sequences are only supported from void type.");
701  "TypedArrays are only supported from primitive types or void.");
702 
703  // Return the same type with the merged flags.
704  return CTypeInfo(TypeInfoHelper<T>::Type(),
705  TypeInfoHelper<T>::SequenceType(), kFlags);
706  }
707 
708  private:
709  template <typename... Rest>
710  static constexpr CTypeInfo::Flags MergeFlags(CTypeInfo::Flags flags,
711  Rest... rest) {
712  return CTypeInfo::Flags(uint8_t(flags) | uint8_t(MergeFlags(rest...)));
713  }
714  static constexpr CTypeInfo::Flags MergeFlags() { return CTypeInfo::Flags(0); }
715 };
716 
717 template <typename RetBuilder, typename... ArgBuilders>
719  public:
720  explicit constexpr CFunctionBuilderWithFunction(const void* fn) : fn_(fn) {}
721 
722  template <CTypeInfo::Flags... Flags>
723  constexpr auto Ret() {
725  CTypeInfoBuilder<typename RetBuilder::BaseType, Flags...>,
726  ArgBuilders...>(fn_);
727  }
728 
729  template <unsigned int N, CTypeInfo::Flags... Flags>
730  constexpr auto Arg() {
731  // Return a copy of the builder with the Nth arg builder merged with
732  // template parameter pack Flags.
733  return ArgImpl<N, Flags...>(
734  std::make_index_sequence<sizeof...(ArgBuilders)>());
735  }
736 
737  auto Build() {
738  static CFunctionInfoImpl<RetBuilder, ArgBuilders...> instance;
739  return CFunction(fn_, &instance);
740  }
741 
742  private:
743  template <bool Merge, unsigned int N, CTypeInfo::Flags... Flags>
744  struct GetArgBuilder;
745 
746  // Returns the same ArgBuilder as the one at index N, including its flags.
747  // Flags in the template parameter pack are ignored.
748  template <unsigned int N, CTypeInfo::Flags... Flags>
749  struct GetArgBuilder<false, N, Flags...> {
750  using type =
751  typename std::tuple_element<N, std::tuple<ArgBuilders...>>::type;
752  };
753 
754  // Returns an ArgBuilder with the same base type as the one at index N,
755  // but merges the flags with the flags in the template parameter pack.
756  template <unsigned int N, CTypeInfo::Flags... Flags>
757  struct GetArgBuilder<true, N, Flags...> {
758  using type = CTypeInfoBuilder<
759  typename std::tuple_element<N,
760  std::tuple<ArgBuilders...>>::type::BaseType,
761  std::tuple_element<N, std::tuple<ArgBuilders...>>::type::Build()
762  .GetFlags(),
763  Flags...>;
764  };
765 
766  // Return a copy of the CFunctionBuilder, but merges the Flags on
767  // ArgBuilder index N with the new Flags passed in the template parameter
768  // pack.
769  template <unsigned int N, CTypeInfo::Flags... Flags, size_t... I>
770  constexpr auto ArgImpl(std::index_sequence<I...>) {
772  RetBuilder, typename GetArgBuilder<N == I, I, Flags...>::type...>(fn_);
773  }
774 
775  const void* fn_;
776 };
777 
779  public:
780  constexpr CFunctionBuilder() {}
781 
782  template <typename R, typename... Args>
783  constexpr auto Fn(R (*fn)(Args...)) {
785  CTypeInfoBuilder<Args>...>(
786  reinterpret_cast<const void*>(fn));
787  }
788 };
789 
790 } // namespace internal
791 
792 // static
793 template <typename R, typename... Args>
794 CFunction CFunction::ArgUnwrap<R (*)(Args...)>::Make(R (*func)(Args...)) {
795  return internal::CFunctionBuilder().Fn(func).Build();
796 }
797 
798 using CFunctionBuilder = internal::CFunctionBuilder;
799 
800 static constexpr CTypeInfo kTypeInfoInt32 = CTypeInfo(CTypeInfo::Type::kInt32);
801 static constexpr CTypeInfo kTypeInfoFloat64 =
803 
804 /**
805  * Copies the contents of this JavaScript array to a C++ buffer with
806  * a given max_length. A CTypeInfo is passed as an argument,
807  * instructing different rules for conversion (e.g. restricted float/double).
808  * The element type T of the destination array must match the C type
809  * corresponding to the CTypeInfo (specified by CTypeInfoTraits).
810  * If the array length is larger than max_length or the array is of
811  * unsupported type, the operation will fail, returning false. Generally, an
812  * array which contains objects, undefined, null or anything not convertible
813  * to the requested destination type, is considered unsupported. The operation
814  * returns true on success. `type_info` will be used for conversions.
815  */
816 template <const CTypeInfo* type_info, typename T>
818  Local<Array> src, T* dst, uint32_t max_length);
819 
820 template <>
823  Local<Array> src, int32_t* dst, uint32_t max_length) {
824  return CopyAndConvertArrayToCppBufferInt32(src, dst, max_length);
825 }
826 
827 template <>
830  Local<Array> src, double* dst, uint32_t max_length) {
831  return CopyAndConvertArrayToCppBufferFloat64(src, dst, max_length);
832 }
833 
834 } // namespace v8
835 
836 #endif // INCLUDE_V8_FAST_API_CALLS_H_