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