[V8] Allow access to the calling script data
[profile/ivi/qtjsbackend.git] / src / 3rdparty / v8 / include / v8.h
1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 /** \mainpage V8 API Reference Guide
29  *
30  * V8 is Google's open source JavaScript engine.
31  *
32  * This set of documents provides reference material generated from the
33  * V8 header file, include/v8.h.
34  *
35  * For other documentation see http://code.google.com/apis/v8/
36  */
37
38 #ifndef V8_H_
39 #define V8_H_
40
41 #include "v8stdint.h"
42
43 #ifdef _WIN32
44
45 // Setup for Windows DLL export/import. When building the V8 DLL the
46 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
47 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
48 // static library or building a program which uses the V8 static library neither
49 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
50 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
51 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
52   build configuration to ensure that at most one of these is set
53 #endif
54
55 #ifdef BUILDING_V8_SHARED
56 #define V8EXPORT __declspec(dllexport)
57 #elif USING_V8_SHARED
58 #define V8EXPORT __declspec(dllimport)
59 #else
60 #define V8EXPORT
61 #endif  // BUILDING_V8_SHARED
62
63 #else  // _WIN32
64
65 // Setup for Linux shared library export. There is no need to distinguish
66 // between building or using the V8 shared library, but we should not
67 // export symbols when we are building a static library.
68 #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
69 #define V8EXPORT __attribute__ ((visibility("default")))
70 #else  // defined(__GNUC__) && (__GNUC__ >= 4)
71 #define V8EXPORT
72 #endif  // defined(__GNUC__) && (__GNUC__ >= 4)
73
74 #endif  // _WIN32
75
76 /**
77  * The v8 JavaScript engine.
78  */
79 namespace v8 {
80
81 class Context;
82 class String;
83 class StringObject;
84 class Value;
85 class Utils;
86 class Number;
87 class NumberObject;
88 class Object;
89 class Array;
90 class Int32;
91 class Uint32;
92 class External;
93 class Primitive;
94 class Boolean;
95 class BooleanObject;
96 class Integer;
97 class Function;
98 class Date;
99 class ImplementationUtilities;
100 class Signature;
101 template <class T> class Handle;
102 template <class T> class Local;
103 template <class T> class Persistent;
104 class FunctionTemplate;
105 class ObjectTemplate;
106 class Data;
107 class AccessorInfo;
108 class StackTrace;
109 class StackFrame;
110
111 namespace internal {
112
113 class Arguments;
114 class Object;
115 class Heap;
116 class HeapObject;
117 class Isolate;
118 }
119
120
121 // --- Weak Handles ---
122
123
124 /**
125  * A weak reference callback function.
126  *
127  * This callback should either explicitly invoke Dispose on |object| if
128  * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak.
129  *
130  * \param object the weak global object to be reclaimed by the garbage collector
131  * \param parameter the value passed in when making the weak global object
132  */
133 typedef void (*WeakReferenceCallback)(Persistent<Value> object,
134                                       void* parameter);
135
136
137 // --- Handles ---
138
139 #define TYPE_CHECK(T, S)                                       \
140   while (false) {                                              \
141     *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);      \
142   }
143
144 /**
145  * An object reference managed by the v8 garbage collector.
146  *
147  * All objects returned from v8 have to be tracked by the garbage
148  * collector so that it knows that the objects are still alive.  Also,
149  * because the garbage collector may move objects, it is unsafe to
150  * point directly to an object.  Instead, all objects are stored in
151  * handles which are known by the garbage collector and updated
152  * whenever an object moves.  Handles should always be passed by value
153  * (except in cases like out-parameters) and they should never be
154  * allocated on the heap.
155  *
156  * There are two types of handles: local and persistent handles.
157  * Local handles are light-weight and transient and typically used in
158  * local operations.  They are managed by HandleScopes.  Persistent
159  * handles can be used when storing objects across several independent
160  * operations and have to be explicitly deallocated when they're no
161  * longer used.
162  *
163  * It is safe to extract the object stored in the handle by
164  * dereferencing the handle (for instance, to extract the Object* from
165  * a Handle<Object>); the value will still be governed by a handle
166  * behind the scenes and the same rules apply to these values as to
167  * their handles.
168  */
169 template <class T> class Handle {
170  public:
171   /**
172    * Creates an empty handle.
173    */
174   inline Handle() : val_(0) {}
175
176   /**
177    * Creates a new handle for the specified value.
178    */
179   inline explicit Handle(T* val) : val_(val) {}
180
181   /**
182    * Creates a handle for the contents of the specified handle.  This
183    * constructor allows you to pass handles as arguments by value and
184    * to assign between handles.  However, if you try to assign between
185    * incompatible handles, for instance from a Handle<String> to a
186    * Handle<Number> it will cause a compile-time error.  Assigning
187    * between compatible handles, for instance assigning a
188    * Handle<String> to a variable declared as Handle<Value>, is legal
189    * because String is a subclass of Value.
190    */
191   template <class S> inline Handle(Handle<S> that)
192       : val_(reinterpret_cast<T*>(*that)) {
193     /**
194      * This check fails when trying to convert between incompatible
195      * handles. For example, converting from a Handle<String> to a
196      * Handle<Number>.
197      */
198     TYPE_CHECK(T, S);
199   }
200
201   /**
202    * Returns true if the handle is empty.
203    */
204   inline bool IsEmpty() const { return val_ == 0; }
205
206   /**
207    * Sets the handle to be empty. IsEmpty() will then return true.
208    */
209   inline void Clear() { val_ = 0; }
210
211   inline T* operator->() const { return val_; }
212
213   inline T* operator*() const { return val_; }
214
215   /**
216    * Checks whether two handles are the same.
217    * Returns true if both are empty, or if the objects
218    * to which they refer are identical.
219    * The handles' references are not checked.
220    */
221   template <class S> inline bool operator==(Handle<S> that) const {
222     internal::Object** a = reinterpret_cast<internal::Object**>(**this);
223     internal::Object** b = reinterpret_cast<internal::Object**>(*that);
224     if (a == 0) return b == 0;
225     if (b == 0) return false;
226     return *a == *b;
227   }
228
229   /**
230    * Checks whether two handles are different.
231    * Returns true if only one of the handles is empty, or if
232    * the objects to which they refer are different.
233    * The handles' references are not checked.
234    */
235   template <class S> inline bool operator!=(Handle<S> that) const {
236     return !operator==(that);
237   }
238
239   template <class S> static inline Handle<T> Cast(Handle<S> that) {
240 #ifdef V8_ENABLE_CHECKS
241     // If we're going to perform the type check then we have to check
242     // that the handle isn't empty before doing the checked cast.
243     if (that.IsEmpty()) return Handle<T>();
244 #endif
245     return Handle<T>(T::Cast(*that));
246   }
247
248   template <class S> inline Handle<S> As() {
249     return Handle<S>::Cast(*this);
250   }
251
252  private:
253   T* val_;
254 };
255
256
257 /**
258  * A light-weight stack-allocated object handle.  All operations
259  * that return objects from within v8 return them in local handles.  They
260  * are created within HandleScopes, and all local handles allocated within a
261  * handle scope are destroyed when the handle scope is destroyed.  Hence it
262  * is not necessary to explicitly deallocate local handles.
263  */
264 template <class T> class Local : public Handle<T> {
265  public:
266   inline Local();
267   template <class S> inline Local(Local<S> that)
268       : Handle<T>(reinterpret_cast<T*>(*that)) {
269     /**
270      * This check fails when trying to convert between incompatible
271      * handles. For example, converting from a Handle<String> to a
272      * Handle<Number>.
273      */
274     TYPE_CHECK(T, S);
275   }
276   template <class S> inline Local(S* that) : Handle<T>(that) { }
277   template <class S> static inline Local<T> Cast(Local<S> that) {
278 #ifdef V8_ENABLE_CHECKS
279     // If we're going to perform the type check then we have to check
280     // that the handle isn't empty before doing the checked cast.
281     if (that.IsEmpty()) return Local<T>();
282 #endif
283     return Local<T>(T::Cast(*that));
284   }
285
286   template <class S> inline Local<S> As() {
287     return Local<S>::Cast(*this);
288   }
289
290   /** Create a local handle for the content of another handle.
291    *  The referee is kept alive by the local handle even when
292    *  the original handle is destroyed/disposed.
293    */
294   inline static Local<T> New(Handle<T> that);
295 };
296
297
298 /**
299  * An object reference that is independent of any handle scope.  Where
300  * a Local handle only lives as long as the HandleScope in which it was
301  * allocated, a Persistent handle remains valid until it is explicitly
302  * disposed.
303  *
304  * A persistent handle contains a reference to a storage cell within
305  * the v8 engine which holds an object value and which is updated by
306  * the garbage collector whenever the object is moved.  A new storage
307  * cell can be created using Persistent::New and existing handles can
308  * be disposed using Persistent::Dispose.  Since persistent handles
309  * are passed by value you may have many persistent handle objects
310  * that point to the same storage cell.  For instance, if you pass a
311  * persistent handle as an argument to a function you will not get two
312  * different storage cells but rather two references to the same
313  * storage cell.
314  */
315 template <class T> class Persistent : public Handle<T> {
316  public:
317   /**
318    * Creates an empty persistent handle that doesn't point to any
319    * storage cell.
320    */
321   inline Persistent();
322
323   /**
324    * Creates a persistent handle for the same storage cell as the
325    * specified handle.  This constructor allows you to pass persistent
326    * handles as arguments by value and to assign between persistent
327    * handles.  However, attempting to assign between incompatible
328    * persistent handles, for instance from a Persistent<String> to a
329    * Persistent<Number> will cause a compile-time error.  Assigning
330    * between compatible persistent handles, for instance assigning a
331    * Persistent<String> to a variable declared as Persistent<Value>,
332    * is allowed as String is a subclass of Value.
333    */
334   template <class S> inline Persistent(Persistent<S> that)
335       : Handle<T>(reinterpret_cast<T*>(*that)) {
336     /**
337      * This check fails when trying to convert between incompatible
338      * handles. For example, converting from a Handle<String> to a
339      * Handle<Number>.
340      */
341     TYPE_CHECK(T, S);
342   }
343
344   template <class S> inline Persistent(S* that) : Handle<T>(that) { }
345
346   /**
347    * "Casts" a plain handle which is known to be a persistent handle
348    * to a persistent handle.
349    */
350   template <class S> explicit inline Persistent(Handle<S> that)
351       : Handle<T>(*that) { }
352
353   template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
354 #ifdef V8_ENABLE_CHECKS
355     // If we're going to perform the type check then we have to check
356     // that the handle isn't empty before doing the checked cast.
357     if (that.IsEmpty()) return Persistent<T>();
358 #endif
359     return Persistent<T>(T::Cast(*that));
360   }
361
362   template <class S> inline Persistent<S> As() {
363     return Persistent<S>::Cast(*this);
364   }
365
366   /**
367    * Creates a new persistent handle for an existing local or
368    * persistent handle.
369    */
370   inline static Persistent<T> New(Handle<T> that);
371
372   /**
373    * Releases the storage cell referenced by this persistent handle.
374    * Does not remove the reference to the cell from any handles.
375    * This handle's reference, and any other references to the storage
376    * cell remain and IsEmpty will still return false.
377    */
378   inline void Dispose();
379
380   /**
381    * Make the reference to this object weak.  When only weak handles
382    * refer to the object, the garbage collector will perform a
383    * callback to the given V8::WeakReferenceCallback function, passing
384    * it the object reference and the given parameters.
385    */
386   inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
387
388   /** Clears the weak reference to this object.*/
389   inline void ClearWeak();
390
391   /**
392    * Marks the reference to this object independent. Garbage collector
393    * is free to ignore any object groups containing this object.
394    * Weak callback for an independent handle should not
395    * assume that it will be preceded by a global GC prologue callback
396    * or followed by a global GC epilogue callback.
397    */
398   inline void MarkIndependent();
399
400   /**
401    *Checks if the handle holds the only reference to an object.
402    */
403   inline bool IsNearDeath() const;
404
405   /**
406    * Returns true if the handle's reference is weak.
407    */
408   inline bool IsWeak() const;
409
410   /**
411    * Assigns a wrapper class ID to the handle. See RetainedObjectInfo
412    * interface description in v8-profiler.h for details.
413    */
414   inline void SetWrapperClassId(uint16_t class_id);
415
416  private:
417   friend class ImplementationUtilities;
418   friend class ObjectTemplate;
419 };
420
421
422  /**
423  * A stack-allocated class that governs a number of local handles.
424  * After a handle scope has been created, all local handles will be
425  * allocated within that handle scope until either the handle scope is
426  * deleted or another handle scope is created.  If there is already a
427  * handle scope and a new one is created, all allocations will take
428  * place in the new handle scope until it is deleted.  After that,
429  * new handles will again be allocated in the original handle scope.
430  *
431  * After the handle scope of a local handle has been deleted the
432  * garbage collector will no longer track the object stored in the
433  * handle and may deallocate it.  The behavior of accessing a handle
434  * for which the handle scope has been deleted is undefined.
435  */
436 class V8EXPORT HandleScope {
437  public:
438   HandleScope();
439
440   ~HandleScope();
441
442   /**
443    * Closes the handle scope and returns the value as a handle in the
444    * previous scope, which is the new current scope after the call.
445    */
446   template <class T> Local<T> Close(Handle<T> value);
447
448   /**
449    * Counts the number of allocated handles.
450    */
451   static int NumberOfHandles();
452
453   /**
454    * Creates a new handle with the given value.
455    */
456   static internal::Object** CreateHandle(internal::Object* value);
457   // Faster version, uses HeapObject to obtain the current Isolate.
458   static internal::Object** CreateHandle(internal::HeapObject* value);
459
460  private:
461   // Make it impossible to create heap-allocated or illegal handle
462   // scopes by disallowing certain operations.
463   HandleScope(const HandleScope&);
464   void operator=(const HandleScope&);
465   void* operator new(size_t size);
466   void operator delete(void*, size_t);
467
468   // This Data class is accessible internally as HandleScopeData through a
469   // typedef in the ImplementationUtilities class.
470   class V8EXPORT Data {
471    public:
472     internal::Object** next;
473     internal::Object** limit;
474     int level;
475     inline void Initialize() {
476       next = limit = NULL;
477       level = 0;
478     }
479   };
480
481   void Leave();
482
483   internal::Isolate* isolate_;
484   internal::Object** prev_next_;
485   internal::Object** prev_limit_;
486
487   // Allow for the active closing of HandleScopes which allows to pass a handle
488   // from the HandleScope being closed to the next top most HandleScope.
489   bool is_closed_;
490   internal::Object** RawClose(internal::Object** value);
491
492   friend class ImplementationUtilities;
493 };
494
495
496 // --- Special objects ---
497
498
499 /**
500  * The superclass of values and API object templates.
501  */
502 class V8EXPORT Data {
503  private:
504   Data();
505 };
506
507
508 /**
509  * Pre-compilation data that can be associated with a script.  This
510  * data can be calculated for a script in advance of actually
511  * compiling it, and can be stored between compilations.  When script
512  * data is given to the compile method compilation will be faster.
513  */
514 class V8EXPORT ScriptData {  // NOLINT
515  public:
516   virtual ~ScriptData() { }
517
518   /**
519    * Pre-compiles the specified script (context-independent).
520    *
521    * \param input Pointer to UTF-8 script source code.
522    * \param length Length of UTF-8 script source code.
523    */
524   static ScriptData* PreCompile(const char* input, int length);
525
526   /**
527    * Pre-compiles the specified script (context-independent).
528    *
529    * NOTE: Pre-compilation using this method cannot happen on another thread
530    * without using Lockers.
531    *
532    * \param source Script source code.
533    */
534   static ScriptData* PreCompile(Handle<String> source);
535
536   /**
537    * Load previous pre-compilation data.
538    *
539    * \param data Pointer to data returned by a call to Data() of a previous
540    *   ScriptData. Ownership is not transferred.
541    * \param length Length of data.
542    */
543   static ScriptData* New(const char* data, int length);
544
545   /**
546    * Returns the length of Data().
547    */
548   virtual int Length() = 0;
549
550   /**
551    * Returns a serialized representation of this ScriptData that can later be
552    * passed to New(). NOTE: Serialized data is platform-dependent.
553    */
554   virtual const char* Data() = 0;
555
556   /**
557    * Returns true if the source code could not be parsed.
558    */
559   virtual bool HasError() = 0;
560 };
561
562
563 /**
564  * The origin, within a file, of a script.
565  */
566 class ScriptOrigin {
567  public:
568   inline ScriptOrigin(
569       Handle<Value> resource_name,
570       Handle<Integer> resource_line_offset = Handle<Integer>(),
571       Handle<Integer> resource_column_offset = Handle<Integer>())
572       : resource_name_(resource_name),
573         resource_line_offset_(resource_line_offset),
574         resource_column_offset_(resource_column_offset) { }
575   inline Handle<Value> ResourceName() const;
576   inline Handle<Integer> ResourceLineOffset() const;
577   inline Handle<Integer> ResourceColumnOffset() const;
578  private:
579   Handle<Value> resource_name_;
580   Handle<Integer> resource_line_offset_;
581   Handle<Integer> resource_column_offset_;
582 };
583
584
585 /**
586  * A compiled JavaScript script.
587  */
588 class V8EXPORT Script {
589  public:
590   enum CompileFlags {
591       Default = 0x00,
592       QmlMode = 0x01
593   };
594
595   /**
596    * Compiles the specified script (context-independent).
597    *
598    * \param source Script source code.
599    * \param origin Script origin, owned by caller, no references are kept
600    *   when New() returns
601    * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
602    *   using pre_data speeds compilation if it's done multiple times.
603    *   Owned by caller, no references are kept when New() returns.
604    * \param script_data Arbitrary data associated with script. Using
605    *   this has same effect as calling SetData(), but allows data to be
606    *   available to compile event handlers.
607    * \return Compiled script object (context independent; when run it
608    *   will use the currently entered context).
609    */
610   static Local<Script> New(Handle<String> source,
611                            ScriptOrigin* origin = NULL,
612                            ScriptData* pre_data = NULL,
613                            Handle<String> script_data = Handle<String>(),
614                            CompileFlags = Default);
615
616   /**
617    * Compiles the specified script using the specified file name
618    * object (typically a string) as the script's origin.
619    *
620    * \param source Script source code.
621    * \param file_name file name object (typically a string) to be used
622    *   as the script's origin.
623    * \return Compiled script object (context independent; when run it
624    *   will use the currently entered context).
625    */
626   static Local<Script> New(Handle<String> source,
627                            Handle<Value> file_name,
628                            CompileFlags = Default);
629
630   /**
631    * Compiles the specified script (bound to current context).
632    *
633    * \param source Script source code.
634    * \param origin Script origin, owned by caller, no references are kept
635    *   when Compile() returns
636    * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
637    *   using pre_data speeds compilation if it's done multiple times.
638    *   Owned by caller, no references are kept when Compile() returns.
639    * \param script_data Arbitrary data associated with script. Using
640    *   this has same effect as calling SetData(), but makes data available
641    *   earlier (i.e. to compile event handlers).
642    * \return Compiled script object, bound to the context that was active
643    *   when this function was called.  When run it will always use this
644    *   context.
645    */
646   static Local<Script> Compile(Handle<String> source,
647                                ScriptOrigin* origin = NULL,
648                                ScriptData* pre_data = NULL,
649                                Handle<String> script_data = Handle<String>(),
650                                CompileFlags = Default);
651
652   /**
653    * Compiles the specified script using the specified file name
654    * object (typically a string) as the script's origin.
655    *
656    * \param source Script source code.
657    * \param file_name File name to use as script's origin
658    * \param script_data Arbitrary data associated with script. Using
659    *   this has same effect as calling SetData(), but makes data available
660    *   earlier (i.e. to compile event handlers).
661    * \return Compiled script object, bound to the context that was active
662    *   when this function was called.  When run it will always use this
663    *   context.
664    */
665   static Local<Script> Compile(Handle<String> source,
666                                Handle<Value> file_name,
667                                Handle<String> script_data = Handle<String>(),
668                                CompileFlags = Default);
669
670   /**
671    * Runs the script returning the resulting value.  If the script is
672    * context independent (created using ::New) it will be run in the
673    * currently entered context.  If it is context specific (created
674    * using ::Compile) it will be run in the context in which it was
675    * compiled.
676    */
677   Local<Value> Run();
678   Local<Value> Run(Handle<Object> qml);
679
680   /**
681    * Returns the script id value.
682    */
683   Local<Value> Id();
684
685   /**
686    * Associate an additional data object with the script. This is mainly used
687    * with the debugger as this data object is only available through the
688    * debugger API.
689    */
690   void SetData(Handle<String> data);
691 };
692
693
694 /**
695  * An error message.
696  */
697 class V8EXPORT Message {
698  public:
699   Local<String> Get() const;
700   Local<String> GetSourceLine() const;
701
702   /**
703    * Returns the resource name for the script from where the function causing
704    * the error originates.
705    */
706   Handle<Value> GetScriptResourceName() const;
707
708   /**
709    * Returns the resource data for the script from where the function causing
710    * the error originates.
711    */
712   Handle<Value> GetScriptData() const;
713
714   /**
715    * Exception stack trace. By default stack traces are not captured for
716    * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
717    * to change this option.
718    */
719   Handle<StackTrace> GetStackTrace() const;
720
721   /**
722    * Returns the number, 1-based, of the line where the error occurred.
723    */
724   int GetLineNumber() const;
725
726   /**
727    * Returns the index within the script of the first character where
728    * the error occurred.
729    */
730   int GetStartPosition() const;
731
732   /**
733    * Returns the index within the script of the last character where
734    * the error occurred.
735    */
736   int GetEndPosition() const;
737
738   /**
739    * Returns the index within the line of the first character where
740    * the error occurred.
741    */
742   int GetStartColumn() const;
743
744   /**
745    * Returns the index within the line of the last character where
746    * the error occurred.
747    */
748   int GetEndColumn() const;
749
750   // TODO(1245381): Print to a string instead of on a FILE.
751   static void PrintCurrentStackTrace(FILE* out);
752
753   static const int kNoLineNumberInfo = 0;
754   static const int kNoColumnInfo = 0;
755 };
756
757
758 /**
759  * Representation of a JavaScript stack trace. The information collected is a
760  * snapshot of the execution stack and the information remains valid after
761  * execution continues.
762  */
763 class V8EXPORT StackTrace {
764  public:
765   /**
766    * Flags that determine what information is placed captured for each
767    * StackFrame when grabbing the current stack trace.
768    */
769   enum StackTraceOptions {
770     kLineNumber = 1,
771     kColumnOffset = 1 << 1 | kLineNumber,
772     kScriptName = 1 << 2,
773     kFunctionName = 1 << 3,
774     kIsEval = 1 << 4,
775     kIsConstructor = 1 << 5,
776     kScriptNameOrSourceURL = 1 << 6,
777     kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
778     kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
779   };
780
781   /**
782    * Returns a StackFrame at a particular index.
783    */
784   Local<StackFrame> GetFrame(uint32_t index) const;
785
786   /**
787    * Returns the number of StackFrames.
788    */
789   int GetFrameCount() const;
790
791   /**
792    * Returns StackTrace as a v8::Array that contains StackFrame objects.
793    */
794   Local<Array> AsArray();
795
796   /**
797    * Grab a snapshot of the current JavaScript execution stack.
798    *
799    * \param frame_limit The maximum number of stack frames we want to capture.
800    * \param options Enumerates the set of things we will capture for each
801    *   StackFrame.
802    */
803   static Local<StackTrace> CurrentStackTrace(
804       int frame_limit,
805       StackTraceOptions options = kOverview);
806 };
807
808
809 /**
810  * A single JavaScript stack frame.
811  */
812 class V8EXPORT StackFrame {
813  public:
814   /**
815    * Returns the number, 1-based, of the line for the associate function call.
816    * This method will return Message::kNoLineNumberInfo if it is unable to
817    * retrieve the line number, or if kLineNumber was not passed as an option
818    * when capturing the StackTrace.
819    */
820   int GetLineNumber() const;
821
822   /**
823    * Returns the 1-based column offset on the line for the associated function
824    * call.
825    * This method will return Message::kNoColumnInfo if it is unable to retrieve
826    * the column number, or if kColumnOffset was not passed as an option when
827    * capturing the StackTrace.
828    */
829   int GetColumn() const;
830
831   /**
832    * Returns the name of the resource that contains the script for the
833    * function for this StackFrame.
834    */
835   Local<String> GetScriptName() const;
836
837   /**
838    * Returns the name of the resource that contains the script for the
839    * function for this StackFrame or sourceURL value if the script name
840    * is undefined and its source ends with //@ sourceURL=... string.
841    */
842   Local<String> GetScriptNameOrSourceURL() const;
843
844   /**
845    * Returns the name of the function associated with this stack frame.
846    */
847   Local<String> GetFunctionName() const;
848
849   /**
850    * Returns whether or not the associated function is compiled via a call to
851    * eval().
852    */
853   bool IsEval() const;
854
855   /**
856    * Returns whether or not the associated function is called as a
857    * constructor via "new".
858    */
859   bool IsConstructor() const;
860 };
861
862
863 // --- Value ---
864
865
866 /**
867  * The superclass of all JavaScript values and objects.
868  */
869 class Value : public Data {
870  public:
871   /**
872    * Returns true if this value is the undefined value.  See ECMA-262
873    * 4.3.10.
874    */
875   V8EXPORT bool IsUndefined() const;
876
877   /**
878    * Returns true if this value is the null value.  See ECMA-262
879    * 4.3.11.
880    */
881   V8EXPORT bool IsNull() const;
882
883    /**
884    * Returns true if this value is true.
885    */
886   V8EXPORT bool IsTrue() const;
887
888   /**
889    * Returns true if this value is false.
890    */
891   V8EXPORT bool IsFalse() const;
892
893   /**
894    * Returns true if this value is an instance of the String type.
895    * See ECMA-262 8.4.
896    */
897   inline bool IsString() const;
898
899   /**
900    * Returns true if this value is a function.
901    */
902   V8EXPORT bool IsFunction() const;
903
904   /**
905    * Returns true if this value is an array.
906    */
907   V8EXPORT bool IsArray() const;
908
909   /**
910    * Returns true if this value is an object.
911    */
912   V8EXPORT bool IsObject() const;
913
914   /**
915    * Returns true if this value is boolean.
916    */
917   V8EXPORT bool IsBoolean() const;
918
919   /**
920    * Returns true if this value is a number.
921    */
922   V8EXPORT bool IsNumber() const;
923
924   /**
925    * Returns true if this value is external.
926    */
927   V8EXPORT bool IsExternal() const;
928
929   /**
930    * Returns true if this value is a 32-bit signed integer.
931    */
932   V8EXPORT bool IsInt32() const;
933
934   /**
935    * Returns true if this value is a 32-bit unsigned integer.
936    */
937   V8EXPORT bool IsUint32() const;
938
939   /**
940    * Returns true if this value is a Date.
941    */
942   V8EXPORT bool IsDate() const;
943
944   /**
945    * Returns true if this value is a Boolean object.
946    */
947   V8EXPORT bool IsBooleanObject() const;
948
949   /**
950    * Returns true if this value is a Number object.
951    */
952   V8EXPORT bool IsNumberObject() const;
953
954   /**
955    * Returns true if this value is a String object.
956    */
957   V8EXPORT bool IsStringObject() const;
958
959   /**
960    * Returns true if this value is a NativeError.
961    */
962   V8EXPORT bool IsNativeError() const;
963
964   /**
965    * Returns true if this value is a RegExp.
966    */
967   V8EXPORT bool IsRegExp() const;
968
969   V8EXPORT Local<Boolean> ToBoolean() const;
970   V8EXPORT Local<Number> ToNumber() const;
971   V8EXPORT Local<String> ToString() const;
972   V8EXPORT Local<String> ToDetailString() const;
973   V8EXPORT Local<Object> ToObject() const;
974   V8EXPORT Local<Integer> ToInteger() const;
975   V8EXPORT Local<Uint32> ToUint32() const;
976   V8EXPORT Local<Int32> ToInt32() const;
977
978   /**
979    * Attempts to convert a string to an array index.
980    * Returns an empty handle if the conversion fails.
981    */
982   V8EXPORT Local<Uint32> ToArrayIndex() const;
983
984   V8EXPORT bool BooleanValue() const;
985   V8EXPORT double NumberValue() const;
986   V8EXPORT int64_t IntegerValue() const;
987   V8EXPORT uint32_t Uint32Value() const;
988   V8EXPORT int32_t Int32Value() const;
989
990   /** JS == */
991   V8EXPORT bool Equals(Handle<Value> that) const;
992   V8EXPORT bool StrictEquals(Handle<Value> that) const;
993
994  private:
995   inline bool QuickIsString() const;
996   V8EXPORT bool FullIsString() const;
997 };
998
999
1000 /**
1001  * The superclass of primitive values.  See ECMA-262 4.3.2.
1002  */
1003 class Primitive : public Value { };
1004
1005
1006 /**
1007  * A primitive boolean value (ECMA-262, 4.3.14).  Either the true
1008  * or false value.
1009  */
1010 class Boolean : public Primitive {
1011  public:
1012   V8EXPORT bool Value() const;
1013   static inline Handle<Boolean> New(bool value);
1014 };
1015
1016
1017 /**
1018  * A JavaScript string value (ECMA-262, 4.3.17).
1019  */
1020 class String : public Primitive {
1021  public:
1022   /**
1023    * Returns the number of characters in this string.
1024    */
1025   V8EXPORT int Length() const;
1026
1027   /**
1028    * Returns the number of bytes in the UTF-8 encoded
1029    * representation of this string.
1030    */
1031   V8EXPORT int Utf8Length() const;
1032
1033   /**
1034    * Returns the hash of this string.
1035    */
1036   V8EXPORT uint32_t Hash() const;
1037
1038   struct CompleteHashData {
1039     CompleteHashData() : length(0), hash(0), symbol_id(0) {}
1040     int length;
1041     uint32_t hash;
1042     uint32_t symbol_id;
1043   };
1044
1045   /**
1046    * Returns the "complete" hash of the string.  This is 
1047    * all the information about the string needed to implement
1048    * a very efficient hash keyed on the string.
1049    *
1050    * The members of CompleteHashData are:
1051    *    length: The length of the string.  Equivalent to Length()
1052    *    hash: The hash of the string.  Equivalent to Hash()
1053    *    symbol_id: If the string is a sequential symbol, the symbol
1054    *        id, otherwise 0.  If the symbol ids of two strings are 
1055    *        the same (and non-zero) the two strings are identical.
1056    *        If the symbol ids are different the strings may still be
1057    *        identical, but an Equals() check must be performed.
1058    */
1059   V8EXPORT CompleteHashData CompleteHash() const;
1060
1061   /**
1062    * Compute a hash value for the passed UTF16 string
1063    * data.
1064    */
1065   V8EXPORT static uint32_t ComputeHash(uint16_t *string, int length);
1066   V8EXPORT static uint32_t ComputeHash(char *string, int length);
1067
1068   /**
1069    * Returns true if this string is equal to the external
1070    * string data provided.
1071    */
1072   V8EXPORT bool Equals(uint16_t *string, int length);
1073   V8EXPORT bool Equals(char *string, int length);
1074   inline bool Equals(Handle<Value> that) const { return v8::Value::Equals(that); }
1075
1076   /**
1077    * Write the contents of the string to an external buffer.
1078    * If no arguments are given, expects the buffer to be large
1079    * enough to hold the entire string and NULL terminator. Copies
1080    * the contents of the string and the NULL terminator into the
1081    * buffer.
1082    *
1083    * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1084    * before the end of the buffer.
1085    *
1086    * Copies up to length characters into the output buffer.
1087    * Only null-terminates if there is enough space in the buffer.
1088    *
1089    * \param buffer The buffer into which the string will be copied.
1090    * \param start The starting position within the string at which
1091    * copying begins.
1092    * \param length The number of characters to copy from the string.  For
1093    *    WriteUtf8 the number of bytes in the buffer.
1094    * \param nchars_ref The number of characters written, can be NULL.
1095    * \param options Various options that might affect performance of this or
1096    *    subsequent operations.
1097    * \return The number of characters copied to the buffer excluding the null
1098    *    terminator.  For WriteUtf8: The number of bytes copied to the buffer
1099    *    including the null terminator (if written).
1100    */
1101   enum WriteOptions {
1102     NO_OPTIONS = 0,
1103     HINT_MANY_WRITES_EXPECTED = 1,
1104     NO_NULL_TERMINATION = 2
1105   };
1106
1107   V8EXPORT uint16_t GetCharacter(int index);
1108
1109   // 16-bit character codes.
1110   V8EXPORT int Write(uint16_t* buffer,
1111                      int start = 0,
1112                      int length = -1,
1113                      int options = NO_OPTIONS) const;
1114   // ASCII characters.
1115   V8EXPORT int WriteAscii(char* buffer,
1116                           int start = 0,
1117                           int length = -1,
1118                           int options = NO_OPTIONS) const;
1119   // UTF-8 encoded characters.
1120   V8EXPORT int WriteUtf8(char* buffer,
1121                          int length = -1,
1122                          int* nchars_ref = NULL,
1123                          int options = NO_OPTIONS) const;
1124
1125   /**
1126    * A zero length string.
1127    */
1128   V8EXPORT static v8::Local<v8::String> Empty();
1129
1130   /**
1131    * Returns true if the string is external
1132    */
1133   V8EXPORT bool IsExternal() const;
1134
1135   /**
1136    * Returns true if the string is both external and ASCII
1137    */
1138   V8EXPORT bool IsExternalAscii() const;
1139
1140   class V8EXPORT ExternalStringResourceBase {  // NOLINT
1141    public:
1142     virtual ~ExternalStringResourceBase() {}
1143
1144    protected:
1145     ExternalStringResourceBase() {}
1146
1147     /**
1148      * Internally V8 will call this Dispose method when the external string
1149      * resource is no longer needed. The default implementation will use the
1150      * delete operator. This method can be overridden in subclasses to
1151      * control how allocated external string resources are disposed.
1152      */
1153     virtual void Dispose() { delete this; }
1154
1155    private:
1156     // Disallow copying and assigning.
1157     ExternalStringResourceBase(const ExternalStringResourceBase&);
1158     void operator=(const ExternalStringResourceBase&);
1159
1160     friend class v8::internal::Heap;
1161   };
1162
1163   /**
1164    * An ExternalStringResource is a wrapper around a two-byte string
1165    * buffer that resides outside V8's heap. Implement an
1166    * ExternalStringResource to manage the life cycle of the underlying
1167    * buffer.  Note that the string data must be immutable.
1168    */
1169   class V8EXPORT ExternalStringResource
1170       : public ExternalStringResourceBase {
1171    public:
1172     /**
1173      * Override the destructor to manage the life cycle of the underlying
1174      * buffer.
1175      */
1176     virtual ~ExternalStringResource() {}
1177
1178     /**
1179      * The string data from the underlying buffer.
1180      */
1181     virtual const uint16_t* data() const = 0;
1182
1183     /**
1184      * The length of the string. That is, the number of two-byte characters.
1185      */
1186     virtual size_t length() const = 0;
1187
1188    protected:
1189     ExternalStringResource() {}
1190   };
1191
1192   /**
1193    * An ExternalAsciiStringResource is a wrapper around an ASCII
1194    * string buffer that resides outside V8's heap. Implement an
1195    * ExternalAsciiStringResource to manage the life cycle of the
1196    * underlying buffer.  Note that the string data must be immutable
1197    * and that the data must be strict (7-bit) ASCII, not Latin-1 or
1198    * UTF-8, which would require special treatment internally in the
1199    * engine and, in the case of UTF-8, do not allow efficient indexing.
1200    * Use String::New or convert to 16 bit data for non-ASCII.
1201    */
1202
1203   class V8EXPORT ExternalAsciiStringResource
1204       : public ExternalStringResourceBase {
1205    public:
1206     /**
1207      * Override the destructor to manage the life cycle of the underlying
1208      * buffer.
1209      */
1210     virtual ~ExternalAsciiStringResource() {}
1211     /** The string data from the underlying buffer.*/
1212     virtual const char* data() const = 0;
1213     /** The number of ASCII characters in the string.*/
1214     virtual size_t length() const = 0;
1215    protected:
1216     ExternalAsciiStringResource() {}
1217   };
1218
1219   /**
1220    * Get the ExternalStringResource for an external string.  Returns
1221    * NULL if IsExternal() doesn't return true.
1222    */
1223   inline ExternalStringResource* GetExternalStringResource() const;
1224
1225   /**
1226    * Get the ExternalAsciiStringResource for an external ASCII string.
1227    * Returns NULL if IsExternalAscii() doesn't return true.
1228    */
1229   V8EXPORT const ExternalAsciiStringResource* GetExternalAsciiStringResource()
1230       const;
1231
1232   static inline String* Cast(v8::Value* obj);
1233
1234   /**
1235    * Allocates a new string from either UTF-8 encoded or ASCII data.
1236    * The second parameter 'length' gives the buffer length.
1237    * If the data is UTF-8 encoded, the caller must
1238    * be careful to supply the length parameter.
1239    * If it is not given, the function calls
1240    * 'strlen' to determine the buffer length, it might be
1241    * wrong if 'data' contains a null character.
1242    */
1243   V8EXPORT static Local<String> New(const char* data, int length = -1);
1244
1245   /** Allocates a new string from 16-bit character codes.*/
1246   V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
1247
1248   /** Creates a symbol. Returns one if it exists already.*/
1249   V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
1250
1251   /**
1252    * Creates a new string by concatenating the left and the right strings
1253    * passed in as parameters.
1254    */
1255   V8EXPORT static Local<String> Concat(Handle<String> left,
1256                                        Handle<String>right);
1257
1258   /**
1259    * Creates a new external string using the data defined in the given
1260    * resource. When the external string is no longer live on V8's heap the
1261    * resource will be disposed by calling its Dispose method. The caller of
1262    * this function should not otherwise delete or modify the resource. Neither
1263    * should the underlying buffer be deallocated or modified except through the
1264    * destructor of the external string resource.
1265    */
1266   V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
1267
1268   /**
1269    * Associate an external string resource with this string by transforming it
1270    * in place so that existing references to this string in the JavaScript heap
1271    * will use the external string resource. The external string resource's
1272    * character contents need to be equivalent to this string.
1273    * Returns true if the string has been changed to be an external string.
1274    * The string is not modified if the operation fails. See NewExternal for
1275    * information on the lifetime of the resource.
1276    */
1277   V8EXPORT bool MakeExternal(ExternalStringResource* resource);
1278
1279   /**
1280    * Creates a new external string using the ASCII data defined in the given
1281    * resource. When the external string is no longer live on V8's heap the
1282    * resource will be disposed by calling its Dispose method. The caller of
1283    * this function should not otherwise delete or modify the resource. Neither
1284    * should the underlying buffer be deallocated or modified except through the
1285    * destructor of the external string resource.
1286    */
1287   V8EXPORT static Local<String> NewExternal(
1288       ExternalAsciiStringResource* resource);
1289
1290   /**
1291    * Associate an external string resource with this string by transforming it
1292    * in place so that existing references to this string in the JavaScript heap
1293    * will use the external string resource. The external string resource's
1294    * character contents need to be equivalent to this string.
1295    * Returns true if the string has been changed to be an external string.
1296    * The string is not modified if the operation fails. See NewExternal for
1297    * information on the lifetime of the resource.
1298    */
1299   V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
1300
1301   /**
1302    * Returns true if this string can be made external.
1303    */
1304   V8EXPORT bool CanMakeExternal();
1305
1306   /** Creates an undetectable string from the supplied ASCII or UTF-8 data.*/
1307   V8EXPORT static Local<String> NewUndetectable(const char* data,
1308                                                 int length = -1);
1309
1310   /** Creates an undetectable string from the supplied 16-bit character codes.*/
1311   V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1312                                                 int length = -1);
1313
1314   /**
1315    * Converts an object to a UTF-8-encoded character array.  Useful if
1316    * you want to print the object.  If conversion to a string fails
1317    * (e.g. due to an exception in the toString() method of the object)
1318    * then the length() method returns 0 and the * operator returns
1319    * NULL.
1320    */
1321   class V8EXPORT Utf8Value {
1322    public:
1323     explicit Utf8Value(Handle<v8::Value> obj);
1324     ~Utf8Value();
1325     char* operator*() { return str_; }
1326     const char* operator*() const { return str_; }
1327     int length() const { return length_; }
1328    private:
1329     char* str_;
1330     int length_;
1331
1332     // Disallow copying and assigning.
1333     Utf8Value(const Utf8Value&);
1334     void operator=(const Utf8Value&);
1335   };
1336
1337   /**
1338    * Converts an object to an ASCII string.
1339    * Useful if you want to print the object.
1340    * If conversion to a string fails (eg. due to an exception in the toString()
1341    * method of the object) then the length() method returns 0 and the * operator
1342    * returns NULL.
1343    */
1344   class V8EXPORT AsciiValue {
1345    public:
1346     explicit AsciiValue(Handle<v8::Value> obj);
1347     ~AsciiValue();
1348     char* operator*() { return str_; }
1349     const char* operator*() const { return str_; }
1350     int length() const { return length_; }
1351    private:
1352     char* str_;
1353     int length_;
1354
1355     // Disallow copying and assigning.
1356     AsciiValue(const AsciiValue&);
1357     void operator=(const AsciiValue&);
1358   };
1359
1360   /**
1361    * Converts an object to a two-byte string.
1362    * If conversion to a string fails (eg. due to an exception in the toString()
1363    * method of the object) then the length() method returns 0 and the * operator
1364    * returns NULL.
1365    */
1366   class V8EXPORT Value {
1367    public:
1368     explicit Value(Handle<v8::Value> obj);
1369     ~Value();
1370     uint16_t* operator*() { return str_; }
1371     const uint16_t* operator*() const { return str_; }
1372     int length() const { return length_; }
1373    private:
1374     uint16_t* str_;
1375     int length_;
1376
1377     // Disallow copying and assigning.
1378     Value(const Value&);
1379     void operator=(const Value&);
1380   };
1381
1382  private:
1383   V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1384   V8EXPORT static void CheckCast(v8::Value* obj);
1385 };
1386
1387
1388 /**
1389  * A JavaScript number value (ECMA-262, 4.3.20)
1390  */
1391 class Number : public Primitive {
1392  public:
1393   V8EXPORT double Value() const;
1394   V8EXPORT static Local<Number> New(double value);
1395   static inline Number* Cast(v8::Value* obj);
1396  private:
1397   V8EXPORT Number();
1398   V8EXPORT static void CheckCast(v8::Value* obj);
1399 };
1400
1401
1402 /**
1403  * A JavaScript value representing a signed integer.
1404  */
1405 class Integer : public Number {
1406  public:
1407   V8EXPORT static Local<Integer> New(int32_t value);
1408   V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1409   V8EXPORT int64_t Value() const;
1410   static inline Integer* Cast(v8::Value* obj);
1411  private:
1412   V8EXPORT Integer();
1413   V8EXPORT static void CheckCast(v8::Value* obj);
1414 };
1415
1416
1417 /**
1418  * A JavaScript value representing a 32-bit signed integer.
1419  */
1420 class Int32 : public Integer {
1421  public:
1422   V8EXPORT int32_t Value() const;
1423  private:
1424   V8EXPORT Int32();
1425 };
1426
1427
1428 /**
1429  * A JavaScript value representing a 32-bit unsigned integer.
1430  */
1431 class Uint32 : public Integer {
1432  public:
1433   V8EXPORT uint32_t Value() const;
1434  private:
1435   V8EXPORT Uint32();
1436 };
1437
1438
1439 enum PropertyAttribute {
1440   None       = 0,
1441   ReadOnly   = 1 << 0,
1442   DontEnum   = 1 << 1,
1443   DontDelete = 1 << 2
1444 };
1445
1446 enum ExternalArrayType {
1447   kExternalByteArray = 1,
1448   kExternalUnsignedByteArray,
1449   kExternalShortArray,
1450   kExternalUnsignedShortArray,
1451   kExternalIntArray,
1452   kExternalUnsignedIntArray,
1453   kExternalFloatArray,
1454   kExternalDoubleArray,
1455   kExternalPixelArray
1456 };
1457
1458 /**
1459  * Accessor[Getter|Setter] are used as callback functions when
1460  * setting|getting a particular property. See Object and ObjectTemplate's
1461  * method SetAccessor.
1462  */
1463 typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1464                                         const AccessorInfo& info);
1465
1466
1467 typedef void (*AccessorSetter)(Local<String> property,
1468                                Local<Value> value,
1469                                const AccessorInfo& info);
1470
1471
1472 /**
1473  * Access control specifications.
1474  *
1475  * Some accessors should be accessible across contexts.  These
1476  * accessors have an explicit access control parameter which specifies
1477  * the kind of cross-context access that should be allowed.
1478  *
1479  * Additionally, for security, accessors can prohibit overwriting by
1480  * accessors defined in JavaScript.  For objects that have such
1481  * accessors either locally or in their prototype chain it is not
1482  * possible to overwrite the accessor by using __defineGetter__ or
1483  * __defineSetter__ from JavaScript code.
1484  */
1485 enum AccessControl {
1486   DEFAULT               = 0,
1487   ALL_CAN_READ          = 1,
1488   ALL_CAN_WRITE         = 1 << 1,
1489   PROHIBITS_OVERWRITING = 1 << 2
1490 };
1491
1492
1493 /**
1494  * A JavaScript object (ECMA-262, 4.3.3)
1495  */
1496 class Object : public Value {
1497  public:
1498   V8EXPORT bool Set(Handle<Value> key,
1499                     Handle<Value> value,
1500                     PropertyAttribute attribs = None);
1501
1502   V8EXPORT bool Set(uint32_t index,
1503                     Handle<Value> value);
1504
1505   // Sets a local property on this object bypassing interceptors and
1506   // overriding accessors or read-only properties.
1507   //
1508   // Note that if the object has an interceptor the property will be set
1509   // locally, but since the interceptor takes precedence the local property
1510   // will only be returned if the interceptor doesn't return a value.
1511   //
1512   // Note also that this only works for named properties.
1513   V8EXPORT bool ForceSet(Handle<Value> key,
1514                          Handle<Value> value,
1515                          PropertyAttribute attribs = None);
1516
1517   V8EXPORT Local<Value> Get(Handle<Value> key);
1518
1519   V8EXPORT Local<Value> Get(uint32_t index);
1520
1521   /**
1522    * Gets the property attributes of a property which can be None or
1523    * any combination of ReadOnly, DontEnum and DontDelete. Returns
1524    * None when the property doesn't exist.
1525    */
1526   V8EXPORT PropertyAttribute GetPropertyAttributes(Handle<Value> key);
1527
1528   // TODO(1245389): Replace the type-specific versions of these
1529   // functions with generic ones that accept a Handle<Value> key.
1530   V8EXPORT bool Has(Handle<String> key);
1531
1532   V8EXPORT bool Delete(Handle<String> key);
1533
1534   // Delete a property on this object bypassing interceptors and
1535   // ignoring dont-delete attributes.
1536   V8EXPORT bool ForceDelete(Handle<Value> key);
1537
1538   V8EXPORT bool Has(uint32_t index);
1539
1540   V8EXPORT bool Delete(uint32_t index);
1541
1542   V8EXPORT bool SetAccessor(Handle<String> name,
1543                             AccessorGetter getter,
1544                             AccessorSetter setter = 0,
1545                             Handle<Value> data = Handle<Value>(),
1546                             AccessControl settings = DEFAULT,
1547                             PropertyAttribute attribute = None);
1548
1549   /**
1550    * Returns an array containing the names of the enumerable properties
1551    * of this object, including properties from prototype objects.  The
1552    * array returned by this method contains the same values as would
1553    * be enumerated by a for-in statement over this object.
1554    */
1555   V8EXPORT Local<Array> GetPropertyNames();
1556
1557   /**
1558    * This function has the same functionality as GetPropertyNames but
1559    * the returned array doesn't contain the names of properties from
1560    * prototype objects.
1561    */
1562   V8EXPORT Local<Array> GetOwnPropertyNames();
1563
1564   /**
1565    * Get the prototype object.  This does not skip objects marked to
1566    * be skipped by __proto__ and it does not consult the security
1567    * handler.
1568    */
1569   V8EXPORT Local<Value> GetPrototype();
1570
1571   /**
1572    * Set the prototype object.  This does not skip objects marked to
1573    * be skipped by __proto__ and it does not consult the security
1574    * handler.
1575    */
1576   V8EXPORT bool SetPrototype(Handle<Value> prototype);
1577
1578   /**
1579    * Finds an instance of the given function template in the prototype
1580    * chain.
1581    */
1582   V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1583       Handle<FunctionTemplate> tmpl);
1584
1585   /**
1586    * Call builtin Object.prototype.toString on this object.
1587    * This is different from Value::ToString() that may call
1588    * user-defined toString function. This one does not.
1589    */
1590   V8EXPORT Local<String> ObjectProtoToString();
1591
1592   /**
1593    * Returns the name of the function invoked as a constructor for this object.
1594    */
1595   V8EXPORT Local<String> GetConstructorName();
1596
1597   /** Gets the number of internal fields for this Object. */
1598   V8EXPORT int InternalFieldCount();
1599   /** Gets the value in an internal field. */
1600   inline Local<Value> GetInternalField(int index);
1601   /** Sets the value in an internal field. */
1602   V8EXPORT void SetInternalField(int index, Handle<Value> value);
1603
1604   /** Gets a native pointer from an internal field. */
1605   inline void* GetPointerFromInternalField(int index);
1606
1607   /** Sets a native pointer in an internal field. */
1608   V8EXPORT void SetPointerInInternalField(int index, void* value);
1609
1610   class V8EXPORT ExternalResource { // NOLINT
1611    public:
1612     ExternalResource() {}
1613     virtual ~ExternalResource() {}
1614
1615    protected:
1616     virtual void Dispose() { delete this; }
1617
1618    private:
1619     // Disallow copying and assigning.
1620     ExternalResource(const ExternalResource&);
1621     void operator=(const ExternalResource&);
1622
1623     friend class v8::internal::Heap;
1624   };
1625
1626   V8EXPORT void SetExternalResource(ExternalResource *);
1627   V8EXPORT ExternalResource *GetExternalResource();
1628
1629   // Testers for local properties.
1630   V8EXPORT bool HasOwnProperty(Handle<String> key);
1631   V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1632   V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1633   V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
1634
1635   /**
1636    * If result.IsEmpty() no real property was located in the prototype chain.
1637    * This means interceptors in the prototype chain are not called.
1638    */
1639   V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1640       Handle<String> key);
1641
1642   /**
1643    * If result.IsEmpty() no real property was located on the object or
1644    * in the prototype chain.
1645    * This means interceptors in the prototype chain are not called.
1646    */
1647   V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
1648
1649   /** Tests for a named lookup interceptor.*/
1650   V8EXPORT bool HasNamedLookupInterceptor();
1651
1652   /** Tests for an index lookup interceptor.*/
1653   V8EXPORT bool HasIndexedLookupInterceptor();
1654
1655   /**
1656    * Turns on access check on the object if the object is an instance of
1657    * a template that has access check callbacks. If an object has no
1658    * access check info, the object cannot be accessed by anyone.
1659    */
1660   V8EXPORT void TurnOnAccessCheck();
1661
1662   /**
1663    * Returns the identity hash for this object. The current implementation
1664    * uses a hidden property on the object to store the identity hash.
1665    *
1666    * The return value will never be 0. Also, it is not guaranteed to be
1667    * unique.
1668    */
1669   V8EXPORT int GetIdentityHash();
1670
1671   /**
1672    * Access hidden properties on JavaScript objects. These properties are
1673    * hidden from the executing JavaScript and only accessible through the V8
1674    * C++ API. Hidden properties introduced by V8 internally (for example the
1675    * identity hash) are prefixed with "v8::".
1676    */
1677   V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1678   V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1679   V8EXPORT bool DeleteHiddenValue(Handle<String> key);
1680
1681   /**
1682    * Returns true if this is an instance of an api function (one
1683    * created from a function created from a function template) and has
1684    * been modified since it was created.  Note that this method is
1685    * conservative and may return true for objects that haven't actually
1686    * been modified.
1687    */
1688   V8EXPORT bool IsDirty();
1689
1690   /**
1691    * Clone this object with a fast but shallow copy.  Values will point
1692    * to the same values as the original object.
1693    */
1694   V8EXPORT Local<Object> Clone();
1695
1696   /**
1697    * Returns the context in which the object was created.
1698    */
1699   V8EXPORT Local<Context> CreationContext();
1700
1701   /**
1702    * Set the backing store of the indexed properties to be managed by the
1703    * embedding layer. Access to the indexed properties will follow the rules
1704    * spelled out in CanvasPixelArray.
1705    * Note: The embedding program still owns the data and needs to ensure that
1706    *       the backing store is preserved while V8 has a reference.
1707    */
1708   V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
1709   V8EXPORT bool HasIndexedPropertiesInPixelData();
1710   V8EXPORT uint8_t* GetIndexedPropertiesPixelData();
1711   V8EXPORT int GetIndexedPropertiesPixelDataLength();
1712
1713   /**
1714    * Set the backing store of the indexed properties to be managed by the
1715    * embedding layer. Access to the indexed properties will follow the rules
1716    * spelled out for the CanvasArray subtypes in the WebGL specification.
1717    * Note: The embedding program still owns the data and needs to ensure that
1718    *       the backing store is preserved while V8 has a reference.
1719    */
1720   V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1721       void* data,
1722       ExternalArrayType array_type,
1723       int number_of_elements);
1724   V8EXPORT bool HasIndexedPropertiesInExternalArrayData();
1725   V8EXPORT void* GetIndexedPropertiesExternalArrayData();
1726   V8EXPORT ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1727   V8EXPORT int GetIndexedPropertiesExternalArrayDataLength();
1728
1729   /**
1730    * Checks whether a callback is set by the
1731    * ObjectTemplate::SetCallAsFunctionHandler method.
1732    * When an Object is callable this method returns true.
1733    */
1734   V8EXPORT bool IsCallable();
1735
1736   /**
1737    * Call an Object as a function if a callback is set by the
1738    * ObjectTemplate::SetCallAsFunctionHandler method.
1739    */
1740   V8EXPORT Local<Value> CallAsFunction(Handle<Object> recv,
1741                                        int argc,
1742                                        Handle<Value> argv[]);
1743
1744   /**
1745    * Call an Object as a constructor if a callback is set by the
1746    * ObjectTemplate::SetCallAsFunctionHandler method.
1747    * Note: This method behaves like the Function::NewInstance method.
1748    */
1749   V8EXPORT Local<Value> CallAsConstructor(int argc,
1750                                           Handle<Value> argv[]);
1751
1752   V8EXPORT static Local<Object> New();
1753   static inline Object* Cast(Value* obj);
1754
1755  private:
1756   V8EXPORT Object();
1757   V8EXPORT static void CheckCast(Value* obj);
1758   V8EXPORT Local<Value> CheckedGetInternalField(int index);
1759   V8EXPORT void* SlowGetPointerFromInternalField(int index);
1760
1761   /**
1762    * If quick access to the internal field is possible this method
1763    * returns the value.  Otherwise an empty handle is returned.
1764    */
1765   inline Local<Value> UncheckedGetInternalField(int index);
1766 };
1767
1768
1769 /**
1770  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1771  */
1772 class Array : public Object {
1773  public:
1774   V8EXPORT uint32_t Length() const;
1775
1776   /**
1777    * Clones an element at index |index|.  Returns an empty
1778    * handle if cloning fails (for any reason).
1779    */
1780   V8EXPORT Local<Object> CloneElementAt(uint32_t index);
1781
1782   /**
1783    * Creates a JavaScript array with the given length. If the length
1784    * is negative the returned array will have length 0.
1785    */
1786   V8EXPORT static Local<Array> New(int length = 0);
1787
1788   static inline Array* Cast(Value* obj);
1789  private:
1790   V8EXPORT Array();
1791   V8EXPORT static void CheckCast(Value* obj);
1792 };
1793
1794
1795 /**
1796  * A JavaScript function object (ECMA-262, 15.3).
1797  */
1798 class Function : public Object {
1799  public:
1800   V8EXPORT Local<Object> NewInstance() const;
1801   V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1802   V8EXPORT Local<Value> Call(Handle<Object> recv,
1803                              int argc,
1804                              Handle<Value> argv[]);
1805   V8EXPORT void SetName(Handle<String> name);
1806   V8EXPORT Handle<Value> GetName() const;
1807
1808   /**
1809    * Returns zero based line number of function body and
1810    * kLineOffsetNotFound if no information available.
1811    */
1812   V8EXPORT int GetScriptLineNumber() const;
1813   V8EXPORT ScriptOrigin GetScriptOrigin() const;
1814   static inline Function* Cast(Value* obj);
1815   V8EXPORT static const int kLineOffsetNotFound;
1816  private:
1817   V8EXPORT Function();
1818   V8EXPORT static void CheckCast(Value* obj);
1819 };
1820
1821
1822 /**
1823  * An instance of the built-in Date constructor (ECMA-262, 15.9).
1824  */
1825 class Date : public Object {
1826  public:
1827   V8EXPORT static Local<Value> New(double time);
1828
1829   /**
1830    * A specialization of Value::NumberValue that is more efficient
1831    * because we know the structure of this object.
1832    */
1833   V8EXPORT double NumberValue() const;
1834
1835   static inline Date* Cast(v8::Value* obj);
1836
1837   /**
1838    * Notification that the embedder has changed the time zone,
1839    * daylight savings time, or other date / time configuration
1840    * parameters.  V8 keeps a cache of various values used for
1841    * date / time computation.  This notification will reset
1842    * those cached values for the current context so that date /
1843    * time configuration changes would be reflected in the Date
1844    * object.
1845    *
1846    * This API should not be called more than needed as it will
1847    * negatively impact the performance of date operations.
1848    */
1849   V8EXPORT static void DateTimeConfigurationChangeNotification();
1850
1851  private:
1852   V8EXPORT static void CheckCast(v8::Value* obj);
1853 };
1854
1855
1856 /**
1857  * A Number object (ECMA-262, 4.3.21).
1858  */
1859 class NumberObject : public Object {
1860  public:
1861   V8EXPORT static Local<Value> New(double value);
1862
1863   /**
1864    * Returns the Number held by the object.
1865    */
1866   V8EXPORT double NumberValue() const;
1867
1868   static inline NumberObject* Cast(v8::Value* obj);
1869
1870  private:
1871   V8EXPORT static void CheckCast(v8::Value* obj);
1872 };
1873
1874
1875 /**
1876  * A Boolean object (ECMA-262, 4.3.15).
1877  */
1878 class BooleanObject : public Object {
1879  public:
1880   V8EXPORT static Local<Value> New(bool value);
1881
1882   /**
1883    * Returns the Boolean held by the object.
1884    */
1885   V8EXPORT bool BooleanValue() const;
1886
1887   static inline BooleanObject* Cast(v8::Value* obj);
1888
1889  private:
1890   V8EXPORT static void CheckCast(v8::Value* obj);
1891 };
1892
1893
1894 /**
1895  * A String object (ECMA-262, 4.3.18).
1896  */
1897 class StringObject : public Object {
1898  public:
1899   V8EXPORT static Local<Value> New(Handle<String> value);
1900
1901   /**
1902    * Returns the String held by the object.
1903    */
1904   V8EXPORT Local<String> StringValue() const;
1905
1906   static inline StringObject* Cast(v8::Value* obj);
1907
1908  private:
1909   V8EXPORT static void CheckCast(v8::Value* obj);
1910 };
1911
1912
1913 /**
1914  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1915  */
1916 class RegExp : public Object {
1917  public:
1918   /**
1919    * Regular expression flag bits. They can be or'ed to enable a set
1920    * of flags.
1921    */
1922   enum Flags {
1923     kNone = 0,
1924     kGlobal = 1,
1925     kIgnoreCase = 2,
1926     kMultiline = 4
1927   };
1928
1929   /**
1930    * Creates a regular expression from the given pattern string and
1931    * the flags bit field. May throw a JavaScript exception as
1932    * described in ECMA-262, 15.10.4.1.
1933    *
1934    * For example,
1935    *   RegExp::New(v8::String::New("foo"),
1936    *               static_cast<RegExp::Flags>(kGlobal | kMultiline))
1937    * is equivalent to evaluating "/foo/gm".
1938    */
1939   V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1940                                     Flags flags);
1941
1942   /**
1943    * Returns the value of the source property: a string representing
1944    * the regular expression.
1945    */
1946   V8EXPORT Local<String> GetSource() const;
1947
1948   /**
1949    * Returns the flags bit field.
1950    */
1951   V8EXPORT Flags GetFlags() const;
1952
1953   static inline RegExp* Cast(v8::Value* obj);
1954
1955  private:
1956   V8EXPORT static void CheckCast(v8::Value* obj);
1957 };
1958
1959
1960 /**
1961  * A JavaScript value that wraps a C++ void*.  This type of value is
1962  * mainly used to associate C++ data structures with JavaScript
1963  * objects.
1964  *
1965  * The Wrap function V8 will return the most optimal Value object wrapping the
1966  * C++ void*. The type of the value is not guaranteed to be an External object
1967  * and no assumptions about its type should be made. To access the wrapped
1968  * value Unwrap should be used, all other operations on that object will lead
1969  * to unpredictable results.
1970  */
1971 class External : public Value {
1972  public:
1973   V8EXPORT static Local<Value> Wrap(void* data);
1974   static inline void* Unwrap(Handle<Value> obj);
1975
1976   V8EXPORT static Local<External> New(void* value);
1977   static inline External* Cast(Value* obj);
1978   V8EXPORT void* Value() const;
1979  private:
1980   V8EXPORT External();
1981   V8EXPORT static void CheckCast(v8::Value* obj);
1982   static inline void* QuickUnwrap(Handle<v8::Value> obj);
1983   V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
1984 };
1985
1986
1987 // --- Templates ---
1988
1989
1990 /**
1991  * The superclass of object and function templates.
1992  */
1993 class V8EXPORT Template : public Data {
1994  public:
1995   /** Adds a property to each instance created by this template.*/
1996   void Set(Handle<String> name, Handle<Data> value,
1997            PropertyAttribute attributes = None);
1998   inline void Set(const char* name, Handle<Data> value);
1999  private:
2000   Template();
2001
2002   friend class ObjectTemplate;
2003   friend class FunctionTemplate;
2004 };
2005
2006
2007 /**
2008  * The argument information given to function call callbacks.  This
2009  * class provides access to information about the context of the call,
2010  * including the receiver, the number and values of arguments, and
2011  * the holder of the function.
2012  */
2013 class Arguments {
2014  public:
2015   inline int Length() const;
2016   inline Local<Value> operator[](int i) const;
2017   inline Local<Function> Callee() const;
2018   inline Local<Object> This() const;
2019   inline Local<Object> Holder() const;
2020   inline bool IsConstructCall() const;
2021   inline Local<Value> Data() const;
2022  private:
2023   static const int kDataIndex = 0;
2024   static const int kCalleeIndex = -1;
2025   static const int kHolderIndex = -2;
2026
2027   friend class ImplementationUtilities;
2028   inline Arguments(internal::Object** implicit_args,
2029                    internal::Object** values,
2030                    int length,
2031                    bool is_construct_call);
2032   internal::Object** implicit_args_;
2033   internal::Object** values_;
2034   int length_;
2035   bool is_construct_call_;
2036 };
2037
2038
2039 /**
2040  * The information passed to an accessor callback about the context
2041  * of the property access.
2042  */
2043 class V8EXPORT AccessorInfo {
2044  public:
2045   inline AccessorInfo(internal::Object** args)
2046       : args_(args) { }
2047   inline Local<Value> Data() const;
2048   inline Local<Object> This() const;
2049   inline Local<Object> Holder() const;
2050  private:
2051   internal::Object** args_;
2052 };
2053
2054
2055 typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
2056
2057 /**
2058  * NamedProperty[Getter|Setter] are used as interceptors on object.
2059  * See ObjectTemplate::SetNamedPropertyHandler.
2060  */
2061 typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
2062                                              const AccessorInfo& info);
2063
2064
2065 /**
2066  * Returns the value if the setter intercepts the request.
2067  * Otherwise, returns an empty handle.
2068  */
2069 typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
2070                                              Local<Value> value,
2071                                              const AccessorInfo& info);
2072
2073 /**
2074  * Returns a non-empty handle if the interceptor intercepts the request.
2075  * The result is an integer encoding property attributes (like v8::None,
2076  * v8::DontEnum, etc.)
2077  */
2078 typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
2079                                               const AccessorInfo& info);
2080
2081
2082 /**
2083  * Returns a non-empty handle if the deleter intercepts the request.
2084  * The return value is true if the property could be deleted and false
2085  * otherwise.
2086  */
2087 typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
2088                                                 const AccessorInfo& info);
2089
2090 /**
2091  * Returns an array containing the names of the properties the named
2092  * property getter intercepts.
2093  */
2094 typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
2095
2096
2097 /**
2098  * Returns the value of the property if the getter intercepts the
2099  * request.  Otherwise, returns an empty handle.
2100  */
2101 typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
2102                                                const AccessorInfo& info);
2103
2104
2105 /**
2106  * Returns the value if the setter intercepts the request.
2107  * Otherwise, returns an empty handle.
2108  */
2109 typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
2110                                                Local<Value> value,
2111                                                const AccessorInfo& info);
2112
2113
2114 /**
2115  * Returns a non-empty handle if the interceptor intercepts the request.
2116  * The result is an integer encoding property attributes.
2117  */
2118 typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
2119                                                 const AccessorInfo& info);
2120
2121 /**
2122  * Returns a non-empty handle if the deleter intercepts the request.
2123  * The return value is true if the property could be deleted and false
2124  * otherwise.
2125  */
2126 typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
2127                                                   const AccessorInfo& info);
2128
2129 /**
2130  * Returns an array containing the indices of the properties the
2131  * indexed property getter intercepts.
2132  */
2133 typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
2134
2135
2136 /**
2137  * Access type specification.
2138  */
2139 enum AccessType {
2140   ACCESS_GET,
2141   ACCESS_SET,
2142   ACCESS_HAS,
2143   ACCESS_DELETE,
2144   ACCESS_KEYS
2145 };
2146
2147
2148 /**
2149  * Returns true if cross-context access should be allowed to the named
2150  * property with the given key on the host object.
2151  */
2152 typedef bool (*NamedSecurityCallback)(Local<Object> host,
2153                                       Local<Value> key,
2154                                       AccessType type,
2155                                       Local<Value> data);
2156
2157
2158 /**
2159  * Returns true if cross-context access should be allowed to the indexed
2160  * property with the given index on the host object.
2161  */
2162 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
2163                                         uint32_t index,
2164                                         AccessType type,
2165                                         Local<Value> data);
2166
2167
2168 /**
2169  * A FunctionTemplate is used to create functions at runtime. There
2170  * can only be one function created from a FunctionTemplate in a
2171  * context.  The lifetime of the created function is equal to the
2172  * lifetime of the context.  So in case the embedder needs to create
2173  * temporary functions that can be collected using Scripts is
2174  * preferred.
2175  *
2176  * A FunctionTemplate can have properties, these properties are added to the
2177  * function object when it is created.
2178  *
2179  * A FunctionTemplate has a corresponding instance template which is
2180  * used to create object instances when the function is used as a
2181  * constructor. Properties added to the instance template are added to
2182  * each object instance.
2183  *
2184  * A FunctionTemplate can have a prototype template. The prototype template
2185  * is used to create the prototype object of the function.
2186  *
2187  * The following example shows how to use a FunctionTemplate:
2188  *
2189  * \code
2190  *    v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
2191  *    t->Set("func_property", v8::Number::New(1));
2192  *
2193  *    v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
2194  *    proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
2195  *    proto_t->Set("proto_const", v8::Number::New(2));
2196  *
2197  *    v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
2198  *    instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
2199  *    instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
2200  *    instance_t->Set("instance_property", Number::New(3));
2201  *
2202  *    v8::Local<v8::Function> function = t->GetFunction();
2203  *    v8::Local<v8::Object> instance = function->NewInstance();
2204  * \endcode
2205  *
2206  * Let's use "function" as the JS variable name of the function object
2207  * and "instance" for the instance object created above.  The function
2208  * and the instance will have the following properties:
2209  *
2210  * \code
2211  *   func_property in function == true;
2212  *   function.func_property == 1;
2213  *
2214  *   function.prototype.proto_method() invokes 'InvokeCallback'
2215  *   function.prototype.proto_const == 2;
2216  *
2217  *   instance instanceof function == true;
2218  *   instance.instance_accessor calls 'InstanceAccessorCallback'
2219  *   instance.instance_property == 3;
2220  * \endcode
2221  *
2222  * A FunctionTemplate can inherit from another one by calling the
2223  * FunctionTemplate::Inherit method.  The following graph illustrates
2224  * the semantics of inheritance:
2225  *
2226  * \code
2227  *   FunctionTemplate Parent  -> Parent() . prototype -> { }
2228  *     ^                                                  ^
2229  *     | Inherit(Parent)                                  | .__proto__
2230  *     |                                                  |
2231  *   FunctionTemplate Child   -> Child()  . prototype -> { }
2232  * \endcode
2233  *
2234  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
2235  * object of the Child() function has __proto__ pointing to the
2236  * Parent() function's prototype object. An instance of the Child
2237  * function has all properties on Parent's instance templates.
2238  *
2239  * Let Parent be the FunctionTemplate initialized in the previous
2240  * section and create a Child FunctionTemplate by:
2241  *
2242  * \code
2243  *   Local<FunctionTemplate> parent = t;
2244  *   Local<FunctionTemplate> child = FunctionTemplate::New();
2245  *   child->Inherit(parent);
2246  *
2247  *   Local<Function> child_function = child->GetFunction();
2248  *   Local<Object> child_instance = child_function->NewInstance();
2249  * \endcode
2250  *
2251  * The Child function and Child instance will have the following
2252  * properties:
2253  *
2254  * \code
2255  *   child_func.prototype.__proto__ == function.prototype;
2256  *   child_instance.instance_accessor calls 'InstanceAccessorCallback'
2257  *   child_instance.instance_property == 3;
2258  * \endcode
2259  */
2260 class V8EXPORT FunctionTemplate : public Template {
2261  public:
2262   /** Creates a function template.*/
2263   static Local<FunctionTemplate> New(
2264       InvocationCallback callback = 0,
2265       Handle<Value> data = Handle<Value>(),
2266       Handle<Signature> signature = Handle<Signature>());
2267   /** Returns the unique function instance in the current execution context.*/
2268   Local<Function> GetFunction();
2269
2270   /**
2271    * Set the call-handler callback for a FunctionTemplate.  This
2272    * callback is called whenever the function created from this
2273    * FunctionTemplate is called.
2274    */
2275   void SetCallHandler(InvocationCallback callback,
2276                       Handle<Value> data = Handle<Value>());
2277
2278   /** Get the InstanceTemplate. */
2279   Local<ObjectTemplate> InstanceTemplate();
2280
2281   /** Causes the function template to inherit from a parent function template.*/
2282   void Inherit(Handle<FunctionTemplate> parent);
2283
2284   /**
2285    * A PrototypeTemplate is the template used to create the prototype object
2286    * of the function created by this template.
2287    */
2288   Local<ObjectTemplate> PrototypeTemplate();
2289
2290
2291   /**
2292    * Set the class name of the FunctionTemplate.  This is used for
2293    * printing objects created with the function created from the
2294    * FunctionTemplate as its constructor.
2295    */
2296   void SetClassName(Handle<String> name);
2297
2298   /**
2299    * Determines whether the __proto__ accessor ignores instances of
2300    * the function template.  If instances of the function template are
2301    * ignored, __proto__ skips all instances and instead returns the
2302    * next object in the prototype chain.
2303    *
2304    * Call with a value of true to make the __proto__ accessor ignore
2305    * instances of the function template.  Call with a value of false
2306    * to make the __proto__ accessor not ignore instances of the
2307    * function template.  By default, instances of a function template
2308    * are not ignored.
2309    */
2310   void SetHiddenPrototype(bool value);
2311
2312   /**
2313    * Sets the ReadOnly flag in the attributes of the 'prototype' property
2314    * of functions created from this FunctionTemplate to true.
2315    */
2316   void ReadOnlyPrototype();
2317
2318   /**
2319    * Returns true if the given object is an instance of this function
2320    * template.
2321    */
2322   bool HasInstance(Handle<Value> object);
2323
2324  private:
2325   FunctionTemplate();
2326   void AddInstancePropertyAccessor(Handle<String> name,
2327                                    AccessorGetter getter,
2328                                    AccessorSetter setter,
2329                                    Handle<Value> data,
2330                                    AccessControl settings,
2331                                    PropertyAttribute attributes);
2332   void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2333                                        NamedPropertySetter setter,
2334                                        NamedPropertyQuery query,
2335                                        NamedPropertyDeleter remover,
2336                                        NamedPropertyEnumerator enumerator,
2337                                        bool is_fallback,
2338                                        Handle<Value> data);
2339   void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2340                                          IndexedPropertySetter setter,
2341                                          IndexedPropertyQuery query,
2342                                          IndexedPropertyDeleter remover,
2343                                          IndexedPropertyEnumerator enumerator,
2344                                          Handle<Value> data);
2345   void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2346                                         Handle<Value> data);
2347
2348   friend class Context;
2349   friend class ObjectTemplate;
2350 };
2351
2352
2353 /**
2354  * An ObjectTemplate is used to create objects at runtime.
2355  *
2356  * Properties added to an ObjectTemplate are added to each object
2357  * created from the ObjectTemplate.
2358  */
2359 class V8EXPORT ObjectTemplate : public Template {
2360  public:
2361   /** Creates an ObjectTemplate. */
2362   static Local<ObjectTemplate> New();
2363
2364   /** Creates a new instance of this template.*/
2365   Local<Object> NewInstance();
2366
2367   /**
2368    * Sets an accessor on the object template.
2369    *
2370    * Whenever the property with the given name is accessed on objects
2371    * created from this ObjectTemplate the getter and setter callbacks
2372    * are called instead of getting and setting the property directly
2373    * on the JavaScript object.
2374    *
2375    * \param name The name of the property for which an accessor is added.
2376    * \param getter The callback to invoke when getting the property.
2377    * \param setter The callback to invoke when setting the property.
2378    * \param data A piece of data that will be passed to the getter and setter
2379    *   callbacks whenever they are invoked.
2380    * \param settings Access control settings for the accessor. This is a bit
2381    *   field consisting of one of more of
2382    *   DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2383    *   The default is to not allow cross-context access.
2384    *   ALL_CAN_READ means that all cross-context reads are allowed.
2385    *   ALL_CAN_WRITE means that all cross-context writes are allowed.
2386    *   The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2387    *   cross-context access.
2388    * \param attribute The attributes of the property for which an accessor
2389    *   is added.
2390    */
2391   void SetAccessor(Handle<String> name,
2392                    AccessorGetter getter,
2393                    AccessorSetter setter = 0,
2394                    Handle<Value> data = Handle<Value>(),
2395                    AccessControl settings = DEFAULT,
2396                    PropertyAttribute attribute = None);
2397
2398   /**
2399    * Sets a named property handler on the object template.
2400    *
2401    * Whenever a named property is accessed on objects created from
2402    * this object template, the provided callback is invoked instead of
2403    * accessing the property directly on the JavaScript object.
2404    *
2405    * \param getter The callback to invoke when getting a property.
2406    * \param setter The callback to invoke when setting a property.
2407    * \param query The callback to invoke to check if a property is present,
2408    *   and if present, get its attributes.
2409    * \param deleter The callback to invoke when deleting a property.
2410    * \param enumerator The callback to invoke to enumerate all the named
2411    *   properties of an object.
2412    * \param data A piece of data that will be passed to the callbacks
2413    *   whenever they are invoked.
2414    */
2415   void SetNamedPropertyHandler(NamedPropertyGetter getter,
2416                                NamedPropertySetter setter = 0,
2417                                NamedPropertyQuery query = 0,
2418                                NamedPropertyDeleter deleter = 0,
2419                                NamedPropertyEnumerator enumerator = 0,
2420                                Handle<Value> data = Handle<Value>());
2421   void SetFallbackPropertyHandler(NamedPropertyGetter getter,
2422                                   NamedPropertySetter setter = 0,
2423                                   NamedPropertyQuery query = 0,
2424                                   NamedPropertyDeleter deleter = 0,
2425                                   NamedPropertyEnumerator enumerator = 0,
2426                                   Handle<Value> data = Handle<Value>());
2427
2428   /**
2429    * Sets an indexed property handler on the object template.
2430    *
2431    * Whenever an indexed property is accessed on objects created from
2432    * this object template, the provided callback is invoked instead of
2433    * accessing the property directly on the JavaScript object.
2434    *
2435    * \param getter The callback to invoke when getting a property.
2436    * \param setter The callback to invoke when setting a property.
2437    * \param query The callback to invoke to check if an object has a property.
2438    * \param deleter The callback to invoke when deleting a property.
2439    * \param enumerator The callback to invoke to enumerate all the indexed
2440    *   properties of an object.
2441    * \param data A piece of data that will be passed to the callbacks
2442    *   whenever they are invoked.
2443    */
2444   void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2445                                  IndexedPropertySetter setter = 0,
2446                                  IndexedPropertyQuery query = 0,
2447                                  IndexedPropertyDeleter deleter = 0,
2448                                  IndexedPropertyEnumerator enumerator = 0,
2449                                  Handle<Value> data = Handle<Value>());
2450
2451   /**
2452    * Sets the callback to be used when calling instances created from
2453    * this template as a function.  If no callback is set, instances
2454    * behave like normal JavaScript objects that cannot be called as a
2455    * function.
2456    */
2457   void SetCallAsFunctionHandler(InvocationCallback callback,
2458                                 Handle<Value> data = Handle<Value>());
2459
2460   /**
2461    * Mark object instances of the template as undetectable.
2462    *
2463    * In many ways, undetectable objects behave as though they are not
2464    * there.  They behave like 'undefined' in conditionals and when
2465    * printed.  However, properties can be accessed and called as on
2466    * normal objects.
2467    */
2468   void MarkAsUndetectable();
2469
2470   /**
2471    * Sets access check callbacks on the object template.
2472    *
2473    * When accessing properties on instances of this object template,
2474    * the access check callback will be called to determine whether or
2475    * not to allow cross-context access to the properties.
2476    * The last parameter specifies whether access checks are turned
2477    * on by default on instances. If access checks are off by default,
2478    * they can be turned on on individual instances by calling
2479    * Object::TurnOnAccessCheck().
2480    */
2481   void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2482                                IndexedSecurityCallback indexed_handler,
2483                                Handle<Value> data = Handle<Value>(),
2484                                bool turned_on_by_default = true);
2485
2486   /**
2487    * Gets the number of internal fields for objects generated from
2488    * this template.
2489    */
2490   int InternalFieldCount();
2491
2492   /**
2493    * Sets the number of internal fields for objects generated from
2494    * this template.
2495    */
2496   void SetInternalFieldCount(int value);
2497
2498   /**
2499    * Sets whether the object can store an "external resource" object.
2500    */
2501   bool HasExternalResource();
2502   void SetHasExternalResource(bool value);
2503
2504  private:
2505   ObjectTemplate();
2506   static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2507   friend class FunctionTemplate;
2508 };
2509
2510
2511 /**
2512  * A Signature specifies which receivers and arguments a function can
2513  * legally be called with.
2514  */
2515 class V8EXPORT Signature : public Data {
2516  public:
2517   static Local<Signature> New(Handle<FunctionTemplate> receiver =
2518                                   Handle<FunctionTemplate>(),
2519                               int argc = 0,
2520                               Handle<FunctionTemplate> argv[] = 0);
2521  private:
2522   Signature();
2523 };
2524
2525
2526 /**
2527  * A utility for determining the type of objects based on the template
2528  * they were constructed from.
2529  */
2530 class V8EXPORT TypeSwitch : public Data {
2531  public:
2532   static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2533   static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2534   int match(Handle<Value> value);
2535  private:
2536   TypeSwitch();
2537 };
2538
2539
2540 // --- Extensions ---
2541
2542 class V8EXPORT ExternalAsciiStringResourceImpl
2543     : public String::ExternalAsciiStringResource {
2544  public:
2545   ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
2546   ExternalAsciiStringResourceImpl(const char* data, size_t length)
2547       : data_(data), length_(length) {}
2548   const char* data() const { return data_; }
2549   size_t length() const { return length_; }
2550
2551  private:
2552   const char* data_;
2553   size_t length_;
2554 };
2555
2556 /**
2557  * Ignore
2558  */
2559 class V8EXPORT Extension {  // NOLINT
2560  public:
2561   // Note that the strings passed into this constructor must live as long
2562   // as the Extension itself.
2563   Extension(const char* name,
2564             const char* source = 0,
2565             int dep_count = 0,
2566             const char** deps = 0,
2567             int source_length = -1);
2568   virtual ~Extension() { }
2569   virtual v8::Handle<v8::FunctionTemplate>
2570       GetNativeFunction(v8::Handle<v8::String> name) {
2571     return v8::Handle<v8::FunctionTemplate>();
2572   }
2573
2574   const char* name() const { return name_; }
2575   size_t source_length() const { return source_length_; }
2576   const String::ExternalAsciiStringResource* source() const {
2577     return &source_; }
2578   int dependency_count() { return dep_count_; }
2579   const char** dependencies() { return deps_; }
2580   void set_auto_enable(bool value) { auto_enable_ = value; }
2581   bool auto_enable() { return auto_enable_; }
2582
2583  private:
2584   const char* name_;
2585   size_t source_length_;  // expected to initialize before source_
2586   ExternalAsciiStringResourceImpl source_;
2587   int dep_count_;
2588   const char** deps_;
2589   bool auto_enable_;
2590
2591   // Disallow copying and assigning.
2592   Extension(const Extension&);
2593   void operator=(const Extension&);
2594 };
2595
2596
2597 void V8EXPORT RegisterExtension(Extension* extension);
2598
2599
2600 /**
2601  * Ignore
2602  */
2603 class V8EXPORT DeclareExtension {
2604  public:
2605   inline DeclareExtension(Extension* extension) {
2606     RegisterExtension(extension);
2607   }
2608 };
2609
2610
2611 // --- Statics ---
2612
2613
2614 Handle<Primitive> V8EXPORT Undefined();
2615 Handle<Primitive> V8EXPORT Null();
2616 Handle<Boolean> V8EXPORT True();
2617 Handle<Boolean> V8EXPORT False();
2618
2619
2620 /**
2621  * A set of constraints that specifies the limits of the runtime's memory use.
2622  * You must set the heap size before initializing the VM - the size cannot be
2623  * adjusted after the VM is initialized.
2624  *
2625  * If you are using threads then you should hold the V8::Locker lock while
2626  * setting the stack limit and you must set a non-default stack limit separately
2627  * for each thread.
2628  */
2629 class V8EXPORT ResourceConstraints {
2630  public:
2631   ResourceConstraints();
2632   int max_young_space_size() const { return max_young_space_size_; }
2633   void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2634   int max_old_space_size() const { return max_old_space_size_; }
2635   void set_max_old_space_size(int value) { max_old_space_size_ = value; }
2636   int max_executable_size() { return max_executable_size_; }
2637   void set_max_executable_size(int value) { max_executable_size_ = value; }
2638   uint32_t* stack_limit() const { return stack_limit_; }
2639   // Sets an address beyond which the VM's stack may not grow.
2640   void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2641  private:
2642   int max_young_space_size_;
2643   int max_old_space_size_;
2644   int max_executable_size_;
2645   uint32_t* stack_limit_;
2646 };
2647
2648
2649 bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
2650
2651
2652 // --- Exceptions ---
2653
2654
2655 typedef void (*FatalErrorCallback)(const char* location, const char* message);
2656
2657
2658 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2659
2660
2661 /**
2662  * Schedules an exception to be thrown when returning to JavaScript.  When an
2663  * exception has been scheduled it is illegal to invoke any JavaScript
2664  * operation; the caller must return immediately and only after the exception
2665  * has been handled does it become legal to invoke JavaScript operations.
2666  */
2667 Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2668
2669 /**
2670  * Create new error objects by calling the corresponding error object
2671  * constructor with the message.
2672  */
2673 class V8EXPORT Exception {
2674  public:
2675   static Local<Value> RangeError(Handle<String> message);
2676   static Local<Value> ReferenceError(Handle<String> message);
2677   static Local<Value> SyntaxError(Handle<String> message);
2678   static Local<Value> TypeError(Handle<String> message);
2679   static Local<Value> Error(Handle<String> message);
2680 };
2681
2682
2683 // --- Counters Callbacks ---
2684
2685 typedef int* (*CounterLookupCallback)(const char* name);
2686
2687 typedef void* (*CreateHistogramCallback)(const char* name,
2688                                          int min,
2689                                          int max,
2690                                          size_t buckets);
2691
2692 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2693
2694 // --- Memory Allocation Callback ---
2695   enum ObjectSpace {
2696     kObjectSpaceNewSpace = 1 << 0,
2697     kObjectSpaceOldPointerSpace = 1 << 1,
2698     kObjectSpaceOldDataSpace = 1 << 2,
2699     kObjectSpaceCodeSpace = 1 << 3,
2700     kObjectSpaceMapSpace = 1 << 4,
2701     kObjectSpaceLoSpace = 1 << 5,
2702
2703     kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2704       kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2705       kObjectSpaceLoSpace
2706   };
2707
2708   enum AllocationAction {
2709     kAllocationActionAllocate = 1 << 0,
2710     kAllocationActionFree = 1 << 1,
2711     kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2712   };
2713
2714 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2715                                          AllocationAction action,
2716                                          int size);
2717
2718 // --- Failed Access Check Callback ---
2719 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2720                                           AccessType type,
2721                                           Local<Value> data);
2722
2723 // --- AllowCodeGenerationFromStrings callbacks ---
2724
2725 /**
2726  * Callback to check if code generation from strings is allowed. See
2727  * Context::AllowCodeGenerationFromStrings.
2728  */
2729 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
2730
2731 // --- Garbage Collection Callbacks ---
2732
2733 /**
2734  * Applications can register callback functions which will be called
2735  * before and after a garbage collection.  Allocations are not
2736  * allowed in the callback functions, you therefore cannot manipulate
2737  * objects (set or delete properties for example) since it is possible
2738  * such operations will result in the allocation of objects.
2739  */
2740 enum GCType {
2741   kGCTypeScavenge = 1 << 0,
2742   kGCTypeMarkSweepCompact = 1 << 1,
2743   kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2744 };
2745
2746 enum GCCallbackFlags {
2747   kNoGCCallbackFlags = 0,
2748   kGCCallbackFlagCompacted = 1 << 0
2749 };
2750
2751 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2752 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2753
2754 typedef void (*GCCallback)();
2755
2756
2757 /**
2758  * Collection of V8 heap information.
2759  *
2760  * Instances of this class can be passed to v8::V8::HeapStatistics to
2761  * get heap statistics from V8.
2762  */
2763 class V8EXPORT HeapStatistics {
2764  public:
2765   HeapStatistics();
2766   size_t total_heap_size() { return total_heap_size_; }
2767   size_t total_heap_size_executable() { return total_heap_size_executable_; }
2768   size_t used_heap_size() { return used_heap_size_; }
2769   size_t heap_size_limit() { return heap_size_limit_; }
2770
2771  private:
2772   void set_total_heap_size(size_t size) { total_heap_size_ = size; }
2773   void set_total_heap_size_executable(size_t size) {
2774     total_heap_size_executable_ = size;
2775   }
2776   void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2777   void set_heap_size_limit(size_t size) { heap_size_limit_ = size; }
2778
2779   size_t total_heap_size_;
2780   size_t total_heap_size_executable_;
2781   size_t used_heap_size_;
2782   size_t heap_size_limit_;
2783
2784   friend class V8;
2785 };
2786
2787
2788 class RetainedObjectInfo;
2789
2790 /**
2791  * Isolate represents an isolated instance of the V8 engine.  V8
2792  * isolates have completely separate states.  Objects from one isolate
2793  * must not be used in other isolates.  When V8 is initialized a
2794  * default isolate is implicitly created and entered.  The embedder
2795  * can create additional isolates and use them in parallel in multiple
2796  * threads.  An isolate can be entered by at most one thread at any
2797  * given time.  The Locker/Unlocker API can be used to synchronize.
2798  */
2799 class V8EXPORT Isolate {
2800  public:
2801   /**
2802    * Stack-allocated class which sets the isolate for all operations
2803    * executed within a local scope.
2804    */
2805   class V8EXPORT Scope {
2806    public:
2807     explicit Scope(Isolate* isolate) : isolate_(isolate) {
2808       isolate->Enter();
2809     }
2810
2811     ~Scope() { isolate_->Exit(); }
2812
2813    private:
2814     Isolate* const isolate_;
2815
2816     // Prevent copying of Scope objects.
2817     Scope(const Scope&);
2818     Scope& operator=(const Scope&);
2819   };
2820
2821   /**
2822    * Creates a new isolate.  Does not change the currently entered
2823    * isolate.
2824    *
2825    * When an isolate is no longer used its resources should be freed
2826    * by calling Dispose().  Using the delete operator is not allowed.
2827    */
2828   static Isolate* New();
2829
2830   /**
2831    * Returns the entered isolate for the current thread or NULL in
2832    * case there is no current isolate.
2833    */
2834   static Isolate* GetCurrent();
2835
2836   /**
2837    * Methods below this point require holding a lock (using Locker) in
2838    * a multi-threaded environment.
2839    */
2840
2841   /**
2842    * Sets this isolate as the entered one for the current thread.
2843    * Saves the previously entered one (if any), so that it can be
2844    * restored when exiting.  Re-entering an isolate is allowed.
2845    */
2846   void Enter();
2847
2848   /**
2849    * Exits this isolate by restoring the previously entered one in the
2850    * current thread.  The isolate may still stay the same, if it was
2851    * entered more than once.
2852    *
2853    * Requires: this == Isolate::GetCurrent().
2854    */
2855   void Exit();
2856
2857   /**
2858    * Disposes the isolate.  The isolate must not be entered by any
2859    * thread to be disposable.
2860    */
2861   void Dispose();
2862
2863   /**
2864    * Associate embedder-specific data with the isolate
2865    */
2866   void SetData(void* data);
2867
2868   /**
2869    * Retrive embedder-specific data from the isolate.
2870    * Returns NULL if SetData has never been called.
2871    */
2872   void* GetData();
2873
2874  private:
2875   Isolate();
2876   Isolate(const Isolate&);
2877   ~Isolate();
2878   Isolate& operator=(const Isolate&);
2879   void* operator new(size_t size);
2880   void operator delete(void*, size_t);
2881 };
2882
2883
2884 class StartupData {
2885  public:
2886   enum CompressionAlgorithm {
2887     kUncompressed,
2888     kBZip2
2889   };
2890
2891   const char* data;
2892   int compressed_size;
2893   int raw_size;
2894 };
2895
2896
2897 /**
2898  * A helper class for driving V8 startup data decompression.  It is based on
2899  * "CompressedStartupData" API functions from the V8 class.  It isn't mandatory
2900  * for an embedder to use this class, instead, API functions can be used
2901  * directly.
2902  *
2903  * For an example of the class usage, see the "shell.cc" sample application.
2904  */
2905 class V8EXPORT StartupDataDecompressor {  // NOLINT
2906  public:
2907   StartupDataDecompressor();
2908   virtual ~StartupDataDecompressor();
2909   int Decompress();
2910
2911  protected:
2912   virtual int DecompressData(char* raw_data,
2913                              int* raw_data_size,
2914                              const char* compressed_data,
2915                              int compressed_data_size) = 0;
2916
2917  private:
2918   char** raw_data;
2919 };
2920
2921
2922 /**
2923  * EntropySource is used as a callback function when v8 needs a source
2924  * of entropy.
2925  */
2926 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
2927
2928 /**
2929  * Container class for static utility functions.
2930  */
2931 class V8EXPORT V8 {
2932  public:
2933   /** Set the callback to invoke in case of fatal errors. */
2934   static void SetFatalErrorHandler(FatalErrorCallback that);
2935
2936   /**
2937    * Set the callback to invoke to check if code generation from
2938    * strings should be allowed.
2939    */
2940   static void SetAllowCodeGenerationFromStringsCallback(
2941       AllowCodeGenerationFromStringsCallback that);
2942
2943   /**
2944    * Ignore out-of-memory exceptions.
2945    *
2946    * V8 running out of memory is treated as a fatal error by default.
2947    * This means that the fatal error handler is called and that V8 is
2948    * terminated.
2949    *
2950    * IgnoreOutOfMemoryException can be used to not treat an
2951    * out-of-memory situation as a fatal error.  This way, the contexts
2952    * that did not cause the out of memory problem might be able to
2953    * continue execution.
2954    */
2955   static void IgnoreOutOfMemoryException();
2956
2957   /**
2958    * Check if V8 is dead and therefore unusable.  This is the case after
2959    * fatal errors such as out-of-memory situations.
2960    */
2961   static bool IsDead();
2962
2963   /**
2964    * The following 4 functions are to be used when V8 is built with
2965    * the 'compress_startup_data' flag enabled. In this case, the
2966    * embedder must decompress startup data prior to initializing V8.
2967    *
2968    * This is how interaction with V8 should look like:
2969    *   int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
2970    *   v8::StartupData* compressed_data =
2971    *     new v8::StartupData[compressed_data_count];
2972    *   v8::V8::GetCompressedStartupData(compressed_data);
2973    *   ... decompress data (compressed_data can be updated in-place) ...
2974    *   v8::V8::SetDecompressedStartupData(compressed_data);
2975    *   ... now V8 can be initialized
2976    *   ... make sure the decompressed data stays valid until V8 shutdown
2977    *
2978    * A helper class StartupDataDecompressor is provided. It implements
2979    * the protocol of the interaction described above, and can be used in
2980    * most cases instead of calling these API functions directly.
2981    */
2982   static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
2983   static int GetCompressedStartupDataCount();
2984   static void GetCompressedStartupData(StartupData* compressed_data);
2985   static void SetDecompressedStartupData(StartupData* decompressed_data);
2986
2987   /**
2988    * Adds a message listener.
2989    *
2990    * The same message listener can be added more than once and in that
2991    * case it will be called more than once for each message.
2992    */
2993   static bool AddMessageListener(MessageCallback that,
2994                                  Handle<Value> data = Handle<Value>());
2995
2996   /**
2997    * Remove all message listeners from the specified callback function.
2998    */
2999   static void RemoveMessageListeners(MessageCallback that);
3000
3001   /**
3002    * Tells V8 to capture current stack trace when uncaught exception occurs
3003    * and report it to the message listeners. The option is off by default.
3004    */
3005   static void SetCaptureStackTraceForUncaughtExceptions(
3006       bool capture,
3007       int frame_limit = 10,
3008       StackTrace::StackTraceOptions options = StackTrace::kOverview);
3009
3010   /**
3011    * Sets V8 flags from a string.
3012    */
3013   static void SetFlagsFromString(const char* str, int length);
3014
3015   /**
3016    * Sets V8 flags from the command line.
3017    */
3018   static void SetFlagsFromCommandLine(int* argc,
3019                                       char** argv,
3020                                       bool remove_flags);
3021
3022   /** Get the version string. */
3023   static const char* GetVersion();
3024
3025   /**
3026    * Enables the host application to provide a mechanism for recording
3027    * statistics counters.
3028    */
3029   static void SetCounterFunction(CounterLookupCallback);
3030
3031   /**
3032    * Enables the host application to provide a mechanism for recording
3033    * histograms. The CreateHistogram function returns a
3034    * histogram which will later be passed to the AddHistogramSample
3035    * function.
3036    */
3037   static void SetCreateHistogramFunction(CreateHistogramCallback);
3038   static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
3039
3040   /**
3041    * Enables the computation of a sliding window of states. The sliding
3042    * window information is recorded in statistics counters.
3043    */
3044   static void EnableSlidingStateWindow();
3045
3046   /** Callback function for reporting failed access checks.*/
3047   static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
3048
3049   /**
3050    * Enables the host application to receive a notification before a
3051    * garbage collection.  Allocations are not allowed in the
3052    * callback function, you therefore cannot manipulate objects (set
3053    * or delete properties for example) since it is possible such
3054    * operations will result in the allocation of objects. It is possible
3055    * to specify the GCType filter for your callback. But it is not possible to
3056    * register the same callback function two times with different
3057    * GCType filters.
3058    */
3059   static void AddGCPrologueCallback(
3060       GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
3061
3062   /**
3063    * This function removes callback which was installed by
3064    * AddGCPrologueCallback function.
3065    */
3066   static void RemoveGCPrologueCallback(GCPrologueCallback callback);
3067
3068   /**
3069    * The function is deprecated. Please use AddGCPrologueCallback instead.
3070    * Enables the host application to receive a notification before a
3071    * garbage collection.  Allocations are not allowed in the
3072    * callback function, you therefore cannot manipulate objects (set
3073    * or delete properties for example) since it is possible such
3074    * operations will result in the allocation of objects.
3075    */
3076   static void SetGlobalGCPrologueCallback(GCCallback);
3077
3078   /**
3079    * Enables the host application to receive a notification after a
3080    * garbage collection.  Allocations are not allowed in the
3081    * callback function, you therefore cannot manipulate objects (set
3082    * or delete properties for example) since it is possible such
3083    * operations will result in the allocation of objects. It is possible
3084    * to specify the GCType filter for your callback. But it is not possible to
3085    * register the same callback function two times with different
3086    * GCType filters.
3087    */
3088   static void AddGCEpilogueCallback(
3089       GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
3090
3091   /**
3092    * This function removes callback which was installed by
3093    * AddGCEpilogueCallback function.
3094    */
3095   static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
3096
3097   /**
3098    * The function is deprecated. Please use AddGCEpilogueCallback instead.
3099    * Enables the host application to receive a notification after a
3100    * major garbage collection.  Allocations are not allowed in the
3101    * callback function, you therefore cannot manipulate objects (set
3102    * or delete properties for example) since it is possible such
3103    * operations will result in the allocation of objects.
3104    */
3105   static void SetGlobalGCEpilogueCallback(GCCallback);
3106
3107   /**
3108    * Enables the host application to provide a mechanism to be notified
3109    * and perform custom logging when V8 Allocates Executable Memory.
3110    */
3111   static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
3112                                           ObjectSpace space,
3113                                           AllocationAction action);
3114
3115   /**
3116    * This function removes callback which was installed by
3117    * AddMemoryAllocationCallback function.
3118    */
3119   static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
3120
3121   /**
3122    * Allows the host application to group objects together. If one
3123    * object in the group is alive, all objects in the group are alive.
3124    * After each garbage collection, object groups are removed. It is
3125    * intended to be used in the before-garbage-collection callback
3126    * function, for instance to simulate DOM tree connections among JS
3127    * wrapper objects.
3128    * See v8-profiler.h for RetainedObjectInfo interface description.
3129    */
3130   static void AddObjectGroup(Persistent<Value>* objects,
3131                              size_t length,
3132                              RetainedObjectInfo* info = NULL);
3133
3134   /**
3135    * Allows the host application to declare implicit references between
3136    * the objects: if |parent| is alive, all |children| are alive too.
3137    * After each garbage collection, all implicit references
3138    * are removed.  It is intended to be used in the before-garbage-collection
3139    * callback function.
3140    */
3141   static void AddImplicitReferences(Persistent<Object> parent,
3142                                     Persistent<Value>* children,
3143                                     size_t length);
3144
3145   /**
3146    * Initializes from snapshot if possible. Otherwise, attempts to
3147    * initialize from scratch.  This function is called implicitly if
3148    * you use the API without calling it first.
3149    */
3150   static bool Initialize();
3151
3152   /**
3153    * Allows the host application to provide a callback which can be used
3154    * as a source of entropy for random number generators.
3155    */
3156   static void SetEntropySource(EntropySource source);
3157
3158   /**
3159    * Adjusts the amount of registered external memory.  Used to give
3160    * V8 an indication of the amount of externally allocated memory
3161    * that is kept alive by JavaScript objects.  V8 uses this to decide
3162    * when to perform global garbage collections.  Registering
3163    * externally allocated memory will trigger global garbage
3164    * collections more often than otherwise in an attempt to garbage
3165    * collect the JavaScript objects keeping the externally allocated
3166    * memory alive.
3167    *
3168    * \param change_in_bytes the change in externally allocated memory
3169    *   that is kept alive by JavaScript objects.
3170    * \returns the adjusted value.
3171    */
3172   static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
3173
3174   /**
3175    * Suspends recording of tick samples in the profiler.
3176    * When the V8 profiling mode is enabled (usually via command line
3177    * switches) this function suspends recording of tick samples.
3178    * Profiling ticks are discarded until ResumeProfiler() is called.
3179    *
3180    * See also the --prof and --prof_auto command line switches to
3181    * enable V8 profiling.
3182    */
3183   static void PauseProfiler();
3184
3185   /**
3186    * Resumes recording of tick samples in the profiler.
3187    * See also PauseProfiler().
3188    */
3189   static void ResumeProfiler();
3190
3191   /**
3192    * Return whether profiler is currently paused.
3193    */
3194   static bool IsProfilerPaused();
3195
3196   /**
3197    * Retrieve the V8 thread id of the calling thread.
3198    *
3199    * The thread id for a thread should only be retrieved after the V8
3200    * lock has been acquired with a Locker object with that thread.
3201    */
3202   static int GetCurrentThreadId();
3203
3204   /**
3205    * Forcefully terminate execution of a JavaScript thread.  This can
3206    * be used to terminate long-running scripts.
3207    *
3208    * TerminateExecution should only be called when then V8 lock has
3209    * been acquired with a Locker object.  Therefore, in order to be
3210    * able to terminate long-running threads, preemption must be
3211    * enabled to allow the user of TerminateExecution to acquire the
3212    * lock.
3213    *
3214    * The termination is achieved by throwing an exception that is
3215    * uncatchable by JavaScript exception handlers.  Termination
3216    * exceptions act as if they were caught by a C++ TryCatch exception
3217    * handler.  If forceful termination is used, any C++ TryCatch
3218    * exception handler that catches an exception should check if that
3219    * exception is a termination exception and immediately return if
3220    * that is the case.  Returning immediately in that case will
3221    * continue the propagation of the termination exception if needed.
3222    *
3223    * The thread id passed to TerminateExecution must have been
3224    * obtained by calling GetCurrentThreadId on the thread in question.
3225    *
3226    * \param thread_id The thread id of the thread to terminate.
3227    */
3228   static void TerminateExecution(int thread_id);
3229
3230   /**
3231    * Forcefully terminate the current thread of JavaScript execution
3232    * in the given isolate. If no isolate is provided, the default
3233    * isolate is used.
3234    *
3235    * This method can be used by any thread even if that thread has not
3236    * acquired the V8 lock with a Locker object.
3237    *
3238    * \param isolate The isolate in which to terminate the current JS execution.
3239    */
3240   static void TerminateExecution(Isolate* isolate = NULL);
3241
3242   /**
3243    * Is V8 terminating JavaScript execution.
3244    *
3245    * Returns true if JavaScript execution is currently terminating
3246    * because of a call to TerminateExecution.  In that case there are
3247    * still JavaScript frames on the stack and the termination
3248    * exception is still active.
3249    *
3250    * \param isolate The isolate in which to check.
3251    */
3252   static bool IsExecutionTerminating(Isolate* isolate = NULL);
3253
3254   /**
3255    * Releases any resources used by v8 and stops any utility threads
3256    * that may be running.  Note that disposing v8 is permanent, it
3257    * cannot be reinitialized.
3258    *
3259    * It should generally not be necessary to dispose v8 before exiting
3260    * a process, this should happen automatically.  It is only necessary
3261    * to use if the process needs the resources taken up by v8.
3262    */
3263   static bool Dispose();
3264
3265   /**
3266    * Get statistics about the heap memory usage.
3267    */
3268   static void GetHeapStatistics(HeapStatistics* heap_statistics);
3269
3270   /**
3271    * Optional notification that the embedder is idle.
3272    * V8 uses the notification to reduce memory footprint.
3273    * This call can be used repeatedly if the embedder remains idle.
3274    * Returns true if the embedder should stop calling IdleNotification
3275    * until real work has been done.  This indicates that V8 has done
3276    * as much cleanup as it will be able to do.
3277    */
3278   static bool IdleNotification();
3279
3280   /**
3281    * Optional notification that the system is running low on memory.
3282    * V8 uses these notifications to attempt to free memory.
3283    */
3284   static void LowMemoryNotification();
3285
3286   /**
3287    * Optional notification that a context has been disposed. V8 uses
3288    * these notifications to guide the GC heuristic. Returns the number
3289    * of context disposals - including this one - since the last time
3290    * V8 had a chance to clean up.
3291    */
3292   static int ContextDisposedNotification();
3293
3294  private:
3295   V8();
3296
3297   static internal::Object** GlobalizeReference(internal::Object** handle);
3298   static void DisposeGlobal(internal::Object** global_handle);
3299   static void MakeWeak(internal::Object** global_handle,
3300                        void* data,
3301                        WeakReferenceCallback);
3302   static void ClearWeak(internal::Object** global_handle);
3303   static void MarkIndependent(internal::Object** global_handle);
3304   static bool IsGlobalNearDeath(internal::Object** global_handle);
3305   static bool IsGlobalWeak(internal::Object** global_handle);
3306   static void SetWrapperClassId(internal::Object** global_handle,
3307                                 uint16_t class_id);
3308
3309   template <class T> friend class Handle;
3310   template <class T> friend class Local;
3311   template <class T> friend class Persistent;
3312   friend class Context;
3313 };
3314
3315
3316 /**
3317  * An external exception handler.
3318  */
3319 class V8EXPORT TryCatch {
3320  public:
3321   /**
3322    * Creates a new try/catch block and registers it with v8.
3323    */
3324   TryCatch();
3325
3326   /**
3327    * Unregisters and deletes this try/catch block.
3328    */
3329   ~TryCatch();
3330
3331   /**
3332    * Returns true if an exception has been caught by this try/catch block.
3333    */
3334   bool HasCaught() const;
3335
3336   /**
3337    * For certain types of exceptions, it makes no sense to continue
3338    * execution.
3339    *
3340    * Currently, the only type of exception that can be caught by a
3341    * TryCatch handler and for which it does not make sense to continue
3342    * is termination exception.  Such exceptions are thrown when the
3343    * TerminateExecution methods are called to terminate a long-running
3344    * script.
3345    *
3346    * If CanContinue returns false, the correct action is to perform
3347    * any C++ cleanup needed and then return.
3348    */
3349   bool CanContinue() const;
3350
3351   /**
3352    * Throws the exception caught by this TryCatch in a way that avoids
3353    * it being caught again by this same TryCatch.  As with ThrowException
3354    * it is illegal to execute any JavaScript operations after calling
3355    * ReThrow; the caller must return immediately to where the exception
3356    * is caught.
3357    */
3358   Handle<Value> ReThrow();
3359
3360   /**
3361    * Returns the exception caught by this try/catch block.  If no exception has
3362    * been caught an empty handle is returned.
3363    *
3364    * The returned handle is valid until this TryCatch block has been destroyed.
3365    */
3366   Local<Value> Exception() const;
3367
3368   /**
3369    * Returns the .stack property of the thrown object.  If no .stack
3370    * property is present an empty handle is returned.
3371    */
3372   Local<Value> StackTrace() const;
3373
3374   /**
3375    * Returns the message associated with this exception.  If there is
3376    * no message associated an empty handle is returned.
3377    *
3378    * The returned handle is valid until this TryCatch block has been
3379    * destroyed.
3380    */
3381   Local<v8::Message> Message() const;
3382
3383   /**
3384    * Clears any exceptions that may have been caught by this try/catch block.
3385    * After this method has been called, HasCaught() will return false.
3386    *
3387    * It is not necessary to clear a try/catch block before using it again; if
3388    * another exception is thrown the previously caught exception will just be
3389    * overwritten.  However, it is often a good idea since it makes it easier
3390    * to determine which operation threw a given exception.
3391    */
3392   void Reset();
3393
3394   /**
3395    * Set verbosity of the external exception handler.
3396    *
3397    * By default, exceptions that are caught by an external exception
3398    * handler are not reported.  Call SetVerbose with true on an
3399    * external exception handler to have exceptions caught by the
3400    * handler reported as if they were not caught.
3401    */
3402   void SetVerbose(bool value);
3403
3404   /**
3405    * Set whether or not this TryCatch should capture a Message object
3406    * which holds source information about where the exception
3407    * occurred.  True by default.
3408    */
3409   void SetCaptureMessage(bool value);
3410
3411  private:
3412   v8::internal::Isolate* isolate_;
3413   void* next_;
3414   void* exception_;
3415   void* message_;
3416   bool is_verbose_ : 1;
3417   bool can_continue_ : 1;
3418   bool capture_message_ : 1;
3419   bool rethrow_ : 1;
3420
3421   friend class v8::internal::Isolate;
3422 };
3423
3424
3425 // --- Context ---
3426
3427
3428 /**
3429  * Ignore
3430  */
3431 class V8EXPORT ExtensionConfiguration {
3432  public:
3433   ExtensionConfiguration(int name_count, const char* names[])
3434       : name_count_(name_count), names_(names) { }
3435  private:
3436   friend class ImplementationUtilities;
3437   int name_count_;
3438   const char** names_;
3439 };
3440
3441
3442 /**
3443  * A sandboxed execution context with its own set of built-in objects
3444  * and functions.
3445  */
3446 class V8EXPORT Context {
3447  public:
3448   /**
3449    * Returns the global proxy object or global object itself for
3450    * detached contexts.
3451    *
3452    * Global proxy object is a thin wrapper whose prototype points to
3453    * actual context's global object with the properties like Object, etc.
3454    * This is done that way for security reasons (for more details see
3455    * https://wiki.mozilla.org/Gecko:SplitWindow).
3456    *
3457    * Please note that changes to global proxy object prototype most probably
3458    * would break VM---v8 expects only global object as a prototype of
3459    * global proxy object.
3460    *
3461    * If DetachGlobal() has been invoked, Global() would return actual global
3462    * object until global is reattached with ReattachGlobal().
3463    */
3464   Local<Object> Global();
3465
3466   /**
3467    * Detaches the global object from its context before
3468    * the global object can be reused to create a new context.
3469    */
3470   void DetachGlobal();
3471
3472   /**
3473    * Reattaches a global object to a context.  This can be used to
3474    * restore the connection between a global object and a context
3475    * after DetachGlobal has been called.
3476    *
3477    * \param global_object The global object to reattach to the
3478    *   context.  For this to work, the global object must be the global
3479    *   object that was associated with this context before a call to
3480    *   DetachGlobal.
3481    */
3482   void ReattachGlobal(Handle<Object> global_object);
3483
3484   /** Creates a new context.
3485    *
3486    * Returns a persistent handle to the newly allocated context. This
3487    * persistent handle has to be disposed when the context is no
3488    * longer used so the context can be garbage collected.
3489    *
3490    * \param extensions An optional extension configuration containing
3491    * the extensions to be installed in the newly created context.
3492    *
3493    * \param global_template An optional object template from which the
3494    * global object for the newly created context will be created.
3495    *
3496    * \param global_object An optional global object to be reused for
3497    * the newly created context. This global object must have been
3498    * created by a previous call to Context::New with the same global
3499    * template. The state of the global object will be completely reset
3500    * and only object identify will remain.
3501    */
3502   static Persistent<Context> New(
3503       ExtensionConfiguration* extensions = NULL,
3504       Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3505       Handle<Value> global_object = Handle<Value>());
3506
3507   /** Returns the last entered context. */
3508   static Local<Context> GetEntered();
3509
3510   /** Returns the context that is on the top of the stack. */
3511   static Local<Context> GetCurrent();
3512
3513   /**
3514    * Returns the context of the calling JavaScript code.  That is the
3515    * context of the top-most JavaScript frame.  If there are no
3516    * JavaScript frames an empty handle is returned.
3517    */
3518   static Local<Context> GetCalling();
3519   static Local<Object> GetCallingQmlGlobal();
3520   static Local<Value> GetCallingScriptData();
3521
3522   /**
3523    * Sets the security token for the context.  To access an object in
3524    * another context, the security tokens must match.
3525    */
3526   void SetSecurityToken(Handle<Value> token);
3527
3528   /** Restores the security token to the default value. */
3529   void UseDefaultSecurityToken();
3530
3531   /** Returns the security token of this context.*/
3532   Handle<Value> GetSecurityToken();
3533
3534   /**
3535    * Enter this context.  After entering a context, all code compiled
3536    * and run is compiled and run in this context.  If another context
3537    * is already entered, this old context is saved so it can be
3538    * restored when the new context is exited.
3539    */
3540   void Enter();
3541
3542   /**
3543    * Exit this context.  Exiting the current context restores the
3544    * context that was in place when entering the current context.
3545    */
3546   void Exit();
3547
3548   /** Returns true if the context has experienced an out of memory situation. */
3549   bool HasOutOfMemoryException();
3550
3551   /** Returns true if V8 has a current context. */
3552   static bool InContext();
3553
3554   /**
3555    * Associate an additional data object with the context. This is mainly used
3556    * with the debugger to provide additional information on the context through
3557    * the debugger API.
3558    */
3559   void SetData(Handle<String> data);
3560   Local<Value> GetData();
3561
3562   /**
3563    * Control whether code generation from strings is allowed. Calling
3564    * this method with false will disable 'eval' and the 'Function'
3565    * constructor for code running in this context. If 'eval' or the
3566    * 'Function' constructor are used an exception will be thrown.
3567    *
3568    * If code generation from strings is not allowed the
3569    * V8::AllowCodeGenerationFromStrings callback will be invoked if
3570    * set before blocking the call to 'eval' or the 'Function'
3571    * constructor. If that callback returns true, the call will be
3572    * allowed, otherwise an exception will be thrown. If no callback is
3573    * set an exception will be thrown.
3574    */
3575   void AllowCodeGenerationFromStrings(bool allow);
3576
3577   /**
3578    * Stack-allocated class which sets the execution context for all
3579    * operations executed within a local scope.
3580    */
3581   class Scope {
3582    public:
3583     explicit inline Scope(Handle<Context> context) : context_(context) {
3584       context_->Enter();
3585     }
3586     inline ~Scope() { context_->Exit(); }
3587    private:
3588     Handle<Context> context_;
3589   };
3590
3591  private:
3592   friend class Value;
3593   friend class Script;
3594   friend class Object;
3595   friend class Function;
3596 };
3597
3598
3599 /**
3600  * Multiple threads in V8 are allowed, but only one thread at a time
3601  * is allowed to use any given V8 isolate. See Isolate class
3602  * comments. The definition of 'using V8 isolate' includes
3603  * accessing handles or holding onto object pointers obtained
3604  * from V8 handles while in the particular V8 isolate.  It is up
3605  * to the user of V8 to ensure (perhaps with locking) that this
3606  * constraint is not violated.
3607  *
3608  * v8::Locker is a scoped lock object. While it's
3609  * active (i.e. between its construction and destruction) the current thread is
3610  * allowed to use the locked isolate. V8 guarantees that an isolate can be
3611  * locked by at most one thread at any time. In other words, the scope of a
3612  * v8::Locker is a critical section.
3613  *
3614  * Sample usage:
3615 * \code
3616  * ...
3617  * {
3618  *   v8::Locker locker(isolate);
3619  *   v8::Isolate::Scope isolate_scope(isolate);
3620  *   ...
3621  *   // Code using V8 and isolate goes here.
3622  *   ...
3623  * } // Destructor called here
3624  * \endcode
3625  *
3626  * If you wish to stop using V8 in a thread A you can do this either
3627  * by destroying the v8::Locker object as above or by constructing a
3628  * v8::Unlocker object:
3629  *
3630  * \code
3631  * {
3632  *   isolate->Exit();
3633  *   v8::Unlocker unlocker(isolate);
3634  *   ...
3635  *   // Code not using V8 goes here while V8 can run in another thread.
3636  *   ...
3637  * } // Destructor called here.
3638  * isolate->Enter();
3639  * \endcode
3640  *
3641  * The Unlocker object is intended for use in a long-running callback
3642  * from V8, where you want to release the V8 lock for other threads to
3643  * use.
3644  *
3645  * The v8::Locker is a recursive lock.  That is, you can lock more than
3646  * once in a given thread.  This can be useful if you have code that can
3647  * be called either from code that holds the lock or from code that does
3648  * not.  The Unlocker is not recursive so you can not have several
3649  * Unlockers on the stack at once, and you can not use an Unlocker in a
3650  * thread that is not inside a Locker's scope.
3651  *
3652  * An unlocker will unlock several lockers if it has to and reinstate
3653  * the correct depth of locking on its destruction. eg.:
3654  *
3655  * \code
3656  * // V8 not locked.
3657  * {
3658  *   v8::Locker locker(isolate);
3659  *   Isolate::Scope isolate_scope(isolate);
3660  *   // V8 locked.
3661  *   {
3662  *     v8::Locker another_locker(isolate);
3663  *     // V8 still locked (2 levels).
3664  *     {
3665  *       isolate->Exit();
3666  *       v8::Unlocker unlocker(isolate);
3667  *       // V8 not locked.
3668  *     }
3669  *     isolate->Enter();
3670  *     // V8 locked again (2 levels).
3671  *   }
3672  *   // V8 still locked (1 level).
3673  * }
3674  * // V8 Now no longer locked.
3675  * \endcode
3676  *
3677  *
3678  */
3679 class V8EXPORT Unlocker {
3680  public:
3681   /**
3682    * Initialize Unlocker for a given Isolate. NULL means default isolate.
3683    */
3684   explicit Unlocker(Isolate* isolate = NULL);
3685   ~Unlocker();
3686  private:
3687   internal::Isolate* isolate_;
3688 };
3689
3690
3691 class V8EXPORT Locker {
3692  public:
3693   /**
3694    * Initialize Locker for a given Isolate. NULL means default isolate.
3695    */
3696   explicit Locker(Isolate* isolate = NULL);
3697   ~Locker();
3698
3699   /**
3700    * Start preemption.
3701    *
3702    * When preemption is started, a timer is fired every n milliseconds
3703    * that will switch between multiple threads that are in contention
3704    * for the V8 lock.
3705    */
3706   static void StartPreemption(int every_n_ms);
3707
3708   /**
3709    * Stop preemption.
3710    */
3711   static void StopPreemption();
3712
3713   /**
3714    * Returns whether or not the locker for a given isolate, or default isolate
3715    * if NULL is given, is locked by the current thread.
3716    */
3717   static bool IsLocked(Isolate* isolate = NULL);
3718
3719   /**
3720    * Returns whether v8::Locker is being used by this V8 instance.
3721    */
3722   static bool IsActive();
3723
3724  private:
3725   bool has_lock_;
3726   bool top_level_;
3727   internal::Isolate* isolate_;
3728
3729   static bool active_;
3730
3731   // Disallow copying and assigning.
3732   Locker(const Locker&);
3733   void operator=(const Locker&);
3734 };
3735
3736
3737 /**
3738  * An interface for exporting data from V8, using "push" model.
3739  */
3740 class V8EXPORT OutputStream {  // NOLINT
3741  public:
3742   enum OutputEncoding {
3743     kAscii = 0  // 7-bit ASCII.
3744   };
3745   enum WriteResult {
3746     kContinue = 0,
3747     kAbort = 1
3748   };
3749   virtual ~OutputStream() {}
3750   /** Notify about the end of stream. */
3751   virtual void EndOfStream() = 0;
3752   /** Get preferred output chunk size. Called only once. */
3753   virtual int GetChunkSize() { return 1024; }
3754   /** Get preferred output encoding. Called only once. */
3755   virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3756   /**
3757    * Writes the next chunk of snapshot data into the stream. Writing
3758    * can be stopped by returning kAbort as function result. EndOfStream
3759    * will not be called in case writing was aborted.
3760    */
3761   virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3762 };
3763
3764
3765 /**
3766  * An interface for reporting progress and controlling long-running
3767  * activities.
3768  */
3769 class V8EXPORT ActivityControl {  // NOLINT
3770  public:
3771   enum ControlOption {
3772     kContinue = 0,
3773     kAbort = 1
3774   };
3775   virtual ~ActivityControl() {}
3776   /**
3777    * Notify about current progress. The activity can be stopped by
3778    * returning kAbort as the callback result.
3779    */
3780   virtual ControlOption ReportProgressValue(int done, int total) = 0;
3781 };
3782
3783
3784 // --- Implementation ---
3785
3786
3787 namespace internal {
3788
3789 static const int kApiPointerSize = sizeof(void*);  // NOLINT
3790 static const int kApiIntSize = sizeof(int);  // NOLINT
3791
3792 // Tag information for HeapObject.
3793 const int kHeapObjectTag = 1;
3794 const int kHeapObjectTagSize = 2;
3795 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3796
3797 // Tag information for Smi.
3798 const int kSmiTag = 0;
3799 const int kSmiTagSize = 1;
3800 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3801
3802 template <size_t ptr_size> struct SmiTagging;
3803
3804 // Smi constants for 32-bit systems.
3805 template <> struct SmiTagging<4> {
3806   static const int kSmiShiftSize = 0;
3807   static const int kSmiValueSize = 31;
3808   static inline int SmiToInt(internal::Object* value) {
3809     int shift_bits = kSmiTagSize + kSmiShiftSize;
3810     // Throw away top 32 bits and shift down (requires >> to be sign extending).
3811     return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3812   }
3813
3814   // For 32-bit systems any 2 bytes aligned pointer can be encoded as smi
3815   // with a plain reinterpret_cast.
3816   static const uintptr_t kEncodablePointerMask = 0x1;
3817   static const int kPointerToSmiShift = 0;
3818 };
3819
3820 // Smi constants for 64-bit systems.
3821 template <> struct SmiTagging<8> {
3822   static const int kSmiShiftSize = 31;
3823   static const int kSmiValueSize = 32;
3824   static inline int SmiToInt(internal::Object* value) {
3825     int shift_bits = kSmiTagSize + kSmiShiftSize;
3826     // Shift down and throw away top 32 bits.
3827     return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3828   }
3829
3830   // To maximize the range of pointers that can be encoded
3831   // in the available 32 bits, we require them to be 8 bytes aligned.
3832   // This gives 2 ^ (32 + 3) = 32G address space covered.
3833   // It might be not enough to cover stack allocated objects on some platforms.
3834   static const int kPointerAlignment = 3;
3835
3836   static const uintptr_t kEncodablePointerMask =
3837       ~(uintptr_t(0xffffffff) << kPointerAlignment);
3838
3839   static const int kPointerToSmiShift =
3840       kSmiTagSize + kSmiShiftSize - kPointerAlignment;
3841 };
3842
3843 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
3844 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
3845 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
3846 const uintptr_t kEncodablePointerMask =
3847     PlatformSmiTagging::kEncodablePointerMask;
3848 const int kPointerToSmiShift = PlatformSmiTagging::kPointerToSmiShift;
3849
3850 template <size_t ptr_size> struct InternalConstants;
3851
3852 // Internal constants for 32-bit systems.
3853 template <> struct InternalConstants<4> {
3854   static const int kStringResourceOffset = 3 * kApiPointerSize;
3855 };
3856
3857 // Internal constants for 64-bit systems.
3858 template <> struct InternalConstants<8> {
3859   static const int kStringResourceOffset = 3 * kApiPointerSize;
3860 };
3861
3862 /**
3863  * This class exports constants and functionality from within v8 that
3864  * is necessary to implement inline functions in the v8 api.  Don't
3865  * depend on functions and constants defined here.
3866  */
3867 class Internals {
3868  public:
3869   // These values match non-compiler-dependent values defined within
3870   // the implementation of v8.
3871   static const int kHeapObjectMapOffset = 0;
3872   static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
3873   static const int kStringResourceOffset =
3874       InternalConstants<kApiPointerSize>::kStringResourceOffset;
3875
3876   static const int kForeignAddressOffset = kApiPointerSize;
3877   static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
3878   static const int kFullStringRepresentationMask = 0x07;
3879   static const int kExternalTwoByteRepresentationTag = 0x02;
3880
3881   static const int kJSObjectType = 0xa6;
3882   static const int kFirstNonstringType = 0x80;
3883   static const int kForeignType = 0x85;
3884
3885   static inline bool HasHeapObjectTag(internal::Object* value) {
3886     return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3887             kHeapObjectTag);
3888   }
3889
3890   static inline bool HasSmiTag(internal::Object* value) {
3891     return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3892   }
3893
3894   static inline int SmiValue(internal::Object* value) {
3895     return PlatformSmiTagging::SmiToInt(value);
3896   }
3897
3898   static inline int GetInstanceType(internal::Object* obj) {
3899     typedef internal::Object O;
3900     O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3901     return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3902   }
3903
3904   static inline void* GetExternalPointerFromSmi(internal::Object* value) {
3905     const uintptr_t address = reinterpret_cast<uintptr_t>(value);
3906     return reinterpret_cast<void*>(address >> kPointerToSmiShift);
3907   }
3908
3909   static inline void* GetExternalPointer(internal::Object* obj) {
3910     if (HasSmiTag(obj)) {
3911       return GetExternalPointerFromSmi(obj);
3912     } else if (GetInstanceType(obj) == kForeignType) {
3913       return ReadField<void*>(obj, kForeignAddressOffset);
3914     } else {
3915       return NULL;
3916     }
3917   }
3918
3919   static inline bool IsExternalTwoByteString(int instance_type) {
3920     int representation = (instance_type & kFullStringRepresentationMask);
3921     return representation == kExternalTwoByteRepresentationTag;
3922   }
3923
3924   template <typename T>
3925   static inline T ReadField(Object* ptr, int offset) {
3926     uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3927     return *reinterpret_cast<T*>(addr);
3928   }
3929
3930   static inline bool CanCastToHeapObject(void* o) { return false; }
3931   static inline bool CanCastToHeapObject(Context* o) { return true; }
3932   static inline bool CanCastToHeapObject(String* o) { return true; }
3933   static inline bool CanCastToHeapObject(Object* o) { return true; }
3934   static inline bool CanCastToHeapObject(Message* o) { return true; }
3935   static inline bool CanCastToHeapObject(StackTrace* o) { return true; }
3936   static inline bool CanCastToHeapObject(StackFrame* o) { return true; }
3937 };
3938
3939 }  // namespace internal
3940
3941
3942 template <class T>
3943 Local<T>::Local() : Handle<T>() { }
3944
3945
3946 template <class T>
3947 Local<T> Local<T>::New(Handle<T> that) {
3948   if (that.IsEmpty()) return Local<T>();
3949   T* that_ptr = *that;
3950   internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
3951   if (internal::Internals::CanCastToHeapObject(that_ptr)) {
3952     return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
3953         reinterpret_cast<internal::HeapObject*>(*p))));
3954   }
3955   return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3956 }
3957
3958
3959 template <class T>
3960 Persistent<T> Persistent<T>::New(Handle<T> that) {
3961   if (that.IsEmpty()) return Persistent<T>();
3962   internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3963   return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3964 }
3965
3966
3967 template <class T>
3968 bool Persistent<T>::IsNearDeath() const {
3969   if (this->IsEmpty()) return false;
3970   return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3971 }
3972
3973
3974 template <class T>
3975 bool Persistent<T>::IsWeak() const {
3976   if (this->IsEmpty()) return false;
3977   return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3978 }
3979
3980
3981 template <class T>
3982 void Persistent<T>::Dispose() {
3983   if (this->IsEmpty()) return;
3984   V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3985 }
3986
3987
3988 template <class T>
3989 Persistent<T>::Persistent() : Handle<T>() { }
3990
3991 template <class T>
3992 void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3993   V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3994                parameters,
3995                callback);
3996 }
3997
3998 template <class T>
3999 void Persistent<T>::ClearWeak() {
4000   V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
4001 }
4002
4003 template <class T>
4004 void Persistent<T>::MarkIndependent() {
4005   V8::MarkIndependent(reinterpret_cast<internal::Object**>(**this));
4006 }
4007
4008 template <class T>
4009 void Persistent<T>::SetWrapperClassId(uint16_t class_id) {
4010   V8::SetWrapperClassId(reinterpret_cast<internal::Object**>(**this), class_id);
4011 }
4012
4013 Arguments::Arguments(internal::Object** implicit_args,
4014                      internal::Object** values, int length,
4015                      bool is_construct_call)
4016     : implicit_args_(implicit_args),
4017       values_(values),
4018       length_(length),
4019       is_construct_call_(is_construct_call) { }
4020
4021
4022 Local<Value> Arguments::operator[](int i) const {
4023   if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
4024   return Local<Value>(reinterpret_cast<Value*>(values_ - i));
4025 }
4026
4027
4028 Local<Function> Arguments::Callee() const {
4029   return Local<Function>(reinterpret_cast<Function*>(
4030       &implicit_args_[kCalleeIndex]));
4031 }
4032
4033
4034 Local<Object> Arguments::This() const {
4035   return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
4036 }
4037
4038
4039 Local<Object> Arguments::Holder() const {
4040   return Local<Object>(reinterpret_cast<Object*>(
4041       &implicit_args_[kHolderIndex]));
4042 }
4043
4044
4045 Local<Value> Arguments::Data() const {
4046   return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
4047 }
4048
4049
4050 bool Arguments::IsConstructCall() const {
4051   return is_construct_call_;
4052 }
4053
4054
4055 int Arguments::Length() const {
4056   return length_;
4057 }
4058
4059
4060 template <class T>
4061 Local<T> HandleScope::Close(Handle<T> value) {
4062   internal::Object** before = reinterpret_cast<internal::Object**>(*value);
4063   internal::Object** after = RawClose(before);
4064   return Local<T>(reinterpret_cast<T*>(after));
4065 }
4066
4067 Handle<Value> ScriptOrigin::ResourceName() const {
4068   return resource_name_;
4069 }
4070
4071
4072 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
4073   return resource_line_offset_;
4074 }
4075
4076
4077 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
4078   return resource_column_offset_;
4079 }
4080
4081
4082 Handle<Boolean> Boolean::New(bool value) {
4083   return value ? True() : False();
4084 }
4085
4086
4087 void Template::Set(const char* name, v8::Handle<Data> value) {
4088   Set(v8::String::New(name), value);
4089 }
4090
4091
4092 Local<Value> Object::GetInternalField(int index) {
4093 #ifndef V8_ENABLE_CHECKS
4094   Local<Value> quick_result = UncheckedGetInternalField(index);
4095   if (!quick_result.IsEmpty()) return quick_result;
4096 #endif
4097   return CheckedGetInternalField(index);
4098 }
4099
4100
4101 Local<Value> Object::UncheckedGetInternalField(int index) {
4102   typedef internal::Object O;
4103   typedef internal::Internals I;
4104   O* obj = *reinterpret_cast<O**>(this);
4105   if (I::GetInstanceType(obj) == I::kJSObjectType) {
4106     // If the object is a plain JSObject, which is the common case,
4107     // we know where to find the internal fields and can return the
4108     // value directly.
4109     int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
4110     O* value = I::ReadField<O*>(obj, offset);
4111     O** result = HandleScope::CreateHandle(value);
4112     return Local<Value>(reinterpret_cast<Value*>(result));
4113   } else {
4114     return Local<Value>();
4115   }
4116 }
4117
4118
4119 void* External::Unwrap(Handle<v8::Value> obj) {
4120 #ifdef V8_ENABLE_CHECKS
4121   return FullUnwrap(obj);
4122 #else
4123   return QuickUnwrap(obj);
4124 #endif
4125 }
4126
4127
4128 void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
4129   typedef internal::Object O;
4130   O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
4131   return internal::Internals::GetExternalPointer(obj);
4132 }
4133
4134
4135 void* Object::GetPointerFromInternalField(int index) {
4136   typedef internal::Object O;
4137   typedef internal::Internals I;
4138
4139   O* obj = *reinterpret_cast<O**>(this);
4140
4141   if (I::GetInstanceType(obj) == I::kJSObjectType) {
4142     // If the object is a plain JSObject, which is the common case,
4143     // we know where to find the internal fields and can return the
4144     // value directly.
4145     int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
4146     O* value = I::ReadField<O*>(obj, offset);
4147     return I::GetExternalPointer(value);
4148   }
4149
4150   return SlowGetPointerFromInternalField(index);
4151 }
4152
4153
4154 String* String::Cast(v8::Value* value) {
4155 #ifdef V8_ENABLE_CHECKS
4156   CheckCast(value);
4157 #endif
4158   return static_cast<String*>(value);
4159 }
4160
4161
4162 String::ExternalStringResource* String::GetExternalStringResource() const {
4163   typedef internal::Object O;
4164   typedef internal::Internals I;
4165   O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
4166   String::ExternalStringResource* result;
4167   if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
4168     void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
4169     result = reinterpret_cast<String::ExternalStringResource*>(value);
4170   } else {
4171     result = NULL;
4172   }
4173 #ifdef V8_ENABLE_CHECKS
4174   VerifyExternalStringResource(result);
4175 #endif
4176   return result;
4177 }
4178
4179
4180 bool Value::IsString() const {
4181 #ifdef V8_ENABLE_CHECKS
4182   return FullIsString();
4183 #else
4184   return QuickIsString();
4185 #endif
4186 }
4187
4188 bool Value::QuickIsString() const {
4189   typedef internal::Object O;
4190   typedef internal::Internals I;
4191   O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
4192   if (!I::HasHeapObjectTag(obj)) return false;
4193   return (I::GetInstanceType(obj) < I::kFirstNonstringType);
4194 }
4195
4196
4197 Number* Number::Cast(v8::Value* value) {
4198 #ifdef V8_ENABLE_CHECKS
4199   CheckCast(value);
4200 #endif
4201   return static_cast<Number*>(value);
4202 }
4203
4204
4205 Integer* Integer::Cast(v8::Value* value) {
4206 #ifdef V8_ENABLE_CHECKS
4207   CheckCast(value);
4208 #endif
4209   return static_cast<Integer*>(value);
4210 }
4211
4212
4213 Date* Date::Cast(v8::Value* value) {
4214 #ifdef V8_ENABLE_CHECKS
4215   CheckCast(value);
4216 #endif
4217   return static_cast<Date*>(value);
4218 }
4219
4220
4221 StringObject* StringObject::Cast(v8::Value* value) {
4222 #ifdef V8_ENABLE_CHECKS
4223   CheckCast(value);
4224 #endif
4225   return static_cast<StringObject*>(value);
4226 }
4227
4228
4229 NumberObject* NumberObject::Cast(v8::Value* value) {
4230 #ifdef V8_ENABLE_CHECKS
4231   CheckCast(value);
4232 #endif
4233   return static_cast<NumberObject*>(value);
4234 }
4235
4236
4237 BooleanObject* BooleanObject::Cast(v8::Value* value) {
4238 #ifdef V8_ENABLE_CHECKS
4239   CheckCast(value);
4240 #endif
4241   return static_cast<BooleanObject*>(value);
4242 }
4243
4244
4245 RegExp* RegExp::Cast(v8::Value* value) {
4246 #ifdef V8_ENABLE_CHECKS
4247   CheckCast(value);
4248 #endif
4249   return static_cast<RegExp*>(value);
4250 }
4251
4252
4253 Object* Object::Cast(v8::Value* value) {
4254 #ifdef V8_ENABLE_CHECKS
4255   CheckCast(value);
4256 #endif
4257   return static_cast<Object*>(value);
4258 }
4259
4260
4261 Array* Array::Cast(v8::Value* value) {
4262 #ifdef V8_ENABLE_CHECKS
4263   CheckCast(value);
4264 #endif
4265   return static_cast<Array*>(value);
4266 }
4267
4268
4269 Function* Function::Cast(v8::Value* value) {
4270 #ifdef V8_ENABLE_CHECKS
4271   CheckCast(value);
4272 #endif
4273   return static_cast<Function*>(value);
4274 }
4275
4276
4277 External* External::Cast(v8::Value* value) {
4278 #ifdef V8_ENABLE_CHECKS
4279   CheckCast(value);
4280 #endif
4281   return static_cast<External*>(value);
4282 }
4283
4284
4285 Local<Value> AccessorInfo::Data() const {
4286   return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
4287 }
4288
4289
4290 Local<Object> AccessorInfo::This() const {
4291   return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
4292 }
4293
4294
4295 Local<Object> AccessorInfo::Holder() const {
4296   return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
4297 }
4298
4299
4300 /**
4301  * \example shell.cc
4302  * A simple shell that takes a list of expressions on the
4303  * command-line and executes them.
4304  */
4305
4306
4307 /**
4308  * \example process.cc
4309  */
4310
4311
4312 }  // namespace v8
4313
4314
4315 #undef V8EXPORT
4316 #undef TYPE_CHECK
4317
4318
4319 #endif  // V8_H_