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