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