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