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