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