blob: 8c730df8aee9a3d154ae42f3f09c652703f13d45 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2007-2009 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
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080041#include "v8stdint.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000042
43#ifdef _WIN32
Steve Blocka7e24c12009-10-30 11:49:00 +000044
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.
Steve Blocka7e24c12009-10-30 11:49:00 +000050#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)
Steve Blocka7e24c12009-10-30 11:49:00 +000057#elif USING_V8_SHARED
58#define V8EXPORT __declspec(dllimport)
Steve Blocka7e24c12009-10-30 11:49:00 +000059#else
60#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000061#endif // BUILDING_V8_SHARED
62
63#else // _WIN32
64
Steve Blocka7e24c12009-10-30 11:49:00 +000065// Setup for Linux shared library export. There is no need to distinguish
66// between building or using the V8 shared library, but we should not
67// export symbols when we are building a static library.
68#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
69#define V8EXPORT __attribute__ ((visibility("default")))
Steve Blocka7e24c12009-10-30 11:49:00 +000070#else // defined(__GNUC__) && (__GNUC__ >= 4)
71#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000072#endif // defined(__GNUC__) && (__GNUC__ >= 4)
73
74#endif // _WIN32
75
76/**
77 * The v8 JavaScript engine.
78 */
79namespace v8 {
80
81class Context;
82class String;
83class Value;
84class Utils;
85class Number;
86class Object;
87class Array;
88class Int32;
89class Uint32;
90class External;
91class Primitive;
92class Boolean;
93class Integer;
94class Function;
95class Date;
96class ImplementationUtilities;
97class Signature;
98template <class T> class Handle;
99template <class T> class Local;
100template <class T> class Persistent;
101class FunctionTemplate;
102class ObjectTemplate;
103class Data;
Leon Clarkef7060e22010-06-03 12:02:55 +0100104class AccessorInfo;
Kristian Monsen25f61362010-05-21 11:50:48 +0100105class StackTrace;
106class StackFrame;
Steve Blocka7e24c12009-10-30 11:49:00 +0000107
108namespace internal {
109
Steve Blocka7e24c12009-10-30 11:49:00 +0000110class Arguments;
Steve Blockd0582a62009-12-15 09:54:21 +0000111class Object;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100112class Heap;
Steve Blockd0582a62009-12-15 09:54:21 +0000113class Top;
Steve Blocka7e24c12009-10-30 11:49:00 +0000114}
115
116
117// --- W e a k H a n d l e s
118
119
120/**
121 * A weak reference callback function.
122 *
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100123 * This callback should either explicitly invoke Dispose on |object| if
124 * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak.
125 *
Steve Blocka7e24c12009-10-30 11:49:00 +0000126 * \param object the weak global object to be reclaimed by the garbage collector
127 * \param parameter the value passed in when making the weak global object
128 */
129typedef void (*WeakReferenceCallback)(Persistent<Value> object,
130 void* parameter);
131
132
133// --- H a n d l e s ---
134
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100135#define TYPE_CHECK(T, S) \
136 while (false) { \
137 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
Steve Blocka7e24c12009-10-30 11:49:00 +0000138 }
139
140/**
141 * An object reference managed by the v8 garbage collector.
142 *
143 * All objects returned from v8 have to be tracked by the garbage
144 * collector so that it knows that the objects are still alive. Also,
145 * because the garbage collector may move objects, it is unsafe to
146 * point directly to an object. Instead, all objects are stored in
147 * handles which are known by the garbage collector and updated
148 * whenever an object moves. Handles should always be passed by value
149 * (except in cases like out-parameters) and they should never be
150 * allocated on the heap.
151 *
152 * There are two types of handles: local and persistent handles.
153 * Local handles are light-weight and transient and typically used in
154 * local operations. They are managed by HandleScopes. Persistent
155 * handles can be used when storing objects across several independent
156 * operations and have to be explicitly deallocated when they're no
157 * longer used.
158 *
159 * It is safe to extract the object stored in the handle by
160 * dereferencing the handle (for instance, to extract the Object* from
161 * an Handle<Object>); the value will still be governed by a handle
162 * behind the scenes and the same rules apply to these values as to
163 * their handles.
164 */
Steve Block8defd9f2010-07-08 12:39:36 +0100165template <class T> class Handle {
Steve Blocka7e24c12009-10-30 11:49:00 +0000166 public:
167
168 /**
169 * Creates an empty handle.
170 */
171 inline Handle();
172
173 /**
174 * Creates a new handle for the specified value.
175 */
Steve Block8defd9f2010-07-08 12:39:36 +0100176 inline explicit Handle(T* val) : val_(val) { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000177
178 /**
179 * Creates a handle for the contents of the specified handle. This
180 * constructor allows you to pass handles as arguments by value and
181 * to assign between handles. However, if you try to assign between
182 * incompatible handles, for instance from a Handle<String> to a
183 * Handle<Number> it will cause a compiletime error. Assigning
184 * between compatible handles, for instance assigning a
185 * Handle<String> to a variable declared as Handle<Value>, is legal
186 * because String is a subclass of Value.
187 */
188 template <class S> inline Handle(Handle<S> that)
189 : val_(reinterpret_cast<T*>(*that)) {
190 /**
191 * This check fails when trying to convert between incompatible
192 * handles. For example, converting from a Handle<String> to a
193 * Handle<Number>.
194 */
195 TYPE_CHECK(T, S);
196 }
197
198 /**
199 * Returns true if the handle is empty.
200 */
Steve Block8defd9f2010-07-08 12:39:36 +0100201 inline bool IsEmpty() const { return val_ == 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000202
Steve Block8defd9f2010-07-08 12:39:36 +0100203 inline T* operator->() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000204
Steve Block8defd9f2010-07-08 12:39:36 +0100205 inline T* operator*() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000206
207 /**
208 * Sets the handle to be empty. IsEmpty() will then return true.
209 */
Steve Block8defd9f2010-07-08 12:39:36 +0100210 inline void Clear() { this->val_ = 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000211
212 /**
213 * Checks whether two handles are the same.
214 * Returns true if both are empty, or if the objects
215 * to which they refer are identical.
216 * The handles' references are not checked.
217 */
Steve Block8defd9f2010-07-08 12:39:36 +0100218 template <class S> inline bool operator==(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000219 internal::Object** a = reinterpret_cast<internal::Object**>(**this);
220 internal::Object** b = reinterpret_cast<internal::Object**>(*that);
221 if (a == 0) return b == 0;
222 if (b == 0) return false;
223 return *a == *b;
224 }
225
226 /**
227 * Checks whether two handles are different.
228 * Returns true if only one of the handles is empty, or if
229 * the objects to which they refer are different.
230 * The handles' references are not checked.
231 */
Steve Block8defd9f2010-07-08 12:39:36 +0100232 template <class S> inline bool operator!=(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000233 return !operator==(that);
234 }
235
236 template <class S> static inline Handle<T> Cast(Handle<S> that) {
237#ifdef V8_ENABLE_CHECKS
238 // If we're going to perform the type check then we have to check
239 // that the handle isn't empty before doing the checked cast.
240 if (that.IsEmpty()) return Handle<T>();
241#endif
242 return Handle<T>(T::Cast(*that));
243 }
244
Steve Block6ded16b2010-05-10 14:33:55 +0100245 template <class S> inline Handle<S> As() {
246 return Handle<S>::Cast(*this);
247 }
248
Steve Blocka7e24c12009-10-30 11:49:00 +0000249 private:
250 T* val_;
251};
252
253
254/**
255 * A light-weight stack-allocated object handle. All operations
256 * that return objects from within v8 return them in local handles. They
257 * are created within HandleScopes, and all local handles allocated within a
258 * handle scope are destroyed when the handle scope is destroyed. Hence it
259 * is not necessary to explicitly deallocate local handles.
260 */
Steve Block8defd9f2010-07-08 12:39:36 +0100261template <class T> class Local : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000262 public:
263 inline Local();
264 template <class S> inline Local(Local<S> that)
265 : Handle<T>(reinterpret_cast<T*>(*that)) {
266 /**
267 * This check fails when trying to convert between incompatible
268 * handles. For example, converting from a Handle<String> to a
269 * Handle<Number>.
270 */
271 TYPE_CHECK(T, S);
272 }
273 template <class S> inline Local(S* that) : Handle<T>(that) { }
274 template <class S> static inline Local<T> Cast(Local<S> that) {
275#ifdef V8_ENABLE_CHECKS
276 // If we're going to perform the type check then we have to check
277 // that the handle isn't empty before doing the checked cast.
278 if (that.IsEmpty()) return Local<T>();
279#endif
280 return Local<T>(T::Cast(*that));
281 }
282
Steve Block6ded16b2010-05-10 14:33:55 +0100283 template <class S> inline Local<S> As() {
284 return Local<S>::Cast(*this);
285 }
286
Steve Blocka7e24c12009-10-30 11:49:00 +0000287 /** Create a local handle for the content of another handle.
288 * The referee is kept alive by the local handle even when
289 * the original handle is destroyed/disposed.
290 */
291 inline static Local<T> New(Handle<T> that);
292};
293
294
295/**
296 * An object reference that is independent of any handle scope. Where
297 * a Local handle only lives as long as the HandleScope in which it was
298 * allocated, a Persistent handle remains valid until it is explicitly
299 * disposed.
300 *
301 * A persistent handle contains a reference to a storage cell within
302 * the v8 engine which holds an object value and which is updated by
303 * the garbage collector whenever the object is moved. A new storage
304 * cell can be created using Persistent::New and existing handles can
305 * be disposed using Persistent::Dispose. Since persistent handles
306 * are passed by value you may have many persistent handle objects
307 * that point to the same storage cell. For instance, if you pass a
308 * persistent handle as an argument to a function you will not get two
309 * different storage cells but rather two references to the same
310 * storage cell.
311 */
Steve Block8defd9f2010-07-08 12:39:36 +0100312template <class T> class Persistent : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000313 public:
314
315 /**
316 * Creates an empty persistent handle that doesn't point to any
317 * storage cell.
318 */
319 inline Persistent();
320
321 /**
322 * Creates a persistent handle for the same storage cell as the
323 * specified handle. This constructor allows you to pass persistent
324 * handles as arguments by value and to assign between persistent
325 * handles. However, attempting to assign between incompatible
326 * persistent handles, for instance from a Persistent<String> to a
327 * Persistent<Number> will cause a compiletime error. Assigning
328 * between compatible persistent handles, for instance assigning a
329 * Persistent<String> to a variable declared as Persistent<Value>,
330 * is allowed as String is a subclass of Value.
331 */
332 template <class S> inline Persistent(Persistent<S> that)
333 : Handle<T>(reinterpret_cast<T*>(*that)) {
334 /**
335 * This check fails when trying to convert between incompatible
336 * handles. For example, converting from a Handle<String> to a
337 * Handle<Number>.
338 */
339 TYPE_CHECK(T, S);
340 }
341
342 template <class S> inline Persistent(S* that) : Handle<T>(that) { }
343
344 /**
345 * "Casts" a plain handle which is known to be a persistent handle
346 * to a persistent handle.
347 */
348 template <class S> explicit inline Persistent(Handle<S> that)
349 : Handle<T>(*that) { }
350
351 template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
352#ifdef V8_ENABLE_CHECKS
353 // If we're going to perform the type check then we have to check
354 // that the handle isn't empty before doing the checked cast.
355 if (that.IsEmpty()) return Persistent<T>();
356#endif
357 return Persistent<T>(T::Cast(*that));
358 }
359
Steve Block6ded16b2010-05-10 14:33:55 +0100360 template <class S> inline Persistent<S> As() {
361 return Persistent<S>::Cast(*this);
362 }
363
Steve Blocka7e24c12009-10-30 11:49:00 +0000364 /**
365 * Creates a new persistent handle for an existing local or
366 * persistent handle.
367 */
368 inline static Persistent<T> New(Handle<T> that);
369
370 /**
371 * Releases the storage cell referenced by this persistent handle.
372 * Does not remove the reference to the cell from any handles.
373 * This handle's reference, and any any other references to the storage
374 * cell remain and IsEmpty will still return false.
375 */
376 inline void Dispose();
377
378 /**
379 * Make the reference to this object weak. When only weak handles
380 * refer to the object, the garbage collector will perform a
381 * callback to the given V8::WeakReferenceCallback function, passing
382 * it the object reference and the given parameters.
383 */
384 inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
385
386 /** Clears the weak reference to this object.*/
387 inline void ClearWeak();
388
389 /**
390 *Checks if the handle holds the only reference to an object.
391 */
392 inline bool IsNearDeath() const;
393
394 /**
395 * Returns true if the handle's reference is weak.
396 */
397 inline bool IsWeak() const;
398
399 private:
400 friend class ImplementationUtilities;
401 friend class ObjectTemplate;
402};
403
404
405 /**
406 * A stack-allocated class that governs a number of local handles.
407 * After a handle scope has been created, all local handles will be
408 * allocated within that handle scope until either the handle scope is
409 * deleted or another handle scope is created. If there is already a
410 * handle scope and a new one is created, all allocations will take
411 * place in the new handle scope until it is deleted. After that,
412 * new handles will again be allocated in the original handle scope.
413 *
414 * After the handle scope of a local handle has been deleted the
415 * garbage collector will no longer track the object stored in the
416 * handle and may deallocate it. The behavior of accessing a handle
417 * for which the handle scope has been deleted is undefined.
418 */
419class V8EXPORT HandleScope {
420 public:
421 HandleScope();
422
423 ~HandleScope();
424
425 /**
426 * Closes the handle scope and returns the value as a handle in the
427 * previous scope, which is the new current scope after the call.
428 */
429 template <class T> Local<T> Close(Handle<T> value);
430
431 /**
432 * Counts the number of allocated handles.
433 */
434 static int NumberOfHandles();
435
436 /**
437 * Creates a new handle with the given value.
438 */
439 static internal::Object** CreateHandle(internal::Object* value);
440
441 private:
442 // Make it impossible to create heap-allocated or illegal handle
443 // scopes by disallowing certain operations.
444 HandleScope(const HandleScope&);
445 void operator=(const HandleScope&);
446 void* operator new(size_t size);
447 void operator delete(void*, size_t);
448
Steve Blockd0582a62009-12-15 09:54:21 +0000449 // This Data class is accessible internally as HandleScopeData through a
450 // typedef in the ImplementationUtilities class.
Steve Blocka7e24c12009-10-30 11:49:00 +0000451 class V8EXPORT Data {
452 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000453 internal::Object** next;
454 internal::Object** limit;
John Reck59135872010-11-02 12:39:01 -0700455 int level;
456
Steve Blocka7e24c12009-10-30 11:49:00 +0000457 inline void Initialize() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000458 next = limit = NULL;
John Reck59135872010-11-02 12:39:01 -0700459 level = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000460 }
461 };
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800462
John Reck59135872010-11-02 12:39:01 -0700463 void Leave();
Steve Blocka7e24c12009-10-30 11:49:00 +0000464
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800465
John Reck59135872010-11-02 12:39:01 -0700466 internal::Object** prev_next_;
467 internal::Object** prev_limit_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000468
469 // Allow for the active closing of HandleScopes which allows to pass a handle
470 // from the HandleScope being closed to the next top most HandleScope.
471 bool is_closed_;
472 internal::Object** RawClose(internal::Object** value);
473
474 friend class ImplementationUtilities;
475};
476
477
478// --- S p e c i a l o b j e c t s ---
479
480
481/**
482 * The superclass of values and API object templates.
483 */
484class V8EXPORT Data {
485 private:
486 Data();
487};
488
489
490/**
491 * Pre-compilation data that can be associated with a script. This
492 * data can be calculated for a script in advance of actually
493 * compiling it, and can be stored between compilations. When script
494 * data is given to the compile method compilation will be faster.
495 */
496class V8EXPORT ScriptData { // NOLINT
497 public:
498 virtual ~ScriptData() { }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100499
Leon Clarkef7060e22010-06-03 12:02:55 +0100500 /**
501 * Pre-compiles the specified script (context-independent).
502 *
503 * \param input Pointer to UTF-8 script source code.
504 * \param length Length of UTF-8 script source code.
505 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000506 static ScriptData* PreCompile(const char* input, int length);
Steve Blocka7e24c12009-10-30 11:49:00 +0000507
Leon Clarkef7060e22010-06-03 12:02:55 +0100508 /**
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100509 * Pre-compiles the specified script (context-independent).
510 *
511 * NOTE: Pre-compilation using this method cannot happen on another thread
512 * without using Lockers.
513 *
514 * \param source Script source code.
515 */
516 static ScriptData* PreCompile(Handle<String> source);
517
518 /**
Leon Clarkef7060e22010-06-03 12:02:55 +0100519 * Load previous pre-compilation data.
520 *
521 * \param data Pointer to data returned by a call to Data() of a previous
522 * ScriptData. Ownership is not transferred.
523 * \param length Length of data.
524 */
525 static ScriptData* New(const char* data, int length);
526
527 /**
528 * Returns the length of Data().
529 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000530 virtual int Length() = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100531
532 /**
533 * Returns a serialized representation of this ScriptData that can later be
534 * passed to New(). NOTE: Serialized data is platform-dependent.
535 */
536 virtual const char* Data() = 0;
537
538 /**
539 * Returns true if the source code could not be parsed.
540 */
Leon Clarkee46be812010-01-19 14:06:41 +0000541 virtual bool HasError() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000542};
543
544
545/**
546 * The origin, within a file, of a script.
547 */
Steve Block8defd9f2010-07-08 12:39:36 +0100548class ScriptOrigin {
Steve Blocka7e24c12009-10-30 11:49:00 +0000549 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100550 inline ScriptOrigin(
551 Handle<Value> resource_name,
552 Handle<Integer> resource_line_offset = Handle<Integer>(),
553 Handle<Integer> resource_column_offset = Handle<Integer>())
Steve Blocka7e24c12009-10-30 11:49:00 +0000554 : resource_name_(resource_name),
555 resource_line_offset_(resource_line_offset),
556 resource_column_offset_(resource_column_offset) { }
557 inline Handle<Value> ResourceName() const;
558 inline Handle<Integer> ResourceLineOffset() const;
559 inline Handle<Integer> ResourceColumnOffset() const;
560 private:
561 Handle<Value> resource_name_;
562 Handle<Integer> resource_line_offset_;
563 Handle<Integer> resource_column_offset_;
564};
565
566
567/**
568 * A compiled JavaScript script.
569 */
570class V8EXPORT Script {
571 public:
572
Steve Blocka7e24c12009-10-30 11:49:00 +0000573 /**
Andrei Popescu402d9372010-02-26 13:31:12 +0000574 * Compiles the specified script (context-independent).
Steve Blocka7e24c12009-10-30 11:49:00 +0000575 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000576 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100577 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000578 * when New() returns
579 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
580 * using pre_data speeds compilation if it's done multiple times.
581 * Owned by caller, no references are kept when New() returns.
582 * \param script_data Arbitrary data associated with script. Using
Steve Block6ded16b2010-05-10 14:33:55 +0100583 * this has same effect as calling SetData(), but allows data to be
Andrei Popescu402d9372010-02-26 13:31:12 +0000584 * available to compile event handlers.
585 * \return Compiled script object (context independent; when run it
586 * will use the currently entered context).
Steve Blocka7e24c12009-10-30 11:49:00 +0000587 */
Andrei Popescu402d9372010-02-26 13:31:12 +0000588 static Local<Script> New(Handle<String> source,
589 ScriptOrigin* origin = NULL,
590 ScriptData* pre_data = NULL,
591 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000592
593 /**
594 * Compiles the specified script using the specified file name
595 * object (typically a string) as the script's origin.
596 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000597 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100598 * \param file_name file name object (typically a string) to be used
Andrei Popescu402d9372010-02-26 13:31:12 +0000599 * as the script's origin.
600 * \return Compiled script object (context independent; when run it
601 * will use the currently entered context).
602 */
603 static Local<Script> New(Handle<String> source,
604 Handle<Value> file_name);
605
606 /**
607 * Compiles the specified script (bound to current context).
608 *
609 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100610 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000611 * when Compile() returns
612 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
613 * using pre_data speeds compilation if it's done multiple times.
614 * Owned by caller, no references are kept when Compile() returns.
615 * \param script_data Arbitrary data associated with script. Using
616 * this has same effect as calling SetData(), but makes data available
617 * earlier (i.e. to compile event handlers).
618 * \return Compiled script object, bound to the context that was active
619 * when this function was called. When run it will always use this
620 * context.
Steve Blocka7e24c12009-10-30 11:49:00 +0000621 */
622 static Local<Script> Compile(Handle<String> source,
Andrei Popescu402d9372010-02-26 13:31:12 +0000623 ScriptOrigin* origin = NULL,
624 ScriptData* pre_data = NULL,
625 Handle<String> script_data = Handle<String>());
626
627 /**
628 * Compiles the specified script using the specified file name
629 * object (typically a string) as the script's origin.
630 *
631 * \param source Script source code.
632 * \param file_name File name to use as script's origin
633 * \param script_data Arbitrary data associated with script. Using
634 * this has same effect as calling SetData(), but makes data available
635 * earlier (i.e. to compile event handlers).
636 * \return Compiled script object, bound to the context that was active
637 * when this function was called. When run it will always use this
638 * context.
639 */
640 static Local<Script> Compile(Handle<String> source,
641 Handle<Value> file_name,
642 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000643
644 /**
645 * Runs the script returning the resulting value. If the script is
646 * context independent (created using ::New) it will be run in the
647 * currently entered context. If it is context specific (created
648 * using ::Compile) it will be run in the context in which it was
649 * compiled.
650 */
651 Local<Value> Run();
652
653 /**
654 * Returns the script id value.
655 */
656 Local<Value> Id();
657
658 /**
659 * Associate an additional data object with the script. This is mainly used
660 * with the debugger as this data object is only available through the
661 * debugger API.
662 */
Steve Blockd0582a62009-12-15 09:54:21 +0000663 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000664};
665
666
667/**
668 * An error message.
669 */
670class V8EXPORT Message {
671 public:
672 Local<String> Get() const;
673 Local<String> GetSourceLine() const;
674
675 /**
676 * Returns the resource name for the script from where the function causing
677 * the error originates.
678 */
679 Handle<Value> GetScriptResourceName() const;
680
681 /**
682 * Returns the resource data for the script from where the function causing
683 * the error originates.
684 */
685 Handle<Value> GetScriptData() const;
686
687 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100688 * Exception stack trace. By default stack traces are not captured for
689 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
690 * to change this option.
691 */
692 Handle<StackTrace> GetStackTrace() const;
693
694 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000695 * Returns the number, 1-based, of the line where the error occurred.
696 */
697 int GetLineNumber() const;
698
699 /**
700 * Returns the index within the script of the first character where
701 * the error occurred.
702 */
703 int GetStartPosition() const;
704
705 /**
706 * Returns the index within the script of the last character where
707 * the error occurred.
708 */
709 int GetEndPosition() const;
710
711 /**
712 * Returns the index within the line of the first character where
713 * the error occurred.
714 */
715 int GetStartColumn() const;
716
717 /**
718 * Returns the index within the line of the last character where
719 * the error occurred.
720 */
721 int GetEndColumn() const;
722
723 // TODO(1245381): Print to a string instead of on a FILE.
724 static void PrintCurrentStackTrace(FILE* out);
Kristian Monsen25f61362010-05-21 11:50:48 +0100725
726 static const int kNoLineNumberInfo = 0;
727 static const int kNoColumnInfo = 0;
728};
729
730
731/**
732 * Representation of a JavaScript stack trace. The information collected is a
733 * snapshot of the execution stack and the information remains valid after
734 * execution continues.
735 */
736class V8EXPORT StackTrace {
737 public:
738 /**
739 * Flags that determine what information is placed captured for each
740 * StackFrame when grabbing the current stack trace.
741 */
742 enum StackTraceOptions {
743 kLineNumber = 1,
744 kColumnOffset = 1 << 1 | kLineNumber,
745 kScriptName = 1 << 2,
746 kFunctionName = 1 << 3,
747 kIsEval = 1 << 4,
748 kIsConstructor = 1 << 5,
Ben Murdochf87a2032010-10-22 12:50:53 +0100749 kScriptNameOrSourceURL = 1 << 6,
Kristian Monsen25f61362010-05-21 11:50:48 +0100750 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
Ben Murdochf87a2032010-10-22 12:50:53 +0100751 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
Kristian Monsen25f61362010-05-21 11:50:48 +0100752 };
753
754 /**
755 * Returns a StackFrame at a particular index.
756 */
757 Local<StackFrame> GetFrame(uint32_t index) const;
758
759 /**
760 * Returns the number of StackFrames.
761 */
762 int GetFrameCount() const;
763
764 /**
765 * Returns StackTrace as a v8::Array that contains StackFrame objects.
766 */
767 Local<Array> AsArray();
768
769 /**
770 * Grab a snapshot of the the current JavaScript execution stack.
771 *
772 * \param frame_limit The maximum number of stack frames we want to capture.
773 * \param options Enumerates the set of things we will capture for each
774 * StackFrame.
775 */
776 static Local<StackTrace> CurrentStackTrace(
777 int frame_limit,
778 StackTraceOptions options = kOverview);
779};
780
781
782/**
783 * A single JavaScript stack frame.
784 */
785class V8EXPORT StackFrame {
786 public:
787 /**
788 * Returns the number, 1-based, of the line for the associate function call.
789 * This method will return Message::kNoLineNumberInfo if it is unable to
790 * retrieve the line number, or if kLineNumber was not passed as an option
791 * when capturing the StackTrace.
792 */
793 int GetLineNumber() const;
794
795 /**
796 * Returns the 1-based column offset on the line for the associated function
797 * call.
798 * This method will return Message::kNoColumnInfo if it is unable to retrieve
799 * the column number, or if kColumnOffset was not passed as an option when
800 * capturing the StackTrace.
801 */
802 int GetColumn() const;
803
804 /**
805 * Returns the name of the resource that contains the script for the
806 * function for this StackFrame.
807 */
808 Local<String> GetScriptName() const;
809
810 /**
Ben Murdochf87a2032010-10-22 12:50:53 +0100811 * Returns the name of the resource that contains the script for the
812 * function for this StackFrame or sourceURL value if the script name
813 * is undefined and its source ends with //@ sourceURL=... string.
814 */
815 Local<String> GetScriptNameOrSourceURL() const;
816
817 /**
Kristian Monsen25f61362010-05-21 11:50:48 +0100818 * Returns the name of the function associated with this stack frame.
819 */
820 Local<String> GetFunctionName() const;
821
822 /**
823 * Returns whether or not the associated function is compiled via a call to
824 * eval().
825 */
826 bool IsEval() const;
827
828 /**
829 * Returns whther or not the associated function is called as a
830 * constructor via "new".
831 */
832 bool IsConstructor() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000833};
834
835
836// --- V a l u e ---
837
838
839/**
840 * The superclass of all JavaScript values and objects.
841 */
Steve Block8defd9f2010-07-08 12:39:36 +0100842class Value : public Data {
Steve Blocka7e24c12009-10-30 11:49:00 +0000843 public:
844
845 /**
846 * Returns true if this value is the undefined value. See ECMA-262
847 * 4.3.10.
848 */
Steve Block8defd9f2010-07-08 12:39:36 +0100849 V8EXPORT bool IsUndefined() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000850
851 /**
852 * Returns true if this value is the null value. See ECMA-262
853 * 4.3.11.
854 */
Steve Block8defd9f2010-07-08 12:39:36 +0100855 V8EXPORT bool IsNull() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000856
857 /**
858 * Returns true if this value is true.
859 */
Steve Block8defd9f2010-07-08 12:39:36 +0100860 V8EXPORT bool IsTrue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000861
862 /**
863 * Returns true if this value is false.
864 */
Steve Block8defd9f2010-07-08 12:39:36 +0100865 V8EXPORT bool IsFalse() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000866
867 /**
868 * Returns true if this value is an instance of the String type.
869 * See ECMA-262 8.4.
870 */
871 inline bool IsString() const;
872
873 /**
874 * Returns true if this value is a function.
875 */
Steve Block8defd9f2010-07-08 12:39:36 +0100876 V8EXPORT bool IsFunction() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000877
878 /**
879 * Returns true if this value is an array.
880 */
Steve Block8defd9f2010-07-08 12:39:36 +0100881 V8EXPORT bool IsArray() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000882
883 /**
884 * Returns true if this value is an object.
885 */
Steve Block8defd9f2010-07-08 12:39:36 +0100886 V8EXPORT bool IsObject() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000887
888 /**
889 * Returns true if this value is boolean.
890 */
Steve Block8defd9f2010-07-08 12:39:36 +0100891 V8EXPORT bool IsBoolean() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000892
893 /**
894 * Returns true if this value is a number.
895 */
Steve Block8defd9f2010-07-08 12:39:36 +0100896 V8EXPORT bool IsNumber() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000897
898 /**
899 * Returns true if this value is external.
900 */
Steve Block8defd9f2010-07-08 12:39:36 +0100901 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000902
903 /**
904 * Returns true if this value is a 32-bit signed integer.
905 */
Steve Block8defd9f2010-07-08 12:39:36 +0100906 V8EXPORT bool IsInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000907
908 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100909 * Returns true if this value is a 32-bit unsigned integer.
910 */
Steve Block8defd9f2010-07-08 12:39:36 +0100911 V8EXPORT bool IsUint32() const;
Steve Block6ded16b2010-05-10 14:33:55 +0100912
913 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000914 * Returns true if this value is a Date.
915 */
Steve Block8defd9f2010-07-08 12:39:36 +0100916 V8EXPORT bool IsDate() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000917
Iain Merrick75681382010-08-19 15:07:18 +0100918 /**
919 * Returns true if this value is a RegExp.
920 */
921 V8EXPORT bool IsRegExp() const;
922
Steve Block8defd9f2010-07-08 12:39:36 +0100923 V8EXPORT Local<Boolean> ToBoolean() const;
924 V8EXPORT Local<Number> ToNumber() const;
925 V8EXPORT Local<String> ToString() const;
926 V8EXPORT Local<String> ToDetailString() const;
927 V8EXPORT Local<Object> ToObject() const;
928 V8EXPORT Local<Integer> ToInteger() const;
929 V8EXPORT Local<Uint32> ToUint32() const;
930 V8EXPORT Local<Int32> ToInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000931
932 /**
933 * Attempts to convert a string to an array index.
934 * Returns an empty handle if the conversion fails.
935 */
Steve Block8defd9f2010-07-08 12:39:36 +0100936 V8EXPORT Local<Uint32> ToArrayIndex() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000937
Steve Block8defd9f2010-07-08 12:39:36 +0100938 V8EXPORT bool BooleanValue() const;
939 V8EXPORT double NumberValue() const;
940 V8EXPORT int64_t IntegerValue() const;
941 V8EXPORT uint32_t Uint32Value() const;
942 V8EXPORT int32_t Int32Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000943
944 /** JS == */
Steve Block8defd9f2010-07-08 12:39:36 +0100945 V8EXPORT bool Equals(Handle<Value> that) const;
946 V8EXPORT bool StrictEquals(Handle<Value> that) const;
Steve Block3ce2e202009-11-05 08:53:23 +0000947
Steve Blocka7e24c12009-10-30 11:49:00 +0000948 private:
949 inline bool QuickIsString() const;
Steve Block8defd9f2010-07-08 12:39:36 +0100950 V8EXPORT bool FullIsString() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000951};
952
953
954/**
955 * The superclass of primitive values. See ECMA-262 4.3.2.
956 */
Steve Block8defd9f2010-07-08 12:39:36 +0100957class Primitive : public Value { };
Steve Blocka7e24c12009-10-30 11:49:00 +0000958
959
960/**
961 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
962 * or false value.
963 */
Steve Block8defd9f2010-07-08 12:39:36 +0100964class Boolean : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000965 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100966 V8EXPORT bool Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000967 static inline Handle<Boolean> New(bool value);
968};
969
970
971/**
972 * A JavaScript string value (ECMA-262, 4.3.17).
973 */
Steve Block8defd9f2010-07-08 12:39:36 +0100974class String : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000975 public:
976
977 /**
978 * Returns the number of characters in this string.
979 */
Steve Block8defd9f2010-07-08 12:39:36 +0100980 V8EXPORT int Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000981
982 /**
983 * Returns the number of bytes in the UTF-8 encoded
984 * representation of this string.
985 */
Steve Block8defd9f2010-07-08 12:39:36 +0100986 V8EXPORT int Utf8Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000987
988 /**
989 * Write the contents of the string to an external buffer.
990 * If no arguments are given, expects the buffer to be large
991 * enough to hold the entire string and NULL terminator. Copies
992 * the contents of the string and the NULL terminator into the
993 * buffer.
994 *
995 * Copies up to length characters into the output buffer.
996 * Only null-terminates if there is enough space in the buffer.
997 *
998 * \param buffer The buffer into which the string will be copied.
999 * \param start The starting position within the string at which
1000 * copying begins.
1001 * \param length The number of bytes to copy from the string.
Steve Block6ded16b2010-05-10 14:33:55 +01001002 * \param nchars_ref The number of characters written, can be NULL.
1003 * \param hints Various hints that might affect performance of this or
1004 * subsequent operations.
1005 * \return The number of bytes copied to the buffer
Steve Blocka7e24c12009-10-30 11:49:00 +00001006 * excluding the NULL terminator.
1007 */
Steve Block6ded16b2010-05-10 14:33:55 +01001008 enum WriteHints {
1009 NO_HINTS = 0,
1010 HINT_MANY_WRITES_EXPECTED = 1
1011 };
1012
Steve Block8defd9f2010-07-08 12:39:36 +01001013 V8EXPORT int Write(uint16_t* buffer,
1014 int start = 0,
1015 int length = -1,
1016 WriteHints hints = NO_HINTS) const; // UTF-16
1017 V8EXPORT int WriteAscii(char* buffer,
1018 int start = 0,
1019 int length = -1,
1020 WriteHints hints = NO_HINTS) const; // ASCII
1021 V8EXPORT int WriteUtf8(char* buffer,
1022 int length = -1,
1023 int* nchars_ref = NULL,
1024 WriteHints hints = NO_HINTS) const; // UTF-8
Steve Blocka7e24c12009-10-30 11:49:00 +00001025
1026 /**
1027 * A zero length string.
1028 */
Steve Block8defd9f2010-07-08 12:39:36 +01001029 V8EXPORT static v8::Local<v8::String> Empty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001030
1031 /**
1032 * Returns true if the string is external
1033 */
Steve Block8defd9f2010-07-08 12:39:36 +01001034 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001035
1036 /**
1037 * Returns true if the string is both external and ascii
1038 */
Steve Block8defd9f2010-07-08 12:39:36 +01001039 V8EXPORT bool IsExternalAscii() const;
Leon Clarkee46be812010-01-19 14:06:41 +00001040
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001041 class V8EXPORT ExternalStringResourceBase { // NOLINT
Leon Clarkee46be812010-01-19 14:06:41 +00001042 public:
1043 virtual ~ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001044
Leon Clarkee46be812010-01-19 14:06:41 +00001045 protected:
1046 ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001047
1048 /**
1049 * Internally V8 will call this Dispose method when the external string
1050 * resource is no longer needed. The default implementation will use the
1051 * delete operator. This method can be overridden in subclasses to
1052 * control how allocated external string resources are disposed.
1053 */
1054 virtual void Dispose() { delete this; }
1055
Leon Clarkee46be812010-01-19 14:06:41 +00001056 private:
1057 // Disallow copying and assigning.
1058 ExternalStringResourceBase(const ExternalStringResourceBase&);
1059 void operator=(const ExternalStringResourceBase&);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001060
1061 friend class v8::internal::Heap;
Leon Clarkee46be812010-01-19 14:06:41 +00001062 };
1063
Steve Blocka7e24c12009-10-30 11:49:00 +00001064 /**
1065 * An ExternalStringResource is a wrapper around a two-byte string
1066 * buffer that resides outside V8's heap. Implement an
1067 * ExternalStringResource to manage the life cycle of the underlying
1068 * buffer. Note that the string data must be immutable.
1069 */
Leon Clarkee46be812010-01-19 14:06:41 +00001070 class V8EXPORT ExternalStringResource
1071 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001072 public:
1073 /**
1074 * Override the destructor to manage the life cycle of the underlying
1075 * buffer.
1076 */
1077 virtual ~ExternalStringResource() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001078
1079 /**
1080 * The string data from the underlying buffer.
1081 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001082 virtual const uint16_t* data() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001083
1084 /**
1085 * The length of the string. That is, the number of two-byte characters.
1086 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001087 virtual size_t length() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001088
Steve Blocka7e24c12009-10-30 11:49:00 +00001089 protected:
1090 ExternalStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001091 };
1092
1093 /**
1094 * An ExternalAsciiStringResource is a wrapper around an ascii
1095 * string buffer that resides outside V8's heap. Implement an
1096 * ExternalAsciiStringResource to manage the life cycle of the
1097 * underlying buffer. Note that the string data must be immutable
1098 * and that the data must be strict 7-bit ASCII, not Latin1 or
1099 * UTF-8, which would require special treatment internally in the
1100 * engine and, in the case of UTF-8, do not allow efficient indexing.
1101 * Use String::New or convert to 16 bit data for non-ASCII.
1102 */
1103
Leon Clarkee46be812010-01-19 14:06:41 +00001104 class V8EXPORT ExternalAsciiStringResource
1105 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001106 public:
1107 /**
1108 * Override the destructor to manage the life cycle of the underlying
1109 * buffer.
1110 */
1111 virtual ~ExternalAsciiStringResource() {}
1112 /** The string data from the underlying buffer.*/
1113 virtual const char* data() const = 0;
1114 /** The number of ascii characters in the string.*/
1115 virtual size_t length() const = 0;
1116 protected:
1117 ExternalAsciiStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001118 };
1119
1120 /**
1121 * Get the ExternalStringResource for an external string. Returns
1122 * NULL if IsExternal() doesn't return true.
1123 */
1124 inline ExternalStringResource* GetExternalStringResource() const;
1125
1126 /**
1127 * Get the ExternalAsciiStringResource for an external ascii string.
1128 * Returns NULL if IsExternalAscii() doesn't return true.
1129 */
Steve Block8defd9f2010-07-08 12:39:36 +01001130 V8EXPORT ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001131
1132 static inline String* Cast(v8::Value* obj);
1133
1134 /**
1135 * Allocates a new string from either utf-8 encoded or ascii data.
1136 * The second parameter 'length' gives the buffer length.
1137 * If the data is utf-8 encoded, the caller must
1138 * be careful to supply the length parameter.
1139 * If it is not given, the function calls
1140 * 'strlen' to determine the buffer length, it might be
1141 * wrong if 'data' contains a null character.
1142 */
Steve Block8defd9f2010-07-08 12:39:36 +01001143 V8EXPORT static Local<String> New(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001144
1145 /** Allocates a new string from utf16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001146 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001147
1148 /** Creates a symbol. Returns one if it exists already.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001149 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001150
1151 /**
Steve Block3ce2e202009-11-05 08:53:23 +00001152 * Creates a new string by concatenating the left and the right strings
1153 * passed in as parameters.
1154 */
Steve Block8defd9f2010-07-08 12:39:36 +01001155 V8EXPORT static Local<String> Concat(Handle<String> left,
1156 Handle<String>right);
Steve Block3ce2e202009-11-05 08:53:23 +00001157
1158 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001159 * Creates a new external string using the data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001160 * resource. When the external string is no longer live on V8's heap the
1161 * resource will be disposed by calling its Dispose method. The caller of
1162 * this function should not otherwise delete or modify the resource. Neither
1163 * should the underlying buffer be deallocated or modified except through the
1164 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001165 */
Steve Block8defd9f2010-07-08 12:39:36 +01001166 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001167
1168 /**
1169 * Associate an external string resource with this string by transforming it
1170 * in place so that existing references to this string in the JavaScript heap
1171 * will use the external string resource. The external string resource's
1172 * character contents needs to be equivalent to this string.
1173 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001174 * The string is not modified if the operation fails. See NewExternal for
1175 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001176 */
Steve Block8defd9f2010-07-08 12:39:36 +01001177 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001178
1179 /**
1180 * Creates a new external string using the ascii data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001181 * resource. When the external string is no longer live on V8's heap the
1182 * resource will be disposed by calling its Dispose method. The caller of
1183 * this function should not otherwise delete or modify the resource. Neither
1184 * should the underlying buffer be deallocated or modified except through the
1185 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001186 */
Steve Block8defd9f2010-07-08 12:39:36 +01001187 V8EXPORT static Local<String> NewExternal(
1188 ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001189
1190 /**
1191 * Associate an external string resource with this string by transforming it
1192 * in place so that existing references to this string in the JavaScript heap
1193 * will use the external string resource. The external string resource's
1194 * character contents needs to be equivalent to this string.
1195 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001196 * The string is not modified if the operation fails. See NewExternal for
1197 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001198 */
Steve Block8defd9f2010-07-08 12:39:36 +01001199 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001200
1201 /**
1202 * Returns true if this string can be made external.
1203 */
Steve Block8defd9f2010-07-08 12:39:36 +01001204 V8EXPORT bool CanMakeExternal();
Steve Blocka7e24c12009-10-30 11:49:00 +00001205
1206 /** Creates an undetectable string from the supplied ascii or utf-8 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001207 V8EXPORT static Local<String> NewUndetectable(const char* data,
1208 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001209
1210 /** Creates an undetectable string from the supplied utf-16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001211 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1212 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001213
1214 /**
1215 * Converts an object to a utf8-encoded character array. Useful if
1216 * you want to print the object. If conversion to a string fails
1217 * (eg. due to an exception in the toString() method of the object)
1218 * then the length() method returns 0 and the * operator returns
1219 * NULL.
1220 */
1221 class V8EXPORT Utf8Value {
1222 public:
1223 explicit Utf8Value(Handle<v8::Value> obj);
1224 ~Utf8Value();
1225 char* operator*() { return str_; }
1226 const char* operator*() const { return str_; }
1227 int length() const { return length_; }
1228 private:
1229 char* str_;
1230 int length_;
1231
1232 // Disallow copying and assigning.
1233 Utf8Value(const Utf8Value&);
1234 void operator=(const Utf8Value&);
1235 };
1236
1237 /**
1238 * Converts an object to an ascii string.
1239 * Useful if you want to print the object.
1240 * If conversion to a string fails (eg. due to an exception in the toString()
1241 * method of the object) then the length() method returns 0 and the * operator
1242 * returns NULL.
1243 */
1244 class V8EXPORT AsciiValue {
1245 public:
1246 explicit AsciiValue(Handle<v8::Value> obj);
1247 ~AsciiValue();
1248 char* operator*() { return str_; }
1249 const char* operator*() const { return str_; }
1250 int length() const { return length_; }
1251 private:
1252 char* str_;
1253 int length_;
1254
1255 // Disallow copying and assigning.
1256 AsciiValue(const AsciiValue&);
1257 void operator=(const AsciiValue&);
1258 };
1259
1260 /**
1261 * Converts an object to a two-byte string.
1262 * If conversion to a string fails (eg. due to an exception in the toString()
1263 * method of the object) then the length() method returns 0 and the * operator
1264 * returns NULL.
1265 */
1266 class V8EXPORT Value {
1267 public:
1268 explicit Value(Handle<v8::Value> obj);
1269 ~Value();
1270 uint16_t* operator*() { return str_; }
1271 const uint16_t* operator*() const { return str_; }
1272 int length() const { return length_; }
1273 private:
1274 uint16_t* str_;
1275 int length_;
1276
1277 // Disallow copying and assigning.
1278 Value(const Value&);
1279 void operator=(const Value&);
1280 };
Steve Block3ce2e202009-11-05 08:53:23 +00001281
Steve Blocka7e24c12009-10-30 11:49:00 +00001282 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001283 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1284 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001285};
1286
1287
1288/**
1289 * A JavaScript number value (ECMA-262, 4.3.20)
1290 */
Steve Block8defd9f2010-07-08 12:39:36 +01001291class Number : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001292 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001293 V8EXPORT double Value() const;
1294 V8EXPORT static Local<Number> New(double value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001295 static inline Number* Cast(v8::Value* obj);
1296 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001297 V8EXPORT Number();
Steve Blocka7e24c12009-10-30 11:49:00 +00001298 static void CheckCast(v8::Value* obj);
1299};
1300
1301
1302/**
1303 * A JavaScript value representing a signed integer.
1304 */
Steve Block8defd9f2010-07-08 12:39:36 +01001305class Integer : public Number {
Steve Blocka7e24c12009-10-30 11:49:00 +00001306 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001307 V8EXPORT static Local<Integer> New(int32_t value);
1308 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1309 V8EXPORT int64_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001310 static inline Integer* Cast(v8::Value* obj);
1311 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001312 V8EXPORT Integer();
1313 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001314};
1315
1316
1317/**
1318 * A JavaScript value representing a 32-bit signed integer.
1319 */
Steve Block8defd9f2010-07-08 12:39:36 +01001320class Int32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001321 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001322 V8EXPORT int32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001323 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001324 V8EXPORT Int32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001325};
1326
1327
1328/**
1329 * A JavaScript value representing a 32-bit unsigned integer.
1330 */
Steve Block8defd9f2010-07-08 12:39:36 +01001331class Uint32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001332 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001333 V8EXPORT uint32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001334 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001335 V8EXPORT Uint32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001336};
1337
1338
1339/**
1340 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1341 */
Steve Block8defd9f2010-07-08 12:39:36 +01001342class Date : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001343 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001344 V8EXPORT static Local<Value> New(double time);
Steve Blocka7e24c12009-10-30 11:49:00 +00001345
1346 /**
1347 * A specialization of Value::NumberValue that is more efficient
1348 * because we know the structure of this object.
1349 */
Steve Block8defd9f2010-07-08 12:39:36 +01001350 V8EXPORT double NumberValue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001351
1352 static inline Date* Cast(v8::Value* obj);
1353 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001354 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001355};
1356
1357
Ben Murdochf87a2032010-10-22 12:50:53 +01001358/**
1359 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1360 */
1361class RegExp : public Value {
1362 public:
1363 /**
1364 * Regular expression flag bits. They can be or'ed to enable a set
1365 * of flags.
1366 */
1367 enum Flags {
1368 kNone = 0,
1369 kGlobal = 1,
1370 kIgnoreCase = 2,
1371 kMultiline = 4
1372 };
1373
1374 /**
1375 * Creates a regular expression from the given pattern string and
1376 * the flags bit field. May throw a JavaScript exception as
1377 * described in ECMA-262, 15.10.4.1.
1378 *
1379 * For example,
1380 * RegExp::New(v8::String::New("foo"),
1381 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1382 * is equivalent to evaluating "/foo/gm".
1383 */
1384 V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1385 Flags flags);
1386
1387 /**
1388 * Returns the value of the source property: a string representing
1389 * the regular expression.
1390 */
1391 V8EXPORT Local<String> GetSource() const;
1392
1393 /**
1394 * Returns the flags bit field.
1395 */
1396 V8EXPORT Flags GetFlags() const;
1397
1398 static inline RegExp* Cast(v8::Value* obj);
1399
1400 private:
1401 V8EXPORT static void CheckCast(v8::Value* obj);
1402};
1403
1404
Steve Blocka7e24c12009-10-30 11:49:00 +00001405enum PropertyAttribute {
1406 None = 0,
1407 ReadOnly = 1 << 0,
1408 DontEnum = 1 << 1,
1409 DontDelete = 1 << 2
1410};
1411
Steve Block3ce2e202009-11-05 08:53:23 +00001412enum ExternalArrayType {
1413 kExternalByteArray = 1,
1414 kExternalUnsignedByteArray,
1415 kExternalShortArray,
1416 kExternalUnsignedShortArray,
1417 kExternalIntArray,
1418 kExternalUnsignedIntArray,
1419 kExternalFloatArray
1420};
1421
Steve Blocka7e24c12009-10-30 11:49:00 +00001422/**
Leon Clarkef7060e22010-06-03 12:02:55 +01001423 * Accessor[Getter|Setter] are used as callback functions when
1424 * setting|getting a particular property. See Object and ObjectTemplate's
1425 * method SetAccessor.
1426 */
1427typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1428 const AccessorInfo& info);
1429
1430
1431typedef void (*AccessorSetter)(Local<String> property,
1432 Local<Value> value,
1433 const AccessorInfo& info);
1434
1435
1436/**
1437 * Access control specifications.
1438 *
1439 * Some accessors should be accessible across contexts. These
1440 * accessors have an explicit access control parameter which specifies
1441 * the kind of cross-context access that should be allowed.
1442 *
1443 * Additionally, for security, accessors can prohibit overwriting by
1444 * accessors defined in JavaScript. For objects that have such
1445 * accessors either locally or in their prototype chain it is not
1446 * possible to overwrite the accessor by using __defineGetter__ or
1447 * __defineSetter__ from JavaScript code.
1448 */
1449enum AccessControl {
1450 DEFAULT = 0,
1451 ALL_CAN_READ = 1,
1452 ALL_CAN_WRITE = 1 << 1,
1453 PROHIBITS_OVERWRITING = 1 << 2
1454};
1455
1456
1457/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001458 * A JavaScript object (ECMA-262, 4.3.3)
1459 */
Steve Block8defd9f2010-07-08 12:39:36 +01001460class Object : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001461 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001462 V8EXPORT bool Set(Handle<Value> key,
1463 Handle<Value> value,
1464 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001465
Steve Block8defd9f2010-07-08 12:39:36 +01001466 V8EXPORT bool Set(uint32_t index,
1467 Handle<Value> value);
Steve Block6ded16b2010-05-10 14:33:55 +01001468
Steve Blocka7e24c12009-10-30 11:49:00 +00001469 // Sets a local property on this object bypassing interceptors and
1470 // overriding accessors or read-only properties.
1471 //
1472 // Note that if the object has an interceptor the property will be set
1473 // locally, but since the interceptor takes precedence the local property
1474 // will only be returned if the interceptor doesn't return a value.
1475 //
1476 // Note also that this only works for named properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001477 V8EXPORT bool ForceSet(Handle<Value> key,
1478 Handle<Value> value,
1479 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001480
Steve Block8defd9f2010-07-08 12:39:36 +01001481 V8EXPORT Local<Value> Get(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001482
Steve Block8defd9f2010-07-08 12:39:36 +01001483 V8EXPORT Local<Value> Get(uint32_t index);
Steve Block6ded16b2010-05-10 14:33:55 +01001484
Steve Blocka7e24c12009-10-30 11:49:00 +00001485 // TODO(1245389): Replace the type-specific versions of these
1486 // functions with generic ones that accept a Handle<Value> key.
Steve Block8defd9f2010-07-08 12:39:36 +01001487 V8EXPORT bool Has(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001488
Steve Block8defd9f2010-07-08 12:39:36 +01001489 V8EXPORT bool Delete(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001490
1491 // Delete a property on this object bypassing interceptors and
1492 // ignoring dont-delete attributes.
Steve Block8defd9f2010-07-08 12:39:36 +01001493 V8EXPORT bool ForceDelete(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001494
Steve Block8defd9f2010-07-08 12:39:36 +01001495 V8EXPORT bool Has(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001496
Steve Block8defd9f2010-07-08 12:39:36 +01001497 V8EXPORT bool Delete(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001498
Steve Block8defd9f2010-07-08 12:39:36 +01001499 V8EXPORT bool SetAccessor(Handle<String> name,
1500 AccessorGetter getter,
1501 AccessorSetter setter = 0,
1502 Handle<Value> data = Handle<Value>(),
1503 AccessControl settings = DEFAULT,
1504 PropertyAttribute attribute = None);
Leon Clarkef7060e22010-06-03 12:02:55 +01001505
Steve Blocka7e24c12009-10-30 11:49:00 +00001506 /**
1507 * Returns an array containing the names of the enumerable properties
1508 * of this object, including properties from prototype objects. The
1509 * array returned by this method contains the same values as would
1510 * be enumerated by a for-in statement over this object.
1511 */
Steve Block8defd9f2010-07-08 12:39:36 +01001512 V8EXPORT Local<Array> GetPropertyNames();
Steve Blocka7e24c12009-10-30 11:49:00 +00001513
1514 /**
1515 * Get the prototype object. This does not skip objects marked to
1516 * be skipped by __proto__ and it does not consult the security
1517 * handler.
1518 */
Steve Block8defd9f2010-07-08 12:39:36 +01001519 V8EXPORT Local<Value> GetPrototype();
Steve Blocka7e24c12009-10-30 11:49:00 +00001520
1521 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001522 * Set the prototype object. This does not skip objects marked to
1523 * be skipped by __proto__ and it does not consult the security
1524 * handler.
1525 */
Steve Block8defd9f2010-07-08 12:39:36 +01001526 V8EXPORT bool SetPrototype(Handle<Value> prototype);
Andrei Popescu402d9372010-02-26 13:31:12 +00001527
1528 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001529 * Finds an instance of the given function template in the prototype
1530 * chain.
1531 */
Steve Block8defd9f2010-07-08 12:39:36 +01001532 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1533 Handle<FunctionTemplate> tmpl);
Steve Blocka7e24c12009-10-30 11:49:00 +00001534
1535 /**
1536 * Call builtin Object.prototype.toString on this object.
1537 * This is different from Value::ToString() that may call
1538 * user-defined toString function. This one does not.
1539 */
Steve Block8defd9f2010-07-08 12:39:36 +01001540 V8EXPORT Local<String> ObjectProtoToString();
Steve Blocka7e24c12009-10-30 11:49:00 +00001541
1542 /** Gets the number of internal fields for this Object. */
Steve Block8defd9f2010-07-08 12:39:36 +01001543 V8EXPORT int InternalFieldCount();
Steve Blocka7e24c12009-10-30 11:49:00 +00001544 /** Gets the value in an internal field. */
1545 inline Local<Value> GetInternalField(int index);
1546 /** Sets the value in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001547 V8EXPORT void SetInternalField(int index, Handle<Value> value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001548
1549 /** Gets a native pointer from an internal field. */
1550 inline void* GetPointerFromInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001551
Steve Blocka7e24c12009-10-30 11:49:00 +00001552 /** Sets a native pointer in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001553 V8EXPORT void SetPointerInInternalField(int index, void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001554
1555 // Testers for local properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001556 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1557 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1558 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001559
1560 /**
1561 * If result.IsEmpty() no real property was located in the prototype chain.
1562 * This means interceptors in the prototype chain are not called.
1563 */
Steve Block8defd9f2010-07-08 12:39:36 +01001564 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1565 Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001566
1567 /**
1568 * If result.IsEmpty() no real property was located on the object or
1569 * in the prototype chain.
1570 * This means interceptors in the prototype chain are not called.
1571 */
Steve Block8defd9f2010-07-08 12:39:36 +01001572 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001573
1574 /** Tests for a named lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001575 V8EXPORT bool HasNamedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001576
1577 /** Tests for an index lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001578 V8EXPORT bool HasIndexedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001579
1580 /**
1581 * Turns on access check on the object if the object is an instance of
1582 * a template that has access check callbacks. If an object has no
1583 * access check info, the object cannot be accessed by anyone.
1584 */
Steve Block8defd9f2010-07-08 12:39:36 +01001585 V8EXPORT void TurnOnAccessCheck();
Steve Blocka7e24c12009-10-30 11:49:00 +00001586
1587 /**
1588 * Returns the identity hash for this object. The current implemenation uses
1589 * a hidden property on the object to store the identity hash.
1590 *
1591 * The return value will never be 0. Also, it is not guaranteed to be
1592 * unique.
1593 */
Steve Block8defd9f2010-07-08 12:39:36 +01001594 V8EXPORT int GetIdentityHash();
Steve Blocka7e24c12009-10-30 11:49:00 +00001595
1596 /**
1597 * Access hidden properties on JavaScript objects. These properties are
1598 * hidden from the executing JavaScript and only accessible through the V8
1599 * C++ API. Hidden properties introduced by V8 internally (for example the
1600 * identity hash) are prefixed with "v8::".
1601 */
Steve Block8defd9f2010-07-08 12:39:36 +01001602 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1603 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1604 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
Steve Block3ce2e202009-11-05 08:53:23 +00001605
Steve Blocka7e24c12009-10-30 11:49:00 +00001606 /**
1607 * Returns true if this is an instance of an api function (one
1608 * created from a function created from a function template) and has
1609 * been modified since it was created. Note that this method is
1610 * conservative and may return true for objects that haven't actually
1611 * been modified.
1612 */
Steve Block8defd9f2010-07-08 12:39:36 +01001613 V8EXPORT bool IsDirty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001614
1615 /**
1616 * Clone this object with a fast but shallow copy. Values will point
1617 * to the same values as the original object.
1618 */
Steve Block8defd9f2010-07-08 12:39:36 +01001619 V8EXPORT Local<Object> Clone();
Steve Blocka7e24c12009-10-30 11:49:00 +00001620
1621 /**
1622 * Set the backing store of the indexed properties to be managed by the
1623 * embedding layer. Access to the indexed properties will follow the rules
1624 * spelled out in CanvasPixelArray.
1625 * Note: The embedding program still owns the data and needs to ensure that
1626 * the backing store is preserved while V8 has a reference.
1627 */
Steve Block8defd9f2010-07-08 12:39:36 +01001628 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001629 bool HasIndexedPropertiesInPixelData();
1630 uint8_t* GetIndexedPropertiesPixelData();
1631 int GetIndexedPropertiesPixelDataLength();
Steve Blocka7e24c12009-10-30 11:49:00 +00001632
Steve Block3ce2e202009-11-05 08:53:23 +00001633 /**
1634 * Set the backing store of the indexed properties to be managed by the
1635 * embedding layer. Access to the indexed properties will follow the rules
1636 * spelled out for the CanvasArray subtypes in the WebGL specification.
1637 * Note: The embedding program still owns the data and needs to ensure that
1638 * the backing store is preserved while V8 has a reference.
1639 */
Steve Block8defd9f2010-07-08 12:39:36 +01001640 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1641 void* data,
1642 ExternalArrayType array_type,
1643 int number_of_elements);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001644 bool HasIndexedPropertiesInExternalArrayData();
1645 void* GetIndexedPropertiesExternalArrayData();
1646 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1647 int GetIndexedPropertiesExternalArrayDataLength();
Steve Block3ce2e202009-11-05 08:53:23 +00001648
Steve Block8defd9f2010-07-08 12:39:36 +01001649 V8EXPORT static Local<Object> New();
Steve Blocka7e24c12009-10-30 11:49:00 +00001650 static inline Object* Cast(Value* obj);
1651 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001652 V8EXPORT Object();
1653 V8EXPORT static void CheckCast(Value* obj);
1654 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1655 V8EXPORT void* SlowGetPointerFromInternalField(int index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001656
1657 /**
1658 * If quick access to the internal field is possible this method
Steve Block3ce2e202009-11-05 08:53:23 +00001659 * returns the value. Otherwise an empty handle is returned.
Steve Blocka7e24c12009-10-30 11:49:00 +00001660 */
1661 inline Local<Value> UncheckedGetInternalField(int index);
1662};
1663
1664
1665/**
1666 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1667 */
Steve Block8defd9f2010-07-08 12:39:36 +01001668class Array : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001669 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001670 V8EXPORT uint32_t Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001671
1672 /**
1673 * Clones an element at index |index|. Returns an empty
1674 * handle if cloning fails (for any reason).
1675 */
Steve Block8defd9f2010-07-08 12:39:36 +01001676 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001677
Steve Block8defd9f2010-07-08 12:39:36 +01001678 V8EXPORT static Local<Array> New(int length = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001679 static inline Array* Cast(Value* obj);
1680 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001681 V8EXPORT Array();
Steve Blocka7e24c12009-10-30 11:49:00 +00001682 static void CheckCast(Value* obj);
1683};
1684
1685
1686/**
1687 * A JavaScript function object (ECMA-262, 15.3).
1688 */
Steve Block8defd9f2010-07-08 12:39:36 +01001689class Function : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001690 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001691 V8EXPORT Local<Object> NewInstance() const;
1692 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1693 V8EXPORT Local<Value> Call(Handle<Object> recv,
1694 int argc,
1695 Handle<Value> argv[]);
1696 V8EXPORT void SetName(Handle<String> name);
1697 V8EXPORT Handle<Value> GetName() const;
Andrei Popescu402d9372010-02-26 13:31:12 +00001698
1699 /**
1700 * Returns zero based line number of function body and
1701 * kLineOffsetNotFound if no information available.
1702 */
Steve Block8defd9f2010-07-08 12:39:36 +01001703 V8EXPORT int GetScriptLineNumber() const;
1704 V8EXPORT ScriptOrigin GetScriptOrigin() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001705 static inline Function* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001706 V8EXPORT static const int kLineOffsetNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00001707 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001708 V8EXPORT Function();
1709 V8EXPORT static void CheckCast(Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001710};
1711
1712
1713/**
1714 * A JavaScript value that wraps a C++ void*. This type of value is
1715 * mainly used to associate C++ data structures with JavaScript
1716 * objects.
1717 *
1718 * The Wrap function V8 will return the most optimal Value object wrapping the
1719 * C++ void*. The type of the value is not guaranteed to be an External object
1720 * and no assumptions about its type should be made. To access the wrapped
1721 * value Unwrap should be used, all other operations on that object will lead
1722 * to unpredictable results.
1723 */
Steve Block8defd9f2010-07-08 12:39:36 +01001724class External : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001725 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001726 V8EXPORT static Local<Value> Wrap(void* data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001727 static inline void* Unwrap(Handle<Value> obj);
1728
Steve Block8defd9f2010-07-08 12:39:36 +01001729 V8EXPORT static Local<External> New(void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001730 static inline External* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001731 V8EXPORT void* Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001732 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001733 V8EXPORT External();
1734 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001735 static inline void* QuickUnwrap(Handle<v8::Value> obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001736 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001737};
1738
1739
1740// --- T e m p l a t e s ---
1741
1742
1743/**
1744 * The superclass of object and function templates.
1745 */
1746class V8EXPORT Template : public Data {
1747 public:
1748 /** Adds a property to each instance created by this template.*/
1749 void Set(Handle<String> name, Handle<Data> value,
1750 PropertyAttribute attributes = None);
1751 inline void Set(const char* name, Handle<Data> value);
1752 private:
1753 Template();
1754
1755 friend class ObjectTemplate;
1756 friend class FunctionTemplate;
1757};
1758
1759
1760/**
1761 * The argument information given to function call callbacks. This
1762 * class provides access to information about the context of the call,
1763 * including the receiver, the number and values of arguments, and
1764 * the holder of the function.
1765 */
Steve Block8defd9f2010-07-08 12:39:36 +01001766class Arguments {
Steve Blocka7e24c12009-10-30 11:49:00 +00001767 public:
1768 inline int Length() const;
1769 inline Local<Value> operator[](int i) const;
1770 inline Local<Function> Callee() const;
1771 inline Local<Object> This() const;
1772 inline Local<Object> Holder() const;
1773 inline bool IsConstructCall() const;
1774 inline Local<Value> Data() const;
1775 private:
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001776 static const int kDataIndex = 0;
1777 static const int kCalleeIndex = -1;
1778 static const int kHolderIndex = -2;
1779
Steve Blocka7e24c12009-10-30 11:49:00 +00001780 friend class ImplementationUtilities;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001781 inline Arguments(internal::Object** implicit_args,
1782 internal::Object** values,
1783 int length,
1784 bool is_construct_call);
1785 internal::Object** implicit_args_;
1786 internal::Object** values_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001787 int length_;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001788 bool is_construct_call_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001789};
1790
1791
1792/**
1793 * The information passed to an accessor callback about the context
1794 * of the property access.
1795 */
1796class V8EXPORT AccessorInfo {
1797 public:
1798 inline AccessorInfo(internal::Object** args)
1799 : args_(args) { }
1800 inline Local<Value> Data() const;
1801 inline Local<Object> This() const;
1802 inline Local<Object> Holder() const;
1803 private:
1804 internal::Object** args_;
1805};
1806
1807
1808typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1809
Steve Blocka7e24c12009-10-30 11:49:00 +00001810/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001811 * NamedProperty[Getter|Setter] are used as interceptors on object.
1812 * See ObjectTemplate::SetNamedPropertyHandler.
1813 */
1814typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
1815 const AccessorInfo& info);
1816
1817
1818/**
1819 * Returns the value if the setter intercepts the request.
1820 * Otherwise, returns an empty handle.
1821 */
1822typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
1823 Local<Value> value,
1824 const AccessorInfo& info);
1825
Steve Blocka7e24c12009-10-30 11:49:00 +00001826/**
1827 * Returns a non-empty handle if the interceptor intercepts the request.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001828 * The result is an integer encoding property attributes (like v8::None,
1829 * v8::DontEnum, etc.)
Steve Blocka7e24c12009-10-30 11:49:00 +00001830 */
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001831typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
1832 const AccessorInfo& info);
Steve Blocka7e24c12009-10-30 11:49:00 +00001833
1834
1835/**
1836 * Returns a non-empty handle if the deleter intercepts the request.
1837 * The return value is true if the property could be deleted and false
1838 * otherwise.
1839 */
1840typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
1841 const AccessorInfo& info);
1842
1843/**
1844 * Returns an array containing the names of the properties the named
1845 * property getter intercepts.
1846 */
1847typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
1848
1849
1850/**
1851 * Returns the value of the property if the getter intercepts the
1852 * request. Otherwise, returns an empty handle.
1853 */
1854typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
1855 const AccessorInfo& info);
1856
1857
1858/**
1859 * Returns the value if the setter intercepts the request.
1860 * Otherwise, returns an empty handle.
1861 */
1862typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
1863 Local<Value> value,
1864 const AccessorInfo& info);
1865
1866
1867/**
1868 * Returns a non-empty handle if the interceptor intercepts the request.
Iain Merrick75681382010-08-19 15:07:18 +01001869 * The result is an integer encoding property attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00001870 */
Iain Merrick75681382010-08-19 15:07:18 +01001871typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
Steve Blocka7e24c12009-10-30 11:49:00 +00001872 const AccessorInfo& info);
1873
1874/**
1875 * Returns a non-empty handle if the deleter intercepts the request.
1876 * The return value is true if the property could be deleted and false
1877 * otherwise.
1878 */
1879typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
1880 const AccessorInfo& info);
1881
1882/**
1883 * Returns an array containing the indices of the properties the
1884 * indexed property getter intercepts.
1885 */
1886typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
1887
1888
1889/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001890 * Access type specification.
1891 */
1892enum AccessType {
1893 ACCESS_GET,
1894 ACCESS_SET,
1895 ACCESS_HAS,
1896 ACCESS_DELETE,
1897 ACCESS_KEYS
1898};
1899
1900
1901/**
1902 * Returns true if cross-context access should be allowed to the named
1903 * property with the given key on the host object.
1904 */
1905typedef bool (*NamedSecurityCallback)(Local<Object> host,
1906 Local<Value> key,
1907 AccessType type,
1908 Local<Value> data);
1909
1910
1911/**
1912 * Returns true if cross-context access should be allowed to the indexed
1913 * property with the given index on the host object.
1914 */
1915typedef bool (*IndexedSecurityCallback)(Local<Object> host,
1916 uint32_t index,
1917 AccessType type,
1918 Local<Value> data);
1919
1920
1921/**
1922 * A FunctionTemplate is used to create functions at runtime. There
1923 * can only be one function created from a FunctionTemplate in a
1924 * context. The lifetime of the created function is equal to the
1925 * lifetime of the context. So in case the embedder needs to create
1926 * temporary functions that can be collected using Scripts is
1927 * preferred.
1928 *
1929 * A FunctionTemplate can have properties, these properties are added to the
1930 * function object when it is created.
1931 *
1932 * A FunctionTemplate has a corresponding instance template which is
1933 * used to create object instances when the function is used as a
1934 * constructor. Properties added to the instance template are added to
1935 * each object instance.
1936 *
1937 * A FunctionTemplate can have a prototype template. The prototype template
1938 * is used to create the prototype object of the function.
1939 *
1940 * The following example shows how to use a FunctionTemplate:
1941 *
1942 * \code
1943 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
1944 * t->Set("func_property", v8::Number::New(1));
1945 *
1946 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
1947 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
1948 * proto_t->Set("proto_const", v8::Number::New(2));
1949 *
1950 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
1951 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
1952 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
1953 * instance_t->Set("instance_property", Number::New(3));
1954 *
1955 * v8::Local<v8::Function> function = t->GetFunction();
1956 * v8::Local<v8::Object> instance = function->NewInstance();
1957 * \endcode
1958 *
1959 * Let's use "function" as the JS variable name of the function object
1960 * and "instance" for the instance object created above. The function
1961 * and the instance will have the following properties:
1962 *
1963 * \code
1964 * func_property in function == true;
1965 * function.func_property == 1;
1966 *
1967 * function.prototype.proto_method() invokes 'InvokeCallback'
1968 * function.prototype.proto_const == 2;
1969 *
1970 * instance instanceof function == true;
1971 * instance.instance_accessor calls 'InstanceAccessorCallback'
1972 * instance.instance_property == 3;
1973 * \endcode
1974 *
1975 * A FunctionTemplate can inherit from another one by calling the
1976 * FunctionTemplate::Inherit method. The following graph illustrates
1977 * the semantics of inheritance:
1978 *
1979 * \code
1980 * FunctionTemplate Parent -> Parent() . prototype -> { }
1981 * ^ ^
1982 * | Inherit(Parent) | .__proto__
1983 * | |
1984 * FunctionTemplate Child -> Child() . prototype -> { }
1985 * \endcode
1986 *
1987 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
1988 * object of the Child() function has __proto__ pointing to the
1989 * Parent() function's prototype object. An instance of the Child
1990 * function has all properties on Parent's instance templates.
1991 *
1992 * Let Parent be the FunctionTemplate initialized in the previous
1993 * section and create a Child FunctionTemplate by:
1994 *
1995 * \code
1996 * Local<FunctionTemplate> parent = t;
1997 * Local<FunctionTemplate> child = FunctionTemplate::New();
1998 * child->Inherit(parent);
1999 *
2000 * Local<Function> child_function = child->GetFunction();
2001 * Local<Object> child_instance = child_function->NewInstance();
2002 * \endcode
2003 *
2004 * The Child function and Child instance will have the following
2005 * properties:
2006 *
2007 * \code
2008 * child_func.prototype.__proto__ == function.prototype;
2009 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2010 * child_instance.instance_property == 3;
2011 * \endcode
2012 */
2013class V8EXPORT FunctionTemplate : public Template {
2014 public:
2015 /** Creates a function template.*/
2016 static Local<FunctionTemplate> New(
2017 InvocationCallback callback = 0,
2018 Handle<Value> data = Handle<Value>(),
2019 Handle<Signature> signature = Handle<Signature>());
2020 /** Returns the unique function instance in the current execution context.*/
2021 Local<Function> GetFunction();
2022
2023 /**
2024 * Set the call-handler callback for a FunctionTemplate. This
2025 * callback is called whenever the function created from this
2026 * FunctionTemplate is called.
2027 */
2028 void SetCallHandler(InvocationCallback callback,
2029 Handle<Value> data = Handle<Value>());
2030
2031 /** Get the InstanceTemplate. */
2032 Local<ObjectTemplate> InstanceTemplate();
2033
2034 /** Causes the function template to inherit from a parent function template.*/
2035 void Inherit(Handle<FunctionTemplate> parent);
2036
2037 /**
2038 * A PrototypeTemplate is the template used to create the prototype object
2039 * of the function created by this template.
2040 */
2041 Local<ObjectTemplate> PrototypeTemplate();
2042
2043
2044 /**
2045 * Set the class name of the FunctionTemplate. This is used for
2046 * printing objects created with the function created from the
2047 * FunctionTemplate as its constructor.
2048 */
2049 void SetClassName(Handle<String> name);
2050
2051 /**
2052 * Determines whether the __proto__ accessor ignores instances of
2053 * the function template. If instances of the function template are
2054 * ignored, __proto__ skips all instances and instead returns the
2055 * next object in the prototype chain.
2056 *
2057 * Call with a value of true to make the __proto__ accessor ignore
2058 * instances of the function template. Call with a value of false
2059 * to make the __proto__ accessor not ignore instances of the
2060 * function template. By default, instances of a function template
2061 * are not ignored.
2062 */
2063 void SetHiddenPrototype(bool value);
2064
2065 /**
2066 * Returns true if the given object is an instance of this function
2067 * template.
2068 */
2069 bool HasInstance(Handle<Value> object);
2070
2071 private:
2072 FunctionTemplate();
2073 void AddInstancePropertyAccessor(Handle<String> name,
2074 AccessorGetter getter,
2075 AccessorSetter setter,
2076 Handle<Value> data,
2077 AccessControl settings,
2078 PropertyAttribute attributes);
2079 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2080 NamedPropertySetter setter,
2081 NamedPropertyQuery query,
2082 NamedPropertyDeleter remover,
2083 NamedPropertyEnumerator enumerator,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002084 Handle<Value> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00002085 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2086 IndexedPropertySetter setter,
2087 IndexedPropertyQuery query,
2088 IndexedPropertyDeleter remover,
2089 IndexedPropertyEnumerator enumerator,
2090 Handle<Value> data);
2091 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2092 Handle<Value> data);
2093
2094 friend class Context;
2095 friend class ObjectTemplate;
2096};
2097
2098
2099/**
2100 * An ObjectTemplate is used to create objects at runtime.
2101 *
2102 * Properties added to an ObjectTemplate are added to each object
2103 * created from the ObjectTemplate.
2104 */
2105class V8EXPORT ObjectTemplate : public Template {
2106 public:
2107 /** Creates an ObjectTemplate. */
2108 static Local<ObjectTemplate> New();
2109
2110 /** Creates a new instance of this template.*/
2111 Local<Object> NewInstance();
2112
2113 /**
2114 * Sets an accessor on the object template.
2115 *
2116 * Whenever the property with the given name is accessed on objects
2117 * created from this ObjectTemplate the getter and setter callbacks
2118 * are called instead of getting and setting the property directly
2119 * on the JavaScript object.
2120 *
2121 * \param name The name of the property for which an accessor is added.
2122 * \param getter The callback to invoke when getting the property.
2123 * \param setter The callback to invoke when setting the property.
2124 * \param data A piece of data that will be passed to the getter and setter
2125 * callbacks whenever they are invoked.
2126 * \param settings Access control settings for the accessor. This is a bit
2127 * field consisting of one of more of
2128 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2129 * The default is to not allow cross-context access.
2130 * ALL_CAN_READ means that all cross-context reads are allowed.
2131 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2132 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2133 * cross-context access.
2134 * \param attribute The attributes of the property for which an accessor
2135 * is added.
2136 */
2137 void SetAccessor(Handle<String> name,
2138 AccessorGetter getter,
2139 AccessorSetter setter = 0,
2140 Handle<Value> data = Handle<Value>(),
2141 AccessControl settings = DEFAULT,
2142 PropertyAttribute attribute = None);
2143
2144 /**
2145 * Sets a named property handler on the object template.
2146 *
2147 * Whenever a named property is accessed on objects created from
2148 * this object template, the provided callback is invoked instead of
2149 * accessing the property directly on the JavaScript object.
2150 *
2151 * \param getter The callback to invoke when getting a property.
2152 * \param setter The callback to invoke when setting a property.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002153 * \param query The callback to invoke to check if a property is present,
2154 * and if present, get its attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00002155 * \param deleter The callback to invoke when deleting a property.
2156 * \param enumerator The callback to invoke to enumerate all the named
2157 * properties of an object.
2158 * \param data A piece of data that will be passed to the callbacks
2159 * whenever they are invoked.
2160 */
2161 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2162 NamedPropertySetter setter = 0,
2163 NamedPropertyQuery query = 0,
2164 NamedPropertyDeleter deleter = 0,
2165 NamedPropertyEnumerator enumerator = 0,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002166 Handle<Value> data = Handle<Value>());
Steve Blocka7e24c12009-10-30 11:49:00 +00002167
2168 /**
2169 * Sets an indexed property handler on the object template.
2170 *
2171 * Whenever an indexed property is accessed on objects created from
2172 * this object template, the provided callback is invoked instead of
2173 * accessing the property directly on the JavaScript object.
2174 *
2175 * \param getter The callback to invoke when getting a property.
2176 * \param setter The callback to invoke when setting a property.
2177 * \param query The callback to invoke to check is an object has a property.
2178 * \param deleter The callback to invoke when deleting a property.
2179 * \param enumerator The callback to invoke to enumerate all the indexed
2180 * properties of an object.
2181 * \param data A piece of data that will be passed to the callbacks
2182 * whenever they are invoked.
2183 */
2184 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2185 IndexedPropertySetter setter = 0,
2186 IndexedPropertyQuery query = 0,
2187 IndexedPropertyDeleter deleter = 0,
2188 IndexedPropertyEnumerator enumerator = 0,
2189 Handle<Value> data = Handle<Value>());
Iain Merrick75681382010-08-19 15:07:18 +01002190
Steve Blocka7e24c12009-10-30 11:49:00 +00002191 /**
2192 * Sets the callback to be used when calling instances created from
2193 * this template as a function. If no callback is set, instances
2194 * behave like normal JavaScript objects that cannot be called as a
2195 * function.
2196 */
2197 void SetCallAsFunctionHandler(InvocationCallback callback,
2198 Handle<Value> data = Handle<Value>());
2199
2200 /**
2201 * Mark object instances of the template as undetectable.
2202 *
2203 * In many ways, undetectable objects behave as though they are not
2204 * there. They behave like 'undefined' in conditionals and when
2205 * printed. However, properties can be accessed and called as on
2206 * normal objects.
2207 */
2208 void MarkAsUndetectable();
2209
2210 /**
2211 * Sets access check callbacks on the object template.
2212 *
2213 * When accessing properties on instances of this object template,
2214 * the access check callback will be called to determine whether or
2215 * not to allow cross-context access to the properties.
2216 * The last parameter specifies whether access checks are turned
2217 * on by default on instances. If access checks are off by default,
2218 * they can be turned on on individual instances by calling
2219 * Object::TurnOnAccessCheck().
2220 */
2221 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2222 IndexedSecurityCallback indexed_handler,
2223 Handle<Value> data = Handle<Value>(),
2224 bool turned_on_by_default = true);
2225
2226 /**
2227 * Gets the number of internal fields for objects generated from
2228 * this template.
2229 */
2230 int InternalFieldCount();
2231
2232 /**
2233 * Sets the number of internal fields for objects generated from
2234 * this template.
2235 */
2236 void SetInternalFieldCount(int value);
2237
2238 private:
2239 ObjectTemplate();
2240 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2241 friend class FunctionTemplate;
2242};
2243
2244
2245/**
2246 * A Signature specifies which receivers and arguments a function can
2247 * legally be called with.
2248 */
2249class V8EXPORT Signature : public Data {
2250 public:
2251 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2252 Handle<FunctionTemplate>(),
2253 int argc = 0,
2254 Handle<FunctionTemplate> argv[] = 0);
2255 private:
2256 Signature();
2257};
2258
2259
2260/**
2261 * A utility for determining the type of objects based on the template
2262 * they were constructed from.
2263 */
2264class V8EXPORT TypeSwitch : public Data {
2265 public:
2266 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2267 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2268 int match(Handle<Value> value);
2269 private:
2270 TypeSwitch();
2271};
2272
2273
2274// --- E x t e n s i o n s ---
2275
2276
2277/**
2278 * Ignore
2279 */
2280class V8EXPORT Extension { // NOLINT
2281 public:
2282 Extension(const char* name,
2283 const char* source = 0,
2284 int dep_count = 0,
2285 const char** deps = 0);
2286 virtual ~Extension() { }
2287 virtual v8::Handle<v8::FunctionTemplate>
2288 GetNativeFunction(v8::Handle<v8::String> name) {
2289 return v8::Handle<v8::FunctionTemplate>();
2290 }
2291
2292 const char* name() { return name_; }
2293 const char* source() { return source_; }
2294 int dependency_count() { return dep_count_; }
2295 const char** dependencies() { return deps_; }
2296 void set_auto_enable(bool value) { auto_enable_ = value; }
2297 bool auto_enable() { return auto_enable_; }
2298
2299 private:
2300 const char* name_;
2301 const char* source_;
2302 int dep_count_;
2303 const char** deps_;
2304 bool auto_enable_;
2305
2306 // Disallow copying and assigning.
2307 Extension(const Extension&);
2308 void operator=(const Extension&);
2309};
2310
2311
2312void V8EXPORT RegisterExtension(Extension* extension);
2313
2314
2315/**
2316 * Ignore
2317 */
2318class V8EXPORT DeclareExtension {
2319 public:
2320 inline DeclareExtension(Extension* extension) {
2321 RegisterExtension(extension);
2322 }
2323};
2324
2325
2326// --- S t a t i c s ---
2327
2328
2329Handle<Primitive> V8EXPORT Undefined();
2330Handle<Primitive> V8EXPORT Null();
2331Handle<Boolean> V8EXPORT True();
2332Handle<Boolean> V8EXPORT False();
2333
2334
2335/**
2336 * A set of constraints that specifies the limits of the runtime's memory use.
2337 * You must set the heap size before initializing the VM - the size cannot be
2338 * adjusted after the VM is initialized.
2339 *
2340 * If you are using threads then you should hold the V8::Locker lock while
2341 * setting the stack limit and you must set a non-default stack limit separately
2342 * for each thread.
2343 */
2344class V8EXPORT ResourceConstraints {
2345 public:
2346 ResourceConstraints();
2347 int max_young_space_size() const { return max_young_space_size_; }
2348 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2349 int max_old_space_size() const { return max_old_space_size_; }
2350 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
2351 uint32_t* stack_limit() const { return stack_limit_; }
2352 // Sets an address beyond which the VM's stack may not grow.
2353 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2354 private:
2355 int max_young_space_size_;
2356 int max_old_space_size_;
2357 uint32_t* stack_limit_;
2358};
2359
2360
Kristian Monsen25f61362010-05-21 11:50:48 +01002361bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
Steve Blocka7e24c12009-10-30 11:49:00 +00002362
2363
2364// --- E x c e p t i o n s ---
2365
2366
2367typedef void (*FatalErrorCallback)(const char* location, const char* message);
2368
2369
2370typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2371
2372
2373/**
2374 * Schedules an exception to be thrown when returning to JavaScript. When an
2375 * exception has been scheduled it is illegal to invoke any JavaScript
2376 * operation; the caller must return immediately and only after the exception
2377 * has been handled does it become legal to invoke JavaScript operations.
2378 */
2379Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2380
2381/**
2382 * Create new error objects by calling the corresponding error object
2383 * constructor with the message.
2384 */
2385class V8EXPORT Exception {
2386 public:
2387 static Local<Value> RangeError(Handle<String> message);
2388 static Local<Value> ReferenceError(Handle<String> message);
2389 static Local<Value> SyntaxError(Handle<String> message);
2390 static Local<Value> TypeError(Handle<String> message);
2391 static Local<Value> Error(Handle<String> message);
2392};
2393
2394
2395// --- C o u n t e r s C a l l b a c k s ---
2396
2397typedef int* (*CounterLookupCallback)(const char* name);
2398
2399typedef void* (*CreateHistogramCallback)(const char* name,
2400 int min,
2401 int max,
2402 size_t buckets);
2403
2404typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2405
Iain Merrick9ac36c92010-09-13 15:29:50 +01002406// --- M e m o r y A l l o c a t i o n C a l l b a c k ---
2407 enum ObjectSpace {
2408 kObjectSpaceNewSpace = 1 << 0,
2409 kObjectSpaceOldPointerSpace = 1 << 1,
2410 kObjectSpaceOldDataSpace = 1 << 2,
2411 kObjectSpaceCodeSpace = 1 << 3,
2412 kObjectSpaceMapSpace = 1 << 4,
2413 kObjectSpaceLoSpace = 1 << 5,
2414
2415 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2416 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2417 kObjectSpaceLoSpace
2418 };
2419
2420 enum AllocationAction {
2421 kAllocationActionAllocate = 1 << 0,
2422 kAllocationActionFree = 1 << 1,
2423 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2424 };
2425
2426typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2427 AllocationAction action,
2428 int size);
2429
Steve Blocka7e24c12009-10-30 11:49:00 +00002430// --- F a i l e d A c c e s s C h e c k C a l l b a c k ---
2431typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2432 AccessType type,
2433 Local<Value> data);
2434
2435// --- G a r b a g e C o l l e c t i o n C a l l b a c k s
2436
2437/**
Steve Block6ded16b2010-05-10 14:33:55 +01002438 * Applications can register callback functions which will be called
2439 * before and after a garbage collection. Allocations are not
2440 * allowed in the callback functions, you therefore cannot manipulate
Steve Blocka7e24c12009-10-30 11:49:00 +00002441 * objects (set or delete properties for example) since it is possible
2442 * such operations will result in the allocation of objects.
2443 */
Steve Block6ded16b2010-05-10 14:33:55 +01002444enum GCType {
2445 kGCTypeScavenge = 1 << 0,
2446 kGCTypeMarkSweepCompact = 1 << 1,
2447 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2448};
2449
2450enum GCCallbackFlags {
2451 kNoGCCallbackFlags = 0,
2452 kGCCallbackFlagCompacted = 1 << 0
2453};
2454
2455typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2456typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2457
Steve Blocka7e24c12009-10-30 11:49:00 +00002458typedef void (*GCCallback)();
2459
2460
Steve Blocka7e24c12009-10-30 11:49:00 +00002461/**
2462 * Profiler modules.
2463 *
2464 * In V8, profiler consists of several modules: CPU profiler, and different
2465 * kinds of heap profiling. Each can be turned on / off independently.
2466 * When PROFILER_MODULE_HEAP_SNAPSHOT flag is passed to ResumeProfilerEx,
2467 * modules are enabled only temporarily for making a snapshot of the heap.
2468 */
2469enum ProfilerModules {
2470 PROFILER_MODULE_NONE = 0,
2471 PROFILER_MODULE_CPU = 1,
2472 PROFILER_MODULE_HEAP_STATS = 1 << 1,
2473 PROFILER_MODULE_JS_CONSTRUCTORS = 1 << 2,
2474 PROFILER_MODULE_HEAP_SNAPSHOT = 1 << 16
2475};
2476
2477
2478/**
Steve Block3ce2e202009-11-05 08:53:23 +00002479 * Collection of V8 heap information.
2480 *
2481 * Instances of this class can be passed to v8::V8::HeapStatistics to
2482 * get heap statistics from V8.
2483 */
2484class V8EXPORT HeapStatistics {
2485 public:
2486 HeapStatistics();
2487 size_t total_heap_size() { return total_heap_size_; }
2488 size_t used_heap_size() { return used_heap_size_; }
2489
2490 private:
2491 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
2492 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2493
2494 size_t total_heap_size_;
2495 size_t used_heap_size_;
2496
2497 friend class V8;
2498};
2499
2500
2501/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002502 * Container class for static utility functions.
2503 */
2504class V8EXPORT V8 {
2505 public:
2506 /** Set the callback to invoke in case of fatal errors. */
2507 static void SetFatalErrorHandler(FatalErrorCallback that);
2508
2509 /**
2510 * Ignore out-of-memory exceptions.
2511 *
2512 * V8 running out of memory is treated as a fatal error by default.
2513 * This means that the fatal error handler is called and that V8 is
2514 * terminated.
2515 *
2516 * IgnoreOutOfMemoryException can be used to not treat a
2517 * out-of-memory situation as a fatal error. This way, the contexts
2518 * that did not cause the out of memory problem might be able to
2519 * continue execution.
2520 */
2521 static void IgnoreOutOfMemoryException();
2522
2523 /**
2524 * Check if V8 is dead and therefore unusable. This is the case after
2525 * fatal errors such as out-of-memory situations.
2526 */
2527 static bool IsDead();
2528
2529 /**
2530 * Adds a message listener.
2531 *
2532 * The same message listener can be added more than once and it that
2533 * case it will be called more than once for each message.
2534 */
2535 static bool AddMessageListener(MessageCallback that,
2536 Handle<Value> data = Handle<Value>());
2537
2538 /**
2539 * Remove all message listeners from the specified callback function.
2540 */
2541 static void RemoveMessageListeners(MessageCallback that);
2542
2543 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002544 * Tells V8 to capture current stack trace when uncaught exception occurs
2545 * and report it to the message listeners. The option is off by default.
2546 */
2547 static void SetCaptureStackTraceForUncaughtExceptions(
2548 bool capture,
2549 int frame_limit = 10,
2550 StackTrace::StackTraceOptions options = StackTrace::kOverview);
2551
2552 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002553 * Sets V8 flags from a string.
2554 */
2555 static void SetFlagsFromString(const char* str, int length);
2556
2557 /**
2558 * Sets V8 flags from the command line.
2559 */
2560 static void SetFlagsFromCommandLine(int* argc,
2561 char** argv,
2562 bool remove_flags);
2563
2564 /** Get the version string. */
2565 static const char* GetVersion();
2566
2567 /**
2568 * Enables the host application to provide a mechanism for recording
2569 * statistics counters.
2570 */
2571 static void SetCounterFunction(CounterLookupCallback);
2572
2573 /**
2574 * Enables the host application to provide a mechanism for recording
2575 * histograms. The CreateHistogram function returns a
2576 * histogram which will later be passed to the AddHistogramSample
2577 * function.
2578 */
2579 static void SetCreateHistogramFunction(CreateHistogramCallback);
2580 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2581
2582 /**
2583 * Enables the computation of a sliding window of states. The sliding
2584 * window information is recorded in statistics counters.
2585 */
2586 static void EnableSlidingStateWindow();
2587
2588 /** Callback function for reporting failed access checks.*/
2589 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2590
2591 /**
2592 * Enables the host application to receive a notification before a
Steve Block6ded16b2010-05-10 14:33:55 +01002593 * garbage collection. Allocations are not allowed in the
2594 * callback function, you therefore cannot manipulate objects (set
2595 * or delete properties for example) since it is possible such
2596 * operations will result in the allocation of objects. It is possible
2597 * to specify the GCType filter for your callback. But it is not possible to
2598 * register the same callback function two times with different
2599 * GCType filters.
2600 */
2601 static void AddGCPrologueCallback(
2602 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
2603
2604 /**
2605 * This function removes callback which was installed by
2606 * AddGCPrologueCallback function.
2607 */
2608 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
2609
2610 /**
2611 * The function is deprecated. Please use AddGCPrologueCallback instead.
2612 * Enables the host application to receive a notification before a
2613 * garbage collection. Allocations are not allowed in the
Steve Blocka7e24c12009-10-30 11:49:00 +00002614 * callback function, you therefore cannot manipulate objects (set
2615 * or delete properties for example) since it is possible such
2616 * operations will result in the allocation of objects.
2617 */
2618 static void SetGlobalGCPrologueCallback(GCCallback);
2619
2620 /**
2621 * Enables the host application to receive a notification after a
Steve Block6ded16b2010-05-10 14:33:55 +01002622 * garbage collection. Allocations are not allowed in the
2623 * callback function, you therefore cannot manipulate objects (set
2624 * or delete properties for example) since it is possible such
2625 * operations will result in the allocation of objects. It is possible
2626 * to specify the GCType filter for your callback. But it is not possible to
2627 * register the same callback function two times with different
2628 * GCType filters.
2629 */
2630 static void AddGCEpilogueCallback(
2631 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
2632
2633 /**
2634 * This function removes callback which was installed by
2635 * AddGCEpilogueCallback function.
2636 */
2637 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
2638
2639 /**
2640 * The function is deprecated. Please use AddGCEpilogueCallback instead.
2641 * Enables the host application to receive a notification after a
Steve Blocka7e24c12009-10-30 11:49:00 +00002642 * major garbage collection. Allocations are not allowed in the
2643 * callback function, you therefore cannot manipulate objects (set
2644 * or delete properties for example) since it is possible such
2645 * operations will result in the allocation of objects.
2646 */
2647 static void SetGlobalGCEpilogueCallback(GCCallback);
2648
2649 /**
Iain Merrick9ac36c92010-09-13 15:29:50 +01002650 * Enables the host application to provide a mechanism to be notified
2651 * and perform custom logging when V8 Allocates Executable Memory.
2652 */
2653 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
2654 ObjectSpace space,
2655 AllocationAction action);
2656
2657 /**
2658 * This function removes callback which was installed by
2659 * AddMemoryAllocationCallback function.
2660 */
2661 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
2662
2663 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002664 * Allows the host application to group objects together. If one
2665 * object in the group is alive, all objects in the group are alive.
2666 * After each garbage collection, object groups are removed. It is
2667 * intended to be used in the before-garbage-collection callback
2668 * function, for instance to simulate DOM tree connections among JS
2669 * wrapper objects.
2670 */
2671 static void AddObjectGroup(Persistent<Value>* objects, size_t length);
2672
2673 /**
2674 * Initializes from snapshot if possible. Otherwise, attempts to
2675 * initialize from scratch. This function is called implicitly if
2676 * you use the API without calling it first.
2677 */
2678 static bool Initialize();
2679
2680 /**
2681 * Adjusts the amount of registered external memory. Used to give
2682 * V8 an indication of the amount of externally allocated memory
2683 * that is kept alive by JavaScript objects. V8 uses this to decide
2684 * when to perform global garbage collections. Registering
2685 * externally allocated memory will trigger global garbage
2686 * collections more often than otherwise in an attempt to garbage
2687 * collect the JavaScript objects keeping the externally allocated
2688 * memory alive.
2689 *
2690 * \param change_in_bytes the change in externally allocated memory
2691 * that is kept alive by JavaScript objects.
2692 * \returns the adjusted value.
2693 */
2694 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
2695
2696 /**
2697 * Suspends recording of tick samples in the profiler.
2698 * When the V8 profiling mode is enabled (usually via command line
2699 * switches) this function suspends recording of tick samples.
2700 * Profiling ticks are discarded until ResumeProfiler() is called.
2701 *
2702 * See also the --prof and --prof_auto command line switches to
2703 * enable V8 profiling.
2704 */
2705 static void PauseProfiler();
2706
2707 /**
2708 * Resumes recording of tick samples in the profiler.
2709 * See also PauseProfiler().
2710 */
2711 static void ResumeProfiler();
2712
2713 /**
2714 * Return whether profiler is currently paused.
2715 */
2716 static bool IsProfilerPaused();
2717
2718 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002719 * Resumes specified profiler modules. Can be called several times to
2720 * mark the opening of a profiler events block with the given tag.
2721 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002722 * "ResumeProfiler" is equivalent to "ResumeProfilerEx(PROFILER_MODULE_CPU)".
2723 * See ProfilerModules enum.
2724 *
2725 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002726 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002727 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002728 static void ResumeProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002729
2730 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002731 * Pauses specified profiler modules. Each call to "PauseProfilerEx" closes
2732 * a block of profiler events opened by a call to "ResumeProfilerEx" with the
2733 * same tag value. There is no need for blocks to be properly nested.
2734 * The profiler is paused when the last opened block is closed.
2735 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002736 * "PauseProfiler" is equivalent to "PauseProfilerEx(PROFILER_MODULE_CPU)".
2737 * See ProfilerModules enum.
2738 *
2739 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002740 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002741 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002742 static void PauseProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002743
2744 /**
2745 * Returns active (resumed) profiler modules.
2746 * See ProfilerModules enum.
2747 *
2748 * \returns active profiler modules.
2749 */
2750 static int GetActiveProfilerModules();
2751
2752 /**
2753 * If logging is performed into a memory buffer (via --logfile=*), allows to
2754 * retrieve previously written messages. This can be used for retrieving
2755 * profiler log data in the application. This function is thread-safe.
2756 *
2757 * Caller provides a destination buffer that must exist during GetLogLines
2758 * call. Only whole log lines are copied into the buffer.
2759 *
2760 * \param from_pos specified a point in a buffer to read from, 0 is the
2761 * beginning of a buffer. It is assumed that caller updates its current
2762 * position using returned size value from the previous call.
2763 * \param dest_buf destination buffer for log data.
2764 * \param max_size size of the destination buffer.
2765 * \returns actual size of log data copied into buffer.
2766 */
2767 static int GetLogLines(int from_pos, char* dest_buf, int max_size);
2768
2769 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002770 * The minimum allowed size for a log lines buffer. If the size of
2771 * the buffer given will not be enough to hold a line of the maximum
2772 * length, an attempt to find a log line end in GetLogLines will
2773 * fail, and an empty result will be returned.
2774 */
2775 static const int kMinimumSizeForLogLinesBuffer = 2048;
2776
2777 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002778 * Retrieve the V8 thread id of the calling thread.
2779 *
2780 * The thread id for a thread should only be retrieved after the V8
2781 * lock has been acquired with a Locker object with that thread.
2782 */
2783 static int GetCurrentThreadId();
2784
2785 /**
2786 * Forcefully terminate execution of a JavaScript thread. This can
2787 * be used to terminate long-running scripts.
2788 *
2789 * TerminateExecution should only be called when then V8 lock has
2790 * been acquired with a Locker object. Therefore, in order to be
2791 * able to terminate long-running threads, preemption must be
2792 * enabled to allow the user of TerminateExecution to acquire the
2793 * lock.
2794 *
2795 * The termination is achieved by throwing an exception that is
2796 * uncatchable by JavaScript exception handlers. Termination
2797 * exceptions act as if they were caught by a C++ TryCatch exception
2798 * handlers. If forceful termination is used, any C++ TryCatch
2799 * exception handler that catches an exception should check if that
2800 * exception is a termination exception and immediately return if
2801 * that is the case. Returning immediately in that case will
2802 * continue the propagation of the termination exception if needed.
2803 *
2804 * The thread id passed to TerminateExecution must have been
2805 * obtained by calling GetCurrentThreadId on the thread in question.
2806 *
2807 * \param thread_id The thread id of the thread to terminate.
2808 */
2809 static void TerminateExecution(int thread_id);
2810
2811 /**
2812 * Forcefully terminate the current thread of JavaScript execution.
2813 *
2814 * This method can be used by any thread even if that thread has not
2815 * acquired the V8 lock with a Locker object.
2816 */
2817 static void TerminateExecution();
2818
2819 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002820 * Is V8 terminating JavaScript execution.
2821 *
2822 * Returns true if JavaScript execution is currently terminating
2823 * because of a call to TerminateExecution. In that case there are
2824 * still JavaScript frames on the stack and the termination
2825 * exception is still active.
2826 */
2827 static bool IsExecutionTerminating();
2828
2829 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002830 * Releases any resources used by v8 and stops any utility threads
2831 * that may be running. Note that disposing v8 is permanent, it
2832 * cannot be reinitialized.
2833 *
2834 * It should generally not be necessary to dispose v8 before exiting
2835 * a process, this should happen automatically. It is only necessary
2836 * to use if the process needs the resources taken up by v8.
2837 */
2838 static bool Dispose();
2839
Steve Block3ce2e202009-11-05 08:53:23 +00002840 /**
2841 * Get statistics about the heap memory usage.
2842 */
2843 static void GetHeapStatistics(HeapStatistics* heap_statistics);
Steve Blocka7e24c12009-10-30 11:49:00 +00002844
2845 /**
2846 * Optional notification that the embedder is idle.
2847 * V8 uses the notification to reduce memory footprint.
2848 * This call can be used repeatedly if the embedder remains idle.
Steve Blocka7e24c12009-10-30 11:49:00 +00002849 * Returns true if the embedder should stop calling IdleNotification
2850 * until real work has been done. This indicates that V8 has done
2851 * as much cleanup as it will be able to do.
2852 */
Steve Block3ce2e202009-11-05 08:53:23 +00002853 static bool IdleNotification();
Steve Blocka7e24c12009-10-30 11:49:00 +00002854
2855 /**
2856 * Optional notification that the system is running low on memory.
2857 * V8 uses these notifications to attempt to free memory.
2858 */
2859 static void LowMemoryNotification();
2860
Steve Block6ded16b2010-05-10 14:33:55 +01002861 /**
2862 * Optional notification that a context has been disposed. V8 uses
2863 * these notifications to guide the GC heuristic. Returns the number
2864 * of context disposals - including this one - since the last time
2865 * V8 had a chance to clean up.
2866 */
2867 static int ContextDisposedNotification();
2868
Steve Blocka7e24c12009-10-30 11:49:00 +00002869 private:
2870 V8();
2871
2872 static internal::Object** GlobalizeReference(internal::Object** handle);
2873 static void DisposeGlobal(internal::Object** global_handle);
2874 static void MakeWeak(internal::Object** global_handle,
2875 void* data,
2876 WeakReferenceCallback);
2877 static void ClearWeak(internal::Object** global_handle);
2878 static bool IsGlobalNearDeath(internal::Object** global_handle);
2879 static bool IsGlobalWeak(internal::Object** global_handle);
2880
2881 template <class T> friend class Handle;
2882 template <class T> friend class Local;
2883 template <class T> friend class Persistent;
2884 friend class Context;
2885};
2886
2887
2888/**
2889 * An external exception handler.
2890 */
2891class V8EXPORT TryCatch {
2892 public:
2893
2894 /**
2895 * Creates a new try/catch block and registers it with v8.
2896 */
2897 TryCatch();
2898
2899 /**
2900 * Unregisters and deletes this try/catch block.
2901 */
2902 ~TryCatch();
2903
2904 /**
2905 * Returns true if an exception has been caught by this try/catch block.
2906 */
2907 bool HasCaught() const;
2908
2909 /**
2910 * For certain types of exceptions, it makes no sense to continue
2911 * execution.
2912 *
2913 * Currently, the only type of exception that can be caught by a
2914 * TryCatch handler and for which it does not make sense to continue
2915 * is termination exception. Such exceptions are thrown when the
2916 * TerminateExecution methods are called to terminate a long-running
2917 * script.
2918 *
2919 * If CanContinue returns false, the correct action is to perform
2920 * any C++ cleanup needed and then return.
2921 */
2922 bool CanContinue() const;
2923
2924 /**
Steve Blockd0582a62009-12-15 09:54:21 +00002925 * Throws the exception caught by this TryCatch in a way that avoids
2926 * it being caught again by this same TryCatch. As with ThrowException
2927 * it is illegal to execute any JavaScript operations after calling
2928 * ReThrow; the caller must return immediately to where the exception
2929 * is caught.
2930 */
2931 Handle<Value> ReThrow();
2932
2933 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002934 * Returns the exception caught by this try/catch block. If no exception has
2935 * been caught an empty handle is returned.
2936 *
2937 * The returned handle is valid until this TryCatch block has been destroyed.
2938 */
2939 Local<Value> Exception() const;
2940
2941 /**
2942 * Returns the .stack property of the thrown object. If no .stack
2943 * property is present an empty handle is returned.
2944 */
2945 Local<Value> StackTrace() const;
2946
2947 /**
2948 * Returns the message associated with this exception. If there is
2949 * no message associated an empty handle is returned.
2950 *
2951 * The returned handle is valid until this TryCatch block has been
2952 * destroyed.
2953 */
2954 Local<v8::Message> Message() const;
2955
2956 /**
2957 * Clears any exceptions that may have been caught by this try/catch block.
2958 * After this method has been called, HasCaught() will return false.
2959 *
2960 * It is not necessary to clear a try/catch block before using it again; if
2961 * another exception is thrown the previously caught exception will just be
2962 * overwritten. However, it is often a good idea since it makes it easier
2963 * to determine which operation threw a given exception.
2964 */
2965 void Reset();
2966
2967 /**
2968 * Set verbosity of the external exception handler.
2969 *
2970 * By default, exceptions that are caught by an external exception
2971 * handler are not reported. Call SetVerbose with true on an
2972 * external exception handler to have exceptions caught by the
2973 * handler reported as if they were not caught.
2974 */
2975 void SetVerbose(bool value);
2976
2977 /**
2978 * Set whether or not this TryCatch should capture a Message object
2979 * which holds source information about where the exception
2980 * occurred. True by default.
2981 */
2982 void SetCaptureMessage(bool value);
2983
Steve Blockd0582a62009-12-15 09:54:21 +00002984 private:
2985 void* next_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002986 void* exception_;
2987 void* message_;
Steve Blockd0582a62009-12-15 09:54:21 +00002988 bool is_verbose_ : 1;
2989 bool can_continue_ : 1;
2990 bool capture_message_ : 1;
2991 bool rethrow_ : 1;
2992
2993 friend class v8::internal::Top;
Steve Blocka7e24c12009-10-30 11:49:00 +00002994};
2995
2996
2997// --- C o n t e x t ---
2998
2999
3000/**
3001 * Ignore
3002 */
3003class V8EXPORT ExtensionConfiguration {
3004 public:
3005 ExtensionConfiguration(int name_count, const char* names[])
3006 : name_count_(name_count), names_(names) { }
3007 private:
3008 friend class ImplementationUtilities;
3009 int name_count_;
3010 const char** names_;
3011};
3012
3013
3014/**
3015 * A sandboxed execution context with its own set of built-in objects
3016 * and functions.
3017 */
3018class V8EXPORT Context {
3019 public:
3020 /** Returns the global object of the context. */
3021 Local<Object> Global();
3022
3023 /**
3024 * Detaches the global object from its context before
3025 * the global object can be reused to create a new context.
3026 */
3027 void DetachGlobal();
3028
Andrei Popescu74b3c142010-03-29 12:03:09 +01003029 /**
3030 * Reattaches a global object to a context. This can be used to
3031 * restore the connection between a global object and a context
3032 * after DetachGlobal has been called.
3033 *
3034 * \param global_object The global object to reattach to the
3035 * context. For this to work, the global object must be the global
3036 * object that was associated with this context before a call to
3037 * DetachGlobal.
3038 */
3039 void ReattachGlobal(Handle<Object> global_object);
3040
Leon Clarkef7060e22010-06-03 12:02:55 +01003041 /** Creates a new context.
3042 *
3043 * Returns a persistent handle to the newly allocated context. This
3044 * persistent handle has to be disposed when the context is no
3045 * longer used so the context can be garbage collected.
3046 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003047 static Persistent<Context> New(
Andrei Popescu31002712010-02-23 13:46:05 +00003048 ExtensionConfiguration* extensions = NULL,
Steve Blocka7e24c12009-10-30 11:49:00 +00003049 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3050 Handle<Value> global_object = Handle<Value>());
3051
3052 /** Returns the last entered context. */
3053 static Local<Context> GetEntered();
3054
3055 /** Returns the context that is on the top of the stack. */
3056 static Local<Context> GetCurrent();
3057
3058 /**
3059 * Returns the context of the calling JavaScript code. That is the
3060 * context of the top-most JavaScript frame. If there are no
3061 * JavaScript frames an empty handle is returned.
3062 */
3063 static Local<Context> GetCalling();
3064
3065 /**
3066 * Sets the security token for the context. To access an object in
3067 * another context, the security tokens must match.
3068 */
3069 void SetSecurityToken(Handle<Value> token);
3070
3071 /** Restores the security token to the default value. */
3072 void UseDefaultSecurityToken();
3073
3074 /** Returns the security token of this context.*/
3075 Handle<Value> GetSecurityToken();
3076
3077 /**
3078 * Enter this context. After entering a context, all code compiled
3079 * and run is compiled and run in this context. If another context
3080 * is already entered, this old context is saved so it can be
3081 * restored when the new context is exited.
3082 */
3083 void Enter();
3084
3085 /**
3086 * Exit this context. Exiting the current context restores the
3087 * context that was in place when entering the current context.
3088 */
3089 void Exit();
3090
3091 /** Returns true if the context has experienced an out of memory situation. */
3092 bool HasOutOfMemoryException();
3093
3094 /** Returns true if V8 has a current context. */
3095 static bool InContext();
3096
3097 /**
3098 * Associate an additional data object with the context. This is mainly used
3099 * with the debugger to provide additional information on the context through
3100 * the debugger API.
3101 */
Steve Blockd0582a62009-12-15 09:54:21 +00003102 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00003103 Local<Value> GetData();
3104
3105 /**
3106 * Stack-allocated class which sets the execution context for all
3107 * operations executed within a local scope.
3108 */
Steve Block8defd9f2010-07-08 12:39:36 +01003109 class Scope {
Steve Blocka7e24c12009-10-30 11:49:00 +00003110 public:
3111 inline Scope(Handle<Context> context) : context_(context) {
3112 context_->Enter();
3113 }
3114 inline ~Scope() { context_->Exit(); }
3115 private:
3116 Handle<Context> context_;
3117 };
3118
3119 private:
3120 friend class Value;
3121 friend class Script;
3122 friend class Object;
3123 friend class Function;
3124};
3125
3126
3127/**
3128 * Multiple threads in V8 are allowed, but only one thread at a time
3129 * is allowed to use V8. The definition of 'using V8' includes
3130 * accessing handles or holding onto object pointers obtained from V8
3131 * handles. It is up to the user of V8 to ensure (perhaps with
3132 * locking) that this constraint is not violated.
3133 *
3134 * If you wish to start using V8 in a thread you can do this by constructing
3135 * a v8::Locker object. After the code using V8 has completed for the
3136 * current thread you can call the destructor. This can be combined
3137 * with C++ scope-based construction as follows:
3138 *
3139 * \code
3140 * ...
3141 * {
3142 * v8::Locker locker;
3143 * ...
3144 * // Code using V8 goes here.
3145 * ...
3146 * } // Destructor called here
3147 * \endcode
3148 *
3149 * If you wish to stop using V8 in a thread A you can do this by either
3150 * by destroying the v8::Locker object as above or by constructing a
3151 * v8::Unlocker object:
3152 *
3153 * \code
3154 * {
3155 * v8::Unlocker unlocker;
3156 * ...
3157 * // Code not using V8 goes here while V8 can run in another thread.
3158 * ...
3159 * } // Destructor called here.
3160 * \endcode
3161 *
3162 * The Unlocker object is intended for use in a long-running callback
3163 * from V8, where you want to release the V8 lock for other threads to
3164 * use.
3165 *
3166 * The v8::Locker is a recursive lock. That is, you can lock more than
3167 * once in a given thread. This can be useful if you have code that can
3168 * be called either from code that holds the lock or from code that does
3169 * not. The Unlocker is not recursive so you can not have several
3170 * Unlockers on the stack at once, and you can not use an Unlocker in a
3171 * thread that is not inside a Locker's scope.
3172 *
3173 * An unlocker will unlock several lockers if it has to and reinstate
3174 * the correct depth of locking on its destruction. eg.:
3175 *
3176 * \code
3177 * // V8 not locked.
3178 * {
3179 * v8::Locker locker;
3180 * // V8 locked.
3181 * {
3182 * v8::Locker another_locker;
3183 * // V8 still locked (2 levels).
3184 * {
3185 * v8::Unlocker unlocker;
3186 * // V8 not locked.
3187 * }
3188 * // V8 locked again (2 levels).
3189 * }
3190 * // V8 still locked (1 level).
3191 * }
3192 * // V8 Now no longer locked.
3193 * \endcode
3194 */
3195class V8EXPORT Unlocker {
3196 public:
3197 Unlocker();
3198 ~Unlocker();
3199};
3200
3201
3202class V8EXPORT Locker {
3203 public:
3204 Locker();
3205 ~Locker();
3206
3207 /**
3208 * Start preemption.
3209 *
3210 * When preemption is started, a timer is fired every n milli seconds
3211 * that will switch between multiple threads that are in contention
3212 * for the V8 lock.
3213 */
3214 static void StartPreemption(int every_n_ms);
3215
3216 /**
3217 * Stop preemption.
3218 */
3219 static void StopPreemption();
3220
3221 /**
3222 * Returns whether or not the locker is locked by the current thread.
3223 */
3224 static bool IsLocked();
3225
3226 /**
3227 * Returns whether v8::Locker is being used by this V8 instance.
3228 */
3229 static bool IsActive() { return active_; }
3230
3231 private:
3232 bool has_lock_;
3233 bool top_level_;
3234
3235 static bool active_;
3236
3237 // Disallow copying and assigning.
3238 Locker(const Locker&);
3239 void operator=(const Locker&);
3240};
3241
3242
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003243/**
3244 * An interface for exporting data from V8, using "push" model.
3245 */
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003246class V8EXPORT OutputStream { // NOLINT
3247 public:
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003248 enum OutputEncoding {
3249 kAscii = 0 // 7-bit ASCII.
3250 };
3251 enum WriteResult {
3252 kContinue = 0,
3253 kAbort = 1
3254 };
3255 virtual ~OutputStream() {}
3256 /** Notify about the end of stream. */
3257 virtual void EndOfStream() = 0;
3258 /** Get preferred output chunk size. Called only once. */
3259 virtual int GetChunkSize() { return 1024; }
3260 /** Get preferred output encoding. Called only once. */
3261 virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3262 /**
3263 * Writes the next chunk of snapshot data into the stream. Writing
3264 * can be stopped by returning kAbort as function result. EndOfStream
3265 * will not be called in case writing was aborted.
3266 */
3267 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3268};
3269
3270
Steve Blocka7e24c12009-10-30 11:49:00 +00003271
3272// --- I m p l e m e n t a t i o n ---
3273
3274
3275namespace internal {
3276
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003277const int kPointerSize = sizeof(void*); // NOLINT
3278const int kIntSize = sizeof(int); // NOLINT
Steve Blocka7e24c12009-10-30 11:49:00 +00003279
3280// Tag information for HeapObject.
3281const int kHeapObjectTag = 1;
3282const int kHeapObjectTagSize = 2;
3283const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3284
Steve Blocka7e24c12009-10-30 11:49:00 +00003285// Tag information for Smi.
3286const int kSmiTag = 0;
3287const int kSmiTagSize = 1;
3288const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3289
Steve Block3ce2e202009-11-05 08:53:23 +00003290template <size_t ptr_size> struct SmiConstants;
3291
3292// Smi constants for 32-bit systems.
3293template <> struct SmiConstants<4> {
3294 static const int kSmiShiftSize = 0;
3295 static const int kSmiValueSize = 31;
3296 static inline int SmiToInt(internal::Object* value) {
3297 int shift_bits = kSmiTagSize + kSmiShiftSize;
3298 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3299 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3300 }
3301};
3302
3303// Smi constants for 64-bit systems.
3304template <> struct SmiConstants<8> {
3305 static const int kSmiShiftSize = 31;
3306 static const int kSmiValueSize = 32;
3307 static inline int SmiToInt(internal::Object* value) {
3308 int shift_bits = kSmiTagSize + kSmiShiftSize;
3309 // Shift down and throw away top 32 bits.
3310 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3311 }
3312};
3313
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003314const int kSmiShiftSize = SmiConstants<kPointerSize>::kSmiShiftSize;
3315const int kSmiValueSize = SmiConstants<kPointerSize>::kSmiValueSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003316
Steve Blockd0582a62009-12-15 09:54:21 +00003317template <size_t ptr_size> struct InternalConstants;
3318
3319// Internal constants for 32-bit systems.
3320template <> struct InternalConstants<4> {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003321 static const int kStringResourceOffset = 3 * kPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003322};
3323
3324// Internal constants for 64-bit systems.
3325template <> struct InternalConstants<8> {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003326 static const int kStringResourceOffset = 3 * kPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003327};
3328
Steve Blocka7e24c12009-10-30 11:49:00 +00003329/**
3330 * This class exports constants and functionality from within v8 that
3331 * is necessary to implement inline functions in the v8 api. Don't
3332 * depend on functions and constants defined here.
3333 */
3334class Internals {
3335 public:
3336
3337 // These values match non-compiler-dependent values defined within
3338 // the implementation of v8.
3339 static const int kHeapObjectMapOffset = 0;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003340 static const int kMapInstanceTypeOffset = kPointerSize + kIntSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003341 static const int kStringResourceOffset =
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003342 InternalConstants<kPointerSize>::kStringResourceOffset;
Steve Blockd0582a62009-12-15 09:54:21 +00003343
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003344 static const int kProxyProxyOffset = kPointerSize;
3345 static const int kJSObjectHeaderSize = 3 * kPointerSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003346 static const int kFullStringRepresentationMask = 0x07;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003347 static const int kExternalTwoByteRepresentationTag = 0x02;
Steve Blocka7e24c12009-10-30 11:49:00 +00003348
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003349 static const int kJSObjectType = 0x9f;
3350 static const int kFirstNonstringType = 0x80;
3351 static const int kProxyType = 0x85;
Steve Blocka7e24c12009-10-30 11:49:00 +00003352
3353 static inline bool HasHeapObjectTag(internal::Object* value) {
3354 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3355 kHeapObjectTag);
3356 }
3357
3358 static inline bool HasSmiTag(internal::Object* value) {
3359 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3360 }
3361
3362 static inline int SmiValue(internal::Object* value) {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003363 return SmiConstants<kPointerSize>::SmiToInt(value);
Steve Block3ce2e202009-11-05 08:53:23 +00003364 }
3365
3366 static inline int GetInstanceType(internal::Object* obj) {
3367 typedef internal::Object O;
3368 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3369 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3370 }
3371
3372 static inline void* GetExternalPointer(internal::Object* obj) {
3373 if (HasSmiTag(obj)) {
3374 return obj;
3375 } else if (GetInstanceType(obj) == kProxyType) {
3376 return ReadField<void*>(obj, kProxyProxyOffset);
3377 } else {
3378 return NULL;
3379 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003380 }
3381
3382 static inline bool IsExternalTwoByteString(int instance_type) {
3383 int representation = (instance_type & kFullStringRepresentationMask);
3384 return representation == kExternalTwoByteRepresentationTag;
3385 }
3386
3387 template <typename T>
3388 static inline T ReadField(Object* ptr, int offset) {
3389 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3390 return *reinterpret_cast<T*>(addr);
3391 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003392};
3393
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003394} // namespace internal
Steve Blocka7e24c12009-10-30 11:49:00 +00003395
3396
3397template <class T>
3398Handle<T>::Handle() : val_(0) { }
3399
3400
3401template <class T>
3402Local<T>::Local() : Handle<T>() { }
3403
3404
3405template <class T>
3406Local<T> Local<T>::New(Handle<T> that) {
3407 if (that.IsEmpty()) return Local<T>();
3408 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3409 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3410}
3411
3412
3413template <class T>
3414Persistent<T> Persistent<T>::New(Handle<T> that) {
3415 if (that.IsEmpty()) return Persistent<T>();
3416 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3417 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3418}
3419
3420
3421template <class T>
3422bool Persistent<T>::IsNearDeath() const {
3423 if (this->IsEmpty()) return false;
3424 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3425}
3426
3427
3428template <class T>
3429bool Persistent<T>::IsWeak() const {
3430 if (this->IsEmpty()) return false;
3431 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3432}
3433
3434
3435template <class T>
3436void Persistent<T>::Dispose() {
3437 if (this->IsEmpty()) return;
3438 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3439}
3440
3441
3442template <class T>
3443Persistent<T>::Persistent() : Handle<T>() { }
3444
3445template <class T>
3446void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3447 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3448 parameters,
3449 callback);
3450}
3451
3452template <class T>
3453void Persistent<T>::ClearWeak() {
3454 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3455}
3456
Steve Block8defd9f2010-07-08 12:39:36 +01003457
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003458Arguments::Arguments(internal::Object** implicit_args,
3459 internal::Object** values, int length,
3460 bool is_construct_call)
3461 : implicit_args_(implicit_args),
3462 values_(values),
3463 length_(length),
3464 is_construct_call_(is_construct_call) { }
Steve Block8defd9f2010-07-08 12:39:36 +01003465
3466
Steve Blocka7e24c12009-10-30 11:49:00 +00003467Local<Value> Arguments::operator[](int i) const {
3468 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3469 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3470}
3471
3472
3473Local<Function> Arguments::Callee() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003474 return Local<Function>(reinterpret_cast<Function*>(
3475 &implicit_args_[kCalleeIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003476}
3477
3478
3479Local<Object> Arguments::This() const {
3480 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
3481}
3482
3483
3484Local<Object> Arguments::Holder() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003485 return Local<Object>(reinterpret_cast<Object*>(
3486 &implicit_args_[kHolderIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003487}
3488
3489
3490Local<Value> Arguments::Data() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003491 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003492}
3493
3494
3495bool Arguments::IsConstructCall() const {
3496 return is_construct_call_;
3497}
3498
3499
3500int Arguments::Length() const {
3501 return length_;
3502}
3503
3504
3505template <class T>
3506Local<T> HandleScope::Close(Handle<T> value) {
3507 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
3508 internal::Object** after = RawClose(before);
3509 return Local<T>(reinterpret_cast<T*>(after));
3510}
3511
3512Handle<Value> ScriptOrigin::ResourceName() const {
3513 return resource_name_;
3514}
3515
3516
3517Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
3518 return resource_line_offset_;
3519}
3520
3521
3522Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
3523 return resource_column_offset_;
3524}
3525
3526
3527Handle<Boolean> Boolean::New(bool value) {
3528 return value ? True() : False();
3529}
3530
3531
3532void Template::Set(const char* name, v8::Handle<Data> value) {
3533 Set(v8::String::New(name), value);
3534}
3535
3536
3537Local<Value> Object::GetInternalField(int index) {
3538#ifndef V8_ENABLE_CHECKS
3539 Local<Value> quick_result = UncheckedGetInternalField(index);
3540 if (!quick_result.IsEmpty()) return quick_result;
3541#endif
3542 return CheckedGetInternalField(index);
3543}
3544
3545
3546Local<Value> Object::UncheckedGetInternalField(int index) {
3547 typedef internal::Object O;
3548 typedef internal::Internals I;
3549 O* obj = *reinterpret_cast<O**>(this);
Steve Block3ce2e202009-11-05 08:53:23 +00003550 if (I::GetInstanceType(obj) == I::kJSObjectType) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003551 // If the object is a plain JSObject, which is the common case,
3552 // we know where to find the internal fields and can return the
3553 // value directly.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003554 int offset = I::kJSObjectHeaderSize + (internal::kPointerSize * index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003555 O* value = I::ReadField<O*>(obj, offset);
3556 O** result = HandleScope::CreateHandle(value);
3557 return Local<Value>(reinterpret_cast<Value*>(result));
3558 } else {
3559 return Local<Value>();
3560 }
3561}
3562
3563
3564void* External::Unwrap(Handle<v8::Value> obj) {
3565#ifdef V8_ENABLE_CHECKS
3566 return FullUnwrap(obj);
3567#else
3568 return QuickUnwrap(obj);
3569#endif
3570}
3571
3572
3573void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
3574 typedef internal::Object O;
Steve Blocka7e24c12009-10-30 11:49:00 +00003575 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
Steve Block3ce2e202009-11-05 08:53:23 +00003576 return internal::Internals::GetExternalPointer(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00003577}
3578
3579
3580void* Object::GetPointerFromInternalField(int index) {
Steve Block3ce2e202009-11-05 08:53:23 +00003581 typedef internal::Object O;
3582 typedef internal::Internals I;
3583
3584 O* obj = *reinterpret_cast<O**>(this);
3585
3586 if (I::GetInstanceType(obj) == I::kJSObjectType) {
3587 // If the object is a plain JSObject, which is the common case,
3588 // we know where to find the internal fields and can return the
3589 // value directly.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003590 int offset = I::kJSObjectHeaderSize + (internal::kPointerSize * index);
Steve Block3ce2e202009-11-05 08:53:23 +00003591 O* value = I::ReadField<O*>(obj, offset);
3592 return I::GetExternalPointer(value);
3593 }
3594
3595 return SlowGetPointerFromInternalField(index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003596}
3597
3598
3599String* String::Cast(v8::Value* value) {
3600#ifdef V8_ENABLE_CHECKS
3601 CheckCast(value);
3602#endif
3603 return static_cast<String*>(value);
3604}
3605
3606
3607String::ExternalStringResource* String::GetExternalStringResource() const {
3608 typedef internal::Object O;
3609 typedef internal::Internals I;
3610 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
Steve Blocka7e24c12009-10-30 11:49:00 +00003611 String::ExternalStringResource* result;
Steve Block3ce2e202009-11-05 08:53:23 +00003612 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003613 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
3614 result = reinterpret_cast<String::ExternalStringResource*>(value);
3615 } else {
3616 result = NULL;
3617 }
3618#ifdef V8_ENABLE_CHECKS
3619 VerifyExternalStringResource(result);
3620#endif
3621 return result;
3622}
3623
3624
3625bool Value::IsString() const {
3626#ifdef V8_ENABLE_CHECKS
3627 return FullIsString();
3628#else
3629 return QuickIsString();
3630#endif
3631}
3632
3633bool Value::QuickIsString() const {
3634 typedef internal::Object O;
3635 typedef internal::Internals I;
3636 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
3637 if (!I::HasHeapObjectTag(obj)) return false;
Steve Block3ce2e202009-11-05 08:53:23 +00003638 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
Steve Blocka7e24c12009-10-30 11:49:00 +00003639}
3640
3641
3642Number* Number::Cast(v8::Value* value) {
3643#ifdef V8_ENABLE_CHECKS
3644 CheckCast(value);
3645#endif
3646 return static_cast<Number*>(value);
3647}
3648
3649
3650Integer* Integer::Cast(v8::Value* value) {
3651#ifdef V8_ENABLE_CHECKS
3652 CheckCast(value);
3653#endif
3654 return static_cast<Integer*>(value);
3655}
3656
3657
3658Date* Date::Cast(v8::Value* value) {
3659#ifdef V8_ENABLE_CHECKS
3660 CheckCast(value);
3661#endif
3662 return static_cast<Date*>(value);
3663}
3664
3665
Ben Murdochf87a2032010-10-22 12:50:53 +01003666RegExp* RegExp::Cast(v8::Value* value) {
3667#ifdef V8_ENABLE_CHECKS
3668 CheckCast(value);
3669#endif
3670 return static_cast<RegExp*>(value);
3671}
3672
3673
Steve Blocka7e24c12009-10-30 11:49:00 +00003674Object* Object::Cast(v8::Value* value) {
3675#ifdef V8_ENABLE_CHECKS
3676 CheckCast(value);
3677#endif
3678 return static_cast<Object*>(value);
3679}
3680
3681
3682Array* Array::Cast(v8::Value* value) {
3683#ifdef V8_ENABLE_CHECKS
3684 CheckCast(value);
3685#endif
3686 return static_cast<Array*>(value);
3687}
3688
3689
3690Function* Function::Cast(v8::Value* value) {
3691#ifdef V8_ENABLE_CHECKS
3692 CheckCast(value);
3693#endif
3694 return static_cast<Function*>(value);
3695}
3696
3697
3698External* External::Cast(v8::Value* value) {
3699#ifdef V8_ENABLE_CHECKS
3700 CheckCast(value);
3701#endif
3702 return static_cast<External*>(value);
3703}
3704
3705
3706Local<Value> AccessorInfo::Data() const {
Steve Block6ded16b2010-05-10 14:33:55 +01003707 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003708}
3709
3710
3711Local<Object> AccessorInfo::This() const {
3712 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
3713}
3714
3715
3716Local<Object> AccessorInfo::Holder() const {
3717 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
3718}
3719
3720
3721/**
3722 * \example shell.cc
3723 * A simple shell that takes a list of expressions on the
3724 * command-line and executes them.
3725 */
3726
3727
3728/**
3729 * \example process.cc
3730 */
3731
3732
3733} // namespace v8
3734
3735
3736#undef V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00003737#undef TYPE_CHECK
3738
3739
3740#endif // V8_H_