blob: ef9a41168cb5c39cca83c3c4af3314252a111db6 [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,
Ben Murdochf87a2032010-10-22 12:50:53 +0100761 kScriptNameOrSourceURL = 1 << 6,
Kristian Monsen25f61362010-05-21 11:50:48 +0100762 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
Ben Murdochf87a2032010-10-22 12:50:53 +0100763 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
Kristian Monsen25f61362010-05-21 11:50:48 +0100764 };
765
766 /**
767 * Returns a StackFrame at a particular index.
768 */
769 Local<StackFrame> GetFrame(uint32_t index) const;
770
771 /**
772 * Returns the number of StackFrames.
773 */
774 int GetFrameCount() const;
775
776 /**
777 * Returns StackTrace as a v8::Array that contains StackFrame objects.
778 */
779 Local<Array> AsArray();
780
781 /**
782 * Grab a snapshot of the the current JavaScript execution stack.
783 *
784 * \param frame_limit The maximum number of stack frames we want to capture.
785 * \param options Enumerates the set of things we will capture for each
786 * StackFrame.
787 */
788 static Local<StackTrace> CurrentStackTrace(
789 int frame_limit,
790 StackTraceOptions options = kOverview);
791};
792
793
794/**
795 * A single JavaScript stack frame.
796 */
797class V8EXPORT StackFrame {
798 public:
799 /**
800 * Returns the number, 1-based, of the line for the associate function call.
801 * This method will return Message::kNoLineNumberInfo if it is unable to
802 * retrieve the line number, or if kLineNumber was not passed as an option
803 * when capturing the StackTrace.
804 */
805 int GetLineNumber() const;
806
807 /**
808 * Returns the 1-based column offset on the line for the associated function
809 * call.
810 * This method will return Message::kNoColumnInfo if it is unable to retrieve
811 * the column number, or if kColumnOffset was not passed as an option when
812 * capturing the StackTrace.
813 */
814 int GetColumn() const;
815
816 /**
817 * Returns the name of the resource that contains the script for the
818 * function for this StackFrame.
819 */
820 Local<String> GetScriptName() const;
821
822 /**
Ben Murdochf87a2032010-10-22 12:50:53 +0100823 * Returns the name of the resource that contains the script for the
824 * function for this StackFrame or sourceURL value if the script name
825 * is undefined and its source ends with //@ sourceURL=... string.
826 */
827 Local<String> GetScriptNameOrSourceURL() const;
828
829 /**
Kristian Monsen25f61362010-05-21 11:50:48 +0100830 * Returns the name of the function associated with this stack frame.
831 */
832 Local<String> GetFunctionName() const;
833
834 /**
835 * Returns whether or not the associated function is compiled via a call to
836 * eval().
837 */
838 bool IsEval() const;
839
840 /**
841 * Returns whther or not the associated function is called as a
842 * constructor via "new".
843 */
844 bool IsConstructor() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000845};
846
847
848// --- V a l u e ---
849
850
851/**
852 * The superclass of all JavaScript values and objects.
853 */
Steve Block8defd9f2010-07-08 12:39:36 +0100854class Value : public Data {
Steve Blocka7e24c12009-10-30 11:49:00 +0000855 public:
856
857 /**
858 * Returns true if this value is the undefined value. See ECMA-262
859 * 4.3.10.
860 */
Steve Block8defd9f2010-07-08 12:39:36 +0100861 V8EXPORT bool IsUndefined() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000862
863 /**
864 * Returns true if this value is the null value. See ECMA-262
865 * 4.3.11.
866 */
Steve Block8defd9f2010-07-08 12:39:36 +0100867 V8EXPORT bool IsNull() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000868
869 /**
870 * Returns true if this value is true.
871 */
Steve Block8defd9f2010-07-08 12:39:36 +0100872 V8EXPORT bool IsTrue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000873
874 /**
875 * Returns true if this value is false.
876 */
Steve Block8defd9f2010-07-08 12:39:36 +0100877 V8EXPORT bool IsFalse() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000878
879 /**
880 * Returns true if this value is an instance of the String type.
881 * See ECMA-262 8.4.
882 */
883 inline bool IsString() const;
884
885 /**
886 * Returns true if this value is a function.
887 */
Steve Block8defd9f2010-07-08 12:39:36 +0100888 V8EXPORT bool IsFunction() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000889
890 /**
891 * Returns true if this value is an array.
892 */
Steve Block8defd9f2010-07-08 12:39:36 +0100893 V8EXPORT bool IsArray() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000894
895 /**
896 * Returns true if this value is an object.
897 */
Steve Block8defd9f2010-07-08 12:39:36 +0100898 V8EXPORT bool IsObject() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000899
900 /**
901 * Returns true if this value is boolean.
902 */
Steve Block8defd9f2010-07-08 12:39:36 +0100903 V8EXPORT bool IsBoolean() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000904
905 /**
906 * Returns true if this value is a number.
907 */
Steve Block8defd9f2010-07-08 12:39:36 +0100908 V8EXPORT bool IsNumber() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000909
910 /**
911 * Returns true if this value is external.
912 */
Steve Block8defd9f2010-07-08 12:39:36 +0100913 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000914
915 /**
916 * Returns true if this value is a 32-bit signed integer.
917 */
Steve Block8defd9f2010-07-08 12:39:36 +0100918 V8EXPORT bool IsInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000919
920 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100921 * Returns true if this value is a 32-bit unsigned integer.
922 */
Steve Block8defd9f2010-07-08 12:39:36 +0100923 V8EXPORT bool IsUint32() const;
Steve Block6ded16b2010-05-10 14:33:55 +0100924
925 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000926 * Returns true if this value is a Date.
927 */
Steve Block8defd9f2010-07-08 12:39:36 +0100928 V8EXPORT bool IsDate() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000929
Iain Merrick75681382010-08-19 15:07:18 +0100930 /**
931 * Returns true if this value is a RegExp.
932 */
933 V8EXPORT bool IsRegExp() const;
934
Steve Block8defd9f2010-07-08 12:39:36 +0100935 V8EXPORT Local<Boolean> ToBoolean() const;
936 V8EXPORT Local<Number> ToNumber() const;
937 V8EXPORT Local<String> ToString() const;
938 V8EXPORT Local<String> ToDetailString() const;
939 V8EXPORT Local<Object> ToObject() const;
940 V8EXPORT Local<Integer> ToInteger() const;
941 V8EXPORT Local<Uint32> ToUint32() const;
942 V8EXPORT Local<Int32> ToInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000943
944 /**
945 * Attempts to convert a string to an array index.
946 * Returns an empty handle if the conversion fails.
947 */
Steve Block8defd9f2010-07-08 12:39:36 +0100948 V8EXPORT Local<Uint32> ToArrayIndex() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000949
Steve Block8defd9f2010-07-08 12:39:36 +0100950 V8EXPORT bool BooleanValue() const;
951 V8EXPORT double NumberValue() const;
952 V8EXPORT int64_t IntegerValue() const;
953 V8EXPORT uint32_t Uint32Value() const;
954 V8EXPORT int32_t Int32Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000955
956 /** JS == */
Steve Block8defd9f2010-07-08 12:39:36 +0100957 V8EXPORT bool Equals(Handle<Value> that) const;
958 V8EXPORT bool StrictEquals(Handle<Value> that) const;
Steve Block3ce2e202009-11-05 08:53:23 +0000959
Steve Blocka7e24c12009-10-30 11:49:00 +0000960 private:
961 inline bool QuickIsString() const;
Steve Block8defd9f2010-07-08 12:39:36 +0100962 V8EXPORT bool FullIsString() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000963};
964
965
966/**
967 * The superclass of primitive values. See ECMA-262 4.3.2.
968 */
Steve Block8defd9f2010-07-08 12:39:36 +0100969class Primitive : public Value { };
Steve Blocka7e24c12009-10-30 11:49:00 +0000970
971
972/**
973 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
974 * or false value.
975 */
Steve Block8defd9f2010-07-08 12:39:36 +0100976class Boolean : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000977 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100978 V8EXPORT bool Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000979 static inline Handle<Boolean> New(bool value);
980};
981
982
983/**
984 * A JavaScript string value (ECMA-262, 4.3.17).
985 */
Steve Block8defd9f2010-07-08 12:39:36 +0100986class String : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000987 public:
988
989 /**
990 * Returns the number of characters in this string.
991 */
Steve Block8defd9f2010-07-08 12:39:36 +0100992 V8EXPORT int Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000993
994 /**
995 * Returns the number of bytes in the UTF-8 encoded
996 * representation of this string.
997 */
Steve Block8defd9f2010-07-08 12:39:36 +0100998 V8EXPORT int Utf8Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000999
1000 /**
1001 * Write the contents of the string to an external buffer.
1002 * If no arguments are given, expects the buffer to be large
1003 * enough to hold the entire string and NULL terminator. Copies
1004 * the contents of the string and the NULL terminator into the
1005 * buffer.
1006 *
1007 * Copies up to length characters into the output buffer.
1008 * Only null-terminates if there is enough space in the buffer.
1009 *
1010 * \param buffer The buffer into which the string will be copied.
1011 * \param start The starting position within the string at which
1012 * copying begins.
1013 * \param length The number of bytes to copy from the string.
Steve Block6ded16b2010-05-10 14:33:55 +01001014 * \param nchars_ref The number of characters written, can be NULL.
1015 * \param hints Various hints that might affect performance of this or
1016 * subsequent operations.
1017 * \return The number of bytes copied to the buffer
Steve Blocka7e24c12009-10-30 11:49:00 +00001018 * excluding the NULL terminator.
1019 */
Steve Block6ded16b2010-05-10 14:33:55 +01001020 enum WriteHints {
1021 NO_HINTS = 0,
1022 HINT_MANY_WRITES_EXPECTED = 1
1023 };
1024
Steve Block8defd9f2010-07-08 12:39:36 +01001025 V8EXPORT int Write(uint16_t* buffer,
1026 int start = 0,
1027 int length = -1,
1028 WriteHints hints = NO_HINTS) const; // UTF-16
1029 V8EXPORT int WriteAscii(char* buffer,
1030 int start = 0,
1031 int length = -1,
1032 WriteHints hints = NO_HINTS) const; // ASCII
1033 V8EXPORT int WriteUtf8(char* buffer,
1034 int length = -1,
1035 int* nchars_ref = NULL,
1036 WriteHints hints = NO_HINTS) const; // UTF-8
Steve Blocka7e24c12009-10-30 11:49:00 +00001037
1038 /**
1039 * A zero length string.
1040 */
Steve Block8defd9f2010-07-08 12:39:36 +01001041 V8EXPORT static v8::Local<v8::String> Empty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001042
1043 /**
1044 * Returns true if the string is external
1045 */
Steve Block8defd9f2010-07-08 12:39:36 +01001046 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001047
1048 /**
1049 * Returns true if the string is both external and ascii
1050 */
Steve Block8defd9f2010-07-08 12:39:36 +01001051 V8EXPORT bool IsExternalAscii() const;
Leon Clarkee46be812010-01-19 14:06:41 +00001052
1053 class V8EXPORT ExternalStringResourceBase {
1054 public:
1055 virtual ~ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001056
Leon Clarkee46be812010-01-19 14:06:41 +00001057 protected:
1058 ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001059
1060 /**
1061 * Internally V8 will call this Dispose method when the external string
1062 * resource is no longer needed. The default implementation will use the
1063 * delete operator. This method can be overridden in subclasses to
1064 * control how allocated external string resources are disposed.
1065 */
1066 virtual void Dispose() { delete this; }
1067
Leon Clarkee46be812010-01-19 14:06:41 +00001068 private:
1069 // Disallow copying and assigning.
1070 ExternalStringResourceBase(const ExternalStringResourceBase&);
1071 void operator=(const ExternalStringResourceBase&);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001072
1073 friend class v8::internal::Heap;
Leon Clarkee46be812010-01-19 14:06:41 +00001074 };
1075
Steve Blocka7e24c12009-10-30 11:49:00 +00001076 /**
1077 * An ExternalStringResource is a wrapper around a two-byte string
1078 * buffer that resides outside V8's heap. Implement an
1079 * ExternalStringResource to manage the life cycle of the underlying
1080 * buffer. Note that the string data must be immutable.
1081 */
Leon Clarkee46be812010-01-19 14:06:41 +00001082 class V8EXPORT ExternalStringResource
1083 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001084 public:
1085 /**
1086 * Override the destructor to manage the life cycle of the underlying
1087 * buffer.
1088 */
1089 virtual ~ExternalStringResource() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001090
1091 /**
1092 * The string data from the underlying buffer.
1093 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001094 virtual const uint16_t* data() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001095
1096 /**
1097 * The length of the string. That is, the number of two-byte characters.
1098 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001099 virtual size_t length() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001100
Steve Blocka7e24c12009-10-30 11:49:00 +00001101 protected:
1102 ExternalStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001103 };
1104
1105 /**
1106 * An ExternalAsciiStringResource is a wrapper around an ascii
1107 * string buffer that resides outside V8's heap. Implement an
1108 * ExternalAsciiStringResource to manage the life cycle of the
1109 * underlying buffer. Note that the string data must be immutable
1110 * and that the data must be strict 7-bit ASCII, not Latin1 or
1111 * UTF-8, which would require special treatment internally in the
1112 * engine and, in the case of UTF-8, do not allow efficient indexing.
1113 * Use String::New or convert to 16 bit data for non-ASCII.
1114 */
1115
Leon Clarkee46be812010-01-19 14:06:41 +00001116 class V8EXPORT ExternalAsciiStringResource
1117 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001118 public:
1119 /**
1120 * Override the destructor to manage the life cycle of the underlying
1121 * buffer.
1122 */
1123 virtual ~ExternalAsciiStringResource() {}
1124 /** The string data from the underlying buffer.*/
1125 virtual const char* data() const = 0;
1126 /** The number of ascii characters in the string.*/
1127 virtual size_t length() const = 0;
1128 protected:
1129 ExternalAsciiStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001130 };
1131
1132 /**
1133 * Get the ExternalStringResource for an external string. Returns
1134 * NULL if IsExternal() doesn't return true.
1135 */
1136 inline ExternalStringResource* GetExternalStringResource() const;
1137
1138 /**
1139 * Get the ExternalAsciiStringResource for an external ascii string.
1140 * Returns NULL if IsExternalAscii() doesn't return true.
1141 */
Steve Block8defd9f2010-07-08 12:39:36 +01001142 V8EXPORT ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001143
1144 static inline String* Cast(v8::Value* obj);
1145
1146 /**
1147 * Allocates a new string from either utf-8 encoded or ascii data.
1148 * The second parameter 'length' gives the buffer length.
1149 * If the data is utf-8 encoded, the caller must
1150 * be careful to supply the length parameter.
1151 * If it is not given, the function calls
1152 * 'strlen' to determine the buffer length, it might be
1153 * wrong if 'data' contains a null character.
1154 */
Steve Block8defd9f2010-07-08 12:39:36 +01001155 V8EXPORT static Local<String> New(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001156
1157 /** Allocates a new string from utf16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001158 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001159
1160 /** Creates a symbol. Returns one if it exists already.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001161 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001162
1163 /**
Steve Block3ce2e202009-11-05 08:53:23 +00001164 * Creates a new string by concatenating the left and the right strings
1165 * passed in as parameters.
1166 */
Steve Block8defd9f2010-07-08 12:39:36 +01001167 V8EXPORT static Local<String> Concat(Handle<String> left,
1168 Handle<String>right);
Steve Block3ce2e202009-11-05 08:53:23 +00001169
1170 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001171 * Creates a new external string using the data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001172 * resource. When the external string is no longer live on V8's heap the
1173 * resource will be disposed by calling its Dispose method. The caller of
1174 * this function should not otherwise delete or modify the resource. Neither
1175 * should the underlying buffer be deallocated or modified except through the
1176 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001177 */
Steve Block8defd9f2010-07-08 12:39:36 +01001178 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001179
1180 /**
1181 * Associate an external string resource with this string by transforming it
1182 * in place so that existing references to this string in the JavaScript heap
1183 * will use the external string resource. The external string resource's
1184 * character contents needs to be equivalent to this string.
1185 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001186 * The string is not modified if the operation fails. See NewExternal for
1187 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001188 */
Steve Block8defd9f2010-07-08 12:39:36 +01001189 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001190
1191 /**
1192 * Creates a new external string using the ascii data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001193 * resource. When the external string is no longer live on V8's heap the
1194 * resource will be disposed by calling its Dispose method. The caller of
1195 * this function should not otherwise delete or modify the resource. Neither
1196 * should the underlying buffer be deallocated or modified except through the
1197 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001198 */
Steve Block8defd9f2010-07-08 12:39:36 +01001199 V8EXPORT static Local<String> NewExternal(
1200 ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001201
1202 /**
1203 * Associate an external string resource with this string by transforming it
1204 * in place so that existing references to this string in the JavaScript heap
1205 * will use the external string resource. The external string resource's
1206 * character contents needs to be equivalent to this string.
1207 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001208 * The string is not modified if the operation fails. See NewExternal for
1209 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001210 */
Steve Block8defd9f2010-07-08 12:39:36 +01001211 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001212
1213 /**
1214 * Returns true if this string can be made external.
1215 */
Steve Block8defd9f2010-07-08 12:39:36 +01001216 V8EXPORT bool CanMakeExternal();
Steve Blocka7e24c12009-10-30 11:49:00 +00001217
1218 /** Creates an undetectable string from the supplied ascii or utf-8 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001219 V8EXPORT static Local<String> NewUndetectable(const char* data,
1220 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001221
1222 /** Creates an undetectable string from the supplied utf-16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001223 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1224 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001225
1226 /**
1227 * Converts an object to a utf8-encoded character array. Useful if
1228 * you want to print the object. If conversion to a string fails
1229 * (eg. due to an exception in the toString() method of the object)
1230 * then the length() method returns 0 and the * operator returns
1231 * NULL.
1232 */
1233 class V8EXPORT Utf8Value {
1234 public:
1235 explicit Utf8Value(Handle<v8::Value> obj);
1236 ~Utf8Value();
1237 char* operator*() { return str_; }
1238 const char* operator*() const { return str_; }
1239 int length() const { return length_; }
1240 private:
1241 char* str_;
1242 int length_;
1243
1244 // Disallow copying and assigning.
1245 Utf8Value(const Utf8Value&);
1246 void operator=(const Utf8Value&);
1247 };
1248
1249 /**
1250 * Converts an object to an ascii string.
1251 * Useful if you want to print the object.
1252 * If conversion to a string fails (eg. due to an exception in the toString()
1253 * method of the object) then the length() method returns 0 and the * operator
1254 * returns NULL.
1255 */
1256 class V8EXPORT AsciiValue {
1257 public:
1258 explicit AsciiValue(Handle<v8::Value> obj);
1259 ~AsciiValue();
1260 char* operator*() { return str_; }
1261 const char* operator*() const { return str_; }
1262 int length() const { return length_; }
1263 private:
1264 char* str_;
1265 int length_;
1266
1267 // Disallow copying and assigning.
1268 AsciiValue(const AsciiValue&);
1269 void operator=(const AsciiValue&);
1270 };
1271
1272 /**
1273 * Converts an object to a two-byte string.
1274 * If conversion to a string fails (eg. due to an exception in the toString()
1275 * method of the object) then the length() method returns 0 and the * operator
1276 * returns NULL.
1277 */
1278 class V8EXPORT Value {
1279 public:
1280 explicit Value(Handle<v8::Value> obj);
1281 ~Value();
1282 uint16_t* operator*() { return str_; }
1283 const uint16_t* operator*() const { return str_; }
1284 int length() const { return length_; }
1285 private:
1286 uint16_t* str_;
1287 int length_;
1288
1289 // Disallow copying and assigning.
1290 Value(const Value&);
1291 void operator=(const Value&);
1292 };
Steve Block3ce2e202009-11-05 08:53:23 +00001293
Steve Blocka7e24c12009-10-30 11:49:00 +00001294 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001295 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1296 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001297};
1298
1299
1300/**
1301 * A JavaScript number value (ECMA-262, 4.3.20)
1302 */
Steve Block8defd9f2010-07-08 12:39:36 +01001303class Number : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001304 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001305 V8EXPORT double Value() const;
1306 V8EXPORT static Local<Number> New(double value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001307 static inline Number* Cast(v8::Value* obj);
1308 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001309 V8EXPORT Number();
Steve Blocka7e24c12009-10-30 11:49:00 +00001310 static void CheckCast(v8::Value* obj);
1311};
1312
1313
1314/**
1315 * A JavaScript value representing a signed integer.
1316 */
Steve Block8defd9f2010-07-08 12:39:36 +01001317class Integer : public Number {
Steve Blocka7e24c12009-10-30 11:49:00 +00001318 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001319 V8EXPORT static Local<Integer> New(int32_t value);
1320 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1321 V8EXPORT int64_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001322 static inline Integer* Cast(v8::Value* obj);
1323 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001324 V8EXPORT Integer();
1325 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001326};
1327
1328
1329/**
1330 * A JavaScript value representing a 32-bit signed integer.
1331 */
Steve Block8defd9f2010-07-08 12:39:36 +01001332class Int32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001333 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001334 V8EXPORT int32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001335 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001336 V8EXPORT Int32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001337};
1338
1339
1340/**
1341 * A JavaScript value representing a 32-bit unsigned integer.
1342 */
Steve Block8defd9f2010-07-08 12:39:36 +01001343class Uint32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001344 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001345 V8EXPORT uint32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001346 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001347 V8EXPORT Uint32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001348};
1349
1350
1351/**
1352 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1353 */
Steve Block8defd9f2010-07-08 12:39:36 +01001354class Date : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001355 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001356 V8EXPORT static Local<Value> New(double time);
Steve Blocka7e24c12009-10-30 11:49:00 +00001357
1358 /**
1359 * A specialization of Value::NumberValue that is more efficient
1360 * because we know the structure of this object.
1361 */
Steve Block8defd9f2010-07-08 12:39:36 +01001362 V8EXPORT double NumberValue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001363
1364 static inline Date* Cast(v8::Value* obj);
1365 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001366 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001367};
1368
1369
Ben Murdochf87a2032010-10-22 12:50:53 +01001370/**
1371 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1372 */
1373class RegExp : public Value {
1374 public:
1375 /**
1376 * Regular expression flag bits. They can be or'ed to enable a set
1377 * of flags.
1378 */
1379 enum Flags {
1380 kNone = 0,
1381 kGlobal = 1,
1382 kIgnoreCase = 2,
1383 kMultiline = 4
1384 };
1385
1386 /**
1387 * Creates a regular expression from the given pattern string and
1388 * the flags bit field. May throw a JavaScript exception as
1389 * described in ECMA-262, 15.10.4.1.
1390 *
1391 * For example,
1392 * RegExp::New(v8::String::New("foo"),
1393 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1394 * is equivalent to evaluating "/foo/gm".
1395 */
1396 V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1397 Flags flags);
1398
1399 /**
1400 * Returns the value of the source property: a string representing
1401 * the regular expression.
1402 */
1403 V8EXPORT Local<String> GetSource() const;
1404
1405 /**
1406 * Returns the flags bit field.
1407 */
1408 V8EXPORT Flags GetFlags() const;
1409
1410 static inline RegExp* Cast(v8::Value* obj);
1411
1412 private:
1413 V8EXPORT static void CheckCast(v8::Value* obj);
1414};
1415
1416
Steve Blocka7e24c12009-10-30 11:49:00 +00001417enum PropertyAttribute {
1418 None = 0,
1419 ReadOnly = 1 << 0,
1420 DontEnum = 1 << 1,
1421 DontDelete = 1 << 2
1422};
1423
Steve Block3ce2e202009-11-05 08:53:23 +00001424enum ExternalArrayType {
1425 kExternalByteArray = 1,
1426 kExternalUnsignedByteArray,
1427 kExternalShortArray,
1428 kExternalUnsignedShortArray,
1429 kExternalIntArray,
1430 kExternalUnsignedIntArray,
1431 kExternalFloatArray
1432};
1433
Steve Blocka7e24c12009-10-30 11:49:00 +00001434/**
Leon Clarkef7060e22010-06-03 12:02:55 +01001435 * Accessor[Getter|Setter] are used as callback functions when
1436 * setting|getting a particular property. See Object and ObjectTemplate's
1437 * method SetAccessor.
1438 */
1439typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1440 const AccessorInfo& info);
1441
1442
1443typedef void (*AccessorSetter)(Local<String> property,
1444 Local<Value> value,
1445 const AccessorInfo& info);
1446
1447
1448/**
1449 * Access control specifications.
1450 *
1451 * Some accessors should be accessible across contexts. These
1452 * accessors have an explicit access control parameter which specifies
1453 * the kind of cross-context access that should be allowed.
1454 *
1455 * Additionally, for security, accessors can prohibit overwriting by
1456 * accessors defined in JavaScript. For objects that have such
1457 * accessors either locally or in their prototype chain it is not
1458 * possible to overwrite the accessor by using __defineGetter__ or
1459 * __defineSetter__ from JavaScript code.
1460 */
1461enum AccessControl {
1462 DEFAULT = 0,
1463 ALL_CAN_READ = 1,
1464 ALL_CAN_WRITE = 1 << 1,
1465 PROHIBITS_OVERWRITING = 1 << 2
1466};
1467
1468
1469/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001470 * A JavaScript object (ECMA-262, 4.3.3)
1471 */
Steve Block8defd9f2010-07-08 12:39:36 +01001472class Object : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001473 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001474 V8EXPORT bool Set(Handle<Value> key,
1475 Handle<Value> value,
1476 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001477
Steve Block8defd9f2010-07-08 12:39:36 +01001478 V8EXPORT bool Set(uint32_t index,
1479 Handle<Value> value);
Steve Block6ded16b2010-05-10 14:33:55 +01001480
Steve Blocka7e24c12009-10-30 11:49:00 +00001481 // Sets a local property on this object bypassing interceptors and
1482 // overriding accessors or read-only properties.
1483 //
1484 // Note that if the object has an interceptor the property will be set
1485 // locally, but since the interceptor takes precedence the local property
1486 // will only be returned if the interceptor doesn't return a value.
1487 //
1488 // Note also that this only works for named properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001489 V8EXPORT bool ForceSet(Handle<Value> key,
1490 Handle<Value> value,
1491 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001492
Steve Block8defd9f2010-07-08 12:39:36 +01001493 V8EXPORT Local<Value> Get(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001494
Steve Block8defd9f2010-07-08 12:39:36 +01001495 V8EXPORT Local<Value> Get(uint32_t index);
Steve Block6ded16b2010-05-10 14:33:55 +01001496
Steve Blocka7e24c12009-10-30 11:49:00 +00001497 // TODO(1245389): Replace the type-specific versions of these
1498 // functions with generic ones that accept a Handle<Value> key.
Steve Block8defd9f2010-07-08 12:39:36 +01001499 V8EXPORT bool Has(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001500
Steve Block8defd9f2010-07-08 12:39:36 +01001501 V8EXPORT bool Delete(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001502
1503 // Delete a property on this object bypassing interceptors and
1504 // ignoring dont-delete attributes.
Steve Block8defd9f2010-07-08 12:39:36 +01001505 V8EXPORT bool ForceDelete(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001506
Steve Block8defd9f2010-07-08 12:39:36 +01001507 V8EXPORT bool Has(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001508
Steve Block8defd9f2010-07-08 12:39:36 +01001509 V8EXPORT bool Delete(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001510
Steve Block8defd9f2010-07-08 12:39:36 +01001511 V8EXPORT bool SetAccessor(Handle<String> name,
1512 AccessorGetter getter,
1513 AccessorSetter setter = 0,
1514 Handle<Value> data = Handle<Value>(),
1515 AccessControl settings = DEFAULT,
1516 PropertyAttribute attribute = None);
Leon Clarkef7060e22010-06-03 12:02:55 +01001517
Steve Blocka7e24c12009-10-30 11:49:00 +00001518 /**
1519 * Returns an array containing the names of the enumerable properties
1520 * of this object, including properties from prototype objects. The
1521 * array returned by this method contains the same values as would
1522 * be enumerated by a for-in statement over this object.
1523 */
Steve Block8defd9f2010-07-08 12:39:36 +01001524 V8EXPORT Local<Array> GetPropertyNames();
Steve Blocka7e24c12009-10-30 11:49:00 +00001525
1526 /**
1527 * Get the prototype object. This does not skip objects marked to
1528 * be skipped by __proto__ and it does not consult the security
1529 * handler.
1530 */
Steve Block8defd9f2010-07-08 12:39:36 +01001531 V8EXPORT Local<Value> GetPrototype();
Steve Blocka7e24c12009-10-30 11:49:00 +00001532
1533 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001534 * Set the prototype object. This does not skip objects marked to
1535 * be skipped by __proto__ and it does not consult the security
1536 * handler.
1537 */
Steve Block8defd9f2010-07-08 12:39:36 +01001538 V8EXPORT bool SetPrototype(Handle<Value> prototype);
Andrei Popescu402d9372010-02-26 13:31:12 +00001539
1540 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001541 * Finds an instance of the given function template in the prototype
1542 * chain.
1543 */
Steve Block8defd9f2010-07-08 12:39:36 +01001544 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1545 Handle<FunctionTemplate> tmpl);
Steve Blocka7e24c12009-10-30 11:49:00 +00001546
1547 /**
1548 * Call builtin Object.prototype.toString on this object.
1549 * This is different from Value::ToString() that may call
1550 * user-defined toString function. This one does not.
1551 */
Steve Block8defd9f2010-07-08 12:39:36 +01001552 V8EXPORT Local<String> ObjectProtoToString();
Steve Blocka7e24c12009-10-30 11:49:00 +00001553
1554 /** Gets the number of internal fields for this Object. */
Steve Block8defd9f2010-07-08 12:39:36 +01001555 V8EXPORT int InternalFieldCount();
Steve Blocka7e24c12009-10-30 11:49:00 +00001556 /** Gets the value in an internal field. */
1557 inline Local<Value> GetInternalField(int index);
1558 /** Sets the value in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001559 V8EXPORT void SetInternalField(int index, Handle<Value> value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001560
1561 /** Gets a native pointer from an internal field. */
1562 inline void* GetPointerFromInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001563
Steve Blocka7e24c12009-10-30 11:49:00 +00001564 /** Sets a native pointer in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001565 V8EXPORT void SetPointerInInternalField(int index, void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001566
1567 // Testers for local properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001568 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1569 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1570 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001571
1572 /**
1573 * If result.IsEmpty() no real property was located in the prototype chain.
1574 * This means interceptors in the prototype chain are not called.
1575 */
Steve Block8defd9f2010-07-08 12:39:36 +01001576 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1577 Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001578
1579 /**
1580 * If result.IsEmpty() no real property was located on the object or
1581 * in the prototype chain.
1582 * This means interceptors in the prototype chain are not called.
1583 */
Steve Block8defd9f2010-07-08 12:39:36 +01001584 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001585
1586 /** Tests for a named lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001587 V8EXPORT bool HasNamedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001588
1589 /** Tests for an index lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001590 V8EXPORT bool HasIndexedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001591
1592 /**
1593 * Turns on access check on the object if the object is an instance of
1594 * a template that has access check callbacks. If an object has no
1595 * access check info, the object cannot be accessed by anyone.
1596 */
Steve Block8defd9f2010-07-08 12:39:36 +01001597 V8EXPORT void TurnOnAccessCheck();
Steve Blocka7e24c12009-10-30 11:49:00 +00001598
1599 /**
1600 * Returns the identity hash for this object. The current implemenation uses
1601 * a hidden property on the object to store the identity hash.
1602 *
1603 * The return value will never be 0. Also, it is not guaranteed to be
1604 * unique.
1605 */
Steve Block8defd9f2010-07-08 12:39:36 +01001606 V8EXPORT int GetIdentityHash();
Steve Blocka7e24c12009-10-30 11:49:00 +00001607
1608 /**
1609 * Access hidden properties on JavaScript objects. These properties are
1610 * hidden from the executing JavaScript and only accessible through the V8
1611 * C++ API. Hidden properties introduced by V8 internally (for example the
1612 * identity hash) are prefixed with "v8::".
1613 */
Steve Block8defd9f2010-07-08 12:39:36 +01001614 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1615 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1616 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
Steve Block3ce2e202009-11-05 08:53:23 +00001617
Steve Blocka7e24c12009-10-30 11:49:00 +00001618 /**
1619 * Returns true if this is an instance of an api function (one
1620 * created from a function created from a function template) and has
1621 * been modified since it was created. Note that this method is
1622 * conservative and may return true for objects that haven't actually
1623 * been modified.
1624 */
Steve Block8defd9f2010-07-08 12:39:36 +01001625 V8EXPORT bool IsDirty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001626
1627 /**
1628 * Clone this object with a fast but shallow copy. Values will point
1629 * to the same values as the original object.
1630 */
Steve Block8defd9f2010-07-08 12:39:36 +01001631 V8EXPORT Local<Object> Clone();
Steve Blocka7e24c12009-10-30 11:49:00 +00001632
1633 /**
1634 * Set the backing store of the indexed properties to be managed by the
1635 * embedding layer. Access to the indexed properties will follow the rules
1636 * spelled out in CanvasPixelArray.
1637 * Note: The embedding program still owns the data and needs to ensure that
1638 * the backing store is preserved while V8 has a reference.
1639 */
Steve Block8defd9f2010-07-08 12:39:36 +01001640 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001641 bool HasIndexedPropertiesInPixelData();
1642 uint8_t* GetIndexedPropertiesPixelData();
1643 int GetIndexedPropertiesPixelDataLength();
Steve Blocka7e24c12009-10-30 11:49:00 +00001644
Steve Block3ce2e202009-11-05 08:53:23 +00001645 /**
1646 * Set the backing store of the indexed properties to be managed by the
1647 * embedding layer. Access to the indexed properties will follow the rules
1648 * spelled out for the CanvasArray subtypes in the WebGL specification.
1649 * Note: The embedding program still owns the data and needs to ensure that
1650 * the backing store is preserved while V8 has a reference.
1651 */
Steve Block8defd9f2010-07-08 12:39:36 +01001652 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1653 void* data,
1654 ExternalArrayType array_type,
1655 int number_of_elements);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001656 bool HasIndexedPropertiesInExternalArrayData();
1657 void* GetIndexedPropertiesExternalArrayData();
1658 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1659 int GetIndexedPropertiesExternalArrayDataLength();
Steve Block3ce2e202009-11-05 08:53:23 +00001660
Steve Block8defd9f2010-07-08 12:39:36 +01001661 V8EXPORT static Local<Object> New();
Steve Blocka7e24c12009-10-30 11:49:00 +00001662 static inline Object* Cast(Value* obj);
1663 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001664 V8EXPORT Object();
1665 V8EXPORT static void CheckCast(Value* obj);
1666 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1667 V8EXPORT void* SlowGetPointerFromInternalField(int index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001668
1669 /**
1670 * If quick access to the internal field is possible this method
Steve Block3ce2e202009-11-05 08:53:23 +00001671 * returns the value. Otherwise an empty handle is returned.
Steve Blocka7e24c12009-10-30 11:49:00 +00001672 */
1673 inline Local<Value> UncheckedGetInternalField(int index);
1674};
1675
1676
1677/**
1678 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1679 */
Steve Block8defd9f2010-07-08 12:39:36 +01001680class Array : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001681 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001682 V8EXPORT uint32_t Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001683
1684 /**
1685 * Clones an element at index |index|. Returns an empty
1686 * handle if cloning fails (for any reason).
1687 */
Steve Block8defd9f2010-07-08 12:39:36 +01001688 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001689
Steve Block8defd9f2010-07-08 12:39:36 +01001690 V8EXPORT static Local<Array> New(int length = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001691 static inline Array* Cast(Value* obj);
1692 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001693 V8EXPORT Array();
Steve Blocka7e24c12009-10-30 11:49:00 +00001694 static void CheckCast(Value* obj);
1695};
1696
1697
1698/**
1699 * A JavaScript function object (ECMA-262, 15.3).
1700 */
Steve Block8defd9f2010-07-08 12:39:36 +01001701class Function : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001702 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001703 V8EXPORT Local<Object> NewInstance() const;
1704 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1705 V8EXPORT Local<Value> Call(Handle<Object> recv,
1706 int argc,
1707 Handle<Value> argv[]);
1708 V8EXPORT void SetName(Handle<String> name);
1709 V8EXPORT Handle<Value> GetName() const;
Andrei Popescu402d9372010-02-26 13:31:12 +00001710
1711 /**
1712 * Returns zero based line number of function body and
1713 * kLineOffsetNotFound if no information available.
1714 */
Steve Block8defd9f2010-07-08 12:39:36 +01001715 V8EXPORT int GetScriptLineNumber() const;
1716 V8EXPORT ScriptOrigin GetScriptOrigin() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001717 static inline Function* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001718 V8EXPORT static const int kLineOffsetNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00001719 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001720 V8EXPORT Function();
1721 V8EXPORT static void CheckCast(Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001722};
1723
1724
1725/**
1726 * A JavaScript value that wraps a C++ void*. This type of value is
1727 * mainly used to associate C++ data structures with JavaScript
1728 * objects.
1729 *
1730 * The Wrap function V8 will return the most optimal Value object wrapping the
1731 * C++ void*. The type of the value is not guaranteed to be an External object
1732 * and no assumptions about its type should be made. To access the wrapped
1733 * value Unwrap should be used, all other operations on that object will lead
1734 * to unpredictable results.
1735 */
Steve Block8defd9f2010-07-08 12:39:36 +01001736class External : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001737 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001738 V8EXPORT static Local<Value> Wrap(void* data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001739 static inline void* Unwrap(Handle<Value> obj);
1740
Steve Block8defd9f2010-07-08 12:39:36 +01001741 V8EXPORT static Local<External> New(void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001742 static inline External* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001743 V8EXPORT void* Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001744 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001745 V8EXPORT External();
1746 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001747 static inline void* QuickUnwrap(Handle<v8::Value> obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001748 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001749};
1750
1751
1752// --- T e m p l a t e s ---
1753
1754
1755/**
1756 * The superclass of object and function templates.
1757 */
1758class V8EXPORT Template : public Data {
1759 public:
1760 /** Adds a property to each instance created by this template.*/
1761 void Set(Handle<String> name, Handle<Data> value,
1762 PropertyAttribute attributes = None);
1763 inline void Set(const char* name, Handle<Data> value);
1764 private:
1765 Template();
1766
1767 friend class ObjectTemplate;
1768 friend class FunctionTemplate;
1769};
1770
1771
1772/**
1773 * The argument information given to function call callbacks. This
1774 * class provides access to information about the context of the call,
1775 * including the receiver, the number and values of arguments, and
1776 * the holder of the function.
1777 */
Steve Block8defd9f2010-07-08 12:39:36 +01001778class Arguments {
Steve Blocka7e24c12009-10-30 11:49:00 +00001779 public:
1780 inline int Length() const;
1781 inline Local<Value> operator[](int i) const;
1782 inline Local<Function> Callee() const;
1783 inline Local<Object> This() const;
1784 inline Local<Object> Holder() const;
1785 inline bool IsConstructCall() const;
1786 inline Local<Value> Data() const;
1787 private:
Steve Blocka7e24c12009-10-30 11:49:00 +00001788 friend class ImplementationUtilities;
1789 inline Arguments(Local<Value> data,
1790 Local<Object> holder,
1791 Local<Function> callee,
1792 bool is_construct_call,
1793 void** values, int length);
1794 Local<Value> data_;
1795 Local<Object> holder_;
1796 Local<Function> callee_;
1797 bool is_construct_call_;
1798 void** values_;
1799 int length_;
1800};
1801
1802
1803/**
1804 * The information passed to an accessor callback about the context
1805 * of the property access.
1806 */
1807class V8EXPORT AccessorInfo {
1808 public:
1809 inline AccessorInfo(internal::Object** args)
1810 : args_(args) { }
1811 inline Local<Value> Data() const;
1812 inline Local<Object> This() const;
1813 inline Local<Object> Holder() const;
1814 private:
1815 internal::Object** args_;
1816};
1817
1818
1819typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1820
Steve Blocka7e24c12009-10-30 11:49:00 +00001821/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001822 * NamedProperty[Getter|Setter] are used as interceptors on object.
1823 * See ObjectTemplate::SetNamedPropertyHandler.
1824 */
1825typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
1826 const AccessorInfo& info);
1827
1828
1829/**
1830 * Returns the value if the setter intercepts the request.
1831 * Otherwise, returns an empty handle.
1832 */
1833typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
1834 Local<Value> value,
1835 const AccessorInfo& info);
1836
Steve Blocka7e24c12009-10-30 11:49:00 +00001837/**
1838 * Returns a non-empty handle if the interceptor intercepts the request.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001839 * The result is an integer encoding property attributes (like v8::None,
1840 * v8::DontEnum, etc.)
Steve Blocka7e24c12009-10-30 11:49:00 +00001841 */
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001842typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
1843 const AccessorInfo& info);
Steve Blocka7e24c12009-10-30 11:49:00 +00001844
1845
1846/**
1847 * Returns a non-empty handle if the deleter intercepts the request.
1848 * The return value is true if the property could be deleted and false
1849 * otherwise.
1850 */
1851typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
1852 const AccessorInfo& info);
1853
1854/**
1855 * Returns an array containing the names of the properties the named
1856 * property getter intercepts.
1857 */
1858typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
1859
1860
1861/**
1862 * Returns the value of the property if the getter intercepts the
1863 * request. Otherwise, returns an empty handle.
1864 */
1865typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
1866 const AccessorInfo& info);
1867
1868
1869/**
1870 * Returns the value if the setter intercepts the request.
1871 * Otherwise, returns an empty handle.
1872 */
1873typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
1874 Local<Value> value,
1875 const AccessorInfo& info);
1876
1877
1878/**
1879 * Returns a non-empty handle if the interceptor intercepts the request.
Iain Merrick75681382010-08-19 15:07:18 +01001880 * The result is an integer encoding property attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00001881 */
Iain Merrick75681382010-08-19 15:07:18 +01001882typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
Steve Blocka7e24c12009-10-30 11:49:00 +00001883 const AccessorInfo& info);
1884
1885/**
1886 * Returns a non-empty handle if the deleter intercepts the request.
1887 * The return value is true if the property could be deleted and false
1888 * otherwise.
1889 */
1890typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
1891 const AccessorInfo& info);
1892
1893/**
1894 * Returns an array containing the indices of the properties the
1895 * indexed property getter intercepts.
1896 */
1897typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
1898
1899
1900/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001901 * Access type specification.
1902 */
1903enum AccessType {
1904 ACCESS_GET,
1905 ACCESS_SET,
1906 ACCESS_HAS,
1907 ACCESS_DELETE,
1908 ACCESS_KEYS
1909};
1910
1911
1912/**
1913 * Returns true if cross-context access should be allowed to the named
1914 * property with the given key on the host object.
1915 */
1916typedef bool (*NamedSecurityCallback)(Local<Object> host,
1917 Local<Value> key,
1918 AccessType type,
1919 Local<Value> data);
1920
1921
1922/**
1923 * Returns true if cross-context access should be allowed to the indexed
1924 * property with the given index on the host object.
1925 */
1926typedef bool (*IndexedSecurityCallback)(Local<Object> host,
1927 uint32_t index,
1928 AccessType type,
1929 Local<Value> data);
1930
1931
1932/**
1933 * A FunctionTemplate is used to create functions at runtime. There
1934 * can only be one function created from a FunctionTemplate in a
1935 * context. The lifetime of the created function is equal to the
1936 * lifetime of the context. So in case the embedder needs to create
1937 * temporary functions that can be collected using Scripts is
1938 * preferred.
1939 *
1940 * A FunctionTemplate can have properties, these properties are added to the
1941 * function object when it is created.
1942 *
1943 * A FunctionTemplate has a corresponding instance template which is
1944 * used to create object instances when the function is used as a
1945 * constructor. Properties added to the instance template are added to
1946 * each object instance.
1947 *
1948 * A FunctionTemplate can have a prototype template. The prototype template
1949 * is used to create the prototype object of the function.
1950 *
1951 * The following example shows how to use a FunctionTemplate:
1952 *
1953 * \code
1954 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
1955 * t->Set("func_property", v8::Number::New(1));
1956 *
1957 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
1958 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
1959 * proto_t->Set("proto_const", v8::Number::New(2));
1960 *
1961 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
1962 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
1963 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
1964 * instance_t->Set("instance_property", Number::New(3));
1965 *
1966 * v8::Local<v8::Function> function = t->GetFunction();
1967 * v8::Local<v8::Object> instance = function->NewInstance();
1968 * \endcode
1969 *
1970 * Let's use "function" as the JS variable name of the function object
1971 * and "instance" for the instance object created above. The function
1972 * and the instance will have the following properties:
1973 *
1974 * \code
1975 * func_property in function == true;
1976 * function.func_property == 1;
1977 *
1978 * function.prototype.proto_method() invokes 'InvokeCallback'
1979 * function.prototype.proto_const == 2;
1980 *
1981 * instance instanceof function == true;
1982 * instance.instance_accessor calls 'InstanceAccessorCallback'
1983 * instance.instance_property == 3;
1984 * \endcode
1985 *
1986 * A FunctionTemplate can inherit from another one by calling the
1987 * FunctionTemplate::Inherit method. The following graph illustrates
1988 * the semantics of inheritance:
1989 *
1990 * \code
1991 * FunctionTemplate Parent -> Parent() . prototype -> { }
1992 * ^ ^
1993 * | Inherit(Parent) | .__proto__
1994 * | |
1995 * FunctionTemplate Child -> Child() . prototype -> { }
1996 * \endcode
1997 *
1998 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
1999 * object of the Child() function has __proto__ pointing to the
2000 * Parent() function's prototype object. An instance of the Child
2001 * function has all properties on Parent's instance templates.
2002 *
2003 * Let Parent be the FunctionTemplate initialized in the previous
2004 * section and create a Child FunctionTemplate by:
2005 *
2006 * \code
2007 * Local<FunctionTemplate> parent = t;
2008 * Local<FunctionTemplate> child = FunctionTemplate::New();
2009 * child->Inherit(parent);
2010 *
2011 * Local<Function> child_function = child->GetFunction();
2012 * Local<Object> child_instance = child_function->NewInstance();
2013 * \endcode
2014 *
2015 * The Child function and Child instance will have the following
2016 * properties:
2017 *
2018 * \code
2019 * child_func.prototype.__proto__ == function.prototype;
2020 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2021 * child_instance.instance_property == 3;
2022 * \endcode
2023 */
2024class V8EXPORT FunctionTemplate : public Template {
2025 public:
2026 /** Creates a function template.*/
2027 static Local<FunctionTemplate> New(
2028 InvocationCallback callback = 0,
2029 Handle<Value> data = Handle<Value>(),
2030 Handle<Signature> signature = Handle<Signature>());
2031 /** Returns the unique function instance in the current execution context.*/
2032 Local<Function> GetFunction();
2033
2034 /**
2035 * Set the call-handler callback for a FunctionTemplate. This
2036 * callback is called whenever the function created from this
2037 * FunctionTemplate is called.
2038 */
2039 void SetCallHandler(InvocationCallback callback,
2040 Handle<Value> data = Handle<Value>());
2041
2042 /** Get the InstanceTemplate. */
2043 Local<ObjectTemplate> InstanceTemplate();
2044
2045 /** Causes the function template to inherit from a parent function template.*/
2046 void Inherit(Handle<FunctionTemplate> parent);
2047
2048 /**
2049 * A PrototypeTemplate is the template used to create the prototype object
2050 * of the function created by this template.
2051 */
2052 Local<ObjectTemplate> PrototypeTemplate();
2053
2054
2055 /**
2056 * Set the class name of the FunctionTemplate. This is used for
2057 * printing objects created with the function created from the
2058 * FunctionTemplate as its constructor.
2059 */
2060 void SetClassName(Handle<String> name);
2061
2062 /**
2063 * Determines whether the __proto__ accessor ignores instances of
2064 * the function template. If instances of the function template are
2065 * ignored, __proto__ skips all instances and instead returns the
2066 * next object in the prototype chain.
2067 *
2068 * Call with a value of true to make the __proto__ accessor ignore
2069 * instances of the function template. Call with a value of false
2070 * to make the __proto__ accessor not ignore instances of the
2071 * function template. By default, instances of a function template
2072 * are not ignored.
2073 */
2074 void SetHiddenPrototype(bool value);
2075
2076 /**
2077 * Returns true if the given object is an instance of this function
2078 * template.
2079 */
2080 bool HasInstance(Handle<Value> object);
2081
2082 private:
2083 FunctionTemplate();
2084 void AddInstancePropertyAccessor(Handle<String> name,
2085 AccessorGetter getter,
2086 AccessorSetter setter,
2087 Handle<Value> data,
2088 AccessControl settings,
2089 PropertyAttribute attributes);
2090 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2091 NamedPropertySetter setter,
2092 NamedPropertyQuery query,
2093 NamedPropertyDeleter remover,
2094 NamedPropertyEnumerator enumerator,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002095 Handle<Value> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00002096 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2097 IndexedPropertySetter setter,
2098 IndexedPropertyQuery query,
2099 IndexedPropertyDeleter remover,
2100 IndexedPropertyEnumerator enumerator,
2101 Handle<Value> data);
2102 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2103 Handle<Value> data);
2104
2105 friend class Context;
2106 friend class ObjectTemplate;
2107};
2108
2109
2110/**
2111 * An ObjectTemplate is used to create objects at runtime.
2112 *
2113 * Properties added to an ObjectTemplate are added to each object
2114 * created from the ObjectTemplate.
2115 */
2116class V8EXPORT ObjectTemplate : public Template {
2117 public:
2118 /** Creates an ObjectTemplate. */
2119 static Local<ObjectTemplate> New();
2120
2121 /** Creates a new instance of this template.*/
2122 Local<Object> NewInstance();
2123
2124 /**
2125 * Sets an accessor on the object template.
2126 *
2127 * Whenever the property with the given name is accessed on objects
2128 * created from this ObjectTemplate the getter and setter callbacks
2129 * are called instead of getting and setting the property directly
2130 * on the JavaScript object.
2131 *
2132 * \param name The name of the property for which an accessor is added.
2133 * \param getter The callback to invoke when getting the property.
2134 * \param setter The callback to invoke when setting the property.
2135 * \param data A piece of data that will be passed to the getter and setter
2136 * callbacks whenever they are invoked.
2137 * \param settings Access control settings for the accessor. This is a bit
2138 * field consisting of one of more of
2139 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2140 * The default is to not allow cross-context access.
2141 * ALL_CAN_READ means that all cross-context reads are allowed.
2142 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2143 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2144 * cross-context access.
2145 * \param attribute The attributes of the property for which an accessor
2146 * is added.
2147 */
2148 void SetAccessor(Handle<String> name,
2149 AccessorGetter getter,
2150 AccessorSetter setter = 0,
2151 Handle<Value> data = Handle<Value>(),
2152 AccessControl settings = DEFAULT,
2153 PropertyAttribute attribute = None);
2154
2155 /**
2156 * Sets a named property handler on the object template.
2157 *
2158 * Whenever a named property is accessed on objects created from
2159 * this object template, the provided callback is invoked instead of
2160 * accessing the property directly on the JavaScript object.
2161 *
2162 * \param getter The callback to invoke when getting a property.
2163 * \param setter The callback to invoke when setting a property.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002164 * \param query The callback to invoke to check if a property is present,
2165 * and if present, get its attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00002166 * \param deleter The callback to invoke when deleting a property.
2167 * \param enumerator The callback to invoke to enumerate all the named
2168 * properties of an object.
2169 * \param data A piece of data that will be passed to the callbacks
2170 * whenever they are invoked.
2171 */
2172 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2173 NamedPropertySetter setter = 0,
2174 NamedPropertyQuery query = 0,
2175 NamedPropertyDeleter deleter = 0,
2176 NamedPropertyEnumerator enumerator = 0,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002177 Handle<Value> data = Handle<Value>());
Steve Blocka7e24c12009-10-30 11:49:00 +00002178
2179 /**
2180 * Sets an indexed property handler on the object template.
2181 *
2182 * Whenever an indexed property is accessed on objects created from
2183 * this object template, the provided callback is invoked instead of
2184 * accessing the property directly on the JavaScript object.
2185 *
2186 * \param getter The callback to invoke when getting a property.
2187 * \param setter The callback to invoke when setting a property.
2188 * \param query The callback to invoke to check is an object has a property.
2189 * \param deleter The callback to invoke when deleting a property.
2190 * \param enumerator The callback to invoke to enumerate all the indexed
2191 * properties of an object.
2192 * \param data A piece of data that will be passed to the callbacks
2193 * whenever they are invoked.
2194 */
2195 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2196 IndexedPropertySetter setter = 0,
2197 IndexedPropertyQuery query = 0,
2198 IndexedPropertyDeleter deleter = 0,
2199 IndexedPropertyEnumerator enumerator = 0,
2200 Handle<Value> data = Handle<Value>());
Iain Merrick75681382010-08-19 15:07:18 +01002201
Steve Blocka7e24c12009-10-30 11:49:00 +00002202 /**
2203 * Sets the callback to be used when calling instances created from
2204 * this template as a function. If no callback is set, instances
2205 * behave like normal JavaScript objects that cannot be called as a
2206 * function.
2207 */
2208 void SetCallAsFunctionHandler(InvocationCallback callback,
2209 Handle<Value> data = Handle<Value>());
2210
2211 /**
2212 * Mark object instances of the template as undetectable.
2213 *
2214 * In many ways, undetectable objects behave as though they are not
2215 * there. They behave like 'undefined' in conditionals and when
2216 * printed. However, properties can be accessed and called as on
2217 * normal objects.
2218 */
2219 void MarkAsUndetectable();
2220
2221 /**
2222 * Sets access check callbacks on the object template.
2223 *
2224 * When accessing properties on instances of this object template,
2225 * the access check callback will be called to determine whether or
2226 * not to allow cross-context access to the properties.
2227 * The last parameter specifies whether access checks are turned
2228 * on by default on instances. If access checks are off by default,
2229 * they can be turned on on individual instances by calling
2230 * Object::TurnOnAccessCheck().
2231 */
2232 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2233 IndexedSecurityCallback indexed_handler,
2234 Handle<Value> data = Handle<Value>(),
2235 bool turned_on_by_default = true);
2236
2237 /**
2238 * Gets the number of internal fields for objects generated from
2239 * this template.
2240 */
2241 int InternalFieldCount();
2242
2243 /**
2244 * Sets the number of internal fields for objects generated from
2245 * this template.
2246 */
2247 void SetInternalFieldCount(int value);
2248
2249 private:
2250 ObjectTemplate();
2251 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2252 friend class FunctionTemplate;
2253};
2254
2255
2256/**
2257 * A Signature specifies which receivers and arguments a function can
2258 * legally be called with.
2259 */
2260class V8EXPORT Signature : public Data {
2261 public:
2262 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2263 Handle<FunctionTemplate>(),
2264 int argc = 0,
2265 Handle<FunctionTemplate> argv[] = 0);
2266 private:
2267 Signature();
2268};
2269
2270
2271/**
2272 * A utility for determining the type of objects based on the template
2273 * they were constructed from.
2274 */
2275class V8EXPORT TypeSwitch : public Data {
2276 public:
2277 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2278 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2279 int match(Handle<Value> value);
2280 private:
2281 TypeSwitch();
2282};
2283
2284
2285// --- E x t e n s i o n s ---
2286
2287
2288/**
2289 * Ignore
2290 */
2291class V8EXPORT Extension { // NOLINT
2292 public:
2293 Extension(const char* name,
2294 const char* source = 0,
2295 int dep_count = 0,
2296 const char** deps = 0);
2297 virtual ~Extension() { }
2298 virtual v8::Handle<v8::FunctionTemplate>
2299 GetNativeFunction(v8::Handle<v8::String> name) {
2300 return v8::Handle<v8::FunctionTemplate>();
2301 }
2302
2303 const char* name() { return name_; }
2304 const char* source() { return source_; }
2305 int dependency_count() { return dep_count_; }
2306 const char** dependencies() { return deps_; }
2307 void set_auto_enable(bool value) { auto_enable_ = value; }
2308 bool auto_enable() { return auto_enable_; }
2309
2310 private:
2311 const char* name_;
2312 const char* source_;
2313 int dep_count_;
2314 const char** deps_;
2315 bool auto_enable_;
2316
2317 // Disallow copying and assigning.
2318 Extension(const Extension&);
2319 void operator=(const Extension&);
2320};
2321
2322
2323void V8EXPORT RegisterExtension(Extension* extension);
2324
2325
2326/**
2327 * Ignore
2328 */
2329class V8EXPORT DeclareExtension {
2330 public:
2331 inline DeclareExtension(Extension* extension) {
2332 RegisterExtension(extension);
2333 }
2334};
2335
2336
2337// --- S t a t i c s ---
2338
2339
2340Handle<Primitive> V8EXPORT Undefined();
2341Handle<Primitive> V8EXPORT Null();
2342Handle<Boolean> V8EXPORT True();
2343Handle<Boolean> V8EXPORT False();
2344
2345
2346/**
2347 * A set of constraints that specifies the limits of the runtime's memory use.
2348 * You must set the heap size before initializing the VM - the size cannot be
2349 * adjusted after the VM is initialized.
2350 *
2351 * If you are using threads then you should hold the V8::Locker lock while
2352 * setting the stack limit and you must set a non-default stack limit separately
2353 * for each thread.
2354 */
2355class V8EXPORT ResourceConstraints {
2356 public:
2357 ResourceConstraints();
2358 int max_young_space_size() const { return max_young_space_size_; }
2359 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2360 int max_old_space_size() const { return max_old_space_size_; }
2361 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
2362 uint32_t* stack_limit() const { return stack_limit_; }
2363 // Sets an address beyond which the VM's stack may not grow.
2364 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2365 private:
2366 int max_young_space_size_;
2367 int max_old_space_size_;
2368 uint32_t* stack_limit_;
2369};
2370
2371
Kristian Monsen25f61362010-05-21 11:50:48 +01002372bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
Steve Blocka7e24c12009-10-30 11:49:00 +00002373
2374
2375// --- E x c e p t i o n s ---
2376
2377
2378typedef void (*FatalErrorCallback)(const char* location, const char* message);
2379
2380
2381typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2382
2383
2384/**
2385 * Schedules an exception to be thrown when returning to JavaScript. When an
2386 * exception has been scheduled it is illegal to invoke any JavaScript
2387 * operation; the caller must return immediately and only after the exception
2388 * has been handled does it become legal to invoke JavaScript operations.
2389 */
2390Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2391
2392/**
2393 * Create new error objects by calling the corresponding error object
2394 * constructor with the message.
2395 */
2396class V8EXPORT Exception {
2397 public:
2398 static Local<Value> RangeError(Handle<String> message);
2399 static Local<Value> ReferenceError(Handle<String> message);
2400 static Local<Value> SyntaxError(Handle<String> message);
2401 static Local<Value> TypeError(Handle<String> message);
2402 static Local<Value> Error(Handle<String> message);
2403};
2404
2405
2406// --- C o u n t e r s C a l l b a c k s ---
2407
2408typedef int* (*CounterLookupCallback)(const char* name);
2409
2410typedef void* (*CreateHistogramCallback)(const char* name,
2411 int min,
2412 int max,
2413 size_t buckets);
2414
2415typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2416
Iain Merrick9ac36c92010-09-13 15:29:50 +01002417// --- M e m o r y A l l o c a t i o n C a l l b a c k ---
2418 enum ObjectSpace {
2419 kObjectSpaceNewSpace = 1 << 0,
2420 kObjectSpaceOldPointerSpace = 1 << 1,
2421 kObjectSpaceOldDataSpace = 1 << 2,
2422 kObjectSpaceCodeSpace = 1 << 3,
2423 kObjectSpaceMapSpace = 1 << 4,
2424 kObjectSpaceLoSpace = 1 << 5,
2425
2426 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2427 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2428 kObjectSpaceLoSpace
2429 };
2430
2431 enum AllocationAction {
2432 kAllocationActionAllocate = 1 << 0,
2433 kAllocationActionFree = 1 << 1,
2434 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2435 };
2436
2437typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2438 AllocationAction action,
2439 int size);
2440
Steve Blocka7e24c12009-10-30 11:49:00 +00002441// --- 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 ---
2442typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2443 AccessType type,
2444 Local<Value> data);
2445
2446// --- 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
2447
2448/**
Steve Block6ded16b2010-05-10 14:33:55 +01002449 * Applications can register callback functions which will be called
2450 * before and after a garbage collection. Allocations are not
2451 * allowed in the callback functions, you therefore cannot manipulate
Steve Blocka7e24c12009-10-30 11:49:00 +00002452 * objects (set or delete properties for example) since it is possible
2453 * such operations will result in the allocation of objects.
2454 */
Steve Block6ded16b2010-05-10 14:33:55 +01002455enum GCType {
2456 kGCTypeScavenge = 1 << 0,
2457 kGCTypeMarkSweepCompact = 1 << 1,
2458 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2459};
2460
2461enum GCCallbackFlags {
2462 kNoGCCallbackFlags = 0,
2463 kGCCallbackFlagCompacted = 1 << 0
2464};
2465
2466typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2467typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2468
Steve Blocka7e24c12009-10-30 11:49:00 +00002469typedef void (*GCCallback)();
2470
2471
Steve Blocka7e24c12009-10-30 11:49:00 +00002472/**
2473 * Profiler modules.
2474 *
2475 * In V8, profiler consists of several modules: CPU profiler, and different
2476 * kinds of heap profiling. Each can be turned on / off independently.
2477 * When PROFILER_MODULE_HEAP_SNAPSHOT flag is passed to ResumeProfilerEx,
2478 * modules are enabled only temporarily for making a snapshot of the heap.
2479 */
2480enum ProfilerModules {
2481 PROFILER_MODULE_NONE = 0,
2482 PROFILER_MODULE_CPU = 1,
2483 PROFILER_MODULE_HEAP_STATS = 1 << 1,
2484 PROFILER_MODULE_JS_CONSTRUCTORS = 1 << 2,
2485 PROFILER_MODULE_HEAP_SNAPSHOT = 1 << 16
2486};
2487
2488
2489/**
Steve Block3ce2e202009-11-05 08:53:23 +00002490 * Collection of V8 heap information.
2491 *
2492 * Instances of this class can be passed to v8::V8::HeapStatistics to
2493 * get heap statistics from V8.
2494 */
2495class V8EXPORT HeapStatistics {
2496 public:
2497 HeapStatistics();
2498 size_t total_heap_size() { return total_heap_size_; }
2499 size_t used_heap_size() { return used_heap_size_; }
2500
2501 private:
2502 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
2503 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2504
2505 size_t total_heap_size_;
2506 size_t used_heap_size_;
2507
2508 friend class V8;
2509};
2510
2511
2512/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002513 * Container class for static utility functions.
2514 */
2515class V8EXPORT V8 {
2516 public:
2517 /** Set the callback to invoke in case of fatal errors. */
2518 static void SetFatalErrorHandler(FatalErrorCallback that);
2519
2520 /**
2521 * Ignore out-of-memory exceptions.
2522 *
2523 * V8 running out of memory is treated as a fatal error by default.
2524 * This means that the fatal error handler is called and that V8 is
2525 * terminated.
2526 *
2527 * IgnoreOutOfMemoryException can be used to not treat a
2528 * out-of-memory situation as a fatal error. This way, the contexts
2529 * that did not cause the out of memory problem might be able to
2530 * continue execution.
2531 */
2532 static void IgnoreOutOfMemoryException();
2533
2534 /**
2535 * Check if V8 is dead and therefore unusable. This is the case after
2536 * fatal errors such as out-of-memory situations.
2537 */
2538 static bool IsDead();
2539
2540 /**
2541 * Adds a message listener.
2542 *
2543 * The same message listener can be added more than once and it that
2544 * case it will be called more than once for each message.
2545 */
2546 static bool AddMessageListener(MessageCallback that,
2547 Handle<Value> data = Handle<Value>());
2548
2549 /**
2550 * Remove all message listeners from the specified callback function.
2551 */
2552 static void RemoveMessageListeners(MessageCallback that);
2553
2554 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002555 * Tells V8 to capture current stack trace when uncaught exception occurs
2556 * and report it to the message listeners. The option is off by default.
2557 */
2558 static void SetCaptureStackTraceForUncaughtExceptions(
2559 bool capture,
2560 int frame_limit = 10,
2561 StackTrace::StackTraceOptions options = StackTrace::kOverview);
2562
2563 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002564 * Sets V8 flags from a string.
2565 */
2566 static void SetFlagsFromString(const char* str, int length);
2567
2568 /**
2569 * Sets V8 flags from the command line.
2570 */
2571 static void SetFlagsFromCommandLine(int* argc,
2572 char** argv,
2573 bool remove_flags);
2574
2575 /** Get the version string. */
2576 static const char* GetVersion();
2577
2578 /**
2579 * Enables the host application to provide a mechanism for recording
2580 * statistics counters.
2581 */
2582 static void SetCounterFunction(CounterLookupCallback);
2583
2584 /**
2585 * Enables the host application to provide a mechanism for recording
2586 * histograms. The CreateHistogram function returns a
2587 * histogram which will later be passed to the AddHistogramSample
2588 * function.
2589 */
2590 static void SetCreateHistogramFunction(CreateHistogramCallback);
2591 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2592
2593 /**
2594 * Enables the computation of a sliding window of states. The sliding
2595 * window information is recorded in statistics counters.
2596 */
2597 static void EnableSlidingStateWindow();
2598
2599 /** Callback function for reporting failed access checks.*/
2600 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2601
2602 /**
2603 * Enables the host application to receive a notification before a
Steve Block6ded16b2010-05-10 14:33:55 +01002604 * garbage collection. Allocations are not allowed in the
2605 * callback function, you therefore cannot manipulate objects (set
2606 * or delete properties for example) since it is possible such
2607 * operations will result in the allocation of objects. It is possible
2608 * to specify the GCType filter for your callback. But it is not possible to
2609 * register the same callback function two times with different
2610 * GCType filters.
2611 */
2612 static void AddGCPrologueCallback(
2613 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
2614
2615 /**
2616 * This function removes callback which was installed by
2617 * AddGCPrologueCallback function.
2618 */
2619 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
2620
2621 /**
2622 * The function is deprecated. Please use AddGCPrologueCallback instead.
2623 * Enables the host application to receive a notification before a
2624 * garbage collection. Allocations are not allowed in the
Steve Blocka7e24c12009-10-30 11:49:00 +00002625 * callback function, you therefore cannot manipulate objects (set
2626 * or delete properties for example) since it is possible such
2627 * operations will result in the allocation of objects.
2628 */
2629 static void SetGlobalGCPrologueCallback(GCCallback);
2630
2631 /**
2632 * Enables the host application to receive a notification after a
Steve Block6ded16b2010-05-10 14:33:55 +01002633 * garbage collection. Allocations are not allowed in the
2634 * callback function, you therefore cannot manipulate objects (set
2635 * or delete properties for example) since it is possible such
2636 * operations will result in the allocation of objects. It is possible
2637 * to specify the GCType filter for your callback. But it is not possible to
2638 * register the same callback function two times with different
2639 * GCType filters.
2640 */
2641 static void AddGCEpilogueCallback(
2642 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
2643
2644 /**
2645 * This function removes callback which was installed by
2646 * AddGCEpilogueCallback function.
2647 */
2648 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
2649
2650 /**
2651 * The function is deprecated. Please use AddGCEpilogueCallback instead.
2652 * Enables the host application to receive a notification after a
Steve Blocka7e24c12009-10-30 11:49:00 +00002653 * major garbage collection. Allocations are not allowed in the
2654 * callback function, you therefore cannot manipulate objects (set
2655 * or delete properties for example) since it is possible such
2656 * operations will result in the allocation of objects.
2657 */
2658 static void SetGlobalGCEpilogueCallback(GCCallback);
2659
2660 /**
Iain Merrick9ac36c92010-09-13 15:29:50 +01002661 * Enables the host application to provide a mechanism to be notified
2662 * and perform custom logging when V8 Allocates Executable Memory.
2663 */
2664 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
2665 ObjectSpace space,
2666 AllocationAction action);
2667
2668 /**
2669 * This function removes callback which was installed by
2670 * AddMemoryAllocationCallback function.
2671 */
2672 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
2673
2674 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002675 * Allows the host application to group objects together. If one
2676 * object in the group is alive, all objects in the group are alive.
2677 * After each garbage collection, object groups are removed. It is
2678 * intended to be used in the before-garbage-collection callback
2679 * function, for instance to simulate DOM tree connections among JS
2680 * wrapper objects.
2681 */
2682 static void AddObjectGroup(Persistent<Value>* objects, size_t length);
2683
2684 /**
2685 * Initializes from snapshot if possible. Otherwise, attempts to
2686 * initialize from scratch. This function is called implicitly if
2687 * you use the API without calling it first.
2688 */
2689 static bool Initialize();
2690
2691 /**
2692 * Adjusts the amount of registered external memory. Used to give
2693 * V8 an indication of the amount of externally allocated memory
2694 * that is kept alive by JavaScript objects. V8 uses this to decide
2695 * when to perform global garbage collections. Registering
2696 * externally allocated memory will trigger global garbage
2697 * collections more often than otherwise in an attempt to garbage
2698 * collect the JavaScript objects keeping the externally allocated
2699 * memory alive.
2700 *
2701 * \param change_in_bytes the change in externally allocated memory
2702 * that is kept alive by JavaScript objects.
2703 * \returns the adjusted value.
2704 */
2705 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
2706
2707 /**
2708 * Suspends recording of tick samples in the profiler.
2709 * When the V8 profiling mode is enabled (usually via command line
2710 * switches) this function suspends recording of tick samples.
2711 * Profiling ticks are discarded until ResumeProfiler() is called.
2712 *
2713 * See also the --prof and --prof_auto command line switches to
2714 * enable V8 profiling.
2715 */
2716 static void PauseProfiler();
2717
2718 /**
2719 * Resumes recording of tick samples in the profiler.
2720 * See also PauseProfiler().
2721 */
2722 static void ResumeProfiler();
2723
2724 /**
2725 * Return whether profiler is currently paused.
2726 */
2727 static bool IsProfilerPaused();
2728
2729 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002730 * Resumes specified profiler modules. Can be called several times to
2731 * mark the opening of a profiler events block with the given tag.
2732 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002733 * "ResumeProfiler" is equivalent to "ResumeProfilerEx(PROFILER_MODULE_CPU)".
2734 * See ProfilerModules enum.
2735 *
2736 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002737 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002738 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002739 static void ResumeProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002740
2741 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002742 * Pauses specified profiler modules. Each call to "PauseProfilerEx" closes
2743 * a block of profiler events opened by a call to "ResumeProfilerEx" with the
2744 * same tag value. There is no need for blocks to be properly nested.
2745 * The profiler is paused when the last opened block is closed.
2746 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002747 * "PauseProfiler" is equivalent to "PauseProfilerEx(PROFILER_MODULE_CPU)".
2748 * See ProfilerModules enum.
2749 *
2750 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002751 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002752 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002753 static void PauseProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002754
2755 /**
2756 * Returns active (resumed) profiler modules.
2757 * See ProfilerModules enum.
2758 *
2759 * \returns active profiler modules.
2760 */
2761 static int GetActiveProfilerModules();
2762
2763 /**
2764 * If logging is performed into a memory buffer (via --logfile=*), allows to
2765 * retrieve previously written messages. This can be used for retrieving
2766 * profiler log data in the application. This function is thread-safe.
2767 *
2768 * Caller provides a destination buffer that must exist during GetLogLines
2769 * call. Only whole log lines are copied into the buffer.
2770 *
2771 * \param from_pos specified a point in a buffer to read from, 0 is the
2772 * beginning of a buffer. It is assumed that caller updates its current
2773 * position using returned size value from the previous call.
2774 * \param dest_buf destination buffer for log data.
2775 * \param max_size size of the destination buffer.
2776 * \returns actual size of log data copied into buffer.
2777 */
2778 static int GetLogLines(int from_pos, char* dest_buf, int max_size);
2779
2780 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002781 * The minimum allowed size for a log lines buffer. If the size of
2782 * the buffer given will not be enough to hold a line of the maximum
2783 * length, an attempt to find a log line end in GetLogLines will
2784 * fail, and an empty result will be returned.
2785 */
2786 static const int kMinimumSizeForLogLinesBuffer = 2048;
2787
2788 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002789 * Retrieve the V8 thread id of the calling thread.
2790 *
2791 * The thread id for a thread should only be retrieved after the V8
2792 * lock has been acquired with a Locker object with that thread.
2793 */
2794 static int GetCurrentThreadId();
2795
2796 /**
2797 * Forcefully terminate execution of a JavaScript thread. This can
2798 * be used to terminate long-running scripts.
2799 *
2800 * TerminateExecution should only be called when then V8 lock has
2801 * been acquired with a Locker object. Therefore, in order to be
2802 * able to terminate long-running threads, preemption must be
2803 * enabled to allow the user of TerminateExecution to acquire the
2804 * lock.
2805 *
2806 * The termination is achieved by throwing an exception that is
2807 * uncatchable by JavaScript exception handlers. Termination
2808 * exceptions act as if they were caught by a C++ TryCatch exception
2809 * handlers. If forceful termination is used, any C++ TryCatch
2810 * exception handler that catches an exception should check if that
2811 * exception is a termination exception and immediately return if
2812 * that is the case. Returning immediately in that case will
2813 * continue the propagation of the termination exception if needed.
2814 *
2815 * The thread id passed to TerminateExecution must have been
2816 * obtained by calling GetCurrentThreadId on the thread in question.
2817 *
2818 * \param thread_id The thread id of the thread to terminate.
2819 */
2820 static void TerminateExecution(int thread_id);
2821
2822 /**
2823 * Forcefully terminate the current thread of JavaScript execution.
2824 *
2825 * This method can be used by any thread even if that thread has not
2826 * acquired the V8 lock with a Locker object.
2827 */
2828 static void TerminateExecution();
2829
2830 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002831 * Is V8 terminating JavaScript execution.
2832 *
2833 * Returns true if JavaScript execution is currently terminating
2834 * because of a call to TerminateExecution. In that case there are
2835 * still JavaScript frames on the stack and the termination
2836 * exception is still active.
2837 */
2838 static bool IsExecutionTerminating();
2839
2840 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002841 * Releases any resources used by v8 and stops any utility threads
2842 * that may be running. Note that disposing v8 is permanent, it
2843 * cannot be reinitialized.
2844 *
2845 * It should generally not be necessary to dispose v8 before exiting
2846 * a process, this should happen automatically. It is only necessary
2847 * to use if the process needs the resources taken up by v8.
2848 */
2849 static bool Dispose();
2850
Steve Block3ce2e202009-11-05 08:53:23 +00002851 /**
2852 * Get statistics about the heap memory usage.
2853 */
2854 static void GetHeapStatistics(HeapStatistics* heap_statistics);
Steve Blocka7e24c12009-10-30 11:49:00 +00002855
2856 /**
2857 * Optional notification that the embedder is idle.
2858 * V8 uses the notification to reduce memory footprint.
2859 * This call can be used repeatedly if the embedder remains idle.
Steve Blocka7e24c12009-10-30 11:49:00 +00002860 * Returns true if the embedder should stop calling IdleNotification
2861 * until real work has been done. This indicates that V8 has done
2862 * as much cleanup as it will be able to do.
2863 */
Steve Block3ce2e202009-11-05 08:53:23 +00002864 static bool IdleNotification();
Steve Blocka7e24c12009-10-30 11:49:00 +00002865
2866 /**
2867 * Optional notification that the system is running low on memory.
2868 * V8 uses these notifications to attempt to free memory.
2869 */
2870 static void LowMemoryNotification();
2871
Steve Block6ded16b2010-05-10 14:33:55 +01002872 /**
2873 * Optional notification that a context has been disposed. V8 uses
2874 * these notifications to guide the GC heuristic. Returns the number
2875 * of context disposals - including this one - since the last time
2876 * V8 had a chance to clean up.
2877 */
2878 static int ContextDisposedNotification();
2879
Steve Blocka7e24c12009-10-30 11:49:00 +00002880 private:
2881 V8();
2882
2883 static internal::Object** GlobalizeReference(internal::Object** handle);
2884 static void DisposeGlobal(internal::Object** global_handle);
2885 static void MakeWeak(internal::Object** global_handle,
2886 void* data,
2887 WeakReferenceCallback);
2888 static void ClearWeak(internal::Object** global_handle);
2889 static bool IsGlobalNearDeath(internal::Object** global_handle);
2890 static bool IsGlobalWeak(internal::Object** global_handle);
2891
2892 template <class T> friend class Handle;
2893 template <class T> friend class Local;
2894 template <class T> friend class Persistent;
2895 friend class Context;
2896};
2897
2898
2899/**
2900 * An external exception handler.
2901 */
2902class V8EXPORT TryCatch {
2903 public:
2904
2905 /**
2906 * Creates a new try/catch block and registers it with v8.
2907 */
2908 TryCatch();
2909
2910 /**
2911 * Unregisters and deletes this try/catch block.
2912 */
2913 ~TryCatch();
2914
2915 /**
2916 * Returns true if an exception has been caught by this try/catch block.
2917 */
2918 bool HasCaught() const;
2919
2920 /**
2921 * For certain types of exceptions, it makes no sense to continue
2922 * execution.
2923 *
2924 * Currently, the only type of exception that can be caught by a
2925 * TryCatch handler and for which it does not make sense to continue
2926 * is termination exception. Such exceptions are thrown when the
2927 * TerminateExecution methods are called to terminate a long-running
2928 * script.
2929 *
2930 * If CanContinue returns false, the correct action is to perform
2931 * any C++ cleanup needed and then return.
2932 */
2933 bool CanContinue() const;
2934
2935 /**
Steve Blockd0582a62009-12-15 09:54:21 +00002936 * Throws the exception caught by this TryCatch in a way that avoids
2937 * it being caught again by this same TryCatch. As with ThrowException
2938 * it is illegal to execute any JavaScript operations after calling
2939 * ReThrow; the caller must return immediately to where the exception
2940 * is caught.
2941 */
2942 Handle<Value> ReThrow();
2943
2944 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002945 * Returns the exception caught by this try/catch block. If no exception has
2946 * been caught an empty handle is returned.
2947 *
2948 * The returned handle is valid until this TryCatch block has been destroyed.
2949 */
2950 Local<Value> Exception() const;
2951
2952 /**
2953 * Returns the .stack property of the thrown object. If no .stack
2954 * property is present an empty handle is returned.
2955 */
2956 Local<Value> StackTrace() const;
2957
2958 /**
2959 * Returns the message associated with this exception. If there is
2960 * no message associated an empty handle is returned.
2961 *
2962 * The returned handle is valid until this TryCatch block has been
2963 * destroyed.
2964 */
2965 Local<v8::Message> Message() const;
2966
2967 /**
2968 * Clears any exceptions that may have been caught by this try/catch block.
2969 * After this method has been called, HasCaught() will return false.
2970 *
2971 * It is not necessary to clear a try/catch block before using it again; if
2972 * another exception is thrown the previously caught exception will just be
2973 * overwritten. However, it is often a good idea since it makes it easier
2974 * to determine which operation threw a given exception.
2975 */
2976 void Reset();
2977
2978 /**
2979 * Set verbosity of the external exception handler.
2980 *
2981 * By default, exceptions that are caught by an external exception
2982 * handler are not reported. Call SetVerbose with true on an
2983 * external exception handler to have exceptions caught by the
2984 * handler reported as if they were not caught.
2985 */
2986 void SetVerbose(bool value);
2987
2988 /**
2989 * Set whether or not this TryCatch should capture a Message object
2990 * which holds source information about where the exception
2991 * occurred. True by default.
2992 */
2993 void SetCaptureMessage(bool value);
2994
Steve Blockd0582a62009-12-15 09:54:21 +00002995 private:
2996 void* next_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002997 void* exception_;
2998 void* message_;
Steve Blockd0582a62009-12-15 09:54:21 +00002999 bool is_verbose_ : 1;
3000 bool can_continue_ : 1;
3001 bool capture_message_ : 1;
3002 bool rethrow_ : 1;
3003
3004 friend class v8::internal::Top;
Steve Blocka7e24c12009-10-30 11:49:00 +00003005};
3006
3007
3008// --- C o n t e x t ---
3009
3010
3011/**
3012 * Ignore
3013 */
3014class V8EXPORT ExtensionConfiguration {
3015 public:
3016 ExtensionConfiguration(int name_count, const char* names[])
3017 : name_count_(name_count), names_(names) { }
3018 private:
3019 friend class ImplementationUtilities;
3020 int name_count_;
3021 const char** names_;
3022};
3023
3024
3025/**
3026 * A sandboxed execution context with its own set of built-in objects
3027 * and functions.
3028 */
3029class V8EXPORT Context {
3030 public:
3031 /** Returns the global object of the context. */
3032 Local<Object> Global();
3033
3034 /**
3035 * Detaches the global object from its context before
3036 * the global object can be reused to create a new context.
3037 */
3038 void DetachGlobal();
3039
Andrei Popescu74b3c142010-03-29 12:03:09 +01003040 /**
3041 * Reattaches a global object to a context. This can be used to
3042 * restore the connection between a global object and a context
3043 * after DetachGlobal has been called.
3044 *
3045 * \param global_object The global object to reattach to the
3046 * context. For this to work, the global object must be the global
3047 * object that was associated with this context before a call to
3048 * DetachGlobal.
3049 */
3050 void ReattachGlobal(Handle<Object> global_object);
3051
Leon Clarkef7060e22010-06-03 12:02:55 +01003052 /** Creates a new context.
3053 *
3054 * Returns a persistent handle to the newly allocated context. This
3055 * persistent handle has to be disposed when the context is no
3056 * longer used so the context can be garbage collected.
3057 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003058 static Persistent<Context> New(
Andrei Popescu31002712010-02-23 13:46:05 +00003059 ExtensionConfiguration* extensions = NULL,
Steve Blocka7e24c12009-10-30 11:49:00 +00003060 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3061 Handle<Value> global_object = Handle<Value>());
3062
3063 /** Returns the last entered context. */
3064 static Local<Context> GetEntered();
3065
3066 /** Returns the context that is on the top of the stack. */
3067 static Local<Context> GetCurrent();
3068
3069 /**
3070 * Returns the context of the calling JavaScript code. That is the
3071 * context of the top-most JavaScript frame. If there are no
3072 * JavaScript frames an empty handle is returned.
3073 */
3074 static Local<Context> GetCalling();
3075
3076 /**
3077 * Sets the security token for the context. To access an object in
3078 * another context, the security tokens must match.
3079 */
3080 void SetSecurityToken(Handle<Value> token);
3081
3082 /** Restores the security token to the default value. */
3083 void UseDefaultSecurityToken();
3084
3085 /** Returns the security token of this context.*/
3086 Handle<Value> GetSecurityToken();
3087
3088 /**
3089 * Enter this context. After entering a context, all code compiled
3090 * and run is compiled and run in this context. If another context
3091 * is already entered, this old context is saved so it can be
3092 * restored when the new context is exited.
3093 */
3094 void Enter();
3095
3096 /**
3097 * Exit this context. Exiting the current context restores the
3098 * context that was in place when entering the current context.
3099 */
3100 void Exit();
3101
3102 /** Returns true if the context has experienced an out of memory situation. */
3103 bool HasOutOfMemoryException();
3104
3105 /** Returns true if V8 has a current context. */
3106 static bool InContext();
3107
3108 /**
3109 * Associate an additional data object with the context. This is mainly used
3110 * with the debugger to provide additional information on the context through
3111 * the debugger API.
3112 */
Steve Blockd0582a62009-12-15 09:54:21 +00003113 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00003114 Local<Value> GetData();
3115
3116 /**
3117 * Stack-allocated class which sets the execution context for all
3118 * operations executed within a local scope.
3119 */
Steve Block8defd9f2010-07-08 12:39:36 +01003120 class Scope {
Steve Blocka7e24c12009-10-30 11:49:00 +00003121 public:
3122 inline Scope(Handle<Context> context) : context_(context) {
3123 context_->Enter();
3124 }
3125 inline ~Scope() { context_->Exit(); }
3126 private:
3127 Handle<Context> context_;
3128 };
3129
3130 private:
3131 friend class Value;
3132 friend class Script;
3133 friend class Object;
3134 friend class Function;
3135};
3136
3137
3138/**
3139 * Multiple threads in V8 are allowed, but only one thread at a time
3140 * is allowed to use V8. The definition of 'using V8' includes
3141 * accessing handles or holding onto object pointers obtained from V8
3142 * handles. It is up to the user of V8 to ensure (perhaps with
3143 * locking) that this constraint is not violated.
3144 *
3145 * If you wish to start using V8 in a thread you can do this by constructing
3146 * a v8::Locker object. After the code using V8 has completed for the
3147 * current thread you can call the destructor. This can be combined
3148 * with C++ scope-based construction as follows:
3149 *
3150 * \code
3151 * ...
3152 * {
3153 * v8::Locker locker;
3154 * ...
3155 * // Code using V8 goes here.
3156 * ...
3157 * } // Destructor called here
3158 * \endcode
3159 *
3160 * If you wish to stop using V8 in a thread A you can do this by either
3161 * by destroying the v8::Locker object as above or by constructing a
3162 * v8::Unlocker object:
3163 *
3164 * \code
3165 * {
3166 * v8::Unlocker unlocker;
3167 * ...
3168 * // Code not using V8 goes here while V8 can run in another thread.
3169 * ...
3170 * } // Destructor called here.
3171 * \endcode
3172 *
3173 * The Unlocker object is intended for use in a long-running callback
3174 * from V8, where you want to release the V8 lock for other threads to
3175 * use.
3176 *
3177 * The v8::Locker is a recursive lock. That is, you can lock more than
3178 * once in a given thread. This can be useful if you have code that can
3179 * be called either from code that holds the lock or from code that does
3180 * not. The Unlocker is not recursive so you can not have several
3181 * Unlockers on the stack at once, and you can not use an Unlocker in a
3182 * thread that is not inside a Locker's scope.
3183 *
3184 * An unlocker will unlock several lockers if it has to and reinstate
3185 * the correct depth of locking on its destruction. eg.:
3186 *
3187 * \code
3188 * // V8 not locked.
3189 * {
3190 * v8::Locker locker;
3191 * // V8 locked.
3192 * {
3193 * v8::Locker another_locker;
3194 * // V8 still locked (2 levels).
3195 * {
3196 * v8::Unlocker unlocker;
3197 * // V8 not locked.
3198 * }
3199 * // V8 locked again (2 levels).
3200 * }
3201 * // V8 still locked (1 level).
3202 * }
3203 * // V8 Now no longer locked.
3204 * \endcode
3205 */
3206class V8EXPORT Unlocker {
3207 public:
3208 Unlocker();
3209 ~Unlocker();
3210};
3211
3212
3213class V8EXPORT Locker {
3214 public:
3215 Locker();
3216 ~Locker();
3217
3218 /**
3219 * Start preemption.
3220 *
3221 * When preemption is started, a timer is fired every n milli seconds
3222 * that will switch between multiple threads that are in contention
3223 * for the V8 lock.
3224 */
3225 static void StartPreemption(int every_n_ms);
3226
3227 /**
3228 * Stop preemption.
3229 */
3230 static void StopPreemption();
3231
3232 /**
3233 * Returns whether or not the locker is locked by the current thread.
3234 */
3235 static bool IsLocked();
3236
3237 /**
3238 * Returns whether v8::Locker is being used by this V8 instance.
3239 */
3240 static bool IsActive() { return active_; }
3241
3242 private:
3243 bool has_lock_;
3244 bool top_level_;
3245
3246 static bool active_;
3247
3248 // Disallow copying and assigning.
3249 Locker(const Locker&);
3250 void operator=(const Locker&);
3251};
3252
3253
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003254/**
3255 * An interface for exporting data from V8, using "push" model.
3256 */
3257class V8EXPORT OutputStream {
3258public:
3259 enum OutputEncoding {
3260 kAscii = 0 // 7-bit ASCII.
3261 };
3262 enum WriteResult {
3263 kContinue = 0,
3264 kAbort = 1
3265 };
3266 virtual ~OutputStream() {}
3267 /** Notify about the end of stream. */
3268 virtual void EndOfStream() = 0;
3269 /** Get preferred output chunk size. Called only once. */
3270 virtual int GetChunkSize() { return 1024; }
3271 /** Get preferred output encoding. Called only once. */
3272 virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3273 /**
3274 * Writes the next chunk of snapshot data into the stream. Writing
3275 * can be stopped by returning kAbort as function result. EndOfStream
3276 * will not be called in case writing was aborted.
3277 */
3278 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3279};
3280
3281
Steve Blocka7e24c12009-10-30 11:49:00 +00003282
3283// --- I m p l e m e n t a t i o n ---
3284
3285
3286namespace internal {
3287
3288
3289// Tag information for HeapObject.
3290const int kHeapObjectTag = 1;
3291const int kHeapObjectTagSize = 2;
3292const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3293
Steve Blocka7e24c12009-10-30 11:49:00 +00003294// Tag information for Smi.
3295const int kSmiTag = 0;
3296const int kSmiTagSize = 1;
3297const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3298
Steve Block3ce2e202009-11-05 08:53:23 +00003299template <size_t ptr_size> struct SmiConstants;
3300
3301// Smi constants for 32-bit systems.
3302template <> struct SmiConstants<4> {
3303 static const int kSmiShiftSize = 0;
3304 static const int kSmiValueSize = 31;
3305 static inline int SmiToInt(internal::Object* value) {
3306 int shift_bits = kSmiTagSize + kSmiShiftSize;
3307 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3308 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3309 }
3310};
3311
3312// Smi constants for 64-bit systems.
3313template <> struct SmiConstants<8> {
3314 static const int kSmiShiftSize = 31;
3315 static const int kSmiValueSize = 32;
3316 static inline int SmiToInt(internal::Object* value) {
3317 int shift_bits = kSmiTagSize + kSmiShiftSize;
3318 // Shift down and throw away top 32 bits.
3319 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3320 }
3321};
3322
3323const int kSmiShiftSize = SmiConstants<sizeof(void*)>::kSmiShiftSize;
3324const int kSmiValueSize = SmiConstants<sizeof(void*)>::kSmiValueSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003325
Steve Blockd0582a62009-12-15 09:54:21 +00003326template <size_t ptr_size> struct InternalConstants;
3327
3328// Internal constants for 32-bit systems.
3329template <> struct InternalConstants<4> {
3330 static const int kStringResourceOffset = 3 * sizeof(void*);
3331};
3332
3333// Internal constants for 64-bit systems.
3334template <> struct InternalConstants<8> {
Steve Block6ded16b2010-05-10 14:33:55 +01003335 static const int kStringResourceOffset = 3 * sizeof(void*);
Steve Blockd0582a62009-12-15 09:54:21 +00003336};
3337
Steve Blocka7e24c12009-10-30 11:49:00 +00003338/**
3339 * This class exports constants and functionality from within v8 that
3340 * is necessary to implement inline functions in the v8 api. Don't
3341 * depend on functions and constants defined here.
3342 */
3343class Internals {
3344 public:
3345
3346 // These values match non-compiler-dependent values defined within
3347 // the implementation of v8.
3348 static const int kHeapObjectMapOffset = 0;
3349 static const int kMapInstanceTypeOffset = sizeof(void*) + sizeof(int);
Steve Blockd0582a62009-12-15 09:54:21 +00003350 static const int kStringResourceOffset =
3351 InternalConstants<sizeof(void*)>::kStringResourceOffset;
3352
Steve Blocka7e24c12009-10-30 11:49:00 +00003353 static const int kProxyProxyOffset = sizeof(void*);
3354 static const int kJSObjectHeaderSize = 3 * sizeof(void*);
3355 static const int kFullStringRepresentationMask = 0x07;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003356 static const int kExternalTwoByteRepresentationTag = 0x02;
Steve Blocka7e24c12009-10-30 11:49:00 +00003357
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003358 static const int kJSObjectType = 0x9f;
3359 static const int kFirstNonstringType = 0x80;
3360 static const int kProxyType = 0x85;
Steve Blocka7e24c12009-10-30 11:49:00 +00003361
3362 static inline bool HasHeapObjectTag(internal::Object* value) {
3363 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3364 kHeapObjectTag);
3365 }
3366
3367 static inline bool HasSmiTag(internal::Object* value) {
3368 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3369 }
3370
3371 static inline int SmiValue(internal::Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00003372 return SmiConstants<sizeof(void*)>::SmiToInt(value);
3373 }
3374
3375 static inline int GetInstanceType(internal::Object* obj) {
3376 typedef internal::Object O;
3377 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3378 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3379 }
3380
3381 static inline void* GetExternalPointer(internal::Object* obj) {
3382 if (HasSmiTag(obj)) {
3383 return obj;
3384 } else if (GetInstanceType(obj) == kProxyType) {
3385 return ReadField<void*>(obj, kProxyProxyOffset);
3386 } else {
3387 return NULL;
3388 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003389 }
3390
3391 static inline bool IsExternalTwoByteString(int instance_type) {
3392 int representation = (instance_type & kFullStringRepresentationMask);
3393 return representation == kExternalTwoByteRepresentationTag;
3394 }
3395
3396 template <typename T>
3397 static inline T ReadField(Object* ptr, int offset) {
3398 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3399 return *reinterpret_cast<T*>(addr);
3400 }
3401
3402};
3403
3404}
3405
3406
3407template <class T>
3408Handle<T>::Handle() : val_(0) { }
3409
3410
3411template <class T>
3412Local<T>::Local() : Handle<T>() { }
3413
3414
3415template <class T>
3416Local<T> Local<T>::New(Handle<T> that) {
3417 if (that.IsEmpty()) return Local<T>();
3418 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3419 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3420}
3421
3422
3423template <class T>
3424Persistent<T> Persistent<T>::New(Handle<T> that) {
3425 if (that.IsEmpty()) return Persistent<T>();
3426 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3427 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3428}
3429
3430
3431template <class T>
3432bool Persistent<T>::IsNearDeath() const {
3433 if (this->IsEmpty()) return false;
3434 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3435}
3436
3437
3438template <class T>
3439bool Persistent<T>::IsWeak() const {
3440 if (this->IsEmpty()) return false;
3441 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3442}
3443
3444
3445template <class T>
3446void Persistent<T>::Dispose() {
3447 if (this->IsEmpty()) return;
3448 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3449}
3450
3451
3452template <class T>
3453Persistent<T>::Persistent() : Handle<T>() { }
3454
3455template <class T>
3456void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3457 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3458 parameters,
3459 callback);
3460}
3461
3462template <class T>
3463void Persistent<T>::ClearWeak() {
3464 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3465}
3466
Steve Block8defd9f2010-07-08 12:39:36 +01003467
3468Arguments::Arguments(v8::Local<v8::Value> data,
3469 v8::Local<v8::Object> holder,
3470 v8::Local<v8::Function> callee,
3471 bool is_construct_call,
3472 void** values, int length)
3473 : data_(data), holder_(holder), callee_(callee),
3474 is_construct_call_(is_construct_call),
3475 values_(values), length_(length) { }
3476
3477
Steve Blocka7e24c12009-10-30 11:49:00 +00003478Local<Value> Arguments::operator[](int i) const {
3479 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3480 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3481}
3482
3483
3484Local<Function> Arguments::Callee() const {
3485 return callee_;
3486}
3487
3488
3489Local<Object> Arguments::This() const {
3490 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
3491}
3492
3493
3494Local<Object> Arguments::Holder() const {
3495 return holder_;
3496}
3497
3498
3499Local<Value> Arguments::Data() const {
3500 return data_;
3501}
3502
3503
3504bool Arguments::IsConstructCall() const {
3505 return is_construct_call_;
3506}
3507
3508
3509int Arguments::Length() const {
3510 return length_;
3511}
3512
3513
3514template <class T>
3515Local<T> HandleScope::Close(Handle<T> value) {
3516 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
3517 internal::Object** after = RawClose(before);
3518 return Local<T>(reinterpret_cast<T*>(after));
3519}
3520
3521Handle<Value> ScriptOrigin::ResourceName() const {
3522 return resource_name_;
3523}
3524
3525
3526Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
3527 return resource_line_offset_;
3528}
3529
3530
3531Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
3532 return resource_column_offset_;
3533}
3534
3535
3536Handle<Boolean> Boolean::New(bool value) {
3537 return value ? True() : False();
3538}
3539
3540
3541void Template::Set(const char* name, v8::Handle<Data> value) {
3542 Set(v8::String::New(name), value);
3543}
3544
3545
3546Local<Value> Object::GetInternalField(int index) {
3547#ifndef V8_ENABLE_CHECKS
3548 Local<Value> quick_result = UncheckedGetInternalField(index);
3549 if (!quick_result.IsEmpty()) return quick_result;
3550#endif
3551 return CheckedGetInternalField(index);
3552}
3553
3554
3555Local<Value> Object::UncheckedGetInternalField(int index) {
3556 typedef internal::Object O;
3557 typedef internal::Internals I;
3558 O* obj = *reinterpret_cast<O**>(this);
Steve Block3ce2e202009-11-05 08:53:23 +00003559 if (I::GetInstanceType(obj) == I::kJSObjectType) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003560 // If the object is a plain JSObject, which is the common case,
3561 // we know where to find the internal fields and can return the
3562 // value directly.
3563 int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3564 O* value = I::ReadField<O*>(obj, offset);
3565 O** result = HandleScope::CreateHandle(value);
3566 return Local<Value>(reinterpret_cast<Value*>(result));
3567 } else {
3568 return Local<Value>();
3569 }
3570}
3571
3572
3573void* External::Unwrap(Handle<v8::Value> obj) {
3574#ifdef V8_ENABLE_CHECKS
3575 return FullUnwrap(obj);
3576#else
3577 return QuickUnwrap(obj);
3578#endif
3579}
3580
3581
3582void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
3583 typedef internal::Object O;
Steve Blocka7e24c12009-10-30 11:49:00 +00003584 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
Steve Block3ce2e202009-11-05 08:53:23 +00003585 return internal::Internals::GetExternalPointer(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00003586}
3587
3588
3589void* Object::GetPointerFromInternalField(int index) {
Steve Block3ce2e202009-11-05 08:53:23 +00003590 typedef internal::Object O;
3591 typedef internal::Internals I;
3592
3593 O* obj = *reinterpret_cast<O**>(this);
3594
3595 if (I::GetInstanceType(obj) == I::kJSObjectType) {
3596 // If the object is a plain JSObject, which is the common case,
3597 // we know where to find the internal fields and can return the
3598 // value directly.
3599 int offset = I::kJSObjectHeaderSize + (sizeof(void*) * index);
3600 O* value = I::ReadField<O*>(obj, offset);
3601 return I::GetExternalPointer(value);
3602 }
3603
3604 return SlowGetPointerFromInternalField(index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003605}
3606
3607
3608String* String::Cast(v8::Value* value) {
3609#ifdef V8_ENABLE_CHECKS
3610 CheckCast(value);
3611#endif
3612 return static_cast<String*>(value);
3613}
3614
3615
3616String::ExternalStringResource* String::GetExternalStringResource() const {
3617 typedef internal::Object O;
3618 typedef internal::Internals I;
3619 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
Steve Blocka7e24c12009-10-30 11:49:00 +00003620 String::ExternalStringResource* result;
Steve Block3ce2e202009-11-05 08:53:23 +00003621 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003622 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
3623 result = reinterpret_cast<String::ExternalStringResource*>(value);
3624 } else {
3625 result = NULL;
3626 }
3627#ifdef V8_ENABLE_CHECKS
3628 VerifyExternalStringResource(result);
3629#endif
3630 return result;
3631}
3632
3633
3634bool Value::IsString() const {
3635#ifdef V8_ENABLE_CHECKS
3636 return FullIsString();
3637#else
3638 return QuickIsString();
3639#endif
3640}
3641
3642bool Value::QuickIsString() const {
3643 typedef internal::Object O;
3644 typedef internal::Internals I;
3645 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
3646 if (!I::HasHeapObjectTag(obj)) return false;
Steve Block3ce2e202009-11-05 08:53:23 +00003647 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
Steve Blocka7e24c12009-10-30 11:49:00 +00003648}
3649
3650
3651Number* Number::Cast(v8::Value* value) {
3652#ifdef V8_ENABLE_CHECKS
3653 CheckCast(value);
3654#endif
3655 return static_cast<Number*>(value);
3656}
3657
3658
3659Integer* Integer::Cast(v8::Value* value) {
3660#ifdef V8_ENABLE_CHECKS
3661 CheckCast(value);
3662#endif
3663 return static_cast<Integer*>(value);
3664}
3665
3666
3667Date* Date::Cast(v8::Value* value) {
3668#ifdef V8_ENABLE_CHECKS
3669 CheckCast(value);
3670#endif
3671 return static_cast<Date*>(value);
3672}
3673
3674
Ben Murdochf87a2032010-10-22 12:50:53 +01003675RegExp* RegExp::Cast(v8::Value* value) {
3676#ifdef V8_ENABLE_CHECKS
3677 CheckCast(value);
3678#endif
3679 return static_cast<RegExp*>(value);
3680}
3681
3682
Steve Blocka7e24c12009-10-30 11:49:00 +00003683Object* Object::Cast(v8::Value* value) {
3684#ifdef V8_ENABLE_CHECKS
3685 CheckCast(value);
3686#endif
3687 return static_cast<Object*>(value);
3688}
3689
3690
3691Array* Array::Cast(v8::Value* value) {
3692#ifdef V8_ENABLE_CHECKS
3693 CheckCast(value);
3694#endif
3695 return static_cast<Array*>(value);
3696}
3697
3698
3699Function* Function::Cast(v8::Value* value) {
3700#ifdef V8_ENABLE_CHECKS
3701 CheckCast(value);
3702#endif
3703 return static_cast<Function*>(value);
3704}
3705
3706
3707External* External::Cast(v8::Value* value) {
3708#ifdef V8_ENABLE_CHECKS
3709 CheckCast(value);
3710#endif
3711 return static_cast<External*>(value);
3712}
3713
3714
3715Local<Value> AccessorInfo::Data() const {
Steve Block6ded16b2010-05-10 14:33:55 +01003716 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003717}
3718
3719
3720Local<Object> AccessorInfo::This() const {
3721 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
3722}
3723
3724
3725Local<Object> AccessorInfo::Holder() const {
3726 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
3727}
3728
3729
3730/**
3731 * \example shell.cc
3732 * A simple shell that takes a list of expressions on the
3733 * command-line and executes them.
3734 */
3735
3736
3737/**
3738 * \example process.cc
3739 */
3740
3741
3742} // namespace v8
3743
3744
3745#undef V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00003746#undef TYPE_CHECK
3747
3748
3749#endif // V8_H_