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