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