395354341120de691db72afbd7b69f433b5e8f63
[platform/upstream/v8.git] / include / v8.h
1 // Copyright 2012 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 /** \mainpage V8 API Reference Guide
6  *
7  * V8 is Google's open source JavaScript engine.
8  *
9  * This set of documents provides reference material generated from the
10  * V8 header file, include/v8.h.
11  *
12  * For other documentation see http://code.google.com/apis/v8/
13  */
14
15 #ifndef V8_H_
16 #define V8_H_
17
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stdio.h>
21
22 #include "v8-version.h"  // NOLINT(build/include)
23 #include "v8config.h"    // NOLINT(build/include)
24
25 // We reserve the V8_* prefix for macros defined in V8 public API and
26 // assume there are no name conflicts with the embedder's code.
27
28 #ifdef V8_OS_WIN
29
30 // Setup for Windows DLL export/import. When building the V8 DLL the
31 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
32 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
33 // static library or building a program which uses the V8 static library neither
34 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
35 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
36 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
37   build configuration to ensure that at most one of these is set
38 #endif
39
40 #ifdef BUILDING_V8_SHARED
41 # define V8_EXPORT __declspec(dllexport)
42 #elif USING_V8_SHARED
43 # define V8_EXPORT __declspec(dllimport)
44 #else
45 # define V8_EXPORT
46 #endif  // BUILDING_V8_SHARED
47
48 #else  // V8_OS_WIN
49
50 // Setup for Linux shared library export.
51 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
52 # ifdef BUILDING_V8_SHARED
53 #  define V8_EXPORT __attribute__ ((visibility("default")))
54 # else
55 #  define V8_EXPORT
56 # endif
57 #else
58 # define V8_EXPORT
59 #endif
60
61 #endif  // V8_OS_WIN
62
63 /**
64  * The v8 JavaScript engine.
65  */
66 namespace v8 {
67
68 class AccessorSignature;
69 class Array;
70 class Boolean;
71 class BooleanObject;
72 class Context;
73 class CpuProfiler;
74 class Data;
75 class Date;
76 class External;
77 class Function;
78 class FunctionTemplate;
79 class HeapProfiler;
80 class ImplementationUtilities;
81 class Int32;
82 class Integer;
83 class Isolate;
84 template <class T>
85 class Maybe;
86 class Name;
87 class Number;
88 class NumberObject;
89 class Object;
90 class ObjectOperationDescriptor;
91 class ObjectTemplate;
92 class Platform;
93 class Primitive;
94 class Promise;
95 class RawOperationDescriptor;
96 class Script;
97 class SharedArrayBuffer;
98 class Signature;
99 class StartupData;
100 class StackFrame;
101 class StackTrace;
102 class String;
103 class StringObject;
104 class Symbol;
105 class SymbolObject;
106 class Uint32;
107 class Utils;
108 class Value;
109 template <class T> class Local;
110 template <class T>
111 class MaybeLocal;
112 template <class T> class Eternal;
113 template<class T> class NonCopyablePersistentTraits;
114 template<class T> class PersistentBase;
115 template <class T, class M = NonCopyablePersistentTraits<T> >
116 class Persistent;
117 template <class T>
118 class Global;
119 template<class K, class V, class T> class PersistentValueMap;
120 template <class K, class V, class T>
121 class PersistentValueMapBase;
122 template <class K, class V, class T>
123 class GlobalValueMap;
124 template<class V, class T> class PersistentValueVector;
125 template<class T, class P> class WeakCallbackObject;
126 class FunctionTemplate;
127 class ObjectTemplate;
128 class Data;
129 template<typename T> class FunctionCallbackInfo;
130 template<typename T> class PropertyCallbackInfo;
131 class StackTrace;
132 class StackFrame;
133 class Isolate;
134 class CallHandlerHelper;
135 class EscapableHandleScope;
136 template<typename T> class ReturnValue;
137
138 namespace internal {
139 class Arguments;
140 class Heap;
141 class HeapObject;
142 class Isolate;
143 class Object;
144 struct StreamedSource;
145 template<typename T> class CustomArguments;
146 class PropertyCallbackArguments;
147 class FunctionCallbackArguments;
148 class GlobalHandles;
149 }
150
151
152 /**
153  * General purpose unique identifier.
154  */
155 class UniqueId {
156  public:
157   explicit UniqueId(intptr_t data)
158       : data_(data) {}
159
160   bool operator==(const UniqueId& other) const {
161     return data_ == other.data_;
162   }
163
164   bool operator!=(const UniqueId& other) const {
165     return data_ != other.data_;
166   }
167
168   bool operator<(const UniqueId& other) const {
169     return data_ < other.data_;
170   }
171
172  private:
173   intptr_t data_;
174 };
175
176 // --- Handles ---
177
178 #define TYPE_CHECK(T, S)                                       \
179   while (false) {                                              \
180     *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);      \
181   }
182
183
184 /**
185  * An object reference managed by the v8 garbage collector.
186  *
187  * All objects returned from v8 have to be tracked by the garbage
188  * collector so that it knows that the objects are still alive.  Also,
189  * because the garbage collector may move objects, it is unsafe to
190  * point directly to an object.  Instead, all objects are stored in
191  * handles which are known by the garbage collector and updated
192  * whenever an object moves.  Handles should always be passed by value
193  * (except in cases like out-parameters) and they should never be
194  * allocated on the heap.
195  *
196  * There are two types of handles: local and persistent handles.
197  * Local handles are light-weight and transient and typically used in
198  * local operations.  They are managed by HandleScopes.  Persistent
199  * handles can be used when storing objects across several independent
200  * operations and have to be explicitly deallocated when they're no
201  * longer used.
202  *
203  * It is safe to extract the object stored in the handle by
204  * dereferencing the handle (for instance, to extract the Object* from
205  * a Local<Object>); the value will still be governed by a handle
206  * behind the scenes and the same rules apply to these values as to
207  * their handles.
208  */
209 template <class T>
210 class Local {
211  public:
212   V8_INLINE Local() : val_(0) {}
213   template <class S>
214   V8_INLINE Local(Local<S> that)
215       : val_(reinterpret_cast<T*>(*that)) {
216     /**
217      * This check fails when trying to convert between incompatible
218      * handles. For example, converting from a Local<String> to a
219      * Local<Number>.
220      */
221     TYPE_CHECK(T, S);
222   }
223
224   /**
225    * Returns true if the handle is empty.
226    */
227   V8_INLINE bool IsEmpty() const { return val_ == 0; }
228
229   /**
230    * Sets the handle to be empty. IsEmpty() will then return true.
231    */
232   V8_INLINE void Clear() { val_ = 0; }
233
234   V8_INLINE T* operator->() const { return val_; }
235
236   V8_INLINE T* operator*() const { return val_; }
237
238   /**
239    * Checks whether two handles are the same.
240    * Returns true if both are empty, or if the objects
241    * to which they refer are identical.
242    * The handles' references are not checked.
243    */
244   template <class S>
245   V8_INLINE bool operator==(const Local<S>& that) const {
246     internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
247     internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
248     if (a == 0) return b == 0;
249     if (b == 0) return false;
250     return *a == *b;
251   }
252
253   template <class S> V8_INLINE bool operator==(
254       const PersistentBase<S>& that) const {
255     internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
256     internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
257     if (a == 0) return b == 0;
258     if (b == 0) return false;
259     return *a == *b;
260   }
261
262   /**
263    * Checks whether two handles are different.
264    * Returns true if only one of the handles is empty, or if
265    * the objects to which they refer are different.
266    * The handles' references are not checked.
267    */
268   template <class S>
269   V8_INLINE bool operator!=(const Local<S>& that) const {
270     return !operator==(that);
271   }
272
273   template <class S> V8_INLINE bool operator!=(
274       const Persistent<S>& that) const {
275     return !operator==(that);
276   }
277
278   template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
279 #ifdef V8_ENABLE_CHECKS
280     // If we're going to perform the type check then we have to check
281     // that the handle isn't empty before doing the checked cast.
282     if (that.IsEmpty()) return Local<T>();
283 #endif
284     return Local<T>(T::Cast(*that));
285   }
286
287
288   template <class S> V8_INLINE Local<S> As() {
289     return Local<S>::Cast(*this);
290   }
291
292   /**
293    * Create a local handle for the content of another handle.
294    * The referee is kept alive by the local handle even when
295    * the original handle is destroyed/disposed.
296    */
297   V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
298   V8_INLINE static Local<T> New(Isolate* isolate,
299                                 const PersistentBase<T>& that);
300
301  private:
302   friend class Utils;
303   template<class F> friend class Eternal;
304   template<class F> friend class PersistentBase;
305   template<class F, class M> friend class Persistent;
306   template<class F> friend class Local;
307   template <class F>
308   friend class MaybeLocal;
309   template<class F> friend class FunctionCallbackInfo;
310   template<class F> friend class PropertyCallbackInfo;
311   friend class String;
312   friend class Object;
313   friend class Context;
314   template<class F> friend class internal::CustomArguments;
315   friend Local<Primitive> Undefined(Isolate* isolate);
316   friend Local<Primitive> Null(Isolate* isolate);
317   friend Local<Boolean> True(Isolate* isolate);
318   friend Local<Boolean> False(Isolate* isolate);
319   friend class HandleScope;
320   friend class EscapableHandleScope;
321   template <class F1, class F2, class F3>
322   friend class PersistentValueMapBase;
323   template<class F1, class F2> friend class PersistentValueVector;
324
325   template <class S>
326   V8_INLINE Local(S* that)
327       : val_(that) {}
328   V8_INLINE static Local<T> New(Isolate* isolate, T* that);
329   T* val_;
330 };
331
332
333 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
334 // Local is an alias for Local for historical reasons.
335 template <class T>
336 using Handle = Local<T>;
337 #endif
338
339
340 /**
341  * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
342  * the Local<> is empty before it can be used.
343  *
344  * If an API method returns a MaybeLocal<>, the API method can potentially fail
345  * either because an exception is thrown, or because an exception is pending,
346  * e.g. because a previous API call threw an exception that hasn't been caught
347  * yet, or because a TerminateExecution exception was thrown. In that case, an
348  * empty MaybeLocal is returned.
349  */
350 template <class T>
351 class MaybeLocal {
352  public:
353   V8_INLINE MaybeLocal() : val_(nullptr) {}
354   template <class S>
355   V8_INLINE MaybeLocal(Local<S> that)
356       : val_(reinterpret_cast<T*>(*that)) {
357     TYPE_CHECK(T, S);
358   }
359
360   V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
361
362   template <class S>
363   V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const {
364     out->val_ = IsEmpty() ? nullptr : this->val_;
365     return !IsEmpty();
366   }
367
368   // Will crash if the MaybeLocal<> is empty.
369   V8_INLINE Local<T> ToLocalChecked();
370
371   template <class S>
372   V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
373     return IsEmpty() ? default_value : Local<S>(val_);
374   }
375
376  private:
377   T* val_;
378 };
379
380
381 // Eternal handles are set-once handles that live for the life of the isolate.
382 template <class T> class Eternal {
383  public:
384   V8_INLINE Eternal() : index_(kInitialValue) { }
385   template<class S>
386   V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
387     Set(isolate, handle);
388   }
389   // Can only be safely called if already set.
390   V8_INLINE Local<T> Get(Isolate* isolate);
391   V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
392   template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
393
394  private:
395   static const int kInitialValue = -1;
396   int index_;
397 };
398
399
400 static const int kInternalFieldsInWeakCallback = 2;
401
402
403 template <typename T>
404 class WeakCallbackInfo {
405  public:
406   typedef void (*Callback)(const WeakCallbackInfo<T>& data);
407
408   WeakCallbackInfo(Isolate* isolate, T* parameter,
409                    void* internal_fields[kInternalFieldsInWeakCallback],
410                    Callback* callback)
411       : isolate_(isolate), parameter_(parameter), callback_(callback) {
412     for (int i = 0; i < kInternalFieldsInWeakCallback; ++i) {
413       internal_fields_[i] = internal_fields[i];
414     }
415   }
416
417   V8_INLINE Isolate* GetIsolate() const { return isolate_; }
418   V8_INLINE T* GetParameter() const { return parameter_; }
419   V8_INLINE void* GetInternalField(int index) const;
420
421   V8_INLINE V8_DEPRECATE_SOON("use indexed version",
422                               void* GetInternalField1() const) {
423     return internal_fields_[0];
424   }
425   V8_INLINE V8_DEPRECATE_SOON("use indexed version",
426                               void* GetInternalField2() const) {
427     return internal_fields_[1];
428   }
429
430   bool IsFirstPass() const { return callback_ != nullptr; }
431
432   // When first called, the embedder MUST Reset() the Global which triggered the
433   // callback. The Global itself is unusable for anything else. No v8 other api
434   // calls may be called in the first callback. Should additional work be
435   // required, the embedder must set a second pass callback, which will be
436   // called after all the initial callbacks are processed.
437   // Calling SetSecondPassCallback on the second pass will immediately crash.
438   void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
439
440  private:
441   Isolate* isolate_;
442   T* parameter_;
443   Callback* callback_;
444   void* internal_fields_[kInternalFieldsInWeakCallback];
445 };
446
447
448 template <class T, class P>
449 class WeakCallbackData {
450  public:
451   typedef void (*Callback)(const WeakCallbackData<T, P>& data);
452
453   WeakCallbackData(Isolate* isolate, P* parameter, Local<T> handle)
454       : isolate_(isolate), parameter_(parameter), handle_(handle) {}
455
456   V8_INLINE Isolate* GetIsolate() const { return isolate_; }
457   V8_INLINE P* GetParameter() const { return parameter_; }
458   V8_INLINE Local<T> GetValue() const { return handle_; }
459
460  private:
461   Isolate* isolate_;
462   P* parameter_;
463   Local<T> handle_;
464 };
465
466
467 // TODO(dcarney): delete this with WeakCallbackData
468 template <class T>
469 using PhantomCallbackData = WeakCallbackInfo<T>;
470
471
472 enum class WeakCallbackType { kParameter, kInternalFields };
473
474
475 /**
476  * An object reference that is independent of any handle scope.  Where
477  * a Local handle only lives as long as the HandleScope in which it was
478  * allocated, a PersistentBase handle remains valid until it is explicitly
479  * disposed.
480  *
481  * A persistent handle contains a reference to a storage cell within
482  * the v8 engine which holds an object value and which is updated by
483  * the garbage collector whenever the object is moved.  A new storage
484  * cell can be created using the constructor or PersistentBase::Reset and
485  * existing handles can be disposed using PersistentBase::Reset.
486  *
487  */
488 template <class T> class PersistentBase {
489  public:
490   /**
491    * If non-empty, destroy the underlying storage cell
492    * IsEmpty() will return true after this call.
493    */
494   V8_INLINE void Reset();
495   /**
496    * If non-empty, destroy the underlying storage cell
497    * and create a new one with the contents of other if other is non empty
498    */
499   template <class S>
500   V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
501
502   /**
503    * If non-empty, destroy the underlying storage cell
504    * and create a new one with the contents of other if other is non empty
505    */
506   template <class S>
507   V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
508
509   V8_INLINE bool IsEmpty() const { return val_ == NULL; }
510   V8_INLINE void Empty() { val_ = 0; }
511
512   V8_INLINE Local<T> Get(Isolate* isolate) const {
513     return Local<T>::New(isolate, *this);
514   }
515
516   template <class S>
517   V8_INLINE bool operator==(const PersistentBase<S>& that) const {
518     internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
519     internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
520     if (a == NULL) return b == NULL;
521     if (b == NULL) return false;
522     return *a == *b;
523   }
524
525   template <class S>
526   V8_INLINE bool operator==(const Local<S>& that) const {
527     internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
528     internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
529     if (a == NULL) return b == NULL;
530     if (b == NULL) return false;
531     return *a == *b;
532   }
533
534   template <class S>
535   V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
536     return !operator==(that);
537   }
538
539   template <class S>
540   V8_INLINE bool operator!=(const Local<S>& that) const {
541     return !operator==(that);
542   }
543
544   /**
545    *  Install a finalization callback on this object.
546    *  NOTE: There is no guarantee as to *when* or even *if* the callback is
547    *  invoked. The invocation is performed solely on a best effort basis.
548    *  As always, GC-based finalization should *not* be relied upon for any
549    *  critical form of resource management!
550    */
551   template <typename P>
552   V8_INLINE V8_DEPRECATE_SOON(
553       "use WeakCallbackInfo version",
554       void SetWeak(P* parameter,
555                    typename WeakCallbackData<T, P>::Callback callback));
556
557   template <typename S, typename P>
558   V8_INLINE V8_DEPRECATE_SOON(
559       "use WeakCallbackInfo version",
560       void SetWeak(P* parameter,
561                    typename WeakCallbackData<S, P>::Callback callback));
562
563   // Phantom persistents work like weak persistents, except that the pointer to
564   // the object being collected is not available in the finalization callback.
565   // This enables the garbage collector to collect the object and any objects
566   // it references transitively in one GC cycle. At the moment you can either
567   // specify a parameter for the callback or the location of two internal
568   // fields in the dying object.
569   template <typename P>
570   V8_INLINE V8_DEPRECATE_SOON(
571       "use SetWeak",
572       void SetPhantom(P* parameter,
573                       typename WeakCallbackInfo<P>::Callback callback,
574                       int internal_field_index1 = -1,
575                       int internal_field_index2 = -1));
576
577   template <typename P>
578   V8_INLINE void SetWeak(P* parameter,
579                          typename WeakCallbackInfo<P>::Callback callback,
580                          WeakCallbackType type);
581
582   template<typename P>
583   V8_INLINE P* ClearWeak();
584
585   // TODO(dcarney): remove this.
586   V8_INLINE void ClearWeak() { ClearWeak<void>(); }
587
588   /**
589    * Marks the reference to this object independent. Garbage collector is free
590    * to ignore any object groups containing this object. Weak callback for an
591    * independent handle should not assume that it will be preceded by a global
592    * GC prologue callback or followed by a global GC epilogue callback.
593    */
594   V8_INLINE void MarkIndependent();
595
596   /**
597    * Marks the reference to this object partially dependent. Partially dependent
598    * handles only depend on other partially dependent handles and these
599    * dependencies are provided through object groups. It provides a way to build
600    * smaller object groups for young objects that represent only a subset of all
601    * external dependencies. This mark is automatically cleared after each
602    * garbage collection.
603    */
604   V8_INLINE void MarkPartiallyDependent();
605
606   V8_INLINE bool IsIndependent() const;
607
608   /** Checks if the handle holds the only reference to an object. */
609   V8_INLINE bool IsNearDeath() const;
610
611   /** Returns true if the handle's reference is weak.  */
612   V8_INLINE bool IsWeak() const;
613
614   /**
615    * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
616    * description in v8-profiler.h for details.
617    */
618   V8_INLINE void SetWrapperClassId(uint16_t class_id);
619
620   /**
621    * Returns the class ID previously assigned to this handle or 0 if no class ID
622    * was previously assigned.
623    */
624   V8_INLINE uint16_t WrapperClassId() const;
625
626  private:
627   friend class Isolate;
628   friend class Utils;
629   template<class F> friend class Local;
630   template<class F1, class F2> friend class Persistent;
631   template <class F>
632   friend class Global;
633   template<class F> friend class PersistentBase;
634   template<class F> friend class ReturnValue;
635   template <class F1, class F2, class F3>
636   friend class PersistentValueMapBase;
637   template<class F1, class F2> friend class PersistentValueVector;
638   friend class Object;
639
640   explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
641   PersistentBase(const PersistentBase& other) = delete;  // NOLINT
642   void operator=(const PersistentBase&) = delete;
643   V8_INLINE static T* New(Isolate* isolate, T* that);
644
645   T* val_;
646 };
647
648
649 /**
650  * Default traits for Persistent. This class does not allow
651  * use of the copy constructor or assignment operator.
652  * At present kResetInDestructor is not set, but that will change in a future
653  * version.
654  */
655 template<class T>
656 class NonCopyablePersistentTraits {
657  public:
658   typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
659   static const bool kResetInDestructor = false;
660   template<class S, class M>
661   V8_INLINE static void Copy(const Persistent<S, M>& source,
662                              NonCopyablePersistent* dest) {
663     Uncompilable<Object>();
664   }
665   // TODO(dcarney): come up with a good compile error here.
666   template<class O> V8_INLINE static void Uncompilable() {
667     TYPE_CHECK(O, Primitive);
668   }
669 };
670
671
672 /**
673  * Helper class traits to allow copying and assignment of Persistent.
674  * This will clone the contents of storage cell, but not any of the flags, etc.
675  */
676 template<class T>
677 struct CopyablePersistentTraits {
678   typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
679   static const bool kResetInDestructor = true;
680   template<class S, class M>
681   static V8_INLINE void Copy(const Persistent<S, M>& source,
682                              CopyablePersistent* dest) {
683     // do nothing, just allow copy
684   }
685 };
686
687
688 /**
689  * A PersistentBase which allows copy and assignment.
690  *
691  * Copy, assignment and destructor bevavior is controlled by the traits
692  * class M.
693  *
694  * Note: Persistent class hierarchy is subject to future changes.
695  */
696 template <class T, class M> class Persistent : public PersistentBase<T> {
697  public:
698   /**
699    * A Persistent with no storage cell.
700    */
701   V8_INLINE Persistent() : PersistentBase<T>(0) { }
702   /**
703    * Construct a Persistent from a Local.
704    * When the Local is non-empty, a new storage cell is created
705    * pointing to the same object, and no flags are set.
706    */
707   template <class S>
708   V8_INLINE Persistent(Isolate* isolate, Local<S> that)
709       : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
710     TYPE_CHECK(T, S);
711   }
712   /**
713    * Construct a Persistent from a Persistent.
714    * When the Persistent is non-empty, a new storage cell is created
715    * pointing to the same object, and no flags are set.
716    */
717   template <class S, class M2>
718   V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
719     : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
720     TYPE_CHECK(T, S);
721   }
722   /**
723    * The copy constructors and assignment operator create a Persistent
724    * exactly as the Persistent constructor, but the Copy function from the
725    * traits class is called, allowing the setting of flags based on the
726    * copied Persistent.
727    */
728   V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
729     Copy(that);
730   }
731   template <class S, class M2>
732   V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
733     Copy(that);
734   }
735   V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
736     Copy(that);
737     return *this;
738   }
739   template <class S, class M2>
740   V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
741     Copy(that);
742     return *this;
743   }
744   /**
745    * The destructor will dispose the Persistent based on the
746    * kResetInDestructor flags in the traits class.  Since not calling dispose
747    * can result in a memory leak, it is recommended to always set this flag.
748    */
749   V8_INLINE ~Persistent() {
750     if (M::kResetInDestructor) this->Reset();
751   }
752
753   // TODO(dcarney): this is pretty useless, fix or remove
754   template <class S>
755   V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
756 #ifdef V8_ENABLE_CHECKS
757     // If we're going to perform the type check then we have to check
758     // that the handle isn't empty before doing the checked cast.
759     if (!that.IsEmpty()) T::Cast(*that);
760 #endif
761     return reinterpret_cast<Persistent<T>&>(that);
762   }
763
764   // TODO(dcarney): this is pretty useless, fix or remove
765   template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
766     return Persistent<S>::Cast(*this);
767   }
768
769  private:
770   friend class Isolate;
771   friend class Utils;
772   template<class F> friend class Local;
773   template<class F1, class F2> friend class Persistent;
774   template<class F> friend class ReturnValue;
775
776   template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
777   V8_INLINE T* operator*() const { return this->val_; }
778   template<class S, class M2>
779   V8_INLINE void Copy(const Persistent<S, M2>& that);
780 };
781
782
783 /**
784  * A PersistentBase which has move semantics.
785  *
786  * Note: Persistent class hierarchy is subject to future changes.
787  */
788 template <class T>
789 class Global : public PersistentBase<T> {
790  public:
791   /**
792    * A Global with no storage cell.
793    */
794   V8_INLINE Global() : PersistentBase<T>(nullptr) {}
795   /**
796    * Construct a Global from a Local.
797    * When the Local is non-empty, a new storage cell is created
798    * pointing to the same object, and no flags are set.
799    */
800   template <class S>
801   V8_INLINE Global(Isolate* isolate, Local<S> that)
802       : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
803     TYPE_CHECK(T, S);
804   }
805   /**
806    * Construct a Global from a PersistentBase.
807    * When the Persistent is non-empty, a new storage cell is created
808    * pointing to the same object, and no flags are set.
809    */
810   template <class S>
811   V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
812       : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
813     TYPE_CHECK(T, S);
814   }
815   /**
816    * Move constructor.
817    */
818   V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) {  // NOLINT
819     other.val_ = nullptr;
820   }
821   V8_INLINE ~Global() { this->Reset(); }
822   /**
823    * Move via assignment.
824    */
825   template <class S>
826   V8_INLINE Global& operator=(Global<S>&& rhs) {  // NOLINT
827     TYPE_CHECK(T, S);
828     if (this != &rhs) {
829       this->Reset();
830       this->val_ = rhs.val_;
831       rhs.val_ = nullptr;
832     }
833     return *this;
834   }
835   /**
836    * Pass allows returning uniques from functions, etc.
837    */
838   Global Pass() { return static_cast<Global&&>(*this); }  // NOLINT
839
840   /*
841    * For compatibility with Chromium's base::Bind (base::Passed).
842    */
843   typedef void MoveOnlyTypeForCPP03;
844
845  private:
846   template <class F>
847   friend class ReturnValue;
848   Global(const Global&) = delete;
849   void operator=(const Global&) = delete;
850   V8_INLINE T* operator*() const { return this->val_; }
851 };
852
853
854 // UniquePersistent is an alias for Global for historical reason.
855 template <class T>
856 using UniquePersistent = Global<T>;
857
858
859  /**
860  * A stack-allocated class that governs a number of local handles.
861  * After a handle scope has been created, all local handles will be
862  * allocated within that handle scope until either the handle scope is
863  * deleted or another handle scope is created.  If there is already a
864  * handle scope and a new one is created, all allocations will take
865  * place in the new handle scope until it is deleted.  After that,
866  * new handles will again be allocated in the original handle scope.
867  *
868  * After the handle scope of a local handle has been deleted the
869  * garbage collector will no longer track the object stored in the
870  * handle and may deallocate it.  The behavior of accessing a handle
871  * for which the handle scope has been deleted is undefined.
872  */
873 class V8_EXPORT HandleScope {
874  public:
875   HandleScope(Isolate* isolate);
876
877   ~HandleScope();
878
879   /**
880    * Counts the number of allocated handles.
881    */
882   static int NumberOfHandles(Isolate* isolate);
883
884   V8_INLINE Isolate* GetIsolate() const {
885     return reinterpret_cast<Isolate*>(isolate_);
886   }
887
888  protected:
889   V8_INLINE HandleScope() {}
890
891   void Initialize(Isolate* isolate);
892
893   static internal::Object** CreateHandle(internal::Isolate* isolate,
894                                          internal::Object* value);
895
896  private:
897   // Uses heap_object to obtain the current Isolate.
898   static internal::Object** CreateHandle(internal::HeapObject* heap_object,
899                                          internal::Object* value);
900
901   // Make it hard to create heap-allocated or illegal handle scopes by
902   // disallowing certain operations.
903   HandleScope(const HandleScope&);
904   void operator=(const HandleScope&);
905   void* operator new(size_t size);
906   void operator delete(void*, size_t);
907
908   internal::Isolate* isolate_;
909   internal::Object** prev_next_;
910   internal::Object** prev_limit_;
911
912   // Local::New uses CreateHandle with an Isolate* parameter.
913   template<class F> friend class Local;
914
915   // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
916   // a HeapObject* in their shortcuts.
917   friend class Object;
918   friend class Context;
919 };
920
921
922 /**
923  * A HandleScope which first allocates a handle in the current scope
924  * which will be later filled with the escape value.
925  */
926 class V8_EXPORT EscapableHandleScope : public HandleScope {
927  public:
928   EscapableHandleScope(Isolate* isolate);
929   V8_INLINE ~EscapableHandleScope() {}
930
931   /**
932    * Pushes the value into the previous scope and returns a handle to it.
933    * Cannot be called twice.
934    */
935   template <class T>
936   V8_INLINE Local<T> Escape(Local<T> value) {
937     internal::Object** slot =
938         Escape(reinterpret_cast<internal::Object**>(*value));
939     return Local<T>(reinterpret_cast<T*>(slot));
940   }
941
942  private:
943   internal::Object** Escape(internal::Object** escape_value);
944
945   // Make it hard to create heap-allocated or illegal handle scopes by
946   // disallowing certain operations.
947   EscapableHandleScope(const EscapableHandleScope&);
948   void operator=(const EscapableHandleScope&);
949   void* operator new(size_t size);
950   void operator delete(void*, size_t);
951
952   internal::Object** escape_slot_;
953 };
954
955 class V8_EXPORT SealHandleScope {
956  public:
957   SealHandleScope(Isolate* isolate);
958   ~SealHandleScope();
959
960  private:
961   // Make it hard to create heap-allocated or illegal handle scopes by
962   // disallowing certain operations.
963   SealHandleScope(const SealHandleScope&);
964   void operator=(const SealHandleScope&);
965   void* operator new(size_t size);
966   void operator delete(void*, size_t);
967
968   internal::Isolate* isolate_;
969   int prev_level_;
970   internal::Object** prev_limit_;
971 };
972
973
974 // --- Special objects ---
975
976
977 /**
978  * The superclass of values and API object templates.
979  */
980 class V8_EXPORT Data {
981  private:
982   Data();
983 };
984
985
986 /**
987  * The optional attributes of ScriptOrigin.
988  */
989 class ScriptOriginOptions {
990  public:
991   V8_INLINE ScriptOriginOptions(bool is_embedder_debug_script = false,
992                                 bool is_shared_cross_origin = false,
993                                 bool is_opaque = false)
994       : flags_((is_embedder_debug_script ? kIsEmbedderDebugScript : 0) |
995                (is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
996                (is_opaque ? kIsOpaque : 0)) {}
997   V8_INLINE ScriptOriginOptions(int flags)
998       : flags_(flags &
999                (kIsEmbedderDebugScript | kIsSharedCrossOrigin | kIsOpaque)) {}
1000   bool IsEmbedderDebugScript() const {
1001     return (flags_ & kIsEmbedderDebugScript) != 0;
1002   }
1003   bool IsSharedCrossOrigin() const {
1004     return (flags_ & kIsSharedCrossOrigin) != 0;
1005   }
1006   bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1007   int Flags() const { return flags_; }
1008
1009  private:
1010   enum {
1011     kIsEmbedderDebugScript = 1,
1012     kIsSharedCrossOrigin = 1 << 1,
1013     kIsOpaque = 1 << 2
1014   };
1015   const int flags_;
1016 };
1017
1018 /**
1019  * The origin, within a file, of a script.
1020  */
1021 class ScriptOrigin {
1022  public:
1023   V8_INLINE ScriptOrigin(
1024       Local<Value> resource_name,
1025       Local<Integer> resource_line_offset = Local<Integer>(),
1026       Local<Integer> resource_column_offset = Local<Integer>(),
1027       Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1028       Local<Integer> script_id = Local<Integer>(),
1029       Local<Boolean> resource_is_embedder_debug_script = Local<Boolean>(),
1030       Local<Value> source_map_url = Local<Value>(),
1031       Local<Boolean> resource_is_opaque = Local<Boolean>());
1032   V8_INLINE Local<Value> ResourceName() const;
1033   V8_INLINE Local<Integer> ResourceLineOffset() const;
1034   V8_INLINE Local<Integer> ResourceColumnOffset() const;
1035   /**
1036     * Returns true for embedder's debugger scripts
1037     */
1038   V8_INLINE Local<Integer> ScriptID() const;
1039   V8_INLINE Local<Value> SourceMapUrl() const;
1040   V8_INLINE ScriptOriginOptions Options() const { return options_; }
1041
1042  private:
1043   Local<Value> resource_name_;
1044   Local<Integer> resource_line_offset_;
1045   Local<Integer> resource_column_offset_;
1046   ScriptOriginOptions options_;
1047   Local<Integer> script_id_;
1048   Local<Value> source_map_url_;
1049 };
1050
1051
1052 /**
1053  * A compiled JavaScript script, not yet tied to a Context.
1054  */
1055 class V8_EXPORT UnboundScript {
1056  public:
1057   /**
1058    * Binds the script to the currently entered context.
1059    */
1060   Local<Script> BindToCurrentContext();
1061
1062   int GetId();
1063   Local<Value> GetScriptName();
1064
1065   /**
1066    * Data read from magic sourceURL comments.
1067    */
1068   Local<Value> GetSourceURL();
1069   /**
1070    * Data read from magic sourceMappingURL comments.
1071    */
1072   Local<Value> GetSourceMappingURL();
1073
1074   /**
1075    * Returns zero based line number of the code_pos location in the script.
1076    * -1 will be returned if no information available.
1077    */
1078   int GetLineNumber(int code_pos);
1079
1080   static const int kNoScriptId = 0;
1081 };
1082
1083
1084 /**
1085  * A compiled JavaScript script, tied to a Context which was active when the
1086  * script was compiled.
1087  */
1088 class V8_EXPORT Script {
1089  public:
1090   /**
1091    * A shorthand for ScriptCompiler::Compile().
1092    */
1093   static V8_DEPRECATE_SOON(
1094       "Use maybe version",
1095       Local<Script> Compile(Local<String> source,
1096                             ScriptOrigin* origin = nullptr));
1097   static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1098       Local<Context> context, Local<String> source,
1099       ScriptOrigin* origin = nullptr);
1100
1101   static Local<Script> V8_DEPRECATE_SOON("Use maybe version",
1102                                          Compile(Local<String> source,
1103                                                  Local<String> file_name));
1104
1105   /**
1106    * Runs the script returning the resulting value. It will be run in the
1107    * context in which it was created (ScriptCompiler::CompileBound or
1108    * UnboundScript::BindToCurrentContext()).
1109    */
1110   V8_DEPRECATE_SOON("Use maybe version", Local<Value> Run());
1111   V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context);
1112
1113   /**
1114    * Returns the corresponding context-unbound script.
1115    */
1116   Local<UnboundScript> GetUnboundScript();
1117 };
1118
1119
1120 /**
1121  * For compiling scripts.
1122  */
1123 class V8_EXPORT ScriptCompiler {
1124  public:
1125   /**
1126    * Compilation data that the embedder can cache and pass back to speed up
1127    * future compilations. The data is produced if the CompilerOptions passed to
1128    * the compilation functions in ScriptCompiler contains produce_data_to_cache
1129    * = true. The data to cache can then can be retrieved from
1130    * UnboundScript.
1131    */
1132   struct V8_EXPORT CachedData {
1133     enum BufferPolicy {
1134       BufferNotOwned,
1135       BufferOwned
1136     };
1137
1138     CachedData()
1139         : data(NULL),
1140           length(0),
1141           rejected(false),
1142           buffer_policy(BufferNotOwned) {}
1143
1144     // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1145     // data and guarantees that it stays alive until the CachedData object is
1146     // destroyed. If the policy is BufferOwned, the given data will be deleted
1147     // (with delete[]) when the CachedData object is destroyed.
1148     CachedData(const uint8_t* data, int length,
1149                BufferPolicy buffer_policy = BufferNotOwned);
1150     ~CachedData();
1151     // TODO(marja): Async compilation; add constructors which take a callback
1152     // which will be called when V8 no longer needs the data.
1153     const uint8_t* data;
1154     int length;
1155     bool rejected;
1156     BufferPolicy buffer_policy;
1157
1158    private:
1159     // Prevent copying. Not implemented.
1160     CachedData(const CachedData&);
1161     CachedData& operator=(const CachedData&);
1162   };
1163
1164   /**
1165    * Source code which can be then compiled to a UnboundScript or Script.
1166    */
1167   class Source {
1168    public:
1169     // Source takes ownership of CachedData.
1170     V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1171            CachedData* cached_data = NULL);
1172     V8_INLINE Source(Local<String> source_string,
1173                      CachedData* cached_data = NULL);
1174     V8_INLINE ~Source();
1175
1176     // Ownership of the CachedData or its buffers is *not* transferred to the
1177     // caller. The CachedData object is alive as long as the Source object is
1178     // alive.
1179     V8_INLINE const CachedData* GetCachedData() const;
1180
1181    private:
1182     friend class ScriptCompiler;
1183     // Prevent copying. Not implemented.
1184     Source(const Source&);
1185     Source& operator=(const Source&);
1186
1187     Local<String> source_string;
1188
1189     // Origin information
1190     Local<Value> resource_name;
1191     Local<Integer> resource_line_offset;
1192     Local<Integer> resource_column_offset;
1193     ScriptOriginOptions resource_options;
1194     Local<Value> source_map_url;
1195
1196     // Cached data from previous compilation (if a kConsume*Cache flag is
1197     // set), or hold newly generated cache data (kProduce*Cache flags) are
1198     // set when calling a compile method.
1199     CachedData* cached_data;
1200   };
1201
1202   /**
1203    * For streaming incomplete script data to V8. The embedder should implement a
1204    * subclass of this class.
1205    */
1206   class V8_EXPORT ExternalSourceStream {
1207    public:
1208     virtual ~ExternalSourceStream() {}
1209
1210     /**
1211      * V8 calls this to request the next chunk of data from the embedder. This
1212      * function will be called on a background thread, so it's OK to block and
1213      * wait for the data, if the embedder doesn't have data yet. Returns the
1214      * length of the data returned. When the data ends, GetMoreData should
1215      * return 0. Caller takes ownership of the data.
1216      *
1217      * When streaming UTF-8 data, V8 handles multi-byte characters split between
1218      * two data chunks, but doesn't handle multi-byte characters split between
1219      * more than two data chunks. The embedder can avoid this problem by always
1220      * returning at least 2 bytes of data.
1221      *
1222      * If the embedder wants to cancel the streaming, they should make the next
1223      * GetMoreData call return 0. V8 will interpret it as end of data (and most
1224      * probably, parsing will fail). The streaming task will return as soon as
1225      * V8 has parsed the data it received so far.
1226      */
1227     virtual size_t GetMoreData(const uint8_t** src) = 0;
1228
1229     /**
1230      * V8 calls this method to set a 'bookmark' at the current position in
1231      * the source stream, for the purpose of (maybe) later calling
1232      * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1233      * calls to GetMoreData should return the same data as they did when
1234      * SetBookmark was called earlier.
1235      *
1236      * The embedder may return 'false' to indicate it cannot provide this
1237      * functionality.
1238      */
1239     virtual bool SetBookmark();
1240
1241     /**
1242      * V8 calls this to return to a previously set bookmark.
1243      */
1244     virtual void ResetToBookmark();
1245   };
1246
1247
1248   /**
1249    * Source code which can be streamed into V8 in pieces. It will be parsed
1250    * while streaming. It can be compiled after the streaming is complete.
1251    * StreamedSource must be kept alive while the streaming task is ran (see
1252    * ScriptStreamingTask below).
1253    */
1254   class V8_EXPORT StreamedSource {
1255    public:
1256     enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1257
1258     StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1259     ~StreamedSource();
1260
1261     // Ownership of the CachedData or its buffers is *not* transferred to the
1262     // caller. The CachedData object is alive as long as the StreamedSource
1263     // object is alive.
1264     const CachedData* GetCachedData() const;
1265
1266     internal::StreamedSource* impl() const { return impl_; }
1267
1268    private:
1269     // Prevent copying. Not implemented.
1270     StreamedSource(const StreamedSource&);
1271     StreamedSource& operator=(const StreamedSource&);
1272
1273     internal::StreamedSource* impl_;
1274   };
1275
1276   /**
1277    * A streaming task which the embedder must run on a background thread to
1278    * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1279    */
1280   class ScriptStreamingTask {
1281    public:
1282     virtual ~ScriptStreamingTask() {}
1283     virtual void Run() = 0;
1284   };
1285
1286   enum CompileOptions {
1287     kNoCompileOptions = 0,
1288     kProduceParserCache,
1289     kConsumeParserCache,
1290     kProduceCodeCache,
1291     kConsumeCodeCache
1292   };
1293
1294   /**
1295    * Compiles the specified script (context-independent).
1296    * Cached data as part of the source object can be optionally produced to be
1297    * consumed later to speed up compilation of identical source scripts.
1298    *
1299    * Note that when producing cached data, the source must point to NULL for
1300    * cached data. When consuming cached data, the cached data must have been
1301    * produced by the same version of V8.
1302    *
1303    * \param source Script source code.
1304    * \return Compiled script object (context independent; for running it must be
1305    *   bound to a context).
1306    */
1307   static V8_DEPRECATE_SOON("Use maybe version",
1308                            Local<UnboundScript> CompileUnbound(
1309                                Isolate* isolate, Source* source,
1310                                CompileOptions options = kNoCompileOptions));
1311   static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript(
1312       Isolate* isolate, Source* source,
1313       CompileOptions options = kNoCompileOptions);
1314
1315   /**
1316    * Compiles the specified script (bound to current context).
1317    *
1318    * \param source Script source code.
1319    * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1320    *   using pre_data speeds compilation if it's done multiple times.
1321    *   Owned by caller, no references are kept when this function returns.
1322    * \return Compiled script object, bound to the context that was active
1323    *   when this function was called. When run it will always use this
1324    *   context.
1325    */
1326   static V8_DEPRECATE_SOON(
1327       "Use maybe version",
1328       Local<Script> Compile(Isolate* isolate, Source* source,
1329                             CompileOptions options = kNoCompileOptions));
1330   static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1331       Local<Context> context, Source* source,
1332       CompileOptions options = kNoCompileOptions);
1333
1334   /**
1335    * Returns a task which streams script data into V8, or NULL if the script
1336    * cannot be streamed. The user is responsible for running the task on a
1337    * background thread and deleting it. When ran, the task starts parsing the
1338    * script, and it will request data from the StreamedSource as needed. When
1339    * ScriptStreamingTask::Run exits, all data has been streamed and the script
1340    * can be compiled (see Compile below).
1341    *
1342    * This API allows to start the streaming with as little data as possible, and
1343    * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1344    */
1345   static ScriptStreamingTask* StartStreamingScript(
1346       Isolate* isolate, StreamedSource* source,
1347       CompileOptions options = kNoCompileOptions);
1348
1349   /**
1350    * Compiles a streamed script (bound to current context).
1351    *
1352    * This can only be called after the streaming has finished
1353    * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1354    * during streaming, so the embedder needs to pass the full source here.
1355    */
1356   static V8_DEPRECATE_SOON(
1357       "Use maybe version",
1358       Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1359                             Local<String> full_source_string,
1360                             const ScriptOrigin& origin));
1361   static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1362       Local<Context> context, StreamedSource* source,
1363       Local<String> full_source_string, const ScriptOrigin& origin);
1364
1365   /**
1366    * Return a version tag for CachedData for the current V8 version & flags.
1367    *
1368    * This value is meant only for determining whether a previously generated
1369    * CachedData instance is still valid; the tag has no other meaing.
1370    *
1371    * Background: The data carried by CachedData may depend on the exact
1372    *   V8 version number or currently compiler flags. This means when
1373    *   persisting CachedData, the embedder must take care to not pass in
1374    *   data from another V8 version, or the same version with different
1375    *   features enabled.
1376    *
1377    *   The easiest way to do so is to clear the embedder's cache on any
1378    *   such change.
1379    *
1380    *   Alternatively, this tag can be stored alongside the cached data and
1381    *   compared when it is being used.
1382    */
1383   static uint32_t CachedDataVersionTag();
1384
1385   /**
1386    * Compile an ES6 module.
1387    *
1388    * This is an unfinished experimental feature, and is only exposed
1389    * here for internal testing purposes.
1390    * Only parsing works at the moment. Do not use.
1391    *
1392    * TODO(adamk): Script is likely the wrong return value for this;
1393    * should return some new Module type.
1394    */
1395   static V8_WARN_UNUSED_RESULT MaybeLocal<Script> CompileModule(
1396       Local<Context> context, Source* source,
1397       CompileOptions options = kNoCompileOptions);
1398
1399   /**
1400    * Compile a function for a given context. This is equivalent to running
1401    *
1402    * with (obj) {
1403    *   return function(args) { ... }
1404    * }
1405    *
1406    * It is possible to specify multiple context extensions (obj in the above
1407    * example).
1408    */
1409   static V8_DEPRECATE_SOON("Use maybe version",
1410                            Local<Function> CompileFunctionInContext(
1411                                Isolate* isolate, Source* source,
1412                                Local<Context> context, size_t arguments_count,
1413                                Local<String> arguments[],
1414                                size_t context_extension_count,
1415                                Local<Object> context_extensions[]));
1416   static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext(
1417       Local<Context> context, Source* source, size_t arguments_count,
1418       Local<String> arguments[], size_t context_extension_count,
1419       Local<Object> context_extensions[]);
1420
1421  private:
1422   static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1423       Isolate* isolate, Source* source, CompileOptions options, bool is_module);
1424 };
1425
1426
1427 /**
1428  * An error message.
1429  */
1430 class V8_EXPORT Message {
1431  public:
1432   Local<String> Get() const;
1433
1434   V8_DEPRECATE_SOON("Use maybe version", Local<String> GetSourceLine() const);
1435   V8_WARN_UNUSED_RESULT MaybeLocal<String> GetSourceLine(
1436       Local<Context> context) const;
1437
1438   /**
1439    * Returns the origin for the script from where the function causing the
1440    * error originates.
1441    */
1442   ScriptOrigin GetScriptOrigin() const;
1443
1444   /**
1445    * Returns the resource name for the script from where the function causing
1446    * the error originates.
1447    */
1448   Local<Value> GetScriptResourceName() const;
1449
1450   /**
1451    * Exception stack trace. By default stack traces are not captured for
1452    * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1453    * to change this option.
1454    */
1455   Local<StackTrace> GetStackTrace() const;
1456
1457   /**
1458    * Returns the number, 1-based, of the line where the error occurred.
1459    */
1460   V8_DEPRECATE_SOON("Use maybe version", int GetLineNumber() const);
1461   V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
1462
1463   /**
1464    * Returns the index within the script of the first character where
1465    * the error occurred.
1466    */
1467   int GetStartPosition() const;
1468
1469   /**
1470    * Returns the index within the script of the last character where
1471    * the error occurred.
1472    */
1473   int GetEndPosition() const;
1474
1475   /**
1476    * Returns the index within the line of the first character where
1477    * the error occurred.
1478    */
1479   V8_DEPRECATE_SOON("Use maybe version", int GetStartColumn() const);
1480   V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
1481
1482   /**
1483    * Returns the index within the line of the last character where
1484    * the error occurred.
1485    */
1486   V8_DEPRECATE_SOON("Use maybe version", int GetEndColumn() const);
1487   V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
1488
1489   /**
1490    * Passes on the value set by the embedder when it fed the script from which
1491    * this Message was generated to V8.
1492    */
1493   bool IsSharedCrossOrigin() const;
1494   bool IsOpaque() const;
1495
1496   // TODO(1245381): Print to a string instead of on a FILE.
1497   static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1498
1499   static const int kNoLineNumberInfo = 0;
1500   static const int kNoColumnInfo = 0;
1501   static const int kNoScriptIdInfo = 0;
1502 };
1503
1504
1505 /**
1506  * Representation of a JavaScript stack trace. The information collected is a
1507  * snapshot of the execution stack and the information remains valid after
1508  * execution continues.
1509  */
1510 class V8_EXPORT StackTrace {
1511  public:
1512   /**
1513    * Flags that determine what information is placed captured for each
1514    * StackFrame when grabbing the current stack trace.
1515    */
1516   enum StackTraceOptions {
1517     kLineNumber = 1,
1518     kColumnOffset = 1 << 1 | kLineNumber,
1519     kScriptName = 1 << 2,
1520     kFunctionName = 1 << 3,
1521     kIsEval = 1 << 4,
1522     kIsConstructor = 1 << 5,
1523     kScriptNameOrSourceURL = 1 << 6,
1524     kScriptId = 1 << 7,
1525     kExposeFramesAcrossSecurityOrigins = 1 << 8,
1526     kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1527     kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1528   };
1529
1530   /**
1531    * Returns a StackFrame at a particular index.
1532    */
1533   Local<StackFrame> GetFrame(uint32_t index) const;
1534
1535   /**
1536    * Returns the number of StackFrames.
1537    */
1538   int GetFrameCount() const;
1539
1540   /**
1541    * Returns StackTrace as a v8::Array that contains StackFrame objects.
1542    */
1543   Local<Array> AsArray();
1544
1545   /**
1546    * Grab a snapshot of the current JavaScript execution stack.
1547    *
1548    * \param frame_limit The maximum number of stack frames we want to capture.
1549    * \param options Enumerates the set of things we will capture for each
1550    *   StackFrame.
1551    */
1552   static Local<StackTrace> CurrentStackTrace(
1553       Isolate* isolate,
1554       int frame_limit,
1555       StackTraceOptions options = kOverview);
1556 };
1557
1558
1559 /**
1560  * A single JavaScript stack frame.
1561  */
1562 class V8_EXPORT StackFrame {
1563  public:
1564   /**
1565    * Returns the number, 1-based, of the line for the associate function call.
1566    * This method will return Message::kNoLineNumberInfo if it is unable to
1567    * retrieve the line number, or if kLineNumber was not passed as an option
1568    * when capturing the StackTrace.
1569    */
1570   int GetLineNumber() const;
1571
1572   /**
1573    * Returns the 1-based column offset on the line for the associated function
1574    * call.
1575    * This method will return Message::kNoColumnInfo if it is unable to retrieve
1576    * the column number, or if kColumnOffset was not passed as an option when
1577    * capturing the StackTrace.
1578    */
1579   int GetColumn() const;
1580
1581   /**
1582    * Returns the id of the script for the function for this StackFrame.
1583    * This method will return Message::kNoScriptIdInfo if it is unable to
1584    * retrieve the script id, or if kScriptId was not passed as an option when
1585    * capturing the StackTrace.
1586    */
1587   int GetScriptId() const;
1588
1589   /**
1590    * Returns the name of the resource that contains the script for the
1591    * function for this StackFrame.
1592    */
1593   Local<String> GetScriptName() const;
1594
1595   /**
1596    * Returns the name of the resource that contains the script for the
1597    * function for this StackFrame or sourceURL value if the script name
1598    * is undefined and its source ends with //# sourceURL=... string or
1599    * deprecated //@ sourceURL=... string.
1600    */
1601   Local<String> GetScriptNameOrSourceURL() const;
1602
1603   /**
1604    * Returns the name of the function associated with this stack frame.
1605    */
1606   Local<String> GetFunctionName() const;
1607
1608   /**
1609    * Returns whether or not the associated function is compiled via a call to
1610    * eval().
1611    */
1612   bool IsEval() const;
1613
1614   /**
1615    * Returns whether or not the associated function is called as a
1616    * constructor via "new".
1617    */
1618   bool IsConstructor() const;
1619 };
1620
1621
1622 // A StateTag represents a possible state of the VM.
1623 enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE };
1624
1625
1626 // A RegisterState represents the current state of registers used
1627 // by the sampling profiler API.
1628 struct RegisterState {
1629   RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1630   void* pc;  // Instruction pointer.
1631   void* sp;  // Stack pointer.
1632   void* fp;  // Frame pointer.
1633 };
1634
1635
1636 // The output structure filled up by GetStackSample API function.
1637 struct SampleInfo {
1638   size_t frames_count;
1639   StateTag vm_state;
1640 };
1641
1642
1643 /**
1644  * A JSON Parser.
1645  */
1646 class V8_EXPORT JSON {
1647  public:
1648   /**
1649    * Tries to parse the string |json_string| and returns it as value if
1650    * successful.
1651    *
1652    * \param json_string The string to parse.
1653    * \return The corresponding value if successfully parsed.
1654    */
1655   static V8_DEPRECATE_SOON("Use maybe version",
1656                            Local<Value> Parse(Local<String> json_string));
1657   static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse(
1658       Isolate* isolate, Local<String> json_string);
1659 };
1660
1661
1662 /**
1663  * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
1664  * but can be created without entering a v8::Context and hence shouldn't
1665  * escape to JavaScript.
1666  */
1667 class V8_EXPORT NativeWeakMap : public Data {
1668  public:
1669   static Local<NativeWeakMap> New(Isolate* isolate);
1670   void Set(Local<Value> key, Local<Value> value);
1671   Local<Value> Get(Local<Value> key);
1672   bool Has(Local<Value> key);
1673   bool Delete(Local<Value> key);
1674 };
1675
1676
1677 // --- Value ---
1678
1679
1680 /**
1681  * The superclass of all JavaScript values and objects.
1682  */
1683 class V8_EXPORT Value : public Data {
1684  public:
1685   /**
1686    * Returns true if this value is the undefined value.  See ECMA-262
1687    * 4.3.10.
1688    */
1689   V8_INLINE bool IsUndefined() const;
1690
1691   /**
1692    * Returns true if this value is the null value.  See ECMA-262
1693    * 4.3.11.
1694    */
1695   V8_INLINE bool IsNull() const;
1696
1697    /**
1698    * Returns true if this value is true.
1699    */
1700   bool IsTrue() const;
1701
1702   /**
1703    * Returns true if this value is false.
1704    */
1705   bool IsFalse() const;
1706
1707   /**
1708    * Returns true if this value is a symbol or a string.
1709    * This is an experimental feature.
1710    */
1711   bool IsName() const;
1712
1713   /**
1714    * Returns true if this value is an instance of the String type.
1715    * See ECMA-262 8.4.
1716    */
1717   V8_INLINE bool IsString() const;
1718
1719   /**
1720    * Returns true if this value is a symbol.
1721    * This is an experimental feature.
1722    */
1723   bool IsSymbol() const;
1724
1725   /**
1726    * Returns true if this value is a function.
1727    */
1728   bool IsFunction() const;
1729
1730   /**
1731    * Returns true if this value is an array.
1732    */
1733   bool IsArray() const;
1734
1735   /**
1736    * Returns true if this value is an object.
1737    */
1738   bool IsObject() const;
1739
1740   /**
1741    * Returns true if this value is boolean.
1742    */
1743   bool IsBoolean() const;
1744
1745   /**
1746    * Returns true if this value is a number.
1747    */
1748   bool IsNumber() const;
1749
1750   /**
1751    * Returns true if this value is external.
1752    */
1753   bool IsExternal() const;
1754
1755   /**
1756    * Returns true if this value is a 32-bit signed integer.
1757    */
1758   bool IsInt32() const;
1759
1760   /**
1761    * Returns true if this value is a 32-bit unsigned integer.
1762    */
1763   bool IsUint32() const;
1764
1765   /**
1766    * Returns true if this value is a Date.
1767    */
1768   bool IsDate() const;
1769
1770   /**
1771    * Returns true if this value is an Arguments object.
1772    */
1773   bool IsArgumentsObject() const;
1774
1775   /**
1776    * Returns true if this value is a Boolean object.
1777    */
1778   bool IsBooleanObject() const;
1779
1780   /**
1781    * Returns true if this value is a Number object.
1782    */
1783   bool IsNumberObject() const;
1784
1785   /**
1786    * Returns true if this value is a String object.
1787    */
1788   bool IsStringObject() const;
1789
1790   /**
1791    * Returns true if this value is a Symbol object.
1792    * This is an experimental feature.
1793    */
1794   bool IsSymbolObject() const;
1795
1796   /**
1797    * Returns true if this value is a NativeError.
1798    */
1799   bool IsNativeError() const;
1800
1801   /**
1802    * Returns true if this value is a RegExp.
1803    */
1804   bool IsRegExp() const;
1805
1806   /**
1807    * Returns true if this value is a Generator function.
1808    * This is an experimental feature.
1809    */
1810   bool IsGeneratorFunction() const;
1811
1812   /**
1813    * Returns true if this value is a Generator object (iterator).
1814    * This is an experimental feature.
1815    */
1816   bool IsGeneratorObject() const;
1817
1818   /**
1819    * Returns true if this value is a Promise.
1820    * This is an experimental feature.
1821    */
1822   bool IsPromise() const;
1823
1824   /**
1825    * Returns true if this value is a Map.
1826    */
1827   bool IsMap() const;
1828
1829   /**
1830    * Returns true if this value is a Set.
1831    */
1832   bool IsSet() const;
1833
1834   /**
1835    * Returns true if this value is a Map Iterator.
1836    */
1837   bool IsMapIterator() const;
1838
1839   /**
1840    * Returns true if this value is a Set Iterator.
1841    */
1842   bool IsSetIterator() const;
1843
1844   /**
1845    * Returns true if this value is a WeakMap.
1846    */
1847   bool IsWeakMap() const;
1848
1849   /**
1850    * Returns true if this value is a WeakSet.
1851    */
1852   bool IsWeakSet() const;
1853
1854   /**
1855    * Returns true if this value is an ArrayBuffer.
1856    * This is an experimental feature.
1857    */
1858   bool IsArrayBuffer() const;
1859
1860   /**
1861    * Returns true if this value is an ArrayBufferView.
1862    * This is an experimental feature.
1863    */
1864   bool IsArrayBufferView() const;
1865
1866   /**
1867    * Returns true if this value is one of TypedArrays.
1868    * This is an experimental feature.
1869    */
1870   bool IsTypedArray() const;
1871
1872   /**
1873    * Returns true if this value is an Uint8Array.
1874    * This is an experimental feature.
1875    */
1876   bool IsUint8Array() const;
1877
1878   /**
1879    * Returns true if this value is an Uint8ClampedArray.
1880    * This is an experimental feature.
1881    */
1882   bool IsUint8ClampedArray() const;
1883
1884   /**
1885    * Returns true if this value is an Int8Array.
1886    * This is an experimental feature.
1887    */
1888   bool IsInt8Array() const;
1889
1890   /**
1891    * Returns true if this value is an Uint16Array.
1892    * This is an experimental feature.
1893    */
1894   bool IsUint16Array() const;
1895
1896   /**
1897    * Returns true if this value is an Int16Array.
1898    * This is an experimental feature.
1899    */
1900   bool IsInt16Array() const;
1901
1902   /**
1903    * Returns true if this value is an Uint32Array.
1904    * This is an experimental feature.
1905    */
1906   bool IsUint32Array() const;
1907
1908   /**
1909    * Returns true if this value is an Int32Array.
1910    * This is an experimental feature.
1911    */
1912   bool IsInt32Array() const;
1913
1914   /**
1915    * Returns true if this value is a Float32Array.
1916    * This is an experimental feature.
1917    */
1918   bool IsFloat32Array() const;
1919
1920   /**
1921    * Returns true if this value is a Float64Array.
1922    * This is an experimental feature.
1923    */
1924   bool IsFloat64Array() const;
1925
1926   /**
1927    * Returns true if this value is a SIMD Float32x4.
1928    * This is an experimental feature.
1929    */
1930   bool IsFloat32x4() const;
1931
1932   /**
1933    * Returns true if this value is a DataView.
1934    * This is an experimental feature.
1935    */
1936   bool IsDataView() const;
1937
1938   /**
1939    * Returns true if this value is a SharedArrayBuffer.
1940    * This is an experimental feature.
1941    */
1942   bool IsSharedArrayBuffer() const;
1943
1944
1945   V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean(
1946       Local<Context> context) const;
1947   V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber(
1948       Local<Context> context) const;
1949   V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
1950       Local<Context> context) const;
1951   V8_WARN_UNUSED_RESULT MaybeLocal<String> ToDetailString(
1952       Local<Context> context) const;
1953   V8_WARN_UNUSED_RESULT MaybeLocal<Object> ToObject(
1954       Local<Context> context) const;
1955   V8_WARN_UNUSED_RESULT MaybeLocal<Integer> ToInteger(
1956       Local<Context> context) const;
1957   V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToUint32(
1958       Local<Context> context) const;
1959   V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
1960
1961   V8_DEPRECATE_SOON("Use maybe version",
1962                     Local<Boolean> ToBoolean(Isolate* isolate) const);
1963   V8_DEPRECATE_SOON("Use maybe version",
1964                     Local<Number> ToNumber(Isolate* isolate) const);
1965   V8_DEPRECATE_SOON("Use maybe version",
1966                     Local<String> ToString(Isolate* isolate) const);
1967   V8_DEPRECATE_SOON("Use maybe version",
1968                     Local<String> ToDetailString(Isolate* isolate) const);
1969   V8_DEPRECATE_SOON("Use maybe version",
1970                     Local<Object> ToObject(Isolate* isolate) const);
1971   V8_DEPRECATE_SOON("Use maybe version",
1972                     Local<Integer> ToInteger(Isolate* isolate) const);
1973   V8_DEPRECATE_SOON("Use maybe version",
1974                     Local<Uint32> ToUint32(Isolate* isolate) const);
1975   V8_DEPRECATE_SOON("Use maybe version",
1976                     Local<Int32> ToInt32(Isolate* isolate) const);
1977
1978   inline V8_DEPRECATE_SOON("Use maybe version",
1979                            Local<Boolean> ToBoolean() const);
1980   inline V8_DEPRECATE_SOON("Use maybe version", Local<Number> ToNumber() const);
1981   inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const);
1982   inline V8_DEPRECATE_SOON("Use maybe version",
1983                            Local<String> ToDetailString() const);
1984   inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject() const);
1985   inline V8_DEPRECATE_SOON("Use maybe version",
1986                            Local<Integer> ToInteger() const);
1987   inline V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToUint32() const);
1988   inline V8_DEPRECATE_SOON("Use maybe version", Local<Int32> ToInt32() const);
1989
1990   /**
1991    * Attempts to convert a string to an array index.
1992    * Returns an empty handle if the conversion fails.
1993    */
1994   V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToArrayIndex() const);
1995   V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToArrayIndex(
1996       Local<Context> context) const;
1997
1998   V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const;
1999   V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2000   V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
2001       Local<Context> context) const;
2002   V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value(
2003       Local<Context> context) const;
2004   V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2005
2006   V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const);
2007   V8_DEPRECATE_SOON("Use maybe version", double NumberValue() const);
2008   V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue() const);
2009   V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value() const);
2010   V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value() const);
2011
2012   /** JS == */
2013   V8_DEPRECATE_SOON("Use maybe version", bool Equals(Local<Value> that) const);
2014   V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
2015                                            Local<Value> that) const;
2016   bool StrictEquals(Local<Value> that) const;
2017   bool SameValue(Local<Value> that) const;
2018
2019   template <class T> V8_INLINE static Value* Cast(T* value);
2020
2021  private:
2022   V8_INLINE bool QuickIsUndefined() const;
2023   V8_INLINE bool QuickIsNull() const;
2024   V8_INLINE bool QuickIsString() const;
2025   bool FullIsUndefined() const;
2026   bool FullIsNull() const;
2027   bool FullIsString() const;
2028 };
2029
2030
2031 /**
2032  * The superclass of primitive values.  See ECMA-262 4.3.2.
2033  */
2034 class V8_EXPORT Primitive : public Value { };
2035
2036
2037 /**
2038  * A primitive boolean value (ECMA-262, 4.3.14).  Either the true
2039  * or false value.
2040  */
2041 class V8_EXPORT Boolean : public Primitive {
2042  public:
2043   bool Value() const;
2044   V8_INLINE static Boolean* Cast(v8::Value* obj);
2045   V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2046
2047  private:
2048   static void CheckCast(v8::Value* obj);
2049 };
2050
2051
2052 /**
2053  * A superclass for symbols and strings.
2054  */
2055 class V8_EXPORT Name : public Primitive {
2056  public:
2057   /**
2058    * Returns the identity hash for this object. The current implementation
2059    * uses an inline property on the object to store the identity hash.
2060    *
2061    * The return value will never be 0. Also, it is not guaranteed to be
2062    * unique.
2063    */
2064   int GetIdentityHash();
2065
2066   V8_INLINE static Name* Cast(v8::Value* obj);
2067  private:
2068   static void CheckCast(v8::Value* obj);
2069 };
2070
2071
2072 enum class NewStringType { kNormal, kInternalized };
2073
2074
2075 /**
2076  * A JavaScript string value (ECMA-262, 4.3.17).
2077  */
2078 class V8_EXPORT String : public Name {
2079  public:
2080   static const int kMaxLength = (1 << 28) - 16;
2081
2082   enum Encoding {
2083     UNKNOWN_ENCODING = 0x1,
2084     TWO_BYTE_ENCODING = 0x0,
2085     ONE_BYTE_ENCODING = 0x4
2086   };
2087   /**
2088    * Returns the number of characters in this string.
2089    */
2090   int Length() const;
2091
2092   /**
2093    * Returns the number of bytes in the UTF-8 encoded
2094    * representation of this string.
2095    */
2096   int Utf8Length() const;
2097
2098   /**
2099    * Returns whether this string is known to contain only one byte data.
2100    * Does not read the string.
2101    * False negatives are possible.
2102    */
2103   bool IsOneByte() const;
2104
2105   /**
2106    * Returns whether this string contain only one byte data.
2107    * Will read the entire string in some cases.
2108    */
2109   bool ContainsOnlyOneByte() const;
2110
2111   /**
2112    * Write the contents of the string to an external buffer.
2113    * If no arguments are given, expects the buffer to be large
2114    * enough to hold the entire string and NULL terminator. Copies
2115    * the contents of the string and the NULL terminator into the
2116    * buffer.
2117    *
2118    * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2119    * before the end of the buffer.
2120    *
2121    * Copies up to length characters into the output buffer.
2122    * Only null-terminates if there is enough space in the buffer.
2123    *
2124    * \param buffer The buffer into which the string will be copied.
2125    * \param start The starting position within the string at which
2126    * copying begins.
2127    * \param length The number of characters to copy from the string.  For
2128    *    WriteUtf8 the number of bytes in the buffer.
2129    * \param nchars_ref The number of characters written, can be NULL.
2130    * \param options Various options that might affect performance of this or
2131    *    subsequent operations.
2132    * \return The number of characters copied to the buffer excluding the null
2133    *    terminator.  For WriteUtf8: The number of bytes copied to the buffer
2134    *    including the null terminator (if written).
2135    */
2136   enum WriteOptions {
2137     NO_OPTIONS = 0,
2138     HINT_MANY_WRITES_EXPECTED = 1,
2139     NO_NULL_TERMINATION = 2,
2140     PRESERVE_ONE_BYTE_NULL = 4,
2141     // Used by WriteUtf8 to replace orphan surrogate code units with the
2142     // unicode replacement character. Needs to be set to guarantee valid UTF-8
2143     // output.
2144     REPLACE_INVALID_UTF8 = 8
2145   };
2146
2147   // 16-bit character codes.
2148   int Write(uint16_t* buffer,
2149             int start = 0,
2150             int length = -1,
2151             int options = NO_OPTIONS) const;
2152   // One byte characters.
2153   int WriteOneByte(uint8_t* buffer,
2154                    int start = 0,
2155                    int length = -1,
2156                    int options = NO_OPTIONS) const;
2157   // UTF-8 encoded characters.
2158   int WriteUtf8(char* buffer,
2159                 int length = -1,
2160                 int* nchars_ref = NULL,
2161                 int options = NO_OPTIONS) const;
2162
2163   /**
2164    * A zero length string.
2165    */
2166   V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
2167
2168   /**
2169    * Returns true if the string is external
2170    */
2171   bool IsExternal() const;
2172
2173   /**
2174    * Returns true if the string is both external and one-byte.
2175    */
2176   bool IsExternalOneByte() const;
2177
2178   class V8_EXPORT ExternalStringResourceBase {  // NOLINT
2179    public:
2180     virtual ~ExternalStringResourceBase() {}
2181
2182    protected:
2183     ExternalStringResourceBase() {}
2184
2185     /**
2186      * Internally V8 will call this Dispose method when the external string
2187      * resource is no longer needed. The default implementation will use the
2188      * delete operator. This method can be overridden in subclasses to
2189      * control how allocated external string resources are disposed.
2190      */
2191     virtual void Dispose() { delete this; }
2192
2193    private:
2194     // Disallow copying and assigning.
2195     ExternalStringResourceBase(const ExternalStringResourceBase&);
2196     void operator=(const ExternalStringResourceBase&);
2197
2198     friend class v8::internal::Heap;
2199   };
2200
2201   /**
2202    * An ExternalStringResource is a wrapper around a two-byte string
2203    * buffer that resides outside V8's heap. Implement an
2204    * ExternalStringResource to manage the life cycle of the underlying
2205    * buffer.  Note that the string data must be immutable.
2206    */
2207   class V8_EXPORT ExternalStringResource
2208       : public ExternalStringResourceBase {
2209    public:
2210     /**
2211      * Override the destructor to manage the life cycle of the underlying
2212      * buffer.
2213      */
2214     virtual ~ExternalStringResource() {}
2215
2216     /**
2217      * The string data from the underlying buffer.
2218      */
2219     virtual const uint16_t* data() const = 0;
2220
2221     /**
2222      * The length of the string. That is, the number of two-byte characters.
2223      */
2224     virtual size_t length() const = 0;
2225
2226    protected:
2227     ExternalStringResource() {}
2228   };
2229
2230   /**
2231    * An ExternalOneByteStringResource is a wrapper around an one-byte
2232    * string buffer that resides outside V8's heap. Implement an
2233    * ExternalOneByteStringResource to manage the life cycle of the
2234    * underlying buffer.  Note that the string data must be immutable
2235    * and that the data must be Latin-1 and not UTF-8, which would require
2236    * special treatment internally in the engine and do not allow efficient
2237    * indexing.  Use String::New or convert to 16 bit data for non-Latin1.
2238    */
2239
2240   class V8_EXPORT ExternalOneByteStringResource
2241       : public ExternalStringResourceBase {
2242    public:
2243     /**
2244      * Override the destructor to manage the life cycle of the underlying
2245      * buffer.
2246      */
2247     virtual ~ExternalOneByteStringResource() {}
2248     /** The string data from the underlying buffer.*/
2249     virtual const char* data() const = 0;
2250     /** The number of Latin-1 characters in the string.*/
2251     virtual size_t length() const = 0;
2252    protected:
2253     ExternalOneByteStringResource() {}
2254   };
2255
2256   /**
2257    * If the string is an external string, return the ExternalStringResourceBase
2258    * regardless of the encoding, otherwise return NULL.  The encoding of the
2259    * string is returned in encoding_out.
2260    */
2261   V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
2262       Encoding* encoding_out) const;
2263
2264   /**
2265    * Get the ExternalStringResource for an external string.  Returns
2266    * NULL if IsExternal() doesn't return true.
2267    */
2268   V8_INLINE ExternalStringResource* GetExternalStringResource() const;
2269
2270   /**
2271    * Get the ExternalOneByteStringResource for an external one-byte string.
2272    * Returns NULL if IsExternalOneByte() doesn't return true.
2273    */
2274   const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
2275
2276   V8_INLINE static String* Cast(v8::Value* obj);
2277
2278   // TODO(dcarney): remove with deprecation of New functions.
2279   enum NewStringType {
2280     kNormalString = static_cast<int>(v8::NewStringType::kNormal),
2281     kInternalizedString = static_cast<int>(v8::NewStringType::kInternalized)
2282   };
2283
2284   /** Allocates a new string from UTF-8 data.*/
2285   static V8_DEPRECATE_SOON(
2286       "Use maybe version",
2287       Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2288                                 NewStringType type = kNormalString,
2289                                 int length = -1));
2290
2291   /** Allocates a new string from UTF-8 data. Only returns an empty value when
2292    * length > kMaxLength. **/
2293   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
2294       Isolate* isolate, const char* data, v8::NewStringType type,
2295       int length = -1);
2296
2297   /** Allocates a new string from Latin-1 data.*/
2298   static V8_DEPRECATE_SOON(
2299       "Use maybe version",
2300       Local<String> NewFromOneByte(Isolate* isolate, const uint8_t* data,
2301                                    NewStringType type = kNormalString,
2302                                    int length = -1));
2303
2304   /** Allocates a new string from Latin-1 data.  Only returns an empty value
2305    * when length > kMaxLength. **/
2306   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
2307       Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2308       int length = -1);
2309
2310   /** Allocates a new string from UTF-16 data.*/
2311   static V8_DEPRECATE_SOON(
2312       "Use maybe version",
2313       Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2314                                    NewStringType type = kNormalString,
2315                                    int length = -1));
2316
2317   /** Allocates a new string from UTF-16 data. Only returns an empty value when
2318    * length > kMaxLength. **/
2319   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
2320       Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2321       int length = -1);
2322
2323   /**
2324    * Creates a new string by concatenating the left and the right strings
2325    * passed in as parameters.
2326    */
2327   static Local<String> Concat(Local<String> left, Local<String> right);
2328
2329   /**
2330    * Creates a new external string using the data defined in the given
2331    * resource. When the external string is no longer live on V8's heap the
2332    * resource will be disposed by calling its Dispose method. The caller of
2333    * this function should not otherwise delete or modify the resource. Neither
2334    * should the underlying buffer be deallocated or modified except through the
2335    * destructor of the external string resource.
2336    */
2337   static V8_DEPRECATE_SOON(
2338       "Use maybe version",
2339       Local<String> NewExternal(Isolate* isolate,
2340                                 ExternalStringResource* resource));
2341   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
2342       Isolate* isolate, ExternalStringResource* resource);
2343
2344   /**
2345    * Associate an external string resource with this string by transforming it
2346    * in place so that existing references to this string in the JavaScript heap
2347    * will use the external string resource. The external string resource's
2348    * character contents need to be equivalent to this string.
2349    * Returns true if the string has been changed to be an external string.
2350    * The string is not modified if the operation fails. See NewExternal for
2351    * information on the lifetime of the resource.
2352    */
2353   bool MakeExternal(ExternalStringResource* resource);
2354
2355   /**
2356    * Creates a new external string using the one-byte data defined in the given
2357    * resource. When the external string is no longer live on V8's heap the
2358    * resource will be disposed by calling its Dispose method. The caller of
2359    * this function should not otherwise delete or modify the resource. Neither
2360    * should the underlying buffer be deallocated or modified except through the
2361    * destructor of the external string resource.
2362    */
2363   static V8_DEPRECATE_SOON(
2364       "Use maybe version",
2365       Local<String> NewExternal(Isolate* isolate,
2366                                 ExternalOneByteStringResource* resource));
2367   static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
2368       Isolate* isolate, ExternalOneByteStringResource* resource);
2369
2370   /**
2371    * Associate an external string resource with this string by transforming it
2372    * in place so that existing references to this string in the JavaScript heap
2373    * will use the external string resource. The external string resource's
2374    * character contents need to be equivalent to this string.
2375    * Returns true if the string has been changed to be an external string.
2376    * The string is not modified if the operation fails. See NewExternal for
2377    * information on the lifetime of the resource.
2378    */
2379   bool MakeExternal(ExternalOneByteStringResource* resource);
2380
2381   /**
2382    * Returns true if this string can be made external.
2383    */
2384   bool CanMakeExternal();
2385
2386   /**
2387    * Converts an object to a UTF-8-encoded character array.  Useful if
2388    * you want to print the object.  If conversion to a string fails
2389    * (e.g. due to an exception in the toString() method of the object)
2390    * then the length() method returns 0 and the * operator returns
2391    * NULL.
2392    */
2393   class V8_EXPORT Utf8Value {
2394    public:
2395     explicit Utf8Value(Local<v8::Value> obj);
2396     ~Utf8Value();
2397     char* operator*() { return str_; }
2398     const char* operator*() const { return str_; }
2399     int length() const { return length_; }
2400    private:
2401     char* str_;
2402     int length_;
2403
2404     // Disallow copying and assigning.
2405     Utf8Value(const Utf8Value&);
2406     void operator=(const Utf8Value&);
2407   };
2408
2409   /**
2410    * Converts an object to a two-byte string.
2411    * If conversion to a string fails (eg. due to an exception in the toString()
2412    * method of the object) then the length() method returns 0 and the * operator
2413    * returns NULL.
2414    */
2415   class V8_EXPORT Value {
2416    public:
2417     explicit Value(Local<v8::Value> obj);
2418     ~Value();
2419     uint16_t* operator*() { return str_; }
2420     const uint16_t* operator*() const { return str_; }
2421     int length() const { return length_; }
2422    private:
2423     uint16_t* str_;
2424     int length_;
2425
2426     // Disallow copying and assigning.
2427     Value(const Value&);
2428     void operator=(const Value&);
2429   };
2430
2431  private:
2432   void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2433                                         Encoding encoding) const;
2434   void VerifyExternalStringResource(ExternalStringResource* val) const;
2435   static void CheckCast(v8::Value* obj);
2436 };
2437
2438
2439 /**
2440  * A JavaScript symbol (ECMA-262 edition 6)
2441  *
2442  * This is an experimental feature. Use at your own risk.
2443  */
2444 class V8_EXPORT Symbol : public Name {
2445  public:
2446   // Returns the print name string of the symbol, or undefined if none.
2447   Local<Value> Name() const;
2448
2449   // Create a symbol. If name is not empty, it will be used as the description.
2450   static Local<Symbol> New(
2451       Isolate *isolate, Local<String> name = Local<String>());
2452
2453   // Access global symbol registry.
2454   // Note that symbols created this way are never collected, so
2455   // they should only be used for statically fixed properties.
2456   // Also, there is only one global name space for the names used as keys.
2457   // To minimize the potential for clashes, use qualified names as keys.
2458   static Local<Symbol> For(Isolate *isolate, Local<String> name);
2459
2460   // Retrieve a global symbol. Similar to |For|, but using a separate
2461   // registry that is not accessible by (and cannot clash with) JavaScript code.
2462   static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2463
2464   // Well-known symbols
2465   static Local<Symbol> GetIterator(Isolate* isolate);
2466   static Local<Symbol> GetUnscopables(Isolate* isolate);
2467   static Local<Symbol> GetToStringTag(Isolate* isolate);
2468
2469   V8_INLINE static Symbol* Cast(v8::Value* obj);
2470
2471  private:
2472   Symbol();
2473   static void CheckCast(v8::Value* obj);
2474 };
2475
2476
2477 /**
2478  * A JavaScript number value (ECMA-262, 4.3.20)
2479  */
2480 class V8_EXPORT Number : public Primitive {
2481  public:
2482   double Value() const;
2483   static Local<Number> New(Isolate* isolate, double value);
2484   V8_INLINE static Number* Cast(v8::Value* obj);
2485  private:
2486   Number();
2487   static void CheckCast(v8::Value* obj);
2488 };
2489
2490
2491 /**
2492  * A JavaScript value representing a signed integer.
2493  */
2494 class V8_EXPORT Integer : public Number {
2495  public:
2496   static Local<Integer> New(Isolate* isolate, int32_t value);
2497   static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2498   int64_t Value() const;
2499   V8_INLINE static Integer* Cast(v8::Value* obj);
2500  private:
2501   Integer();
2502   static void CheckCast(v8::Value* obj);
2503 };
2504
2505
2506 /**
2507  * A JavaScript value representing a 32-bit signed integer.
2508  */
2509 class V8_EXPORT Int32 : public Integer {
2510  public:
2511   int32_t Value() const;
2512   V8_INLINE static Int32* Cast(v8::Value* obj);
2513
2514  private:
2515   Int32();
2516   static void CheckCast(v8::Value* obj);
2517 };
2518
2519
2520 /**
2521  * A JavaScript value representing a 32-bit unsigned integer.
2522  */
2523 class V8_EXPORT Uint32 : public Integer {
2524  public:
2525   uint32_t Value() const;
2526   V8_INLINE static Uint32* Cast(v8::Value* obj);
2527
2528  private:
2529   Uint32();
2530   static void CheckCast(v8::Value* obj);
2531 };
2532
2533
2534 enum PropertyAttribute {
2535   None       = 0,
2536   ReadOnly   = 1 << 0,
2537   DontEnum   = 1 << 1,
2538   DontDelete = 1 << 2
2539 };
2540
2541 /**
2542  * Accessor[Getter|Setter] are used as callback functions when
2543  * setting|getting a particular property. See Object and ObjectTemplate's
2544  * method SetAccessor.
2545  */
2546 typedef void (*AccessorGetterCallback)(
2547     Local<String> property,
2548     const PropertyCallbackInfo<Value>& info);
2549 typedef void (*AccessorNameGetterCallback)(
2550     Local<Name> property,
2551     const PropertyCallbackInfo<Value>& info);
2552
2553
2554 typedef void (*AccessorSetterCallback)(
2555     Local<String> property,
2556     Local<Value> value,
2557     const PropertyCallbackInfo<void>& info);
2558 typedef void (*AccessorNameSetterCallback)(
2559     Local<Name> property,
2560     Local<Value> value,
2561     const PropertyCallbackInfo<void>& info);
2562
2563
2564 /**
2565  * Access control specifications.
2566  *
2567  * Some accessors should be accessible across contexts.  These
2568  * accessors have an explicit access control parameter which specifies
2569  * the kind of cross-context access that should be allowed.
2570  *
2571  * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2572  */
2573 enum AccessControl {
2574   DEFAULT               = 0,
2575   ALL_CAN_READ          = 1,
2576   ALL_CAN_WRITE         = 1 << 1,
2577   PROHIBITS_OVERWRITING = 1 << 2
2578 };
2579
2580
2581 /**
2582  * A JavaScript object (ECMA-262, 4.3.3)
2583  */
2584 class V8_EXPORT Object : public Value {
2585  public:
2586   V8_DEPRECATE_SOON("Use maybe version",
2587                     bool Set(Local<Value> key, Local<Value> value));
2588   V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
2589                                         Local<Value> key, Local<Value> value);
2590
2591   V8_DEPRECATE_SOON("Use maybe version",
2592                     bool Set(uint32_t index, Local<Value> value));
2593   V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
2594                                         Local<Value> value);
2595
2596   // Implements CreateDataProperty (ECMA-262, 7.3.4).
2597   //
2598   // Defines a configurable, writable, enumerable property with the given value
2599   // on the object unless the property already exists and is not configurable
2600   // or the object is not extensible.
2601   //
2602   // Returns true on success.
2603   V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2604                                                        Local<Name> key,
2605                                                        Local<Value> value);
2606   V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2607                                                        uint32_t index,
2608                                                        Local<Value> value);
2609
2610   // Implements DefineOwnProperty.
2611   //
2612   // In general, CreateDataProperty will be faster, however, does not allow
2613   // for specifying attributes.
2614   //
2615   // Returns true on success.
2616   V8_WARN_UNUSED_RESULT Maybe<bool> DefineOwnProperty(
2617       Local<Context> context, Local<Name> key, Local<Value> value,
2618       PropertyAttribute attributes = None);
2619
2620   // Sets an own property on this object bypassing interceptors and
2621   // overriding accessors or read-only properties.
2622   //
2623   // Note that if the object has an interceptor the property will be set
2624   // locally, but since the interceptor takes precedence the local property
2625   // will only be returned if the interceptor doesn't return a value.
2626   //
2627   // Note also that this only works for named properties.
2628   V8_DEPRECATE_SOON("Use CreateDataProperty",
2629                     bool ForceSet(Local<Value> key, Local<Value> value,
2630                                   PropertyAttribute attribs = None));
2631   V8_DEPRECATE_SOON("Use CreateDataProperty",
2632                     Maybe<bool> ForceSet(Local<Context> context,
2633                                          Local<Value> key, Local<Value> value,
2634                                          PropertyAttribute attribs = None));
2635
2636   V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
2637   V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2638                                               Local<Value> key);
2639
2640   V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
2641   V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2642                                               uint32_t index);
2643
2644   /**
2645    * Gets the property attributes of a property which can be None or
2646    * any combination of ReadOnly, DontEnum and DontDelete. Returns
2647    * None when the property doesn't exist.
2648    */
2649   V8_DEPRECATE_SOON("Use maybe version",
2650                     PropertyAttribute GetPropertyAttributes(Local<Value> key));
2651   V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetPropertyAttributes(
2652       Local<Context> context, Local<Value> key);
2653
2654   /**
2655    * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2656    */
2657   V8_DEPRECATE_SOON("Use maybe version",
2658                     Local<Value> GetOwnPropertyDescriptor(Local<String> key));
2659   V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetOwnPropertyDescriptor(
2660       Local<Context> context, Local<String> key);
2661
2662   V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
2663   V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2664                                         Local<Value> key);
2665
2666   V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
2667   // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2668   Maybe<bool> Delete(Local<Context> context, Local<Value> key);
2669
2670   V8_DEPRECATE_SOON("Use maybe version", bool Has(uint32_t index));
2671   V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
2672
2673   V8_DEPRECATE_SOON("Use maybe version", bool Delete(uint32_t index));
2674   // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2675   Maybe<bool> Delete(Local<Context> context, uint32_t index);
2676
2677   V8_DEPRECATE_SOON("Use maybe version",
2678                     bool SetAccessor(Local<String> name,
2679                                      AccessorGetterCallback getter,
2680                                      AccessorSetterCallback setter = 0,
2681                                      Local<Value> data = Local<Value>(),
2682                                      AccessControl settings = DEFAULT,
2683                                      PropertyAttribute attribute = None));
2684   V8_DEPRECATE_SOON("Use maybe version",
2685                     bool SetAccessor(Local<Name> name,
2686                                      AccessorNameGetterCallback getter,
2687                                      AccessorNameSetterCallback setter = 0,
2688                                      Local<Value> data = Local<Value>(),
2689                                      AccessControl settings = DEFAULT,
2690                                      PropertyAttribute attribute = None));
2691   // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2692   Maybe<bool> SetAccessor(Local<Context> context, Local<Name> name,
2693                           AccessorNameGetterCallback getter,
2694                           AccessorNameSetterCallback setter = 0,
2695                           MaybeLocal<Value> data = MaybeLocal<Value>(),
2696                           AccessControl settings = DEFAULT,
2697                           PropertyAttribute attribute = None);
2698
2699   void SetAccessorProperty(Local<Name> name, Local<Function> getter,
2700                            Local<Function> setter = Local<Function>(),
2701                            PropertyAttribute attribute = None,
2702                            AccessControl settings = DEFAULT);
2703
2704   /**
2705    * Returns an array containing the names of the enumerable properties
2706    * of this object, including properties from prototype objects.  The
2707    * array returned by this method contains the same values as would
2708    * be enumerated by a for-in statement over this object.
2709    */
2710   V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
2711   V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
2712       Local<Context> context);
2713
2714   /**
2715    * This function has the same functionality as GetPropertyNames but
2716    * the returned array doesn't contain the names of properties from
2717    * prototype objects.
2718    */
2719   V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
2720   V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
2721       Local<Context> context);
2722
2723   /**
2724    * Get the prototype object.  This does not skip objects marked to
2725    * be skipped by __proto__ and it does not consult the security
2726    * handler.
2727    */
2728   Local<Value> GetPrototype();
2729
2730   /**
2731    * Set the prototype object.  This does not skip objects marked to
2732    * be skipped by __proto__ and it does not consult the security
2733    * handler.
2734    */
2735   V8_DEPRECATE_SOON("Use maybe version",
2736                     bool SetPrototype(Local<Value> prototype));
2737   V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
2738                                                  Local<Value> prototype);
2739
2740   /**
2741    * Finds an instance of the given function template in the prototype
2742    * chain.
2743    */
2744   Local<Object> FindInstanceInPrototypeChain(Local<FunctionTemplate> tmpl);
2745
2746   /**
2747    * Call builtin Object.prototype.toString on this object.
2748    * This is different from Value::ToString() that may call
2749    * user-defined toString function. This one does not.
2750    */
2751   V8_DEPRECATE_SOON("Use maybe version", Local<String> ObjectProtoToString());
2752   V8_WARN_UNUSED_RESULT MaybeLocal<String> ObjectProtoToString(
2753       Local<Context> context);
2754
2755   /**
2756    * Returns the name of the function invoked as a constructor for this object.
2757    */
2758   Local<String> GetConstructorName();
2759
2760   /** Gets the number of internal fields for this Object. */
2761   int InternalFieldCount();
2762
2763   /** Same as above, but works for Persistents */
2764   V8_INLINE static int InternalFieldCount(
2765       const PersistentBase<Object>& object) {
2766     return object.val_->InternalFieldCount();
2767   }
2768
2769   /** Gets the value from an internal field. */
2770   V8_INLINE Local<Value> GetInternalField(int index);
2771
2772   /** Sets the value in an internal field. */
2773   void SetInternalField(int index, Local<Value> value);
2774
2775   /**
2776    * Gets a 2-byte-aligned native pointer from an internal field. This field
2777    * must have been set by SetAlignedPointerInInternalField, everything else
2778    * leads to undefined behavior.
2779    */
2780   V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2781
2782   /** Same as above, but works for Persistents */
2783   V8_INLINE static void* GetAlignedPointerFromInternalField(
2784       const PersistentBase<Object>& object, int index) {
2785     return object.val_->GetAlignedPointerFromInternalField(index);
2786   }
2787
2788   /**
2789    * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2790    * a field, GetAlignedPointerFromInternalField must be used, everything else
2791    * leads to undefined behavior.
2792    */
2793   void SetAlignedPointerInInternalField(int index, void* value);
2794
2795   // Testers for local properties.
2796   V8_DEPRECATE_SOON("Use maybe version",
2797                     bool HasOwnProperty(Local<String> key));
2798   V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
2799                                                    Local<Name> key);
2800   V8_DEPRECATE_SOON("Use maybe version",
2801                     bool HasRealNamedProperty(Local<String> key));
2802   V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
2803                                                          Local<Name> key);
2804   V8_DEPRECATE_SOON("Use maybe version",
2805                     bool HasRealIndexedProperty(uint32_t index));
2806   V8_WARN_UNUSED_RESULT Maybe<bool> HasRealIndexedProperty(
2807       Local<Context> context, uint32_t index);
2808   V8_DEPRECATE_SOON("Use maybe version",
2809                     bool HasRealNamedCallbackProperty(Local<String> key));
2810   V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedCallbackProperty(
2811       Local<Context> context, Local<Name> key);
2812
2813   /**
2814    * If result.IsEmpty() no real property was located in the prototype chain.
2815    * This means interceptors in the prototype chain are not called.
2816    */
2817   V8_DEPRECATE_SOON(
2818       "Use maybe version",
2819       Local<Value> GetRealNamedPropertyInPrototypeChain(Local<String> key));
2820   V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain(
2821       Local<Context> context, Local<Name> key);
2822
2823   /**
2824    * Gets the property attributes of a real property in the prototype chain,
2825    * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
2826    * Interceptors in the prototype chain are not called.
2827    */
2828   V8_DEPRECATE_SOON(
2829       "Use maybe version",
2830       Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain(
2831           Local<String> key));
2832   V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute>
2833   GetRealNamedPropertyAttributesInPrototypeChain(Local<Context> context,
2834                                                  Local<Name> key);
2835
2836   /**
2837    * If result.IsEmpty() no real property was located on the object or
2838    * in the prototype chain.
2839    * This means interceptors in the prototype chain are not called.
2840    */
2841   V8_DEPRECATE_SOON("Use maybe version",
2842                     Local<Value> GetRealNamedProperty(Local<String> key));
2843   V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedProperty(
2844       Local<Context> context, Local<Name> key);
2845
2846   /**
2847    * Gets the property attributes of a real property which can be
2848    * None or any combination of ReadOnly, DontEnum and DontDelete.
2849    * Interceptors in the prototype chain are not called.
2850    */
2851   V8_DEPRECATE_SOON("Use maybe version",
2852                     Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2853                         Local<String> key));
2854   V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2855       Local<Context> context, Local<Name> key);
2856
2857   /** Tests for a named lookup interceptor.*/
2858   bool HasNamedLookupInterceptor();
2859
2860   /** Tests for an index lookup interceptor.*/
2861   bool HasIndexedLookupInterceptor();
2862
2863   /**
2864    * Returns the identity hash for this object. The current implementation
2865    * uses a hidden property on the object to store the identity hash.
2866    *
2867    * The return value will never be 0. Also, it is not guaranteed to be
2868    * unique.
2869    */
2870   int GetIdentityHash();
2871
2872   /**
2873    * Access hidden properties on JavaScript objects. These properties are
2874    * hidden from the executing JavaScript and only accessible through the V8
2875    * C++ API. Hidden properties introduced by V8 internally (for example the
2876    * identity hash) are prefixed with "v8::".
2877    */
2878   // TODO(dcarney): convert these to take a isolate and optionally bailout?
2879   bool SetHiddenValue(Local<String> key, Local<Value> value);
2880   Local<Value> GetHiddenValue(Local<String> key);
2881   bool DeleteHiddenValue(Local<String> key);
2882
2883   /**
2884    * Clone this object with a fast but shallow copy.  Values will point
2885    * to the same values as the original object.
2886    */
2887   // TODO(dcarney): take an isolate and optionally bail out?
2888   Local<Object> Clone();
2889
2890   /**
2891    * Returns the context in which the object was created.
2892    */
2893   Local<Context> CreationContext();
2894
2895   /**
2896    * Checks whether a callback is set by the
2897    * ObjectTemplate::SetCallAsFunctionHandler method.
2898    * When an Object is callable this method returns true.
2899    */
2900   bool IsCallable();
2901
2902   /**
2903    * Call an Object as a function if a callback is set by the
2904    * ObjectTemplate::SetCallAsFunctionHandler method.
2905    */
2906   V8_DEPRECATE_SOON("Use maybe version",
2907                     Local<Value> CallAsFunction(Local<Value> recv, int argc,
2908                                                 Local<Value> argv[]));
2909   V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context,
2910                                                          Local<Value> recv,
2911                                                          int argc,
2912                                                          Local<Value> argv[]);
2913
2914   /**
2915    * Call an Object as a constructor if a callback is set by the
2916    * ObjectTemplate::SetCallAsFunctionHandler method.
2917    * Note: This method behaves like the Function::NewInstance method.
2918    */
2919   V8_DEPRECATE_SOON("Use maybe version",
2920                     Local<Value> CallAsConstructor(int argc,
2921                                                    Local<Value> argv[]));
2922   V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsConstructor(
2923       Local<Context> context, int argc, Local<Value> argv[]);
2924
2925   /**
2926    * Return the isolate to which the Object belongs to.
2927    */
2928   V8_DEPRECATE_SOON("Keep track of isolate correctly", Isolate* GetIsolate());
2929
2930   static Local<Object> New(Isolate* isolate);
2931
2932   V8_INLINE static Object* Cast(Value* obj);
2933
2934  private:
2935   Object();
2936   static void CheckCast(Value* obj);
2937   Local<Value> SlowGetInternalField(int index);
2938   void* SlowGetAlignedPointerFromInternalField(int index);
2939 };
2940
2941
2942 /**
2943  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2944  */
2945 class V8_EXPORT Array : public Object {
2946  public:
2947   uint32_t Length() const;
2948
2949   /**
2950    * Clones an element at index |index|.  Returns an empty
2951    * handle if cloning fails (for any reason).
2952    */
2953   V8_DEPRECATE_SOON("Use maybe version",
2954                     Local<Object> CloneElementAt(uint32_t index));
2955   V8_WARN_UNUSED_RESULT MaybeLocal<Object> CloneElementAt(
2956       Local<Context> context, uint32_t index);
2957
2958   /**
2959    * Creates a JavaScript array with the given length. If the length
2960    * is negative the returned array will have length 0.
2961    */
2962   static Local<Array> New(Isolate* isolate, int length = 0);
2963
2964   V8_INLINE static Array* Cast(Value* obj);
2965  private:
2966   Array();
2967   static void CheckCast(Value* obj);
2968 };
2969
2970
2971 /**
2972  * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
2973  */
2974 class V8_EXPORT Map : public Object {
2975  public:
2976   size_t Size() const;
2977   void Clear();
2978   V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2979                                               Local<Value> key);
2980   V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context,
2981                                             Local<Value> key,
2982                                             Local<Value> value);
2983   V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2984                                         Local<Value> key);
2985   V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
2986                                            Local<Value> key);
2987
2988   /**
2989    * Returns an array of length Size() * 2, where index N is the Nth key and
2990    * index N + 1 is the Nth value.
2991    */
2992   Local<Array> AsArray() const;
2993
2994   /**
2995    * Creates a new empty Map.
2996    */
2997   static Local<Map> New(Isolate* isolate);
2998
2999   /**
3000    * Creates a new Map containing the elements of array, which must be formatted
3001    * in the same manner as the array returned from AsArray().
3002    * Guaranteed to be side-effect free if the array contains no holes.
3003    */
3004   static V8_WARN_UNUSED_RESULT V8_DEPRECATED(
3005       "Use mutation methods instead",
3006       MaybeLocal<Map> FromArray(Local<Context> context, Local<Array> array));
3007
3008   V8_INLINE static Map* Cast(Value* obj);
3009
3010  private:
3011   Map();
3012   static void CheckCast(Value* obj);
3013 };
3014
3015
3016 /**
3017  * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3018  */
3019 class V8_EXPORT Set : public Object {
3020  public:
3021   size_t Size() const;
3022   void Clear();
3023   V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context,
3024                                             Local<Value> key);
3025   V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3026                                         Local<Value> key);
3027   V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3028                                            Local<Value> key);
3029
3030   /**
3031    * Returns an array of the keys in this Set.
3032    */
3033   Local<Array> AsArray() const;
3034
3035   /**
3036    * Creates a new empty Set.
3037    */
3038   static Local<Set> New(Isolate* isolate);
3039
3040   /**
3041    * Creates a new Set containing the items in array.
3042    * Guaranteed to be side-effect free if the array contains no holes.
3043    */
3044   static V8_WARN_UNUSED_RESULT V8_DEPRECATED(
3045       "Use mutation methods instead",
3046       MaybeLocal<Set> FromArray(Local<Context> context, Local<Array> array));
3047
3048   V8_INLINE static Set* Cast(Value* obj);
3049
3050  private:
3051   Set();
3052   static void CheckCast(Value* obj);
3053 };
3054
3055
3056 template<typename T>
3057 class ReturnValue {
3058  public:
3059   template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3060       : value_(that.value_) {
3061     TYPE_CHECK(T, S);
3062   }
3063   // Local setters
3064   template <typename S>
3065   V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3066                               void Set(const Persistent<S>& handle));
3067   template <typename S>
3068   V8_INLINE void Set(const Global<S>& handle);
3069   template <typename S>
3070   V8_INLINE void Set(const Local<S> handle);
3071   // Fast primitive setters
3072   V8_INLINE void Set(bool value);
3073   V8_INLINE void Set(double i);
3074   V8_INLINE void Set(int32_t i);
3075   V8_INLINE void Set(uint32_t i);
3076   // Fast JS primitive setters
3077   V8_INLINE void SetNull();
3078   V8_INLINE void SetUndefined();
3079   V8_INLINE void SetEmptyString();
3080   // Convenience getter for Isolate
3081   V8_INLINE Isolate* GetIsolate();
3082
3083   // Pointer setter: Uncompilable to prevent inadvertent misuse.
3084   template <typename S>
3085   V8_INLINE void Set(S* whatever);
3086
3087  private:
3088   template<class F> friend class ReturnValue;
3089   template<class F> friend class FunctionCallbackInfo;
3090   template<class F> friend class PropertyCallbackInfo;
3091   template <class F, class G, class H>
3092   friend class PersistentValueMapBase;
3093   V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3094   V8_INLINE internal::Object* GetDefaultValue();
3095   V8_INLINE explicit ReturnValue(internal::Object** slot);
3096   internal::Object** value_;
3097 };
3098
3099
3100 /**
3101  * The argument information given to function call callbacks.  This
3102  * class provides access to information about the context of the call,
3103  * including the receiver, the number and values of arguments, and
3104  * the holder of the function.
3105  */
3106 template<typename T>
3107 class FunctionCallbackInfo {
3108  public:
3109   V8_INLINE int Length() const;
3110   V8_INLINE Local<Value> operator[](int i) const;
3111   V8_INLINE Local<Function> Callee() const;
3112   V8_INLINE Local<Object> This() const;
3113   V8_INLINE Local<Object> Holder() const;
3114   V8_INLINE bool IsConstructCall() const;
3115   V8_INLINE Local<Value> Data() const;
3116   V8_INLINE Isolate* GetIsolate() const;
3117   V8_INLINE ReturnValue<T> GetReturnValue() const;
3118   // This shouldn't be public, but the arm compiler needs it.
3119   static const int kArgsLength = 7;
3120
3121  protected:
3122   friend class internal::FunctionCallbackArguments;
3123   friend class internal::CustomArguments<FunctionCallbackInfo>;
3124   static const int kHolderIndex = 0;
3125   static const int kIsolateIndex = 1;
3126   static const int kReturnValueDefaultValueIndex = 2;
3127   static const int kReturnValueIndex = 3;
3128   static const int kDataIndex = 4;
3129   static const int kCalleeIndex = 5;
3130   static const int kContextSaveIndex = 6;
3131
3132   V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3133                    internal::Object** values,
3134                    int length,
3135                    bool is_construct_call);
3136   internal::Object** implicit_args_;
3137   internal::Object** values_;
3138   int length_;
3139   int is_construct_call_;
3140 };
3141
3142
3143 /**
3144  * The information passed to a property callback about the context
3145  * of the property access.
3146  */
3147 template<typename T>
3148 class PropertyCallbackInfo {
3149  public:
3150   V8_INLINE Isolate* GetIsolate() const;
3151   V8_INLINE Local<Value> Data() const;
3152   V8_INLINE Local<Object> This() const;
3153   V8_INLINE Local<Object> Holder() const;
3154   V8_INLINE ReturnValue<T> GetReturnValue() const;
3155   // This shouldn't be public, but the arm compiler needs it.
3156   static const int kArgsLength = 6;
3157
3158  protected:
3159   friend class MacroAssembler;
3160   friend class internal::PropertyCallbackArguments;
3161   friend class internal::CustomArguments<PropertyCallbackInfo>;
3162   static const int kHolderIndex = 0;
3163   static const int kIsolateIndex = 1;
3164   static const int kReturnValueDefaultValueIndex = 2;
3165   static const int kReturnValueIndex = 3;
3166   static const int kDataIndex = 4;
3167   static const int kThisIndex = 5;
3168
3169   V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
3170   internal::Object** args_;
3171 };
3172
3173
3174 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
3175
3176
3177 /**
3178  * A JavaScript function object (ECMA-262, 15.3).
3179  */
3180 class V8_EXPORT Function : public Object {
3181  public:
3182   /**
3183    * Create a function in the current execution context
3184    * for a given FunctionCallback.
3185    */
3186   static MaybeLocal<Function> New(Local<Context> context,
3187                                   FunctionCallback callback,
3188                                   Local<Value> data = Local<Value>(),
3189                                   int length = 0);
3190   static V8_DEPRECATE_SOON(
3191       "Use maybe version",
3192       Local<Function> New(Isolate* isolate, FunctionCallback callback,
3193                           Local<Value> data = Local<Value>(), int length = 0));
3194
3195   V8_DEPRECATE_SOON("Use maybe version",
3196                     Local<Object> NewInstance(int argc, Local<Value> argv[])
3197                         const);
3198   V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3199       Local<Context> context, int argc, Local<Value> argv[]) const;
3200
3201   V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance() const);
3202   V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3203       Local<Context> context) const {
3204     return NewInstance(context, 0, nullptr);
3205   }
3206
3207   V8_DEPRECATE_SOON("Use maybe version",
3208                     Local<Value> Call(Local<Value> recv, int argc,
3209                                       Local<Value> argv[]));
3210   V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context,
3211                                                Local<Value> recv, int argc,
3212                                                Local<Value> argv[]);
3213
3214   void SetName(Local<String> name);
3215   Local<Value> GetName() const;
3216
3217   /**
3218    * Name inferred from variable or property assignment of this function.
3219    * Used to facilitate debugging and profiling of JavaScript code written
3220    * in an OO style, where many functions are anonymous but are assigned
3221    * to object properties.
3222    */
3223   Local<Value> GetInferredName() const;
3224
3225   /**
3226    * User-defined name assigned to the "displayName" property of this function.
3227    * Used to facilitate debugging and profiling of JavaScript code.
3228    */
3229   Local<Value> GetDisplayName() const;
3230
3231   /**
3232    * Returns zero based line number of function body and
3233    * kLineOffsetNotFound if no information available.
3234    */
3235   int GetScriptLineNumber() const;
3236   /**
3237    * Returns zero based column number of function body and
3238    * kLineOffsetNotFound if no information available.
3239    */
3240   int GetScriptColumnNumber() const;
3241
3242   /**
3243    * Tells whether this function is builtin.
3244    */
3245   bool IsBuiltin() const;
3246
3247   /**
3248    * Returns scriptId.
3249    */
3250   int ScriptId() const;
3251
3252   /**
3253    * Returns the original function if this function is bound, else returns
3254    * v8::Undefined.
3255    */
3256   Local<Value> GetBoundFunction() const;
3257
3258   ScriptOrigin GetScriptOrigin() const;
3259   V8_INLINE static Function* Cast(Value* obj);
3260   static const int kLineOffsetNotFound;
3261
3262  private:
3263   Function();
3264   static void CheckCast(Value* obj);
3265 };
3266
3267
3268 /**
3269  * An instance of the built-in Promise constructor (ES6 draft).
3270  * This API is experimental. Only works with --harmony flag.
3271  */
3272 class V8_EXPORT Promise : public Object {
3273  public:
3274   class V8_EXPORT Resolver : public Object {
3275    public:
3276     /**
3277      * Create a new resolver, along with an associated promise in pending state.
3278      */
3279     static V8_DEPRECATE_SOON("Use maybe version",
3280                              Local<Resolver> New(Isolate* isolate));
3281     static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New(
3282         Local<Context> context);
3283
3284     /**
3285      * Extract the associated promise.
3286      */
3287     Local<Promise> GetPromise();
3288
3289     /**
3290      * Resolve/reject the associated promise with a given value.
3291      * Ignored if the promise is no longer pending.
3292      */
3293     V8_DEPRECATE_SOON("Use maybe version", void Resolve(Local<Value> value));
3294     // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3295     Maybe<bool> Resolve(Local<Context> context, Local<Value> value);
3296
3297     V8_DEPRECATE_SOON("Use maybe version", void Reject(Local<Value> value));
3298     // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3299     Maybe<bool> Reject(Local<Context> context, Local<Value> value);
3300
3301     V8_INLINE static Resolver* Cast(Value* obj);
3302
3303    private:
3304     Resolver();
3305     static void CheckCast(Value* obj);
3306   };
3307
3308   /**
3309    * Register a resolution/rejection handler with a promise.
3310    * The handler is given the respective resolution/rejection value as
3311    * an argument. If the promise is already resolved/rejected, the handler is
3312    * invoked at the end of turn.
3313    */
3314   V8_DEPRECATE_SOON("Use maybe version",
3315                     Local<Promise> Chain(Local<Function> handler));
3316   V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Chain(Local<Context> context,
3317                                                   Local<Function> handler);
3318
3319   V8_DEPRECATE_SOON("Use maybe version",
3320                     Local<Promise> Catch(Local<Function> handler));
3321   V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context,
3322                                                   Local<Function> handler);
3323
3324   V8_DEPRECATE_SOON("Use maybe version",
3325                     Local<Promise> Then(Local<Function> handler));
3326   V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
3327                                                  Local<Function> handler);
3328
3329   /**
3330    * Returns true if the promise has at least one derived promise, and
3331    * therefore resolve/reject handlers (including default handler).
3332    */
3333   bool HasHandler();
3334
3335   V8_INLINE static Promise* Cast(Value* obj);
3336
3337  private:
3338   Promise();
3339   static void CheckCast(Value* obj);
3340 };
3341
3342
3343 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
3344 // The number of required internal fields can be defined by embedder.
3345 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
3346 #endif
3347
3348
3349 enum class ArrayBufferCreationMode { kInternalized, kExternalized };
3350
3351
3352 /**
3353  * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
3354  * This API is experimental and may change significantly.
3355  */
3356 class V8_EXPORT ArrayBuffer : public Object {
3357  public:
3358   /**
3359    * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
3360    * The allocator is a global V8 setting. It has to be set via
3361    * Isolate::CreateParams.
3362    *
3363    * This API is experimental and may change significantly.
3364    */
3365   class V8_EXPORT Allocator { // NOLINT
3366    public:
3367     virtual ~Allocator() {}
3368
3369     /**
3370      * Allocate |length| bytes. Return NULL if allocation is not successful.
3371      * Memory should be initialized to zeroes.
3372      */
3373     virtual void* Allocate(size_t length) = 0;
3374
3375     /**
3376      * Allocate |length| bytes. Return NULL if allocation is not successful.
3377      * Memory does not have to be initialized.
3378      */
3379     virtual void* AllocateUninitialized(size_t length) = 0;
3380     /**
3381      * Free the memory block of size |length|, pointed to by |data|.
3382      * That memory is guaranteed to be previously allocated by |Allocate|.
3383      */
3384     virtual void Free(void* data, size_t length) = 0;
3385   };
3386
3387   /**
3388    * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
3389    * returns an instance of this class, populated, with a pointer to data
3390    * and byte length.
3391    *
3392    * The Data pointer of ArrayBuffer::Contents is always allocated with
3393    * Allocator::Allocate that is set via Isolate::CreateParams.
3394    *
3395    * This API is experimental and may change significantly.
3396    */
3397   class V8_EXPORT Contents { // NOLINT
3398    public:
3399     Contents() : data_(NULL), byte_length_(0) {}
3400
3401     void* Data() const { return data_; }
3402     size_t ByteLength() const { return byte_length_; }
3403
3404    private:
3405     void* data_;
3406     size_t byte_length_;
3407
3408     friend class ArrayBuffer;
3409   };
3410
3411
3412   /**
3413    * Data length in bytes.
3414    */
3415   size_t ByteLength() const;
3416
3417   /**
3418    * Create a new ArrayBuffer. Allocate |byte_length| bytes.
3419    * Allocated memory will be owned by a created ArrayBuffer and
3420    * will be deallocated when it is garbage-collected,
3421    * unless the object is externalized.
3422    */
3423   static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
3424
3425   /**
3426    * Create a new ArrayBuffer over an existing memory block.
3427    * The created array buffer is by default immediately in externalized state.
3428    * The memory block will not be reclaimed when a created ArrayBuffer
3429    * is garbage-collected.
3430    */
3431   static Local<ArrayBuffer> New(
3432       Isolate* isolate, void* data, size_t byte_length,
3433       ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3434
3435   /**
3436    * Returns true if ArrayBuffer is externalized, that is, does not
3437    * own its memory block.
3438    */
3439   bool IsExternal() const;
3440
3441   /**
3442    * Returns true if this ArrayBuffer may be neutered.
3443    */
3444   bool IsNeuterable() const;
3445
3446   /**
3447    * Neuters this ArrayBuffer and all its views (typed arrays).
3448    * Neutering sets the byte length of the buffer and all typed arrays to zero,
3449    * preventing JavaScript from ever accessing underlying backing store.
3450    * ArrayBuffer should have been externalized and must be neuterable.
3451    */
3452   void Neuter();
3453
3454   /**
3455    * Make this ArrayBuffer external. The pointer to underlying memory block
3456    * and byte length are returned as |Contents| structure. After ArrayBuffer
3457    * had been etxrenalized, it does no longer owns the memory block. The caller
3458    * should take steps to free memory when it is no longer needed.
3459    *
3460    * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3461    * that has been set via Isolate::CreateParams.
3462    */
3463   Contents Externalize();
3464
3465   /**
3466    * Get a pointer to the ArrayBuffer's underlying memory block without
3467    * externalizing it. If the ArrayBuffer is not externalized, this pointer
3468    * will become invalid as soon as the ArrayBuffer became garbage collected.
3469    *
3470    * The embedder should make sure to hold a strong reference to the
3471    * ArrayBuffer while accessing this pointer.
3472    *
3473    * The memory block is guaranteed to be allocated with |Allocator::Allocate|.
3474    */
3475   Contents GetContents();
3476
3477   V8_INLINE static ArrayBuffer* Cast(Value* obj);
3478
3479   static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3480
3481  private:
3482   ArrayBuffer();
3483   static void CheckCast(Value* obj);
3484 };
3485
3486
3487 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3488 // The number of required internal fields can be defined by embedder.
3489 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3490 #endif
3491
3492
3493 /**
3494  * A base class for an instance of one of "views" over ArrayBuffer,
3495  * including TypedArrays and DataView (ES6 draft 15.13).
3496  *
3497  * This API is experimental and may change significantly.
3498  */
3499 class V8_EXPORT ArrayBufferView : public Object {
3500  public:
3501   /**
3502    * Returns underlying ArrayBuffer.
3503    */
3504   Local<ArrayBuffer> Buffer();
3505   /**
3506    * Byte offset in |Buffer|.
3507    */
3508   size_t ByteOffset();
3509   /**
3510    * Size of a view in bytes.
3511    */
3512   size_t ByteLength();
3513
3514   /**
3515    * Copy the contents of the ArrayBufferView's buffer to an embedder defined
3516    * memory without additional overhead that calling ArrayBufferView::Buffer
3517    * might incur.
3518    *
3519    * Will write at most min(|byte_length|, ByteLength) bytes starting at
3520    * ByteOffset of the underling buffer to the memory starting at |dest|.
3521    * Returns the number of bytes actually written.
3522    */
3523   size_t CopyContents(void* dest, size_t byte_length);
3524
3525   /**
3526    * Returns true if ArrayBufferView's backing ArrayBuffer has already been
3527    * allocated.
3528    */
3529   bool HasBuffer() const;
3530
3531   V8_INLINE static ArrayBufferView* Cast(Value* obj);
3532
3533   static const int kInternalFieldCount =
3534       V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
3535
3536  private:
3537   ArrayBufferView();
3538   static void CheckCast(Value* obj);
3539 };
3540
3541
3542 /**
3543  * A base class for an instance of TypedArray series of constructors
3544  * (ES6 draft 15.13.6).
3545  * This API is experimental and may change significantly.
3546  */
3547 class V8_EXPORT TypedArray : public ArrayBufferView {
3548  public:
3549   /**
3550    * Number of elements in this typed array
3551    * (e.g. for Int16Array, |ByteLength|/2).
3552    */
3553   size_t Length();
3554
3555   V8_INLINE static TypedArray* Cast(Value* obj);
3556
3557  private:
3558   TypedArray();
3559   static void CheckCast(Value* obj);
3560 };
3561
3562
3563 /**
3564  * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3565  * This API is experimental and may change significantly.
3566  */
3567 class V8_EXPORT Uint8Array : public TypedArray {
3568  public:
3569   static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
3570                                size_t byte_offset, size_t length);
3571   static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3572                                size_t byte_offset, size_t length);
3573   V8_INLINE static Uint8Array* Cast(Value* obj);
3574
3575  private:
3576   Uint8Array();
3577   static void CheckCast(Value* obj);
3578 };
3579
3580
3581 /**
3582  * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3583  * This API is experimental and may change significantly.
3584  */
3585 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3586  public:
3587   static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
3588                                       size_t byte_offset, size_t length);
3589   static Local<Uint8ClampedArray> New(
3590       Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
3591       size_t length);
3592   V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3593
3594  private:
3595   Uint8ClampedArray();
3596   static void CheckCast(Value* obj);
3597 };
3598
3599 /**
3600  * An instance of Int8Array constructor (ES6 draft 15.13.6).
3601  * This API is experimental and may change significantly.
3602  */
3603 class V8_EXPORT Int8Array : public TypedArray {
3604  public:
3605   static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
3606                               size_t byte_offset, size_t length);
3607   static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3608                               size_t byte_offset, size_t length);
3609   V8_INLINE static Int8Array* Cast(Value* obj);
3610
3611  private:
3612   Int8Array();
3613   static void CheckCast(Value* obj);
3614 };
3615
3616
3617 /**
3618  * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3619  * This API is experimental and may change significantly.
3620  */
3621 class V8_EXPORT Uint16Array : public TypedArray {
3622  public:
3623   static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
3624                                 size_t byte_offset, size_t length);
3625   static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3626                                 size_t byte_offset, size_t length);
3627   V8_INLINE static Uint16Array* Cast(Value* obj);
3628
3629  private:
3630   Uint16Array();
3631   static void CheckCast(Value* obj);
3632 };
3633
3634
3635 /**
3636  * An instance of Int16Array constructor (ES6 draft 15.13.6).
3637  * This API is experimental and may change significantly.
3638  */
3639 class V8_EXPORT Int16Array : public TypedArray {
3640  public:
3641   static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
3642                                size_t byte_offset, size_t length);
3643   static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3644                                size_t byte_offset, size_t length);
3645   V8_INLINE static Int16Array* Cast(Value* obj);
3646
3647  private:
3648   Int16Array();
3649   static void CheckCast(Value* obj);
3650 };
3651
3652
3653 /**
3654  * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3655  * This API is experimental and may change significantly.
3656  */
3657 class V8_EXPORT Uint32Array : public TypedArray {
3658  public:
3659   static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
3660                                 size_t byte_offset, size_t length);
3661   static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3662                                 size_t byte_offset, size_t length);
3663   V8_INLINE static Uint32Array* Cast(Value* obj);
3664
3665  private:
3666   Uint32Array();
3667   static void CheckCast(Value* obj);
3668 };
3669
3670
3671 /**
3672  * An instance of Int32Array constructor (ES6 draft 15.13.6).
3673  * This API is experimental and may change significantly.
3674  */
3675 class V8_EXPORT Int32Array : public TypedArray {
3676  public:
3677   static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
3678                                size_t byte_offset, size_t length);
3679   static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3680                                size_t byte_offset, size_t length);
3681   V8_INLINE static Int32Array* Cast(Value* obj);
3682
3683  private:
3684   Int32Array();
3685   static void CheckCast(Value* obj);
3686 };
3687
3688
3689 /**
3690  * An instance of Float32Array constructor (ES6 draft 15.13.6).
3691  * This API is experimental and may change significantly.
3692  */
3693 class V8_EXPORT Float32Array : public TypedArray {
3694  public:
3695   static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
3696                                  size_t byte_offset, size_t length);
3697   static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3698                                  size_t byte_offset, size_t length);
3699   V8_INLINE static Float32Array* Cast(Value* obj);
3700
3701  private:
3702   Float32Array();
3703   static void CheckCast(Value* obj);
3704 };
3705
3706
3707 /**
3708  * An instance of Float64Array constructor (ES6 draft 15.13.6).
3709  * This API is experimental and may change significantly.
3710  */
3711 class V8_EXPORT Float64Array : public TypedArray {
3712  public:
3713   static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
3714                                  size_t byte_offset, size_t length);
3715   static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3716                                  size_t byte_offset, size_t length);
3717   V8_INLINE static Float64Array* Cast(Value* obj);
3718
3719  private:
3720   Float64Array();
3721   static void CheckCast(Value* obj);
3722 };
3723
3724
3725 /**
3726  * An instance of DataView constructor (ES6 draft 15.13.7).
3727  * This API is experimental and may change significantly.
3728  */
3729 class V8_EXPORT DataView : public ArrayBufferView {
3730  public:
3731   static Local<DataView> New(Local<ArrayBuffer> array_buffer,
3732                              size_t byte_offset, size_t length);
3733   static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
3734                              size_t byte_offset, size_t length);
3735   V8_INLINE static DataView* Cast(Value* obj);
3736
3737  private:
3738   DataView();
3739   static void CheckCast(Value* obj);
3740 };
3741
3742
3743 /**
3744  * An instance of the built-in SharedArrayBuffer constructor.
3745  * This API is experimental and may change significantly.
3746  */
3747 class V8_EXPORT SharedArrayBuffer : public Object {
3748  public:
3749   /**
3750    * The contents of an |SharedArrayBuffer|. Externalization of
3751    * |SharedArrayBuffer| returns an instance of this class, populated, with a
3752    * pointer to data and byte length.
3753    *
3754    * The Data pointer of SharedArrayBuffer::Contents is always allocated with
3755    * |ArrayBuffer::Allocator::Allocate| by the allocator specified in
3756    * v8::Isolate::CreateParams::array_buffer_allocator.
3757    *
3758    * This API is experimental and may change significantly.
3759    */
3760   class V8_EXPORT Contents {  // NOLINT
3761    public:
3762     Contents() : data_(NULL), byte_length_(0) {}
3763
3764     void* Data() const { return data_; }
3765     size_t ByteLength() const { return byte_length_; }
3766
3767    private:
3768     void* data_;
3769     size_t byte_length_;
3770
3771     friend class SharedArrayBuffer;
3772   };
3773
3774
3775   /**
3776    * Data length in bytes.
3777    */
3778   size_t ByteLength() const;
3779
3780   /**
3781    * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
3782    * Allocated memory will be owned by a created SharedArrayBuffer and
3783    * will be deallocated when it is garbage-collected,
3784    * unless the object is externalized.
3785    */
3786   static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
3787
3788   /**
3789    * Create a new SharedArrayBuffer over an existing memory block.  The created
3790    * array buffer is immediately in externalized state unless otherwise
3791    * specified. The memory block will not be reclaimed when a created
3792    * SharedArrayBuffer is garbage-collected.
3793    */
3794   static Local<SharedArrayBuffer> New(
3795       Isolate* isolate, void* data, size_t byte_length,
3796       ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3797
3798   /**
3799    * Returns true if SharedArrayBuffer is externalized, that is, does not
3800    * own its memory block.
3801    */
3802   bool IsExternal() const;
3803
3804   /**
3805    * Make this SharedArrayBuffer external. The pointer to underlying memory
3806    * block and byte length are returned as |Contents| structure. After
3807    * SharedArrayBuffer had been etxrenalized, it does no longer owns the memory
3808    * block. The caller should take steps to free memory when it is no longer
3809    * needed.
3810    *
3811    * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3812    * by the allocator specified in
3813    * v8::Isolate::CreateParams::array_buffer_allocator.
3814    *
3815    */
3816   Contents Externalize();
3817
3818   /**
3819    * Get a pointer to the ArrayBuffer's underlying memory block without
3820    * externalizing it. If the ArrayBuffer is not externalized, this pointer
3821    * will become invalid as soon as the ArrayBuffer became garbage collected.
3822    *
3823    * The embedder should make sure to hold a strong reference to the
3824    * ArrayBuffer while accessing this pointer.
3825    *
3826    * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3827    * by the allocator specified in
3828    * v8::Isolate::CreateParams::array_buffer_allocator.
3829    */
3830   Contents GetContents();
3831
3832   V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
3833
3834   static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3835
3836  private:
3837   SharedArrayBuffer();
3838   static void CheckCast(Value* obj);
3839 };
3840
3841
3842 /**
3843  * An instance of the built-in Date constructor (ECMA-262, 15.9).
3844  */
3845 class V8_EXPORT Date : public Object {
3846  public:
3847   static V8_DEPRECATE_SOON("Use maybe version.",
3848                            Local<Value> New(Isolate* isolate, double time));
3849   static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
3850                                                      double time);
3851
3852   /**
3853    * A specialization of Value::NumberValue that is more efficient
3854    * because we know the structure of this object.
3855    */
3856   double ValueOf() const;
3857
3858   V8_INLINE static Date* Cast(v8::Value* obj);
3859
3860   /**
3861    * Notification that the embedder has changed the time zone,
3862    * daylight savings time, or other date / time configuration
3863    * parameters.  V8 keeps a cache of various values used for
3864    * date / time computation.  This notification will reset
3865    * those cached values for the current context so that date /
3866    * time configuration changes would be reflected in the Date
3867    * object.
3868    *
3869    * This API should not be called more than needed as it will
3870    * negatively impact the performance of date operations.
3871    */
3872   static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3873
3874  private:
3875   static void CheckCast(v8::Value* obj);
3876 };
3877
3878
3879 /**
3880  * A Number object (ECMA-262, 4.3.21).
3881  */
3882 class V8_EXPORT NumberObject : public Object {
3883  public:
3884   static Local<Value> New(Isolate* isolate, double value);
3885
3886   double ValueOf() const;
3887
3888   V8_INLINE static NumberObject* Cast(v8::Value* obj);
3889
3890  private:
3891   static void CheckCast(v8::Value* obj);
3892 };
3893
3894
3895 /**
3896  * A Boolean object (ECMA-262, 4.3.15).
3897  */
3898 class V8_EXPORT BooleanObject : public Object {
3899  public:
3900   static Local<Value> New(bool value);
3901
3902   bool ValueOf() const;
3903
3904   V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3905
3906  private:
3907   static void CheckCast(v8::Value* obj);
3908 };
3909
3910
3911 /**
3912  * A String object (ECMA-262, 4.3.18).
3913  */
3914 class V8_EXPORT StringObject : public Object {
3915  public:
3916   static Local<Value> New(Local<String> value);
3917
3918   Local<String> ValueOf() const;
3919
3920   V8_INLINE static StringObject* Cast(v8::Value* obj);
3921
3922  private:
3923   static void CheckCast(v8::Value* obj);
3924 };
3925
3926
3927 /**
3928  * A Symbol object (ECMA-262 edition 6).
3929  *
3930  * This is an experimental feature. Use at your own risk.
3931  */
3932 class V8_EXPORT SymbolObject : public Object {
3933  public:
3934   static Local<Value> New(Isolate* isolate, Local<Symbol> value);
3935
3936   Local<Symbol> ValueOf() const;
3937
3938   V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3939
3940  private:
3941   static void CheckCast(v8::Value* obj);
3942 };
3943
3944
3945 /**
3946  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3947  */
3948 class V8_EXPORT RegExp : public Object {
3949  public:
3950   /**
3951    * Regular expression flag bits. They can be or'ed to enable a set
3952    * of flags.
3953    */
3954   enum Flags {
3955     kNone = 0,
3956     kGlobal = 1,
3957     kIgnoreCase = 2,
3958     kMultiline = 4
3959   };
3960
3961   /**
3962    * Creates a regular expression from the given pattern string and
3963    * the flags bit field. May throw a JavaScript exception as
3964    * described in ECMA-262, 15.10.4.1.
3965    *
3966    * For example,
3967    *   RegExp::New(v8::String::New("foo"),
3968    *               static_cast<RegExp::Flags>(kGlobal | kMultiline))
3969    * is equivalent to evaluating "/foo/gm".
3970    */
3971   static V8_DEPRECATE_SOON("Use maybe version",
3972                            Local<RegExp> New(Local<String> pattern,
3973                                              Flags flags));
3974   static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
3975                                                       Local<String> pattern,
3976                                                       Flags flags);
3977
3978   /**
3979    * Returns the value of the source property: a string representing
3980    * the regular expression.
3981    */
3982   Local<String> GetSource() const;
3983
3984   /**
3985    * Returns the flags bit field.
3986    */
3987   Flags GetFlags() const;
3988
3989   V8_INLINE static RegExp* Cast(v8::Value* obj);
3990
3991  private:
3992   static void CheckCast(v8::Value* obj);
3993 };
3994
3995
3996 /**
3997  * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3998  * to associate C++ data structures with JavaScript objects.
3999  */
4000 class V8_EXPORT External : public Value {
4001  public:
4002   static Local<External> New(Isolate* isolate, void* value);
4003   V8_INLINE static External* Cast(Value* obj);
4004   void* Value() const;
4005  private:
4006   static void CheckCast(v8::Value* obj);
4007 };
4008
4009
4010 // --- Templates ---
4011
4012
4013 /**
4014  * The superclass of object and function templates.
4015  */
4016 class V8_EXPORT Template : public Data {
4017  public:
4018   /** Adds a property to each instance created by this template.*/
4019   void Set(Local<Name> name, Local<Data> value,
4020            PropertyAttribute attributes = None);
4021   V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
4022
4023   void SetAccessorProperty(
4024      Local<Name> name,
4025      Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
4026      Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
4027      PropertyAttribute attribute = None,
4028      AccessControl settings = DEFAULT);
4029
4030 #ifdef V8_JS_ACCESSORS
4031   void SetAccessorProperty(Local<Name> name,
4032                            Local<Function> getter = Local<Function>(),
4033                            Local<Function> setter = Local<Function>(),
4034                            PropertyAttribute attribute = None);
4035 #endif  // V8_JS_ACCESSORS
4036
4037   /**
4038    * Whenever the property with the given name is accessed on objects
4039    * created from this Template the getter and setter callbacks
4040    * are called instead of getting and setting the property directly
4041    * on the JavaScript object.
4042    *
4043    * \param name The name of the property for which an accessor is added.
4044    * \param getter The callback to invoke when getting the property.
4045    * \param setter The callback to invoke when setting the property.
4046    * \param data A piece of data that will be passed to the getter and setter
4047    *   callbacks whenever they are invoked.
4048    * \param settings Access control settings for the accessor. This is a bit
4049    *   field consisting of one of more of
4050    *   DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4051    *   The default is to not allow cross-context access.
4052    *   ALL_CAN_READ means that all cross-context reads are allowed.
4053    *   ALL_CAN_WRITE means that all cross-context writes are allowed.
4054    *   The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4055    *   cross-context access.
4056    * \param attribute The attributes of the property for which an accessor
4057    *   is added.
4058    * \param signature The signature describes valid receivers for the accessor
4059    *   and is used to perform implicit instance checks against them. If the
4060    *   receiver is incompatible (i.e. is not an instance of the constructor as
4061    *   defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4062    *   thrown and no callback is invoked.
4063    */
4064   void SetNativeDataProperty(
4065       Local<String> name, AccessorGetterCallback getter,
4066       AccessorSetterCallback setter = 0,
4067       // TODO(dcarney): gcc can't handle Local below
4068       Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4069       Local<AccessorSignature> signature = Local<AccessorSignature>(),
4070       AccessControl settings = DEFAULT);
4071   void SetNativeDataProperty(
4072       Local<Name> name, AccessorNameGetterCallback getter,
4073       AccessorNameSetterCallback setter = 0,
4074       // TODO(dcarney): gcc can't handle Local below
4075       Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4076       Local<AccessorSignature> signature = Local<AccessorSignature>(),
4077       AccessControl settings = DEFAULT);
4078
4079  private:
4080   Template();
4081
4082   friend class ObjectTemplate;
4083   friend class FunctionTemplate;
4084 };
4085
4086
4087 /**
4088  * NamedProperty[Getter|Setter] are used as interceptors on object.
4089  * See ObjectTemplate::SetNamedPropertyHandler.
4090  */
4091 typedef void (*NamedPropertyGetterCallback)(
4092     Local<String> property,
4093     const PropertyCallbackInfo<Value>& info);
4094
4095
4096 /**
4097  * Returns the value if the setter intercepts the request.
4098  * Otherwise, returns an empty handle.
4099  */
4100 typedef void (*NamedPropertySetterCallback)(
4101     Local<String> property,
4102     Local<Value> value,
4103     const PropertyCallbackInfo<Value>& info);
4104
4105
4106 /**
4107  * Returns a non-empty handle if the interceptor intercepts the request.
4108  * The result is an integer encoding property attributes (like v8::None,
4109  * v8::DontEnum, etc.)
4110  */
4111 typedef void (*NamedPropertyQueryCallback)(
4112     Local<String> property,
4113     const PropertyCallbackInfo<Integer>& info);
4114
4115
4116 /**
4117  * Returns a non-empty handle if the deleter intercepts the request.
4118  * The return value is true if the property could be deleted and false
4119  * otherwise.
4120  */
4121 typedef void (*NamedPropertyDeleterCallback)(
4122     Local<String> property,
4123     const PropertyCallbackInfo<Boolean>& info);
4124
4125
4126 /**
4127  * Returns an array containing the names of the properties the named
4128  * property getter intercepts.
4129  */
4130 typedef void (*NamedPropertyEnumeratorCallback)(
4131     const PropertyCallbackInfo<Array>& info);
4132
4133
4134 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
4135 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
4136 /**
4137  * GenericNamedProperty[Getter|Setter] are used as interceptors on object.
4138  * See ObjectTemplate::SetNamedPropertyHandler.
4139  */
4140 typedef void (*GenericNamedPropertyGetterCallback)(
4141     Local<Name> property, const PropertyCallbackInfo<Value>& info);
4142
4143
4144 /**
4145  * Returns the value if the setter intercepts the request.
4146  * Otherwise, returns an empty handle.
4147  */
4148 typedef void (*GenericNamedPropertySetterCallback)(
4149     Local<Name> property, Local<Value> value,
4150     const PropertyCallbackInfo<Value>& info);
4151
4152
4153 /**
4154  * Returns a non-empty handle if the interceptor intercepts the request.
4155  * The result is an integer encoding property attributes (like v8::None,
4156  * v8::DontEnum, etc.)
4157  */
4158 typedef void (*GenericNamedPropertyQueryCallback)(
4159     Local<Name> property, const PropertyCallbackInfo<Integer>& info);
4160
4161
4162 /**
4163  * Returns a non-empty handle if the deleter intercepts the request.
4164  * The return value is true if the property could be deleted and false
4165  * otherwise.
4166  */
4167 typedef void (*GenericNamedPropertyDeleterCallback)(
4168     Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
4169
4170
4171 /**
4172  * Returns an array containing the names of the properties the named
4173  * property getter intercepts.
4174  */
4175 typedef void (*GenericNamedPropertyEnumeratorCallback)(
4176     const PropertyCallbackInfo<Array>& info);
4177
4178
4179 /**
4180  * Returns the value of the property if the getter intercepts the
4181  * request.  Otherwise, returns an empty handle.
4182  */
4183 typedef void (*IndexedPropertyGetterCallback)(
4184     uint32_t index,
4185     const PropertyCallbackInfo<Value>& info);
4186
4187
4188 /**
4189  * Returns the value if the setter intercepts the request.
4190  * Otherwise, returns an empty handle.
4191  */
4192 typedef void (*IndexedPropertySetterCallback)(
4193     uint32_t index,
4194     Local<Value> value,
4195     const PropertyCallbackInfo<Value>& info);
4196
4197
4198 /**
4199  * Returns a non-empty handle if the interceptor intercepts the request.
4200  * The result is an integer encoding property attributes.
4201  */
4202 typedef void (*IndexedPropertyQueryCallback)(
4203     uint32_t index,
4204     const PropertyCallbackInfo<Integer>& info);
4205
4206
4207 /**
4208  * Returns a non-empty handle if the deleter intercepts the request.
4209  * The return value is true if the property could be deleted and false
4210  * otherwise.
4211  */
4212 typedef void (*IndexedPropertyDeleterCallback)(
4213     uint32_t index,
4214     const PropertyCallbackInfo<Boolean>& info);
4215
4216
4217 /**
4218  * Returns an array containing the indices of the properties the
4219  * indexed property getter intercepts.
4220  */
4221 typedef void (*IndexedPropertyEnumeratorCallback)(
4222     const PropertyCallbackInfo<Array>& info);
4223
4224
4225 /**
4226  * Access type specification.
4227  */
4228 enum AccessType {
4229   ACCESS_GET,
4230   ACCESS_SET,
4231   ACCESS_HAS,
4232   ACCESS_DELETE,
4233   ACCESS_KEYS
4234 };
4235
4236
4237 /**
4238  * Returns true if cross-context access should be allowed to the named
4239  * property with the given key on the host object.
4240  */
4241 typedef bool (*NamedSecurityCallback)(Local<Object> host,
4242                                       Local<Value> key,
4243                                       AccessType type,
4244                                       Local<Value> data);
4245
4246
4247 /**
4248  * Returns true if cross-context access should be allowed to the indexed
4249  * property with the given index on the host object.
4250  */
4251 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
4252                                         uint32_t index,
4253                                         AccessType type,
4254                                         Local<Value> data);
4255
4256
4257 /**
4258  * A FunctionTemplate is used to create functions at runtime. There
4259  * can only be one function created from a FunctionTemplate in a
4260  * context.  The lifetime of the created function is equal to the
4261  * lifetime of the context.  So in case the embedder needs to create
4262  * temporary functions that can be collected using Scripts is
4263  * preferred.
4264  *
4265  * Any modification of a FunctionTemplate after first instantiation will trigger
4266  *a crash.
4267  *
4268  * A FunctionTemplate can have properties, these properties are added to the
4269  * function object when it is created.
4270  *
4271  * A FunctionTemplate has a corresponding instance template which is
4272  * used to create object instances when the function is used as a
4273  * constructor. Properties added to the instance template are added to
4274  * each object instance.
4275  *
4276  * A FunctionTemplate can have a prototype template. The prototype template
4277  * is used to create the prototype object of the function.
4278  *
4279  * The following example shows how to use a FunctionTemplate:
4280  *
4281  * \code
4282  *    v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
4283  *    t->Set("func_property", v8::Number::New(1));
4284  *
4285  *    v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
4286  *    proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
4287  *    proto_t->Set("proto_const", v8::Number::New(2));
4288  *
4289  *    v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
4290  *    instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
4291  *    instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
4292  *    instance_t->Set("instance_property", Number::New(3));
4293  *
4294  *    v8::Local<v8::Function> function = t->GetFunction();
4295  *    v8::Local<v8::Object> instance = function->NewInstance();
4296  * \endcode
4297  *
4298  * Let's use "function" as the JS variable name of the function object
4299  * and "instance" for the instance object created above.  The function
4300  * and the instance will have the following properties:
4301  *
4302  * \code
4303  *   func_property in function == true;
4304  *   function.func_property == 1;
4305  *
4306  *   function.prototype.proto_method() invokes 'InvokeCallback'
4307  *   function.prototype.proto_const == 2;
4308  *
4309  *   instance instanceof function == true;
4310  *   instance.instance_accessor calls 'InstanceAccessorCallback'
4311  *   instance.instance_property == 3;
4312  * \endcode
4313  *
4314  * A FunctionTemplate can inherit from another one by calling the
4315  * FunctionTemplate::Inherit method.  The following graph illustrates
4316  * the semantics of inheritance:
4317  *
4318  * \code
4319  *   FunctionTemplate Parent  -> Parent() . prototype -> { }
4320  *     ^                                                  ^
4321  *     | Inherit(Parent)                                  | .__proto__
4322  *     |                                                  |
4323  *   FunctionTemplate Child   -> Child()  . prototype -> { }
4324  * \endcode
4325  *
4326  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
4327  * object of the Child() function has __proto__ pointing to the
4328  * Parent() function's prototype object. An instance of the Child
4329  * function has all properties on Parent's instance templates.
4330  *
4331  * Let Parent be the FunctionTemplate initialized in the previous
4332  * section and create a Child FunctionTemplate by:
4333  *
4334  * \code
4335  *   Local<FunctionTemplate> parent = t;
4336  *   Local<FunctionTemplate> child = FunctionTemplate::New();
4337  *   child->Inherit(parent);
4338  *
4339  *   Local<Function> child_function = child->GetFunction();
4340  *   Local<Object> child_instance = child_function->NewInstance();
4341  * \endcode
4342  *
4343  * The Child function and Child instance will have the following
4344  * properties:
4345  *
4346  * \code
4347  *   child_func.prototype.__proto__ == function.prototype;
4348  *   child_instance.instance_accessor calls 'InstanceAccessorCallback'
4349  *   child_instance.instance_property == 3;
4350  * \endcode
4351  */
4352 class V8_EXPORT FunctionTemplate : public Template {
4353  public:
4354   /** Creates a function template.*/
4355   static Local<FunctionTemplate> New(
4356       Isolate* isolate, FunctionCallback callback = 0,
4357       Local<Value> data = Local<Value>(),
4358       Local<Signature> signature = Local<Signature>(), int length = 0);
4359
4360   /** Returns the unique function instance in the current execution context.*/
4361   V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
4362   V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
4363       Local<Context> context);
4364
4365   /**
4366    * Set the call-handler callback for a FunctionTemplate.  This
4367    * callback is called whenever the function created from this
4368    * FunctionTemplate is called.
4369    */
4370   void SetCallHandler(FunctionCallback callback,
4371                       Local<Value> data = Local<Value>());
4372
4373   /** Set the predefined length property for the FunctionTemplate. */
4374   void SetLength(int length);
4375
4376   /** Get the InstanceTemplate. */
4377   Local<ObjectTemplate> InstanceTemplate();
4378
4379   /** Causes the function template to inherit from a parent function template.*/
4380   void Inherit(Local<FunctionTemplate> parent);
4381
4382   /**
4383    * A PrototypeTemplate is the template used to create the prototype object
4384    * of the function created by this template.
4385    */
4386   Local<ObjectTemplate> PrototypeTemplate();
4387
4388   /**
4389    * Set the class name of the FunctionTemplate.  This is used for
4390    * printing objects created with the function created from the
4391    * FunctionTemplate as its constructor.
4392    */
4393   void SetClassName(Local<String> name);
4394
4395
4396   /**
4397    * When set to true, no access check will be performed on the receiver of a
4398    * function call.  Currently defaults to true, but this is subject to change.
4399    */
4400   void SetAcceptAnyReceiver(bool value);
4401
4402   /**
4403    * Determines whether the __proto__ accessor ignores instances of
4404    * the function template.  If instances of the function template are
4405    * ignored, __proto__ skips all instances and instead returns the
4406    * next object in the prototype chain.
4407    *
4408    * Call with a value of true to make the __proto__ accessor ignore
4409    * instances of the function template.  Call with a value of false
4410    * to make the __proto__ accessor not ignore instances of the
4411    * function template.  By default, instances of a function template
4412    * are not ignored.
4413    */
4414   void SetHiddenPrototype(bool value);
4415
4416   /**
4417    * Sets the ReadOnly flag in the attributes of the 'prototype' property
4418    * of functions created from this FunctionTemplate to true.
4419    */
4420   void ReadOnlyPrototype();
4421
4422   /**
4423    * Removes the prototype property from functions created from this
4424    * FunctionTemplate.
4425    */
4426   void RemovePrototype();
4427
4428   /**
4429    * Returns true if the given object is an instance of this function
4430    * template.
4431    */
4432   bool HasInstance(Local<Value> object);
4433
4434  private:
4435   FunctionTemplate();
4436   friend class Context;
4437   friend class ObjectTemplate;
4438 };
4439
4440
4441 enum class PropertyHandlerFlags {
4442   kNone = 0,
4443   // See ALL_CAN_READ above.
4444   kAllCanRead = 1,
4445   // Will not call into interceptor for properties on the receiver or prototype
4446   // chain.  Currently only valid for named interceptors.
4447   kNonMasking = 1 << 1,
4448   // Will not call into interceptor for symbol lookup.  Only meaningful for
4449   // named interceptors.
4450   kOnlyInterceptStrings = 1 << 2,
4451 };
4452
4453
4454 struct NamedPropertyHandlerConfiguration {
4455   NamedPropertyHandlerConfiguration(
4456       /** Note: getter is required **/
4457       GenericNamedPropertyGetterCallback getter = 0,
4458       GenericNamedPropertySetterCallback setter = 0,
4459       GenericNamedPropertyQueryCallback query = 0,
4460       GenericNamedPropertyDeleterCallback deleter = 0,
4461       GenericNamedPropertyEnumeratorCallback enumerator = 0,
4462       Local<Value> data = Local<Value>(),
4463       PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4464       : getter(getter),
4465         setter(setter),
4466         query(query),
4467         deleter(deleter),
4468         enumerator(enumerator),
4469         data(data),
4470         flags(flags) {}
4471
4472   GenericNamedPropertyGetterCallback getter;
4473   GenericNamedPropertySetterCallback setter;
4474   GenericNamedPropertyQueryCallback query;
4475   GenericNamedPropertyDeleterCallback deleter;
4476   GenericNamedPropertyEnumeratorCallback enumerator;
4477   Local<Value> data;
4478   PropertyHandlerFlags flags;
4479 };
4480
4481
4482 struct IndexedPropertyHandlerConfiguration {
4483   IndexedPropertyHandlerConfiguration(
4484       /** Note: getter is required **/
4485       IndexedPropertyGetterCallback getter = 0,
4486       IndexedPropertySetterCallback setter = 0,
4487       IndexedPropertyQueryCallback query = 0,
4488       IndexedPropertyDeleterCallback deleter = 0,
4489       IndexedPropertyEnumeratorCallback enumerator = 0,
4490       Local<Value> data = Local<Value>(),
4491       PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4492       : getter(getter),
4493         setter(setter),
4494         query(query),
4495         deleter(deleter),
4496         enumerator(enumerator),
4497         data(data),
4498         flags(flags) {}
4499
4500   IndexedPropertyGetterCallback getter;
4501   IndexedPropertySetterCallback setter;
4502   IndexedPropertyQueryCallback query;
4503   IndexedPropertyDeleterCallback deleter;
4504   IndexedPropertyEnumeratorCallback enumerator;
4505   Local<Value> data;
4506   PropertyHandlerFlags flags;
4507 };
4508
4509
4510 /**
4511  * An ObjectTemplate is used to create objects at runtime.
4512  *
4513  * Properties added to an ObjectTemplate are added to each object
4514  * created from the ObjectTemplate.
4515  */
4516 class V8_EXPORT ObjectTemplate : public Template {
4517  public:
4518   /** Creates an ObjectTemplate. */
4519   static Local<ObjectTemplate> New(
4520       Isolate* isolate,
4521       Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
4522   static V8_DEPRECATE_SOON("Use isolate version", Local<ObjectTemplate> New());
4523
4524   /** Creates a new instance of this template.*/
4525   V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
4526   V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context);
4527
4528   /**
4529    * Sets an accessor on the object template.
4530    *
4531    * Whenever the property with the given name is accessed on objects
4532    * created from this ObjectTemplate the getter and setter callbacks
4533    * are called instead of getting and setting the property directly
4534    * on the JavaScript object.
4535    *
4536    * \param name The name of the property for which an accessor is added.
4537    * \param getter The callback to invoke when getting the property.
4538    * \param setter The callback to invoke when setting the property.
4539    * \param data A piece of data that will be passed to the getter and setter
4540    *   callbacks whenever they are invoked.
4541    * \param settings Access control settings for the accessor. This is a bit
4542    *   field consisting of one of more of
4543    *   DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4544    *   The default is to not allow cross-context access.
4545    *   ALL_CAN_READ means that all cross-context reads are allowed.
4546    *   ALL_CAN_WRITE means that all cross-context writes are allowed.
4547    *   The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4548    *   cross-context access.
4549    * \param attribute The attributes of the property for which an accessor
4550    *   is added.
4551    * \param signature The signature describes valid receivers for the accessor
4552    *   and is used to perform implicit instance checks against them. If the
4553    *   receiver is incompatible (i.e. is not an instance of the constructor as
4554    *   defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4555    *   thrown and no callback is invoked.
4556    */
4557   void SetAccessor(
4558       Local<String> name, AccessorGetterCallback getter,
4559       AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4560       AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4561       Local<AccessorSignature> signature = Local<AccessorSignature>());
4562   void SetAccessor(
4563       Local<Name> name, AccessorNameGetterCallback getter,
4564       AccessorNameSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4565       AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4566       Local<AccessorSignature> signature = Local<AccessorSignature>());
4567
4568   /**
4569    * Sets a named property handler on the object template.
4570    *
4571    * Whenever a property whose name is a string is accessed on objects created
4572    * from this object template, the provided callback is invoked instead of
4573    * accessing the property directly on the JavaScript object.
4574    *
4575    * Note that new code should use the second version that can intercept
4576    * symbol-named properties as well as string-named properties.
4577    *
4578    * \param getter The callback to invoke when getting a property.
4579    * \param setter The callback to invoke when setting a property.
4580    * \param query The callback to invoke to check if a property is present,
4581    *   and if present, get its attributes.
4582    * \param deleter The callback to invoke when deleting a property.
4583    * \param enumerator The callback to invoke to enumerate all the named
4584    *   properties of an object.
4585    * \param data A piece of data that will be passed to the callbacks
4586    *   whenever they are invoked.
4587    */
4588   // TODO(dcarney): deprecate
4589   void SetNamedPropertyHandler(NamedPropertyGetterCallback getter,
4590                                NamedPropertySetterCallback setter = 0,
4591                                NamedPropertyQueryCallback query = 0,
4592                                NamedPropertyDeleterCallback deleter = 0,
4593                                NamedPropertyEnumeratorCallback enumerator = 0,
4594                                Local<Value> data = Local<Value>());
4595   void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
4596
4597   /**
4598    * Sets an indexed property handler on the object template.
4599    *
4600    * Whenever an indexed property is accessed on objects created from
4601    * this object template, the provided callback is invoked instead of
4602    * accessing the property directly on the JavaScript object.
4603    *
4604    * \param getter The callback to invoke when getting a property.
4605    * \param setter The callback to invoke when setting a property.
4606    * \param query The callback to invoke to check if an object has a property.
4607    * \param deleter The callback to invoke when deleting a property.
4608    * \param enumerator The callback to invoke to enumerate all the indexed
4609    *   properties of an object.
4610    * \param data A piece of data that will be passed to the callbacks
4611    *   whenever they are invoked.
4612    */
4613   void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
4614   // TODO(dcarney): deprecate
4615   void SetIndexedPropertyHandler(
4616       IndexedPropertyGetterCallback getter,
4617       IndexedPropertySetterCallback setter = 0,
4618       IndexedPropertyQueryCallback query = 0,
4619       IndexedPropertyDeleterCallback deleter = 0,
4620       IndexedPropertyEnumeratorCallback enumerator = 0,
4621       Local<Value> data = Local<Value>()) {
4622     SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
4623                                                    deleter, enumerator, data));
4624   }
4625   /**
4626    * Sets the callback to be used when calling instances created from
4627    * this template as a function.  If no callback is set, instances
4628    * behave like normal JavaScript objects that cannot be called as a
4629    * function.
4630    */
4631   void SetCallAsFunctionHandler(FunctionCallback callback,
4632                                 Local<Value> data = Local<Value>());
4633
4634   /**
4635    * Mark object instances of the template as undetectable.
4636    *
4637    * In many ways, undetectable objects behave as though they are not
4638    * there.  They behave like 'undefined' in conditionals and when
4639    * printed.  However, properties can be accessed and called as on
4640    * normal objects.
4641    */
4642   void MarkAsUndetectable();
4643
4644   /**
4645    * Sets access check callbacks on the object template and enables
4646    * access checks.
4647    *
4648    * When accessing properties on instances of this object template,
4649    * the access check callback will be called to determine whether or
4650    * not to allow cross-context access to the properties.
4651    */
4652   void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
4653                                IndexedSecurityCallback indexed_handler,
4654                                Local<Value> data = Local<Value>());
4655
4656   /**
4657    * Gets the number of internal fields for objects generated from
4658    * this template.
4659    */
4660   int InternalFieldCount();
4661
4662   /**
4663    * Sets the number of internal fields for objects generated from
4664    * this template.
4665    */
4666   void SetInternalFieldCount(int value);
4667
4668  private:
4669   ObjectTemplate();
4670   static Local<ObjectTemplate> New(internal::Isolate* isolate,
4671                                    Local<FunctionTemplate> constructor);
4672   friend class FunctionTemplate;
4673 };
4674
4675
4676 /**
4677  * A Signature specifies which receiver is valid for a function.
4678  */
4679 class V8_EXPORT Signature : public Data {
4680  public:
4681   static Local<Signature> New(
4682       Isolate* isolate,
4683       Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4684
4685  private:
4686   Signature();
4687 };
4688
4689
4690 /**
4691  * An AccessorSignature specifies which receivers are valid parameters
4692  * to an accessor callback.
4693  */
4694 class V8_EXPORT AccessorSignature : public Data {
4695  public:
4696   static Local<AccessorSignature> New(
4697       Isolate* isolate,
4698       Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4699
4700  private:
4701   AccessorSignature();
4702 };
4703
4704
4705 /**
4706  * A utility for determining the type of objects based on the template
4707  * they were constructed from.
4708  */
4709 class V8_EXPORT TypeSwitch : public Data {
4710  public:
4711   static Local<TypeSwitch> New(Local<FunctionTemplate> type);
4712   static Local<TypeSwitch> New(int argc, Local<FunctionTemplate> types[]);
4713   int match(Local<Value> value);
4714
4715  private:
4716   TypeSwitch();
4717 };
4718
4719
4720 // --- Extensions ---
4721
4722 class V8_EXPORT ExternalOneByteStringResourceImpl
4723     : public String::ExternalOneByteStringResource {
4724  public:
4725   ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
4726   ExternalOneByteStringResourceImpl(const char* data, size_t length)
4727       : data_(data), length_(length) {}
4728   const char* data() const { return data_; }
4729   size_t length() const { return length_; }
4730
4731  private:
4732   const char* data_;
4733   size_t length_;
4734 };
4735
4736 /**
4737  * Ignore
4738  */
4739 class V8_EXPORT Extension {  // NOLINT
4740  public:
4741   // Note that the strings passed into this constructor must live as long
4742   // as the Extension itself.
4743   Extension(const char* name,
4744             const char* source = 0,
4745             int dep_count = 0,
4746             const char** deps = 0,
4747             int source_length = -1);
4748   virtual ~Extension() { }
4749   virtual v8::Local<v8::FunctionTemplate> GetNativeFunctionTemplate(
4750       v8::Isolate* isolate, v8::Local<v8::String> name) {
4751     return v8::Local<v8::FunctionTemplate>();
4752   }
4753
4754   const char* name() const { return name_; }
4755   size_t source_length() const { return source_length_; }
4756   const String::ExternalOneByteStringResource* source() const {
4757     return &source_; }
4758   int dependency_count() { return dep_count_; }
4759   const char** dependencies() { return deps_; }
4760   void set_auto_enable(bool value) { auto_enable_ = value; }
4761   bool auto_enable() { return auto_enable_; }
4762
4763  private:
4764   const char* name_;
4765   size_t source_length_;  // expected to initialize before source_
4766   ExternalOneByteStringResourceImpl source_;
4767   int dep_count_;
4768   const char** deps_;
4769   bool auto_enable_;
4770
4771   // Disallow copying and assigning.
4772   Extension(const Extension&);
4773   void operator=(const Extension&);
4774 };
4775
4776
4777 void V8_EXPORT RegisterExtension(Extension* extension);
4778
4779
4780 // --- Statics ---
4781
4782 V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
4783 V8_INLINE Local<Primitive> Null(Isolate* isolate);
4784 V8_INLINE Local<Boolean> True(Isolate* isolate);
4785 V8_INLINE Local<Boolean> False(Isolate* isolate);
4786
4787
4788 /**
4789  * A set of constraints that specifies the limits of the runtime's memory use.
4790  * You must set the heap size before initializing the VM - the size cannot be
4791  * adjusted after the VM is initialized.
4792  *
4793  * If you are using threads then you should hold the V8::Locker lock while
4794  * setting the stack limit and you must set a non-default stack limit separately
4795  * for each thread.
4796  */
4797 class V8_EXPORT ResourceConstraints {
4798  public:
4799   ResourceConstraints();
4800
4801   /**
4802    * Configures the constraints with reasonable default values based on the
4803    * capabilities of the current device the VM is running on.
4804    *
4805    * \param physical_memory The total amount of physical memory on the current
4806    *   device, in bytes.
4807    * \param virtual_memory_limit The amount of virtual memory on the current
4808    *   device, in bytes, or zero, if there is no limit.
4809    */
4810   void ConfigureDefaults(uint64_t physical_memory,
4811                          uint64_t virtual_memory_limit);
4812
4813   int max_semi_space_size() const { return max_semi_space_size_; }
4814   void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4815   int max_old_space_size() const { return max_old_space_size_; }
4816   void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4817   int max_executable_size() const { return max_executable_size_; }
4818   void set_max_executable_size(int value) { max_executable_size_ = value; }
4819   uint32_t* stack_limit() const { return stack_limit_; }
4820   // Sets an address beyond which the VM's stack may not grow.
4821   void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4822   size_t code_range_size() const { return code_range_size_; }
4823   void set_code_range_size(size_t value) {
4824     code_range_size_ = value;
4825   }
4826
4827  private:
4828   int max_semi_space_size_;
4829   int max_old_space_size_;
4830   int max_executable_size_;
4831   uint32_t* stack_limit_;
4832   size_t code_range_size_;
4833 };
4834
4835
4836 // --- Exceptions ---
4837
4838
4839 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4840
4841
4842 typedef void (*MessageCallback)(Local<Message> message, Local<Value> error);
4843
4844 // --- Tracing ---
4845
4846 typedef void (*LogEventCallback)(const char* name, int event);
4847
4848 /**
4849  * Create new error objects by calling the corresponding error object
4850  * constructor with the message.
4851  */
4852 class V8_EXPORT Exception {
4853  public:
4854   static Local<Value> RangeError(Local<String> message);
4855   static Local<Value> ReferenceError(Local<String> message);
4856   static Local<Value> SyntaxError(Local<String> message);
4857   static Local<Value> TypeError(Local<String> message);
4858   static Local<Value> Error(Local<String> message);
4859
4860   /**
4861    * Creates an error message for the given exception.
4862    * Will try to reconstruct the original stack trace from the exception value,
4863    * or capture the current stack trace if not available.
4864    */
4865   static Local<Message> CreateMessage(Local<Value> exception);
4866
4867   /**
4868    * Returns the original stack trace that was captured at the creation time
4869    * of a given exception, or an empty handle if not available.
4870    */
4871   static Local<StackTrace> GetStackTrace(Local<Value> exception);
4872 };
4873
4874
4875 // --- Counters Callbacks ---
4876
4877 typedef int* (*CounterLookupCallback)(const char* name);
4878
4879 typedef void* (*CreateHistogramCallback)(const char* name,
4880                                          int min,
4881                                          int max,
4882                                          size_t buckets);
4883
4884 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4885
4886 // --- Memory Allocation Callback ---
4887 enum ObjectSpace {
4888   kObjectSpaceNewSpace = 1 << 0,
4889   kObjectSpaceOldSpace = 1 << 1,
4890   kObjectSpaceCodeSpace = 1 << 2,
4891   kObjectSpaceMapSpace = 1 << 3,
4892   kObjectSpaceLoSpace = 1 << 4,
4893   kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldSpace |
4894                     kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4895                     kObjectSpaceLoSpace
4896 };
4897
4898   enum AllocationAction {
4899     kAllocationActionAllocate = 1 << 0,
4900     kAllocationActionFree = 1 << 1,
4901     kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4902   };
4903
4904 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4905                                          AllocationAction action,
4906                                          int size);
4907
4908 // --- Leave Script Callback ---
4909 typedef void (*CallCompletedCallback)();
4910
4911 // --- Promise Reject Callback ---
4912 enum PromiseRejectEvent {
4913   kPromiseRejectWithNoHandler = 0,
4914   kPromiseHandlerAddedAfterReject = 1
4915 };
4916
4917 class PromiseRejectMessage {
4918  public:
4919   PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
4920                        Local<Value> value, Local<StackTrace> stack_trace)
4921       : promise_(promise),
4922         event_(event),
4923         value_(value),
4924         stack_trace_(stack_trace) {}
4925
4926   V8_INLINE Local<Promise> GetPromise() const { return promise_; }
4927   V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4928   V8_INLINE Local<Value> GetValue() const { return value_; }
4929
4930   // DEPRECATED. Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()
4931   V8_INLINE Local<StackTrace> GetStackTrace() const { return stack_trace_; }
4932
4933  private:
4934   Local<Promise> promise_;
4935   PromiseRejectEvent event_;
4936   Local<Value> value_;
4937   Local<StackTrace> stack_trace_;
4938 };
4939
4940 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
4941
4942 // --- Microtask Callback ---
4943 typedef void (*MicrotaskCallback)(void* data);
4944
4945 // --- Failed Access Check Callback ---
4946 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4947                                           AccessType type,
4948                                           Local<Value> data);
4949
4950 // --- AllowCodeGenerationFromStrings callbacks ---
4951
4952 /**
4953  * Callback to check if code generation from strings is allowed. See
4954  * Context::AllowCodeGenerationFromStrings.
4955  */
4956 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4957
4958 // --- Garbage Collection Callbacks ---
4959
4960 /**
4961  * Applications can register callback functions which will be called before and
4962  * after certain garbage collection operations.  Allocations are not allowed in
4963  * the callback functions, you therefore cannot manipulate objects (set or
4964  * delete properties for example) since it is possible such operations will
4965  * result in the allocation of objects.
4966  */
4967 enum GCType {
4968   kGCTypeScavenge = 1 << 0,
4969   kGCTypeMarkSweepCompact = 1 << 1,
4970   kGCTypeIncrementalMarking = 1 << 2,
4971   kGCTypeProcessWeakCallbacks = 1 << 3,
4972   kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact |
4973                kGCTypeIncrementalMarking | kGCTypeProcessWeakCallbacks
4974 };
4975
4976 enum GCCallbackFlags {
4977   kNoGCCallbackFlags = 0,
4978   kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4979   kGCCallbackFlagForced = 1 << 2,
4980   kGCCallbackFlagSynchronousPhantomCallbackProcessing = 1 << 3
4981 };
4982
4983 V8_DEPRECATE_SOON("Use GCCallBack instead",
4984                   typedef void (*GCPrologueCallback)(GCType type,
4985                                                      GCCallbackFlags flags));
4986 V8_DEPRECATE_SOON("Use GCCallBack instead",
4987                   typedef void (*GCEpilogueCallback)(GCType type,
4988                                                      GCCallbackFlags flags));
4989 typedef void (*GCCallback)(GCType type, GCCallbackFlags flags);
4990
4991 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4992
4993
4994 /**
4995  * Collection of V8 heap information.
4996  *
4997  * Instances of this class can be passed to v8::V8::HeapStatistics to
4998  * get heap statistics from V8.
4999  */
5000 class V8_EXPORT HeapStatistics {
5001  public:
5002   HeapStatistics();
5003   size_t total_heap_size() { return total_heap_size_; }
5004   size_t total_heap_size_executable() { return total_heap_size_executable_; }
5005   size_t total_physical_size() { return total_physical_size_; }
5006   size_t total_available_size() { return total_available_size_; }
5007   size_t used_heap_size() { return used_heap_size_; }
5008   size_t heap_size_limit() { return heap_size_limit_; }
5009
5010  private:
5011   size_t total_heap_size_;
5012   size_t total_heap_size_executable_;
5013   size_t total_physical_size_;
5014   size_t total_available_size_;
5015   size_t used_heap_size_;
5016   size_t heap_size_limit_;
5017
5018   friend class V8;
5019   friend class Isolate;
5020 };
5021
5022
5023 class V8_EXPORT HeapSpaceStatistics {
5024  public:
5025   HeapSpaceStatistics();
5026   const char* space_name() { return space_name_; }
5027   size_t space_size() { return space_size_; }
5028   size_t space_used_size() { return space_used_size_; }
5029   size_t space_available_size() { return space_available_size_; }
5030   size_t physical_space_size() { return physical_space_size_; }
5031
5032  private:
5033   const char* space_name_;
5034   size_t space_size_;
5035   size_t space_used_size_;
5036   size_t space_available_size_;
5037   size_t physical_space_size_;
5038
5039   friend class Isolate;
5040 };
5041
5042
5043 class V8_EXPORT HeapObjectStatistics {
5044  public:
5045   HeapObjectStatistics();
5046   const char* object_type() { return object_type_; }
5047   const char* object_sub_type() { return object_sub_type_; }
5048   size_t object_count() { return object_count_; }
5049   size_t object_size() { return object_size_; }
5050
5051  private:
5052   const char* object_type_;
5053   const char* object_sub_type_;
5054   size_t object_count_;
5055   size_t object_size_;
5056
5057   friend class Isolate;
5058 };
5059
5060
5061 class RetainedObjectInfo;
5062
5063
5064 /**
5065  * FunctionEntryHook is the type of the profile entry hook called at entry to
5066  * any generated function when function-level profiling is enabled.
5067  *
5068  * \param function the address of the function that's being entered.
5069  * \param return_addr_location points to a location on stack where the machine
5070  *    return address resides. This can be used to identify the caller of
5071  *    \p function, and/or modified to divert execution when \p function exits.
5072  *
5073  * \note the entry hook must not cause garbage collection.
5074  */
5075 typedef void (*FunctionEntryHook)(uintptr_t function,
5076                                   uintptr_t return_addr_location);
5077
5078 /**
5079  * A JIT code event is issued each time code is added, moved or removed.
5080  *
5081  * \note removal events are not currently issued.
5082  */
5083 struct JitCodeEvent {
5084   enum EventType {
5085     CODE_ADDED,
5086     CODE_MOVED,
5087     CODE_REMOVED,
5088     CODE_ADD_LINE_POS_INFO,
5089     CODE_START_LINE_INFO_RECORDING,
5090     CODE_END_LINE_INFO_RECORDING
5091   };
5092   // Definition of the code position type. The "POSITION" type means the place
5093   // in the source code which are of interest when making stack traces to
5094   // pin-point the source location of a stack frame as close as possible.
5095   // The "STATEMENT_POSITION" means the place at the beginning of each
5096   // statement, and is used to indicate possible break locations.
5097   enum PositionType { POSITION, STATEMENT_POSITION };
5098
5099   // Type of event.
5100   EventType type;
5101   // Start of the instructions.
5102   void* code_start;
5103   // Size of the instructions.
5104   size_t code_len;
5105   // Script info for CODE_ADDED event.
5106   Local<UnboundScript> script;
5107   // User-defined data for *_LINE_INFO_* event. It's used to hold the source
5108   // code line information which is returned from the
5109   // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
5110   // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
5111   void* user_data;
5112
5113   struct name_t {
5114     // Name of the object associated with the code, note that the string is not
5115     // zero-terminated.
5116     const char* str;
5117     // Number of chars in str.
5118     size_t len;
5119   };
5120
5121   struct line_info_t {
5122     // PC offset
5123     size_t offset;
5124     // Code postion
5125     size_t pos;
5126     // The position type.
5127     PositionType position_type;
5128   };
5129
5130   union {
5131     // Only valid for CODE_ADDED.
5132     struct name_t name;
5133
5134     // Only valid for CODE_ADD_LINE_POS_INFO
5135     struct line_info_t line_info;
5136
5137     // New location of instructions. Only valid for CODE_MOVED.
5138     void* new_code_start;
5139   };
5140 };
5141
5142 /**
5143  * Option flags passed to the SetJitCodeEventHandler function.
5144  */
5145 enum JitCodeEventOptions {
5146   kJitCodeEventDefault = 0,
5147   // Generate callbacks for already existent code.
5148   kJitCodeEventEnumExisting = 1
5149 };
5150
5151
5152 /**
5153  * Callback function passed to SetJitCodeEventHandler.
5154  *
5155  * \param event code add, move or removal event.
5156  */
5157 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
5158
5159
5160 /**
5161  * Interface for iterating through all external resources in the heap.
5162  */
5163 class V8_EXPORT ExternalResourceVisitor {  // NOLINT
5164  public:
5165   virtual ~ExternalResourceVisitor() {}
5166   virtual void VisitExternalString(Local<String> string) {}
5167 };
5168
5169
5170 /**
5171  * Interface for iterating through all the persistent handles in the heap.
5172  */
5173 class V8_EXPORT PersistentHandleVisitor {  // NOLINT
5174  public:
5175   virtual ~PersistentHandleVisitor() {}
5176   virtual void VisitPersistentHandle(Persistent<Value>* value,
5177                                      uint16_t class_id) {}
5178 };
5179
5180
5181 /**
5182  * Isolate represents an isolated instance of the V8 engine.  V8 isolates have
5183  * completely separate states.  Objects from one isolate must not be used in
5184  * other isolates.  The embedder can create multiple isolates and use them in
5185  * parallel in multiple threads.  An isolate can be entered by at most one
5186  * thread at any given time.  The Locker/Unlocker API must be used to
5187  * synchronize.
5188  */
5189 class V8_EXPORT Isolate {
5190  public:
5191   /**
5192    * Initial configuration parameters for a new Isolate.
5193    */
5194   struct CreateParams {
5195     CreateParams()
5196         : entry_hook(NULL),
5197           code_event_handler(NULL),
5198           snapshot_blob(NULL),
5199           counter_lookup_callback(NULL),
5200           create_histogram_callback(NULL),
5201           add_histogram_sample_callback(NULL),
5202           array_buffer_allocator(NULL) {}
5203
5204     /**
5205      * The optional entry_hook allows the host application to provide the
5206      * address of a function that's invoked on entry to every V8-generated
5207      * function.  Note that entry_hook is invoked at the very start of each
5208      * generated function. Furthermore, if an  entry_hook is given, V8 will
5209      * always run without a context snapshot.
5210      */
5211     FunctionEntryHook entry_hook;
5212
5213     /**
5214      * Allows the host application to provide the address of a function that is
5215      * notified each time code is added, moved or removed.
5216      */
5217     JitCodeEventHandler code_event_handler;
5218
5219     /**
5220      * ResourceConstraints to use for the new Isolate.
5221      */
5222     ResourceConstraints constraints;
5223
5224     /**
5225      * Explicitly specify a startup snapshot blob. The embedder owns the blob.
5226      */
5227     StartupData* snapshot_blob;
5228
5229
5230     /**
5231      * Enables the host application to provide a mechanism for recording
5232      * statistics counters.
5233      */
5234     CounterLookupCallback counter_lookup_callback;
5235
5236     /**
5237      * Enables the host application to provide a mechanism for recording
5238      * histograms. The CreateHistogram function returns a
5239      * histogram which will later be passed to the AddHistogramSample
5240      * function.
5241      */
5242     CreateHistogramCallback create_histogram_callback;
5243     AddHistogramSampleCallback add_histogram_sample_callback;
5244
5245     /**
5246      * The ArrayBuffer::Allocator to use for allocating and freeing the backing
5247      * store of ArrayBuffers.
5248      */
5249     ArrayBuffer::Allocator* array_buffer_allocator;
5250   };
5251
5252
5253   /**
5254    * Stack-allocated class which sets the isolate for all operations
5255    * executed within a local scope.
5256    */
5257   class V8_EXPORT Scope {
5258    public:
5259     explicit Scope(Isolate* isolate) : isolate_(isolate) {
5260       isolate->Enter();
5261     }
5262
5263     ~Scope() { isolate_->Exit(); }
5264
5265    private:
5266     Isolate* const isolate_;
5267
5268     // Prevent copying of Scope objects.
5269     Scope(const Scope&);
5270     Scope& operator=(const Scope&);
5271   };
5272
5273
5274   /**
5275    * Assert that no Javascript code is invoked.
5276    */
5277   class V8_EXPORT DisallowJavascriptExecutionScope {
5278    public:
5279     enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
5280
5281     DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
5282     ~DisallowJavascriptExecutionScope();
5283
5284    private:
5285     bool on_failure_;
5286     void* internal_;
5287
5288     // Prevent copying of Scope objects.
5289     DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
5290     DisallowJavascriptExecutionScope& operator=(
5291         const DisallowJavascriptExecutionScope&);
5292   };
5293
5294
5295   /**
5296    * Introduce exception to DisallowJavascriptExecutionScope.
5297    */
5298   class V8_EXPORT AllowJavascriptExecutionScope {
5299    public:
5300     explicit AllowJavascriptExecutionScope(Isolate* isolate);
5301     ~AllowJavascriptExecutionScope();
5302
5303    private:
5304     void* internal_throws_;
5305     void* internal_assert_;
5306
5307     // Prevent copying of Scope objects.
5308     AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
5309     AllowJavascriptExecutionScope& operator=(
5310         const AllowJavascriptExecutionScope&);
5311   };
5312
5313   /**
5314    * Do not run microtasks while this scope is active, even if microtasks are
5315    * automatically executed otherwise.
5316    */
5317   class V8_EXPORT SuppressMicrotaskExecutionScope {
5318    public:
5319     explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
5320     ~SuppressMicrotaskExecutionScope();
5321
5322    private:
5323     internal::Isolate* isolate_;
5324
5325     // Prevent copying of Scope objects.
5326     SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
5327     SuppressMicrotaskExecutionScope& operator=(
5328         const SuppressMicrotaskExecutionScope&);
5329   };
5330
5331   /**
5332    * Types of garbage collections that can be requested via
5333    * RequestGarbageCollectionForTesting.
5334    */
5335   enum GarbageCollectionType {
5336     kFullGarbageCollection,
5337     kMinorGarbageCollection
5338   };
5339
5340   /**
5341    * Features reported via the SetUseCounterCallback callback. Do not change
5342    * assigned numbers of existing items; add new features to the end of this
5343    * list.
5344    */
5345   enum UseCounterFeature {
5346     kUseAsm = 0,
5347     kBreakIterator = 1,
5348     kLegacyConst = 2,
5349     kMarkDequeOverflow = 3,
5350     kStoreBufferOverflow = 4,
5351     kSlotsBufferOverflow = 5,
5352     kObjectObserve = 6,
5353     kForcedGC = 7,
5354     kUseCounterFeatureCount  // This enum value must be last.
5355   };
5356
5357   typedef void (*UseCounterCallback)(Isolate* isolate,
5358                                      UseCounterFeature feature);
5359
5360
5361   /**
5362    * Creates a new isolate.  Does not change the currently entered
5363    * isolate.
5364    *
5365    * When an isolate is no longer used its resources should be freed
5366    * by calling Dispose().  Using the delete operator is not allowed.
5367    *
5368    * V8::Initialize() must have run prior to this.
5369    */
5370   static Isolate* New(const CreateParams& params);
5371
5372   /**
5373    * Returns the entered isolate for the current thread or NULL in
5374    * case there is no current isolate.
5375    *
5376    * This method must not be invoked before V8::Initialize() was invoked.
5377    */
5378   static Isolate* GetCurrent();
5379
5380   /**
5381    * Methods below this point require holding a lock (using Locker) in
5382    * a multi-threaded environment.
5383    */
5384
5385   /**
5386    * Sets this isolate as the entered one for the current thread.
5387    * Saves the previously entered one (if any), so that it can be
5388    * restored when exiting.  Re-entering an isolate is allowed.
5389    */
5390   void Enter();
5391
5392   /**
5393    * Exits this isolate by restoring the previously entered one in the
5394    * current thread.  The isolate may still stay the same, if it was
5395    * entered more than once.
5396    *
5397    * Requires: this == Isolate::GetCurrent().
5398    */
5399   void Exit();
5400
5401   /**
5402    * Disposes the isolate.  The isolate must not be entered by any
5403    * thread to be disposable.
5404    */
5405   void Dispose();
5406
5407   /**
5408    * Associate embedder-specific data with the isolate. |slot| has to be
5409    * between 0 and GetNumberOfDataSlots() - 1.
5410    */
5411   V8_INLINE void SetData(uint32_t slot, void* data);
5412
5413   /**
5414    * Retrieve embedder-specific data from the isolate.
5415    * Returns NULL if SetData has never been called for the given |slot|.
5416    */
5417   V8_INLINE void* GetData(uint32_t slot);
5418
5419   /**
5420    * Returns the maximum number of available embedder data slots. Valid slots
5421    * are in the range of 0 - GetNumberOfDataSlots() - 1.
5422    */
5423   V8_INLINE static uint32_t GetNumberOfDataSlots();
5424
5425   /**
5426    * Get statistics about the heap memory usage.
5427    */
5428   void GetHeapStatistics(HeapStatistics* heap_statistics);
5429
5430   /**
5431    * Returns the number of spaces in the heap.
5432    */
5433   size_t NumberOfHeapSpaces();
5434
5435   /**
5436    * Get the memory usage of a space in the heap.
5437    *
5438    * \param space_statistics The HeapSpaceStatistics object to fill in
5439    *   statistics.
5440    * \param index The index of the space to get statistics from, which ranges
5441    *   from 0 to NumberOfHeapSpaces() - 1.
5442    * \returns true on success.
5443    */
5444   bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
5445                               size_t index);
5446
5447   /**
5448    * Returns the number of types of objects tracked in the heap at GC.
5449    */
5450   size_t NumberOfTrackedHeapObjectTypes();
5451
5452   /**
5453    * Get statistics about objects in the heap.
5454    *
5455    * \param object_statistics The HeapObjectStatistics object to fill in
5456    *   statistics of objects of given type, which were live in the previous GC.
5457    * \param type_index The index of the type of object to fill details about,
5458    *   which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
5459    * \returns true on success.
5460    */
5461   bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
5462                                        size_t type_index);
5463
5464   /**
5465    * Get a call stack sample from the isolate.
5466    * \param state Execution state.
5467    * \param frames Caller allocated buffer to store stack frames.
5468    * \param frames_limit Maximum number of frames to capture. The buffer must
5469    *                     be large enough to hold the number of frames.
5470    * \param sample_info The sample info is filled up by the function
5471    *                    provides number of actual captured stack frames and
5472    *                    the current VM state.
5473    * \note GetStackSample should only be called when the JS thread is paused or
5474    *       interrupted. Otherwise the behavior is undefined.
5475    */
5476   void GetStackSample(const RegisterState& state, void** frames,
5477                       size_t frames_limit, SampleInfo* sample_info);
5478
5479   /**
5480    * Adjusts the amount of registered external memory. Used to give V8 an
5481    * indication of the amount of externally allocated memory that is kept alive
5482    * by JavaScript objects. V8 uses this to decide when to perform global
5483    * garbage collections. Registering externally allocated memory will trigger
5484    * global garbage collections more often than it would otherwise in an attempt
5485    * to garbage collect the JavaScript objects that keep the externally
5486    * allocated memory alive.
5487    *
5488    * \param change_in_bytes the change in externally allocated memory that is
5489    *   kept alive by JavaScript objects.
5490    * \returns the adjusted value.
5491    */
5492   V8_INLINE int64_t
5493       AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
5494
5495   /**
5496    * Returns heap profiler for this isolate. Will return NULL until the isolate
5497    * is initialized.
5498    */
5499   HeapProfiler* GetHeapProfiler();
5500
5501   /**
5502    * Returns CPU profiler for this isolate. Will return NULL unless the isolate
5503    * is initialized. It is the embedder's responsibility to stop all CPU
5504    * profiling activities if it has started any.
5505    */
5506   CpuProfiler* GetCpuProfiler();
5507
5508   /** Returns true if this isolate has a current context. */
5509   bool InContext();
5510
5511   /** Returns the context that is on the top of the stack. */
5512   Local<Context> GetCurrentContext();
5513
5514   /**
5515    * Returns the context of the calling JavaScript code.  That is the
5516    * context of the top-most JavaScript frame.  If there are no
5517    * JavaScript frames an empty handle is returned.
5518    */
5519   Local<Context> GetCallingContext();
5520
5521   /** Returns the last entered context. */
5522   Local<Context> GetEnteredContext();
5523
5524   /**
5525    * Schedules an exception to be thrown when returning to JavaScript.  When an
5526    * exception has been scheduled it is illegal to invoke any JavaScript
5527    * operation; the caller must return immediately and only after the exception
5528    * has been handled does it become legal to invoke JavaScript operations.
5529    */
5530   Local<Value> ThrowException(Local<Value> exception);
5531
5532   /**
5533    * Allows the host application to group objects together. If one
5534    * object in the group is alive, all objects in the group are alive.
5535    * After each garbage collection, object groups are removed. It is
5536    * intended to be used in the before-garbage-collection callback
5537    * function, for instance to simulate DOM tree connections among JS
5538    * wrapper objects. Object groups for all dependent handles need to
5539    * be provided for kGCTypeMarkSweepCompact collections, for all other
5540    * garbage collection types it is sufficient to provide object groups
5541    * for partially dependent handles only.
5542    */
5543   template<typename T> void SetObjectGroupId(const Persistent<T>& object,
5544                                              UniqueId id);
5545
5546   /**
5547    * Allows the host application to declare implicit references from an object
5548    * group to an object. If the objects of the object group are alive, the child
5549    * object is alive too. After each garbage collection, all implicit references
5550    * are removed. It is intended to be used in the before-garbage-collection
5551    * callback function.
5552    */
5553   template<typename T> void SetReferenceFromGroup(UniqueId id,
5554                                                   const Persistent<T>& child);
5555
5556   /**
5557    * Allows the host application to declare implicit references from an object
5558    * to another object. If the parent object is alive, the child object is alive
5559    * too. After each garbage collection, all implicit references are removed. It
5560    * is intended to be used in the before-garbage-collection callback function.
5561    */
5562   template<typename T, typename S>
5563   void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
5564
5565   V8_DEPRECATE_SOON("Use GCCallBack instead",
5566                     typedef void (*GCPrologueCallback)(Isolate* isolate,
5567                                                        GCType type,
5568                                                        GCCallbackFlags flags));
5569   V8_DEPRECATE_SOON("Use GCCallBack instead",
5570                     typedef void (*GCEpilogueCallback)(Isolate* isolate,
5571                                                        GCType type,
5572                                                        GCCallbackFlags flags));
5573   typedef void (*GCCallback)(Isolate* isolate, GCType type,
5574                              GCCallbackFlags flags);
5575
5576   /**
5577    * Enables the host application to receive a notification before a
5578    * garbage collection. Allocations are allowed in the callback function,
5579    * but the callback is not re-entrant: if the allocation inside it will
5580    * trigger the garbage collection, the callback won't be called again.
5581    * It is possible to specify the GCType filter for your callback. But it is
5582    * not possible to register the same callback function two times with
5583    * different GCType filters.
5584    */
5585   void AddGCPrologueCallback(GCCallback callback,
5586                              GCType gc_type_filter = kGCTypeAll);
5587
5588   /**
5589    * This function removes callback which was installed by
5590    * AddGCPrologueCallback function.
5591    */
5592   void RemoveGCPrologueCallback(GCCallback callback);
5593
5594   /**
5595    * Enables the host application to receive a notification after a
5596    * garbage collection. Allocations are allowed in the callback function,
5597    * but the callback is not re-entrant: if the allocation inside it will
5598    * trigger the garbage collection, the callback won't be called again.
5599    * It is possible to specify the GCType filter for your callback. But it is
5600    * not possible to register the same callback function two times with
5601    * different GCType filters.
5602    */
5603   void AddGCEpilogueCallback(GCCallback callback,
5604                              GCType gc_type_filter = kGCTypeAll);
5605
5606   /**
5607    * This function removes callback which was installed by
5608    * AddGCEpilogueCallback function.
5609    */
5610   void RemoveGCEpilogueCallback(GCCallback callback);
5611
5612   /**
5613    * Forcefully terminate the current thread of JavaScript execution
5614    * in the given isolate.
5615    *
5616    * This method can be used by any thread even if that thread has not
5617    * acquired the V8 lock with a Locker object.
5618    */
5619   void TerminateExecution();
5620
5621   /**
5622    * Is V8 terminating JavaScript execution.
5623    *
5624    * Returns true if JavaScript execution is currently terminating
5625    * because of a call to TerminateExecution.  In that case there are
5626    * still JavaScript frames on the stack and the termination
5627    * exception is still active.
5628    */
5629   bool IsExecutionTerminating();
5630
5631   /**
5632    * Resume execution capability in the given isolate, whose execution
5633    * was previously forcefully terminated using TerminateExecution().
5634    *
5635    * When execution is forcefully terminated using TerminateExecution(),
5636    * the isolate can not resume execution until all JavaScript frames
5637    * have propagated the uncatchable exception which is generated.  This
5638    * method allows the program embedding the engine to handle the
5639    * termination event and resume execution capability, even if
5640    * JavaScript frames remain on the stack.
5641    *
5642    * This method can be used by any thread even if that thread has not
5643    * acquired the V8 lock with a Locker object.
5644    */
5645   void CancelTerminateExecution();
5646
5647   /**
5648    * Request V8 to interrupt long running JavaScript code and invoke
5649    * the given |callback| passing the given |data| to it. After |callback|
5650    * returns control will be returned to the JavaScript code.
5651    * There may be a number of interrupt requests in flight.
5652    * Can be called from another thread without acquiring a |Locker|.
5653    * Registered |callback| must not reenter interrupted Isolate.
5654    */
5655   void RequestInterrupt(InterruptCallback callback, void* data);
5656
5657   /**
5658    * Request garbage collection in this Isolate. It is only valid to call this
5659    * function if --expose_gc was specified.
5660    *
5661    * This should only be used for testing purposes and not to enforce a garbage
5662    * collection schedule. It has strong negative impact on the garbage
5663    * collection performance. Use IdleNotificationDeadline() or
5664    * LowMemoryNotification() instead to influence the garbage collection
5665    * schedule.
5666    */
5667   void RequestGarbageCollectionForTesting(GarbageCollectionType type);
5668
5669   /**
5670    * Set the callback to invoke for logging event.
5671    */
5672   void SetEventLogger(LogEventCallback that);
5673
5674   /**
5675    * Adds a callback to notify the host application when a script finished
5676    * running.  If a script re-enters the runtime during executing, the
5677    * CallCompletedCallback is only invoked when the outer-most script
5678    * execution ends.  Executing scripts inside the callback do not trigger
5679    * further callbacks.
5680    */
5681   void AddCallCompletedCallback(CallCompletedCallback callback);
5682
5683   /**
5684    * Removes callback that was installed by AddCallCompletedCallback.
5685    */
5686   void RemoveCallCompletedCallback(CallCompletedCallback callback);
5687
5688
5689   /**
5690    * Set callback to notify about promise reject with no handler, or
5691    * revocation of such a previous notification once the handler is added.
5692    */
5693   void SetPromiseRejectCallback(PromiseRejectCallback callback);
5694
5695   /**
5696    * Experimental: Runs the Microtask Work Queue until empty
5697    * Any exceptions thrown by microtask callbacks are swallowed.
5698    */
5699   void RunMicrotasks();
5700
5701   /**
5702    * Experimental: Enqueues the callback to the Microtask Work Queue
5703    */
5704   void EnqueueMicrotask(Local<Function> microtask);
5705
5706   /**
5707    * Experimental: Enqueues the callback to the Microtask Work Queue
5708    */
5709   void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
5710
5711    /**
5712    * Experimental: Controls whether the Microtask Work Queue is automatically
5713    * run when the script call depth decrements to zero.
5714    */
5715   void SetAutorunMicrotasks(bool autorun);
5716
5717   /**
5718    * Experimental: Returns whether the Microtask Work Queue is automatically
5719    * run when the script call depth decrements to zero.
5720    */
5721   bool WillAutorunMicrotasks() const;
5722
5723   /**
5724    * Sets a callback for counting the number of times a feature of V8 is used.
5725    */
5726   void SetUseCounterCallback(UseCounterCallback callback);
5727
5728   /**
5729    * Enables the host application to provide a mechanism for recording
5730    * statistics counters.
5731    */
5732   void SetCounterFunction(CounterLookupCallback);
5733
5734   /**
5735    * Enables the host application to provide a mechanism for recording
5736    * histograms. The CreateHistogram function returns a
5737    * histogram which will later be passed to the AddHistogramSample
5738    * function.
5739    */
5740   void SetCreateHistogramFunction(CreateHistogramCallback);
5741   void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
5742
5743   /**
5744    * Optional notification that the embedder is idle.
5745    * V8 uses the notification to perform garbage collection.
5746    * This call can be used repeatedly if the embedder remains idle.
5747    * Returns true if the embedder should stop calling IdleNotificationDeadline
5748    * until real work has been done.  This indicates that V8 has done
5749    * as much cleanup as it will be able to do.
5750    *
5751    * The deadline_in_seconds argument specifies the deadline V8 has to finish
5752    * garbage collection work. deadline_in_seconds is compared with
5753    * MonotonicallyIncreasingTime() and should be based on the same timebase as
5754    * that function. There is no guarantee that the actual work will be done
5755    * within the time limit.
5756    */
5757   bool IdleNotificationDeadline(double deadline_in_seconds);
5758
5759   V8_DEPRECATE_SOON("use IdleNotificationDeadline()",
5760                     bool IdleNotification(int idle_time_in_ms));
5761
5762   /**
5763    * Optional notification that the system is running low on memory.
5764    * V8 uses these notifications to attempt to free memory.
5765    */
5766   void LowMemoryNotification();
5767
5768   /**
5769    * Optional notification that a context has been disposed. V8 uses
5770    * these notifications to guide the GC heuristic. Returns the number
5771    * of context disposals - including this one - since the last time
5772    * V8 had a chance to clean up.
5773    *
5774    * The optional parameter |dependant_context| specifies whether the disposed
5775    * context was depending on state from other contexts or not.
5776    */
5777   int ContextDisposedNotification(bool dependant_context = true);
5778
5779   /**
5780    * Allows the host application to provide the address of a function that is
5781    * notified each time code is added, moved or removed.
5782    *
5783    * \param options options for the JIT code event handler.
5784    * \param event_handler the JIT code event handler, which will be invoked
5785    *     each time code is added, moved or removed.
5786    * \note \p event_handler won't get notified of existent code.
5787    * \note since code removal notifications are not currently issued, the
5788    *     \p event_handler may get notifications of code that overlaps earlier
5789    *     code notifications. This happens when code areas are reused, and the
5790    *     earlier overlapping code areas should therefore be discarded.
5791    * \note the events passed to \p event_handler and the strings they point to
5792    *     are not guaranteed to live past each call. The \p event_handler must
5793    *     copy strings and other parameters it needs to keep around.
5794    * \note the set of events declared in JitCodeEvent::EventType is expected to
5795    *     grow over time, and the JitCodeEvent structure is expected to accrue
5796    *     new members. The \p event_handler function must ignore event codes
5797    *     it does not recognize to maintain future compatibility.
5798    * \note Use Isolate::CreateParams to get events for code executed during
5799    *     Isolate setup.
5800    */
5801   void SetJitCodeEventHandler(JitCodeEventOptions options,
5802                               JitCodeEventHandler event_handler);
5803
5804   /**
5805    * Modifies the stack limit for this Isolate.
5806    *
5807    * \param stack_limit An address beyond which the Vm's stack may not grow.
5808    *
5809    * \note  If you are using threads then you should hold the V8::Locker lock
5810    *     while setting the stack limit and you must set a non-default stack
5811    *     limit separately for each thread.
5812    */
5813   void SetStackLimit(uintptr_t stack_limit);
5814
5815   /**
5816    * Returns a memory range that can potentially contain jitted code.
5817    *
5818    * On Win64, embedders are advised to install function table callbacks for
5819    * these ranges, as default SEH won't be able to unwind through jitted code.
5820    *
5821    * The first page of the code range is reserved for the embedder and is
5822    * committed, writable, and executable.
5823    *
5824    * Might be empty on other platforms.
5825    *
5826    * https://code.google.com/p/v8/issues/detail?id=3598
5827    */
5828   void GetCodeRange(void** start, size_t* length_in_bytes);
5829
5830   /** Set the callback to invoke in case of fatal errors. */
5831   void SetFatalErrorHandler(FatalErrorCallback that);
5832
5833   /**
5834    * Set the callback to invoke to check if code generation from
5835    * strings should be allowed.
5836    */
5837   void SetAllowCodeGenerationFromStringsCallback(
5838       AllowCodeGenerationFromStringsCallback callback);
5839
5840   /**
5841   * Check if V8 is dead and therefore unusable.  This is the case after
5842   * fatal errors such as out-of-memory situations.
5843   */
5844   bool IsDead();
5845
5846   /**
5847    * Adds a message listener.
5848    *
5849    * The same message listener can be added more than once and in that
5850    * case it will be called more than once for each message.
5851    *
5852    * If data is specified, it will be passed to the callback when it is called.
5853    * Otherwise, the exception object will be passed to the callback instead.
5854    */
5855   bool AddMessageListener(MessageCallback that,
5856                           Local<Value> data = Local<Value>());
5857
5858   /**
5859    * Remove all message listeners from the specified callback function.
5860    */
5861   void RemoveMessageListeners(MessageCallback that);
5862
5863   /** Callback function for reporting failed access checks.*/
5864   void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5865
5866   /**
5867    * Tells V8 to capture current stack trace when uncaught exception occurs
5868    * and report it to the message listeners. The option is off by default.
5869    */
5870   void SetCaptureStackTraceForUncaughtExceptions(
5871       bool capture, int frame_limit = 10,
5872       StackTrace::StackTraceOptions options = StackTrace::kOverview);
5873
5874   /**
5875    * Enables the host application to provide a mechanism to be notified
5876    * and perform custom logging when V8 Allocates Executable Memory.
5877    */
5878   void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5879                                    ObjectSpace space, AllocationAction action);
5880
5881   /**
5882    * Removes callback that was installed by AddMemoryAllocationCallback.
5883    */
5884   void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5885
5886   /**
5887    * Iterates through all external resources referenced from current isolate
5888    * heap.  GC is not invoked prior to iterating, therefore there is no
5889    * guarantee that visited objects are still alive.
5890    */
5891   void VisitExternalResources(ExternalResourceVisitor* visitor);
5892
5893   /**
5894    * Iterates through all the persistent handles in the current isolate's heap
5895    * that have class_ids.
5896    */
5897   void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5898
5899   /**
5900    * Iterates through all the persistent handles in the current isolate's heap
5901    * that have class_ids and are candidates to be marked as partially dependent
5902    * handles. This will visit handles to young objects created since the last
5903    * garbage collection but is free to visit an arbitrary superset of these
5904    * objects.
5905    */
5906   void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
5907
5908  private:
5909   template <class K, class V, class Traits>
5910   friend class PersistentValueMapBase;
5911
5912   Isolate();
5913   Isolate(const Isolate&);
5914   ~Isolate();
5915   Isolate& operator=(const Isolate&);
5916   void* operator new(size_t size);
5917   void operator delete(void*, size_t);
5918
5919   void SetObjectGroupId(internal::Object** object, UniqueId id);
5920   void SetReferenceFromGroup(UniqueId id, internal::Object** object);
5921   void SetReference(internal::Object** parent, internal::Object** child);
5922   void ReportExternalAllocationLimitReached();
5923 };
5924
5925 class V8_EXPORT StartupData {
5926  public:
5927   const char* data;
5928   int raw_size;
5929 };
5930
5931
5932 /**
5933  * EntropySource is used as a callback function when v8 needs a source
5934  * of entropy.
5935  */
5936 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
5937
5938
5939 /**
5940  * ReturnAddressLocationResolver is used as a callback function when v8 is
5941  * resolving the location of a return address on the stack. Profilers that
5942  * change the return address on the stack can use this to resolve the stack
5943  * location to whereever the profiler stashed the original return address.
5944  *
5945  * \param return_addr_location points to a location on stack where a machine
5946  *    return address resides.
5947  * \returns either return_addr_location, or else a pointer to the profiler's
5948  *    copy of the original return address.
5949  *
5950  * \note the resolver function must not cause garbage collection.
5951  */
5952 typedef uintptr_t (*ReturnAddressLocationResolver)(
5953     uintptr_t return_addr_location);
5954
5955
5956 /**
5957  * Container class for static utility functions.
5958  */
5959 class V8_EXPORT V8 {
5960  public:
5961   /** Set the callback to invoke in case of fatal errors. */
5962   V8_INLINE static V8_DEPRECATE_SOON(
5963       "Use isolate version",
5964       void SetFatalErrorHandler(FatalErrorCallback that));
5965
5966   /**
5967    * Set the callback to invoke to check if code generation from
5968    * strings should be allowed.
5969    */
5970   V8_INLINE static V8_DEPRECATE_SOON(
5971       "Use isolate version", void SetAllowCodeGenerationFromStringsCallback(
5972                                  AllowCodeGenerationFromStringsCallback that));
5973
5974   /**
5975   * Check if V8 is dead and therefore unusable.  This is the case after
5976   * fatal errors such as out-of-memory situations.
5977   */
5978   V8_INLINE static V8_DEPRECATE_SOON("no alternative", bool IsDead());
5979
5980   /**
5981    * Hand startup data to V8, in case the embedder has chosen to build
5982    * V8 with external startup data.
5983    *
5984    * Note:
5985    * - By default the startup data is linked into the V8 library, in which
5986    *   case this function is not meaningful.
5987    * - If this needs to be called, it needs to be called before V8
5988    *   tries to make use of its built-ins.
5989    * - To avoid unnecessary copies of data, V8 will point directly into the
5990    *   given data blob, so pretty please keep it around until V8 exit.
5991    * - Compression of the startup blob might be useful, but needs to
5992    *   handled entirely on the embedders' side.
5993    * - The call will abort if the data is invalid.
5994    */
5995   static void SetNativesDataBlob(StartupData* startup_blob);
5996   static void SetSnapshotDataBlob(StartupData* startup_blob);
5997
5998   /**
5999    * Create a new isolate and context for the purpose of capturing a snapshot
6000    * Returns { NULL, 0 } on failure.
6001    * The caller owns the data array in the return value.
6002    */
6003   static StartupData CreateSnapshotDataBlob(const char* custom_source = NULL);
6004
6005   /**
6006    * Adds a message listener.
6007    *
6008    * The same message listener can be added more than once and in that
6009    * case it will be called more than once for each message.
6010    *
6011    * If data is specified, it will be passed to the callback when it is called.
6012    * Otherwise, the exception object will be passed to the callback instead.
6013    */
6014   V8_INLINE static V8_DEPRECATE_SOON(
6015       "Use isolate version",
6016       bool AddMessageListener(MessageCallback that,
6017                               Local<Value> data = Local<Value>()));
6018
6019   /**
6020    * Remove all message listeners from the specified callback function.
6021    */
6022   V8_INLINE static V8_DEPRECATE_SOON(
6023       "Use isolate version", void RemoveMessageListeners(MessageCallback that));
6024
6025   /**
6026    * Tells V8 to capture current stack trace when uncaught exception occurs
6027    * and report it to the message listeners. The option is off by default.
6028    */
6029   V8_INLINE static V8_DEPRECATE_SOON(
6030       "Use isolate version",
6031       void SetCaptureStackTraceForUncaughtExceptions(
6032           bool capture, int frame_limit = 10,
6033           StackTrace::StackTraceOptions options = StackTrace::kOverview));
6034
6035   /**
6036    * Sets V8 flags from a string.
6037    */
6038   static void SetFlagsFromString(const char* str, int length);
6039
6040   /**
6041    * Sets V8 flags from the command line.
6042    */
6043   static void SetFlagsFromCommandLine(int* argc,
6044                                       char** argv,
6045                                       bool remove_flags);
6046
6047   /** Get the version string. */
6048   static const char* GetVersion();
6049
6050   /** Callback function for reporting failed access checks.*/
6051   V8_INLINE static V8_DEPRECATE_SOON(
6052       "Use isolate version",
6053       void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback));
6054
6055   /**
6056    * Enables the host application to receive a notification before a
6057    * garbage collection.  Allocations are not allowed in the
6058    * callback function, you therefore cannot manipulate objects (set
6059    * or delete properties for example) since it is possible such
6060    * operations will result in the allocation of objects. It is possible
6061    * to specify the GCType filter for your callback. But it is not possible to
6062    * register the same callback function two times with different
6063    * GCType filters.
6064    */
6065   static V8_DEPRECATE_SOON(
6066       "Use isolate version",
6067       void AddGCPrologueCallback(GCCallback callback,
6068                                  GCType gc_type_filter = kGCTypeAll));
6069
6070   /**
6071    * This function removes callback which was installed by
6072    * AddGCPrologueCallback function.
6073    */
6074   V8_INLINE static V8_DEPRECATE_SOON(
6075       "Use isolate version",
6076       void RemoveGCPrologueCallback(GCCallback callback));
6077
6078   /**
6079    * Enables the host application to receive a notification after a
6080    * garbage collection.  Allocations are not allowed in the
6081    * callback function, you therefore cannot manipulate objects (set
6082    * or delete properties for example) since it is possible such
6083    * operations will result in the allocation of objects. It is possible
6084    * to specify the GCType filter for your callback. But it is not possible to
6085    * register the same callback function two times with different
6086    * GCType filters.
6087    */
6088   static V8_DEPRECATE_SOON(
6089       "Use isolate version",
6090       void AddGCEpilogueCallback(GCCallback callback,
6091                                  GCType gc_type_filter = kGCTypeAll));
6092
6093   /**
6094    * This function removes callback which was installed by
6095    * AddGCEpilogueCallback function.
6096    */
6097   V8_INLINE static V8_DEPRECATE_SOON(
6098       "Use isolate version",
6099       void RemoveGCEpilogueCallback(GCCallback callback));
6100
6101   /**
6102    * Enables the host application to provide a mechanism to be notified
6103    * and perform custom logging when V8 Allocates Executable Memory.
6104    */
6105   V8_INLINE static V8_DEPRECATE_SOON(
6106       "Use isolate version",
6107       void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
6108                                        ObjectSpace space,
6109                                        AllocationAction action));
6110
6111   /**
6112    * Removes callback that was installed by AddMemoryAllocationCallback.
6113    */
6114   V8_INLINE static V8_DEPRECATE_SOON(
6115       "Use isolate version",
6116       void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback));
6117
6118   /**
6119    * Initializes V8. This function needs to be called before the first Isolate
6120    * is created. It always returns true.
6121    */
6122   static bool Initialize();
6123
6124   /**
6125    * Allows the host application to provide a callback which can be used
6126    * as a source of entropy for random number generators.
6127    */
6128   static void SetEntropySource(EntropySource source);
6129
6130   /**
6131    * Allows the host application to provide a callback that allows v8 to
6132    * cooperate with a profiler that rewrites return addresses on stack.
6133    */
6134   static void SetReturnAddressLocationResolver(
6135       ReturnAddressLocationResolver return_address_resolver);
6136
6137   /**
6138    * Forcefully terminate the current thread of JavaScript execution
6139    * in the given isolate.
6140    *
6141    * This method can be used by any thread even if that thread has not
6142    * acquired the V8 lock with a Locker object.
6143    *
6144    * \param isolate The isolate in which to terminate the current JS execution.
6145    */
6146   V8_INLINE static V8_DEPRECATE_SOON("Use isolate version",
6147                                      void TerminateExecution(Isolate* isolate));
6148
6149   /**
6150    * Is V8 terminating JavaScript execution.
6151    *
6152    * Returns true if JavaScript execution is currently terminating
6153    * because of a call to TerminateExecution.  In that case there are
6154    * still JavaScript frames on the stack and the termination
6155    * exception is still active.
6156    *
6157    * \param isolate The isolate in which to check.
6158    */
6159   V8_INLINE static V8_DEPRECATE_SOON(
6160       "Use isolate version",
6161       bool IsExecutionTerminating(Isolate* isolate = NULL));
6162
6163   /**
6164    * Resume execution capability in the given isolate, whose execution
6165    * was previously forcefully terminated using TerminateExecution().
6166    *
6167    * When execution is forcefully terminated using TerminateExecution(),
6168    * the isolate can not resume execution until all JavaScript frames
6169    * have propagated the uncatchable exception which is generated.  This
6170    * method allows the program embedding the engine to handle the
6171    * termination event and resume execution capability, even if
6172    * JavaScript frames remain on the stack.
6173    *
6174    * This method can be used by any thread even if that thread has not
6175    * acquired the V8 lock with a Locker object.
6176    *
6177    * \param isolate The isolate in which to resume execution capability.
6178    */
6179   V8_INLINE static V8_DEPRECATE_SOON(
6180       "Use isolate version", void CancelTerminateExecution(Isolate* isolate));
6181
6182   /**
6183    * Releases any resources used by v8 and stops any utility threads
6184    * that may be running.  Note that disposing v8 is permanent, it
6185    * cannot be reinitialized.
6186    *
6187    * It should generally not be necessary to dispose v8 before exiting
6188    * a process, this should happen automatically.  It is only necessary
6189    * to use if the process needs the resources taken up by v8.
6190    */
6191   static bool Dispose();
6192
6193   /**
6194    * Iterates through all external resources referenced from current isolate
6195    * heap.  GC is not invoked prior to iterating, therefore there is no
6196    * guarantee that visited objects are still alive.
6197    */
6198   V8_INLINE static V8_DEPRECATE_SOON(
6199       "Use isoalte version",
6200       void VisitExternalResources(ExternalResourceVisitor* visitor));
6201
6202   /**
6203    * Iterates through all the persistent handles in the current isolate's heap
6204    * that have class_ids.
6205    */
6206   V8_INLINE static V8_DEPRECATE_SOON(
6207       "Use isolate version",
6208       void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor));
6209
6210   /**
6211    * Iterates through all the persistent handles in isolate's heap that have
6212    * class_ids.
6213    */
6214   V8_INLINE static V8_DEPRECATE_SOON(
6215       "Use isolate version",
6216       void VisitHandlesWithClassIds(Isolate* isolate,
6217                                     PersistentHandleVisitor* visitor));
6218
6219   /**
6220    * Iterates through all the persistent handles in the current isolate's heap
6221    * that have class_ids and are candidates to be marked as partially dependent
6222    * handles. This will visit handles to young objects created since the last
6223    * garbage collection but is free to visit an arbitrary superset of these
6224    * objects.
6225    */
6226   V8_INLINE static V8_DEPRECATE_SOON(
6227       "Use isolate version",
6228       void VisitHandlesForPartialDependence(Isolate* isolate,
6229                                             PersistentHandleVisitor* visitor));
6230
6231   /**
6232    * Initialize the ICU library bundled with V8. The embedder should only
6233    * invoke this method when using the bundled ICU. Returns true on success.
6234    *
6235    * If V8 was compiled with the ICU data in an external file, the location
6236    * of the data file has to be provided.
6237    */
6238   static bool InitializeICU(const char* icu_data_file = NULL);
6239
6240   /**
6241    * Initialize the external startup data. The embedder only needs to
6242    * invoke this method when external startup data was enabled in a build.
6243    *
6244    * If V8 was compiled with the startup data in an external file, then
6245    * V8 needs to be given those external files during startup. There are
6246    * three ways to do this:
6247    * - InitializeExternalStartupData(const char*)
6248    *   This will look in the given directory for files "natives_blob.bin"
6249    *   and "snapshot_blob.bin" - which is what the default build calls them.
6250    * - InitializeExternalStartupData(const char*, const char*)
6251    *   As above, but will directly use the two given file names.
6252    * - Call SetNativesDataBlob, SetNativesDataBlob.
6253    *   This will read the blobs from the given data structures and will
6254    *   not perform any file IO.
6255    */
6256   static void InitializeExternalStartupData(const char* directory_path);
6257   static void InitializeExternalStartupData(const char* natives_blob,
6258                                             const char* snapshot_blob);
6259   /**
6260    * Sets the v8::Platform to use. This should be invoked before V8 is
6261    * initialized.
6262    */
6263   static void InitializePlatform(Platform* platform);
6264
6265   /**
6266    * Clears all references to the v8::Platform. This should be invoked after
6267    * V8 was disposed.
6268    */
6269   static void ShutdownPlatform();
6270
6271  private:
6272   V8();
6273
6274   static internal::Object** GlobalizeReference(internal::Isolate* isolate,
6275                                                internal::Object** handle);
6276   static internal::Object** CopyPersistent(internal::Object** handle);
6277   static void DisposeGlobal(internal::Object** global_handle);
6278   typedef WeakCallbackData<Value, void>::Callback WeakCallback;
6279   static void MakeWeak(internal::Object** global_handle, void* data,
6280                        WeakCallback weak_callback);
6281   static void MakeWeak(internal::Object** global_handle, void* data,
6282                        WeakCallbackInfo<void>::Callback weak_callback,
6283                        WeakCallbackType type);
6284   static void MakeWeak(internal::Object** global_handle, void* data,
6285                        // Must be 0 or -1.
6286                        int internal_field_index1,
6287                        // Must be 1 or -1.
6288                        int internal_field_index2,
6289                        WeakCallbackInfo<void>::Callback weak_callback);
6290   static void* ClearWeak(internal::Object** global_handle);
6291   static void Eternalize(Isolate* isolate,
6292                          Value* handle,
6293                          int* index);
6294   static Local<Value> GetEternal(Isolate* isolate, int index);
6295
6296   static void FromJustIsNothing();
6297   static void ToLocalEmpty();
6298   static void InternalFieldOutOfBounds(int index);
6299   template <class T> friend class Local;
6300   template <class T>
6301   friend class MaybeLocal;
6302   template <class T>
6303   friend class Maybe;
6304   template <class T>
6305   friend class WeakCallbackInfo;
6306   template <class T> friend class Eternal;
6307   template <class T> friend class PersistentBase;
6308   template <class T, class M> friend class Persistent;
6309   friend class Context;
6310 };
6311
6312
6313 /**
6314  * A simple Maybe type, representing an object which may or may not have a
6315  * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
6316  *
6317  * If an API method returns a Maybe<>, the API method can potentially fail
6318  * either because an exception is thrown, or because an exception is pending,
6319  * e.g. because a previous API call threw an exception that hasn't been caught
6320  * yet, or because a TerminateExecution exception was thrown. In that case, a
6321  * "Nothing" value is returned.
6322  */
6323 template <class T>
6324 class Maybe {
6325  public:
6326   V8_INLINE bool IsNothing() const { return !has_value; }
6327   V8_INLINE bool IsJust() const { return has_value; }
6328
6329   // Will crash if the Maybe<> is nothing.
6330   V8_INLINE T FromJust() const {
6331     if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
6332     return value;
6333   }
6334
6335   V8_INLINE T FromMaybe(const T& default_value) const {
6336     return has_value ? value : default_value;
6337   }
6338
6339   V8_INLINE bool operator==(const Maybe& other) const {
6340     return (IsJust() == other.IsJust()) &&
6341            (!IsJust() || FromJust() == other.FromJust());
6342   }
6343
6344   V8_INLINE bool operator!=(const Maybe& other) const {
6345     return !operator==(other);
6346   }
6347
6348  private:
6349   Maybe() : has_value(false) {}
6350   explicit Maybe(const T& t) : has_value(true), value(t) {}
6351
6352   bool has_value;
6353   T value;
6354
6355   template <class U>
6356   friend Maybe<U> Nothing();
6357   template <class U>
6358   friend Maybe<U> Just(const U& u);
6359 };
6360
6361
6362 template <class T>
6363 inline Maybe<T> Nothing() {
6364   return Maybe<T>();
6365 }
6366
6367
6368 template <class T>
6369 inline Maybe<T> Just(const T& t) {
6370   return Maybe<T>(t);
6371 }
6372
6373
6374 /**
6375  * An external exception handler.
6376  */
6377 class V8_EXPORT TryCatch {
6378  public:
6379   /**
6380    * Creates a new try/catch block and registers it with v8.  Note that
6381    * all TryCatch blocks should be stack allocated because the memory
6382    * location itself is compared against JavaScript try/catch blocks.
6383    */
6384   V8_DEPRECATE_SOON("Use isolate version", TryCatch());
6385
6386   /**
6387    * Creates a new try/catch block and registers it with v8.  Note that
6388    * all TryCatch blocks should be stack allocated because the memory
6389    * location itself is compared against JavaScript try/catch blocks.
6390    */
6391   TryCatch(Isolate* isolate);
6392
6393   /**
6394    * Unregisters and deletes this try/catch block.
6395    */
6396   ~TryCatch();
6397
6398   /**
6399    * Returns true if an exception has been caught by this try/catch block.
6400    */
6401   bool HasCaught() const;
6402
6403   /**
6404    * For certain types of exceptions, it makes no sense to continue execution.
6405    *
6406    * If CanContinue returns false, the correct action is to perform any C++
6407    * cleanup needed and then return.  If CanContinue returns false and
6408    * HasTerminated returns true, it is possible to call
6409    * CancelTerminateExecution in order to continue calling into the engine.
6410    */
6411   bool CanContinue() const;
6412
6413   /**
6414    * Returns true if an exception has been caught due to script execution
6415    * being terminated.
6416    *
6417    * There is no JavaScript representation of an execution termination
6418    * exception.  Such exceptions are thrown when the TerminateExecution
6419    * methods are called to terminate a long-running script.
6420    *
6421    * If such an exception has been thrown, HasTerminated will return true,
6422    * indicating that it is possible to call CancelTerminateExecution in order
6423    * to continue calling into the engine.
6424    */
6425   bool HasTerminated() const;
6426
6427   /**
6428    * Throws the exception caught by this TryCatch in a way that avoids
6429    * it being caught again by this same TryCatch.  As with ThrowException
6430    * it is illegal to execute any JavaScript operations after calling
6431    * ReThrow; the caller must return immediately to where the exception
6432    * is caught.
6433    */
6434   Local<Value> ReThrow();
6435
6436   /**
6437    * Returns the exception caught by this try/catch block.  If no exception has
6438    * been caught an empty handle is returned.
6439    *
6440    * The returned handle is valid until this TryCatch block has been destroyed.
6441    */
6442   Local<Value> Exception() const;
6443
6444   /**
6445    * Returns the .stack property of the thrown object.  If no .stack
6446    * property is present an empty handle is returned.
6447    */
6448   V8_DEPRECATE_SOON("Use maybe version.", Local<Value> StackTrace() const);
6449   V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace(
6450       Local<Context> context) const;
6451
6452   /**
6453    * Returns the message associated with this exception.  If there is
6454    * no message associated an empty handle is returned.
6455    *
6456    * The returned handle is valid until this TryCatch block has been
6457    * destroyed.
6458    */
6459   Local<v8::Message> Message() const;
6460
6461   /**
6462    * Clears any exceptions that may have been caught by this try/catch block.
6463    * After this method has been called, HasCaught() will return false. Cancels
6464    * the scheduled exception if it is caught and ReThrow() is not called before.
6465    *
6466    * It is not necessary to clear a try/catch block before using it again; if
6467    * another exception is thrown the previously caught exception will just be
6468    * overwritten.  However, it is often a good idea since it makes it easier
6469    * to determine which operation threw a given exception.
6470    */
6471   void Reset();
6472
6473   /**
6474    * Set verbosity of the external exception handler.
6475    *
6476    * By default, exceptions that are caught by an external exception
6477    * handler are not reported.  Call SetVerbose with true on an
6478    * external exception handler to have exceptions caught by the
6479    * handler reported as if they were not caught.
6480    */
6481   void SetVerbose(bool value);
6482
6483   /**
6484    * Set whether or not this TryCatch should capture a Message object
6485    * which holds source information about where the exception
6486    * occurred.  True by default.
6487    */
6488   void SetCaptureMessage(bool value);
6489
6490   /**
6491    * There are cases when the raw address of C++ TryCatch object cannot be
6492    * used for comparisons with addresses into the JS stack. The cases are:
6493    * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
6494    * 2) Address sanitizer allocates local C++ object in the heap when
6495    *    UseAfterReturn mode is enabled.
6496    * This method returns address that can be used for comparisons with
6497    * addresses into the JS stack. When neither simulator nor ASAN's
6498    * UseAfterReturn is enabled, then the address returned will be the address
6499    * of the C++ try catch handler itself.
6500    */
6501   static void* JSStackComparableAddress(v8::TryCatch* handler) {
6502     if (handler == NULL) return NULL;
6503     return handler->js_stack_comparable_address_;
6504   }
6505
6506  private:
6507   void ResetInternal();
6508
6509   // Make it hard to create heap-allocated TryCatch blocks.
6510   TryCatch(const TryCatch&);
6511   void operator=(const TryCatch&);
6512   void* operator new(size_t size);
6513   void operator delete(void*, size_t);
6514
6515   v8::internal::Isolate* isolate_;
6516   v8::TryCatch* next_;
6517   void* exception_;
6518   void* message_obj_;
6519   void* js_stack_comparable_address_;
6520   bool is_verbose_ : 1;
6521   bool can_continue_ : 1;
6522   bool capture_message_ : 1;
6523   bool rethrow_ : 1;
6524   bool has_terminated_ : 1;
6525
6526   friend class v8::internal::Isolate;
6527 };
6528
6529
6530 // --- Context ---
6531
6532
6533 /**
6534  * A container for extension names.
6535  */
6536 class V8_EXPORT ExtensionConfiguration {
6537  public:
6538   ExtensionConfiguration() : name_count_(0), names_(NULL) { }
6539   ExtensionConfiguration(int name_count, const char* names[])
6540       : name_count_(name_count), names_(names) { }
6541
6542   const char** begin() const { return &names_[0]; }
6543   const char** end()  const { return &names_[name_count_]; }
6544
6545  private:
6546   const int name_count_;
6547   const char** names_;
6548 };
6549
6550
6551 /**
6552  * A sandboxed execution context with its own set of built-in objects
6553  * and functions.
6554  */
6555 class V8_EXPORT Context {
6556  public:
6557   /**
6558    * Returns the global proxy object.
6559    *
6560    * Global proxy object is a thin wrapper whose prototype points to actual
6561    * context's global object with the properties like Object, etc. This is done
6562    * that way for security reasons (for more details see
6563    * https://wiki.mozilla.org/Gecko:SplitWindow).
6564    *
6565    * Please note that changes to global proxy object prototype most probably
6566    * would break VM---v8 expects only global object as a prototype of global
6567    * proxy object.
6568    */
6569   Local<Object> Global();
6570
6571   /**
6572    * Detaches the global object from its context before
6573    * the global object can be reused to create a new context.
6574    */
6575   void DetachGlobal();
6576
6577   /**
6578    * Creates a new context and returns a handle to the newly allocated
6579    * context.
6580    *
6581    * \param isolate The isolate in which to create the context.
6582    *
6583    * \param extensions An optional extension configuration containing
6584    * the extensions to be installed in the newly created context.
6585    *
6586    * \param global_template An optional object template from which the
6587    * global object for the newly created context will be created.
6588    *
6589    * \param global_object An optional global object to be reused for
6590    * the newly created context. This global object must have been
6591    * created by a previous call to Context::New with the same global
6592    * template. The state of the global object will be completely reset
6593    * and only object identify will remain.
6594    */
6595   static Local<Context> New(
6596       Isolate* isolate, ExtensionConfiguration* extensions = NULL,
6597       Local<ObjectTemplate> global_template = Local<ObjectTemplate>(),
6598       Local<Value> global_object = Local<Value>());
6599
6600   /**
6601    * Sets the security token for the context.  To access an object in
6602    * another context, the security tokens must match.
6603    */
6604   void SetSecurityToken(Local<Value> token);
6605
6606   /** Restores the security token to the default value. */
6607   void UseDefaultSecurityToken();
6608
6609   /** Returns the security token of this context.*/
6610   Local<Value> GetSecurityToken();
6611
6612   /**
6613    * Enter this context.  After entering a context, all code compiled
6614    * and run is compiled and run in this context.  If another context
6615    * is already entered, this old context is saved so it can be
6616    * restored when the new context is exited.
6617    */
6618   void Enter();
6619
6620   /**
6621    * Exit this context.  Exiting the current context restores the
6622    * context that was in place when entering the current context.
6623    */
6624   void Exit();
6625
6626   /** Returns an isolate associated with a current context. */
6627   v8::Isolate* GetIsolate();
6628
6629   /**
6630    * The field at kDebugIdIndex is reserved for V8 debugger implementation.
6631    * The value is propagated to the scripts compiled in given Context and
6632    * can be used for filtering scripts.
6633    */
6634   enum EmbedderDataFields { kDebugIdIndex = 0 };
6635
6636   /**
6637    * Gets the embedder data with the given index, which must have been set by a
6638    * previous call to SetEmbedderData with the same index. Note that index 0
6639    * currently has a special meaning for Chrome's debugger.
6640    */
6641   V8_INLINE Local<Value> GetEmbedderData(int index);
6642
6643   /**
6644    * Gets the binding object used by V8 extras. Extra natives get a reference
6645    * to this object and can use it to "export" functionality by adding
6646    * properties. Extra natives can also "import" functionality by accessing
6647    * properties added by the embedder using the V8 API.
6648    */
6649   Local<Object> GetExtrasBindingObject();
6650
6651   /**
6652    * Sets the embedder data with the given index, growing the data as
6653    * needed. Note that index 0 currently has a special meaning for Chrome's
6654    * debugger.
6655    */
6656   void SetEmbedderData(int index, Local<Value> value);
6657
6658   /**
6659    * Gets a 2-byte-aligned native pointer from the embedder data with the given
6660    * index, which must have bees set by a previous call to
6661    * SetAlignedPointerInEmbedderData with the same index. Note that index 0
6662    * currently has a special meaning for Chrome's debugger.
6663    */
6664   V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
6665
6666   /**
6667    * Sets a 2-byte-aligned native pointer in the embedder data with the given
6668    * index, growing the data as needed. Note that index 0 currently has a
6669    * special meaning for Chrome's debugger.
6670    */
6671   void SetAlignedPointerInEmbedderData(int index, void* value);
6672
6673   /**
6674    * Control whether code generation from strings is allowed. Calling
6675    * this method with false will disable 'eval' and the 'Function'
6676    * constructor for code running in this context. If 'eval' or the
6677    * 'Function' constructor are used an exception will be thrown.
6678    *
6679    * If code generation from strings is not allowed the
6680    * V8::AllowCodeGenerationFromStrings callback will be invoked if
6681    * set before blocking the call to 'eval' or the 'Function'
6682    * constructor. If that callback returns true, the call will be
6683    * allowed, otherwise an exception will be thrown. If no callback is
6684    * set an exception will be thrown.
6685    */
6686   void AllowCodeGenerationFromStrings(bool allow);
6687
6688   /**
6689    * Returns true if code generation from strings is allowed for the context.
6690    * For more details see AllowCodeGenerationFromStrings(bool) documentation.
6691    */
6692   bool IsCodeGenerationFromStringsAllowed();
6693
6694   /**
6695    * Sets the error description for the exception that is thrown when
6696    * code generation from strings is not allowed and 'eval' or the 'Function'
6697    * constructor are called.
6698    */
6699   void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
6700
6701   /**
6702    * Estimate the memory in bytes retained by this context.
6703    */
6704   size_t EstimatedSize();
6705
6706   /**
6707    * Stack-allocated class which sets the execution context for all
6708    * operations executed within a local scope.
6709    */
6710   class Scope {
6711    public:
6712     explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
6713       context_->Enter();
6714     }
6715     V8_INLINE ~Scope() { context_->Exit(); }
6716
6717    private:
6718     Local<Context> context_;
6719   };
6720
6721  private:
6722   friend class Value;
6723   friend class Script;
6724   friend class Object;
6725   friend class Function;
6726
6727   Local<Value> SlowGetEmbedderData(int index);
6728   void* SlowGetAlignedPointerFromEmbedderData(int index);
6729 };
6730
6731
6732 /**
6733  * Multiple threads in V8 are allowed, but only one thread at a time is allowed
6734  * to use any given V8 isolate, see the comments in the Isolate class. The
6735  * definition of 'using a V8 isolate' includes accessing handles or holding onto
6736  * object pointers obtained from V8 handles while in the particular V8 isolate.
6737  * It is up to the user of V8 to ensure, perhaps with locking, that this
6738  * constraint is not violated. In addition to any other synchronization
6739  * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
6740  * used to signal thead switches to V8.
6741  *
6742  * v8::Locker is a scoped lock object. While it's active, i.e. between its
6743  * construction and destruction, the current thread is allowed to use the locked
6744  * isolate. V8 guarantees that an isolate can be locked by at most one thread at
6745  * any time. In other words, the scope of a v8::Locker is a critical section.
6746  *
6747  * Sample usage:
6748 * \code
6749  * ...
6750  * {
6751  *   v8::Locker locker(isolate);
6752  *   v8::Isolate::Scope isolate_scope(isolate);
6753  *   ...
6754  *   // Code using V8 and isolate goes here.
6755  *   ...
6756  * } // Destructor called here
6757  * \endcode
6758  *
6759  * If you wish to stop using V8 in a thread A you can do this either by
6760  * destroying the v8::Locker object as above or by constructing a v8::Unlocker
6761  * object:
6762  *
6763  * \code
6764  * {
6765  *   isolate->Exit();
6766  *   v8::Unlocker unlocker(isolate);
6767  *   ...
6768  *   // Code not using V8 goes here while V8 can run in another thread.
6769  *   ...
6770  * } // Destructor called here.
6771  * isolate->Enter();
6772  * \endcode
6773  *
6774  * The Unlocker object is intended for use in a long-running callback from V8,
6775  * where you want to release the V8 lock for other threads to use.
6776  *
6777  * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
6778  * given thread. This can be useful if you have code that can be called either
6779  * from code that holds the lock or from code that does not. The Unlocker is
6780  * not recursive so you can not have several Unlockers on the stack at once, and
6781  * you can not use an Unlocker in a thread that is not inside a Locker's scope.
6782  *
6783  * An unlocker will unlock several lockers if it has to and reinstate the
6784  * correct depth of locking on its destruction, e.g.:
6785  *
6786  * \code
6787  * // V8 not locked.
6788  * {
6789  *   v8::Locker locker(isolate);
6790  *   Isolate::Scope isolate_scope(isolate);
6791  *   // V8 locked.
6792  *   {
6793  *     v8::Locker another_locker(isolate);
6794  *     // V8 still locked (2 levels).
6795  *     {
6796  *       isolate->Exit();
6797  *       v8::Unlocker unlocker(isolate);
6798  *       // V8 not locked.
6799  *     }
6800  *     isolate->Enter();
6801  *     // V8 locked again (2 levels).
6802  *   }
6803  *   // V8 still locked (1 level).
6804  * }
6805  * // V8 Now no longer locked.
6806  * \endcode
6807  */
6808 class V8_EXPORT Unlocker {
6809  public:
6810   /**
6811    * Initialize Unlocker for a given Isolate.
6812    */
6813   V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
6814
6815   ~Unlocker();
6816  private:
6817   void Initialize(Isolate* isolate);
6818
6819   internal::Isolate* isolate_;
6820 };
6821
6822
6823 class V8_EXPORT Locker {
6824  public:
6825   /**
6826    * Initialize Locker for a given Isolate.
6827    */
6828   V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
6829
6830   ~Locker();
6831
6832   /**
6833    * Returns whether or not the locker for a given isolate, is locked by the
6834    * current thread.
6835    */
6836   static bool IsLocked(Isolate* isolate);
6837
6838   /**
6839    * Returns whether v8::Locker is being used by this V8 instance.
6840    */
6841   static bool IsActive();
6842
6843  private:
6844   void Initialize(Isolate* isolate);
6845
6846   bool has_lock_;
6847   bool top_level_;
6848   internal::Isolate* isolate_;
6849
6850   // Disallow copying and assigning.
6851   Locker(const Locker&);
6852   void operator=(const Locker&);
6853 };
6854
6855
6856 // --- Implementation ---
6857
6858
6859 namespace internal {
6860
6861 const int kApiPointerSize = sizeof(void*);  // NOLINT
6862 const int kApiIntSize = sizeof(int);  // NOLINT
6863 const int kApiInt64Size = sizeof(int64_t);  // NOLINT
6864
6865 // Tag information for HeapObject.
6866 const int kHeapObjectTag = 1;
6867 const int kHeapObjectTagSize = 2;
6868 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
6869
6870 // Tag information for Smi.
6871 const int kSmiTag = 0;
6872 const int kSmiTagSize = 1;
6873 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
6874
6875 template <size_t ptr_size> struct SmiTagging;
6876
6877 template<int kSmiShiftSize>
6878 V8_INLINE internal::Object* IntToSmi(int value) {
6879   int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
6880   uintptr_t tagged_value =
6881       (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
6882   return reinterpret_cast<internal::Object*>(tagged_value);
6883 }
6884
6885 // Smi constants for 32-bit systems.
6886 template <> struct SmiTagging<4> {
6887   enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
6888   static int SmiShiftSize() { return kSmiShiftSize; }
6889   static int SmiValueSize() { return kSmiValueSize; }
6890   V8_INLINE static int SmiToInt(const internal::Object* value) {
6891     int shift_bits = kSmiTagSize + kSmiShiftSize;
6892     // Throw away top 32 bits and shift down (requires >> to be sign extending).
6893     return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
6894   }
6895   V8_INLINE static internal::Object* IntToSmi(int value) {
6896     return internal::IntToSmi<kSmiShiftSize>(value);
6897   }
6898   V8_INLINE static bool IsValidSmi(intptr_t value) {
6899     // To be representable as an tagged small integer, the two
6900     // most-significant bits of 'value' must be either 00 or 11 due to
6901     // sign-extension. To check this we add 01 to the two
6902     // most-significant bits, and check if the most-significant bit is 0
6903     //
6904     // CAUTION: The original code below:
6905     // bool result = ((value + 0x40000000) & 0x80000000) == 0;
6906     // may lead to incorrect results according to the C language spec, and
6907     // in fact doesn't work correctly with gcc4.1.1 in some cases: The
6908     // compiler may produce undefined results in case of signed integer
6909     // overflow. The computation must be done w/ unsigned ints.
6910     return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
6911   }
6912 };
6913
6914 // Smi constants for 64-bit systems.
6915 template <> struct SmiTagging<8> {
6916   enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
6917   static int SmiShiftSize() { return kSmiShiftSize; }
6918   static int SmiValueSize() { return kSmiValueSize; }
6919   V8_INLINE static int SmiToInt(const internal::Object* value) {
6920     int shift_bits = kSmiTagSize + kSmiShiftSize;
6921     // Shift down and throw away top 32 bits.
6922     return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
6923   }
6924   V8_INLINE static internal::Object* IntToSmi(int value) {
6925     return internal::IntToSmi<kSmiShiftSize>(value);
6926   }
6927   V8_INLINE static bool IsValidSmi(intptr_t value) {
6928     // To be representable as a long smi, the value must be a 32-bit integer.
6929     return (value == static_cast<int32_t>(value));
6930   }
6931 };
6932
6933 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
6934 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
6935 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
6936 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
6937 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
6938
6939 /**
6940  * This class exports constants and functionality from within v8 that
6941  * is necessary to implement inline functions in the v8 api.  Don't
6942  * depend on functions and constants defined here.
6943  */
6944 class Internals {
6945  public:
6946   // These values match non-compiler-dependent values defined within
6947   // the implementation of v8.
6948   static const int kHeapObjectMapOffset = 0;
6949   static const int kMapInstanceTypeAndBitFieldOffset =
6950       1 * kApiPointerSize + kApiIntSize;
6951   static const int kStringResourceOffset = 3 * kApiPointerSize;
6952
6953   static const int kOddballKindOffset = 4 * kApiPointerSize;
6954   static const int kForeignAddressOffset = kApiPointerSize;
6955   static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
6956   static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
6957   static const int kContextHeaderSize = 2 * kApiPointerSize;
6958   static const int kContextEmbedderDataIndex = 5;
6959   static const int kFullStringRepresentationMask = 0x07;
6960   static const int kStringEncodingMask = 0x4;
6961   static const int kExternalTwoByteRepresentationTag = 0x02;
6962   static const int kExternalOneByteRepresentationTag = 0x06;
6963
6964   static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
6965   static const int kAmountOfExternalAllocatedMemoryOffset =
6966       4 * kApiPointerSize;
6967   static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
6968       kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
6969   static const int kIsolateRootsOffset =
6970       kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
6971       kApiPointerSize;
6972   static const int kUndefinedValueRootIndex = 5;
6973   static const int kNullValueRootIndex = 7;
6974   static const int kTrueValueRootIndex = 8;
6975   static const int kFalseValueRootIndex = 9;
6976   static const int kEmptyStringRootIndex = 10;
6977
6978   // The external allocation limit should be below 256 MB on all architectures
6979   // to avoid that resource-constrained embedders run low on memory.
6980   static const int kExternalAllocationLimit = 192 * 1024 * 1024;
6981
6982   static const int kNodeClassIdOffset = 1 * kApiPointerSize;
6983   static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
6984   static const int kNodeStateMask = 0x7;
6985   static const int kNodeStateIsWeakValue = 2;
6986   static const int kNodeStateIsPendingValue = 3;
6987   static const int kNodeStateIsNearDeathValue = 4;
6988   static const int kNodeIsIndependentShift = 3;
6989   static const int kNodeIsPartiallyDependentShift = 4;
6990
6991   static const int kJSObjectType = 0xb7;
6992   static const int kFirstNonstringType = 0x80;
6993   static const int kOddballType = 0x83;
6994   static const int kForeignType = 0x87;
6995
6996   static const int kUndefinedOddballKind = 5;
6997   static const int kNullOddballKind = 3;
6998
6999   static const uint32_t kNumIsolateDataSlots = 4;
7000
7001   V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
7002   V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
7003 #ifdef V8_ENABLE_CHECKS
7004     CheckInitializedImpl(isolate);
7005 #endif
7006   }
7007
7008   V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
7009     return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
7010             kHeapObjectTag);
7011   }
7012
7013   V8_INLINE static int SmiValue(const internal::Object* value) {
7014     return PlatformSmiTagging::SmiToInt(value);
7015   }
7016
7017   V8_INLINE static internal::Object* IntToSmi(int value) {
7018     return PlatformSmiTagging::IntToSmi(value);
7019   }
7020
7021   V8_INLINE static bool IsValidSmi(intptr_t value) {
7022     return PlatformSmiTagging::IsValidSmi(value);
7023   }
7024
7025   V8_INLINE static int GetInstanceType(const internal::Object* obj) {
7026     typedef internal::Object O;
7027     O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
7028     // Map::InstanceType is defined so that it will always be loaded into
7029     // the LS 8 bits of one 16-bit word, regardless of endianess.
7030     return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
7031   }
7032
7033   V8_INLINE static int GetOddballKind(const internal::Object* obj) {
7034     typedef internal::Object O;
7035     return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
7036   }
7037
7038   V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
7039     int representation = (instance_type & kFullStringRepresentationMask);
7040     return representation == kExternalTwoByteRepresentationTag;
7041   }
7042
7043   V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
7044       uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7045       return *addr & static_cast<uint8_t>(1U << shift);
7046   }
7047
7048   V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
7049                                        bool value, int shift) {
7050       uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7051       uint8_t mask = static_cast<uint8_t>(1U << shift);
7052       *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
7053   }
7054
7055   V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
7056     uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7057     return *addr & kNodeStateMask;
7058   }
7059
7060   V8_INLINE static void UpdateNodeState(internal::Object** obj,
7061                                         uint8_t value) {
7062     uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7063     *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
7064   }
7065
7066   V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
7067                                         uint32_t slot,
7068                                         void* data) {
7069     uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
7070                     kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7071     *reinterpret_cast<void**>(addr) = data;
7072   }
7073
7074   V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
7075                                          uint32_t slot) {
7076     const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
7077         kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7078     return *reinterpret_cast<void* const*>(addr);
7079   }
7080
7081   V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
7082                                               int index) {
7083     uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
7084     return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
7085   }
7086
7087   template <typename T>
7088   V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
7089     const uint8_t* addr =
7090         reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
7091     return *reinterpret_cast<const T*>(addr);
7092   }
7093
7094   template <typename T>
7095   V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
7096     typedef internal::Object O;
7097     typedef internal::Internals I;
7098     O* ctx = *reinterpret_cast<O* const*>(context);
7099     int embedder_data_offset = I::kContextHeaderSize +
7100         (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
7101     O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
7102     int value_offset =
7103         I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
7104     return I::ReadField<T>(embedder_data, value_offset);
7105   }
7106 };
7107
7108 }  // namespace internal
7109
7110
7111 template <class T>
7112 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
7113   return New(isolate, that.val_);
7114 }
7115
7116 template <class T>
7117 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
7118   return New(isolate, that.val_);
7119 }
7120
7121
7122 template <class T>
7123 Local<T> Local<T>::New(Isolate* isolate, T* that) {
7124   if (that == NULL) return Local<T>();
7125   T* that_ptr = that;
7126   internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
7127   return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
7128       reinterpret_cast<internal::Isolate*>(isolate), *p)));
7129 }
7130
7131
7132 template<class T>
7133 template<class S>
7134 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
7135   TYPE_CHECK(T, S);
7136   V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
7137 }
7138
7139
7140 template<class T>
7141 Local<T> Eternal<T>::Get(Isolate* isolate) {
7142   return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
7143 }
7144
7145
7146 template <class T>
7147 Local<T> MaybeLocal<T>::ToLocalChecked() {
7148   if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
7149   return Local<T>(val_);
7150 }
7151
7152
7153 template <class T>
7154 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
7155 #ifdef V8_ENABLE_CHECKS
7156   if (index < 0 || index >= kInternalFieldsInWeakCallback) {
7157     V8::InternalFieldOutOfBounds(index);
7158   }
7159 #endif
7160   return internal_fields_[index];
7161 }
7162
7163
7164 template <class T>
7165 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
7166   if (that == NULL) return NULL;
7167   internal::Object** p = reinterpret_cast<internal::Object**>(that);
7168   return reinterpret_cast<T*>(
7169       V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
7170                              p));
7171 }
7172
7173
7174 template <class T, class M>
7175 template <class S, class M2>
7176 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
7177   TYPE_CHECK(T, S);
7178   this->Reset();
7179   if (that.IsEmpty()) return;
7180   internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
7181   this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
7182   M::Copy(that, this);
7183 }
7184
7185
7186 template <class T>
7187 bool PersistentBase<T>::IsIndependent() const {
7188   typedef internal::Internals I;
7189   if (this->IsEmpty()) return false;
7190   return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7191                         I::kNodeIsIndependentShift);
7192 }
7193
7194
7195 template <class T>
7196 bool PersistentBase<T>::IsNearDeath() const {
7197   typedef internal::Internals I;
7198   if (this->IsEmpty()) return false;
7199   uint8_t node_state =
7200       I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
7201   return node_state == I::kNodeStateIsNearDeathValue ||
7202       node_state == I::kNodeStateIsPendingValue;
7203 }
7204
7205
7206 template <class T>
7207 bool PersistentBase<T>::IsWeak() const {
7208   typedef internal::Internals I;
7209   if (this->IsEmpty()) return false;
7210   return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
7211       I::kNodeStateIsWeakValue;
7212 }
7213
7214
7215 template <class T>
7216 void PersistentBase<T>::Reset() {
7217   if (this->IsEmpty()) return;
7218   V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
7219   val_ = 0;
7220 }
7221
7222
7223 template <class T>
7224 template <class S>
7225 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
7226   TYPE_CHECK(T, S);
7227   Reset();
7228   if (other.IsEmpty()) return;
7229   this->val_ = New(isolate, other.val_);
7230 }
7231
7232
7233 template <class T>
7234 template <class S>
7235 void PersistentBase<T>::Reset(Isolate* isolate,
7236                               const PersistentBase<S>& other) {
7237   TYPE_CHECK(T, S);
7238   Reset();
7239   if (other.IsEmpty()) return;
7240   this->val_ = New(isolate, other.val_);
7241 }
7242
7243
7244 template <class T>
7245 template <typename S, typename P>
7246 void PersistentBase<T>::SetWeak(
7247     P* parameter,
7248     typename WeakCallbackData<S, P>::Callback callback) {
7249   TYPE_CHECK(S, T);
7250   typedef typename WeakCallbackData<Value, void>::Callback Callback;
7251   V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7252                reinterpret_cast<Callback>(callback));
7253 }
7254
7255
7256 template <class T>
7257 template <typename P>
7258 void PersistentBase<T>::SetWeak(
7259     P* parameter,
7260     typename WeakCallbackData<T, P>::Callback callback) {
7261   SetWeak<T, P>(parameter, callback);
7262 }
7263
7264
7265 template <class T>
7266 template <typename P>
7267 void PersistentBase<T>::SetPhantom(
7268     P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7269     int internal_field_index1, int internal_field_index2) {
7270   typedef typename WeakCallbackInfo<void>::Callback Callback;
7271   V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7272                internal_field_index1, internal_field_index2,
7273                reinterpret_cast<Callback>(callback));
7274 }
7275
7276
7277 template <class T>
7278 template <typename P>
7279 V8_INLINE void PersistentBase<T>::SetWeak(
7280     P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7281     WeakCallbackType type) {
7282   typedef typename WeakCallbackInfo<void>::Callback Callback;
7283   V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7284                reinterpret_cast<Callback>(callback), type);
7285 }
7286
7287
7288 template <class T>
7289 template <typename P>
7290 P* PersistentBase<T>::ClearWeak() {
7291   return reinterpret_cast<P*>(
7292     V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
7293 }
7294
7295
7296 template <class T>
7297 void PersistentBase<T>::MarkIndependent() {
7298   typedef internal::Internals I;
7299   if (this->IsEmpty()) return;
7300   I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7301                     true,
7302                     I::kNodeIsIndependentShift);
7303 }
7304
7305
7306 template <class T>
7307 void PersistentBase<T>::MarkPartiallyDependent() {
7308   typedef internal::Internals I;
7309   if (this->IsEmpty()) return;
7310   I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7311                     true,
7312                     I::kNodeIsPartiallyDependentShift);
7313 }
7314
7315
7316 template <class T>
7317 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
7318   typedef internal::Internals I;
7319   if (this->IsEmpty()) return;
7320   internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7321   uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7322   *reinterpret_cast<uint16_t*>(addr) = class_id;
7323 }
7324
7325
7326 template <class T>
7327 uint16_t PersistentBase<T>::WrapperClassId() const {
7328   typedef internal::Internals I;
7329   if (this->IsEmpty()) return 0;
7330   internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7331   uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7332   return *reinterpret_cast<uint16_t*>(addr);
7333 }
7334
7335
7336 template<typename T>
7337 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
7338
7339 template<typename T>
7340 template<typename S>
7341 void ReturnValue<T>::Set(const Persistent<S>& handle) {
7342   TYPE_CHECK(T, S);
7343   if (V8_UNLIKELY(handle.IsEmpty())) {
7344     *value_ = GetDefaultValue();
7345   } else {
7346     *value_ = *reinterpret_cast<internal::Object**>(*handle);
7347   }
7348 }
7349
7350 template <typename T>
7351 template <typename S>
7352 void ReturnValue<T>::Set(const Global<S>& handle) {
7353   TYPE_CHECK(T, S);
7354   if (V8_UNLIKELY(handle.IsEmpty())) {
7355     *value_ = GetDefaultValue();
7356   } else {
7357     *value_ = *reinterpret_cast<internal::Object**>(*handle);
7358   }
7359 }
7360
7361 template <typename T>
7362 template <typename S>
7363 void ReturnValue<T>::Set(const Local<S> handle) {
7364   TYPE_CHECK(T, S);
7365   if (V8_UNLIKELY(handle.IsEmpty())) {
7366     *value_ = GetDefaultValue();
7367   } else {
7368     *value_ = *reinterpret_cast<internal::Object**>(*handle);
7369   }
7370 }
7371
7372 template<typename T>
7373 void ReturnValue<T>::Set(double i) {
7374   TYPE_CHECK(T, Number);
7375   Set(Number::New(GetIsolate(), i));
7376 }
7377
7378 template<typename T>
7379 void ReturnValue<T>::Set(int32_t i) {
7380   TYPE_CHECK(T, Integer);
7381   typedef internal::Internals I;
7382   if (V8_LIKELY(I::IsValidSmi(i))) {
7383     *value_ = I::IntToSmi(i);
7384     return;
7385   }
7386   Set(Integer::New(GetIsolate(), i));
7387 }
7388
7389 template<typename T>
7390 void ReturnValue<T>::Set(uint32_t i) {
7391   TYPE_CHECK(T, Integer);
7392   // Can't simply use INT32_MAX here for whatever reason.
7393   bool fits_into_int32_t = (i & (1U << 31)) == 0;
7394   if (V8_LIKELY(fits_into_int32_t)) {
7395     Set(static_cast<int32_t>(i));
7396     return;
7397   }
7398   Set(Integer::NewFromUnsigned(GetIsolate(), i));
7399 }
7400
7401 template<typename T>
7402 void ReturnValue<T>::Set(bool value) {
7403   TYPE_CHECK(T, Boolean);
7404   typedef internal::Internals I;
7405   int root_index;
7406   if (value) {
7407     root_index = I::kTrueValueRootIndex;
7408   } else {
7409     root_index = I::kFalseValueRootIndex;
7410   }
7411   *value_ = *I::GetRoot(GetIsolate(), root_index);
7412 }
7413
7414 template<typename T>
7415 void ReturnValue<T>::SetNull() {
7416   TYPE_CHECK(T, Primitive);
7417   typedef internal::Internals I;
7418   *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
7419 }
7420
7421 template<typename T>
7422 void ReturnValue<T>::SetUndefined() {
7423   TYPE_CHECK(T, Primitive);
7424   typedef internal::Internals I;
7425   *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
7426 }
7427
7428 template<typename T>
7429 void ReturnValue<T>::SetEmptyString() {
7430   TYPE_CHECK(T, String);
7431   typedef internal::Internals I;
7432   *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
7433 }
7434
7435 template<typename T>
7436 Isolate* ReturnValue<T>::GetIsolate() {
7437   // Isolate is always the pointer below the default value on the stack.
7438   return *reinterpret_cast<Isolate**>(&value_[-2]);
7439 }
7440
7441 template<typename T>
7442 template<typename S>
7443 void ReturnValue<T>::Set(S* whatever) {
7444   // Uncompilable to prevent inadvertent misuse.
7445   TYPE_CHECK(S*, Primitive);
7446 }
7447
7448 template<typename T>
7449 internal::Object* ReturnValue<T>::GetDefaultValue() {
7450   // Default value is always the pointer below value_ on the stack.
7451   return value_[-1];
7452 }
7453
7454
7455 template<typename T>
7456 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
7457                                               internal::Object** values,
7458                                               int length,
7459                                               bool is_construct_call)
7460     : implicit_args_(implicit_args),
7461       values_(values),
7462       length_(length),
7463       is_construct_call_(is_construct_call) { }
7464
7465
7466 template<typename T>
7467 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
7468   if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
7469   return Local<Value>(reinterpret_cast<Value*>(values_ - i));
7470 }
7471
7472
7473 template<typename T>
7474 Local<Function> FunctionCallbackInfo<T>::Callee() const {
7475   return Local<Function>(reinterpret_cast<Function*>(
7476       &implicit_args_[kCalleeIndex]));
7477 }
7478
7479
7480 template<typename T>
7481 Local<Object> FunctionCallbackInfo<T>::This() const {
7482   return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
7483 }
7484
7485
7486 template<typename T>
7487 Local<Object> FunctionCallbackInfo<T>::Holder() const {
7488   return Local<Object>(reinterpret_cast<Object*>(
7489       &implicit_args_[kHolderIndex]));
7490 }
7491
7492
7493 template<typename T>
7494 Local<Value> FunctionCallbackInfo<T>::Data() const {
7495   return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
7496 }
7497
7498
7499 template<typename T>
7500 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
7501   return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
7502 }
7503
7504
7505 template<typename T>
7506 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
7507   return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
7508 }
7509
7510
7511 template<typename T>
7512 bool FunctionCallbackInfo<T>::IsConstructCall() const {
7513   return is_construct_call_ & 0x1;
7514 }
7515
7516
7517 template<typename T>
7518 int FunctionCallbackInfo<T>::Length() const {
7519   return length_;
7520 }
7521
7522 ScriptOrigin::ScriptOrigin(Local<Value> resource_name,
7523                            Local<Integer> resource_line_offset,
7524                            Local<Integer> resource_column_offset,
7525                            Local<Boolean> resource_is_shared_cross_origin,
7526                            Local<Integer> script_id,
7527                            Local<Boolean> resource_is_embedder_debug_script,
7528                            Local<Value> source_map_url,
7529                            Local<Boolean> resource_is_opaque)
7530     : resource_name_(resource_name),
7531       resource_line_offset_(resource_line_offset),
7532       resource_column_offset_(resource_column_offset),
7533       options_(!resource_is_embedder_debug_script.IsEmpty() &&
7534                    resource_is_embedder_debug_script->IsTrue(),
7535                !resource_is_shared_cross_origin.IsEmpty() &&
7536                    resource_is_shared_cross_origin->IsTrue(),
7537                !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue()),
7538       script_id_(script_id),
7539       source_map_url_(source_map_url) {}
7540
7541 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
7542
7543
7544 Local<Integer> ScriptOrigin::ResourceLineOffset() const {
7545   return resource_line_offset_;
7546 }
7547
7548
7549 Local<Integer> ScriptOrigin::ResourceColumnOffset() const {
7550   return resource_column_offset_;
7551 }
7552
7553
7554 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
7555
7556
7557 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
7558
7559
7560 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
7561                                CachedData* data)
7562     : source_string(string),
7563       resource_name(origin.ResourceName()),
7564       resource_line_offset(origin.ResourceLineOffset()),
7565       resource_column_offset(origin.ResourceColumnOffset()),
7566       resource_options(origin.Options()),
7567       source_map_url(origin.SourceMapUrl()),
7568       cached_data(data) {}
7569
7570
7571 ScriptCompiler::Source::Source(Local<String> string,
7572                                CachedData* data)
7573     : source_string(string), cached_data(data) {}
7574
7575
7576 ScriptCompiler::Source::~Source() {
7577   delete cached_data;
7578 }
7579
7580
7581 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
7582     const {
7583   return cached_data;
7584 }
7585
7586
7587 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
7588   return value ? True(isolate) : False(isolate);
7589 }
7590
7591
7592 void Template::Set(Isolate* isolate, const char* name, v8::Local<Data> value) {
7593   Set(v8::String::NewFromUtf8(isolate, name, NewStringType::kNormal)
7594           .ToLocalChecked(),
7595       value);
7596 }
7597
7598
7599 Local<Value> Object::GetInternalField(int index) {
7600 #ifndef V8_ENABLE_CHECKS
7601   typedef internal::Object O;
7602   typedef internal::HeapObject HO;
7603   typedef internal::Internals I;
7604   O* obj = *reinterpret_cast<O**>(this);
7605   // Fast path: If the object is a plain JSObject, which is the common case, we
7606   // know where to find the internal fields and can return the value directly.
7607   if (I::GetInstanceType(obj) == I::kJSObjectType) {
7608     int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7609     O* value = I::ReadField<O*>(obj, offset);
7610     O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
7611     return Local<Value>(reinterpret_cast<Value*>(result));
7612   }
7613 #endif
7614   return SlowGetInternalField(index);
7615 }
7616
7617
7618 void* Object::GetAlignedPointerFromInternalField(int index) {
7619 #ifndef V8_ENABLE_CHECKS
7620   typedef internal::Object O;
7621   typedef internal::Internals I;
7622   O* obj = *reinterpret_cast<O**>(this);
7623   // Fast path: If the object is a plain JSObject, which is the common case, we
7624   // know where to find the internal fields and can return the value directly.
7625   if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
7626     int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7627     return I::ReadField<void*>(obj, offset);
7628   }
7629 #endif
7630   return SlowGetAlignedPointerFromInternalField(index);
7631 }
7632
7633
7634 String* String::Cast(v8::Value* value) {
7635 #ifdef V8_ENABLE_CHECKS
7636   CheckCast(value);
7637 #endif
7638   return static_cast<String*>(value);
7639 }
7640
7641
7642 Local<String> String::Empty(Isolate* isolate) {
7643   typedef internal::Object* S;
7644   typedef internal::Internals I;
7645   I::CheckInitialized(isolate);
7646   S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
7647   return Local<String>(reinterpret_cast<String*>(slot));
7648 }
7649
7650
7651 String::ExternalStringResource* String::GetExternalStringResource() const {
7652   typedef internal::Object O;
7653   typedef internal::Internals I;
7654   O* obj = *reinterpret_cast<O* const*>(this);
7655   String::ExternalStringResource* result;
7656   if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
7657     void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7658     result = reinterpret_cast<String::ExternalStringResource*>(value);
7659   } else {
7660     result = NULL;
7661   }
7662 #ifdef V8_ENABLE_CHECKS
7663   VerifyExternalStringResource(result);
7664 #endif
7665   return result;
7666 }
7667
7668
7669 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
7670     String::Encoding* encoding_out) const {
7671   typedef internal::Object O;
7672   typedef internal::Internals I;
7673   O* obj = *reinterpret_cast<O* const*>(this);
7674   int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
7675   *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
7676   ExternalStringResourceBase* resource = NULL;
7677   if (type == I::kExternalOneByteRepresentationTag ||
7678       type == I::kExternalTwoByteRepresentationTag) {
7679     void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7680     resource = static_cast<ExternalStringResourceBase*>(value);
7681   }
7682 #ifdef V8_ENABLE_CHECKS
7683     VerifyExternalStringResourceBase(resource, *encoding_out);
7684 #endif
7685   return resource;
7686 }
7687
7688
7689 bool Value::IsUndefined() const {
7690 #ifdef V8_ENABLE_CHECKS
7691   return FullIsUndefined();
7692 #else
7693   return QuickIsUndefined();
7694 #endif
7695 }
7696
7697 bool Value::QuickIsUndefined() const {
7698   typedef internal::Object O;
7699   typedef internal::Internals I;
7700   O* obj = *reinterpret_cast<O* const*>(this);
7701   if (!I::HasHeapObjectTag(obj)) return false;
7702   if (I::GetInstanceType(obj) != I::kOddballType) return false;
7703   return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
7704 }
7705
7706
7707 bool Value::IsNull() const {
7708 #ifdef V8_ENABLE_CHECKS
7709   return FullIsNull();
7710 #else
7711   return QuickIsNull();
7712 #endif
7713 }
7714
7715 bool Value::QuickIsNull() const {
7716   typedef internal::Object O;
7717   typedef internal::Internals I;
7718   O* obj = *reinterpret_cast<O* const*>(this);
7719   if (!I::HasHeapObjectTag(obj)) return false;
7720   if (I::GetInstanceType(obj) != I::kOddballType) return false;
7721   return (I::GetOddballKind(obj) == I::kNullOddballKind);
7722 }
7723
7724
7725 bool Value::IsString() const {
7726 #ifdef V8_ENABLE_CHECKS
7727   return FullIsString();
7728 #else
7729   return QuickIsString();
7730 #endif
7731 }
7732
7733 bool Value::QuickIsString() const {
7734   typedef internal::Object O;
7735   typedef internal::Internals I;
7736   O* obj = *reinterpret_cast<O* const*>(this);
7737   if (!I::HasHeapObjectTag(obj)) return false;
7738   return (I::GetInstanceType(obj) < I::kFirstNonstringType);
7739 }
7740
7741
7742 template <class T> Value* Value::Cast(T* value) {
7743   return static_cast<Value*>(value);
7744 }
7745
7746
7747 Local<Boolean> Value::ToBoolean() const {
7748   return ToBoolean(Isolate::GetCurrent()->GetCurrentContext())
7749       .FromMaybe(Local<Boolean>());
7750 }
7751
7752
7753 Local<Number> Value::ToNumber() const {
7754   return ToNumber(Isolate::GetCurrent()->GetCurrentContext())
7755       .FromMaybe(Local<Number>());
7756 }
7757
7758
7759 Local<String> Value::ToString() const {
7760   return ToString(Isolate::GetCurrent()->GetCurrentContext())
7761       .FromMaybe(Local<String>());
7762 }
7763
7764
7765 Local<String> Value::ToDetailString() const {
7766   return ToDetailString(Isolate::GetCurrent()->GetCurrentContext())
7767       .FromMaybe(Local<String>());
7768 }
7769
7770
7771 Local<Object> Value::ToObject() const {
7772   return ToObject(Isolate::GetCurrent()->GetCurrentContext())
7773       .FromMaybe(Local<Object>());
7774 }
7775
7776
7777 Local<Integer> Value::ToInteger() const {
7778   return ToInteger(Isolate::GetCurrent()->GetCurrentContext())
7779       .FromMaybe(Local<Integer>());
7780 }
7781
7782
7783 Local<Uint32> Value::ToUint32() const {
7784   return ToUint32(Isolate::GetCurrent()->GetCurrentContext())
7785       .FromMaybe(Local<Uint32>());
7786 }
7787
7788
7789 Local<Int32> Value::ToInt32() const {
7790   return ToInt32(Isolate::GetCurrent()->GetCurrentContext())
7791       .FromMaybe(Local<Int32>());
7792 }
7793
7794
7795 Boolean* Boolean::Cast(v8::Value* value) {
7796 #ifdef V8_ENABLE_CHECKS
7797   CheckCast(value);
7798 #endif
7799   return static_cast<Boolean*>(value);
7800 }
7801
7802
7803 Name* Name::Cast(v8::Value* value) {
7804 #ifdef V8_ENABLE_CHECKS
7805   CheckCast(value);
7806 #endif
7807   return static_cast<Name*>(value);
7808 }
7809
7810
7811 Symbol* Symbol::Cast(v8::Value* value) {
7812 #ifdef V8_ENABLE_CHECKS
7813   CheckCast(value);
7814 #endif
7815   return static_cast<Symbol*>(value);
7816 }
7817
7818
7819 Number* Number::Cast(v8::Value* value) {
7820 #ifdef V8_ENABLE_CHECKS
7821   CheckCast(value);
7822 #endif
7823   return static_cast<Number*>(value);
7824 }
7825
7826
7827 Integer* Integer::Cast(v8::Value* value) {
7828 #ifdef V8_ENABLE_CHECKS
7829   CheckCast(value);
7830 #endif
7831   return static_cast<Integer*>(value);
7832 }
7833
7834
7835 Int32* Int32::Cast(v8::Value* value) {
7836 #ifdef V8_ENABLE_CHECKS
7837   CheckCast(value);
7838 #endif
7839   return static_cast<Int32*>(value);
7840 }
7841
7842
7843 Uint32* Uint32::Cast(v8::Value* value) {
7844 #ifdef V8_ENABLE_CHECKS
7845   CheckCast(value);
7846 #endif
7847   return static_cast<Uint32*>(value);
7848 }
7849
7850
7851 Date* Date::Cast(v8::Value* value) {
7852 #ifdef V8_ENABLE_CHECKS
7853   CheckCast(value);
7854 #endif
7855   return static_cast<Date*>(value);
7856 }
7857
7858
7859 StringObject* StringObject::Cast(v8::Value* value) {
7860 #ifdef V8_ENABLE_CHECKS
7861   CheckCast(value);
7862 #endif
7863   return static_cast<StringObject*>(value);
7864 }
7865
7866
7867 SymbolObject* SymbolObject::Cast(v8::Value* value) {
7868 #ifdef V8_ENABLE_CHECKS
7869   CheckCast(value);
7870 #endif
7871   return static_cast<SymbolObject*>(value);
7872 }
7873
7874
7875 NumberObject* NumberObject::Cast(v8::Value* value) {
7876 #ifdef V8_ENABLE_CHECKS
7877   CheckCast(value);
7878 #endif
7879   return static_cast<NumberObject*>(value);
7880 }
7881
7882
7883 BooleanObject* BooleanObject::Cast(v8::Value* value) {
7884 #ifdef V8_ENABLE_CHECKS
7885   CheckCast(value);
7886 #endif
7887   return static_cast<BooleanObject*>(value);
7888 }
7889
7890
7891 RegExp* RegExp::Cast(v8::Value* value) {
7892 #ifdef V8_ENABLE_CHECKS
7893   CheckCast(value);
7894 #endif
7895   return static_cast<RegExp*>(value);
7896 }
7897
7898
7899 Object* Object::Cast(v8::Value* value) {
7900 #ifdef V8_ENABLE_CHECKS
7901   CheckCast(value);
7902 #endif
7903   return static_cast<Object*>(value);
7904 }
7905
7906
7907 Array* Array::Cast(v8::Value* value) {
7908 #ifdef V8_ENABLE_CHECKS
7909   CheckCast(value);
7910 #endif
7911   return static_cast<Array*>(value);
7912 }
7913
7914
7915 Map* Map::Cast(v8::Value* value) {
7916 #ifdef V8_ENABLE_CHECKS
7917   CheckCast(value);
7918 #endif
7919   return static_cast<Map*>(value);
7920 }
7921
7922
7923 Set* Set::Cast(v8::Value* value) {
7924 #ifdef V8_ENABLE_CHECKS
7925   CheckCast(value);
7926 #endif
7927   return static_cast<Set*>(value);
7928 }
7929
7930
7931 Promise* Promise::Cast(v8::Value* value) {
7932 #ifdef V8_ENABLE_CHECKS
7933   CheckCast(value);
7934 #endif
7935   return static_cast<Promise*>(value);
7936 }
7937
7938
7939 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
7940 #ifdef V8_ENABLE_CHECKS
7941   CheckCast(value);
7942 #endif
7943   return static_cast<Promise::Resolver*>(value);
7944 }
7945
7946
7947 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
7948 #ifdef V8_ENABLE_CHECKS
7949   CheckCast(value);
7950 #endif
7951   return static_cast<ArrayBuffer*>(value);
7952 }
7953
7954
7955 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
7956 #ifdef V8_ENABLE_CHECKS
7957   CheckCast(value);
7958 #endif
7959   return static_cast<ArrayBufferView*>(value);
7960 }
7961
7962
7963 TypedArray* TypedArray::Cast(v8::Value* value) {
7964 #ifdef V8_ENABLE_CHECKS
7965   CheckCast(value);
7966 #endif
7967   return static_cast<TypedArray*>(value);
7968 }
7969
7970
7971 Uint8Array* Uint8Array::Cast(v8::Value* value) {
7972 #ifdef V8_ENABLE_CHECKS
7973   CheckCast(value);
7974 #endif
7975   return static_cast<Uint8Array*>(value);
7976 }
7977
7978
7979 Int8Array* Int8Array::Cast(v8::Value* value) {
7980 #ifdef V8_ENABLE_CHECKS
7981   CheckCast(value);
7982 #endif
7983   return static_cast<Int8Array*>(value);
7984 }
7985
7986
7987 Uint16Array* Uint16Array::Cast(v8::Value* value) {
7988 #ifdef V8_ENABLE_CHECKS
7989   CheckCast(value);
7990 #endif
7991   return static_cast<Uint16Array*>(value);
7992 }
7993
7994
7995 Int16Array* Int16Array::Cast(v8::Value* value) {
7996 #ifdef V8_ENABLE_CHECKS
7997   CheckCast(value);
7998 #endif
7999   return static_cast<Int16Array*>(value);
8000 }
8001
8002
8003 Uint32Array* Uint32Array::Cast(v8::Value* value) {
8004 #ifdef V8_ENABLE_CHECKS
8005   CheckCast(value);
8006 #endif
8007   return static_cast<Uint32Array*>(value);
8008 }
8009
8010
8011 Int32Array* Int32Array::Cast(v8::Value* value) {
8012 #ifdef V8_ENABLE_CHECKS
8013   CheckCast(value);
8014 #endif
8015   return static_cast<Int32Array*>(value);
8016 }
8017
8018
8019 Float32Array* Float32Array::Cast(v8::Value* value) {
8020 #ifdef V8_ENABLE_CHECKS
8021   CheckCast(value);
8022 #endif
8023   return static_cast<Float32Array*>(value);
8024 }
8025
8026
8027 Float64Array* Float64Array::Cast(v8::Value* value) {
8028 #ifdef V8_ENABLE_CHECKS
8029   CheckCast(value);
8030 #endif
8031   return static_cast<Float64Array*>(value);
8032 }
8033
8034
8035 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
8036 #ifdef V8_ENABLE_CHECKS
8037   CheckCast(value);
8038 #endif
8039   return static_cast<Uint8ClampedArray*>(value);
8040 }
8041
8042
8043 DataView* DataView::Cast(v8::Value* value) {
8044 #ifdef V8_ENABLE_CHECKS
8045   CheckCast(value);
8046 #endif
8047   return static_cast<DataView*>(value);
8048 }
8049
8050
8051 SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) {
8052 #ifdef V8_ENABLE_CHECKS
8053   CheckCast(value);
8054 #endif
8055   return static_cast<SharedArrayBuffer*>(value);
8056 }
8057
8058
8059 Function* Function::Cast(v8::Value* value) {
8060 #ifdef V8_ENABLE_CHECKS
8061   CheckCast(value);
8062 #endif
8063   return static_cast<Function*>(value);
8064 }
8065
8066
8067 External* External::Cast(v8::Value* value) {
8068 #ifdef V8_ENABLE_CHECKS
8069   CheckCast(value);
8070 #endif
8071   return static_cast<External*>(value);
8072 }
8073
8074
8075 template<typename T>
8076 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
8077   return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
8078 }
8079
8080
8081 template<typename T>
8082 Local<Value> PropertyCallbackInfo<T>::Data() const {
8083   return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
8084 }
8085
8086
8087 template<typename T>
8088 Local<Object> PropertyCallbackInfo<T>::This() const {
8089   return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
8090 }
8091
8092
8093 template<typename T>
8094 Local<Object> PropertyCallbackInfo<T>::Holder() const {
8095   return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
8096 }
8097
8098
8099 template<typename T>
8100 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
8101   return ReturnValue<T>(&args_[kReturnValueIndex]);
8102 }
8103
8104
8105 Local<Primitive> Undefined(Isolate* isolate) {
8106   typedef internal::Object* S;
8107   typedef internal::Internals I;
8108   I::CheckInitialized(isolate);
8109   S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
8110   return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8111 }
8112
8113
8114 Local<Primitive> Null(Isolate* isolate) {
8115   typedef internal::Object* S;
8116   typedef internal::Internals I;
8117   I::CheckInitialized(isolate);
8118   S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
8119   return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8120 }
8121
8122
8123 Local<Boolean> True(Isolate* isolate) {
8124   typedef internal::Object* S;
8125   typedef internal::Internals I;
8126   I::CheckInitialized(isolate);
8127   S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
8128   return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8129 }
8130
8131
8132 Local<Boolean> False(Isolate* isolate) {
8133   typedef internal::Object* S;
8134   typedef internal::Internals I;
8135   I::CheckInitialized(isolate);
8136   S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
8137   return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8138 }
8139
8140
8141 void Isolate::SetData(uint32_t slot, void* data) {
8142   typedef internal::Internals I;
8143   I::SetEmbedderData(this, slot, data);
8144 }
8145
8146
8147 void* Isolate::GetData(uint32_t slot) {
8148   typedef internal::Internals I;
8149   return I::GetEmbedderData(this, slot);
8150 }
8151
8152
8153 uint32_t Isolate::GetNumberOfDataSlots() {
8154   typedef internal::Internals I;
8155   return I::kNumIsolateDataSlots;
8156 }
8157
8158
8159 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
8160     int64_t change_in_bytes) {
8161   typedef internal::Internals I;
8162   int64_t* amount_of_external_allocated_memory =
8163       reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
8164                                  I::kAmountOfExternalAllocatedMemoryOffset);
8165   int64_t* amount_of_external_allocated_memory_at_last_global_gc =
8166       reinterpret_cast<int64_t*>(
8167           reinterpret_cast<uint8_t*>(this) +
8168           I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
8169   int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
8170   if (change_in_bytes > 0 &&
8171       amount - *amount_of_external_allocated_memory_at_last_global_gc >
8172           I::kExternalAllocationLimit) {
8173     ReportExternalAllocationLimitReached();
8174   }
8175   *amount_of_external_allocated_memory = amount;
8176   return *amount_of_external_allocated_memory;
8177 }
8178
8179
8180 template<typename T>
8181 void Isolate::SetObjectGroupId(const Persistent<T>& object,
8182                                UniqueId id) {
8183   TYPE_CHECK(Value, T);
8184   SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
8185 }
8186
8187
8188 template<typename T>
8189 void Isolate::SetReferenceFromGroup(UniqueId id,
8190                                     const Persistent<T>& object) {
8191   TYPE_CHECK(Value, T);
8192   SetReferenceFromGroup(id,
8193                         reinterpret_cast<v8::internal::Object**>(object.val_));
8194 }
8195
8196
8197 template<typename T, typename S>
8198 void Isolate::SetReference(const Persistent<T>& parent,
8199                            const Persistent<S>& child) {
8200   TYPE_CHECK(Object, T);
8201   TYPE_CHECK(Value, S);
8202   SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
8203                reinterpret_cast<v8::internal::Object**>(child.val_));
8204 }
8205
8206
8207 Local<Value> Context::GetEmbedderData(int index) {
8208 #ifndef V8_ENABLE_CHECKS
8209   typedef internal::Object O;
8210   typedef internal::HeapObject HO;
8211   typedef internal::Internals I;
8212   HO* context = *reinterpret_cast<HO**>(this);
8213   O** result =
8214       HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
8215   return Local<Value>(reinterpret_cast<Value*>(result));
8216 #else
8217   return SlowGetEmbedderData(index);
8218 #endif
8219 }
8220
8221
8222 void* Context::GetAlignedPointerFromEmbedderData(int index) {
8223 #ifndef V8_ENABLE_CHECKS
8224   typedef internal::Internals I;
8225   return I::ReadEmbedderData<void*>(this, index);
8226 #else
8227   return SlowGetAlignedPointerFromEmbedderData(index);
8228 #endif
8229 }
8230
8231
8232 void V8::SetAllowCodeGenerationFromStringsCallback(
8233     AllowCodeGenerationFromStringsCallback callback) {
8234   Isolate* isolate = Isolate::GetCurrent();
8235   isolate->SetAllowCodeGenerationFromStringsCallback(callback);
8236 }
8237
8238
8239 bool V8::IsDead() {
8240   Isolate* isolate = Isolate::GetCurrent();
8241   return isolate->IsDead();
8242 }
8243
8244
8245 bool V8::AddMessageListener(MessageCallback that, Local<Value> data) {
8246   Isolate* isolate = Isolate::GetCurrent();
8247   return isolate->AddMessageListener(that, data);
8248 }
8249
8250
8251 void V8::RemoveMessageListeners(MessageCallback that) {
8252   Isolate* isolate = Isolate::GetCurrent();
8253   isolate->RemoveMessageListeners(that);
8254 }
8255
8256
8257 void V8::SetFailedAccessCheckCallbackFunction(
8258     FailedAccessCheckCallback callback) {
8259   Isolate* isolate = Isolate::GetCurrent();
8260   isolate->SetFailedAccessCheckCallbackFunction(callback);
8261 }
8262
8263
8264 void V8::SetCaptureStackTraceForUncaughtExceptions(
8265     bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
8266   Isolate* isolate = Isolate::GetCurrent();
8267   isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
8268                                                      options);
8269 }
8270
8271
8272 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
8273   Isolate* isolate = Isolate::GetCurrent();
8274   isolate->SetFatalErrorHandler(callback);
8275 }
8276
8277
8278 void V8::RemoveGCPrologueCallback(GCCallback callback) {
8279   Isolate* isolate = Isolate::GetCurrent();
8280   isolate->RemoveGCPrologueCallback(
8281       reinterpret_cast<v8::Isolate::GCCallback>(callback));
8282 }
8283
8284
8285 void V8::RemoveGCEpilogueCallback(GCCallback callback) {
8286   Isolate* isolate = Isolate::GetCurrent();
8287   isolate->RemoveGCEpilogueCallback(
8288       reinterpret_cast<v8::Isolate::GCCallback>(callback));
8289 }
8290
8291
8292 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
8293                                      ObjectSpace space,
8294                                      AllocationAction action) {
8295   Isolate* isolate = Isolate::GetCurrent();
8296   isolate->AddMemoryAllocationCallback(callback, space, action);
8297 }
8298
8299
8300 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
8301   Isolate* isolate = Isolate::GetCurrent();
8302   isolate->RemoveMemoryAllocationCallback(callback);
8303 }
8304
8305
8306 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
8307
8308
8309 bool V8::IsExecutionTerminating(Isolate* isolate) {
8310   if (isolate == NULL) {
8311     isolate = Isolate::GetCurrent();
8312   }
8313   return isolate->IsExecutionTerminating();
8314 }
8315
8316
8317 void V8::CancelTerminateExecution(Isolate* isolate) {
8318   isolate->CancelTerminateExecution();
8319 }
8320
8321
8322 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
8323   Isolate* isolate = Isolate::GetCurrent();
8324   isolate->VisitExternalResources(visitor);
8325 }
8326
8327
8328 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
8329   Isolate* isolate = Isolate::GetCurrent();
8330   isolate->VisitHandlesWithClassIds(visitor);
8331 }
8332
8333
8334 void V8::VisitHandlesWithClassIds(Isolate* isolate,
8335                                   PersistentHandleVisitor* visitor) {
8336   isolate->VisitHandlesWithClassIds(visitor);
8337 }
8338
8339
8340 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
8341                                           PersistentHandleVisitor* visitor) {
8342   isolate->VisitHandlesForPartialDependence(visitor);
8343 }
8344
8345 /**
8346  * \example shell.cc
8347  * A simple shell that takes a list of expressions on the
8348  * command-line and executes them.
8349  */
8350
8351
8352 /**
8353  * \example process.cc
8354  */
8355
8356
8357 }  // namespace v8
8358
8359
8360 #undef TYPE_CHECK
8361
8362
8363 #endif  // V8_H_