blob: b89c244ca20606ad428a5967f258b599403f6b80 [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:
470 int extensions;
471 internal::Object** next;
472 internal::Object** limit;
473 inline void Initialize() {
474 extensions = -1;
475 next = limit = NULL;
476 }
477 };
478
479 Data previous_;
480
481 // Allow for the active closing of HandleScopes which allows to pass a handle
482 // from the HandleScope being closed to the next top most HandleScope.
483 bool is_closed_;
484 internal::Object** RawClose(internal::Object** value);
485
486 friend class ImplementationUtilities;
487};
488
489
490// --- S p e c i a l o b j e c t s ---
491
492
493/**
494 * The superclass of values and API object templates.
495 */
496class V8EXPORT Data {
497 private:
498 Data();
499};
500
501
502/**
503 * Pre-compilation data that can be associated with a script. This
504 * data can be calculated for a script in advance of actually
505 * compiling it, and can be stored between compilations. When script
506 * data is given to the compile method compilation will be faster.
507 */
508class V8EXPORT ScriptData { // NOLINT
509 public:
510 virtual ~ScriptData() { }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100511
Leon Clarkef7060e22010-06-03 12:02:55 +0100512 /**
513 * Pre-compiles the specified script (context-independent).
514 *
515 * \param input Pointer to UTF-8 script source code.
516 * \param length Length of UTF-8 script source code.
517 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000518 static ScriptData* PreCompile(const char* input, int length);
Steve Blocka7e24c12009-10-30 11:49:00 +0000519
Leon Clarkef7060e22010-06-03 12:02:55 +0100520 /**
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100521 * Pre-compiles the specified script (context-independent).
522 *
523 * NOTE: Pre-compilation using this method cannot happen on another thread
524 * without using Lockers.
525 *
526 * \param source Script source code.
527 */
528 static ScriptData* PreCompile(Handle<String> source);
529
530 /**
Leon Clarkef7060e22010-06-03 12:02:55 +0100531 * Load previous pre-compilation data.
532 *
533 * \param data Pointer to data returned by a call to Data() of a previous
534 * ScriptData. Ownership is not transferred.
535 * \param length Length of data.
536 */
537 static ScriptData* New(const char* data, int length);
538
539 /**
540 * Returns the length of Data().
541 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000542 virtual int Length() = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100543
544 /**
545 * Returns a serialized representation of this ScriptData that can later be
546 * passed to New(). NOTE: Serialized data is platform-dependent.
547 */
548 virtual const char* Data() = 0;
549
550 /**
551 * Returns true if the source code could not be parsed.
552 */
Leon Clarkee46be812010-01-19 14:06:41 +0000553 virtual bool HasError() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000554};
555
556
557/**
558 * The origin, within a file, of a script.
559 */
Steve Block8defd9f2010-07-08 12:39:36 +0100560class ScriptOrigin {
Steve Blocka7e24c12009-10-30 11:49:00 +0000561 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100562 inline ScriptOrigin(
563 Handle<Value> resource_name,
564 Handle<Integer> resource_line_offset = Handle<Integer>(),
565 Handle<Integer> resource_column_offset = Handle<Integer>())
Steve Blocka7e24c12009-10-30 11:49:00 +0000566 : resource_name_(resource_name),
567 resource_line_offset_(resource_line_offset),
568 resource_column_offset_(resource_column_offset) { }
569 inline Handle<Value> ResourceName() const;
570 inline Handle<Integer> ResourceLineOffset() const;
571 inline Handle<Integer> ResourceColumnOffset() const;
572 private:
573 Handle<Value> resource_name_;
574 Handle<Integer> resource_line_offset_;
575 Handle<Integer> resource_column_offset_;
576};
577
578
579/**
580 * A compiled JavaScript script.
581 */
582class V8EXPORT Script {
583 public:
584
Steve Blocka7e24c12009-10-30 11:49:00 +0000585 /**
Andrei Popescu402d9372010-02-26 13:31:12 +0000586 * Compiles the specified script (context-independent).
Steve Blocka7e24c12009-10-30 11:49:00 +0000587 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000588 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100589 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000590 * when New() returns
591 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
592 * using pre_data speeds compilation if it's done multiple times.
593 * Owned by caller, no references are kept when New() returns.
594 * \param script_data Arbitrary data associated with script. Using
Steve Block6ded16b2010-05-10 14:33:55 +0100595 * this has same effect as calling SetData(), but allows data to be
Andrei Popescu402d9372010-02-26 13:31:12 +0000596 * available to compile event handlers.
597 * \return Compiled script object (context independent; when run it
598 * will use the currently entered context).
Steve Blocka7e24c12009-10-30 11:49:00 +0000599 */
Andrei Popescu402d9372010-02-26 13:31:12 +0000600 static Local<Script> New(Handle<String> source,
601 ScriptOrigin* origin = NULL,
602 ScriptData* pre_data = NULL,
603 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000604
605 /**
606 * Compiles the specified script using the specified file name
607 * object (typically a string) as the script's origin.
608 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000609 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100610 * \param file_name file name object (typically a string) to be used
Andrei Popescu402d9372010-02-26 13:31:12 +0000611 * as the script's origin.
612 * \return Compiled script object (context independent; when run it
613 * will use the currently entered context).
614 */
615 static Local<Script> New(Handle<String> source,
616 Handle<Value> file_name);
617
618 /**
619 * Compiles the specified script (bound to current context).
620 *
621 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100622 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000623 * when Compile() returns
624 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
625 * using pre_data speeds compilation if it's done multiple times.
626 * Owned by caller, no references are kept when Compile() returns.
627 * \param script_data Arbitrary data associated with script. Using
628 * this has same effect as calling SetData(), but makes data available
629 * earlier (i.e. to compile event handlers).
630 * \return Compiled script object, bound to the context that was active
631 * when this function was called. When run it will always use this
632 * context.
Steve Blocka7e24c12009-10-30 11:49:00 +0000633 */
634 static Local<Script> Compile(Handle<String> source,
Andrei Popescu402d9372010-02-26 13:31:12 +0000635 ScriptOrigin* origin = NULL,
636 ScriptData* pre_data = NULL,
637 Handle<String> script_data = Handle<String>());
638
639 /**
640 * Compiles the specified script using the specified file name
641 * object (typically a string) as the script's origin.
642 *
643 * \param source Script source code.
644 * \param file_name File name to use as script's origin
645 * \param script_data Arbitrary data associated with script. Using
646 * this has same effect as calling SetData(), but makes data available
647 * earlier (i.e. to compile event handlers).
648 * \return Compiled script object, bound to the context that was active
649 * when this function was called. When run it will always use this
650 * context.
651 */
652 static Local<Script> Compile(Handle<String> source,
653 Handle<Value> file_name,
654 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000655
656 /**
657 * Runs the script returning the resulting value. If the script is
658 * context independent (created using ::New) it will be run in the
659 * currently entered context. If it is context specific (created
660 * using ::Compile) it will be run in the context in which it was
661 * compiled.
662 */
663 Local<Value> Run();
664
665 /**
666 * Returns the script id value.
667 */
668 Local<Value> Id();
669
670 /**
671 * Associate an additional data object with the script. This is mainly used
672 * with the debugger as this data object is only available through the
673 * debugger API.
674 */
Steve Blockd0582a62009-12-15 09:54:21 +0000675 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000676};
677
678
679/**
680 * An error message.
681 */
682class V8EXPORT Message {
683 public:
684 Local<String> Get() const;
685 Local<String> GetSourceLine() const;
686
687 /**
688 * Returns the resource name for the script from where the function causing
689 * the error originates.
690 */
691 Handle<Value> GetScriptResourceName() const;
692
693 /**
694 * Returns the resource data for the script from where the function causing
695 * the error originates.
696 */
697 Handle<Value> GetScriptData() const;
698
699 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100700 * Exception stack trace. By default stack traces are not captured for
701 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
702 * to change this option.
703 */
704 Handle<StackTrace> GetStackTrace() const;
705
706 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000707 * Returns the number, 1-based, of the line where the error occurred.
708 */
709 int GetLineNumber() const;
710
711 /**
712 * Returns the index within the script of the first character where
713 * the error occurred.
714 */
715 int GetStartPosition() const;
716
717 /**
718 * Returns the index within the script of the last character where
719 * the error occurred.
720 */
721 int GetEndPosition() const;
722
723 /**
724 * Returns the index within the line of the first character where
725 * the error occurred.
726 */
727 int GetStartColumn() const;
728
729 /**
730 * Returns the index within the line of the last character where
731 * the error occurred.
732 */
733 int GetEndColumn() const;
734
735 // TODO(1245381): Print to a string instead of on a FILE.
736 static void PrintCurrentStackTrace(FILE* out);
Kristian Monsen25f61362010-05-21 11:50:48 +0100737
738 static const int kNoLineNumberInfo = 0;
739 static const int kNoColumnInfo = 0;
740};
741
742
743/**
744 * Representation of a JavaScript stack trace. The information collected is a
745 * snapshot of the execution stack and the information remains valid after
746 * execution continues.
747 */
748class V8EXPORT StackTrace {
749 public:
750 /**
751 * Flags that determine what information is placed captured for each
752 * StackFrame when grabbing the current stack trace.
753 */
754 enum StackTraceOptions {
755 kLineNumber = 1,
756 kColumnOffset = 1 << 1 | kLineNumber,
757 kScriptName = 1 << 2,
758 kFunctionName = 1 << 3,
759 kIsEval = 1 << 4,
760 kIsConstructor = 1 << 5,
761 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
762 kDetailed = kOverview | kIsEval | kIsConstructor
763 };
764
765 /**
766 * Returns a StackFrame at a particular index.
767 */
768 Local<StackFrame> GetFrame(uint32_t index) const;
769
770 /**
771 * Returns the number of StackFrames.
772 */
773 int GetFrameCount() const;
774
775 /**
776 * Returns StackTrace as a v8::Array that contains StackFrame objects.
777 */
778 Local<Array> AsArray();
779
780 /**
781 * Grab a snapshot of the the current JavaScript execution stack.
782 *
783 * \param frame_limit The maximum number of stack frames we want to capture.
784 * \param options Enumerates the set of things we will capture for each
785 * StackFrame.
786 */
787 static Local<StackTrace> CurrentStackTrace(
788 int frame_limit,
789 StackTraceOptions options = kOverview);
790};
791
792
793/**
794 * A single JavaScript stack frame.
795 */
796class V8EXPORT StackFrame {
797 public:
798 /**
799 * Returns the number, 1-based, of the line for the associate function call.
800 * This method will return Message::kNoLineNumberInfo if it is unable to
801 * retrieve the line number, or if kLineNumber was not passed as an option
802 * when capturing the StackTrace.
803 */
804 int GetLineNumber() const;
805
806 /**
807 * Returns the 1-based column offset on the line for the associated function
808 * call.
809 * This method will return Message::kNoColumnInfo if it is unable to retrieve
810 * the column number, or if kColumnOffset was not passed as an option when
811 * capturing the StackTrace.
812 */
813 int GetColumn() const;
814
815 /**
816 * Returns the name of the resource that contains the script for the
817 * function for this StackFrame.
818 */
819 Local<String> GetScriptName() const;
820
821 /**
822 * Returns the name of the function associated with this stack frame.
823 */
824 Local<String> GetFunctionName() const;
825
826 /**
827 * Returns whether or not the associated function is compiled via a call to
828 * eval().
829 */
830 bool IsEval() const;
831
832 /**
833 * Returns whther or not the associated function is called as a
834 * constructor via "new".
835 */
836 bool IsConstructor() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000837};
838
839
840// --- V a l u e ---
841
842
843/**
844 * The superclass of all JavaScript values and objects.
845 */
Steve Block8defd9f2010-07-08 12:39:36 +0100846class Value : public Data {
Steve Blocka7e24c12009-10-30 11:49:00 +0000847 public:
848
849 /**
850 * Returns true if this value is the undefined value. See ECMA-262
851 * 4.3.10.
852 */
Steve Block8defd9f2010-07-08 12:39:36 +0100853 V8EXPORT bool IsUndefined() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000854
855 /**
856 * Returns true if this value is the null value. See ECMA-262
857 * 4.3.11.
858 */
Steve Block8defd9f2010-07-08 12:39:36 +0100859 V8EXPORT bool IsNull() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000860
861 /**
862 * Returns true if this value is true.
863 */
Steve Block8defd9f2010-07-08 12:39:36 +0100864 V8EXPORT bool IsTrue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000865
866 /**
867 * Returns true if this value is false.
868 */
Steve Block8defd9f2010-07-08 12:39:36 +0100869 V8EXPORT bool IsFalse() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000870
871 /**
872 * Returns true if this value is an instance of the String type.
873 * See ECMA-262 8.4.
874 */
875 inline bool IsString() const;
876
877 /**
878 * Returns true if this value is a function.
879 */
Steve Block8defd9f2010-07-08 12:39:36 +0100880 V8EXPORT bool IsFunction() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000881
882 /**
883 * Returns true if this value is an array.
884 */
Steve Block8defd9f2010-07-08 12:39:36 +0100885 V8EXPORT bool IsArray() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000886
887 /**
888 * Returns true if this value is an object.
889 */
Steve Block8defd9f2010-07-08 12:39:36 +0100890 V8EXPORT bool IsObject() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000891
892 /**
893 * Returns true if this value is boolean.
894 */
Steve Block8defd9f2010-07-08 12:39:36 +0100895 V8EXPORT bool IsBoolean() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000896
897 /**
898 * Returns true if this value is a number.
899 */
Steve Block8defd9f2010-07-08 12:39:36 +0100900 V8EXPORT bool IsNumber() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000901
902 /**
903 * Returns true if this value is external.
904 */
Steve Block8defd9f2010-07-08 12:39:36 +0100905 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000906
907 /**
908 * Returns true if this value is a 32-bit signed integer.
909 */
Steve Block8defd9f2010-07-08 12:39:36 +0100910 V8EXPORT bool IsInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000911
912 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100913 * Returns true if this value is a 32-bit unsigned integer.
914 */
Steve Block8defd9f2010-07-08 12:39:36 +0100915 V8EXPORT bool IsUint32() const;
Steve Block6ded16b2010-05-10 14:33:55 +0100916
917 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000918 * Returns true if this value is a Date.
919 */
Steve Block8defd9f2010-07-08 12:39:36 +0100920 V8EXPORT bool IsDate() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000921
Iain Merrick75681382010-08-19 15:07:18 +0100922 /**
923 * Returns true if this value is a RegExp.
924 */
925 V8EXPORT bool IsRegExp() const;
926
Steve Block8defd9f2010-07-08 12:39:36 +0100927 V8EXPORT Local<Boolean> ToBoolean() const;
928 V8EXPORT Local<Number> ToNumber() const;
929 V8EXPORT Local<String> ToString() const;
930 V8EXPORT Local<String> ToDetailString() const;
931 V8EXPORT Local<Object> ToObject() const;
932 V8EXPORT Local<Integer> ToInteger() const;
933 V8EXPORT Local<Uint32> ToUint32() const;
934 V8EXPORT Local<Int32> ToInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000935
936 /**
937 * Attempts to convert a string to an array index.
938 * Returns an empty handle if the conversion fails.
939 */
Steve Block8defd9f2010-07-08 12:39:36 +0100940 V8EXPORT Local<Uint32> ToArrayIndex() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000941
Steve Block8defd9f2010-07-08 12:39:36 +0100942 V8EXPORT bool BooleanValue() const;
943 V8EXPORT double NumberValue() const;
944 V8EXPORT int64_t IntegerValue() const;
945 V8EXPORT uint32_t Uint32Value() const;
946 V8EXPORT int32_t Int32Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000947
948 /** JS == */
Steve Block8defd9f2010-07-08 12:39:36 +0100949 V8EXPORT bool Equals(Handle<Value> that) const;
950 V8EXPORT bool StrictEquals(Handle<Value> that) const;
Steve Block3ce2e202009-11-05 08:53:23 +0000951
Steve Blocka7e24c12009-10-30 11:49:00 +0000952 private:
953 inline bool QuickIsString() const;
Steve Block8defd9f2010-07-08 12:39:36 +0100954 V8EXPORT bool FullIsString() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000955};
956
957
958/**
959 * The superclass of primitive values. See ECMA-262 4.3.2.
960 */
Steve Block8defd9f2010-07-08 12:39:36 +0100961class Primitive : public Value { };
Steve Blocka7e24c12009-10-30 11:49:00 +0000962
963
964/**
965 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
966 * or false value.
967 */
Steve Block8defd9f2010-07-08 12:39:36 +0100968class Boolean : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000969 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100970 V8EXPORT bool Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000971 static inline Handle<Boolean> New(bool value);
972};
973
974
975/**
976 * A JavaScript string value (ECMA-262, 4.3.17).
977 */
Steve Block8defd9f2010-07-08 12:39:36 +0100978class String : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000979 public:
980
981 /**
982 * Returns the number of characters in this string.
983 */
Steve Block8defd9f2010-07-08 12:39:36 +0100984 V8EXPORT int Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000985
986 /**
987 * Returns the number of bytes in the UTF-8 encoded
988 * representation of this string.
989 */
Steve Block8defd9f2010-07-08 12:39:36 +0100990 V8EXPORT int Utf8Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000991
992 /**
993 * Write the contents of the string to an external buffer.
994 * If no arguments are given, expects the buffer to be large
995 * enough to hold the entire string and NULL terminator. Copies
996 * the contents of the string and the NULL terminator into the
997 * buffer.
998 *
999 * Copies up to length characters into the output buffer.
1000 * Only null-terminates if there is enough space in the buffer.
1001 *
1002 * \param buffer The buffer into which the string will be copied.
1003 * \param start The starting position within the string at which
1004 * copying begins.
1005 * \param length The number of bytes to copy from the string.
Steve Block6ded16b2010-05-10 14:33:55 +01001006 * \param nchars_ref The number of characters written, can be NULL.
1007 * \param hints Various hints that might affect performance of this or
1008 * subsequent operations.
1009 * \return The number of bytes copied to the buffer
Steve Blocka7e24c12009-10-30 11:49:00 +00001010 * excluding the NULL terminator.
1011 */
Steve Block6ded16b2010-05-10 14:33:55 +01001012 enum WriteHints {
1013 NO_HINTS = 0,
1014 HINT_MANY_WRITES_EXPECTED = 1
1015 };
1016
Steve Block8defd9f2010-07-08 12:39:36 +01001017 V8EXPORT int Write(uint16_t* buffer,
1018 int start = 0,
1019 int length = -1,
1020 WriteHints hints = NO_HINTS) const; // UTF-16
1021 V8EXPORT int WriteAscii(char* buffer,
1022 int start = 0,
1023 int length = -1,
1024 WriteHints hints = NO_HINTS) const; // ASCII
1025 V8EXPORT int WriteUtf8(char* buffer,
1026 int length = -1,
1027 int* nchars_ref = NULL,
1028 WriteHints hints = NO_HINTS) const; // UTF-8
Steve Blocka7e24c12009-10-30 11:49:00 +00001029
1030 /**
1031 * A zero length string.
1032 */
Steve Block8defd9f2010-07-08 12:39:36 +01001033 V8EXPORT static v8::Local<v8::String> Empty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001034
1035 /**
1036 * Returns true if the string is external
1037 */
Steve Block8defd9f2010-07-08 12:39:36 +01001038 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001039
1040 /**
1041 * Returns true if the string is both external and ascii
1042 */
Steve Block8defd9f2010-07-08 12:39:36 +01001043 V8EXPORT bool IsExternalAscii() const;
Leon Clarkee46be812010-01-19 14:06:41 +00001044
1045 class V8EXPORT ExternalStringResourceBase {
1046 public:
1047 virtual ~ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001048
Leon Clarkee46be812010-01-19 14:06:41 +00001049 protected:
1050 ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001051
1052 /**
1053 * Internally V8 will call this Dispose method when the external string
1054 * resource is no longer needed. The default implementation will use the
1055 * delete operator. This method can be overridden in subclasses to
1056 * control how allocated external string resources are disposed.
1057 */
1058 virtual void Dispose() { delete this; }
1059
Leon Clarkee46be812010-01-19 14:06:41 +00001060 private:
1061 // Disallow copying and assigning.
1062 ExternalStringResourceBase(const ExternalStringResourceBase&);
1063 void operator=(const ExternalStringResourceBase&);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001064
1065 friend class v8::internal::Heap;
Leon Clarkee46be812010-01-19 14:06:41 +00001066 };
1067
Steve Blocka7e24c12009-10-30 11:49:00 +00001068 /**
1069 * An ExternalStringResource is a wrapper around a two-byte string
1070 * buffer that resides outside V8's heap. Implement an
1071 * ExternalStringResource to manage the life cycle of the underlying
1072 * buffer. Note that the string data must be immutable.
1073 */
Leon Clarkee46be812010-01-19 14:06:41 +00001074 class V8EXPORT ExternalStringResource
1075 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001076 public:
1077 /**
1078 * Override the destructor to manage the life cycle of the underlying
1079 * buffer.
1080 */
1081 virtual ~ExternalStringResource() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001082
1083 /**
1084 * The string data from the underlying buffer.
1085 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001086 virtual const uint16_t* data() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001087
1088 /**
1089 * The length of the string. That is, the number of two-byte characters.
1090 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001091 virtual size_t length() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001092
Steve Blocka7e24c12009-10-30 11:49:00 +00001093 protected:
1094 ExternalStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001095 };
1096
1097 /**
1098 * An ExternalAsciiStringResource is a wrapper around an ascii
1099 * string buffer that resides outside V8's heap. Implement an
1100 * ExternalAsciiStringResource to manage the life cycle of the
1101 * underlying buffer. Note that the string data must be immutable
1102 * and that the data must be strict 7-bit ASCII, not Latin1 or
1103 * UTF-8, which would require special treatment internally in the
1104 * engine and, in the case of UTF-8, do not allow efficient indexing.
1105 * Use String::New or convert to 16 bit data for non-ASCII.
1106 */
1107
Leon Clarkee46be812010-01-19 14:06:41 +00001108 class V8EXPORT ExternalAsciiStringResource
1109 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001110 public:
1111 /**
1112 * Override the destructor to manage the life cycle of the underlying
1113 * buffer.
1114 */
1115 virtual ~ExternalAsciiStringResource() {}
1116 /** The string data from the underlying buffer.*/
1117 virtual const char* data() const = 0;
1118 /** The number of ascii characters in the string.*/
1119 virtual size_t length() const = 0;
1120 protected:
1121 ExternalAsciiStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001122 };
1123
1124 /**
1125 * Get the ExternalStringResource for an external string. Returns
1126 * NULL if IsExternal() doesn't return true.
1127 */
1128 inline ExternalStringResource* GetExternalStringResource() const;
1129
1130 /**
1131 * Get the ExternalAsciiStringResource for an external ascii string.
1132 * Returns NULL if IsExternalAscii() doesn't return true.
1133 */
Steve Block8defd9f2010-07-08 12:39:36 +01001134 V8EXPORT ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001135
1136 static inline String* Cast(v8::Value* obj);
1137
1138 /**
1139 * Allocates a new string from either utf-8 encoded or ascii data.
1140 * The second parameter 'length' gives the buffer length.
1141 * If the data is utf-8 encoded, the caller must
1142 * be careful to supply the length parameter.
1143 * If it is not given, the function calls
1144 * 'strlen' to determine the buffer length, it might be
1145 * wrong if 'data' contains a null character.
1146 */
Steve Block8defd9f2010-07-08 12:39:36 +01001147 V8EXPORT static Local<String> New(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001148
1149 /** Allocates a new string from utf16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001150 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001151
1152 /** Creates a symbol. Returns one if it exists already.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001153 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001154
1155 /**
Steve Block3ce2e202009-11-05 08:53:23 +00001156 * Creates a new string by concatenating the left and the right strings
1157 * passed in as parameters.
1158 */
Steve Block8defd9f2010-07-08 12:39:36 +01001159 V8EXPORT static Local<String> Concat(Handle<String> left,
1160 Handle<String>right);
Steve Block3ce2e202009-11-05 08:53:23 +00001161
1162 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001163 * Creates a new external string using the data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001164 * resource. When the external string is no longer live on V8's heap the
1165 * resource will be disposed by calling its Dispose method. The caller of
1166 * this function should not otherwise delete or modify the resource. Neither
1167 * should the underlying buffer be deallocated or modified except through the
1168 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001169 */
Steve Block8defd9f2010-07-08 12:39:36 +01001170 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001171
1172 /**
1173 * Associate an external string resource with this string by transforming it
1174 * in place so that existing references to this string in the JavaScript heap
1175 * will use the external string resource. The external string resource's
1176 * character contents needs to be equivalent to this string.
1177 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001178 * The string is not modified if the operation fails. See NewExternal for
1179 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001180 */
Steve Block8defd9f2010-07-08 12:39:36 +01001181 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001182
1183 /**
1184 * Creates a new external string using the ascii data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001185 * resource. When the external string is no longer live on V8's heap the
1186 * resource will be disposed by calling its Dispose method. The caller of
1187 * this function should not otherwise delete or modify the resource. Neither
1188 * should the underlying buffer be deallocated or modified except through the
1189 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001190 */
Steve Block8defd9f2010-07-08 12:39:36 +01001191 V8EXPORT static Local<String> NewExternal(
1192 ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001193
1194 /**
1195 * Associate an external string resource with this string by transforming it
1196 * in place so that existing references to this string in the JavaScript heap
1197 * will use the external string resource. The external string resource's
1198 * character contents needs to be equivalent to this string.
1199 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001200 * The string is not modified if the operation fails. See NewExternal for
1201 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001202 */
Steve Block8defd9f2010-07-08 12:39:36 +01001203 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001204
1205 /**
1206 * Returns true if this string can be made external.
1207 */
Steve Block8defd9f2010-07-08 12:39:36 +01001208 V8EXPORT bool CanMakeExternal();
Steve Blocka7e24c12009-10-30 11:49:00 +00001209
1210 /** Creates an undetectable string from the supplied ascii or utf-8 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001211 V8EXPORT static Local<String> NewUndetectable(const char* data,
1212 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001213
1214 /** Creates an undetectable string from the supplied utf-16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001215 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1216 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001217
1218 /**
1219 * Converts an object to a utf8-encoded character array. Useful if
1220 * you want to print the object. If conversion to a string fails
1221 * (eg. due to an exception in the toString() method of the object)
1222 * then the length() method returns 0 and the * operator returns
1223 * NULL.
1224 */
1225 class V8EXPORT Utf8Value {
1226 public:
1227 explicit Utf8Value(Handle<v8::Value> obj);
1228 ~Utf8Value();
1229 char* operator*() { return str_; }
1230 const char* operator*() const { return str_; }
1231 int length() const { return length_; }
1232 private:
1233 char* str_;
1234 int length_;
1235
1236 // Disallow copying and assigning.
1237 Utf8Value(const Utf8Value&);
1238 void operator=(const Utf8Value&);
1239 };
1240
1241 /**
1242 * Converts an object to an ascii string.
1243 * Useful if you want to print the object.
1244 * If conversion to a string fails (eg. due to an exception in the toString()
1245 * method of the object) then the length() method returns 0 and the * operator
1246 * returns NULL.
1247 */
1248 class V8EXPORT AsciiValue {
1249 public:
1250 explicit AsciiValue(Handle<v8::Value> obj);
1251 ~AsciiValue();
1252 char* operator*() { return str_; }
1253 const char* operator*() const { return str_; }
1254 int length() const { return length_; }
1255 private:
1256 char* str_;
1257 int length_;
1258
1259 // Disallow copying and assigning.
1260 AsciiValue(const AsciiValue&);
1261 void operator=(const AsciiValue&);
1262 };
1263
1264 /**
1265 * Converts an object to a two-byte string.
1266 * If conversion to a string fails (eg. due to an exception in the toString()
1267 * method of the object) then the length() method returns 0 and the * operator
1268 * returns NULL.
1269 */
1270 class V8EXPORT Value {
1271 public:
1272 explicit Value(Handle<v8::Value> obj);
1273 ~Value();
1274 uint16_t* operator*() { return str_; }
1275 const uint16_t* operator*() const { return str_; }
1276 int length() const { return length_; }
1277 private:
1278 uint16_t* str_;
1279 int length_;
1280
1281 // Disallow copying and assigning.
1282 Value(const Value&);
1283 void operator=(const Value&);
1284 };
Steve Block3ce2e202009-11-05 08:53:23 +00001285
Steve Blocka7e24c12009-10-30 11:49:00 +00001286 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001287 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1288 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001289};
1290
1291
1292/**
1293 * A JavaScript number value (ECMA-262, 4.3.20)
1294 */
Steve Block8defd9f2010-07-08 12:39:36 +01001295class Number : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001296 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001297 V8EXPORT double Value() const;
1298 V8EXPORT static Local<Number> New(double value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001299 static inline Number* Cast(v8::Value* obj);
1300 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001301 V8EXPORT Number();
Steve Blocka7e24c12009-10-30 11:49:00 +00001302 static void CheckCast(v8::Value* obj);
1303};
1304
1305
1306/**
1307 * A JavaScript value representing a signed integer.
1308 */
Steve Block8defd9f2010-07-08 12:39:36 +01001309class Integer : public Number {
Steve Blocka7e24c12009-10-30 11:49:00 +00001310 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001311 V8EXPORT static Local<Integer> New(int32_t value);
1312 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1313 V8EXPORT int64_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001314 static inline Integer* Cast(v8::Value* obj);
1315 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001316 V8EXPORT Integer();
1317 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001318};
1319
1320
1321/**
1322 * A JavaScript value representing a 32-bit signed integer.
1323 */
Steve Block8defd9f2010-07-08 12:39:36 +01001324class Int32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001325 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001326 V8EXPORT int32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001327 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001328 V8EXPORT Int32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001329};
1330
1331
1332/**
1333 * A JavaScript value representing a 32-bit unsigned integer.
1334 */
Steve Block8defd9f2010-07-08 12:39:36 +01001335class Uint32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001336 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001337 V8EXPORT uint32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001338 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001339 V8EXPORT Uint32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001340};
1341
1342
1343/**
1344 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1345 */
Steve Block8defd9f2010-07-08 12:39:36 +01001346class Date : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001347 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001348 V8EXPORT static Local<Value> New(double time);
Steve Blocka7e24c12009-10-30 11:49:00 +00001349
1350 /**
1351 * A specialization of Value::NumberValue that is more efficient
1352 * because we know the structure of this object.
1353 */
Steve Block8defd9f2010-07-08 12:39:36 +01001354 V8EXPORT double NumberValue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001355
1356 static inline Date* Cast(v8::Value* obj);
1357 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001358 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001359};
1360
1361
1362enum PropertyAttribute {
1363 None = 0,
1364 ReadOnly = 1 << 0,
1365 DontEnum = 1 << 1,
1366 DontDelete = 1 << 2
1367};
1368
Steve Block3ce2e202009-11-05 08:53:23 +00001369enum ExternalArrayType {
1370 kExternalByteArray = 1,
1371 kExternalUnsignedByteArray,
1372 kExternalShortArray,
1373 kExternalUnsignedShortArray,
1374 kExternalIntArray,
1375 kExternalUnsignedIntArray,
1376 kExternalFloatArray
1377};
1378
Steve Blocka7e24c12009-10-30 11:49:00 +00001379/**
Leon Clarkef7060e22010-06-03 12:02:55 +01001380 * Accessor[Getter|Setter] are used as callback functions when
1381 * setting|getting a particular property. See Object and ObjectTemplate's
1382 * method SetAccessor.
1383 */
1384typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1385 const AccessorInfo& info);
1386
1387
1388typedef void (*AccessorSetter)(Local<String> property,
1389 Local<Value> value,
1390 const AccessorInfo& info);
1391
1392
1393/**
1394 * Access control specifications.
1395 *
1396 * Some accessors should be accessible across contexts. These
1397 * accessors have an explicit access control parameter which specifies
1398 * the kind of cross-context access that should be allowed.
1399 *
1400 * Additionally, for security, accessors can prohibit overwriting by
1401 * accessors defined in JavaScript. For objects that have such
1402 * accessors either locally or in their prototype chain it is not
1403 * possible to overwrite the accessor by using __defineGetter__ or
1404 * __defineSetter__ from JavaScript code.
1405 */
1406enum AccessControl {
1407 DEFAULT = 0,
1408 ALL_CAN_READ = 1,
1409 ALL_CAN_WRITE = 1 << 1,
1410 PROHIBITS_OVERWRITING = 1 << 2
1411};
1412
1413
1414/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001415 * A JavaScript object (ECMA-262, 4.3.3)
1416 */
Steve Block8defd9f2010-07-08 12:39:36 +01001417class Object : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001418 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001419 V8EXPORT bool Set(Handle<Value> key,
1420 Handle<Value> value,
1421 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001422
Steve Block8defd9f2010-07-08 12:39:36 +01001423 V8EXPORT bool Set(uint32_t index,
1424 Handle<Value> value);
Steve Block6ded16b2010-05-10 14:33:55 +01001425
Steve Blocka7e24c12009-10-30 11:49:00 +00001426 // Sets a local property on this object bypassing interceptors and
1427 // overriding accessors or read-only properties.
1428 //
1429 // Note that if the object has an interceptor the property will be set
1430 // locally, but since the interceptor takes precedence the local property
1431 // will only be returned if the interceptor doesn't return a value.
1432 //
1433 // Note also that this only works for named properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001434 V8EXPORT bool ForceSet(Handle<Value> key,
1435 Handle<Value> value,
1436 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001437
Steve Block8defd9f2010-07-08 12:39:36 +01001438 V8EXPORT Local<Value> Get(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001439
Steve Block8defd9f2010-07-08 12:39:36 +01001440 V8EXPORT Local<Value> Get(uint32_t index);
Steve Block6ded16b2010-05-10 14:33:55 +01001441
Steve Blocka7e24c12009-10-30 11:49:00 +00001442 // TODO(1245389): Replace the type-specific versions of these
1443 // functions with generic ones that accept a Handle<Value> key.
Steve Block8defd9f2010-07-08 12:39:36 +01001444 V8EXPORT bool Has(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001445
Steve Block8defd9f2010-07-08 12:39:36 +01001446 V8EXPORT bool Delete(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001447
1448 // Delete a property on this object bypassing interceptors and
1449 // ignoring dont-delete attributes.
Steve Block8defd9f2010-07-08 12:39:36 +01001450 V8EXPORT bool ForceDelete(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001451
Steve Block8defd9f2010-07-08 12:39:36 +01001452 V8EXPORT bool Has(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001453
Steve Block8defd9f2010-07-08 12:39:36 +01001454 V8EXPORT bool Delete(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001455
Steve Block8defd9f2010-07-08 12:39:36 +01001456 V8EXPORT bool SetAccessor(Handle<String> name,
1457 AccessorGetter getter,
1458 AccessorSetter setter = 0,
1459 Handle<Value> data = Handle<Value>(),
1460 AccessControl settings = DEFAULT,
1461 PropertyAttribute attribute = None);
Leon Clarkef7060e22010-06-03 12:02:55 +01001462
Steve Blocka7e24c12009-10-30 11:49:00 +00001463 /**
1464 * Returns an array containing the names of the enumerable properties
1465 * of this object, including properties from prototype objects. The
1466 * array returned by this method contains the same values as would
1467 * be enumerated by a for-in statement over this object.
1468 */
Steve Block8defd9f2010-07-08 12:39:36 +01001469 V8EXPORT Local<Array> GetPropertyNames();
Steve Blocka7e24c12009-10-30 11:49:00 +00001470
1471 /**
1472 * Get the prototype object. This does not skip objects marked to
1473 * be skipped by __proto__ and it does not consult the security
1474 * handler.
1475 */
Steve Block8defd9f2010-07-08 12:39:36 +01001476 V8EXPORT Local<Value> GetPrototype();
Steve Blocka7e24c12009-10-30 11:49:00 +00001477
1478 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001479 * Set the prototype object. This does not skip objects marked to
1480 * be skipped by __proto__ and it does not consult the security
1481 * handler.
1482 */
Steve Block8defd9f2010-07-08 12:39:36 +01001483 V8EXPORT bool SetPrototype(Handle<Value> prototype);
Andrei Popescu402d9372010-02-26 13:31:12 +00001484
1485 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001486 * Finds an instance of the given function template in the prototype
1487 * chain.
1488 */
Steve Block8defd9f2010-07-08 12:39:36 +01001489 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1490 Handle<FunctionTemplate> tmpl);
Steve Blocka7e24c12009-10-30 11:49:00 +00001491
1492 /**
1493 * Call builtin Object.prototype.toString on this object.
1494 * This is different from Value::ToString() that may call
1495 * user-defined toString function. This one does not.
1496 */
Steve Block8defd9f2010-07-08 12:39:36 +01001497 V8EXPORT Local<String> ObjectProtoToString();
Steve Blocka7e24c12009-10-30 11:49:00 +00001498
1499 /** Gets the number of internal fields for this Object. */
Steve Block8defd9f2010-07-08 12:39:36 +01001500 V8EXPORT int InternalFieldCount();
Steve Blocka7e24c12009-10-30 11:49:00 +00001501 /** Gets the value in an internal field. */
1502 inline Local<Value> GetInternalField(int index);
1503 /** Sets the value in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001504 V8EXPORT void SetInternalField(int index, Handle<Value> value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001505
1506 /** Gets a native pointer from an internal field. */
1507 inline void* GetPointerFromInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001508
Steve Blocka7e24c12009-10-30 11:49:00 +00001509 /** Sets a native pointer in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001510 V8EXPORT void SetPointerInInternalField(int index, void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001511
1512 // Testers for local properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001513 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1514 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1515 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001516
1517 /**
1518 * If result.IsEmpty() no real property was located in the prototype chain.
1519 * This means interceptors in the prototype chain are not called.
1520 */
Steve Block8defd9f2010-07-08 12:39:36 +01001521 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1522 Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001523
1524 /**
1525 * If result.IsEmpty() no real property was located on the object or
1526 * in the prototype chain.
1527 * This means interceptors in the prototype chain are not called.
1528 */
Steve Block8defd9f2010-07-08 12:39:36 +01001529 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001530
1531 /** Tests for a named lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001532 V8EXPORT bool HasNamedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001533
1534 /** Tests for an index lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001535 V8EXPORT bool HasIndexedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001536
1537 /**
1538 * Turns on access check on the object if the object is an instance of
1539 * a template that has access check callbacks. If an object has no
1540 * access check info, the object cannot be accessed by anyone.
1541 */
Steve Block8defd9f2010-07-08 12:39:36 +01001542 V8EXPORT void TurnOnAccessCheck();
Steve Blocka7e24c12009-10-30 11:49:00 +00001543
1544 /**
1545 * Returns the identity hash for this object. The current implemenation uses
1546 * a hidden property on the object to store the identity hash.
1547 *
1548 * The return value will never be 0. Also, it is not guaranteed to be
1549 * unique.
1550 */
Steve Block8defd9f2010-07-08 12:39:36 +01001551 V8EXPORT int GetIdentityHash();
Steve Blocka7e24c12009-10-30 11:49:00 +00001552
1553 /**
1554 * Access hidden properties on JavaScript objects. These properties are
1555 * hidden from the executing JavaScript and only accessible through the V8
1556 * C++ API. Hidden properties introduced by V8 internally (for example the
1557 * identity hash) are prefixed with "v8::".
1558 */
Steve Block8defd9f2010-07-08 12:39:36 +01001559 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1560 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1561 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
Steve Block3ce2e202009-11-05 08:53:23 +00001562
Steve Blocka7e24c12009-10-30 11:49:00 +00001563 /**
1564 * Returns true if this is an instance of an api function (one
1565 * created from a function created from a function template) and has
1566 * been modified since it was created. Note that this method is
1567 * conservative and may return true for objects that haven't actually
1568 * been modified.
1569 */
Steve Block8defd9f2010-07-08 12:39:36 +01001570 V8EXPORT bool IsDirty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001571
1572 /**
1573 * Clone this object with a fast but shallow copy. Values will point
1574 * to the same values as the original object.
1575 */
Steve Block8defd9f2010-07-08 12:39:36 +01001576 V8EXPORT Local<Object> Clone();
Steve Blocka7e24c12009-10-30 11:49:00 +00001577
1578 /**
1579 * Set the backing store of the indexed properties to be managed by the
1580 * embedding layer. Access to the indexed properties will follow the rules
1581 * spelled out in CanvasPixelArray.
1582 * Note: The embedding program still owns the data and needs to ensure that
1583 * the backing store is preserved while V8 has a reference.
1584 */
Steve Block8defd9f2010-07-08 12:39:36 +01001585 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001586 bool HasIndexedPropertiesInPixelData();
1587 uint8_t* GetIndexedPropertiesPixelData();
1588 int GetIndexedPropertiesPixelDataLength();
Steve Blocka7e24c12009-10-30 11:49:00 +00001589
Steve Block3ce2e202009-11-05 08:53:23 +00001590 /**
1591 * Set the backing store of the indexed properties to be managed by the
1592 * embedding layer. Access to the indexed properties will follow the rules
1593 * spelled out for the CanvasArray subtypes in the WebGL specification.
1594 * Note: The embedding program still owns the data and needs to ensure that
1595 * the backing store is preserved while V8 has a reference.
1596 */
Steve Block8defd9f2010-07-08 12:39:36 +01001597 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1598 void* data,
1599 ExternalArrayType array_type,
1600 int number_of_elements);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001601 bool HasIndexedPropertiesInExternalArrayData();
1602 void* GetIndexedPropertiesExternalArrayData();
1603 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1604 int GetIndexedPropertiesExternalArrayDataLength();
Steve Block3ce2e202009-11-05 08:53:23 +00001605
Steve Block8defd9f2010-07-08 12:39:36 +01001606 V8EXPORT static Local<Object> New();
Steve Blocka7e24c12009-10-30 11:49:00 +00001607 static inline Object* Cast(Value* obj);
1608 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001609 V8EXPORT Object();
1610 V8EXPORT static void CheckCast(Value* obj);
1611 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1612 V8EXPORT void* SlowGetPointerFromInternalField(int index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001613
1614 /**
1615 * If quick access to the internal field is possible this method
Steve Block3ce2e202009-11-05 08:53:23 +00001616 * returns the value. Otherwise an empty handle is returned.
Steve Blocka7e24c12009-10-30 11:49:00 +00001617 */
1618 inline Local<Value> UncheckedGetInternalField(int index);
1619};
1620
1621
1622/**
1623 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1624 */
Steve Block8defd9f2010-07-08 12:39:36 +01001625class Array : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001626 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001627 V8EXPORT uint32_t Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001628
1629 /**
1630 * Clones an element at index |index|. Returns an empty
1631 * handle if cloning fails (for any reason).
1632 */
Steve Block8defd9f2010-07-08 12:39:36 +01001633 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001634
Steve Block8defd9f2010-07-08 12:39:36 +01001635 V8EXPORT static Local<Array> New(int length = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001636 static inline Array* Cast(Value* obj);
1637 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001638 V8EXPORT Array();
Steve Blocka7e24c12009-10-30 11:49:00 +00001639 static void CheckCast(Value* obj);
1640};
1641
1642
1643/**
1644 * A JavaScript function object (ECMA-262, 15.3).
1645 */
Steve Block8defd9f2010-07-08 12:39:36 +01001646class Function : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001647 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001648 V8EXPORT Local<Object> NewInstance() const;
1649 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1650 V8EXPORT Local<Value> Call(Handle<Object> recv,
1651 int argc,
1652 Handle<Value> argv[]);
1653 V8EXPORT void SetName(Handle<String> name);
1654 V8EXPORT Handle<Value> GetName() const;
Andrei Popescu402d9372010-02-26 13:31:12 +00001655
1656 /**
1657 * Returns zero based line number of function body and
1658 * kLineOffsetNotFound if no information available.
1659 */
Steve Block8defd9f2010-07-08 12:39:36 +01001660 V8EXPORT int GetScriptLineNumber() const;
1661 V8EXPORT ScriptOrigin GetScriptOrigin() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001662 static inline Function* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001663 V8EXPORT static const int kLineOffsetNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00001664 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001665 V8EXPORT Function();
1666 V8EXPORT static void CheckCast(Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001667};
1668
1669
1670/**
1671 * A JavaScript value that wraps a C++ void*. This type of value is
1672 * mainly used to associate C++ data structures with JavaScript
1673 * objects.
1674 *
1675 * The Wrap function V8 will return the most optimal Value object wrapping the
1676 * C++ void*. The type of the value is not guaranteed to be an External object
1677 * and no assumptions about its type should be made. To access the wrapped
1678 * value Unwrap should be used, all other operations on that object will lead
1679 * to unpredictable results.
1680 */
Steve Block8defd9f2010-07-08 12:39:36 +01001681class External : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001682 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001683 V8EXPORT static Local<Value> Wrap(void* data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001684 static inline void* Unwrap(Handle<Value> obj);
1685
Steve Block8defd9f2010-07-08 12:39:36 +01001686 V8EXPORT static Local<External> New(void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001687 static inline External* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001688 V8EXPORT void* Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001689 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001690 V8EXPORT External();
1691 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001692 static inline void* QuickUnwrap(Handle<v8::Value> obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001693 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001694};
1695
1696
1697// --- T e m p l a t e s ---
1698
1699
1700/**
1701 * The superclass of object and function templates.
1702 */
1703class V8EXPORT Template : public Data {
1704 public:
1705 /** Adds a property to each instance created by this template.*/
1706 void Set(Handle<String> name, Handle<Data> value,
1707 PropertyAttribute attributes = None);
1708 inline void Set(const char* name, Handle<Data> value);
1709 private:
1710 Template();
1711
1712 friend class ObjectTemplate;
1713 friend class FunctionTemplate;
1714};
1715
1716
1717/**
1718 * The argument information given to function call callbacks. This
1719 * class provides access to information about the context of the call,
1720 * including the receiver, the number and values of arguments, and
1721 * the holder of the function.
1722 */
Steve Block8defd9f2010-07-08 12:39:36 +01001723class Arguments {
Steve Blocka7e24c12009-10-30 11:49:00 +00001724 public:
1725 inline int Length() const;
1726 inline Local<Value> operator[](int i) const;
1727 inline Local<Function> Callee() const;
1728 inline Local<Object> This() const;
1729 inline Local<Object> Holder() const;
1730 inline bool IsConstructCall() const;
1731 inline Local<Value> Data() const;
1732 private:
Steve Blocka7e24c12009-10-30 11:49:00 +00001733 friend class ImplementationUtilities;
1734 inline Arguments(Local<Value> data,
1735 Local<Object> holder,
1736 Local<Function> callee,
1737 bool is_construct_call,
1738 void** values, int length);
1739 Local<Value> data_;
1740 Local<Object> holder_;
1741 Local<Function> callee_;
1742 bool is_construct_call_;
1743 void** values_;
1744 int length_;
1745};
1746
1747
1748/**
1749 * The information passed to an accessor callback about the context
1750 * of the property access.
1751 */
1752class V8EXPORT AccessorInfo {
1753 public:
1754 inline AccessorInfo(internal::Object** args)
1755 : args_(args) { }
1756 inline Local<Value> Data() const;
1757 inline Local<Object> This() const;
1758 inline Local<Object> Holder() const;
1759 private:
1760 internal::Object** args_;
1761};
1762
1763
1764typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1765
Steve Blocka7e24c12009-10-30 11:49:00 +00001766/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001767 * NamedProperty[Getter|Setter] are used as interceptors on object.
1768 * See ObjectTemplate::SetNamedPropertyHandler.
1769 */
1770typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
1771 const AccessorInfo& info);
1772
1773
1774/**
1775 * Returns the value if the setter intercepts the request.
1776 * Otherwise, returns an empty handle.
1777 */
1778typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
1779 Local<Value> value,
1780 const AccessorInfo& info);
1781
Steve Blocka7e24c12009-10-30 11:49:00 +00001782/**
1783 * Returns a non-empty handle if the interceptor intercepts the request.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001784 * The result is an integer encoding property attributes (like v8::None,
1785 * v8::DontEnum, etc.)
Steve Blocka7e24c12009-10-30 11:49:00 +00001786 */
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001787typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
1788 const AccessorInfo& info);
Steve Blocka7e24c12009-10-30 11:49:00 +00001789
1790
1791/**
1792 * Returns a non-empty handle if the deleter intercepts the request.
1793 * The return value is true if the property could be deleted and false
1794 * otherwise.
1795 */
1796typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
1797 const AccessorInfo& info);
1798
1799/**
1800 * Returns an array containing the names of the properties the named
1801 * property getter intercepts.
1802 */
1803typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
1804
1805
1806/**
1807 * Returns the value of the property if the getter intercepts the
1808 * request. Otherwise, returns an empty handle.
1809 */
1810typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
1811 const AccessorInfo& info);
1812
1813
1814/**
1815 * Returns the value if the setter intercepts the request.
1816 * Otherwise, returns an empty handle.
1817 */
1818typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
1819 Local<Value> value,
1820 const AccessorInfo& info);
1821
1822
1823/**
1824 * Returns a non-empty handle if the interceptor intercepts the request.
Iain Merrick75681382010-08-19 15:07:18 +01001825 * The result is an integer encoding property attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00001826 */
Iain Merrick75681382010-08-19 15:07:18 +01001827typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
Steve Blocka7e24c12009-10-30 11:49:00 +00001828 const AccessorInfo& info);
1829
1830/**
1831 * Returns a non-empty handle if the deleter intercepts the request.
1832 * The return value is true if the property could be deleted and false
1833 * otherwise.
1834 */
1835typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
1836 const AccessorInfo& info);
1837
1838/**
1839 * Returns an array containing the indices of the properties the
1840 * indexed property getter intercepts.
1841 */
1842typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
1843
1844
1845/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001846 * Access type specification.
1847 */
1848enum AccessType {
1849 ACCESS_GET,
1850 ACCESS_SET,
1851 ACCESS_HAS,
1852 ACCESS_DELETE,
1853 ACCESS_KEYS
1854};
1855
1856
1857/**
1858 * Returns true if cross-context access should be allowed to the named
1859 * property with the given key on the host object.
1860 */
1861typedef bool (*NamedSecurityCallback)(Local<Object> host,
1862 Local<Value> key,
1863 AccessType type,
1864 Local<Value> data);
1865
1866
1867/**
1868 * Returns true if cross-context access should be allowed to the indexed
1869 * property with the given index on the host object.
1870 */
1871typedef bool (*IndexedSecurityCallback)(Local<Object> host,
1872 uint32_t index,
1873 AccessType type,
1874 Local<Value> data);
1875
1876
1877/**
1878 * A FunctionTemplate is used to create functions at runtime. There
1879 * can only be one function created from a FunctionTemplate in a
1880 * context. The lifetime of the created function is equal to the
1881 * lifetime of the context. So in case the embedder needs to create
1882 * temporary functions that can be collected using Scripts is
1883 * preferred.
1884 *
1885 * A FunctionTemplate can have properties, these properties are added to the
1886 * function object when it is created.
1887 *
1888 * A FunctionTemplate has a corresponding instance template which is
1889 * used to create object instances when the function is used as a
1890 * constructor. Properties added to the instance template are added to
1891 * each object instance.
1892 *
1893 * A FunctionTemplate can have a prototype template. The prototype template
1894 * is used to create the prototype object of the function.
1895 *
1896 * The following example shows how to use a FunctionTemplate:
1897 *
1898 * \code
1899 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
1900 * t->Set("func_property", v8::Number::New(1));
1901 *
1902 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
1903 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
1904 * proto_t->Set("proto_const", v8::Number::New(2));
1905 *
1906 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
1907 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
1908 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
1909 * instance_t->Set("instance_property", Number::New(3));
1910 *
1911 * v8::Local<v8::Function> function = t->GetFunction();
1912 * v8::Local<v8::Object> instance = function->NewInstance();
1913 * \endcode
1914 *
1915 * Let's use "function" as the JS variable name of the function object
1916 * and "instance" for the instance object created above. The function
1917 * and the instance will have the following properties:
1918 *
1919 * \code
1920 * func_property in function == true;
1921 * function.func_property == 1;
1922 *
1923 * function.prototype.proto_method() invokes 'InvokeCallback'
1924 * function.prototype.proto_const == 2;
1925 *
1926 * instance instanceof function == true;
1927 * instance.instance_accessor calls 'InstanceAccessorCallback'
1928 * instance.instance_property == 3;
1929 * \endcode
1930 *
1931 * A FunctionTemplate can inherit from another one by calling the
1932 * FunctionTemplate::Inherit method. The following graph illustrates
1933 * the semantics of inheritance:
1934 *
1935 * \code
1936 * FunctionTemplate Parent -> Parent() . prototype -> { }
1937 * ^ ^
1938 * | Inherit(Parent) | .__proto__
1939 * | |
1940 * FunctionTemplate Child -> Child() . prototype -> { }
1941 * \endcode
1942 *
1943 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
1944 * object of the Child() function has __proto__ pointing to the
1945 * Parent() function's prototype object. An instance of the Child
1946 * function has all properties on Parent's instance templates.
1947 *
1948 * Let Parent be the FunctionTemplate initialized in the previous
1949 * section and create a Child FunctionTemplate by:
1950 *
1951 * \code
1952 * Local<FunctionTemplate> parent = t;
1953 * Local<FunctionTemplate> child = FunctionTemplate::New();
1954 * child->Inherit(parent);
1955 *
1956 * Local<Function> child_function = child->GetFunction();
1957 * Local<Object> child_instance = child_function->NewInstance();
1958 * \endcode
1959 *
1960 * The Child function and Child instance will have the following
1961 * properties:
1962 *
1963 * \code
1964 * child_func.prototype.__proto__ == function.prototype;
1965 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
1966 * child_instance.instance_property == 3;
1967 * \endcode
1968 */
1969class V8EXPORT FunctionTemplate : public Template {
1970 public:
1971 /** Creates a function template.*/
1972 static Local<FunctionTemplate> New(
1973 InvocationCallback callback = 0,
1974 Handle<Value> data = Handle<Value>(),
1975 Handle<Signature> signature = Handle<Signature>());
1976 /** Returns the unique function instance in the current execution context.*/
1977 Local<Function> GetFunction();
1978
1979 /**
1980 * Set the call-handler callback for a FunctionTemplate. This
1981 * callback is called whenever the function created from this
1982 * FunctionTemplate is called.
1983 */
1984 void SetCallHandler(InvocationCallback callback,
1985 Handle<Value> data = Handle<Value>());
1986
1987 /** Get the InstanceTemplate. */
1988 Local<ObjectTemplate> InstanceTemplate();
1989
1990 /** Causes the function template to inherit from a parent function template.*/
1991 void Inherit(Handle<FunctionTemplate> parent);
1992
1993 /**
1994 * A PrototypeTemplate is the template used to create the prototype object
1995 * of the function created by this template.
1996 */
1997 Local<ObjectTemplate> PrototypeTemplate();
1998
1999
2000 /**
2001 * Set the class name of the FunctionTemplate. This is used for
2002 * printing objects created with the function created from the
2003 * FunctionTemplate as its constructor.
2004 */
2005 void SetClassName(Handle<String> name);
2006
2007 /**
2008 * Determines whether the __proto__ accessor ignores instances of
2009 * the function template. If instances of the function template are
2010 * ignored, __proto__ skips all instances and instead returns the
2011 * next object in the prototype chain.
2012 *
2013 * Call with a value of true to make the __proto__ accessor ignore
2014 * instances of the function template. Call with a value of false
2015 * to make the __proto__ accessor not ignore instances of the
2016 * function template. By default, instances of a function template
2017 * are not ignored.
2018 */
2019 void SetHiddenPrototype(bool value);
2020
2021 /**
2022 * Returns true if the given object is an instance of this function
2023 * template.
2024 */
2025 bool HasInstance(Handle<Value> object);
2026
2027 private:
2028 FunctionTemplate();
2029 void AddInstancePropertyAccessor(Handle<String> name,
2030 AccessorGetter getter,
2031 AccessorSetter setter,
2032 Handle<Value> data,
2033 AccessControl settings,
2034 PropertyAttribute attributes);
2035 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2036 NamedPropertySetter setter,
2037 NamedPropertyQuery query,
2038 NamedPropertyDeleter remover,
2039 NamedPropertyEnumerator enumerator,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002040 Handle<Value> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00002041 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2042 IndexedPropertySetter setter,
2043 IndexedPropertyQuery query,
2044 IndexedPropertyDeleter remover,
2045 IndexedPropertyEnumerator enumerator,
2046 Handle<Value> data);
2047 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2048 Handle<Value> data);
2049
2050 friend class Context;
2051 friend class ObjectTemplate;
2052};
2053
2054
2055/**
2056 * An ObjectTemplate is used to create objects at runtime.
2057 *
2058 * Properties added to an ObjectTemplate are added to each object
2059 * created from the ObjectTemplate.
2060 */
2061class V8EXPORT ObjectTemplate : public Template {
2062 public:
2063 /** Creates an ObjectTemplate. */
2064 static Local<ObjectTemplate> New();
2065
2066 /** Creates a new instance of this template.*/
2067 Local<Object> NewInstance();
2068
2069 /**
2070 * Sets an accessor on the object template.
2071 *
2072 * Whenever the property with the given name is accessed on objects
2073 * created from this ObjectTemplate the getter and setter callbacks
2074 * are called instead of getting and setting the property directly
2075 * on the JavaScript object.
2076 *
2077 * \param name The name of the property for which an accessor is added.
2078 * \param getter The callback to invoke when getting the property.
2079 * \param setter The callback to invoke when setting the property.
2080 * \param data A piece of data that will be passed to the getter and setter
2081 * callbacks whenever they are invoked.
2082 * \param settings Access control settings for the accessor. This is a bit
2083 * field consisting of one of more of
2084 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2085 * The default is to not allow cross-context access.
2086 * ALL_CAN_READ means that all cross-context reads are allowed.
2087 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2088 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2089 * cross-context access.
2090 * \param attribute The attributes of the property for which an accessor
2091 * is added.
2092 */
2093 void SetAccessor(Handle<String> name,
2094 AccessorGetter getter,
2095 AccessorSetter setter = 0,
2096 Handle<Value> data = Handle<Value>(),
2097 AccessControl settings = DEFAULT,
2098 PropertyAttribute attribute = None);
2099
2100 /**
2101 * Sets a named property handler on the object template.
2102 *
2103 * Whenever a named property is accessed on objects created from
2104 * this object template, the provided callback is invoked instead of
2105 * accessing the property directly on the JavaScript object.
2106 *
2107 * \param getter The callback to invoke when getting a property.
2108 * \param setter The callback to invoke when setting a property.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002109 * \param query The callback to invoke to check if a property is present,
2110 * and if present, get its attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00002111 * \param deleter The callback to invoke when deleting a property.
2112 * \param enumerator The callback to invoke to enumerate all the named
2113 * properties of an object.
2114 * \param data A piece of data that will be passed to the callbacks
2115 * whenever they are invoked.
2116 */
2117 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2118 NamedPropertySetter setter = 0,
2119 NamedPropertyQuery query = 0,
2120 NamedPropertyDeleter deleter = 0,
2121 NamedPropertyEnumerator enumerator = 0,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002122 Handle<Value> data = Handle<Value>());
Steve Blocka7e24c12009-10-30 11:49:00 +00002123
2124 /**
2125 * Sets an indexed property handler on the object template.
2126 *
2127 * Whenever an indexed property is accessed on objects created from
2128 * this object template, the provided callback is invoked instead of
2129 * accessing the property directly on the JavaScript object.
2130 *
2131 * \param getter The callback to invoke when getting a property.
2132 * \param setter The callback to invoke when setting a property.
2133 * \param query The callback to invoke to check is an object has a property.
2134 * \param deleter The callback to invoke when deleting a property.
2135 * \param enumerator The callback to invoke to enumerate all the indexed
2136 * properties of an object.
2137 * \param data A piece of data that will be passed to the callbacks
2138 * whenever they are invoked.
2139 */
2140 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2141 IndexedPropertySetter setter = 0,
2142 IndexedPropertyQuery query = 0,
2143 IndexedPropertyDeleter deleter = 0,
2144 IndexedPropertyEnumerator enumerator = 0,
2145 Handle<Value> data = Handle<Value>());
Iain Merrick75681382010-08-19 15:07:18 +01002146
Steve Blocka7e24c12009-10-30 11:49:00 +00002147 /**
2148 * Sets the callback to be used when calling instances created from
2149 * this template as a function. If no callback is set, instances
2150 * behave like normal JavaScript objects that cannot be called as a
2151 * function.
2152 */
2153 void SetCallAsFunctionHandler(InvocationCallback callback,
2154 Handle<Value> data = Handle<Value>());
2155
2156 /**
2157 * Mark object instances of the template as undetectable.
2158 *
2159 * In many ways, undetectable objects behave as though they are not
2160 * there. They behave like 'undefined' in conditionals and when
2161 * printed. However, properties can be accessed and called as on
2162 * normal objects.
2163 */
2164 void MarkAsUndetectable();
2165
2166 /**
2167 * Sets access check callbacks on the object template.
2168 *
2169 * When accessing properties on instances of this object template,
2170 * the access check callback will be called to determine whether or
2171 * not to allow cross-context access to the properties.
2172 * The last parameter specifies whether access checks are turned
2173 * on by default on instances. If access checks are off by default,
2174 * they can be turned on on individual instances by calling
2175 * Object::TurnOnAccessCheck().
2176 */
2177 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2178 IndexedSecurityCallback indexed_handler,
2179 Handle<Value> data = Handle<Value>(),
2180 bool turned_on_by_default = true);
2181
2182 /**
2183 * Gets the number of internal fields for objects generated from
2184 * this template.
2185 */
2186 int InternalFieldCount();
2187
2188 /**
2189 * Sets the number of internal fields for objects generated from
2190 * this template.
2191 */
2192 void SetInternalFieldCount(int value);
2193
2194 private:
2195 ObjectTemplate();
2196 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2197 friend class FunctionTemplate;
2198};
2199
2200
2201/**
2202 * A Signature specifies which receivers and arguments a function can
2203 * legally be called with.
2204 */
2205class V8EXPORT Signature : public Data {
2206 public:
2207 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2208 Handle<FunctionTemplate>(),
2209 int argc = 0,
2210 Handle<FunctionTemplate> argv[] = 0);
2211 private:
2212 Signature();
2213};
2214
2215
2216/**
2217 * A utility for determining the type of objects based on the template
2218 * they were constructed from.
2219 */
2220class V8EXPORT TypeSwitch : public Data {
2221 public:
2222 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2223 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2224 int match(Handle<Value> value);
2225 private:
2226 TypeSwitch();
2227};
2228
2229
2230// --- E x t e n s i o n s ---
2231
2232
2233/**
2234 * Ignore
2235 */
2236class V8EXPORT Extension { // NOLINT
2237 public:
2238 Extension(const char* name,
2239 const char* source = 0,
2240 int dep_count = 0,
2241 const char** deps = 0);
2242 virtual ~Extension() { }
2243 virtual v8::Handle<v8::FunctionTemplate>
2244 GetNativeFunction(v8::Handle<v8::String> name) {
2245 return v8::Handle<v8::FunctionTemplate>();
2246 }
2247
2248 const char* name() { return name_; }
2249 const char* source() { return source_; }
2250 int dependency_count() { return dep_count_; }
2251 const char** dependencies() { return deps_; }
2252 void set_auto_enable(bool value) { auto_enable_ = value; }
2253 bool auto_enable() { return auto_enable_; }
2254
2255 private:
2256 const char* name_;
2257 const char* source_;
2258 int dep_count_;
2259 const char** deps_;
2260 bool auto_enable_;
2261
2262 // Disallow copying and assigning.
2263 Extension(const Extension&);
2264 void operator=(const Extension&);
2265};
2266
2267
2268void V8EXPORT RegisterExtension(Extension* extension);
2269
2270
2271/**
2272 * Ignore
2273 */
2274class V8EXPORT DeclareExtension {
2275 public:
2276 inline DeclareExtension(Extension* extension) {
2277 RegisterExtension(extension);
2278 }
2279};
2280
2281
2282// --- S t a t i c s ---
2283
2284
2285Handle<Primitive> V8EXPORT Undefined();
2286Handle<Primitive> V8EXPORT Null();
2287Handle<Boolean> V8EXPORT True();
2288Handle<Boolean> V8EXPORT False();
2289
2290
2291/**
2292 * A set of constraints that specifies the limits of the runtime's memory use.
2293 * You must set the heap size before initializing the VM - the size cannot be
2294 * adjusted after the VM is initialized.
2295 *
2296 * If you are using threads then you should hold the V8::Locker lock while
2297 * setting the stack limit and you must set a non-default stack limit separately
2298 * for each thread.
2299 */
2300class V8EXPORT ResourceConstraints {
2301 public:
2302 ResourceConstraints();
2303 int max_young_space_size() const { return max_young_space_size_; }
2304 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2305 int max_old_space_size() const { return max_old_space_size_; }
2306 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
2307 uint32_t* stack_limit() const { return stack_limit_; }
2308 // Sets an address beyond which the VM's stack may not grow.
2309 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2310 private:
2311 int max_young_space_size_;
2312 int max_old_space_size_;
2313 uint32_t* stack_limit_;
2314};
2315
2316
Kristian Monsen25f61362010-05-21 11:50:48 +01002317bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
Steve Blocka7e24c12009-10-30 11:49:00 +00002318
2319
2320// --- E x c e p t i o n s ---
2321
2322
2323typedef void (*FatalErrorCallback)(const char* location, const char* message);
2324
2325
2326typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2327
2328
2329/**
2330 * Schedules an exception to be thrown when returning to JavaScript. When an
2331 * exception has been scheduled it is illegal to invoke any JavaScript
2332 * operation; the caller must return immediately and only after the exception
2333 * has been handled does it become legal to invoke JavaScript operations.
2334 */
2335Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2336
2337/**
2338 * Create new error objects by calling the corresponding error object
2339 * constructor with the message.
2340 */
2341class V8EXPORT Exception {
2342 public:
2343 static Local<Value> RangeError(Handle<String> message);
2344 static Local<Value> ReferenceError(Handle<String> message);
2345 static Local<Value> SyntaxError(Handle<String> message);
2346 static Local<Value> TypeError(Handle<String> message);
2347 static Local<Value> Error(Handle<String> message);
2348};
2349
2350
2351// --- C o u n t e r s C a l l b a c k s ---
2352
2353typedef int* (*CounterLookupCallback)(const char* name);
2354
2355typedef void* (*CreateHistogramCallback)(const char* name,
2356 int min,
2357 int max,
2358 size_t buckets);
2359
2360typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2361
Iain Merrick9ac36c92010-09-13 15:29:50 +01002362// --- M e m o r y A l l o c a t i o n C a l l b a c k ---
2363 enum ObjectSpace {
2364 kObjectSpaceNewSpace = 1 << 0,
2365 kObjectSpaceOldPointerSpace = 1 << 1,
2366 kObjectSpaceOldDataSpace = 1 << 2,
2367 kObjectSpaceCodeSpace = 1 << 3,
2368 kObjectSpaceMapSpace = 1 << 4,
2369 kObjectSpaceLoSpace = 1 << 5,
2370
2371 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2372 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2373 kObjectSpaceLoSpace
2374 };
2375
2376 enum AllocationAction {
2377 kAllocationActionAllocate = 1 << 0,
2378 kAllocationActionFree = 1 << 1,
2379 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2380 };
2381
2382typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2383 AllocationAction action,
2384 int size);
2385
Steve Blocka7e24c12009-10-30 11:49:00 +00002386// --- 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 ---
2387typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2388 AccessType type,
2389 Local<Value> data);
2390
2391// --- 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
2392
2393/**
Steve Block6ded16b2010-05-10 14:33:55 +01002394 * Applications can register callback functions which will be called
2395 * before and after a garbage collection. Allocations are not
2396 * allowed in the callback functions, you therefore cannot manipulate
Steve Blocka7e24c12009-10-30 11:49:00 +00002397 * objects (set or delete properties for example) since it is possible
2398 * such operations will result in the allocation of objects.
2399 */
Steve Block6ded16b2010-05-10 14:33:55 +01002400enum GCType {
2401 kGCTypeScavenge = 1 << 0,
2402 kGCTypeMarkSweepCompact = 1 << 1,
2403 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2404};
2405
2406enum GCCallbackFlags {
2407 kNoGCCallbackFlags = 0,
2408 kGCCallbackFlagCompacted = 1 << 0
2409};
2410
2411typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2412typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2413
Steve Blocka7e24c12009-10-30 11:49:00 +00002414typedef void (*GCCallback)();
2415
2416
Steve Blocka7e24c12009-10-30 11:49:00 +00002417/**
2418 * Profiler modules.
2419 *
2420 * In V8, profiler consists of several modules: CPU profiler, and different
2421 * kinds of heap profiling. Each can be turned on / off independently.
2422 * When PROFILER_MODULE_HEAP_SNAPSHOT flag is passed to ResumeProfilerEx,
2423 * modules are enabled only temporarily for making a snapshot of the heap.
2424 */
2425enum ProfilerModules {
2426 PROFILER_MODULE_NONE = 0,
2427 PROFILER_MODULE_CPU = 1,
2428 PROFILER_MODULE_HEAP_STATS = 1 << 1,
2429 PROFILER_MODULE_JS_CONSTRUCTORS = 1 << 2,
2430 PROFILER_MODULE_HEAP_SNAPSHOT = 1 << 16
2431};
2432
2433
2434/**
Steve Block3ce2e202009-11-05 08:53:23 +00002435 * Collection of V8 heap information.
2436 *
2437 * Instances of this class can be passed to v8::V8::HeapStatistics to
2438 * get heap statistics from V8.
2439 */
2440class V8EXPORT HeapStatistics {
2441 public:
2442 HeapStatistics();
2443 size_t total_heap_size() { return total_heap_size_; }
2444 size_t used_heap_size() { return used_heap_size_; }
2445
2446 private:
2447 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
2448 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2449
2450 size_t total_heap_size_;
2451 size_t used_heap_size_;
2452
2453 friend class V8;
2454};
2455
2456
2457/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002458 * Container class for static utility functions.
2459 */
2460class V8EXPORT V8 {
2461 public:
2462 /** Set the callback to invoke in case of fatal errors. */
2463 static void SetFatalErrorHandler(FatalErrorCallback that);
2464
2465 /**
2466 * Ignore out-of-memory exceptions.
2467 *
2468 * V8 running out of memory is treated as a fatal error by default.
2469 * This means that the fatal error handler is called and that V8 is
2470 * terminated.
2471 *
2472 * IgnoreOutOfMemoryException can be used to not treat a
2473 * out-of-memory situation as a fatal error. This way, the contexts
2474 * that did not cause the out of memory problem might be able to
2475 * continue execution.
2476 */
2477 static void IgnoreOutOfMemoryException();
2478
2479 /**
2480 * Check if V8 is dead and therefore unusable. This is the case after
2481 * fatal errors such as out-of-memory situations.
2482 */
2483 static bool IsDead();
2484
2485 /**
2486 * Adds a message listener.
2487 *
2488 * The same message listener can be added more than once and it that
2489 * case it will be called more than once for each message.
2490 */
2491 static bool AddMessageListener(MessageCallback that,
2492 Handle<Value> data = Handle<Value>());
2493
2494 /**
2495 * Remove all message listeners from the specified callback function.
2496 */
2497 static void RemoveMessageListeners(MessageCallback that);
2498
2499 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002500 * Tells V8 to capture current stack trace when uncaught exception occurs
2501 * and report it to the message listeners. The option is off by default.
2502 */
2503 static void SetCaptureStackTraceForUncaughtExceptions(
2504 bool capture,
2505 int frame_limit = 10,
2506 StackTrace::StackTraceOptions options = StackTrace::kOverview);
2507
2508 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002509 * Sets V8 flags from a string.
2510 */
2511 static void SetFlagsFromString(const char* str, int length);
2512
2513 /**
2514 * Sets V8 flags from the command line.
2515 */
2516 static void SetFlagsFromCommandLine(int* argc,
2517 char** argv,
2518 bool remove_flags);
2519
2520 /** Get the version string. */
2521 static const char* GetVersion();
2522
2523 /**
2524 * Enables the host application to provide a mechanism for recording
2525 * statistics counters.
2526 */
2527 static void SetCounterFunction(CounterLookupCallback);
2528
2529 /**
2530 * Enables the host application to provide a mechanism for recording
2531 * histograms. The CreateHistogram function returns a
2532 * histogram which will later be passed to the AddHistogramSample
2533 * function.
2534 */
2535 static void SetCreateHistogramFunction(CreateHistogramCallback);
2536 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2537
2538 /**
2539 * Enables the computation of a sliding window of states. The sliding
2540 * window information is recorded in statistics counters.
2541 */
2542 static void EnableSlidingStateWindow();
2543
2544 /** Callback function for reporting failed access checks.*/
2545 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2546
2547 /**
2548 * Enables the host application to receive a notification before a
Steve Block6ded16b2010-05-10 14:33:55 +01002549 * garbage collection. Allocations are not allowed in the
2550 * callback function, you therefore cannot manipulate objects (set
2551 * or delete properties for example) since it is possible such
2552 * operations will result in the allocation of objects. It is possible
2553 * to specify the GCType filter for your callback. But it is not possible to
2554 * register the same callback function two times with different
2555 * GCType filters.
2556 */
2557 static void AddGCPrologueCallback(
2558 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
2559
2560 /**
2561 * This function removes callback which was installed by
2562 * AddGCPrologueCallback function.
2563 */
2564 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
2565
2566 /**
2567 * The function is deprecated. Please use AddGCPrologueCallback instead.
2568 * Enables the host application to receive a notification before a
2569 * garbage collection. Allocations are not allowed in the
Steve Blocka7e24c12009-10-30 11:49:00 +00002570 * callback function, you therefore cannot manipulate objects (set
2571 * or delete properties for example) since it is possible such
2572 * operations will result in the allocation of objects.
2573 */
2574 static void SetGlobalGCPrologueCallback(GCCallback);
2575
2576 /**
2577 * Enables the host application to receive a notification after a
Steve Block6ded16b2010-05-10 14:33:55 +01002578 * garbage collection. Allocations are not allowed in the
2579 * callback function, you therefore cannot manipulate objects (set
2580 * or delete properties for example) since it is possible such
2581 * operations will result in the allocation of objects. It is possible
2582 * to specify the GCType filter for your callback. But it is not possible to
2583 * register the same callback function two times with different
2584 * GCType filters.
2585 */
2586 static void AddGCEpilogueCallback(
2587 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
2588
2589 /**
2590 * This function removes callback which was installed by
2591 * AddGCEpilogueCallback function.
2592 */
2593 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
2594
2595 /**
2596 * The function is deprecated. Please use AddGCEpilogueCallback instead.
2597 * Enables the host application to receive a notification after a
Steve Blocka7e24c12009-10-30 11:49:00 +00002598 * major garbage collection. Allocations are not allowed in the
2599 * callback function, you therefore cannot manipulate objects (set
2600 * or delete properties for example) since it is possible such
2601 * operations will result in the allocation of objects.
2602 */
2603 static void SetGlobalGCEpilogueCallback(GCCallback);
2604
2605 /**
Iain Merrick9ac36c92010-09-13 15:29:50 +01002606 * Enables the host application to provide a mechanism to be notified
2607 * and perform custom logging when V8 Allocates Executable Memory.
2608 */
2609 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
2610 ObjectSpace space,
2611 AllocationAction action);
2612
2613 /**
2614 * This function removes callback which was installed by
2615 * AddMemoryAllocationCallback function.
2616 */
2617 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
2618
2619 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002620 * Allows the host application to group objects together. If one
2621 * object in the group is alive, all objects in the group are alive.
2622 * After each garbage collection, object groups are removed. It is
2623 * intended to be used in the before-garbage-collection callback
2624 * function, for instance to simulate DOM tree connections among JS
2625 * wrapper objects.
2626 */
2627 static void AddObjectGroup(Persistent<Value>* objects, size_t length);
2628
2629 /**
2630 * Initializes from snapshot if possible. Otherwise, attempts to
2631 * initialize from scratch. This function is called implicitly if
2632 * you use the API without calling it first.
2633 */
2634 static bool Initialize();
2635
2636 /**
2637 * Adjusts the amount of registered external memory. Used to give
2638 * V8 an indication of the amount of externally allocated memory
2639 * that is kept alive by JavaScript objects. V8 uses this to decide
2640 * when to perform global garbage collections. Registering
2641 * externally allocated memory will trigger global garbage
2642 * collections more often than otherwise in an attempt to garbage
2643 * collect the JavaScript objects keeping the externally allocated
2644 * memory alive.
2645 *
2646 * \param change_in_bytes the change in externally allocated memory
2647 * that is kept alive by JavaScript objects.
2648 * \returns the adjusted value.
2649 */
2650 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
2651
2652 /**
2653 * Suspends recording of tick samples in the profiler.
2654 * When the V8 profiling mode is enabled (usually via command line
2655 * switches) this function suspends recording of tick samples.
2656 * Profiling ticks are discarded until ResumeProfiler() is called.
2657 *
2658 * See also the --prof and --prof_auto command line switches to
2659 * enable V8 profiling.
2660 */
2661 static void PauseProfiler();
2662
2663 /**
2664 * Resumes recording of tick samples in the profiler.
2665 * See also PauseProfiler().
2666 */
2667 static void ResumeProfiler();
2668
2669 /**
2670 * Return whether profiler is currently paused.
2671 */
2672 static bool IsProfilerPaused();
2673
2674 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002675 * Resumes specified profiler modules. Can be called several times to
2676 * mark the opening of a profiler events block with the given tag.
2677 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002678 * "ResumeProfiler" is equivalent to "ResumeProfilerEx(PROFILER_MODULE_CPU)".
2679 * See ProfilerModules enum.
2680 *
2681 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002682 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002683 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002684 static void ResumeProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002685
2686 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002687 * Pauses specified profiler modules. Each call to "PauseProfilerEx" closes
2688 * a block of profiler events opened by a call to "ResumeProfilerEx" with the
2689 * same tag value. There is no need for blocks to be properly nested.
2690 * The profiler is paused when the last opened block is closed.
2691 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002692 * "PauseProfiler" is equivalent to "PauseProfilerEx(PROFILER_MODULE_CPU)".
2693 * See ProfilerModules enum.
2694 *
2695 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002696 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002697 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002698 static void PauseProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002699
2700 /**
2701 * Returns active (resumed) profiler modules.
2702 * See ProfilerModules enum.
2703 *
2704 * \returns active profiler modules.
2705 */
2706 static int GetActiveProfilerModules();
2707
2708 /**
2709 * If logging is performed into a memory buffer (via --logfile=*), allows to
2710 * retrieve previously written messages. This can be used for retrieving
2711 * profiler log data in the application. This function is thread-safe.
2712 *
2713 * Caller provides a destination buffer that must exist during GetLogLines
2714 * call. Only whole log lines are copied into the buffer.
2715 *
2716 * \param from_pos specified a point in a buffer to read from, 0 is the
2717 * beginning of a buffer. It is assumed that caller updates its current
2718 * position using returned size value from the previous call.
2719 * \param dest_buf destination buffer for log data.
2720 * \param max_size size of the destination buffer.
2721 * \returns actual size of log data copied into buffer.
2722 */
2723 static int GetLogLines(int from_pos, char* dest_buf, int max_size);
2724
2725 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002726 * The minimum allowed size for a log lines buffer. If the size of
2727 * the buffer given will not be enough to hold a line of the maximum
2728 * length, an attempt to find a log line end in GetLogLines will
2729 * fail, and an empty result will be returned.
2730 */
2731 static const int kMinimumSizeForLogLinesBuffer = 2048;
2732
2733 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002734 * Retrieve the V8 thread id of the calling thread.
2735 *
2736 * The thread id for a thread should only be retrieved after the V8
2737 * lock has been acquired with a Locker object with that thread.
2738 */
2739 static int GetCurrentThreadId();
2740
2741 /**
2742 * Forcefully terminate execution of a JavaScript thread. This can
2743 * be used to terminate long-running scripts.
2744 *
2745 * TerminateExecution should only be called when then V8 lock has
2746 * been acquired with a Locker object. Therefore, in order to be
2747 * able to terminate long-running threads, preemption must be
2748 * enabled to allow the user of TerminateExecution to acquire the
2749 * lock.
2750 *
2751 * The termination is achieved by throwing an exception that is
2752 * uncatchable by JavaScript exception handlers. Termination
2753 * exceptions act as if they were caught by a C++ TryCatch exception
2754 * handlers. If forceful termination is used, any C++ TryCatch
2755 * exception handler that catches an exception should check if that
2756 * exception is a termination exception and immediately return if
2757 * that is the case. Returning immediately in that case will
2758 * continue the propagation of the termination exception if needed.
2759 *
2760 * The thread id passed to TerminateExecution must have been
2761 * obtained by calling GetCurrentThreadId on the thread in question.
2762 *
2763 * \param thread_id The thread id of the thread to terminate.
2764 */
2765 static void TerminateExecution(int thread_id);
2766
2767 /**
2768 * Forcefully terminate the current thread of JavaScript execution.
2769 *
2770 * This method can be used by any thread even if that thread has not
2771 * acquired the V8 lock with a Locker object.
2772 */
2773 static void TerminateExecution();
2774
2775 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002776 * Is V8 terminating JavaScript execution.
2777 *
2778 * Returns true if JavaScript execution is currently terminating
2779 * because of a call to TerminateExecution. In that case there are
2780 * still JavaScript frames on the stack and the termination
2781 * exception is still active.
2782 */
2783 static bool IsExecutionTerminating();
2784
2785 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002786 * Releases any resources used by v8 and stops any utility threads
2787 * that may be running. Note that disposing v8 is permanent, it
2788 * cannot be reinitialized.
2789 *
2790 * It should generally not be necessary to dispose v8 before exiting
2791 * a process, this should happen automatically. It is only necessary
2792 * to use if the process needs the resources taken up by v8.
2793 */
2794 static bool Dispose();
2795
Steve Block3ce2e202009-11-05 08:53:23 +00002796 /**
2797 * Get statistics about the heap memory usage.
2798 */
2799 static void GetHeapStatistics(HeapStatistics* heap_statistics);
Steve Blocka7e24c12009-10-30 11:49:00 +00002800
2801 /**
2802 * Optional notification that the embedder is idle.
2803 * V8 uses the notification to reduce memory footprint.
2804 * This call can be used repeatedly if the embedder remains idle.
Steve Blocka7e24c12009-10-30 11:49:00 +00002805 * Returns true if the embedder should stop calling IdleNotification
2806 * until real work has been done. This indicates that V8 has done
2807 * as much cleanup as it will be able to do.
2808 */
Steve Block3ce2e202009-11-05 08:53:23 +00002809 static bool IdleNotification();
Steve Blocka7e24c12009-10-30 11:49:00 +00002810
2811 /**
2812 * Optional notification that the system is running low on memory.
2813 * V8 uses these notifications to attempt to free memory.
2814 */
2815 static void LowMemoryNotification();
2816
Steve Block6ded16b2010-05-10 14:33:55 +01002817 /**
2818 * Optional notification that a context has been disposed. V8 uses
2819 * these notifications to guide the GC heuristic. Returns the number
2820 * of context disposals - including this one - since the last time
2821 * V8 had a chance to clean up.
2822 */
2823 static int ContextDisposedNotification();
2824
Steve Blocka7e24c12009-10-30 11:49:00 +00002825 private:
2826 V8();
2827
2828 static internal::Object** GlobalizeReference(internal::Object** handle);
2829 static void DisposeGlobal(internal::Object** global_handle);
2830 static void MakeWeak(internal::Object** global_handle,
2831 void* data,
2832 WeakReferenceCallback);
2833 static void ClearWeak(internal::Object** global_handle);
2834 static bool IsGlobalNearDeath(internal::Object** global_handle);
2835 static bool IsGlobalWeak(internal::Object** global_handle);
2836
2837 template <class T> friend class Handle;
2838 template <class T> friend class Local;
2839 template <class T> friend class Persistent;
2840 friend class Context;
2841};
2842
2843
2844/**
2845 * An external exception handler.
2846 */
2847class V8EXPORT TryCatch {
2848 public:
2849
2850 /**
2851 * Creates a new try/catch block and registers it with v8.
2852 */
2853 TryCatch();
2854
2855 /**
2856 * Unregisters and deletes this try/catch block.
2857 */
2858 ~TryCatch();
2859
2860 /**
2861 * Returns true if an exception has been caught by this try/catch block.
2862 */
2863 bool HasCaught() const;
2864
2865 /**
2866 * For certain types of exceptions, it makes no sense to continue
2867 * execution.
2868 *
2869 * Currently, the only type of exception that can be caught by a
2870 * TryCatch handler and for which it does not make sense to continue
2871 * is termination exception. Such exceptions are thrown when the
2872 * TerminateExecution methods are called to terminate a long-running
2873 * script.
2874 *
2875 * If CanContinue returns false, the correct action is to perform
2876 * any C++ cleanup needed and then return.
2877 */
2878 bool CanContinue() const;
2879
2880 /**
Steve Blockd0582a62009-12-15 09:54:21 +00002881 * Throws the exception caught by this TryCatch in a way that avoids
2882 * it being caught again by this same TryCatch. As with ThrowException
2883 * it is illegal to execute any JavaScript operations after calling
2884 * ReThrow; the caller must return immediately to where the exception
2885 * is caught.
2886 */
2887 Handle<Value> ReThrow();
2888
2889 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002890 * Returns the exception caught by this try/catch block. If no exception has
2891 * been caught an empty handle is returned.
2892 *
2893 * The returned handle is valid until this TryCatch block has been destroyed.
2894 */
2895 Local<Value> Exception() const;
2896
2897 /**
2898 * Returns the .stack property of the thrown object. If no .stack
2899 * property is present an empty handle is returned.
2900 */
2901 Local<Value> StackTrace() const;
2902
2903 /**
2904 * Returns the message associated with this exception. If there is
2905 * no message associated an empty handle is returned.
2906 *
2907 * The returned handle is valid until this TryCatch block has been
2908 * destroyed.
2909 */
2910 Local<v8::Message> Message() const;
2911
2912 /**
2913 * Clears any exceptions that may have been caught by this try/catch block.
2914 * After this method has been called, HasCaught() will return false.
2915 *
2916 * It is not necessary to clear a try/catch block before using it again; if
2917 * another exception is thrown the previously caught exception will just be
2918 * overwritten. However, it is often a good idea since it makes it easier
2919 * to determine which operation threw a given exception.
2920 */
2921 void Reset();
2922
2923 /**
2924 * Set verbosity of the external exception handler.
2925 *
2926 * By default, exceptions that are caught by an external exception
2927 * handler are not reported. Call SetVerbose with true on an
2928 * external exception handler to have exceptions caught by the
2929 * handler reported as if they were not caught.
2930 */
2931 void SetVerbose(bool value);
2932
2933 /**
2934 * Set whether or not this TryCatch should capture a Message object
2935 * which holds source information about where the exception
2936 * occurred. True by default.
2937 */
2938 void SetCaptureMessage(bool value);
2939
Steve Blockd0582a62009-12-15 09:54:21 +00002940 private:
2941 void* next_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002942 void* exception_;
2943 void* message_;
Steve Blockd0582a62009-12-15 09:54:21 +00002944 bool is_verbose_ : 1;
2945 bool can_continue_ : 1;
2946 bool capture_message_ : 1;
2947 bool rethrow_ : 1;
2948
2949 friend class v8::internal::Top;
Steve Blocka7e24c12009-10-30 11:49:00 +00002950};
2951
2952
2953// --- C o n t e x t ---
2954
2955
2956/**
2957 * Ignore
2958 */
2959class V8EXPORT ExtensionConfiguration {
2960 public:
2961 ExtensionConfiguration(int name_count, const char* names[])
2962 : name_count_(name_count), names_(names) { }
2963 private:
2964 friend class ImplementationUtilities;
2965 int name_count_;
2966 const char** names_;
2967};
2968
2969
2970/**
2971 * A sandboxed execution context with its own set of built-in objects
2972 * and functions.
2973 */
2974class V8EXPORT Context {
2975 public:
2976 /** Returns the global object of the context. */
2977 Local<Object> Global();
2978
2979 /**
2980 * Detaches the global object from its context before
2981 * the global object can be reused to create a new context.
2982 */
2983 void DetachGlobal();
2984
Andrei Popescu74b3c142010-03-29 12:03:09 +01002985 /**
2986 * Reattaches a global object to a context. This can be used to
2987 * restore the connection between a global object and a context
2988 * after DetachGlobal has been called.
2989 *
2990 * \param global_object The global object to reattach to the
2991 * context. For this to work, the global object must be the global
2992 * object that was associated with this context before a call to
2993 * DetachGlobal.
2994 */
2995 void ReattachGlobal(Handle<Object> global_object);
2996
Leon Clarkef7060e22010-06-03 12:02:55 +01002997 /** Creates a new context.
2998 *
2999 * Returns a persistent handle to the newly allocated context. This
3000 * persistent handle has to be disposed when the context is no
3001 * longer used so the context can be garbage collected.
3002 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003003 static Persistent<Context> New(
Andrei Popescu31002712010-02-23 13:46:05 +00003004 ExtensionConfiguration* extensions = NULL,
Steve Blocka7e24c12009-10-30 11:49:00 +00003005 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3006 Handle<Value> global_object = Handle<Value>());
3007
3008 /** Returns the last entered context. */
3009 static Local<Context> GetEntered();
3010
3011 /** Returns the context that is on the top of the stack. */
3012 static Local<Context> GetCurrent();
3013
3014 /**
3015 * Returns the context of the calling JavaScript code. That is the
3016 * context of the top-most JavaScript frame. If there are no
3017 * JavaScript frames an empty handle is returned.
3018 */
3019 static Local<Context> GetCalling();
3020
3021 /**
3022 * Sets the security token for the context. To access an object in
3023 * another context, the security tokens must match.
3024 */
3025 void SetSecurityToken(Handle<Value> token);
3026
3027 /** Restores the security token to the default value. */
3028 void UseDefaultSecurityToken();
3029
3030 /** Returns the security token of this context.*/
3031 Handle<Value> GetSecurityToken();
3032
3033 /**
3034 * Enter this context. After entering a context, all code compiled
3035 * and run is compiled and run in this context. If another context
3036 * is already entered, this old context is saved so it can be
3037 * restored when the new context is exited.
3038 */
3039 void Enter();
3040
3041 /**
3042 * Exit this context. Exiting the current context restores the
3043 * context that was in place when entering the current context.
3044 */
3045 void Exit();
3046
3047 /** Returns true if the context has experienced an out of memory situation. */
3048 bool HasOutOfMemoryException();
3049
3050 /** Returns true if V8 has a current context. */
3051 static bool InContext();
3052
3053 /**
3054 * Associate an additional data object with the context. This is mainly used
3055 * with the debugger to provide additional information on the context through
3056 * the debugger API.
3057 */
Steve Blockd0582a62009-12-15 09:54:21 +00003058 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00003059 Local<Value> GetData();
3060
3061 /**
3062 * Stack-allocated class which sets the execution context for all
3063 * operations executed within a local scope.
3064 */
Steve Block8defd9f2010-07-08 12:39:36 +01003065 class Scope {
Steve Blocka7e24c12009-10-30 11:49:00 +00003066 public:
3067 inline Scope(Handle<Context> context) : context_(context) {
3068 context_->Enter();
3069 }
3070 inline ~Scope() { context_->Exit(); }
3071 private:
3072 Handle<Context> context_;
3073 };
3074
3075 private:
3076 friend class Value;
3077 friend class Script;
3078 friend class Object;
3079 friend class Function;
3080};
3081
3082
3083/**
3084 * Multiple threads in V8 are allowed, but only one thread at a time
3085 * is allowed to use V8. The definition of 'using V8' includes
3086 * accessing handles or holding onto object pointers obtained from V8
3087 * handles. It is up to the user of V8 to ensure (perhaps with
3088 * locking) that this constraint is not violated.
3089 *
3090 * If you wish to start using V8 in a thread you can do this by constructing
3091 * a v8::Locker object. After the code using V8 has completed for the
3092 * current thread you can call the destructor. This can be combined
3093 * with C++ scope-based construction as follows:
3094 *
3095 * \code
3096 * ...
3097 * {
3098 * v8::Locker locker;
3099 * ...
3100 * // Code using V8 goes here.
3101 * ...
3102 * } // Destructor called here
3103 * \endcode
3104 *
3105 * If you wish to stop using V8 in a thread A you can do this by either
3106 * by destroying the v8::Locker object as above or by constructing a
3107 * v8::Unlocker object:
3108 *
3109 * \code
3110 * {
3111 * v8::Unlocker unlocker;
3112 * ...
3113 * // Code not using V8 goes here while V8 can run in another thread.
3114 * ...
3115 * } // Destructor called here.
3116 * \endcode
3117 *
3118 * The Unlocker object is intended for use in a long-running callback
3119 * from V8, where you want to release the V8 lock for other threads to
3120 * use.
3121 *
3122 * The v8::Locker is a recursive lock. That is, you can lock more than
3123 * once in a given thread. This can be useful if you have code that can
3124 * be called either from code that holds the lock or from code that does
3125 * not. The Unlocker is not recursive so you can not have several
3126 * Unlockers on the stack at once, and you can not use an Unlocker in a
3127 * thread that is not inside a Locker's scope.
3128 *
3129 * An unlocker will unlock several lockers if it has to and reinstate
3130 * the correct depth of locking on its destruction. eg.:
3131 *
3132 * \code
3133 * // V8 not locked.
3134 * {
3135 * v8::Locker locker;
3136 * // V8 locked.
3137 * {
3138 * v8::Locker another_locker;
3139 * // V8 still locked (2 levels).
3140 * {
3141 * v8::Unlocker unlocker;
3142 * // V8 not locked.
3143 * }
3144 * // V8 locked again (2 levels).
3145 * }
3146 * // V8 still locked (1 level).
3147 * }
3148 * // V8 Now no longer locked.
3149 * \endcode
3150 */
3151class V8EXPORT Unlocker {
3152 public:
3153 Unlocker();
3154 ~Unlocker();
3155};
3156
3157
3158class V8EXPORT Locker {
3159 public:
3160 Locker();
3161 ~Locker();
3162
3163 /**
3164 * Start preemption.
3165 *
3166 * When preemption is started, a timer is fired every n milli seconds
3167 * that will switch between multiple threads that are in contention
3168 * for the V8 lock.
3169 */
3170 static void StartPreemption(int every_n_ms);
3171
3172 /**
3173 * Stop preemption.
3174 */
3175 static void StopPreemption();
3176
3177 /**
3178 * Returns whether or not the locker is locked by the current thread.
3179 */
3180 static bool IsLocked();
3181
3182 /**
3183 * Returns whether v8::Locker is being used by this V8 instance.
3184 */
3185 static bool IsActive() { return active_; }
3186
3187 private:
3188 bool has_lock_;
3189 bool top_level_;
3190
3191 static bool active_;
3192
3193 // Disallow copying and assigning.
3194 Locker(const Locker&);
3195 void operator=(const Locker&);
3196};
3197
3198
3199
3200// --- I m p l e m e n t a t i o n ---
3201
3202
3203namespace internal {
3204
3205
3206// Tag information for HeapObject.
3207const int kHeapObjectTag = 1;
3208const int kHeapObjectTagSize = 2;
3209const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3210
Steve Blocka7e24c12009-10-30 11:49:00 +00003211// Tag information for Smi.
3212const int kSmiTag = 0;
3213const int kSmiTagSize = 1;
3214const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3215
Steve Block3ce2e202009-11-05 08:53:23 +00003216template <size_t ptr_size> struct SmiConstants;
3217
3218// Smi constants for 32-bit systems.
3219template <> struct SmiConstants<4> {
3220 static const int kSmiShiftSize = 0;
3221 static const int kSmiValueSize = 31;
3222 static inline int SmiToInt(internal::Object* value) {
3223 int shift_bits = kSmiTagSize + kSmiShiftSize;
3224 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3225 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3226 }
3227};
3228
3229// Smi constants for 64-bit systems.
3230template <> struct SmiConstants<8> {
3231 static const int kSmiShiftSize = 31;
3232 static const int kSmiValueSize = 32;
3233 static inline int SmiToInt(internal::Object* value) {
3234 int shift_bits = kSmiTagSize + kSmiShiftSize;
3235 // Shift down and throw away top 32 bits.
3236 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3237 }
3238};
3239
3240const int kSmiShiftSize = SmiConstants<sizeof(void*)>::kSmiShiftSize;
3241const int kSmiValueSize = SmiConstants<sizeof(void*)>::kSmiValueSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003242
Steve Blockd0582a62009-12-15 09:54:21 +00003243template <size_t ptr_size> struct InternalConstants;
3244
3245// Internal constants for 32-bit systems.
3246template <> struct InternalConstants<4> {
3247 static const int kStringResourceOffset = 3 * sizeof(void*);
3248};
3249
3250// Internal constants for 64-bit systems.
3251template <> struct InternalConstants<8> {
Steve Block6ded16b2010-05-10 14:33:55 +01003252 static const int kStringResourceOffset = 3 * sizeof(void*);
Steve Blockd0582a62009-12-15 09:54:21 +00003253};
3254
Steve Blocka7e24c12009-10-30 11:49:00 +00003255/**
3256 * This class exports constants and functionality from within v8 that
3257 * is necessary to implement inline functions in the v8 api. Don't
3258 * depend on functions and constants defined here.
3259 */
3260class Internals {
3261 public:
3262
3263 // These values match non-compiler-dependent values defined within
3264 // the implementation of v8.
3265 static const int kHeapObjectMapOffset = 0;
3266 static const int kMapInstanceTypeOffset = sizeof(void*) + sizeof(int);
Steve Blockd0582a62009-12-15 09:54:21 +00003267 static const int kStringResourceOffset =
3268 InternalConstants<sizeof(void*)>::kStringResourceOffset;
3269
Steve Blocka7e24c12009-10-30 11:49:00 +00003270 static const int kProxyProxyOffset = sizeof(void*);
3271 static const int kJSObjectHeaderSize = 3 * sizeof(void*);
3272 static const int kFullStringRepresentationMask = 0x07;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003273 static const int kExternalTwoByteRepresentationTag = 0x02;
Steve Blocka7e24c12009-10-30 11:49:00 +00003274
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003275 static const int kJSObjectType = 0x9f;
3276 static const int kFirstNonstringType = 0x80;
3277 static const int kProxyType = 0x85;
Steve Blocka7e24c12009-10-30 11:49:00 +00003278
3279 static inline bool HasHeapObjectTag(internal::Object* value) {
3280 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3281 kHeapObjectTag);
3282 }
3283
3284 static inline bool HasSmiTag(internal::Object* value) {
3285 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3286 }
3287
3288 static inline int SmiValue(internal::Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00003289 return SmiConstants<sizeof(void*)>::SmiToInt(value);
3290 }
3291
3292 static inline int GetInstanceType(internal::Object* obj) {
3293 typedef internal::Object O;
3294 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3295 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3296 }
3297
3298 static inline void* GetExternalPointer(internal::Object* obj) {
3299 if (HasSmiTag(obj)) {
3300 return obj;
3301 } else if (GetInstanceType(obj) == kProxyType) {
3302 return ReadField<void*>(obj, kProxyProxyOffset);
3303 } else {
3304 return NULL;
3305 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003306 }
3307
3308 static inline bool IsExternalTwoByteString(int instance_type) {
3309 int representation = (instance_type & kFullStringRepresentationMask);
3310 return representation == kExternalTwoByteRepresentationTag;
3311 }
3312
3313 template <typename T>
3314 static inline T ReadField(Object* ptr, int offset) {
3315 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3316 return *reinterpret_cast<T*>(addr);
3317 }
3318
3319};
3320
3321}
3322
3323
3324template <class T>
3325Handle<T>::Handle() : val_(0) { }
3326
3327
3328template <class T>
3329Local<T>::Local() : Handle<T>() { }
3330
3331
3332template <class T>
3333Local<T> Local<T>::New(Handle<T> that) {
3334 if (that.IsEmpty()) return Local<T>();
3335 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3336 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3337}
3338
3339
3340template <class T>
3341Persistent<T> Persistent<T>::New(Handle<T> that) {
3342 if (that.IsEmpty()) return Persistent<T>();
3343 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3344 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3345}
3346
3347
3348template <class T>
3349bool Persistent<T>::IsNearDeath() const {
3350 if (this->IsEmpty()) return false;
3351 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3352}
3353
3354
3355template <class T>
3356bool Persistent<T>::IsWeak() const {
3357 if (this->IsEmpty()) return false;
3358 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3359}
3360
3361
3362template <class T>
3363void Persistent<T>::Dispose() {
3364 if (this->IsEmpty()) return;
3365 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3366}
3367
3368
3369template <class T>
3370Persistent<T>::Persistent() : Handle<T>() { }
3371
3372template <class T>
3373void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3374 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3375 parameters,
3376 callback);
3377}
3378
3379template <class T>
3380void Persistent<T>::ClearWeak() {
3381 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3382}
3383
Steve Block8defd9f2010-07-08 12:39:36 +01003384
3385Arguments::Arguments(v8::Local<v8::Value> data,
3386 v8::Local<v8::Object> holder,
3387 v8::Local<v8::Function> callee,
3388 bool is_construct_call,
3389 void** values, int length)
3390 : data_(data), holder_(holder), callee_(callee),
3391 is_construct_call_(is_construct_call),
3392 values_(values), length_(length) { }
3393
3394
Steve Blocka7e24c12009-10-30 11:49:00 +00003395Local<Value> Arguments::operator[](int i) const {
3396 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3397 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3398}
3399
3400
3401Local<Function> Arguments::Callee() const {
3402 return callee_;
3403}
3404
3405
3406Local<Object> Arguments::This() const {
3407 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
3408}
3409
3410
3411Local<Object> Arguments::Holder() const {
3412 return holder_;
3413}
3414
3415
3416Local<Value> Arguments::Data() const {
3417 return data_;
3418}
3419
3420
3421bool Arguments::IsConstructCall() const {
3422 return is_construct_call_;
3423}
3424
3425
3426int Arguments::Length() const {
3427 return length_;
3428}
3429
3430
3431template <class T>
3432Local<T> HandleScope::Close(Handle<T> value) {
3433 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
3434 internal::Object** after = RawClose(before);
3435 return Local<T>(reinterpret_cast<T*>(after));
3436}
3437
3438Handle<Value> ScriptOrigin::ResourceName() const {
3439 return resource_name_;
3440}
3441
3442
3443Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
3444 return resource_line_offset_;
3445}
3446
3447
3448Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
3449 return resource_column_offset_;
3450}
3451
3452
3453Handle<Boolean> Boolean::New(bool value) {
3454 return value ? True() : False();
3455}
3456
3457
3458void Template::Set(const char* name, v8::Handle<Data> value) {
3459 Set(v8::String::New(name), value);
3460}
3461
3462
3463Local<Value> Object::GetInternalField(int index) {
3464#ifndef V8_ENABLE_CHECKS
3465 Local<Value> quick_result = UncheckedGetInternalField(index);
3466 if (!quick_result.IsEmpty()) return quick_result;
3467#endif
3468 return CheckedGetInternalField(index);
3469}
3470
3471
3472Local<Value> Object::UncheckedGetInternalField(int index) {
3473 typedef internal::Object O;
3474 typedef internal::Internals I;
3475 O* obj = *reinterpret_cast<O**>(this);
Steve Block3ce2e202009-11-05 08:53:23 +00003476 if (I::GetInstanceType(obj) == I::kJSObjectType) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003477 // If the object is a plain JSObject, which is the common case,
3478 // we know where to find the internal fields and can return the
3479 // value directly.
3480 int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3481 O* value = I::ReadField<O*>(obj, offset);
3482 O** result = HandleScope::CreateHandle(value);
3483 return Local<Value>(reinterpret_cast<Value*>(result));
3484 } else {
3485 return Local<Value>();
3486 }
3487}
3488
3489
3490void* External::Unwrap(Handle<v8::Value> obj) {
3491#ifdef V8_ENABLE_CHECKS
3492 return FullUnwrap(obj);
3493#else
3494 return QuickUnwrap(obj);
3495#endif
3496}
3497
3498
3499void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
3500 typedef internal::Object O;
Steve Blocka7e24c12009-10-30 11:49:00 +00003501 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
Steve Block3ce2e202009-11-05 08:53:23 +00003502 return internal::Internals::GetExternalPointer(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00003503}
3504
3505
3506void* Object::GetPointerFromInternalField(int index) {
Steve Block3ce2e202009-11-05 08:53:23 +00003507 typedef internal::Object O;
3508 typedef internal::Internals I;
3509
3510 O* obj = *reinterpret_cast<O**>(this);
3511
3512 if (I::GetInstanceType(obj) == I::kJSObjectType) {
3513 // If the object is a plain JSObject, which is the common case,
3514 // we know where to find the internal fields and can return the
3515 // value directly.
3516 int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3517 O* value = I::ReadField<O*>(obj, offset);
3518 return I::GetExternalPointer(value);
3519 }
3520
3521 return SlowGetPointerFromInternalField(index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003522}
3523
3524
3525String* String::Cast(v8::Value* value) {
3526#ifdef V8_ENABLE_CHECKS
3527 CheckCast(value);
3528#endif
3529 return static_cast<String*>(value);
3530}
3531
3532
3533String::ExternalStringResource* String::GetExternalStringResource() const {
3534 typedef internal::Object O;
3535 typedef internal::Internals I;
3536 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
Steve Blocka7e24c12009-10-30 11:49:00 +00003537 String::ExternalStringResource* result;
Steve Block3ce2e202009-11-05 08:53:23 +00003538 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003539 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
3540 result = reinterpret_cast<String::ExternalStringResource*>(value);
3541 } else {
3542 result = NULL;
3543 }
3544#ifdef V8_ENABLE_CHECKS
3545 VerifyExternalStringResource(result);
3546#endif
3547 return result;
3548}
3549
3550
3551bool Value::IsString() const {
3552#ifdef V8_ENABLE_CHECKS
3553 return FullIsString();
3554#else
3555 return QuickIsString();
3556#endif
3557}
3558
3559bool Value::QuickIsString() const {
3560 typedef internal::Object O;
3561 typedef internal::Internals I;
3562 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
3563 if (!I::HasHeapObjectTag(obj)) return false;
Steve Block3ce2e202009-11-05 08:53:23 +00003564 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
Steve Blocka7e24c12009-10-30 11:49:00 +00003565}
3566
3567
3568Number* Number::Cast(v8::Value* value) {
3569#ifdef V8_ENABLE_CHECKS
3570 CheckCast(value);
3571#endif
3572 return static_cast<Number*>(value);
3573}
3574
3575
3576Integer* Integer::Cast(v8::Value* value) {
3577#ifdef V8_ENABLE_CHECKS
3578 CheckCast(value);
3579#endif
3580 return static_cast<Integer*>(value);
3581}
3582
3583
3584Date* Date::Cast(v8::Value* value) {
3585#ifdef V8_ENABLE_CHECKS
3586 CheckCast(value);
3587#endif
3588 return static_cast<Date*>(value);
3589}
3590
3591
3592Object* Object::Cast(v8::Value* value) {
3593#ifdef V8_ENABLE_CHECKS
3594 CheckCast(value);
3595#endif
3596 return static_cast<Object*>(value);
3597}
3598
3599
3600Array* Array::Cast(v8::Value* value) {
3601#ifdef V8_ENABLE_CHECKS
3602 CheckCast(value);
3603#endif
3604 return static_cast<Array*>(value);
3605}
3606
3607
3608Function* Function::Cast(v8::Value* value) {
3609#ifdef V8_ENABLE_CHECKS
3610 CheckCast(value);
3611#endif
3612 return static_cast<Function*>(value);
3613}
3614
3615
3616External* External::Cast(v8::Value* value) {
3617#ifdef V8_ENABLE_CHECKS
3618 CheckCast(value);
3619#endif
3620 return static_cast<External*>(value);
3621}
3622
3623
3624Local<Value> AccessorInfo::Data() const {
Steve Block6ded16b2010-05-10 14:33:55 +01003625 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003626}
3627
3628
3629Local<Object> AccessorInfo::This() const {
3630 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
3631}
3632
3633
3634Local<Object> AccessorInfo::Holder() const {
3635 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
3636}
3637
3638
3639/**
3640 * \example shell.cc
3641 * A simple shell that takes a list of expressions on the
3642 * command-line and executes them.
3643 */
3644
3645
3646/**
3647 * \example process.cc
3648 */
3649
3650
3651} // namespace v8
3652
3653
3654#undef V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00003655#undef TYPE_CHECK
3656
3657
3658#endif // V8_H_