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