blob: 89502cb9156af939b6fbc45a18a10a0cab94d313 [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
41#include <stdio.h>
42
43#ifdef _WIN32
44// When compiling on MinGW stdint.h is available.
45#ifdef __MINGW32__
46#include <stdint.h>
47#else // __MINGW32__
48typedef signed char int8_t;
49typedef unsigned char uint8_t;
50typedef short int16_t; // NOLINT
51typedef unsigned short uint16_t; // NOLINT
52typedef int int32_t;
53typedef unsigned int uint32_t;
54typedef __int64 int64_t;
55typedef unsigned __int64 uint64_t;
56// intptr_t and friends are defined in crtdefs.h through stdio.h.
57#endif // __MINGW32__
58
59// Setup for Windows DLL export/import. When building the V8 DLL the
60// BUILDING_V8_SHARED needs to be defined. When building a program which uses
61// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
62// static library or building a program which uses the V8 static library neither
63// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
Steve Blocka7e24c12009-10-30 11:49:00 +000064#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
65#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
66 build configuration to ensure that at most one of these is set
67#endif
68
69#ifdef BUILDING_V8_SHARED
70#define V8EXPORT __declspec(dllexport)
Steve Blocka7e24c12009-10-30 11:49:00 +000071#elif USING_V8_SHARED
72#define V8EXPORT __declspec(dllimport)
Steve Blocka7e24c12009-10-30 11:49:00 +000073#else
74#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000075#endif // BUILDING_V8_SHARED
76
77#else // _WIN32
78
79#include <stdint.h>
80
81// Setup for Linux shared library export. There is no need to distinguish
82// between building or using the V8 shared library, but we should not
83// export symbols when we are building a static library.
84#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
85#define V8EXPORT __attribute__ ((visibility("default")))
Steve Blocka7e24c12009-10-30 11:49:00 +000086#else // defined(__GNUC__) && (__GNUC__ >= 4)
87#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000088#endif // defined(__GNUC__) && (__GNUC__ >= 4)
89
90#endif // _WIN32
91
92/**
93 * The v8 JavaScript engine.
94 */
95namespace v8 {
96
97class Context;
98class String;
99class Value;
100class Utils;
101class Number;
102class Object;
103class Array;
104class Int32;
105class Uint32;
106class External;
107class Primitive;
108class Boolean;
109class Integer;
110class Function;
111class Date;
112class ImplementationUtilities;
113class Signature;
114template <class T> class Handle;
115template <class T> class Local;
116template <class T> class Persistent;
117class FunctionTemplate;
118class ObjectTemplate;
119class Data;
Leon Clarkef7060e22010-06-03 12:02:55 +0100120class AccessorInfo;
Kristian Monsen25f61362010-05-21 11:50:48 +0100121class StackTrace;
122class StackFrame;
Steve Blocka7e24c12009-10-30 11:49:00 +0000123
124namespace internal {
125
Steve Blocka7e24c12009-10-30 11:49:00 +0000126class Arguments;
Steve Blockd0582a62009-12-15 09:54:21 +0000127class Object;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100128class Heap;
Steve Blockd0582a62009-12-15 09:54:21 +0000129class Top;
Steve Blocka7e24c12009-10-30 11:49:00 +0000130
131}
132
133
134// --- W e a k H a n d l e s
135
136
137/**
138 * A weak reference callback function.
139 *
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100140 * This callback should either explicitly invoke Dispose on |object| if
141 * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak.
142 *
Steve Blocka7e24c12009-10-30 11:49:00 +0000143 * \param object the weak global object to be reclaimed by the garbage collector
144 * \param parameter the value passed in when making the weak global object
145 */
146typedef void (*WeakReferenceCallback)(Persistent<Value> object,
147 void* parameter);
148
149
150// --- H a n d l e s ---
151
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100152#define TYPE_CHECK(T, S) \
153 while (false) { \
154 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
Steve Blocka7e24c12009-10-30 11:49:00 +0000155 }
156
157/**
158 * An object reference managed by the v8 garbage collector.
159 *
160 * All objects returned from v8 have to be tracked by the garbage
161 * collector so that it knows that the objects are still alive. Also,
162 * because the garbage collector may move objects, it is unsafe to
163 * point directly to an object. Instead, all objects are stored in
164 * handles which are known by the garbage collector and updated
165 * whenever an object moves. Handles should always be passed by value
166 * (except in cases like out-parameters) and they should never be
167 * allocated on the heap.
168 *
169 * There are two types of handles: local and persistent handles.
170 * Local handles are light-weight and transient and typically used in
171 * local operations. They are managed by HandleScopes. Persistent
172 * handles can be used when storing objects across several independent
173 * operations and have to be explicitly deallocated when they're no
174 * longer used.
175 *
176 * It is safe to extract the object stored in the handle by
177 * dereferencing the handle (for instance, to extract the Object* from
178 * an Handle<Object>); the value will still be governed by a handle
179 * behind the scenes and the same rules apply to these values as to
180 * their handles.
181 */
Steve Block8defd9f2010-07-08 12:39:36 +0100182template <class T> class Handle {
Steve Blocka7e24c12009-10-30 11:49:00 +0000183 public:
184
185 /**
186 * Creates an empty handle.
187 */
188 inline Handle();
189
190 /**
191 * Creates a new handle for the specified value.
192 */
Steve Block8defd9f2010-07-08 12:39:36 +0100193 inline explicit Handle(T* val) : val_(val) { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000194
195 /**
196 * Creates a handle for the contents of the specified handle. This
197 * constructor allows you to pass handles as arguments by value and
198 * to assign between handles. However, if you try to assign between
199 * incompatible handles, for instance from a Handle<String> to a
200 * Handle<Number> it will cause a compiletime error. Assigning
201 * between compatible handles, for instance assigning a
202 * Handle<String> to a variable declared as Handle<Value>, is legal
203 * because String is a subclass of Value.
204 */
205 template <class S> inline Handle(Handle<S> that)
206 : val_(reinterpret_cast<T*>(*that)) {
207 /**
208 * This check fails when trying to convert between incompatible
209 * handles. For example, converting from a Handle<String> to a
210 * Handle<Number>.
211 */
212 TYPE_CHECK(T, S);
213 }
214
215 /**
216 * Returns true if the handle is empty.
217 */
Steve Block8defd9f2010-07-08 12:39:36 +0100218 inline bool IsEmpty() const { return val_ == 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000219
Steve Block8defd9f2010-07-08 12:39:36 +0100220 inline T* operator->() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000221
Steve Block8defd9f2010-07-08 12:39:36 +0100222 inline T* operator*() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000223
224 /**
225 * Sets the handle to be empty. IsEmpty() will then return true.
226 */
Steve Block8defd9f2010-07-08 12:39:36 +0100227 inline void Clear() { this->val_ = 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000228
229 /**
230 * Checks whether two handles are the same.
231 * Returns true if both are empty, or if the objects
232 * to which they refer are identical.
233 * The handles' references are not checked.
234 */
Steve Block8defd9f2010-07-08 12:39:36 +0100235 template <class S> inline bool operator==(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000236 internal::Object** a = reinterpret_cast<internal::Object**>(**this);
237 internal::Object** b = reinterpret_cast<internal::Object**>(*that);
238 if (a == 0) return b == 0;
239 if (b == 0) return false;
240 return *a == *b;
241 }
242
243 /**
244 * Checks whether two handles are different.
245 * Returns true if only one of the handles is empty, or if
246 * the objects to which they refer are different.
247 * The handles' references are not checked.
248 */
Steve Block8defd9f2010-07-08 12:39:36 +0100249 template <class S> inline bool operator!=(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000250 return !operator==(that);
251 }
252
253 template <class S> static inline Handle<T> Cast(Handle<S> that) {
254#ifdef V8_ENABLE_CHECKS
255 // If we're going to perform the type check then we have to check
256 // that the handle isn't empty before doing the checked cast.
257 if (that.IsEmpty()) return Handle<T>();
258#endif
259 return Handle<T>(T::Cast(*that));
260 }
261
Steve Block6ded16b2010-05-10 14:33:55 +0100262 template <class S> inline Handle<S> As() {
263 return Handle<S>::Cast(*this);
264 }
265
Steve Blocka7e24c12009-10-30 11:49:00 +0000266 private:
267 T* val_;
268};
269
270
271/**
272 * A light-weight stack-allocated object handle. All operations
273 * that return objects from within v8 return them in local handles. They
274 * are created within HandleScopes, and all local handles allocated within a
275 * handle scope are destroyed when the handle scope is destroyed. Hence it
276 * is not necessary to explicitly deallocate local handles.
277 */
Steve Block8defd9f2010-07-08 12:39:36 +0100278template <class T> class Local : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000279 public:
280 inline Local();
281 template <class S> inline Local(Local<S> that)
282 : Handle<T>(reinterpret_cast<T*>(*that)) {
283 /**
284 * This check fails when trying to convert between incompatible
285 * handles. For example, converting from a Handle<String> to a
286 * Handle<Number>.
287 */
288 TYPE_CHECK(T, S);
289 }
290 template <class S> inline Local(S* that) : Handle<T>(that) { }
291 template <class S> static inline Local<T> Cast(Local<S> that) {
292#ifdef V8_ENABLE_CHECKS
293 // If we're going to perform the type check then we have to check
294 // that the handle isn't empty before doing the checked cast.
295 if (that.IsEmpty()) return Local<T>();
296#endif
297 return Local<T>(T::Cast(*that));
298 }
299
Steve Block6ded16b2010-05-10 14:33:55 +0100300 template <class S> inline Local<S> As() {
301 return Local<S>::Cast(*this);
302 }
303
Steve Blocka7e24c12009-10-30 11:49:00 +0000304 /** Create a local handle for the content of another handle.
305 * The referee is kept alive by the local handle even when
306 * the original handle is destroyed/disposed.
307 */
308 inline static Local<T> New(Handle<T> that);
309};
310
311
312/**
313 * An object reference that is independent of any handle scope. Where
314 * a Local handle only lives as long as the HandleScope in which it was
315 * allocated, a Persistent handle remains valid until it is explicitly
316 * disposed.
317 *
318 * A persistent handle contains a reference to a storage cell within
319 * the v8 engine which holds an object value and which is updated by
320 * the garbage collector whenever the object is moved. A new storage
321 * cell can be created using Persistent::New and existing handles can
322 * be disposed using Persistent::Dispose. Since persistent handles
323 * are passed by value you may have many persistent handle objects
324 * that point to the same storage cell. For instance, if you pass a
325 * persistent handle as an argument to a function you will not get two
326 * different storage cells but rather two references to the same
327 * storage cell.
328 */
Steve Block8defd9f2010-07-08 12:39:36 +0100329template <class T> class Persistent : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000330 public:
331
332 /**
333 * Creates an empty persistent handle that doesn't point to any
334 * storage cell.
335 */
336 inline Persistent();
337
338 /**
339 * Creates a persistent handle for the same storage cell as the
340 * specified handle. This constructor allows you to pass persistent
341 * handles as arguments by value and to assign between persistent
342 * handles. However, attempting to assign between incompatible
343 * persistent handles, for instance from a Persistent<String> to a
344 * Persistent<Number> will cause a compiletime error. Assigning
345 * between compatible persistent handles, for instance assigning a
346 * Persistent<String> to a variable declared as Persistent<Value>,
347 * is allowed as String is a subclass of Value.
348 */
349 template <class S> inline Persistent(Persistent<S> that)
350 : Handle<T>(reinterpret_cast<T*>(*that)) {
351 /**
352 * This check fails when trying to convert between incompatible
353 * handles. For example, converting from a Handle<String> to a
354 * Handle<Number>.
355 */
356 TYPE_CHECK(T, S);
357 }
358
359 template <class S> inline Persistent(S* that) : Handle<T>(that) { }
360
361 /**
362 * "Casts" a plain handle which is known to be a persistent handle
363 * to a persistent handle.
364 */
365 template <class S> explicit inline Persistent(Handle<S> that)
366 : Handle<T>(*that) { }
367
368 template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
369#ifdef V8_ENABLE_CHECKS
370 // If we're going to perform the type check then we have to check
371 // that the handle isn't empty before doing the checked cast.
372 if (that.IsEmpty()) return Persistent<T>();
373#endif
374 return Persistent<T>(T::Cast(*that));
375 }
376
Steve Block6ded16b2010-05-10 14:33:55 +0100377 template <class S> inline Persistent<S> As() {
378 return Persistent<S>::Cast(*this);
379 }
380
Steve Blocka7e24c12009-10-30 11:49:00 +0000381 /**
382 * Creates a new persistent handle for an existing local or
383 * persistent handle.
384 */
385 inline static Persistent<T> New(Handle<T> that);
386
387 /**
388 * Releases the storage cell referenced by this persistent handle.
389 * Does not remove the reference to the cell from any handles.
390 * This handle's reference, and any any other references to the storage
391 * cell remain and IsEmpty will still return false.
392 */
393 inline void Dispose();
394
395 /**
396 * Make the reference to this object weak. When only weak handles
397 * refer to the object, the garbage collector will perform a
398 * callback to the given V8::WeakReferenceCallback function, passing
399 * it the object reference and the given parameters.
400 */
401 inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
402
403 /** Clears the weak reference to this object.*/
404 inline void ClearWeak();
405
406 /**
407 *Checks if the handle holds the only reference to an object.
408 */
409 inline bool IsNearDeath() const;
410
411 /**
412 * Returns true if the handle's reference is weak.
413 */
414 inline bool IsWeak() const;
415
416 private:
417 friend class ImplementationUtilities;
418 friend class ObjectTemplate;
419};
420
421
422 /**
423 * A stack-allocated class that governs a number of local handles.
424 * After a handle scope has been created, all local handles will be
425 * allocated within that handle scope until either the handle scope is
426 * deleted or another handle scope is created. If there is already a
427 * handle scope and a new one is created, all allocations will take
428 * place in the new handle scope until it is deleted. After that,
429 * new handles will again be allocated in the original handle scope.
430 *
431 * After the handle scope of a local handle has been deleted the
432 * garbage collector will no longer track the object stored in the
433 * handle and may deallocate it. The behavior of accessing a handle
434 * for which the handle scope has been deleted is undefined.
435 */
436class V8EXPORT HandleScope {
437 public:
438 HandleScope();
439
440 ~HandleScope();
441
442 /**
443 * Closes the handle scope and returns the value as a handle in the
444 * previous scope, which is the new current scope after the call.
445 */
446 template <class T> Local<T> Close(Handle<T> value);
447
448 /**
449 * Counts the number of allocated handles.
450 */
451 static int NumberOfHandles();
452
453 /**
454 * Creates a new handle with the given value.
455 */
456 static internal::Object** CreateHandle(internal::Object* value);
457
458 private:
459 // Make it impossible to create heap-allocated or illegal handle
460 // scopes by disallowing certain operations.
461 HandleScope(const HandleScope&);
462 void operator=(const HandleScope&);
463 void* operator new(size_t size);
464 void operator delete(void*, size_t);
465
Steve Blockd0582a62009-12-15 09:54:21 +0000466 // This Data class is accessible internally as HandleScopeData through a
467 // typedef in the ImplementationUtilities class.
Steve Blocka7e24c12009-10-30 11:49:00 +0000468 class V8EXPORT Data {
469 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000470 internal::Object** next;
471 internal::Object** limit;
John Reck59135872010-11-02 12:39:01 -0700472 int level;
473
Steve Blocka7e24c12009-10-30 11:49:00 +0000474 inline void Initialize() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000475 next = limit = NULL;
John Reck59135872010-11-02 12:39:01 -0700476 level = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000477 }
478 };
John Reck59135872010-11-02 12:39:01 -0700479
480 void Leave();
Steve Blocka7e24c12009-10-30 11:49:00 +0000481
John Reck59135872010-11-02 12:39:01 -0700482
483 internal::Object** prev_next_;
484 internal::Object** prev_limit_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000485
486 // Allow for the active closing of HandleScopes which allows to pass a handle
487 // from the HandleScope being closed to the next top most HandleScope.
488 bool is_closed_;
489 internal::Object** RawClose(internal::Object** value);
490
491 friend class ImplementationUtilities;
492};
493
494
495// --- S p e c i a l o b j e c t s ---
496
497
498/**
499 * The superclass of values and API object templates.
500 */
501class V8EXPORT Data {
502 private:
503 Data();
504};
505
506
507/**
508 * Pre-compilation data that can be associated with a script. This
509 * data can be calculated for a script in advance of actually
510 * compiling it, and can be stored between compilations. When script
511 * data is given to the compile method compilation will be faster.
512 */
513class V8EXPORT ScriptData { // NOLINT
514 public:
515 virtual ~ScriptData() { }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100516
Leon Clarkef7060e22010-06-03 12:02:55 +0100517 /**
518 * Pre-compiles the specified script (context-independent).
519 *
520 * \param input Pointer to UTF-8 script source code.
521 * \param length Length of UTF-8 script source code.
522 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000523 static ScriptData* PreCompile(const char* input, int length);
Steve Blocka7e24c12009-10-30 11:49:00 +0000524
Leon Clarkef7060e22010-06-03 12:02:55 +0100525 /**
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100526 * Pre-compiles the specified script (context-independent).
527 *
528 * NOTE: Pre-compilation using this method cannot happen on another thread
529 * without using Lockers.
530 *
531 * \param source Script source code.
532 */
533 static ScriptData* PreCompile(Handle<String> source);
534
535 /**
Leon Clarkef7060e22010-06-03 12:02:55 +0100536 * Load previous pre-compilation data.
537 *
538 * \param data Pointer to data returned by a call to Data() of a previous
539 * ScriptData. Ownership is not transferred.
540 * \param length Length of data.
541 */
542 static ScriptData* New(const char* data, int length);
543
544 /**
545 * Returns the length of Data().
546 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000547 virtual int Length() = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100548
549 /**
550 * Returns a serialized representation of this ScriptData that can later be
551 * passed to New(). NOTE: Serialized data is platform-dependent.
552 */
553 virtual const char* Data() = 0;
554
555 /**
556 * Returns true if the source code could not be parsed.
557 */
Leon Clarkee46be812010-01-19 14:06:41 +0000558 virtual bool HasError() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000559};
560
561
562/**
563 * The origin, within a file, of a script.
564 */
Steve Block8defd9f2010-07-08 12:39:36 +0100565class ScriptOrigin {
Steve Blocka7e24c12009-10-30 11:49:00 +0000566 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100567 inline ScriptOrigin(
568 Handle<Value> resource_name,
569 Handle<Integer> resource_line_offset = Handle<Integer>(),
570 Handle<Integer> resource_column_offset = Handle<Integer>())
Steve Blocka7e24c12009-10-30 11:49:00 +0000571 : resource_name_(resource_name),
572 resource_line_offset_(resource_line_offset),
573 resource_column_offset_(resource_column_offset) { }
574 inline Handle<Value> ResourceName() const;
575 inline Handle<Integer> ResourceLineOffset() const;
576 inline Handle<Integer> ResourceColumnOffset() const;
577 private:
578 Handle<Value> resource_name_;
579 Handle<Integer> resource_line_offset_;
580 Handle<Integer> resource_column_offset_;
581};
582
583
584/**
585 * A compiled JavaScript script.
586 */
587class V8EXPORT Script {
588 public:
589
Steve Blocka7e24c12009-10-30 11:49:00 +0000590 /**
Andrei Popescu402d9372010-02-26 13:31:12 +0000591 * Compiles the specified script (context-independent).
Steve Blocka7e24c12009-10-30 11:49:00 +0000592 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000593 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100594 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000595 * when New() returns
596 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
597 * using pre_data speeds compilation if it's done multiple times.
598 * Owned by caller, no references are kept when New() returns.
599 * \param script_data Arbitrary data associated with script. Using
Steve Block6ded16b2010-05-10 14:33:55 +0100600 * this has same effect as calling SetData(), but allows data to be
Andrei Popescu402d9372010-02-26 13:31:12 +0000601 * available to compile event handlers.
602 * \return Compiled script object (context independent; when run it
603 * will use the currently entered context).
Steve Blocka7e24c12009-10-30 11:49:00 +0000604 */
Andrei Popescu402d9372010-02-26 13:31:12 +0000605 static Local<Script> New(Handle<String> source,
606 ScriptOrigin* origin = NULL,
607 ScriptData* pre_data = NULL,
608 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000609
610 /**
611 * Compiles the specified script using the specified file name
612 * object (typically a string) as the script's origin.
613 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000614 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100615 * \param file_name file name object (typically a string) to be used
Andrei Popescu402d9372010-02-26 13:31:12 +0000616 * as the script's origin.
617 * \return Compiled script object (context independent; when run it
618 * will use the currently entered context).
619 */
620 static Local<Script> New(Handle<String> source,
621 Handle<Value> file_name);
622
623 /**
624 * Compiles the specified script (bound to current context).
625 *
626 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100627 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000628 * when Compile() returns
629 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
630 * using pre_data speeds compilation if it's done multiple times.
631 * Owned by caller, no references are kept when Compile() returns.
632 * \param script_data Arbitrary data associated with script. Using
633 * this has same effect as calling SetData(), but makes data available
634 * earlier (i.e. to compile event handlers).
635 * \return Compiled script object, bound to the context that was active
636 * when this function was called. When run it will always use this
637 * context.
Steve Blocka7e24c12009-10-30 11:49:00 +0000638 */
639 static Local<Script> Compile(Handle<String> source,
Andrei Popescu402d9372010-02-26 13:31:12 +0000640 ScriptOrigin* origin = NULL,
641 ScriptData* pre_data = NULL,
642 Handle<String> script_data = Handle<String>());
643
644 /**
645 * Compiles the specified script using the specified file name
646 * object (typically a string) as the script's origin.
647 *
648 * \param source Script source code.
649 * \param file_name File name to use as script's origin
650 * \param script_data Arbitrary data associated with script. Using
651 * this has same effect as calling SetData(), but makes data available
652 * earlier (i.e. to compile event handlers).
653 * \return Compiled script object, bound to the context that was active
654 * when this function was called. When run it will always use this
655 * context.
656 */
657 static Local<Script> Compile(Handle<String> source,
658 Handle<Value> file_name,
659 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000660
661 /**
662 * Runs the script returning the resulting value. If the script is
663 * context independent (created using ::New) it will be run in the
664 * currently entered context. If it is context specific (created
665 * using ::Compile) it will be run in the context in which it was
666 * compiled.
667 */
668 Local<Value> Run();
669
670 /**
671 * Returns the script id value.
672 */
673 Local<Value> Id();
674
675 /**
676 * Associate an additional data object with the script. This is mainly used
677 * with the debugger as this data object is only available through the
678 * debugger API.
679 */
Steve Blockd0582a62009-12-15 09:54:21 +0000680 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000681};
682
683
684/**
685 * An error message.
686 */
687class V8EXPORT Message {
688 public:
689 Local<String> Get() const;
690 Local<String> GetSourceLine() const;
691
692 /**
693 * Returns the resource name for the script from where the function causing
694 * the error originates.
695 */
696 Handle<Value> GetScriptResourceName() const;
697
698 /**
699 * Returns the resource data for the script from where the function causing
700 * the error originates.
701 */
702 Handle<Value> GetScriptData() const;
703
704 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100705 * Exception stack trace. By default stack traces are not captured for
706 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
707 * to change this option.
708 */
709 Handle<StackTrace> GetStackTrace() const;
710
711 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000712 * Returns the number, 1-based, of the line where the error occurred.
713 */
714 int GetLineNumber() const;
715
716 /**
717 * Returns the index within the script of the first character where
718 * the error occurred.
719 */
720 int GetStartPosition() const;
721
722 /**
723 * Returns the index within the script of the last character where
724 * the error occurred.
725 */
726 int GetEndPosition() const;
727
728 /**
729 * Returns the index within the line of the first character where
730 * the error occurred.
731 */
732 int GetStartColumn() const;
733
734 /**
735 * Returns the index within the line of the last character where
736 * the error occurred.
737 */
738 int GetEndColumn() const;
739
740 // TODO(1245381): Print to a string instead of on a FILE.
741 static void PrintCurrentStackTrace(FILE* out);
Kristian Monsen25f61362010-05-21 11:50:48 +0100742
743 static const int kNoLineNumberInfo = 0;
744 static const int kNoColumnInfo = 0;
745};
746
747
748/**
749 * Representation of a JavaScript stack trace. The information collected is a
750 * snapshot of the execution stack and the information remains valid after
751 * execution continues.
752 */
753class V8EXPORT StackTrace {
754 public:
755 /**
756 * Flags that determine what information is placed captured for each
757 * StackFrame when grabbing the current stack trace.
758 */
759 enum StackTraceOptions {
760 kLineNumber = 1,
761 kColumnOffset = 1 << 1 | kLineNumber,
762 kScriptName = 1 << 2,
763 kFunctionName = 1 << 3,
764 kIsEval = 1 << 4,
765 kIsConstructor = 1 << 5,
Ben Murdochf87a2032010-10-22 12:50:53 +0100766 kScriptNameOrSourceURL = 1 << 6,
Kristian Monsen25f61362010-05-21 11:50:48 +0100767 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
Ben Murdochf87a2032010-10-22 12:50:53 +0100768 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
Kristian Monsen25f61362010-05-21 11:50:48 +0100769 };
770
771 /**
772 * Returns a StackFrame at a particular index.
773 */
774 Local<StackFrame> GetFrame(uint32_t index) const;
775
776 /**
777 * Returns the number of StackFrames.
778 */
779 int GetFrameCount() const;
780
781 /**
782 * Returns StackTrace as a v8::Array that contains StackFrame objects.
783 */
784 Local<Array> AsArray();
785
786 /**
787 * Grab a snapshot of the the current JavaScript execution stack.
788 *
789 * \param frame_limit The maximum number of stack frames we want to capture.
790 * \param options Enumerates the set of things we will capture for each
791 * StackFrame.
792 */
793 static Local<StackTrace> CurrentStackTrace(
794 int frame_limit,
795 StackTraceOptions options = kOverview);
796};
797
798
799/**
800 * A single JavaScript stack frame.
801 */
802class V8EXPORT StackFrame {
803 public:
804 /**
805 * Returns the number, 1-based, of the line for the associate function call.
806 * This method will return Message::kNoLineNumberInfo if it is unable to
807 * retrieve the line number, or if kLineNumber was not passed as an option
808 * when capturing the StackTrace.
809 */
810 int GetLineNumber() const;
811
812 /**
813 * Returns the 1-based column offset on the line for the associated function
814 * call.
815 * This method will return Message::kNoColumnInfo if it is unable to retrieve
816 * the column number, or if kColumnOffset was not passed as an option when
817 * capturing the StackTrace.
818 */
819 int GetColumn() const;
820
821 /**
822 * Returns the name of the resource that contains the script for the
823 * function for this StackFrame.
824 */
825 Local<String> GetScriptName() const;
826
827 /**
Ben Murdochf87a2032010-10-22 12:50:53 +0100828 * Returns the name of the resource that contains the script for the
829 * function for this StackFrame or sourceURL value if the script name
830 * is undefined and its source ends with //@ sourceURL=... string.
831 */
832 Local<String> GetScriptNameOrSourceURL() const;
833
834 /**
Kristian Monsen25f61362010-05-21 11:50:48 +0100835 * Returns the name of the function associated with this stack frame.
836 */
837 Local<String> GetFunctionName() const;
838
839 /**
840 * Returns whether or not the associated function is compiled via a call to
841 * eval().
842 */
843 bool IsEval() const;
844
845 /**
846 * Returns whther or not the associated function is called as a
847 * constructor via "new".
848 */
849 bool IsConstructor() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000850};
851
852
853// --- V a l u e ---
854
855
856/**
857 * The superclass of all JavaScript values and objects.
858 */
Steve Block8defd9f2010-07-08 12:39:36 +0100859class Value : public Data {
Steve Blocka7e24c12009-10-30 11:49:00 +0000860 public:
861
862 /**
863 * Returns true if this value is the undefined value. See ECMA-262
864 * 4.3.10.
865 */
Steve Block8defd9f2010-07-08 12:39:36 +0100866 V8EXPORT bool IsUndefined() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000867
868 /**
869 * Returns true if this value is the null value. See ECMA-262
870 * 4.3.11.
871 */
Steve Block8defd9f2010-07-08 12:39:36 +0100872 V8EXPORT bool IsNull() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000873
874 /**
875 * Returns true if this value is true.
876 */
Steve Block8defd9f2010-07-08 12:39:36 +0100877 V8EXPORT bool IsTrue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000878
879 /**
880 * Returns true if this value is false.
881 */
Steve Block8defd9f2010-07-08 12:39:36 +0100882 V8EXPORT bool IsFalse() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000883
884 /**
885 * Returns true if this value is an instance of the String type.
886 * See ECMA-262 8.4.
887 */
888 inline bool IsString() const;
889
890 /**
891 * Returns true if this value is a function.
892 */
Steve Block8defd9f2010-07-08 12:39:36 +0100893 V8EXPORT bool IsFunction() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000894
895 /**
896 * Returns true if this value is an array.
897 */
Steve Block8defd9f2010-07-08 12:39:36 +0100898 V8EXPORT bool IsArray() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000899
900 /**
901 * Returns true if this value is an object.
902 */
Steve Block8defd9f2010-07-08 12:39:36 +0100903 V8EXPORT bool IsObject() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000904
905 /**
906 * Returns true if this value is boolean.
907 */
Steve Block8defd9f2010-07-08 12:39:36 +0100908 V8EXPORT bool IsBoolean() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000909
910 /**
911 * Returns true if this value is a number.
912 */
Steve Block8defd9f2010-07-08 12:39:36 +0100913 V8EXPORT bool IsNumber() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000914
915 /**
916 * Returns true if this value is external.
917 */
Steve Block8defd9f2010-07-08 12:39:36 +0100918 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000919
920 /**
921 * Returns true if this value is a 32-bit signed integer.
922 */
Steve Block8defd9f2010-07-08 12:39:36 +0100923 V8EXPORT bool IsInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000924
925 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100926 * Returns true if this value is a 32-bit unsigned integer.
927 */
Steve Block8defd9f2010-07-08 12:39:36 +0100928 V8EXPORT bool IsUint32() const;
Steve Block6ded16b2010-05-10 14:33:55 +0100929
930 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000931 * Returns true if this value is a Date.
932 */
Steve Block8defd9f2010-07-08 12:39:36 +0100933 V8EXPORT bool IsDate() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000934
Iain Merrick75681382010-08-19 15:07:18 +0100935 /**
936 * Returns true if this value is a RegExp.
937 */
938 V8EXPORT bool IsRegExp() const;
939
Steve Block8defd9f2010-07-08 12:39:36 +0100940 V8EXPORT Local<Boolean> ToBoolean() const;
941 V8EXPORT Local<Number> ToNumber() const;
942 V8EXPORT Local<String> ToString() const;
943 V8EXPORT Local<String> ToDetailString() const;
944 V8EXPORT Local<Object> ToObject() const;
945 V8EXPORT Local<Integer> ToInteger() const;
946 V8EXPORT Local<Uint32> ToUint32() const;
947 V8EXPORT Local<Int32> ToInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000948
949 /**
950 * Attempts to convert a string to an array index.
951 * Returns an empty handle if the conversion fails.
952 */
Steve Block8defd9f2010-07-08 12:39:36 +0100953 V8EXPORT Local<Uint32> ToArrayIndex() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000954
Steve Block8defd9f2010-07-08 12:39:36 +0100955 V8EXPORT bool BooleanValue() const;
956 V8EXPORT double NumberValue() const;
957 V8EXPORT int64_t IntegerValue() const;
958 V8EXPORT uint32_t Uint32Value() const;
959 V8EXPORT int32_t Int32Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000960
961 /** JS == */
Steve Block8defd9f2010-07-08 12:39:36 +0100962 V8EXPORT bool Equals(Handle<Value> that) const;
963 V8EXPORT bool StrictEquals(Handle<Value> that) const;
Steve Block3ce2e202009-11-05 08:53:23 +0000964
Steve Blocka7e24c12009-10-30 11:49:00 +0000965 private:
966 inline bool QuickIsString() const;
Steve Block8defd9f2010-07-08 12:39:36 +0100967 V8EXPORT bool FullIsString() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000968};
969
970
971/**
972 * The superclass of primitive values. See ECMA-262 4.3.2.
973 */
Steve Block8defd9f2010-07-08 12:39:36 +0100974class Primitive : public Value { };
Steve Blocka7e24c12009-10-30 11:49:00 +0000975
976
977/**
978 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
979 * or false value.
980 */
Steve Block8defd9f2010-07-08 12:39:36 +0100981class Boolean : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000982 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100983 V8EXPORT bool Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000984 static inline Handle<Boolean> New(bool value);
985};
986
987
988/**
989 * A JavaScript string value (ECMA-262, 4.3.17).
990 */
Steve Block8defd9f2010-07-08 12:39:36 +0100991class String : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000992 public:
993
994 /**
995 * Returns the number of characters in this string.
996 */
Steve Block8defd9f2010-07-08 12:39:36 +0100997 V8EXPORT int Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000998
999 /**
1000 * Returns the number of bytes in the UTF-8 encoded
1001 * representation of this string.
1002 */
Steve Block8defd9f2010-07-08 12:39:36 +01001003 V8EXPORT int Utf8Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001004
1005 /**
1006 * Write the contents of the string to an external buffer.
1007 * If no arguments are given, expects the buffer to be large
1008 * enough to hold the entire string and NULL terminator. Copies
1009 * the contents of the string and the NULL terminator into the
1010 * buffer.
1011 *
1012 * Copies up to length characters into the output buffer.
1013 * Only null-terminates if there is enough space in the buffer.
1014 *
1015 * \param buffer The buffer into which the string will be copied.
1016 * \param start The starting position within the string at which
1017 * copying begins.
1018 * \param length The number of bytes to copy from the string.
Steve Block6ded16b2010-05-10 14:33:55 +01001019 * \param nchars_ref The number of characters written, can be NULL.
1020 * \param hints Various hints that might affect performance of this or
1021 * subsequent operations.
1022 * \return The number of bytes copied to the buffer
Steve Blocka7e24c12009-10-30 11:49:00 +00001023 * excluding the NULL terminator.
1024 */
Steve Block6ded16b2010-05-10 14:33:55 +01001025 enum WriteHints {
1026 NO_HINTS = 0,
1027 HINT_MANY_WRITES_EXPECTED = 1
1028 };
1029
Steve Block8defd9f2010-07-08 12:39:36 +01001030 V8EXPORT int Write(uint16_t* buffer,
1031 int start = 0,
1032 int length = -1,
1033 WriteHints hints = NO_HINTS) const; // UTF-16
1034 V8EXPORT int WriteAscii(char* buffer,
1035 int start = 0,
1036 int length = -1,
1037 WriteHints hints = NO_HINTS) const; // ASCII
1038 V8EXPORT int WriteUtf8(char* buffer,
1039 int length = -1,
1040 int* nchars_ref = NULL,
1041 WriteHints hints = NO_HINTS) const; // UTF-8
Steve Blocka7e24c12009-10-30 11:49:00 +00001042
1043 /**
1044 * A zero length string.
1045 */
Steve Block8defd9f2010-07-08 12:39:36 +01001046 V8EXPORT static v8::Local<v8::String> Empty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001047
1048 /**
1049 * Returns true if the string is external
1050 */
Steve Block8defd9f2010-07-08 12:39:36 +01001051 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001052
1053 /**
1054 * Returns true if the string is both external and ascii
1055 */
Steve Block8defd9f2010-07-08 12:39:36 +01001056 V8EXPORT bool IsExternalAscii() const;
Leon Clarkee46be812010-01-19 14:06:41 +00001057
1058 class V8EXPORT ExternalStringResourceBase {
1059 public:
1060 virtual ~ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001061
Leon Clarkee46be812010-01-19 14:06:41 +00001062 protected:
1063 ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001064
1065 /**
1066 * Internally V8 will call this Dispose method when the external string
1067 * resource is no longer needed. The default implementation will use the
1068 * delete operator. This method can be overridden in subclasses to
1069 * control how allocated external string resources are disposed.
1070 */
1071 virtual void Dispose() { delete this; }
1072
Leon Clarkee46be812010-01-19 14:06:41 +00001073 private:
1074 // Disallow copying and assigning.
1075 ExternalStringResourceBase(const ExternalStringResourceBase&);
1076 void operator=(const ExternalStringResourceBase&);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001077
1078 friend class v8::internal::Heap;
Leon Clarkee46be812010-01-19 14:06:41 +00001079 };
1080
Steve Blocka7e24c12009-10-30 11:49:00 +00001081 /**
1082 * An ExternalStringResource is a wrapper around a two-byte string
1083 * buffer that resides outside V8's heap. Implement an
1084 * ExternalStringResource to manage the life cycle of the underlying
1085 * buffer. Note that the string data must be immutable.
1086 */
Leon Clarkee46be812010-01-19 14:06:41 +00001087 class V8EXPORT ExternalStringResource
1088 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001089 public:
1090 /**
1091 * Override the destructor to manage the life cycle of the underlying
1092 * buffer.
1093 */
1094 virtual ~ExternalStringResource() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001095
1096 /**
1097 * The string data from the underlying buffer.
1098 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001099 virtual const uint16_t* data() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001100
1101 /**
1102 * The length of the string. That is, the number of two-byte characters.
1103 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001104 virtual size_t length() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001105
Steve Blocka7e24c12009-10-30 11:49:00 +00001106 protected:
1107 ExternalStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001108 };
1109
1110 /**
1111 * An ExternalAsciiStringResource is a wrapper around an ascii
1112 * string buffer that resides outside V8's heap. Implement an
1113 * ExternalAsciiStringResource to manage the life cycle of the
1114 * underlying buffer. Note that the string data must be immutable
1115 * and that the data must be strict 7-bit ASCII, not Latin1 or
1116 * UTF-8, which would require special treatment internally in the
1117 * engine and, in the case of UTF-8, do not allow efficient indexing.
1118 * Use String::New or convert to 16 bit data for non-ASCII.
1119 */
1120
Leon Clarkee46be812010-01-19 14:06:41 +00001121 class V8EXPORT ExternalAsciiStringResource
1122 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001123 public:
1124 /**
1125 * Override the destructor to manage the life cycle of the underlying
1126 * buffer.
1127 */
1128 virtual ~ExternalAsciiStringResource() {}
1129 /** The string data from the underlying buffer.*/
1130 virtual const char* data() const = 0;
1131 /** The number of ascii characters in the string.*/
1132 virtual size_t length() const = 0;
1133 protected:
1134 ExternalAsciiStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001135 };
1136
1137 /**
1138 * Get the ExternalStringResource for an external string. Returns
1139 * NULL if IsExternal() doesn't return true.
1140 */
1141 inline ExternalStringResource* GetExternalStringResource() const;
1142
1143 /**
1144 * Get the ExternalAsciiStringResource for an external ascii string.
1145 * Returns NULL if IsExternalAscii() doesn't return true.
1146 */
Steve Block8defd9f2010-07-08 12:39:36 +01001147 V8EXPORT ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001148
1149 static inline String* Cast(v8::Value* obj);
1150
1151 /**
1152 * Allocates a new string from either utf-8 encoded or ascii data.
1153 * The second parameter 'length' gives the buffer length.
1154 * If the data is utf-8 encoded, the caller must
1155 * be careful to supply the length parameter.
1156 * If it is not given, the function calls
1157 * 'strlen' to determine the buffer length, it might be
1158 * wrong if 'data' contains a null character.
1159 */
Steve Block8defd9f2010-07-08 12:39:36 +01001160 V8EXPORT static Local<String> New(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001161
1162 /** Allocates a new string from utf16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001163 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001164
1165 /** Creates a symbol. Returns one if it exists already.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001166 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001167
1168 /**
Steve Block3ce2e202009-11-05 08:53:23 +00001169 * Creates a new string by concatenating the left and the right strings
1170 * passed in as parameters.
1171 */
Steve Block8defd9f2010-07-08 12:39:36 +01001172 V8EXPORT static Local<String> Concat(Handle<String> left,
1173 Handle<String>right);
Steve Block3ce2e202009-11-05 08:53:23 +00001174
1175 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001176 * Creates a new external string using the data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001177 * resource. When the external string is no longer live on V8's heap the
1178 * resource will be disposed by calling its Dispose method. The caller of
1179 * this function should not otherwise delete or modify the resource. Neither
1180 * should the underlying buffer be deallocated or modified except through the
1181 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001182 */
Steve Block8defd9f2010-07-08 12:39:36 +01001183 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001184
1185 /**
1186 * Associate an external string resource with this string by transforming it
1187 * in place so that existing references to this string in the JavaScript heap
1188 * will use the external string resource. The external string resource's
1189 * character contents needs to be equivalent to this string.
1190 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001191 * The string is not modified if the operation fails. See NewExternal for
1192 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001193 */
Steve Block8defd9f2010-07-08 12:39:36 +01001194 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001195
1196 /**
1197 * Creates a new external string using the ascii data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001198 * resource. When the external string is no longer live on V8's heap the
1199 * resource will be disposed by calling its Dispose method. The caller of
1200 * this function should not otherwise delete or modify the resource. Neither
1201 * should the underlying buffer be deallocated or modified except through the
1202 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001203 */
Steve Block8defd9f2010-07-08 12:39:36 +01001204 V8EXPORT static Local<String> NewExternal(
1205 ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001206
1207 /**
1208 * Associate an external string resource with this string by transforming it
1209 * in place so that existing references to this string in the JavaScript heap
1210 * will use the external string resource. The external string resource's
1211 * character contents needs to be equivalent to this string.
1212 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001213 * The string is not modified if the operation fails. See NewExternal for
1214 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001215 */
Steve Block8defd9f2010-07-08 12:39:36 +01001216 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001217
1218 /**
1219 * Returns true if this string can be made external.
1220 */
Steve Block8defd9f2010-07-08 12:39:36 +01001221 V8EXPORT bool CanMakeExternal();
Steve Blocka7e24c12009-10-30 11:49:00 +00001222
1223 /** Creates an undetectable string from the supplied ascii or utf-8 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001224 V8EXPORT static Local<String> NewUndetectable(const char* data,
1225 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001226
1227 /** Creates an undetectable string from the supplied utf-16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001228 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1229 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001230
1231 /**
1232 * Converts an object to a utf8-encoded character array. Useful if
1233 * you want to print the object. If conversion to a string fails
1234 * (eg. due to an exception in the toString() method of the object)
1235 * then the length() method returns 0 and the * operator returns
1236 * NULL.
1237 */
1238 class V8EXPORT Utf8Value {
1239 public:
1240 explicit Utf8Value(Handle<v8::Value> obj);
1241 ~Utf8Value();
1242 char* operator*() { return str_; }
1243 const char* operator*() const { return str_; }
1244 int length() const { return length_; }
1245 private:
1246 char* str_;
1247 int length_;
1248
1249 // Disallow copying and assigning.
1250 Utf8Value(const Utf8Value&);
1251 void operator=(const Utf8Value&);
1252 };
1253
1254 /**
1255 * Converts an object to an ascii string.
1256 * Useful if you want to print the object.
1257 * If conversion to a string fails (eg. due to an exception in the toString()
1258 * method of the object) then the length() method returns 0 and the * operator
1259 * returns NULL.
1260 */
1261 class V8EXPORT AsciiValue {
1262 public:
1263 explicit AsciiValue(Handle<v8::Value> obj);
1264 ~AsciiValue();
1265 char* operator*() { return str_; }
1266 const char* operator*() const { return str_; }
1267 int length() const { return length_; }
1268 private:
1269 char* str_;
1270 int length_;
1271
1272 // Disallow copying and assigning.
1273 AsciiValue(const AsciiValue&);
1274 void operator=(const AsciiValue&);
1275 };
1276
1277 /**
1278 * Converts an object to a two-byte string.
1279 * If conversion to a string fails (eg. due to an exception in the toString()
1280 * method of the object) then the length() method returns 0 and the * operator
1281 * returns NULL.
1282 */
1283 class V8EXPORT Value {
1284 public:
1285 explicit Value(Handle<v8::Value> obj);
1286 ~Value();
1287 uint16_t* operator*() { return str_; }
1288 const uint16_t* operator*() const { return str_; }
1289 int length() const { return length_; }
1290 private:
1291 uint16_t* str_;
1292 int length_;
1293
1294 // Disallow copying and assigning.
1295 Value(const Value&);
1296 void operator=(const Value&);
1297 };
Steve Block3ce2e202009-11-05 08:53:23 +00001298
Steve Blocka7e24c12009-10-30 11:49:00 +00001299 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001300 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1301 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001302};
1303
1304
1305/**
1306 * A JavaScript number value (ECMA-262, 4.3.20)
1307 */
Steve Block8defd9f2010-07-08 12:39:36 +01001308class Number : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001309 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001310 V8EXPORT double Value() const;
1311 V8EXPORT static Local<Number> New(double value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001312 static inline Number* Cast(v8::Value* obj);
1313 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001314 V8EXPORT Number();
Steve Blocka7e24c12009-10-30 11:49:00 +00001315 static void CheckCast(v8::Value* obj);
1316};
1317
1318
1319/**
1320 * A JavaScript value representing a signed integer.
1321 */
Steve Block8defd9f2010-07-08 12:39:36 +01001322class Integer : public Number {
Steve Blocka7e24c12009-10-30 11:49:00 +00001323 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001324 V8EXPORT static Local<Integer> New(int32_t value);
1325 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1326 V8EXPORT int64_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001327 static inline Integer* Cast(v8::Value* obj);
1328 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001329 V8EXPORT Integer();
1330 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001331};
1332
1333
1334/**
1335 * A JavaScript value representing a 32-bit signed integer.
1336 */
Steve Block8defd9f2010-07-08 12:39:36 +01001337class Int32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001338 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001339 V8EXPORT int32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001340 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001341 V8EXPORT Int32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001342};
1343
1344
1345/**
1346 * A JavaScript value representing a 32-bit unsigned integer.
1347 */
Steve Block8defd9f2010-07-08 12:39:36 +01001348class Uint32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001349 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001350 V8EXPORT uint32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001351 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001352 V8EXPORT Uint32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001353};
1354
1355
1356/**
1357 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1358 */
Steve Block8defd9f2010-07-08 12:39:36 +01001359class Date : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001360 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001361 V8EXPORT static Local<Value> New(double time);
Steve Blocka7e24c12009-10-30 11:49:00 +00001362
1363 /**
1364 * A specialization of Value::NumberValue that is more efficient
1365 * because we know the structure of this object.
1366 */
Steve Block8defd9f2010-07-08 12:39:36 +01001367 V8EXPORT double NumberValue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001368
1369 static inline Date* Cast(v8::Value* obj);
1370 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001371 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001372};
1373
1374
Ben Murdochf87a2032010-10-22 12:50:53 +01001375/**
1376 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1377 */
1378class RegExp : public Value {
1379 public:
1380 /**
1381 * Regular expression flag bits. They can be or'ed to enable a set
1382 * of flags.
1383 */
1384 enum Flags {
1385 kNone = 0,
1386 kGlobal = 1,
1387 kIgnoreCase = 2,
1388 kMultiline = 4
1389 };
1390
1391 /**
1392 * Creates a regular expression from the given pattern string and
1393 * the flags bit field. May throw a JavaScript exception as
1394 * described in ECMA-262, 15.10.4.1.
1395 *
1396 * For example,
1397 * RegExp::New(v8::String::New("foo"),
1398 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1399 * is equivalent to evaluating "/foo/gm".
1400 */
1401 V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1402 Flags flags);
1403
1404 /**
1405 * Returns the value of the source property: a string representing
1406 * the regular expression.
1407 */
1408 V8EXPORT Local<String> GetSource() const;
1409
1410 /**
1411 * Returns the flags bit field.
1412 */
1413 V8EXPORT Flags GetFlags() const;
1414
1415 static inline RegExp* Cast(v8::Value* obj);
1416
1417 private:
1418 V8EXPORT static void CheckCast(v8::Value* obj);
1419};
1420
1421
Steve Blocka7e24c12009-10-30 11:49:00 +00001422enum PropertyAttribute {
1423 None = 0,
1424 ReadOnly = 1 << 0,
1425 DontEnum = 1 << 1,
1426 DontDelete = 1 << 2
1427};
1428
Steve Block3ce2e202009-11-05 08:53:23 +00001429enum ExternalArrayType {
1430 kExternalByteArray = 1,
1431 kExternalUnsignedByteArray,
1432 kExternalShortArray,
1433 kExternalUnsignedShortArray,
1434 kExternalIntArray,
1435 kExternalUnsignedIntArray,
1436 kExternalFloatArray
1437};
1438
Steve Blocka7e24c12009-10-30 11:49:00 +00001439/**
Leon Clarkef7060e22010-06-03 12:02:55 +01001440 * Accessor[Getter|Setter] are used as callback functions when
1441 * setting|getting a particular property. See Object and ObjectTemplate's
1442 * method SetAccessor.
1443 */
1444typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1445 const AccessorInfo& info);
1446
1447
1448typedef void (*AccessorSetter)(Local<String> property,
1449 Local<Value> value,
1450 const AccessorInfo& info);
1451
1452
1453/**
1454 * Access control specifications.
1455 *
1456 * Some accessors should be accessible across contexts. These
1457 * accessors have an explicit access control parameter which specifies
1458 * the kind of cross-context access that should be allowed.
1459 *
1460 * Additionally, for security, accessors can prohibit overwriting by
1461 * accessors defined in JavaScript. For objects that have such
1462 * accessors either locally or in their prototype chain it is not
1463 * possible to overwrite the accessor by using __defineGetter__ or
1464 * __defineSetter__ from JavaScript code.
1465 */
1466enum AccessControl {
1467 DEFAULT = 0,
1468 ALL_CAN_READ = 1,
1469 ALL_CAN_WRITE = 1 << 1,
1470 PROHIBITS_OVERWRITING = 1 << 2
1471};
1472
1473
1474/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001475 * A JavaScript object (ECMA-262, 4.3.3)
1476 */
Steve Block8defd9f2010-07-08 12:39:36 +01001477class Object : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001478 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001479 V8EXPORT bool Set(Handle<Value> key,
1480 Handle<Value> value,
1481 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001482
Steve Block8defd9f2010-07-08 12:39:36 +01001483 V8EXPORT bool Set(uint32_t index,
1484 Handle<Value> value);
Steve Block6ded16b2010-05-10 14:33:55 +01001485
Steve Blocka7e24c12009-10-30 11:49:00 +00001486 // Sets a local property on this object bypassing interceptors and
1487 // overriding accessors or read-only properties.
1488 //
1489 // Note that if the object has an interceptor the property will be set
1490 // locally, but since the interceptor takes precedence the local property
1491 // will only be returned if the interceptor doesn't return a value.
1492 //
1493 // Note also that this only works for named properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001494 V8EXPORT bool ForceSet(Handle<Value> key,
1495 Handle<Value> value,
1496 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001497
Steve Block8defd9f2010-07-08 12:39:36 +01001498 V8EXPORT Local<Value> Get(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001499
Steve Block8defd9f2010-07-08 12:39:36 +01001500 V8EXPORT Local<Value> Get(uint32_t index);
Steve Block6ded16b2010-05-10 14:33:55 +01001501
Steve Blocka7e24c12009-10-30 11:49:00 +00001502 // TODO(1245389): Replace the type-specific versions of these
1503 // functions with generic ones that accept a Handle<Value> key.
Steve Block8defd9f2010-07-08 12:39:36 +01001504 V8EXPORT bool Has(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001505
Steve Block8defd9f2010-07-08 12:39:36 +01001506 V8EXPORT bool Delete(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001507
1508 // Delete a property on this object bypassing interceptors and
1509 // ignoring dont-delete attributes.
Steve Block8defd9f2010-07-08 12:39:36 +01001510 V8EXPORT bool ForceDelete(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001511
Steve Block8defd9f2010-07-08 12:39:36 +01001512 V8EXPORT bool Has(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001513
Steve Block8defd9f2010-07-08 12:39:36 +01001514 V8EXPORT bool Delete(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001515
Steve Block8defd9f2010-07-08 12:39:36 +01001516 V8EXPORT bool SetAccessor(Handle<String> name,
1517 AccessorGetter getter,
1518 AccessorSetter setter = 0,
1519 Handle<Value> data = Handle<Value>(),
1520 AccessControl settings = DEFAULT,
1521 PropertyAttribute attribute = None);
Leon Clarkef7060e22010-06-03 12:02:55 +01001522
Steve Blocka7e24c12009-10-30 11:49:00 +00001523 /**
1524 * Returns an array containing the names of the enumerable properties
1525 * of this object, including properties from prototype objects. The
1526 * array returned by this method contains the same values as would
1527 * be enumerated by a for-in statement over this object.
1528 */
Steve Block8defd9f2010-07-08 12:39:36 +01001529 V8EXPORT Local<Array> GetPropertyNames();
Steve Blocka7e24c12009-10-30 11:49:00 +00001530
1531 /**
1532 * Get the prototype object. This does not skip objects marked to
1533 * be skipped by __proto__ and it does not consult the security
1534 * handler.
1535 */
Steve Block8defd9f2010-07-08 12:39:36 +01001536 V8EXPORT Local<Value> GetPrototype();
Steve Blocka7e24c12009-10-30 11:49:00 +00001537
1538 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001539 * Set the prototype object. This does not skip objects marked to
1540 * be skipped by __proto__ and it does not consult the security
1541 * handler.
1542 */
Steve Block8defd9f2010-07-08 12:39:36 +01001543 V8EXPORT bool SetPrototype(Handle<Value> prototype);
Andrei Popescu402d9372010-02-26 13:31:12 +00001544
1545 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001546 * Finds an instance of the given function template in the prototype
1547 * chain.
1548 */
Steve Block8defd9f2010-07-08 12:39:36 +01001549 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1550 Handle<FunctionTemplate> tmpl);
Steve Blocka7e24c12009-10-30 11:49:00 +00001551
1552 /**
1553 * Call builtin Object.prototype.toString on this object.
1554 * This is different from Value::ToString() that may call
1555 * user-defined toString function. This one does not.
1556 */
Steve Block8defd9f2010-07-08 12:39:36 +01001557 V8EXPORT Local<String> ObjectProtoToString();
Steve Blocka7e24c12009-10-30 11:49:00 +00001558
1559 /** Gets the number of internal fields for this Object. */
Steve Block8defd9f2010-07-08 12:39:36 +01001560 V8EXPORT int InternalFieldCount();
Steve Blocka7e24c12009-10-30 11:49:00 +00001561 /** Gets the value in an internal field. */
1562 inline Local<Value> GetInternalField(int index);
1563 /** Sets the value in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001564 V8EXPORT void SetInternalField(int index, Handle<Value> value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001565
1566 /** Gets a native pointer from an internal field. */
1567 inline void* GetPointerFromInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001568
Steve Blocka7e24c12009-10-30 11:49:00 +00001569 /** Sets a native pointer in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001570 V8EXPORT void SetPointerInInternalField(int index, void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001571
1572 // Testers for local properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001573 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1574 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1575 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001576
1577 /**
1578 * If result.IsEmpty() no real property was located in the prototype chain.
1579 * This means interceptors in the prototype chain are not called.
1580 */
Steve Block8defd9f2010-07-08 12:39:36 +01001581 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1582 Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001583
1584 /**
1585 * If result.IsEmpty() no real property was located on the object or
1586 * in the prototype chain.
1587 * This means interceptors in the prototype chain are not called.
1588 */
Steve Block8defd9f2010-07-08 12:39:36 +01001589 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001590
1591 /** Tests for a named lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001592 V8EXPORT bool HasNamedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001593
1594 /** Tests for an index lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001595 V8EXPORT bool HasIndexedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001596
1597 /**
1598 * Turns on access check on the object if the object is an instance of
1599 * a template that has access check callbacks. If an object has no
1600 * access check info, the object cannot be accessed by anyone.
1601 */
Steve Block8defd9f2010-07-08 12:39:36 +01001602 V8EXPORT void TurnOnAccessCheck();
Steve Blocka7e24c12009-10-30 11:49:00 +00001603
1604 /**
1605 * Returns the identity hash for this object. The current implemenation uses
1606 * a hidden property on the object to store the identity hash.
1607 *
1608 * The return value will never be 0. Also, it is not guaranteed to be
1609 * unique.
1610 */
Steve Block8defd9f2010-07-08 12:39:36 +01001611 V8EXPORT int GetIdentityHash();
Steve Blocka7e24c12009-10-30 11:49:00 +00001612
1613 /**
1614 * Access hidden properties on JavaScript objects. These properties are
1615 * hidden from the executing JavaScript and only accessible through the V8
1616 * C++ API. Hidden properties introduced by V8 internally (for example the
1617 * identity hash) are prefixed with "v8::".
1618 */
Steve Block8defd9f2010-07-08 12:39:36 +01001619 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1620 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1621 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
Steve Block3ce2e202009-11-05 08:53:23 +00001622
Steve Blocka7e24c12009-10-30 11:49:00 +00001623 /**
1624 * Returns true if this is an instance of an api function (one
1625 * created from a function created from a function template) and has
1626 * been modified since it was created. Note that this method is
1627 * conservative and may return true for objects that haven't actually
1628 * been modified.
1629 */
Steve Block8defd9f2010-07-08 12:39:36 +01001630 V8EXPORT bool IsDirty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001631
1632 /**
1633 * Clone this object with a fast but shallow copy. Values will point
1634 * to the same values as the original object.
1635 */
Steve Block8defd9f2010-07-08 12:39:36 +01001636 V8EXPORT Local<Object> Clone();
Steve Blocka7e24c12009-10-30 11:49:00 +00001637
1638 /**
1639 * Set the backing store of the indexed properties to be managed by the
1640 * embedding layer. Access to the indexed properties will follow the rules
1641 * spelled out in CanvasPixelArray.
1642 * Note: The embedding program still owns the data and needs to ensure that
1643 * the backing store is preserved while V8 has a reference.
1644 */
Steve Block8defd9f2010-07-08 12:39:36 +01001645 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001646 bool HasIndexedPropertiesInPixelData();
1647 uint8_t* GetIndexedPropertiesPixelData();
1648 int GetIndexedPropertiesPixelDataLength();
Steve Blocka7e24c12009-10-30 11:49:00 +00001649
Steve Block3ce2e202009-11-05 08:53:23 +00001650 /**
1651 * Set the backing store of the indexed properties to be managed by the
1652 * embedding layer. Access to the indexed properties will follow the rules
1653 * spelled out for the CanvasArray subtypes in the WebGL specification.
1654 * Note: The embedding program still owns the data and needs to ensure that
1655 * the backing store is preserved while V8 has a reference.
1656 */
Steve Block8defd9f2010-07-08 12:39:36 +01001657 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1658 void* data,
1659 ExternalArrayType array_type,
1660 int number_of_elements);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001661 bool HasIndexedPropertiesInExternalArrayData();
1662 void* GetIndexedPropertiesExternalArrayData();
1663 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1664 int GetIndexedPropertiesExternalArrayDataLength();
Steve Block3ce2e202009-11-05 08:53:23 +00001665
Steve Block8defd9f2010-07-08 12:39:36 +01001666 V8EXPORT static Local<Object> New();
Steve Blocka7e24c12009-10-30 11:49:00 +00001667 static inline Object* Cast(Value* obj);
1668 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001669 V8EXPORT Object();
1670 V8EXPORT static void CheckCast(Value* obj);
1671 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1672 V8EXPORT void* SlowGetPointerFromInternalField(int index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001673
1674 /**
1675 * If quick access to the internal field is possible this method
Steve Block3ce2e202009-11-05 08:53:23 +00001676 * returns the value. Otherwise an empty handle is returned.
Steve Blocka7e24c12009-10-30 11:49:00 +00001677 */
1678 inline Local<Value> UncheckedGetInternalField(int index);
1679};
1680
1681
1682/**
1683 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1684 */
Steve Block8defd9f2010-07-08 12:39:36 +01001685class Array : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001686 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001687 V8EXPORT uint32_t Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001688
1689 /**
1690 * Clones an element at index |index|. Returns an empty
1691 * handle if cloning fails (for any reason).
1692 */
Steve Block8defd9f2010-07-08 12:39:36 +01001693 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001694
Steve Block8defd9f2010-07-08 12:39:36 +01001695 V8EXPORT static Local<Array> New(int length = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001696 static inline Array* Cast(Value* obj);
1697 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001698 V8EXPORT Array();
Steve Blocka7e24c12009-10-30 11:49:00 +00001699 static void CheckCast(Value* obj);
1700};
1701
1702
1703/**
1704 * A JavaScript function object (ECMA-262, 15.3).
1705 */
Steve Block8defd9f2010-07-08 12:39:36 +01001706class Function : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001707 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001708 V8EXPORT Local<Object> NewInstance() const;
1709 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1710 V8EXPORT Local<Value> Call(Handle<Object> recv,
1711 int argc,
1712 Handle<Value> argv[]);
1713 V8EXPORT void SetName(Handle<String> name);
1714 V8EXPORT Handle<Value> GetName() const;
Andrei Popescu402d9372010-02-26 13:31:12 +00001715
1716 /**
1717 * Returns zero based line number of function body and
1718 * kLineOffsetNotFound if no information available.
1719 */
Steve Block8defd9f2010-07-08 12:39:36 +01001720 V8EXPORT int GetScriptLineNumber() const;
1721 V8EXPORT ScriptOrigin GetScriptOrigin() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001722 static inline Function* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001723 V8EXPORT static const int kLineOffsetNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00001724 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001725 V8EXPORT Function();
1726 V8EXPORT static void CheckCast(Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001727};
1728
1729
1730/**
1731 * A JavaScript value that wraps a C++ void*. This type of value is
1732 * mainly used to associate C++ data structures with JavaScript
1733 * objects.
1734 *
1735 * The Wrap function V8 will return the most optimal Value object wrapping the
1736 * C++ void*. The type of the value is not guaranteed to be an External object
1737 * and no assumptions about its type should be made. To access the wrapped
1738 * value Unwrap should be used, all other operations on that object will lead
1739 * to unpredictable results.
1740 */
Steve Block8defd9f2010-07-08 12:39:36 +01001741class External : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001742 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001743 V8EXPORT static Local<Value> Wrap(void* data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001744 static inline void* Unwrap(Handle<Value> obj);
1745
Steve Block8defd9f2010-07-08 12:39:36 +01001746 V8EXPORT static Local<External> New(void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001747 static inline External* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001748 V8EXPORT void* Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001749 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001750 V8EXPORT External();
1751 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001752 static inline void* QuickUnwrap(Handle<v8::Value> obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001753 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001754};
1755
1756
1757// --- T e m p l a t e s ---
1758
1759
1760/**
1761 * The superclass of object and function templates.
1762 */
1763class V8EXPORT Template : public Data {
1764 public:
1765 /** Adds a property to each instance created by this template.*/
1766 void Set(Handle<String> name, Handle<Data> value,
1767 PropertyAttribute attributes = None);
1768 inline void Set(const char* name, Handle<Data> value);
1769 private:
1770 Template();
1771
1772 friend class ObjectTemplate;
1773 friend class FunctionTemplate;
1774};
1775
1776
1777/**
1778 * The argument information given to function call callbacks. This
1779 * class provides access to information about the context of the call,
1780 * including the receiver, the number and values of arguments, and
1781 * the holder of the function.
1782 */
Steve Block8defd9f2010-07-08 12:39:36 +01001783class Arguments {
Steve Blocka7e24c12009-10-30 11:49:00 +00001784 public:
1785 inline int Length() const;
1786 inline Local<Value> operator[](int i) const;
1787 inline Local<Function> Callee() const;
1788 inline Local<Object> This() const;
1789 inline Local<Object> Holder() const;
1790 inline bool IsConstructCall() const;
1791 inline Local<Value> Data() const;
1792 private:
Steve Blocka7e24c12009-10-30 11:49:00 +00001793 friend class ImplementationUtilities;
1794 inline Arguments(Local<Value> data,
1795 Local<Object> holder,
1796 Local<Function> callee,
1797 bool is_construct_call,
1798 void** values, int length);
1799 Local<Value> data_;
1800 Local<Object> holder_;
1801 Local<Function> callee_;
1802 bool is_construct_call_;
1803 void** values_;
1804 int length_;
1805};
1806
1807
1808/**
1809 * The information passed to an accessor callback about the context
1810 * of the property access.
1811 */
1812class V8EXPORT AccessorInfo {
1813 public:
1814 inline AccessorInfo(internal::Object** args)
1815 : args_(args) { }
1816 inline Local<Value> Data() const;
1817 inline Local<Object> This() const;
1818 inline Local<Object> Holder() const;
1819 private:
1820 internal::Object** args_;
1821};
1822
1823
1824typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1825
Steve Blocka7e24c12009-10-30 11:49:00 +00001826/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001827 * NamedProperty[Getter|Setter] are used as interceptors on object.
1828 * See ObjectTemplate::SetNamedPropertyHandler.
1829 */
1830typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
1831 const AccessorInfo& info);
1832
1833
1834/**
1835 * Returns the value if the setter intercepts the request.
1836 * Otherwise, returns an empty handle.
1837 */
1838typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
1839 Local<Value> value,
1840 const AccessorInfo& info);
1841
Steve Blocka7e24c12009-10-30 11:49:00 +00001842/**
1843 * Returns a non-empty handle if the interceptor intercepts the request.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001844 * The result is an integer encoding property attributes (like v8::None,
1845 * v8::DontEnum, etc.)
Steve Blocka7e24c12009-10-30 11:49:00 +00001846 */
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001847typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
1848 const AccessorInfo& info);
Steve Blocka7e24c12009-10-30 11:49:00 +00001849
1850
1851/**
1852 * Returns a non-empty handle if the deleter intercepts the request.
1853 * The return value is true if the property could be deleted and false
1854 * otherwise.
1855 */
1856typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
1857 const AccessorInfo& info);
1858
1859/**
1860 * Returns an array containing the names of the properties the named
1861 * property getter intercepts.
1862 */
1863typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
1864
1865
1866/**
1867 * Returns the value of the property if the getter intercepts the
1868 * request. Otherwise, returns an empty handle.
1869 */
1870typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
1871 const AccessorInfo& info);
1872
1873
1874/**
1875 * Returns the value if the setter intercepts the request.
1876 * Otherwise, returns an empty handle.
1877 */
1878typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
1879 Local<Value> value,
1880 const AccessorInfo& info);
1881
1882
1883/**
1884 * Returns a non-empty handle if the interceptor intercepts the request.
Iain Merrick75681382010-08-19 15:07:18 +01001885 * The result is an integer encoding property attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00001886 */
Iain Merrick75681382010-08-19 15:07:18 +01001887typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
Steve Blocka7e24c12009-10-30 11:49:00 +00001888 const AccessorInfo& info);
1889
1890/**
1891 * Returns a non-empty handle if the deleter intercepts the request.
1892 * The return value is true if the property could be deleted and false
1893 * otherwise.
1894 */
1895typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
1896 const AccessorInfo& info);
1897
1898/**
1899 * Returns an array containing the indices of the properties the
1900 * indexed property getter intercepts.
1901 */
1902typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
1903
1904
1905/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001906 * Access type specification.
1907 */
1908enum AccessType {
1909 ACCESS_GET,
1910 ACCESS_SET,
1911 ACCESS_HAS,
1912 ACCESS_DELETE,
1913 ACCESS_KEYS
1914};
1915
1916
1917/**
1918 * Returns true if cross-context access should be allowed to the named
1919 * property with the given key on the host object.
1920 */
1921typedef bool (*NamedSecurityCallback)(Local<Object> host,
1922 Local<Value> key,
1923 AccessType type,
1924 Local<Value> data);
1925
1926
1927/**
1928 * Returns true if cross-context access should be allowed to the indexed
1929 * property with the given index on the host object.
1930 */
1931typedef bool (*IndexedSecurityCallback)(Local<Object> host,
1932 uint32_t index,
1933 AccessType type,
1934 Local<Value> data);
1935
1936
1937/**
1938 * A FunctionTemplate is used to create functions at runtime. There
1939 * can only be one function created from a FunctionTemplate in a
1940 * context. The lifetime of the created function is equal to the
1941 * lifetime of the context. So in case the embedder needs to create
1942 * temporary functions that can be collected using Scripts is
1943 * preferred.
1944 *
1945 * A FunctionTemplate can have properties, these properties are added to the
1946 * function object when it is created.
1947 *
1948 * A FunctionTemplate has a corresponding instance template which is
1949 * used to create object instances when the function is used as a
1950 * constructor. Properties added to the instance template are added to
1951 * each object instance.
1952 *
1953 * A FunctionTemplate can have a prototype template. The prototype template
1954 * is used to create the prototype object of the function.
1955 *
1956 * The following example shows how to use a FunctionTemplate:
1957 *
1958 * \code
1959 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
1960 * t->Set("func_property", v8::Number::New(1));
1961 *
1962 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
1963 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
1964 * proto_t->Set("proto_const", v8::Number::New(2));
1965 *
1966 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
1967 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
1968 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
1969 * instance_t->Set("instance_property", Number::New(3));
1970 *
1971 * v8::Local<v8::Function> function = t->GetFunction();
1972 * v8::Local<v8::Object> instance = function->NewInstance();
1973 * \endcode
1974 *
1975 * Let's use "function" as the JS variable name of the function object
1976 * and "instance" for the instance object created above. The function
1977 * and the instance will have the following properties:
1978 *
1979 * \code
1980 * func_property in function == true;
1981 * function.func_property == 1;
1982 *
1983 * function.prototype.proto_method() invokes 'InvokeCallback'
1984 * function.prototype.proto_const == 2;
1985 *
1986 * instance instanceof function == true;
1987 * instance.instance_accessor calls 'InstanceAccessorCallback'
1988 * instance.instance_property == 3;
1989 * \endcode
1990 *
1991 * A FunctionTemplate can inherit from another one by calling the
1992 * FunctionTemplate::Inherit method. The following graph illustrates
1993 * the semantics of inheritance:
1994 *
1995 * \code
1996 * FunctionTemplate Parent -> Parent() . prototype -> { }
1997 * ^ ^
1998 * | Inherit(Parent) | .__proto__
1999 * | |
2000 * FunctionTemplate Child -> Child() . prototype -> { }
2001 * \endcode
2002 *
2003 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
2004 * object of the Child() function has __proto__ pointing to the
2005 * Parent() function's prototype object. An instance of the Child
2006 * function has all properties on Parent's instance templates.
2007 *
2008 * Let Parent be the FunctionTemplate initialized in the previous
2009 * section and create a Child FunctionTemplate by:
2010 *
2011 * \code
2012 * Local<FunctionTemplate> parent = t;
2013 * Local<FunctionTemplate> child = FunctionTemplate::New();
2014 * child->Inherit(parent);
2015 *
2016 * Local<Function> child_function = child->GetFunction();
2017 * Local<Object> child_instance = child_function->NewInstance();
2018 * \endcode
2019 *
2020 * The Child function and Child instance will have the following
2021 * properties:
2022 *
2023 * \code
2024 * child_func.prototype.__proto__ == function.prototype;
2025 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2026 * child_instance.instance_property == 3;
2027 * \endcode
2028 */
2029class V8EXPORT FunctionTemplate : public Template {
2030 public:
2031 /** Creates a function template.*/
2032 static Local<FunctionTemplate> New(
2033 InvocationCallback callback = 0,
2034 Handle<Value> data = Handle<Value>(),
2035 Handle<Signature> signature = Handle<Signature>());
2036 /** Returns the unique function instance in the current execution context.*/
2037 Local<Function> GetFunction();
2038
2039 /**
2040 * Set the call-handler callback for a FunctionTemplate. This
2041 * callback is called whenever the function created from this
2042 * FunctionTemplate is called.
2043 */
2044 void SetCallHandler(InvocationCallback callback,
2045 Handle<Value> data = Handle<Value>());
2046
2047 /** Get the InstanceTemplate. */
2048 Local<ObjectTemplate> InstanceTemplate();
2049
2050 /** Causes the function template to inherit from a parent function template.*/
2051 void Inherit(Handle<FunctionTemplate> parent);
2052
2053 /**
2054 * A PrototypeTemplate is the template used to create the prototype object
2055 * of the function created by this template.
2056 */
2057 Local<ObjectTemplate> PrototypeTemplate();
2058
2059
2060 /**
2061 * Set the class name of the FunctionTemplate. This is used for
2062 * printing objects created with the function created from the
2063 * FunctionTemplate as its constructor.
2064 */
2065 void SetClassName(Handle<String> name);
2066
2067 /**
2068 * Determines whether the __proto__ accessor ignores instances of
2069 * the function template. If instances of the function template are
2070 * ignored, __proto__ skips all instances and instead returns the
2071 * next object in the prototype chain.
2072 *
2073 * Call with a value of true to make the __proto__ accessor ignore
2074 * instances of the function template. Call with a value of false
2075 * to make the __proto__ accessor not ignore instances of the
2076 * function template. By default, instances of a function template
2077 * are not ignored.
2078 */
2079 void SetHiddenPrototype(bool value);
2080
2081 /**
2082 * Returns true if the given object is an instance of this function
2083 * template.
2084 */
2085 bool HasInstance(Handle<Value> object);
2086
2087 private:
2088 FunctionTemplate();
2089 void AddInstancePropertyAccessor(Handle<String> name,
2090 AccessorGetter getter,
2091 AccessorSetter setter,
2092 Handle<Value> data,
2093 AccessControl settings,
2094 PropertyAttribute attributes);
2095 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2096 NamedPropertySetter setter,
2097 NamedPropertyQuery query,
2098 NamedPropertyDeleter remover,
2099 NamedPropertyEnumerator enumerator,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002100 Handle<Value> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00002101 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2102 IndexedPropertySetter setter,
2103 IndexedPropertyQuery query,
2104 IndexedPropertyDeleter remover,
2105 IndexedPropertyEnumerator enumerator,
2106 Handle<Value> data);
2107 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2108 Handle<Value> data);
2109
2110 friend class Context;
2111 friend class ObjectTemplate;
2112};
2113
2114
2115/**
2116 * An ObjectTemplate is used to create objects at runtime.
2117 *
2118 * Properties added to an ObjectTemplate are added to each object
2119 * created from the ObjectTemplate.
2120 */
2121class V8EXPORT ObjectTemplate : public Template {
2122 public:
2123 /** Creates an ObjectTemplate. */
2124 static Local<ObjectTemplate> New();
2125
2126 /** Creates a new instance of this template.*/
2127 Local<Object> NewInstance();
2128
2129 /**
2130 * Sets an accessor on the object template.
2131 *
2132 * Whenever the property with the given name is accessed on objects
2133 * created from this ObjectTemplate the getter and setter callbacks
2134 * are called instead of getting and setting the property directly
2135 * on the JavaScript object.
2136 *
2137 * \param name The name of the property for which an accessor is added.
2138 * \param getter The callback to invoke when getting the property.
2139 * \param setter The callback to invoke when setting the property.
2140 * \param data A piece of data that will be passed to the getter and setter
2141 * callbacks whenever they are invoked.
2142 * \param settings Access control settings for the accessor. This is a bit
2143 * field consisting of one of more of
2144 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2145 * The default is to not allow cross-context access.
2146 * ALL_CAN_READ means that all cross-context reads are allowed.
2147 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2148 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2149 * cross-context access.
2150 * \param attribute The attributes of the property for which an accessor
2151 * is added.
2152 */
2153 void SetAccessor(Handle<String> name,
2154 AccessorGetter getter,
2155 AccessorSetter setter = 0,
2156 Handle<Value> data = Handle<Value>(),
2157 AccessControl settings = DEFAULT,
2158 PropertyAttribute attribute = None);
2159
2160 /**
2161 * Sets a named property handler on the object template.
2162 *
2163 * Whenever a named property is accessed on objects created from
2164 * this object template, the provided callback is invoked instead of
2165 * accessing the property directly on the JavaScript object.
2166 *
2167 * \param getter The callback to invoke when getting a property.
2168 * \param setter The callback to invoke when setting a property.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002169 * \param query The callback to invoke to check if a property is present,
2170 * and if present, get its attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00002171 * \param deleter The callback to invoke when deleting a property.
2172 * \param enumerator The callback to invoke to enumerate all the named
2173 * properties of an object.
2174 * \param data A piece of data that will be passed to the callbacks
2175 * whenever they are invoked.
2176 */
2177 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2178 NamedPropertySetter setter = 0,
2179 NamedPropertyQuery query = 0,
2180 NamedPropertyDeleter deleter = 0,
2181 NamedPropertyEnumerator enumerator = 0,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002182 Handle<Value> data = Handle<Value>());
Steve Blocka7e24c12009-10-30 11:49:00 +00002183
2184 /**
2185 * Sets an indexed property handler on the object template.
2186 *
2187 * Whenever an indexed property is accessed on objects created from
2188 * this object template, the provided callback is invoked instead of
2189 * accessing the property directly on the JavaScript object.
2190 *
2191 * \param getter The callback to invoke when getting a property.
2192 * \param setter The callback to invoke when setting a property.
2193 * \param query The callback to invoke to check is an object has a property.
2194 * \param deleter The callback to invoke when deleting a property.
2195 * \param enumerator The callback to invoke to enumerate all the indexed
2196 * properties of an object.
2197 * \param data A piece of data that will be passed to the callbacks
2198 * whenever they are invoked.
2199 */
2200 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2201 IndexedPropertySetter setter = 0,
2202 IndexedPropertyQuery query = 0,
2203 IndexedPropertyDeleter deleter = 0,
2204 IndexedPropertyEnumerator enumerator = 0,
2205 Handle<Value> data = Handle<Value>());
Iain Merrick75681382010-08-19 15:07:18 +01002206
Steve Blocka7e24c12009-10-30 11:49:00 +00002207 /**
2208 * Sets the callback to be used when calling instances created from
2209 * this template as a function. If no callback is set, instances
2210 * behave like normal JavaScript objects that cannot be called as a
2211 * function.
2212 */
2213 void SetCallAsFunctionHandler(InvocationCallback callback,
2214 Handle<Value> data = Handle<Value>());
2215
2216 /**
2217 * Mark object instances of the template as undetectable.
2218 *
2219 * In many ways, undetectable objects behave as though they are not
2220 * there. They behave like 'undefined' in conditionals and when
2221 * printed. However, properties can be accessed and called as on
2222 * normal objects.
2223 */
2224 void MarkAsUndetectable();
2225
2226 /**
2227 * Sets access check callbacks on the object template.
2228 *
2229 * When accessing properties on instances of this object template,
2230 * the access check callback will be called to determine whether or
2231 * not to allow cross-context access to the properties.
2232 * The last parameter specifies whether access checks are turned
2233 * on by default on instances. If access checks are off by default,
2234 * they can be turned on on individual instances by calling
2235 * Object::TurnOnAccessCheck().
2236 */
2237 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2238 IndexedSecurityCallback indexed_handler,
2239 Handle<Value> data = Handle<Value>(),
2240 bool turned_on_by_default = true);
2241
2242 /**
2243 * Gets the number of internal fields for objects generated from
2244 * this template.
2245 */
2246 int InternalFieldCount();
2247
2248 /**
2249 * Sets the number of internal fields for objects generated from
2250 * this template.
2251 */
2252 void SetInternalFieldCount(int value);
2253
2254 private:
2255 ObjectTemplate();
2256 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2257 friend class FunctionTemplate;
2258};
2259
2260
2261/**
2262 * A Signature specifies which receivers and arguments a function can
2263 * legally be called with.
2264 */
2265class V8EXPORT Signature : public Data {
2266 public:
2267 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2268 Handle<FunctionTemplate>(),
2269 int argc = 0,
2270 Handle<FunctionTemplate> argv[] = 0);
2271 private:
2272 Signature();
2273};
2274
2275
2276/**
2277 * A utility for determining the type of objects based on the template
2278 * they were constructed from.
2279 */
2280class V8EXPORT TypeSwitch : public Data {
2281 public:
2282 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2283 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2284 int match(Handle<Value> value);
2285 private:
2286 TypeSwitch();
2287};
2288
2289
2290// --- E x t e n s i o n s ---
2291
2292
2293/**
2294 * Ignore
2295 */
2296class V8EXPORT Extension { // NOLINT
2297 public:
2298 Extension(const char* name,
2299 const char* source = 0,
2300 int dep_count = 0,
2301 const char** deps = 0);
2302 virtual ~Extension() { }
2303 virtual v8::Handle<v8::FunctionTemplate>
2304 GetNativeFunction(v8::Handle<v8::String> name) {
2305 return v8::Handle<v8::FunctionTemplate>();
2306 }
2307
2308 const char* name() { return name_; }
2309 const char* source() { return source_; }
2310 int dependency_count() { return dep_count_; }
2311 const char** dependencies() { return deps_; }
2312 void set_auto_enable(bool value) { auto_enable_ = value; }
2313 bool auto_enable() { return auto_enable_; }
2314
2315 private:
2316 const char* name_;
2317 const char* source_;
2318 int dep_count_;
2319 const char** deps_;
2320 bool auto_enable_;
2321
2322 // Disallow copying and assigning.
2323 Extension(const Extension&);
2324 void operator=(const Extension&);
2325};
2326
2327
2328void V8EXPORT RegisterExtension(Extension* extension);
2329
2330
2331/**
2332 * Ignore
2333 */
2334class V8EXPORT DeclareExtension {
2335 public:
2336 inline DeclareExtension(Extension* extension) {
2337 RegisterExtension(extension);
2338 }
2339};
2340
2341
2342// --- S t a t i c s ---
2343
2344
2345Handle<Primitive> V8EXPORT Undefined();
2346Handle<Primitive> V8EXPORT Null();
2347Handle<Boolean> V8EXPORT True();
2348Handle<Boolean> V8EXPORT False();
2349
2350
2351/**
2352 * A set of constraints that specifies the limits of the runtime's memory use.
2353 * You must set the heap size before initializing the VM - the size cannot be
2354 * adjusted after the VM is initialized.
2355 *
2356 * If you are using threads then you should hold the V8::Locker lock while
2357 * setting the stack limit and you must set a non-default stack limit separately
2358 * for each thread.
2359 */
2360class V8EXPORT ResourceConstraints {
2361 public:
2362 ResourceConstraints();
2363 int max_young_space_size() const { return max_young_space_size_; }
2364 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2365 int max_old_space_size() const { return max_old_space_size_; }
2366 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
2367 uint32_t* stack_limit() const { return stack_limit_; }
2368 // Sets an address beyond which the VM's stack may not grow.
2369 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2370 private:
2371 int max_young_space_size_;
2372 int max_old_space_size_;
2373 uint32_t* stack_limit_;
2374};
2375
2376
Kristian Monsen25f61362010-05-21 11:50:48 +01002377bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
Steve Blocka7e24c12009-10-30 11:49:00 +00002378
2379
2380// --- E x c e p t i o n s ---
2381
2382
2383typedef void (*FatalErrorCallback)(const char* location, const char* message);
2384
2385
2386typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2387
2388
2389/**
2390 * Schedules an exception to be thrown when returning to JavaScript. When an
2391 * exception has been scheduled it is illegal to invoke any JavaScript
2392 * operation; the caller must return immediately and only after the exception
2393 * has been handled does it become legal to invoke JavaScript operations.
2394 */
2395Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2396
2397/**
2398 * Create new error objects by calling the corresponding error object
2399 * constructor with the message.
2400 */
2401class V8EXPORT Exception {
2402 public:
2403 static Local<Value> RangeError(Handle<String> message);
2404 static Local<Value> ReferenceError(Handle<String> message);
2405 static Local<Value> SyntaxError(Handle<String> message);
2406 static Local<Value> TypeError(Handle<String> message);
2407 static Local<Value> Error(Handle<String> message);
2408};
2409
2410
2411// --- C o u n t e r s C a l l b a c k s ---
2412
2413typedef int* (*CounterLookupCallback)(const char* name);
2414
2415typedef void* (*CreateHistogramCallback)(const char* name,
2416 int min,
2417 int max,
2418 size_t buckets);
2419
2420typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2421
Iain Merrick9ac36c92010-09-13 15:29:50 +01002422// --- M e m o r y A l l o c a t i o n C a l l b a c k ---
2423 enum ObjectSpace {
2424 kObjectSpaceNewSpace = 1 << 0,
2425 kObjectSpaceOldPointerSpace = 1 << 1,
2426 kObjectSpaceOldDataSpace = 1 << 2,
2427 kObjectSpaceCodeSpace = 1 << 3,
2428 kObjectSpaceMapSpace = 1 << 4,
2429 kObjectSpaceLoSpace = 1 << 5,
2430
2431 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2432 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2433 kObjectSpaceLoSpace
2434 };
2435
2436 enum AllocationAction {
2437 kAllocationActionAllocate = 1 << 0,
2438 kAllocationActionFree = 1 << 1,
2439 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2440 };
2441
2442typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2443 AllocationAction action,
2444 int size);
2445
Steve Blocka7e24c12009-10-30 11:49:00 +00002446// --- 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 ---
2447typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2448 AccessType type,
2449 Local<Value> data);
2450
2451// --- 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
2452
2453/**
Steve Block6ded16b2010-05-10 14:33:55 +01002454 * Applications can register callback functions which will be called
2455 * before and after a garbage collection. Allocations are not
2456 * allowed in the callback functions, you therefore cannot manipulate
Steve Blocka7e24c12009-10-30 11:49:00 +00002457 * objects (set or delete properties for example) since it is possible
2458 * such operations will result in the allocation of objects.
2459 */
Steve Block6ded16b2010-05-10 14:33:55 +01002460enum GCType {
2461 kGCTypeScavenge = 1 << 0,
2462 kGCTypeMarkSweepCompact = 1 << 1,
2463 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2464};
2465
2466enum GCCallbackFlags {
2467 kNoGCCallbackFlags = 0,
2468 kGCCallbackFlagCompacted = 1 << 0
2469};
2470
2471typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2472typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2473
Steve Blocka7e24c12009-10-30 11:49:00 +00002474typedef void (*GCCallback)();
2475
2476
Steve Blocka7e24c12009-10-30 11:49:00 +00002477/**
2478 * Profiler modules.
2479 *
2480 * In V8, profiler consists of several modules: CPU profiler, and different
2481 * kinds of heap profiling. Each can be turned on / off independently.
2482 * When PROFILER_MODULE_HEAP_SNAPSHOT flag is passed to ResumeProfilerEx,
2483 * modules are enabled only temporarily for making a snapshot of the heap.
2484 */
2485enum ProfilerModules {
2486 PROFILER_MODULE_NONE = 0,
2487 PROFILER_MODULE_CPU = 1,
2488 PROFILER_MODULE_HEAP_STATS = 1 << 1,
2489 PROFILER_MODULE_JS_CONSTRUCTORS = 1 << 2,
2490 PROFILER_MODULE_HEAP_SNAPSHOT = 1 << 16
2491};
2492
2493
2494/**
Steve Block3ce2e202009-11-05 08:53:23 +00002495 * Collection of V8 heap information.
2496 *
2497 * Instances of this class can be passed to v8::V8::HeapStatistics to
2498 * get heap statistics from V8.
2499 */
2500class V8EXPORT HeapStatistics {
2501 public:
2502 HeapStatistics();
2503 size_t total_heap_size() { return total_heap_size_; }
2504 size_t used_heap_size() { return used_heap_size_; }
2505
2506 private:
2507 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
2508 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2509
2510 size_t total_heap_size_;
2511 size_t used_heap_size_;
2512
2513 friend class V8;
2514};
2515
2516
2517/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002518 * Container class for static utility functions.
2519 */
2520class V8EXPORT V8 {
2521 public:
2522 /** Set the callback to invoke in case of fatal errors. */
2523 static void SetFatalErrorHandler(FatalErrorCallback that);
2524
2525 /**
2526 * Ignore out-of-memory exceptions.
2527 *
2528 * V8 running out of memory is treated as a fatal error by default.
2529 * This means that the fatal error handler is called and that V8 is
2530 * terminated.
2531 *
2532 * IgnoreOutOfMemoryException can be used to not treat a
2533 * out-of-memory situation as a fatal error. This way, the contexts
2534 * that did not cause the out of memory problem might be able to
2535 * continue execution.
2536 */
2537 static void IgnoreOutOfMemoryException();
2538
2539 /**
2540 * Check if V8 is dead and therefore unusable. This is the case after
2541 * fatal errors such as out-of-memory situations.
2542 */
2543 static bool IsDead();
2544
2545 /**
2546 * Adds a message listener.
2547 *
2548 * The same message listener can be added more than once and it that
2549 * case it will be called more than once for each message.
2550 */
2551 static bool AddMessageListener(MessageCallback that,
2552 Handle<Value> data = Handle<Value>());
2553
2554 /**
2555 * Remove all message listeners from the specified callback function.
2556 */
2557 static void RemoveMessageListeners(MessageCallback that);
2558
2559 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002560 * Tells V8 to capture current stack trace when uncaught exception occurs
2561 * and report it to the message listeners. The option is off by default.
2562 */
2563 static void SetCaptureStackTraceForUncaughtExceptions(
2564 bool capture,
2565 int frame_limit = 10,
2566 StackTrace::StackTraceOptions options = StackTrace::kOverview);
2567
2568 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002569 * Sets V8 flags from a string.
2570 */
2571 static void SetFlagsFromString(const char* str, int length);
2572
2573 /**
2574 * Sets V8 flags from the command line.
2575 */
2576 static void SetFlagsFromCommandLine(int* argc,
2577 char** argv,
2578 bool remove_flags);
2579
2580 /** Get the version string. */
2581 static const char* GetVersion();
2582
2583 /**
2584 * Enables the host application to provide a mechanism for recording
2585 * statistics counters.
2586 */
2587 static void SetCounterFunction(CounterLookupCallback);
2588
2589 /**
2590 * Enables the host application to provide a mechanism for recording
2591 * histograms. The CreateHistogram function returns a
2592 * histogram which will later be passed to the AddHistogramSample
2593 * function.
2594 */
2595 static void SetCreateHistogramFunction(CreateHistogramCallback);
2596 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2597
2598 /**
2599 * Enables the computation of a sliding window of states. The sliding
2600 * window information is recorded in statistics counters.
2601 */
2602 static void EnableSlidingStateWindow();
2603
2604 /** Callback function for reporting failed access checks.*/
2605 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2606
2607 /**
2608 * Enables the host application to receive a notification before a
Steve Block6ded16b2010-05-10 14:33:55 +01002609 * garbage collection. Allocations are not allowed in the
2610 * callback function, you therefore cannot manipulate objects (set
2611 * or delete properties for example) since it is possible such
2612 * operations will result in the allocation of objects. It is possible
2613 * to specify the GCType filter for your callback. But it is not possible to
2614 * register the same callback function two times with different
2615 * GCType filters.
2616 */
2617 static void AddGCPrologueCallback(
2618 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
2619
2620 /**
2621 * This function removes callback which was installed by
2622 * AddGCPrologueCallback function.
2623 */
2624 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
2625
2626 /**
2627 * The function is deprecated. Please use AddGCPrologueCallback instead.
2628 * Enables the host application to receive a notification before a
2629 * garbage collection. Allocations are not allowed in the
Steve Blocka7e24c12009-10-30 11:49:00 +00002630 * callback function, you therefore cannot manipulate objects (set
2631 * or delete properties for example) since it is possible such
2632 * operations will result in the allocation of objects.
2633 */
2634 static void SetGlobalGCPrologueCallback(GCCallback);
2635
2636 /**
2637 * Enables the host application to receive a notification after a
Steve Block6ded16b2010-05-10 14:33:55 +01002638 * garbage collection. Allocations are not allowed in the
2639 * callback function, you therefore cannot manipulate objects (set
2640 * or delete properties for example) since it is possible such
2641 * operations will result in the allocation of objects. It is possible
2642 * to specify the GCType filter for your callback. But it is not possible to
2643 * register the same callback function two times with different
2644 * GCType filters.
2645 */
2646 static void AddGCEpilogueCallback(
2647 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
2648
2649 /**
2650 * This function removes callback which was installed by
2651 * AddGCEpilogueCallback function.
2652 */
2653 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
2654
2655 /**
2656 * The function is deprecated. Please use AddGCEpilogueCallback instead.
2657 * Enables the host application to receive a notification after a
Steve Blocka7e24c12009-10-30 11:49:00 +00002658 * major garbage collection. Allocations are not allowed in the
2659 * callback function, you therefore cannot manipulate objects (set
2660 * or delete properties for example) since it is possible such
2661 * operations will result in the allocation of objects.
2662 */
2663 static void SetGlobalGCEpilogueCallback(GCCallback);
2664
2665 /**
Iain Merrick9ac36c92010-09-13 15:29:50 +01002666 * Enables the host application to provide a mechanism to be notified
2667 * and perform custom logging when V8 Allocates Executable Memory.
2668 */
2669 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
2670 ObjectSpace space,
2671 AllocationAction action);
2672
2673 /**
2674 * This function removes callback which was installed by
2675 * AddMemoryAllocationCallback function.
2676 */
2677 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
2678
2679 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002680 * Allows the host application to group objects together. If one
2681 * object in the group is alive, all objects in the group are alive.
2682 * After each garbage collection, object groups are removed. It is
2683 * intended to be used in the before-garbage-collection callback
2684 * function, for instance to simulate DOM tree connections among JS
2685 * wrapper objects.
2686 */
2687 static void AddObjectGroup(Persistent<Value>* objects, size_t length);
2688
2689 /**
2690 * Initializes from snapshot if possible. Otherwise, attempts to
2691 * initialize from scratch. This function is called implicitly if
2692 * you use the API without calling it first.
2693 */
2694 static bool Initialize();
2695
2696 /**
2697 * Adjusts the amount of registered external memory. Used to give
2698 * V8 an indication of the amount of externally allocated memory
2699 * that is kept alive by JavaScript objects. V8 uses this to decide
2700 * when to perform global garbage collections. Registering
2701 * externally allocated memory will trigger global garbage
2702 * collections more often than otherwise in an attempt to garbage
2703 * collect the JavaScript objects keeping the externally allocated
2704 * memory alive.
2705 *
2706 * \param change_in_bytes the change in externally allocated memory
2707 * that is kept alive by JavaScript objects.
2708 * \returns the adjusted value.
2709 */
2710 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
2711
2712 /**
2713 * Suspends recording of tick samples in the profiler.
2714 * When the V8 profiling mode is enabled (usually via command line
2715 * switches) this function suspends recording of tick samples.
2716 * Profiling ticks are discarded until ResumeProfiler() is called.
2717 *
2718 * See also the --prof and --prof_auto command line switches to
2719 * enable V8 profiling.
2720 */
2721 static void PauseProfiler();
2722
2723 /**
2724 * Resumes recording of tick samples in the profiler.
2725 * See also PauseProfiler().
2726 */
2727 static void ResumeProfiler();
2728
2729 /**
2730 * Return whether profiler is currently paused.
2731 */
2732 static bool IsProfilerPaused();
2733
2734 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002735 * Resumes specified profiler modules. Can be called several times to
2736 * mark the opening of a profiler events block with the given tag.
2737 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002738 * "ResumeProfiler" is equivalent to "ResumeProfilerEx(PROFILER_MODULE_CPU)".
2739 * See ProfilerModules enum.
2740 *
2741 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002742 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002743 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002744 static void ResumeProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002745
2746 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002747 * Pauses specified profiler modules. Each call to "PauseProfilerEx" closes
2748 * a block of profiler events opened by a call to "ResumeProfilerEx" with the
2749 * same tag value. There is no need for blocks to be properly nested.
2750 * The profiler is paused when the last opened block is closed.
2751 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002752 * "PauseProfiler" is equivalent to "PauseProfilerEx(PROFILER_MODULE_CPU)".
2753 * See ProfilerModules enum.
2754 *
2755 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002756 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002757 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002758 static void PauseProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002759
2760 /**
2761 * Returns active (resumed) profiler modules.
2762 * See ProfilerModules enum.
2763 *
2764 * \returns active profiler modules.
2765 */
2766 static int GetActiveProfilerModules();
2767
2768 /**
2769 * If logging is performed into a memory buffer (via --logfile=*), allows to
2770 * retrieve previously written messages. This can be used for retrieving
2771 * profiler log data in the application. This function is thread-safe.
2772 *
2773 * Caller provides a destination buffer that must exist during GetLogLines
2774 * call. Only whole log lines are copied into the buffer.
2775 *
2776 * \param from_pos specified a point in a buffer to read from, 0 is the
2777 * beginning of a buffer. It is assumed that caller updates its current
2778 * position using returned size value from the previous call.
2779 * \param dest_buf destination buffer for log data.
2780 * \param max_size size of the destination buffer.
2781 * \returns actual size of log data copied into buffer.
2782 */
2783 static int GetLogLines(int from_pos, char* dest_buf, int max_size);
2784
2785 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002786 * The minimum allowed size for a log lines buffer. If the size of
2787 * the buffer given will not be enough to hold a line of the maximum
2788 * length, an attempt to find a log line end in GetLogLines will
2789 * fail, and an empty result will be returned.
2790 */
2791 static const int kMinimumSizeForLogLinesBuffer = 2048;
2792
2793 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002794 * Retrieve the V8 thread id of the calling thread.
2795 *
2796 * The thread id for a thread should only be retrieved after the V8
2797 * lock has been acquired with a Locker object with that thread.
2798 */
2799 static int GetCurrentThreadId();
2800
2801 /**
2802 * Forcefully terminate execution of a JavaScript thread. This can
2803 * be used to terminate long-running scripts.
2804 *
2805 * TerminateExecution should only be called when then V8 lock has
2806 * been acquired with a Locker object. Therefore, in order to be
2807 * able to terminate long-running threads, preemption must be
2808 * enabled to allow the user of TerminateExecution to acquire the
2809 * lock.
2810 *
2811 * The termination is achieved by throwing an exception that is
2812 * uncatchable by JavaScript exception handlers. Termination
2813 * exceptions act as if they were caught by a C++ TryCatch exception
2814 * handlers. If forceful termination is used, any C++ TryCatch
2815 * exception handler that catches an exception should check if that
2816 * exception is a termination exception and immediately return if
2817 * that is the case. Returning immediately in that case will
2818 * continue the propagation of the termination exception if needed.
2819 *
2820 * The thread id passed to TerminateExecution must have been
2821 * obtained by calling GetCurrentThreadId on the thread in question.
2822 *
2823 * \param thread_id The thread id of the thread to terminate.
2824 */
2825 static void TerminateExecution(int thread_id);
2826
2827 /**
2828 * Forcefully terminate the current thread of JavaScript execution.
2829 *
2830 * This method can be used by any thread even if that thread has not
2831 * acquired the V8 lock with a Locker object.
2832 */
2833 static void TerminateExecution();
2834
2835 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002836 * Is V8 terminating JavaScript execution.
2837 *
2838 * Returns true if JavaScript execution is currently terminating
2839 * because of a call to TerminateExecution. In that case there are
2840 * still JavaScript frames on the stack and the termination
2841 * exception is still active.
2842 */
2843 static bool IsExecutionTerminating();
2844
2845 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002846 * Releases any resources used by v8 and stops any utility threads
2847 * that may be running. Note that disposing v8 is permanent, it
2848 * cannot be reinitialized.
2849 *
2850 * It should generally not be necessary to dispose v8 before exiting
2851 * a process, this should happen automatically. It is only necessary
2852 * to use if the process needs the resources taken up by v8.
2853 */
2854 static bool Dispose();
2855
Steve Block3ce2e202009-11-05 08:53:23 +00002856 /**
2857 * Get statistics about the heap memory usage.
2858 */
2859 static void GetHeapStatistics(HeapStatistics* heap_statistics);
Steve Blocka7e24c12009-10-30 11:49:00 +00002860
2861 /**
2862 * Optional notification that the embedder is idle.
2863 * V8 uses the notification to reduce memory footprint.
2864 * This call can be used repeatedly if the embedder remains idle.
Steve Blocka7e24c12009-10-30 11:49:00 +00002865 * Returns true if the embedder should stop calling IdleNotification
2866 * until real work has been done. This indicates that V8 has done
2867 * as much cleanup as it will be able to do.
2868 */
Steve Block3ce2e202009-11-05 08:53:23 +00002869 static bool IdleNotification();
Steve Blocka7e24c12009-10-30 11:49:00 +00002870
2871 /**
2872 * Optional notification that the system is running low on memory.
2873 * V8 uses these notifications to attempt to free memory.
2874 */
2875 static void LowMemoryNotification();
2876
Steve Block6ded16b2010-05-10 14:33:55 +01002877 /**
2878 * Optional notification that a context has been disposed. V8 uses
2879 * these notifications to guide the GC heuristic. Returns the number
2880 * of context disposals - including this one - since the last time
2881 * V8 had a chance to clean up.
2882 */
2883 static int ContextDisposedNotification();
2884
Steve Blocka7e24c12009-10-30 11:49:00 +00002885 private:
2886 V8();
2887
2888 static internal::Object** GlobalizeReference(internal::Object** handle);
2889 static void DisposeGlobal(internal::Object** global_handle);
2890 static void MakeWeak(internal::Object** global_handle,
2891 void* data,
2892 WeakReferenceCallback);
2893 static void ClearWeak(internal::Object** global_handle);
2894 static bool IsGlobalNearDeath(internal::Object** global_handle);
2895 static bool IsGlobalWeak(internal::Object** global_handle);
2896
2897 template <class T> friend class Handle;
2898 template <class T> friend class Local;
2899 template <class T> friend class Persistent;
2900 friend class Context;
2901};
2902
2903
2904/**
2905 * An external exception handler.
2906 */
2907class V8EXPORT TryCatch {
2908 public:
2909
2910 /**
2911 * Creates a new try/catch block and registers it with v8.
2912 */
2913 TryCatch();
2914
2915 /**
2916 * Unregisters and deletes this try/catch block.
2917 */
2918 ~TryCatch();
2919
2920 /**
2921 * Returns true if an exception has been caught by this try/catch block.
2922 */
2923 bool HasCaught() const;
2924
2925 /**
2926 * For certain types of exceptions, it makes no sense to continue
2927 * execution.
2928 *
2929 * Currently, the only type of exception that can be caught by a
2930 * TryCatch handler and for which it does not make sense to continue
2931 * is termination exception. Such exceptions are thrown when the
2932 * TerminateExecution methods are called to terminate a long-running
2933 * script.
2934 *
2935 * If CanContinue returns false, the correct action is to perform
2936 * any C++ cleanup needed and then return.
2937 */
2938 bool CanContinue() const;
2939
2940 /**
Steve Blockd0582a62009-12-15 09:54:21 +00002941 * Throws the exception caught by this TryCatch in a way that avoids
2942 * it being caught again by this same TryCatch. As with ThrowException
2943 * it is illegal to execute any JavaScript operations after calling
2944 * ReThrow; the caller must return immediately to where the exception
2945 * is caught.
2946 */
2947 Handle<Value> ReThrow();
2948
2949 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002950 * Returns the exception caught by this try/catch block. If no exception has
2951 * been caught an empty handle is returned.
2952 *
2953 * The returned handle is valid until this TryCatch block has been destroyed.
2954 */
2955 Local<Value> Exception() const;
2956
2957 /**
2958 * Returns the .stack property of the thrown object. If no .stack
2959 * property is present an empty handle is returned.
2960 */
2961 Local<Value> StackTrace() const;
2962
2963 /**
2964 * Returns the message associated with this exception. If there is
2965 * no message associated an empty handle is returned.
2966 *
2967 * The returned handle is valid until this TryCatch block has been
2968 * destroyed.
2969 */
2970 Local<v8::Message> Message() const;
2971
2972 /**
2973 * Clears any exceptions that may have been caught by this try/catch block.
2974 * After this method has been called, HasCaught() will return false.
2975 *
2976 * It is not necessary to clear a try/catch block before using it again; if
2977 * another exception is thrown the previously caught exception will just be
2978 * overwritten. However, it is often a good idea since it makes it easier
2979 * to determine which operation threw a given exception.
2980 */
2981 void Reset();
2982
2983 /**
2984 * Set verbosity of the external exception handler.
2985 *
2986 * By default, exceptions that are caught by an external exception
2987 * handler are not reported. Call SetVerbose with true on an
2988 * external exception handler to have exceptions caught by the
2989 * handler reported as if they were not caught.
2990 */
2991 void SetVerbose(bool value);
2992
2993 /**
2994 * Set whether or not this TryCatch should capture a Message object
2995 * which holds source information about where the exception
2996 * occurred. True by default.
2997 */
2998 void SetCaptureMessage(bool value);
2999
Steve Blockd0582a62009-12-15 09:54:21 +00003000 private:
3001 void* next_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003002 void* exception_;
3003 void* message_;
Steve Blockd0582a62009-12-15 09:54:21 +00003004 bool is_verbose_ : 1;
3005 bool can_continue_ : 1;
3006 bool capture_message_ : 1;
3007 bool rethrow_ : 1;
3008
3009 friend class v8::internal::Top;
Steve Blocka7e24c12009-10-30 11:49:00 +00003010};
3011
3012
3013// --- C o n t e x t ---
3014
3015
3016/**
3017 * Ignore
3018 */
3019class V8EXPORT ExtensionConfiguration {
3020 public:
3021 ExtensionConfiguration(int name_count, const char* names[])
3022 : name_count_(name_count), names_(names) { }
3023 private:
3024 friend class ImplementationUtilities;
3025 int name_count_;
3026 const char** names_;
3027};
3028
3029
3030/**
3031 * A sandboxed execution context with its own set of built-in objects
3032 * and functions.
3033 */
3034class V8EXPORT Context {
3035 public:
3036 /** Returns the global object of the context. */
3037 Local<Object> Global();
3038
3039 /**
3040 * Detaches the global object from its context before
3041 * the global object can be reused to create a new context.
3042 */
3043 void DetachGlobal();
3044
Andrei Popescu74b3c142010-03-29 12:03:09 +01003045 /**
3046 * Reattaches a global object to a context. This can be used to
3047 * restore the connection between a global object and a context
3048 * after DetachGlobal has been called.
3049 *
3050 * \param global_object The global object to reattach to the
3051 * context. For this to work, the global object must be the global
3052 * object that was associated with this context before a call to
3053 * DetachGlobal.
3054 */
3055 void ReattachGlobal(Handle<Object> global_object);
3056
Leon Clarkef7060e22010-06-03 12:02:55 +01003057 /** Creates a new context.
3058 *
3059 * Returns a persistent handle to the newly allocated context. This
3060 * persistent handle has to be disposed when the context is no
3061 * longer used so the context can be garbage collected.
3062 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003063 static Persistent<Context> New(
Andrei Popescu31002712010-02-23 13:46:05 +00003064 ExtensionConfiguration* extensions = NULL,
Steve Blocka7e24c12009-10-30 11:49:00 +00003065 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3066 Handle<Value> global_object = Handle<Value>());
3067
3068 /** Returns the last entered context. */
3069 static Local<Context> GetEntered();
3070
3071 /** Returns the context that is on the top of the stack. */
3072 static Local<Context> GetCurrent();
3073
3074 /**
3075 * Returns the context of the calling JavaScript code. That is the
3076 * context of the top-most JavaScript frame. If there are no
3077 * JavaScript frames an empty handle is returned.
3078 */
3079 static Local<Context> GetCalling();
3080
3081 /**
3082 * Sets the security token for the context. To access an object in
3083 * another context, the security tokens must match.
3084 */
3085 void SetSecurityToken(Handle<Value> token);
3086
3087 /** Restores the security token to the default value. */
3088 void UseDefaultSecurityToken();
3089
3090 /** Returns the security token of this context.*/
3091 Handle<Value> GetSecurityToken();
3092
3093 /**
3094 * Enter this context. After entering a context, all code compiled
3095 * and run is compiled and run in this context. If another context
3096 * is already entered, this old context is saved so it can be
3097 * restored when the new context is exited.
3098 */
3099 void Enter();
3100
3101 /**
3102 * Exit this context. Exiting the current context restores the
3103 * context that was in place when entering the current context.
3104 */
3105 void Exit();
3106
3107 /** Returns true if the context has experienced an out of memory situation. */
3108 bool HasOutOfMemoryException();
3109
3110 /** Returns true if V8 has a current context. */
3111 static bool InContext();
3112
3113 /**
3114 * Associate an additional data object with the context. This is mainly used
3115 * with the debugger to provide additional information on the context through
3116 * the debugger API.
3117 */
Steve Blockd0582a62009-12-15 09:54:21 +00003118 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00003119 Local<Value> GetData();
3120
3121 /**
3122 * Stack-allocated class which sets the execution context for all
3123 * operations executed within a local scope.
3124 */
Steve Block8defd9f2010-07-08 12:39:36 +01003125 class Scope {
Steve Blocka7e24c12009-10-30 11:49:00 +00003126 public:
3127 inline Scope(Handle<Context> context) : context_(context) {
3128 context_->Enter();
3129 }
3130 inline ~Scope() { context_->Exit(); }
3131 private:
3132 Handle<Context> context_;
3133 };
3134
3135 private:
3136 friend class Value;
3137 friend class Script;
3138 friend class Object;
3139 friend class Function;
3140};
3141
3142
3143/**
3144 * Multiple threads in V8 are allowed, but only one thread at a time
3145 * is allowed to use V8. The definition of 'using V8' includes
3146 * accessing handles or holding onto object pointers obtained from V8
3147 * handles. It is up to the user of V8 to ensure (perhaps with
3148 * locking) that this constraint is not violated.
3149 *
3150 * If you wish to start using V8 in a thread you can do this by constructing
3151 * a v8::Locker object. After the code using V8 has completed for the
3152 * current thread you can call the destructor. This can be combined
3153 * with C++ scope-based construction as follows:
3154 *
3155 * \code
3156 * ...
3157 * {
3158 * v8::Locker locker;
3159 * ...
3160 * // Code using V8 goes here.
3161 * ...
3162 * } // Destructor called here
3163 * \endcode
3164 *
3165 * If you wish to stop using V8 in a thread A you can do this by either
3166 * by destroying the v8::Locker object as above or by constructing a
3167 * v8::Unlocker object:
3168 *
3169 * \code
3170 * {
3171 * v8::Unlocker unlocker;
3172 * ...
3173 * // Code not using V8 goes here while V8 can run in another thread.
3174 * ...
3175 * } // Destructor called here.
3176 * \endcode
3177 *
3178 * The Unlocker object is intended for use in a long-running callback
3179 * from V8, where you want to release the V8 lock for other threads to
3180 * use.
3181 *
3182 * The v8::Locker is a recursive lock. That is, you can lock more than
3183 * once in a given thread. This can be useful if you have code that can
3184 * be called either from code that holds the lock or from code that does
3185 * not. The Unlocker is not recursive so you can not have several
3186 * Unlockers on the stack at once, and you can not use an Unlocker in a
3187 * thread that is not inside a Locker's scope.
3188 *
3189 * An unlocker will unlock several lockers if it has to and reinstate
3190 * the correct depth of locking on its destruction. eg.:
3191 *
3192 * \code
3193 * // V8 not locked.
3194 * {
3195 * v8::Locker locker;
3196 * // V8 locked.
3197 * {
3198 * v8::Locker another_locker;
3199 * // V8 still locked (2 levels).
3200 * {
3201 * v8::Unlocker unlocker;
3202 * // V8 not locked.
3203 * }
3204 * // V8 locked again (2 levels).
3205 * }
3206 * // V8 still locked (1 level).
3207 * }
3208 * // V8 Now no longer locked.
3209 * \endcode
3210 */
3211class V8EXPORT Unlocker {
3212 public:
3213 Unlocker();
3214 ~Unlocker();
3215};
3216
3217
3218class V8EXPORT Locker {
3219 public:
3220 Locker();
3221 ~Locker();
3222
3223 /**
3224 * Start preemption.
3225 *
3226 * When preemption is started, a timer is fired every n milli seconds
3227 * that will switch between multiple threads that are in contention
3228 * for the V8 lock.
3229 */
3230 static void StartPreemption(int every_n_ms);
3231
3232 /**
3233 * Stop preemption.
3234 */
3235 static void StopPreemption();
3236
3237 /**
3238 * Returns whether or not the locker is locked by the current thread.
3239 */
3240 static bool IsLocked();
3241
3242 /**
3243 * Returns whether v8::Locker is being used by this V8 instance.
3244 */
3245 static bool IsActive() { return active_; }
3246
3247 private:
3248 bool has_lock_;
3249 bool top_level_;
3250
3251 static bool active_;
3252
3253 // Disallow copying and assigning.
3254 Locker(const Locker&);
3255 void operator=(const Locker&);
3256};
3257
3258
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003259/**
3260 * An interface for exporting data from V8, using "push" model.
3261 */
3262class V8EXPORT OutputStream {
3263public:
3264 enum OutputEncoding {
3265 kAscii = 0 // 7-bit ASCII.
3266 };
3267 enum WriteResult {
3268 kContinue = 0,
3269 kAbort = 1
3270 };
3271 virtual ~OutputStream() {}
3272 /** Notify about the end of stream. */
3273 virtual void EndOfStream() = 0;
3274 /** Get preferred output chunk size. Called only once. */
3275 virtual int GetChunkSize() { return 1024; }
3276 /** Get preferred output encoding. Called only once. */
3277 virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3278 /**
3279 * Writes the next chunk of snapshot data into the stream. Writing
3280 * can be stopped by returning kAbort as function result. EndOfStream
3281 * will not be called in case writing was aborted.
3282 */
3283 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3284};
3285
3286
Steve Blocka7e24c12009-10-30 11:49:00 +00003287
3288// --- I m p l e m e n t a t i o n ---
3289
3290
3291namespace internal {
3292
3293
3294// Tag information for HeapObject.
3295const int kHeapObjectTag = 1;
3296const int kHeapObjectTagSize = 2;
3297const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3298
Steve Blocka7e24c12009-10-30 11:49:00 +00003299// Tag information for Smi.
3300const int kSmiTag = 0;
3301const int kSmiTagSize = 1;
3302const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3303
Steve Block3ce2e202009-11-05 08:53:23 +00003304template <size_t ptr_size> struct SmiConstants;
3305
3306// Smi constants for 32-bit systems.
3307template <> struct SmiConstants<4> {
3308 static const int kSmiShiftSize = 0;
3309 static const int kSmiValueSize = 31;
3310 static inline int SmiToInt(internal::Object* value) {
3311 int shift_bits = kSmiTagSize + kSmiShiftSize;
3312 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3313 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3314 }
3315};
3316
3317// Smi constants for 64-bit systems.
3318template <> struct SmiConstants<8> {
3319 static const int kSmiShiftSize = 31;
3320 static const int kSmiValueSize = 32;
3321 static inline int SmiToInt(internal::Object* value) {
3322 int shift_bits = kSmiTagSize + kSmiShiftSize;
3323 // Shift down and throw away top 32 bits.
3324 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3325 }
3326};
3327
3328const int kSmiShiftSize = SmiConstants<sizeof(void*)>::kSmiShiftSize;
3329const int kSmiValueSize = SmiConstants<sizeof(void*)>::kSmiValueSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003330
Steve Blockd0582a62009-12-15 09:54:21 +00003331template <size_t ptr_size> struct InternalConstants;
3332
3333// Internal constants for 32-bit systems.
3334template <> struct InternalConstants<4> {
3335 static const int kStringResourceOffset = 3 * sizeof(void*);
3336};
3337
3338// Internal constants for 64-bit systems.
3339template <> struct InternalConstants<8> {
Steve Block6ded16b2010-05-10 14:33:55 +01003340 static const int kStringResourceOffset = 3 * sizeof(void*);
Steve Blockd0582a62009-12-15 09:54:21 +00003341};
3342
Steve Blocka7e24c12009-10-30 11:49:00 +00003343/**
3344 * This class exports constants and functionality from within v8 that
3345 * is necessary to implement inline functions in the v8 api. Don't
3346 * depend on functions and constants defined here.
3347 */
3348class Internals {
3349 public:
3350
3351 // These values match non-compiler-dependent values defined within
3352 // the implementation of v8.
3353 static const int kHeapObjectMapOffset = 0;
3354 static const int kMapInstanceTypeOffset = sizeof(void*) + sizeof(int);
Steve Blockd0582a62009-12-15 09:54:21 +00003355 static const int kStringResourceOffset =
3356 InternalConstants<sizeof(void*)>::kStringResourceOffset;
3357
Steve Blocka7e24c12009-10-30 11:49:00 +00003358 static const int kProxyProxyOffset = sizeof(void*);
3359 static const int kJSObjectHeaderSize = 3 * sizeof(void*);
3360 static const int kFullStringRepresentationMask = 0x07;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003361 static const int kExternalTwoByteRepresentationTag = 0x02;
Steve Blocka7e24c12009-10-30 11:49:00 +00003362
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003363 static const int kJSObjectType = 0x9f;
3364 static const int kFirstNonstringType = 0x80;
3365 static const int kProxyType = 0x85;
Steve Blocka7e24c12009-10-30 11:49:00 +00003366
3367 static inline bool HasHeapObjectTag(internal::Object* value) {
3368 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3369 kHeapObjectTag);
3370 }
3371
3372 static inline bool HasSmiTag(internal::Object* value) {
3373 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3374 }
3375
3376 static inline int SmiValue(internal::Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00003377 return SmiConstants<sizeof(void*)>::SmiToInt(value);
3378 }
3379
3380 static inline int GetInstanceType(internal::Object* obj) {
3381 typedef internal::Object O;
3382 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3383 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3384 }
3385
3386 static inline void* GetExternalPointer(internal::Object* obj) {
3387 if (HasSmiTag(obj)) {
3388 return obj;
3389 } else if (GetInstanceType(obj) == kProxyType) {
3390 return ReadField<void*>(obj, kProxyProxyOffset);
3391 } else {
3392 return NULL;
3393 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003394 }
3395
3396 static inline bool IsExternalTwoByteString(int instance_type) {
3397 int representation = (instance_type & kFullStringRepresentationMask);
3398 return representation == kExternalTwoByteRepresentationTag;
3399 }
3400
3401 template <typename T>
3402 static inline T ReadField(Object* ptr, int offset) {
3403 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3404 return *reinterpret_cast<T*>(addr);
3405 }
3406
3407};
3408
3409}
3410
3411
3412template <class T>
3413Handle<T>::Handle() : val_(0) { }
3414
3415
3416template <class T>
3417Local<T>::Local() : Handle<T>() { }
3418
3419
3420template <class T>
3421Local<T> Local<T>::New(Handle<T> that) {
3422 if (that.IsEmpty()) return Local<T>();
3423 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3424 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3425}
3426
3427
3428template <class T>
3429Persistent<T> Persistent<T>::New(Handle<T> that) {
3430 if (that.IsEmpty()) return Persistent<T>();
3431 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3432 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3433}
3434
3435
3436template <class T>
3437bool Persistent<T>::IsNearDeath() const {
3438 if (this->IsEmpty()) return false;
3439 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3440}
3441
3442
3443template <class T>
3444bool Persistent<T>::IsWeak() const {
3445 if (this->IsEmpty()) return false;
3446 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3447}
3448
3449
3450template <class T>
3451void Persistent<T>::Dispose() {
3452 if (this->IsEmpty()) return;
3453 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3454}
3455
3456
3457template <class T>
3458Persistent<T>::Persistent() : Handle<T>() { }
3459
3460template <class T>
3461void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3462 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3463 parameters,
3464 callback);
3465}
3466
3467template <class T>
3468void Persistent<T>::ClearWeak() {
3469 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3470}
3471
Steve Block8defd9f2010-07-08 12:39:36 +01003472
3473Arguments::Arguments(v8::Local<v8::Value> data,
3474 v8::Local<v8::Object> holder,
3475 v8::Local<v8::Function> callee,
3476 bool is_construct_call,
3477 void** values, int length)
3478 : data_(data), holder_(holder), callee_(callee),
3479 is_construct_call_(is_construct_call),
3480 values_(values), length_(length) { }
3481
3482
Steve Blocka7e24c12009-10-30 11:49:00 +00003483Local<Value> Arguments::operator[](int i) const {
3484 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3485 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3486}
3487
3488
3489Local<Function> Arguments::Callee() const {
3490 return callee_;
3491}
3492
3493
3494Local<Object> Arguments::This() const {
3495 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
3496}
3497
3498
3499Local<Object> Arguments::Holder() const {
3500 return holder_;
3501}
3502
3503
3504Local<Value> Arguments::Data() const {
3505 return data_;
3506}
3507
3508
3509bool Arguments::IsConstructCall() const {
3510 return is_construct_call_;
3511}
3512
3513
3514int Arguments::Length() const {
3515 return length_;
3516}
3517
3518
3519template <class T>
3520Local<T> HandleScope::Close(Handle<T> value) {
3521 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
3522 internal::Object** after = RawClose(before);
3523 return Local<T>(reinterpret_cast<T*>(after));
3524}
3525
3526Handle<Value> ScriptOrigin::ResourceName() const {
3527 return resource_name_;
3528}
3529
3530
3531Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
3532 return resource_line_offset_;
3533}
3534
3535
3536Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
3537 return resource_column_offset_;
3538}
3539
3540
3541Handle<Boolean> Boolean::New(bool value) {
3542 return value ? True() : False();
3543}
3544
3545
3546void Template::Set(const char* name, v8::Handle<Data> value) {
3547 Set(v8::String::New(name), value);
3548}
3549
3550
3551Local<Value> Object::GetInternalField(int index) {
3552#ifndef V8_ENABLE_CHECKS
3553 Local<Value> quick_result = UncheckedGetInternalField(index);
3554 if (!quick_result.IsEmpty()) return quick_result;
3555#endif
3556 return CheckedGetInternalField(index);
3557}
3558
3559
3560Local<Value> Object::UncheckedGetInternalField(int index) {
3561 typedef internal::Object O;
3562 typedef internal::Internals I;
3563 O* obj = *reinterpret_cast<O**>(this);
Steve Block3ce2e202009-11-05 08:53:23 +00003564 if (I::GetInstanceType(obj) == I::kJSObjectType) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003565 // If the object is a plain JSObject, which is the common case,
3566 // we know where to find the internal fields and can return the
3567 // value directly.
3568 int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3569 O* value = I::ReadField<O*>(obj, offset);
3570 O** result = HandleScope::CreateHandle(value);
3571 return Local<Value>(reinterpret_cast<Value*>(result));
3572 } else {
3573 return Local<Value>();
3574 }
3575}
3576
3577
3578void* External::Unwrap(Handle<v8::Value> obj) {
3579#ifdef V8_ENABLE_CHECKS
3580 return FullUnwrap(obj);
3581#else
3582 return QuickUnwrap(obj);
3583#endif
3584}
3585
3586
3587void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
3588 typedef internal::Object O;
Steve Blocka7e24c12009-10-30 11:49:00 +00003589 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
Steve Block3ce2e202009-11-05 08:53:23 +00003590 return internal::Internals::GetExternalPointer(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00003591}
3592
3593
3594void* Object::GetPointerFromInternalField(int index) {
Steve Block3ce2e202009-11-05 08:53:23 +00003595 typedef internal::Object O;
3596 typedef internal::Internals I;
3597
3598 O* obj = *reinterpret_cast<O**>(this);
3599
3600 if (I::GetInstanceType(obj) == I::kJSObjectType) {
3601 // If the object is a plain JSObject, which is the common case,
3602 // we know where to find the internal fields and can return the
3603 // value directly.
3604 int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3605 O* value = I::ReadField<O*>(obj, offset);
3606 return I::GetExternalPointer(value);
3607 }
3608
3609 return SlowGetPointerFromInternalField(index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003610}
3611
3612
3613String* String::Cast(v8::Value* value) {
3614#ifdef V8_ENABLE_CHECKS
3615 CheckCast(value);
3616#endif
3617 return static_cast<String*>(value);
3618}
3619
3620
3621String::ExternalStringResource* String::GetExternalStringResource() const {
3622 typedef internal::Object O;
3623 typedef internal::Internals I;
3624 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
Steve Blocka7e24c12009-10-30 11:49:00 +00003625 String::ExternalStringResource* result;
Steve Block3ce2e202009-11-05 08:53:23 +00003626 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003627 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
3628 result = reinterpret_cast<String::ExternalStringResource*>(value);
3629 } else {
3630 result = NULL;
3631 }
3632#ifdef V8_ENABLE_CHECKS
3633 VerifyExternalStringResource(result);
3634#endif
3635 return result;
3636}
3637
3638
3639bool Value::IsString() const {
3640#ifdef V8_ENABLE_CHECKS
3641 return FullIsString();
3642#else
3643 return QuickIsString();
3644#endif
3645}
3646
3647bool Value::QuickIsString() const {
3648 typedef internal::Object O;
3649 typedef internal::Internals I;
3650 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
3651 if (!I::HasHeapObjectTag(obj)) return false;
Steve Block3ce2e202009-11-05 08:53:23 +00003652 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
Steve Blocka7e24c12009-10-30 11:49:00 +00003653}
3654
3655
3656Number* Number::Cast(v8::Value* value) {
3657#ifdef V8_ENABLE_CHECKS
3658 CheckCast(value);
3659#endif
3660 return static_cast<Number*>(value);
3661}
3662
3663
3664Integer* Integer::Cast(v8::Value* value) {
3665#ifdef V8_ENABLE_CHECKS
3666 CheckCast(value);
3667#endif
3668 return static_cast<Integer*>(value);
3669}
3670
3671
3672Date* Date::Cast(v8::Value* value) {
3673#ifdef V8_ENABLE_CHECKS
3674 CheckCast(value);
3675#endif
3676 return static_cast<Date*>(value);
3677}
3678
3679
Ben Murdochf87a2032010-10-22 12:50:53 +01003680RegExp* RegExp::Cast(v8::Value* value) {
3681#ifdef V8_ENABLE_CHECKS
3682 CheckCast(value);
3683#endif
3684 return static_cast<RegExp*>(value);
3685}
3686
3687
Steve Blocka7e24c12009-10-30 11:49:00 +00003688Object* Object::Cast(v8::Value* value) {
3689#ifdef V8_ENABLE_CHECKS
3690 CheckCast(value);
3691#endif
3692 return static_cast<Object*>(value);
3693}
3694
3695
3696Array* Array::Cast(v8::Value* value) {
3697#ifdef V8_ENABLE_CHECKS
3698 CheckCast(value);
3699#endif
3700 return static_cast<Array*>(value);
3701}
3702
3703
3704Function* Function::Cast(v8::Value* value) {
3705#ifdef V8_ENABLE_CHECKS
3706 CheckCast(value);
3707#endif
3708 return static_cast<Function*>(value);
3709}
3710
3711
3712External* External::Cast(v8::Value* value) {
3713#ifdef V8_ENABLE_CHECKS
3714 CheckCast(value);
3715#endif
3716 return static_cast<External*>(value);
3717}
3718
3719
3720Local<Value> AccessorInfo::Data() const {
Steve Block6ded16b2010-05-10 14:33:55 +01003721 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003722}
3723
3724
3725Local<Object> AccessorInfo::This() const {
3726 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
3727}
3728
3729
3730Local<Object> AccessorInfo::Holder() const {
3731 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
3732}
3733
3734
3735/**
3736 * \example shell.cc
3737 * A simple shell that takes a list of expressions on the
3738 * command-line and executes them.
3739 */
3740
3741
3742/**
3743 * \example process.cc
3744 */
3745
3746
3747} // namespace v8
3748
3749
3750#undef V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00003751#undef TYPE_CHECK
3752
3753
3754#endif // V8_H_