blob: 2c0f35080d3e199ff5e58b7c9f367790922511a4 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2007-2009 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28/** \mainpage V8 API Reference Guide
29 *
30 * V8 is Google's open source JavaScript engine.
31 *
32 * This set of documents provides reference material generated from the
33 * V8 header file, include/v8.h.
34 *
35 * For other documentation see http://code.google.com/apis/v8/
36 */
37
38#ifndef V8_H_
39#define V8_H_
40
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080041#include "v8stdint.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000042
43#ifdef _WIN32
Steve Blocka7e24c12009-10-30 11:49:00 +000044
45// Setup for Windows DLL export/import. When building the V8 DLL the
46// BUILDING_V8_SHARED needs to be defined. When building a program which uses
47// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
48// static library or building a program which uses the V8 static library neither
49// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
Steve Blocka7e24c12009-10-30 11:49:00 +000050#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
51#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
52 build configuration to ensure that at most one of these is set
53#endif
54
55#ifdef BUILDING_V8_SHARED
56#define V8EXPORT __declspec(dllexport)
Steve Blocka7e24c12009-10-30 11:49:00 +000057#elif USING_V8_SHARED
58#define V8EXPORT __declspec(dllimport)
Steve Blocka7e24c12009-10-30 11:49:00 +000059#else
60#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000061#endif // BUILDING_V8_SHARED
62
63#else // _WIN32
64
Steve Blocka7e24c12009-10-30 11:49:00 +000065// Setup for Linux shared library export. There is no need to distinguish
66// between building or using the V8 shared library, but we should not
67// export symbols when we are building a static library.
68#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
69#define V8EXPORT __attribute__ ((visibility("default")))
Steve Blocka7e24c12009-10-30 11:49:00 +000070#else // defined(__GNUC__) && (__GNUC__ >= 4)
71#define V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +000072#endif // defined(__GNUC__) && (__GNUC__ >= 4)
73
74#endif // _WIN32
75
76/**
77 * The v8 JavaScript engine.
78 */
79namespace v8 {
80
81class Context;
82class String;
83class Value;
84class Utils;
85class Number;
86class Object;
87class Array;
88class Int32;
89class Uint32;
90class External;
91class Primitive;
92class Boolean;
93class Integer;
94class Function;
95class Date;
96class ImplementationUtilities;
97class Signature;
98template <class T> class Handle;
99template <class T> class Local;
100template <class T> class Persistent;
101class FunctionTemplate;
102class ObjectTemplate;
103class Data;
Leon Clarkef7060e22010-06-03 12:02:55 +0100104class AccessorInfo;
Kristian Monsen25f61362010-05-21 11:50:48 +0100105class StackTrace;
106class StackFrame;
Steve Blocka7e24c12009-10-30 11:49:00 +0000107
108namespace internal {
109
Steve Blocka7e24c12009-10-30 11:49:00 +0000110class Arguments;
Steve Blockd0582a62009-12-15 09:54:21 +0000111class Object;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100112class Heap;
Steve Blockd0582a62009-12-15 09:54:21 +0000113class Top;
Steve Blocka7e24c12009-10-30 11:49:00 +0000114}
115
116
117// --- W e a k H a n d l e s
118
119
120/**
121 * A weak reference callback function.
122 *
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100123 * This callback should either explicitly invoke Dispose on |object| if
124 * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak.
125 *
Steve Blocka7e24c12009-10-30 11:49:00 +0000126 * \param object the weak global object to be reclaimed by the garbage collector
127 * \param parameter the value passed in when making the weak global object
128 */
129typedef void (*WeakReferenceCallback)(Persistent<Value> object,
130 void* parameter);
131
132
133// --- H a n d l e s ---
134
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100135#define TYPE_CHECK(T, S) \
136 while (false) { \
137 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
Steve Blocka7e24c12009-10-30 11:49:00 +0000138 }
139
140/**
141 * An object reference managed by the v8 garbage collector.
142 *
143 * All objects returned from v8 have to be tracked by the garbage
144 * collector so that it knows that the objects are still alive. Also,
145 * because the garbage collector may move objects, it is unsafe to
146 * point directly to an object. Instead, all objects are stored in
147 * handles which are known by the garbage collector and updated
148 * whenever an object moves. Handles should always be passed by value
149 * (except in cases like out-parameters) and they should never be
150 * allocated on the heap.
151 *
152 * There are two types of handles: local and persistent handles.
153 * Local handles are light-weight and transient and typically used in
154 * local operations. They are managed by HandleScopes. Persistent
155 * handles can be used when storing objects across several independent
156 * operations and have to be explicitly deallocated when they're no
157 * longer used.
158 *
159 * It is safe to extract the object stored in the handle by
160 * dereferencing the handle (for instance, to extract the Object* from
161 * an Handle<Object>); the value will still be governed by a handle
162 * behind the scenes and the same rules apply to these values as to
163 * their handles.
164 */
Steve Block8defd9f2010-07-08 12:39:36 +0100165template <class T> class Handle {
Steve Blocka7e24c12009-10-30 11:49:00 +0000166 public:
167
168 /**
169 * Creates an empty handle.
170 */
171 inline Handle();
172
173 /**
174 * Creates a new handle for the specified value.
175 */
Steve Block8defd9f2010-07-08 12:39:36 +0100176 inline explicit Handle(T* val) : val_(val) { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000177
178 /**
179 * Creates a handle for the contents of the specified handle. This
180 * constructor allows you to pass handles as arguments by value and
181 * to assign between handles. However, if you try to assign between
182 * incompatible handles, for instance from a Handle<String> to a
183 * Handle<Number> it will cause a compiletime error. Assigning
184 * between compatible handles, for instance assigning a
185 * Handle<String> to a variable declared as Handle<Value>, is legal
186 * because String is a subclass of Value.
187 */
188 template <class S> inline Handle(Handle<S> that)
189 : val_(reinterpret_cast<T*>(*that)) {
190 /**
191 * This check fails when trying to convert between incompatible
192 * handles. For example, converting from a Handle<String> to a
193 * Handle<Number>.
194 */
195 TYPE_CHECK(T, S);
196 }
197
198 /**
199 * Returns true if the handle is empty.
200 */
Steve Block8defd9f2010-07-08 12:39:36 +0100201 inline bool IsEmpty() const { return val_ == 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000202
Steve Block8defd9f2010-07-08 12:39:36 +0100203 inline T* operator->() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000204
Steve Block8defd9f2010-07-08 12:39:36 +0100205 inline T* operator*() const { return val_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000206
207 /**
208 * Sets the handle to be empty. IsEmpty() will then return true.
209 */
Steve Block8defd9f2010-07-08 12:39:36 +0100210 inline void Clear() { this->val_ = 0; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000211
212 /**
213 * Checks whether two handles are the same.
214 * Returns true if both are empty, or if the objects
215 * to which they refer are identical.
216 * The handles' references are not checked.
217 */
Steve Block8defd9f2010-07-08 12:39:36 +0100218 template <class S> inline bool operator==(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000219 internal::Object** a = reinterpret_cast<internal::Object**>(**this);
220 internal::Object** b = reinterpret_cast<internal::Object**>(*that);
221 if (a == 0) return b == 0;
222 if (b == 0) return false;
223 return *a == *b;
224 }
225
226 /**
227 * Checks whether two handles are different.
228 * Returns true if only one of the handles is empty, or if
229 * the objects to which they refer are different.
230 * The handles' references are not checked.
231 */
Steve Block8defd9f2010-07-08 12:39:36 +0100232 template <class S> inline bool operator!=(Handle<S> that) const {
Steve Blocka7e24c12009-10-30 11:49:00 +0000233 return !operator==(that);
234 }
235
236 template <class S> static inline Handle<T> Cast(Handle<S> that) {
237#ifdef V8_ENABLE_CHECKS
238 // If we're going to perform the type check then we have to check
239 // that the handle isn't empty before doing the checked cast.
240 if (that.IsEmpty()) return Handle<T>();
241#endif
242 return Handle<T>(T::Cast(*that));
243 }
244
Steve Block6ded16b2010-05-10 14:33:55 +0100245 template <class S> inline Handle<S> As() {
246 return Handle<S>::Cast(*this);
247 }
248
Steve Blocka7e24c12009-10-30 11:49:00 +0000249 private:
250 T* val_;
251};
252
253
254/**
255 * A light-weight stack-allocated object handle. All operations
256 * that return objects from within v8 return them in local handles. They
257 * are created within HandleScopes, and all local handles allocated within a
258 * handle scope are destroyed when the handle scope is destroyed. Hence it
259 * is not necessary to explicitly deallocate local handles.
260 */
Steve Block8defd9f2010-07-08 12:39:36 +0100261template <class T> class Local : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000262 public:
263 inline Local();
264 template <class S> inline Local(Local<S> that)
265 : Handle<T>(reinterpret_cast<T*>(*that)) {
266 /**
267 * This check fails when trying to convert between incompatible
268 * handles. For example, converting from a Handle<String> to a
269 * Handle<Number>.
270 */
271 TYPE_CHECK(T, S);
272 }
273 template <class S> inline Local(S* that) : Handle<T>(that) { }
274 template <class S> static inline Local<T> Cast(Local<S> that) {
275#ifdef V8_ENABLE_CHECKS
276 // If we're going to perform the type check then we have to check
277 // that the handle isn't empty before doing the checked cast.
278 if (that.IsEmpty()) return Local<T>();
279#endif
280 return Local<T>(T::Cast(*that));
281 }
282
Steve Block6ded16b2010-05-10 14:33:55 +0100283 template <class S> inline Local<S> As() {
284 return Local<S>::Cast(*this);
285 }
286
Steve Blocka7e24c12009-10-30 11:49:00 +0000287 /** Create a local handle for the content of another handle.
288 * The referee is kept alive by the local handle even when
289 * the original handle is destroyed/disposed.
290 */
291 inline static Local<T> New(Handle<T> that);
292};
293
294
295/**
296 * An object reference that is independent of any handle scope. Where
297 * a Local handle only lives as long as the HandleScope in which it was
298 * allocated, a Persistent handle remains valid until it is explicitly
299 * disposed.
300 *
301 * A persistent handle contains a reference to a storage cell within
302 * the v8 engine which holds an object value and which is updated by
303 * the garbage collector whenever the object is moved. A new storage
304 * cell can be created using Persistent::New and existing handles can
305 * be disposed using Persistent::Dispose. Since persistent handles
306 * are passed by value you may have many persistent handle objects
307 * that point to the same storage cell. For instance, if you pass a
308 * persistent handle as an argument to a function you will not get two
309 * different storage cells but rather two references to the same
310 * storage cell.
311 */
Steve Block8defd9f2010-07-08 12:39:36 +0100312template <class T> class Persistent : public Handle<T> {
Steve Blocka7e24c12009-10-30 11:49:00 +0000313 public:
314
315 /**
316 * Creates an empty persistent handle that doesn't point to any
317 * storage cell.
318 */
319 inline Persistent();
320
321 /**
322 * Creates a persistent handle for the same storage cell as the
323 * specified handle. This constructor allows you to pass persistent
324 * handles as arguments by value and to assign between persistent
325 * handles. However, attempting to assign between incompatible
326 * persistent handles, for instance from a Persistent<String> to a
327 * Persistent<Number> will cause a compiletime error. Assigning
328 * between compatible persistent handles, for instance assigning a
329 * Persistent<String> to a variable declared as Persistent<Value>,
330 * is allowed as String is a subclass of Value.
331 */
332 template <class S> inline Persistent(Persistent<S> that)
333 : Handle<T>(reinterpret_cast<T*>(*that)) {
334 /**
335 * This check fails when trying to convert between incompatible
336 * handles. For example, converting from a Handle<String> to a
337 * Handle<Number>.
338 */
339 TYPE_CHECK(T, S);
340 }
341
342 template <class S> inline Persistent(S* that) : Handle<T>(that) { }
343
344 /**
345 * "Casts" a plain handle which is known to be a persistent handle
346 * to a persistent handle.
347 */
348 template <class S> explicit inline Persistent(Handle<S> that)
349 : Handle<T>(*that) { }
350
351 template <class S> static inline Persistent<T> Cast(Persistent<S> that) {
352#ifdef V8_ENABLE_CHECKS
353 // If we're going to perform the type check then we have to check
354 // that the handle isn't empty before doing the checked cast.
355 if (that.IsEmpty()) return Persistent<T>();
356#endif
357 return Persistent<T>(T::Cast(*that));
358 }
359
Steve Block6ded16b2010-05-10 14:33:55 +0100360 template <class S> inline Persistent<S> As() {
361 return Persistent<S>::Cast(*this);
362 }
363
Steve Blocka7e24c12009-10-30 11:49:00 +0000364 /**
365 * Creates a new persistent handle for an existing local or
366 * persistent handle.
367 */
368 inline static Persistent<T> New(Handle<T> that);
369
370 /**
371 * Releases the storage cell referenced by this persistent handle.
372 * Does not remove the reference to the cell from any handles.
373 * This handle's reference, and any any other references to the storage
374 * cell remain and IsEmpty will still return false.
375 */
376 inline void Dispose();
377
378 /**
379 * Make the reference to this object weak. When only weak handles
380 * refer to the object, the garbage collector will perform a
381 * callback to the given V8::WeakReferenceCallback function, passing
382 * it the object reference and the given parameters.
383 */
384 inline void MakeWeak(void* parameters, WeakReferenceCallback callback);
385
386 /** Clears the weak reference to this object.*/
387 inline void ClearWeak();
388
389 /**
390 *Checks if the handle holds the only reference to an object.
391 */
392 inline bool IsNearDeath() const;
393
394 /**
395 * Returns true if the handle's reference is weak.
396 */
397 inline bool IsWeak() const;
398
399 private:
400 friend class ImplementationUtilities;
401 friend class ObjectTemplate;
402};
403
404
405 /**
406 * A stack-allocated class that governs a number of local handles.
407 * After a handle scope has been created, all local handles will be
408 * allocated within that handle scope until either the handle scope is
409 * deleted or another handle scope is created. If there is already a
410 * handle scope and a new one is created, all allocations will take
411 * place in the new handle scope until it is deleted. After that,
412 * new handles will again be allocated in the original handle scope.
413 *
414 * After the handle scope of a local handle has been deleted the
415 * garbage collector will no longer track the object stored in the
416 * handle and may deallocate it. The behavior of accessing a handle
417 * for which the handle scope has been deleted is undefined.
418 */
419class V8EXPORT HandleScope {
420 public:
421 HandleScope();
422
423 ~HandleScope();
424
425 /**
426 * Closes the handle scope and returns the value as a handle in the
427 * previous scope, which is the new current scope after the call.
428 */
429 template <class T> Local<T> Close(Handle<T> value);
430
431 /**
432 * Counts the number of allocated handles.
433 */
434 static int NumberOfHandles();
435
436 /**
437 * Creates a new handle with the given value.
438 */
439 static internal::Object** CreateHandle(internal::Object* value);
440
441 private:
442 // Make it impossible to create heap-allocated or illegal handle
443 // scopes by disallowing certain operations.
444 HandleScope(const HandleScope&);
445 void operator=(const HandleScope&);
446 void* operator new(size_t size);
447 void operator delete(void*, size_t);
448
Steve Blockd0582a62009-12-15 09:54:21 +0000449 // This Data class is accessible internally as HandleScopeData through a
450 // typedef in the ImplementationUtilities class.
Steve Blocka7e24c12009-10-30 11:49:00 +0000451 class V8EXPORT Data {
452 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000453 internal::Object** next;
454 internal::Object** limit;
John Reck59135872010-11-02 12:39:01 -0700455 int level;
456
Steve Blocka7e24c12009-10-30 11:49:00 +0000457 inline void Initialize() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000458 next = limit = NULL;
John Reck59135872010-11-02 12:39:01 -0700459 level = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000460 }
461 };
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800462
John Reck59135872010-11-02 12:39:01 -0700463 void Leave();
Steve Blocka7e24c12009-10-30 11:49:00 +0000464
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800465
John Reck59135872010-11-02 12:39:01 -0700466 internal::Object** prev_next_;
467 internal::Object** prev_limit_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000468
469 // Allow for the active closing of HandleScopes which allows to pass a handle
470 // from the HandleScope being closed to the next top most HandleScope.
471 bool is_closed_;
472 internal::Object** RawClose(internal::Object** value);
473
474 friend class ImplementationUtilities;
475};
476
477
478// --- S p e c i a l o b j e c t s ---
479
480
481/**
482 * The superclass of values and API object templates.
483 */
484class V8EXPORT Data {
485 private:
486 Data();
487};
488
489
490/**
491 * Pre-compilation data that can be associated with a script. This
492 * data can be calculated for a script in advance of actually
493 * compiling it, and can be stored between compilations. When script
494 * data is given to the compile method compilation will be faster.
495 */
496class V8EXPORT ScriptData { // NOLINT
497 public:
498 virtual ~ScriptData() { }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100499
Leon Clarkef7060e22010-06-03 12:02:55 +0100500 /**
501 * Pre-compiles the specified script (context-independent).
502 *
503 * \param input Pointer to UTF-8 script source code.
504 * \param length Length of UTF-8 script source code.
505 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000506 static ScriptData* PreCompile(const char* input, int length);
Steve Blocka7e24c12009-10-30 11:49:00 +0000507
Leon Clarkef7060e22010-06-03 12:02:55 +0100508 /**
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100509 * Pre-compiles the specified script (context-independent).
510 *
511 * NOTE: Pre-compilation using this method cannot happen on another thread
512 * without using Lockers.
513 *
514 * \param source Script source code.
515 */
516 static ScriptData* PreCompile(Handle<String> source);
517
518 /**
Leon Clarkef7060e22010-06-03 12:02:55 +0100519 * Load previous pre-compilation data.
520 *
521 * \param data Pointer to data returned by a call to Data() of a previous
522 * ScriptData. Ownership is not transferred.
523 * \param length Length of data.
524 */
525 static ScriptData* New(const char* data, int length);
526
527 /**
528 * Returns the length of Data().
529 */
Steve Blocka7e24c12009-10-30 11:49:00 +0000530 virtual int Length() = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100531
532 /**
533 * Returns a serialized representation of this ScriptData that can later be
534 * passed to New(). NOTE: Serialized data is platform-dependent.
535 */
536 virtual const char* Data() = 0;
537
538 /**
539 * Returns true if the source code could not be parsed.
540 */
Leon Clarkee46be812010-01-19 14:06:41 +0000541 virtual bool HasError() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000542};
543
544
545/**
546 * The origin, within a file, of a script.
547 */
Steve Block8defd9f2010-07-08 12:39:36 +0100548class ScriptOrigin {
Steve Blocka7e24c12009-10-30 11:49:00 +0000549 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100550 inline ScriptOrigin(
551 Handle<Value> resource_name,
552 Handle<Integer> resource_line_offset = Handle<Integer>(),
553 Handle<Integer> resource_column_offset = Handle<Integer>())
Steve Blocka7e24c12009-10-30 11:49:00 +0000554 : resource_name_(resource_name),
555 resource_line_offset_(resource_line_offset),
556 resource_column_offset_(resource_column_offset) { }
557 inline Handle<Value> ResourceName() const;
558 inline Handle<Integer> ResourceLineOffset() const;
559 inline Handle<Integer> ResourceColumnOffset() const;
560 private:
561 Handle<Value> resource_name_;
562 Handle<Integer> resource_line_offset_;
563 Handle<Integer> resource_column_offset_;
564};
565
566
567/**
568 * A compiled JavaScript script.
569 */
570class V8EXPORT Script {
571 public:
572
Steve Blocka7e24c12009-10-30 11:49:00 +0000573 /**
Andrei Popescu402d9372010-02-26 13:31:12 +0000574 * Compiles the specified script (context-independent).
Steve Blocka7e24c12009-10-30 11:49:00 +0000575 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000576 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100577 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000578 * when New() returns
579 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
580 * using pre_data speeds compilation if it's done multiple times.
581 * Owned by caller, no references are kept when New() returns.
582 * \param script_data Arbitrary data associated with script. Using
Steve Block6ded16b2010-05-10 14:33:55 +0100583 * this has same effect as calling SetData(), but allows data to be
Andrei Popescu402d9372010-02-26 13:31:12 +0000584 * available to compile event handlers.
585 * \return Compiled script object (context independent; when run it
586 * will use the currently entered context).
Steve Blocka7e24c12009-10-30 11:49:00 +0000587 */
Andrei Popescu402d9372010-02-26 13:31:12 +0000588 static Local<Script> New(Handle<String> source,
589 ScriptOrigin* origin = NULL,
590 ScriptData* pre_data = NULL,
591 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000592
593 /**
594 * Compiles the specified script using the specified file name
595 * object (typically a string) as the script's origin.
596 *
Andrei Popescu402d9372010-02-26 13:31:12 +0000597 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100598 * \param file_name file name object (typically a string) to be used
Andrei Popescu402d9372010-02-26 13:31:12 +0000599 * as the script's origin.
600 * \return Compiled script object (context independent; when run it
601 * will use the currently entered context).
602 */
603 static Local<Script> New(Handle<String> source,
604 Handle<Value> file_name);
605
606 /**
607 * Compiles the specified script (bound to current context).
608 *
609 * \param source Script source code.
Steve Block6ded16b2010-05-10 14:33:55 +0100610 * \param origin Script origin, owned by caller, no references are kept
Andrei Popescu402d9372010-02-26 13:31:12 +0000611 * when Compile() returns
612 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
613 * using pre_data speeds compilation if it's done multiple times.
614 * Owned by caller, no references are kept when Compile() returns.
615 * \param script_data Arbitrary data associated with script. Using
616 * this has same effect as calling SetData(), but makes data available
617 * earlier (i.e. to compile event handlers).
618 * \return Compiled script object, bound to the context that was active
619 * when this function was called. When run it will always use this
620 * context.
Steve Blocka7e24c12009-10-30 11:49:00 +0000621 */
622 static Local<Script> Compile(Handle<String> source,
Andrei Popescu402d9372010-02-26 13:31:12 +0000623 ScriptOrigin* origin = NULL,
624 ScriptData* pre_data = NULL,
625 Handle<String> script_data = Handle<String>());
626
627 /**
628 * Compiles the specified script using the specified file name
629 * object (typically a string) as the script's origin.
630 *
631 * \param source Script source code.
632 * \param file_name File name to use as script's origin
633 * \param script_data Arbitrary data associated with script. Using
634 * this has same effect as calling SetData(), but makes data available
635 * earlier (i.e. to compile event handlers).
636 * \return Compiled script object, bound to the context that was active
637 * when this function was called. When run it will always use this
638 * context.
639 */
640 static Local<Script> Compile(Handle<String> source,
641 Handle<Value> file_name,
642 Handle<String> script_data = Handle<String>());
Steve Blocka7e24c12009-10-30 11:49:00 +0000643
644 /**
645 * Runs the script returning the resulting value. If the script is
646 * context independent (created using ::New) it will be run in the
647 * currently entered context. If it is context specific (created
648 * using ::Compile) it will be run in the context in which it was
649 * compiled.
650 */
651 Local<Value> Run();
652
653 /**
654 * Returns the script id value.
655 */
656 Local<Value> Id();
657
658 /**
659 * Associate an additional data object with the script. This is mainly used
660 * with the debugger as this data object is only available through the
661 * debugger API.
662 */
Steve Blockd0582a62009-12-15 09:54:21 +0000663 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000664};
665
666
667/**
668 * An error message.
669 */
670class V8EXPORT Message {
671 public:
672 Local<String> Get() const;
673 Local<String> GetSourceLine() const;
674
675 /**
676 * Returns the resource name for the script from where the function causing
677 * the error originates.
678 */
679 Handle<Value> GetScriptResourceName() const;
680
681 /**
682 * Returns the resource data for the script from where the function causing
683 * the error originates.
684 */
685 Handle<Value> GetScriptData() const;
686
687 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100688 * Exception stack trace. By default stack traces are not captured for
689 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
690 * to change this option.
691 */
692 Handle<StackTrace> GetStackTrace() const;
693
694 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000695 * Returns the number, 1-based, of the line where the error occurred.
696 */
697 int GetLineNumber() const;
698
699 /**
700 * Returns the index within the script of the first character where
701 * the error occurred.
702 */
703 int GetStartPosition() const;
704
705 /**
706 * Returns the index within the script of the last character where
707 * the error occurred.
708 */
709 int GetEndPosition() const;
710
711 /**
712 * Returns the index within the line of the first character where
713 * the error occurred.
714 */
715 int GetStartColumn() const;
716
717 /**
718 * Returns the index within the line of the last character where
719 * the error occurred.
720 */
721 int GetEndColumn() const;
722
723 // TODO(1245381): Print to a string instead of on a FILE.
724 static void PrintCurrentStackTrace(FILE* out);
Kristian Monsen25f61362010-05-21 11:50:48 +0100725
726 static const int kNoLineNumberInfo = 0;
727 static const int kNoColumnInfo = 0;
728};
729
730
731/**
732 * Representation of a JavaScript stack trace. The information collected is a
733 * snapshot of the execution stack and the information remains valid after
734 * execution continues.
735 */
736class V8EXPORT StackTrace {
737 public:
738 /**
739 * Flags that determine what information is placed captured for each
740 * StackFrame when grabbing the current stack trace.
741 */
742 enum StackTraceOptions {
743 kLineNumber = 1,
744 kColumnOffset = 1 << 1 | kLineNumber,
745 kScriptName = 1 << 2,
746 kFunctionName = 1 << 3,
747 kIsEval = 1 << 4,
748 kIsConstructor = 1 << 5,
Ben Murdochf87a2032010-10-22 12:50:53 +0100749 kScriptNameOrSourceURL = 1 << 6,
Kristian Monsen25f61362010-05-21 11:50:48 +0100750 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
Ben Murdochf87a2032010-10-22 12:50:53 +0100751 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
Kristian Monsen25f61362010-05-21 11:50:48 +0100752 };
753
754 /**
755 * Returns a StackFrame at a particular index.
756 */
757 Local<StackFrame> GetFrame(uint32_t index) const;
758
759 /**
760 * Returns the number of StackFrames.
761 */
762 int GetFrameCount() const;
763
764 /**
765 * Returns StackTrace as a v8::Array that contains StackFrame objects.
766 */
767 Local<Array> AsArray();
768
769 /**
770 * Grab a snapshot of the the current JavaScript execution stack.
771 *
772 * \param frame_limit The maximum number of stack frames we want to capture.
773 * \param options Enumerates the set of things we will capture for each
774 * StackFrame.
775 */
776 static Local<StackTrace> CurrentStackTrace(
777 int frame_limit,
778 StackTraceOptions options = kOverview);
779};
780
781
782/**
783 * A single JavaScript stack frame.
784 */
785class V8EXPORT StackFrame {
786 public:
787 /**
788 * Returns the number, 1-based, of the line for the associate function call.
789 * This method will return Message::kNoLineNumberInfo if it is unable to
790 * retrieve the line number, or if kLineNumber was not passed as an option
791 * when capturing the StackTrace.
792 */
793 int GetLineNumber() const;
794
795 /**
796 * Returns the 1-based column offset on the line for the associated function
797 * call.
798 * This method will return Message::kNoColumnInfo if it is unable to retrieve
799 * the column number, or if kColumnOffset was not passed as an option when
800 * capturing the StackTrace.
801 */
802 int GetColumn() const;
803
804 /**
805 * Returns the name of the resource that contains the script for the
806 * function for this StackFrame.
807 */
808 Local<String> GetScriptName() const;
809
810 /**
Ben Murdochf87a2032010-10-22 12:50:53 +0100811 * Returns the name of the resource that contains the script for the
812 * function for this StackFrame or sourceURL value if the script name
813 * is undefined and its source ends with //@ sourceURL=... string.
814 */
815 Local<String> GetScriptNameOrSourceURL() const;
816
817 /**
Kristian Monsen25f61362010-05-21 11:50:48 +0100818 * Returns the name of the function associated with this stack frame.
819 */
820 Local<String> GetFunctionName() const;
821
822 /**
823 * Returns whether or not the associated function is compiled via a call to
824 * eval().
825 */
826 bool IsEval() const;
827
828 /**
829 * Returns whther or not the associated function is called as a
830 * constructor via "new".
831 */
832 bool IsConstructor() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000833};
834
835
836// --- V a l u e ---
837
838
839/**
840 * The superclass of all JavaScript values and objects.
841 */
Steve Block8defd9f2010-07-08 12:39:36 +0100842class Value : public Data {
Steve Blocka7e24c12009-10-30 11:49:00 +0000843 public:
844
845 /**
846 * Returns true if this value is the undefined value. See ECMA-262
847 * 4.3.10.
848 */
Steve Block8defd9f2010-07-08 12:39:36 +0100849 V8EXPORT bool IsUndefined() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000850
851 /**
852 * Returns true if this value is the null value. See ECMA-262
853 * 4.3.11.
854 */
Steve Block8defd9f2010-07-08 12:39:36 +0100855 V8EXPORT bool IsNull() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000856
857 /**
858 * Returns true if this value is true.
859 */
Steve Block8defd9f2010-07-08 12:39:36 +0100860 V8EXPORT bool IsTrue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000861
862 /**
863 * Returns true if this value is false.
864 */
Steve Block8defd9f2010-07-08 12:39:36 +0100865 V8EXPORT bool IsFalse() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000866
867 /**
868 * Returns true if this value is an instance of the String type.
869 * See ECMA-262 8.4.
870 */
871 inline bool IsString() const;
872
873 /**
874 * Returns true if this value is a function.
875 */
Steve Block8defd9f2010-07-08 12:39:36 +0100876 V8EXPORT bool IsFunction() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000877
878 /**
879 * Returns true if this value is an array.
880 */
Steve Block8defd9f2010-07-08 12:39:36 +0100881 V8EXPORT bool IsArray() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000882
883 /**
884 * Returns true if this value is an object.
885 */
Steve Block8defd9f2010-07-08 12:39:36 +0100886 V8EXPORT bool IsObject() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000887
888 /**
889 * Returns true if this value is boolean.
890 */
Steve Block8defd9f2010-07-08 12:39:36 +0100891 V8EXPORT bool IsBoolean() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000892
893 /**
894 * Returns true if this value is a number.
895 */
Steve Block8defd9f2010-07-08 12:39:36 +0100896 V8EXPORT bool IsNumber() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000897
898 /**
899 * Returns true if this value is external.
900 */
Steve Block8defd9f2010-07-08 12:39:36 +0100901 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000902
903 /**
904 * Returns true if this value is a 32-bit signed integer.
905 */
Steve Block8defd9f2010-07-08 12:39:36 +0100906 V8EXPORT bool IsInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000907
908 /**
Steve Block6ded16b2010-05-10 14:33:55 +0100909 * Returns true if this value is a 32-bit unsigned integer.
910 */
Steve Block8defd9f2010-07-08 12:39:36 +0100911 V8EXPORT bool IsUint32() const;
Steve Block6ded16b2010-05-10 14:33:55 +0100912
913 /**
Steve Blocka7e24c12009-10-30 11:49:00 +0000914 * Returns true if this value is a Date.
915 */
Steve Block8defd9f2010-07-08 12:39:36 +0100916 V8EXPORT bool IsDate() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000917
Iain Merrick75681382010-08-19 15:07:18 +0100918 /**
919 * Returns true if this value is a RegExp.
920 */
921 V8EXPORT bool IsRegExp() const;
922
Steve Block8defd9f2010-07-08 12:39:36 +0100923 V8EXPORT Local<Boolean> ToBoolean() const;
924 V8EXPORT Local<Number> ToNumber() const;
925 V8EXPORT Local<String> ToString() const;
926 V8EXPORT Local<String> ToDetailString() const;
927 V8EXPORT Local<Object> ToObject() const;
928 V8EXPORT Local<Integer> ToInteger() const;
929 V8EXPORT Local<Uint32> ToUint32() const;
930 V8EXPORT Local<Int32> ToInt32() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000931
932 /**
933 * Attempts to convert a string to an array index.
934 * Returns an empty handle if the conversion fails.
935 */
Steve Block8defd9f2010-07-08 12:39:36 +0100936 V8EXPORT Local<Uint32> ToArrayIndex() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000937
Steve Block8defd9f2010-07-08 12:39:36 +0100938 V8EXPORT bool BooleanValue() const;
939 V8EXPORT double NumberValue() const;
940 V8EXPORT int64_t IntegerValue() const;
941 V8EXPORT uint32_t Uint32Value() const;
942 V8EXPORT int32_t Int32Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000943
944 /** JS == */
Steve Block8defd9f2010-07-08 12:39:36 +0100945 V8EXPORT bool Equals(Handle<Value> that) const;
946 V8EXPORT bool StrictEquals(Handle<Value> that) const;
Steve Block3ce2e202009-11-05 08:53:23 +0000947
Steve Blocka7e24c12009-10-30 11:49:00 +0000948 private:
949 inline bool QuickIsString() const;
Steve Block8defd9f2010-07-08 12:39:36 +0100950 V8EXPORT bool FullIsString() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000951};
952
953
954/**
955 * The superclass of primitive values. See ECMA-262 4.3.2.
956 */
Steve Block8defd9f2010-07-08 12:39:36 +0100957class Primitive : public Value { };
Steve Blocka7e24c12009-10-30 11:49:00 +0000958
959
960/**
961 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
962 * or false value.
963 */
Steve Block8defd9f2010-07-08 12:39:36 +0100964class Boolean : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000965 public:
Steve Block8defd9f2010-07-08 12:39:36 +0100966 V8EXPORT bool Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000967 static inline Handle<Boolean> New(bool value);
968};
969
970
971/**
972 * A JavaScript string value (ECMA-262, 4.3.17).
973 */
Steve Block8defd9f2010-07-08 12:39:36 +0100974class String : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +0000975 public:
976
977 /**
978 * Returns the number of characters in this string.
979 */
Steve Block8defd9f2010-07-08 12:39:36 +0100980 V8EXPORT int Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000981
982 /**
983 * Returns the number of bytes in the UTF-8 encoded
984 * representation of this string.
985 */
Steve Block8defd9f2010-07-08 12:39:36 +0100986 V8EXPORT int Utf8Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +0000987
988 /**
989 * Write the contents of the string to an external buffer.
990 * If no arguments are given, expects the buffer to be large
991 * enough to hold the entire string and NULL terminator. Copies
992 * the contents of the string and the NULL terminator into the
993 * buffer.
994 *
Ben Murdochb0fe1622011-05-05 13:52:32 +0100995 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
996 * before the end of the buffer.
997 *
Steve Blocka7e24c12009-10-30 11:49:00 +0000998 * Copies up to length characters into the output buffer.
999 * Only null-terminates if there is enough space in the buffer.
1000 *
1001 * \param buffer The buffer into which the string will be copied.
1002 * \param start The starting position within the string at which
1003 * copying begins.
Ben Murdochb0fe1622011-05-05 13:52:32 +01001004 * \param length The number of characters to copy from the string. For
1005 * WriteUtf8 the number of bytes in the buffer.
Steve Block6ded16b2010-05-10 14:33:55 +01001006 * \param nchars_ref The number of characters written, can be NULL.
1007 * \param hints Various hints that might affect performance of this or
1008 * subsequent operations.
Ben Murdochb0fe1622011-05-05 13:52:32 +01001009 * \return The number of characters copied to the buffer excluding the null
1010 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1011 * including the null terminator.
Steve Blocka7e24c12009-10-30 11:49:00 +00001012 */
Steve Block6ded16b2010-05-10 14:33:55 +01001013 enum WriteHints {
1014 NO_HINTS = 0,
1015 HINT_MANY_WRITES_EXPECTED = 1
1016 };
1017
Steve Block8defd9f2010-07-08 12:39:36 +01001018 V8EXPORT int Write(uint16_t* buffer,
1019 int start = 0,
1020 int length = -1,
1021 WriteHints hints = NO_HINTS) const; // UTF-16
1022 V8EXPORT int WriteAscii(char* buffer,
1023 int start = 0,
1024 int length = -1,
1025 WriteHints hints = NO_HINTS) const; // ASCII
1026 V8EXPORT int WriteUtf8(char* buffer,
1027 int length = -1,
1028 int* nchars_ref = NULL,
1029 WriteHints hints = NO_HINTS) const; // UTF-8
Steve Blocka7e24c12009-10-30 11:49:00 +00001030
1031 /**
1032 * A zero length string.
1033 */
Steve Block8defd9f2010-07-08 12:39:36 +01001034 V8EXPORT static v8::Local<v8::String> Empty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001035
1036 /**
1037 * Returns true if the string is external
1038 */
Steve Block8defd9f2010-07-08 12:39:36 +01001039 V8EXPORT bool IsExternal() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001040
1041 /**
1042 * Returns true if the string is both external and ascii
1043 */
Steve Block8defd9f2010-07-08 12:39:36 +01001044 V8EXPORT bool IsExternalAscii() const;
Leon Clarkee46be812010-01-19 14:06:41 +00001045
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001046 class V8EXPORT ExternalStringResourceBase { // NOLINT
Leon Clarkee46be812010-01-19 14:06:41 +00001047 public:
1048 virtual ~ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001049
Leon Clarkee46be812010-01-19 14:06:41 +00001050 protected:
1051 ExternalStringResourceBase() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001052
1053 /**
1054 * Internally V8 will call this Dispose method when the external string
1055 * resource is no longer needed. The default implementation will use the
1056 * delete operator. This method can be overridden in subclasses to
1057 * control how allocated external string resources are disposed.
1058 */
1059 virtual void Dispose() { delete this; }
1060
Leon Clarkee46be812010-01-19 14:06:41 +00001061 private:
1062 // Disallow copying and assigning.
1063 ExternalStringResourceBase(const ExternalStringResourceBase&);
1064 void operator=(const ExternalStringResourceBase&);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001065
1066 friend class v8::internal::Heap;
Leon Clarkee46be812010-01-19 14:06:41 +00001067 };
1068
Steve Blocka7e24c12009-10-30 11:49:00 +00001069 /**
1070 * An ExternalStringResource is a wrapper around a two-byte string
1071 * buffer that resides outside V8's heap. Implement an
1072 * ExternalStringResource to manage the life cycle of the underlying
1073 * buffer. Note that the string data must be immutable.
1074 */
Leon Clarkee46be812010-01-19 14:06:41 +00001075 class V8EXPORT ExternalStringResource
1076 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001077 public:
1078 /**
1079 * Override the destructor to manage the life cycle of the underlying
1080 * buffer.
1081 */
1082 virtual ~ExternalStringResource() {}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001083
1084 /**
1085 * The string data from the underlying buffer.
1086 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001087 virtual const uint16_t* data() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001088
1089 /**
1090 * The length of the string. That is, the number of two-byte characters.
1091 */
Steve Blocka7e24c12009-10-30 11:49:00 +00001092 virtual size_t length() const = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001093
Steve Blocka7e24c12009-10-30 11:49:00 +00001094 protected:
1095 ExternalStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001096 };
1097
1098 /**
1099 * An ExternalAsciiStringResource is a wrapper around an ascii
1100 * string buffer that resides outside V8's heap. Implement an
1101 * ExternalAsciiStringResource to manage the life cycle of the
1102 * underlying buffer. Note that the string data must be immutable
1103 * and that the data must be strict 7-bit ASCII, not Latin1 or
1104 * UTF-8, which would require special treatment internally in the
1105 * engine and, in the case of UTF-8, do not allow efficient indexing.
1106 * Use String::New or convert to 16 bit data for non-ASCII.
1107 */
1108
Leon Clarkee46be812010-01-19 14:06:41 +00001109 class V8EXPORT ExternalAsciiStringResource
1110 : public ExternalStringResourceBase {
Steve Blocka7e24c12009-10-30 11:49:00 +00001111 public:
1112 /**
1113 * Override the destructor to manage the life cycle of the underlying
1114 * buffer.
1115 */
1116 virtual ~ExternalAsciiStringResource() {}
1117 /** The string data from the underlying buffer.*/
1118 virtual const char* data() const = 0;
1119 /** The number of ascii characters in the string.*/
1120 virtual size_t length() const = 0;
1121 protected:
1122 ExternalAsciiStringResource() {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001123 };
1124
1125 /**
1126 * Get the ExternalStringResource for an external string. Returns
1127 * NULL if IsExternal() doesn't return true.
1128 */
1129 inline ExternalStringResource* GetExternalStringResource() const;
1130
1131 /**
1132 * Get the ExternalAsciiStringResource for an external ascii string.
1133 * Returns NULL if IsExternalAscii() doesn't return true.
1134 */
Steve Block8defd9f2010-07-08 12:39:36 +01001135 V8EXPORT ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001136
1137 static inline String* Cast(v8::Value* obj);
1138
1139 /**
1140 * Allocates a new string from either utf-8 encoded or ascii data.
1141 * The second parameter 'length' gives the buffer length.
1142 * If the data is utf-8 encoded, the caller must
1143 * be careful to supply the length parameter.
1144 * If it is not given, the function calls
1145 * 'strlen' to determine the buffer length, it might be
1146 * wrong if 'data' contains a null character.
1147 */
Steve Block8defd9f2010-07-08 12:39:36 +01001148 V8EXPORT static Local<String> New(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001149
1150 /** Allocates a new string from utf16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001151 V8EXPORT static Local<String> New(const uint16_t* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001152
1153 /** Creates a symbol. Returns one if it exists already.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001154 V8EXPORT static Local<String> NewSymbol(const char* data, int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001155
1156 /**
Steve Block3ce2e202009-11-05 08:53:23 +00001157 * Creates a new string by concatenating the left and the right strings
1158 * passed in as parameters.
1159 */
Steve Block8defd9f2010-07-08 12:39:36 +01001160 V8EXPORT static Local<String> Concat(Handle<String> left,
1161 Handle<String>right);
Steve Block3ce2e202009-11-05 08:53:23 +00001162
1163 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001164 * Creates a new external string using the data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001165 * resource. When the external string is no longer live on V8's heap the
1166 * resource will be disposed by calling its Dispose method. The caller of
1167 * this function should not otherwise delete or modify the resource. Neither
1168 * should the underlying buffer be deallocated or modified except through the
1169 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001170 */
Steve Block8defd9f2010-07-08 12:39:36 +01001171 V8EXPORT static Local<String> NewExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001172
1173 /**
1174 * Associate an external string resource with this string by transforming it
1175 * in place so that existing references to this string in the JavaScript heap
1176 * will use the external string resource. The external string resource's
1177 * character contents needs to be equivalent to this string.
1178 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001179 * The string is not modified if the operation fails. See NewExternal for
1180 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001181 */
Steve Block8defd9f2010-07-08 12:39:36 +01001182 V8EXPORT bool MakeExternal(ExternalStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001183
1184 /**
1185 * Creates a new external string using the ascii data defined in the given
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001186 * resource. When the external string is no longer live on V8's heap the
1187 * resource will be disposed by calling its Dispose method. The caller of
1188 * this function should not otherwise delete or modify the resource. Neither
1189 * should the underlying buffer be deallocated or modified except through the
1190 * destructor of the external string resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001191 */
Steve Block8defd9f2010-07-08 12:39:36 +01001192 V8EXPORT static Local<String> NewExternal(
1193 ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001194
1195 /**
1196 * Associate an external string resource with this string by transforming it
1197 * in place so that existing references to this string in the JavaScript heap
1198 * will use the external string resource. The external string resource's
1199 * character contents needs to be equivalent to this string.
1200 * Returns true if the string has been changed to be an external string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001201 * The string is not modified if the operation fails. See NewExternal for
1202 * information on the lifetime of the resource.
Steve Blocka7e24c12009-10-30 11:49:00 +00001203 */
Steve Block8defd9f2010-07-08 12:39:36 +01001204 V8EXPORT bool MakeExternal(ExternalAsciiStringResource* resource);
Steve Blocka7e24c12009-10-30 11:49:00 +00001205
1206 /**
1207 * Returns true if this string can be made external.
1208 */
Steve Block8defd9f2010-07-08 12:39:36 +01001209 V8EXPORT bool CanMakeExternal();
Steve Blocka7e24c12009-10-30 11:49:00 +00001210
1211 /** Creates an undetectable string from the supplied ascii or utf-8 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001212 V8EXPORT static Local<String> NewUndetectable(const char* data,
1213 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001214
1215 /** Creates an undetectable string from the supplied utf-16 data.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001216 V8EXPORT static Local<String> NewUndetectable(const uint16_t* data,
1217 int length = -1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001218
1219 /**
1220 * Converts an object to a utf8-encoded character array. Useful if
1221 * you want to print the object. If conversion to a string fails
1222 * (eg. due to an exception in the toString() method of the object)
1223 * then the length() method returns 0 and the * operator returns
1224 * NULL.
1225 */
1226 class V8EXPORT Utf8Value {
1227 public:
1228 explicit Utf8Value(Handle<v8::Value> obj);
1229 ~Utf8Value();
1230 char* operator*() { return str_; }
1231 const char* operator*() const { return str_; }
1232 int length() const { return length_; }
1233 private:
1234 char* str_;
1235 int length_;
1236
1237 // Disallow copying and assigning.
1238 Utf8Value(const Utf8Value&);
1239 void operator=(const Utf8Value&);
1240 };
1241
1242 /**
1243 * Converts an object to an ascii string.
1244 * Useful if you want to print the object.
1245 * If conversion to a string fails (eg. due to an exception in the toString()
1246 * method of the object) then the length() method returns 0 and the * operator
1247 * returns NULL.
1248 */
1249 class V8EXPORT AsciiValue {
1250 public:
1251 explicit AsciiValue(Handle<v8::Value> obj);
1252 ~AsciiValue();
1253 char* operator*() { return str_; }
1254 const char* operator*() const { return str_; }
1255 int length() const { return length_; }
1256 private:
1257 char* str_;
1258 int length_;
1259
1260 // Disallow copying and assigning.
1261 AsciiValue(const AsciiValue&);
1262 void operator=(const AsciiValue&);
1263 };
1264
1265 /**
1266 * Converts an object to a two-byte string.
1267 * If conversion to a string fails (eg. due to an exception in the toString()
1268 * method of the object) then the length() method returns 0 and the * operator
1269 * returns NULL.
1270 */
1271 class V8EXPORT Value {
1272 public:
1273 explicit Value(Handle<v8::Value> obj);
1274 ~Value();
1275 uint16_t* operator*() { return str_; }
1276 const uint16_t* operator*() const { return str_; }
1277 int length() const { return length_; }
1278 private:
1279 uint16_t* str_;
1280 int length_;
1281
1282 // Disallow copying and assigning.
1283 Value(const Value&);
1284 void operator=(const Value&);
1285 };
Steve Block3ce2e202009-11-05 08:53:23 +00001286
Steve Blocka7e24c12009-10-30 11:49:00 +00001287 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001288 V8EXPORT void VerifyExternalStringResource(ExternalStringResource* val) const;
1289 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001290};
1291
1292
1293/**
1294 * A JavaScript number value (ECMA-262, 4.3.20)
1295 */
Steve Block8defd9f2010-07-08 12:39:36 +01001296class Number : public Primitive {
Steve Blocka7e24c12009-10-30 11:49:00 +00001297 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001298 V8EXPORT double Value() const;
1299 V8EXPORT static Local<Number> New(double value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001300 static inline Number* Cast(v8::Value* obj);
1301 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001302 V8EXPORT Number();
Steve Blocka7e24c12009-10-30 11:49:00 +00001303 static void CheckCast(v8::Value* obj);
1304};
1305
1306
1307/**
1308 * A JavaScript value representing a signed integer.
1309 */
Steve Block8defd9f2010-07-08 12:39:36 +01001310class Integer : public Number {
Steve Blocka7e24c12009-10-30 11:49:00 +00001311 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001312 V8EXPORT static Local<Integer> New(int32_t value);
1313 V8EXPORT static Local<Integer> NewFromUnsigned(uint32_t value);
1314 V8EXPORT int64_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001315 static inline Integer* Cast(v8::Value* obj);
1316 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001317 V8EXPORT Integer();
1318 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001319};
1320
1321
1322/**
1323 * A JavaScript value representing a 32-bit signed integer.
1324 */
Steve Block8defd9f2010-07-08 12:39:36 +01001325class Int32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001326 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001327 V8EXPORT int32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001328 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001329 V8EXPORT Int32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001330};
1331
1332
1333/**
1334 * A JavaScript value representing a 32-bit unsigned integer.
1335 */
Steve Block8defd9f2010-07-08 12:39:36 +01001336class Uint32 : public Integer {
Steve Blocka7e24c12009-10-30 11:49:00 +00001337 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001338 V8EXPORT uint32_t Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001339 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001340 V8EXPORT Uint32();
Steve Blocka7e24c12009-10-30 11:49:00 +00001341};
1342
1343
1344/**
1345 * An instance of the built-in Date constructor (ECMA-262, 15.9).
1346 */
Steve Block8defd9f2010-07-08 12:39:36 +01001347class Date : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001348 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001349 V8EXPORT static Local<Value> New(double time);
Steve Blocka7e24c12009-10-30 11:49:00 +00001350
1351 /**
1352 * A specialization of Value::NumberValue that is more efficient
1353 * because we know the structure of this object.
1354 */
Steve Block8defd9f2010-07-08 12:39:36 +01001355 V8EXPORT double NumberValue() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001356
1357 static inline Date* Cast(v8::Value* obj);
Ben Murdochb0fe1622011-05-05 13:52:32 +01001358
1359 /**
1360 * Notification that the embedder has changed the time zone,
1361 * daylight savings time, or other date / time configuration
1362 * parameters. V8 keeps a cache of various values used for
1363 * date / time computation. This notification will reset
1364 * those cached values for the current context so that date /
1365 * time configuration changes would be reflected in the Date
1366 * object.
1367 *
1368 * This API should not be called more than needed as it will
1369 * negatively impact the performance of date operations.
1370 */
1371 V8EXPORT static void DateTimeConfigurationChangeNotification();
1372
Steve Blocka7e24c12009-10-30 11:49:00 +00001373 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001374 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001375};
1376
1377
Ben Murdochf87a2032010-10-22 12:50:53 +01001378/**
1379 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
1380 */
1381class RegExp : public Value {
1382 public:
1383 /**
1384 * Regular expression flag bits. They can be or'ed to enable a set
1385 * of flags.
1386 */
1387 enum Flags {
1388 kNone = 0,
1389 kGlobal = 1,
1390 kIgnoreCase = 2,
1391 kMultiline = 4
1392 };
1393
1394 /**
1395 * Creates a regular expression from the given pattern string and
1396 * the flags bit field. May throw a JavaScript exception as
1397 * described in ECMA-262, 15.10.4.1.
1398 *
1399 * For example,
1400 * RegExp::New(v8::String::New("foo"),
1401 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
1402 * is equivalent to evaluating "/foo/gm".
1403 */
1404 V8EXPORT static Local<RegExp> New(Handle<String> pattern,
1405 Flags flags);
1406
1407 /**
1408 * Returns the value of the source property: a string representing
1409 * the regular expression.
1410 */
1411 V8EXPORT Local<String> GetSource() const;
1412
1413 /**
1414 * Returns the flags bit field.
1415 */
1416 V8EXPORT Flags GetFlags() const;
1417
1418 static inline RegExp* Cast(v8::Value* obj);
1419
1420 private:
1421 V8EXPORT static void CheckCast(v8::Value* obj);
1422};
1423
1424
Steve Blocka7e24c12009-10-30 11:49:00 +00001425enum PropertyAttribute {
1426 None = 0,
1427 ReadOnly = 1 << 0,
1428 DontEnum = 1 << 1,
1429 DontDelete = 1 << 2
1430};
1431
Steve Block3ce2e202009-11-05 08:53:23 +00001432enum ExternalArrayType {
1433 kExternalByteArray = 1,
1434 kExternalUnsignedByteArray,
1435 kExternalShortArray,
1436 kExternalUnsignedShortArray,
1437 kExternalIntArray,
1438 kExternalUnsignedIntArray,
1439 kExternalFloatArray
1440};
1441
Steve Blocka7e24c12009-10-30 11:49:00 +00001442/**
Leon Clarkef7060e22010-06-03 12:02:55 +01001443 * Accessor[Getter|Setter] are used as callback functions when
1444 * setting|getting a particular property. See Object and ObjectTemplate's
1445 * method SetAccessor.
1446 */
1447typedef Handle<Value> (*AccessorGetter)(Local<String> property,
1448 const AccessorInfo& info);
1449
1450
1451typedef void (*AccessorSetter)(Local<String> property,
1452 Local<Value> value,
1453 const AccessorInfo& info);
1454
1455
1456/**
1457 * Access control specifications.
1458 *
1459 * Some accessors should be accessible across contexts. These
1460 * accessors have an explicit access control parameter which specifies
1461 * the kind of cross-context access that should be allowed.
1462 *
1463 * Additionally, for security, accessors can prohibit overwriting by
1464 * accessors defined in JavaScript. For objects that have such
1465 * accessors either locally or in their prototype chain it is not
1466 * possible to overwrite the accessor by using __defineGetter__ or
1467 * __defineSetter__ from JavaScript code.
1468 */
1469enum AccessControl {
1470 DEFAULT = 0,
1471 ALL_CAN_READ = 1,
1472 ALL_CAN_WRITE = 1 << 1,
1473 PROHIBITS_OVERWRITING = 1 << 2
1474};
1475
1476
1477/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001478 * A JavaScript object (ECMA-262, 4.3.3)
1479 */
Steve Block8defd9f2010-07-08 12:39:36 +01001480class Object : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001481 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001482 V8EXPORT bool Set(Handle<Value> key,
1483 Handle<Value> value,
1484 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001485
Steve Block8defd9f2010-07-08 12:39:36 +01001486 V8EXPORT bool Set(uint32_t index,
1487 Handle<Value> value);
Steve Block6ded16b2010-05-10 14:33:55 +01001488
Steve Blocka7e24c12009-10-30 11:49:00 +00001489 // Sets a local property on this object bypassing interceptors and
1490 // overriding accessors or read-only properties.
1491 //
1492 // Note that if the object has an interceptor the property will be set
1493 // locally, but since the interceptor takes precedence the local property
1494 // will only be returned if the interceptor doesn't return a value.
1495 //
1496 // Note also that this only works for named properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001497 V8EXPORT bool ForceSet(Handle<Value> key,
1498 Handle<Value> value,
1499 PropertyAttribute attribs = None);
Steve Blocka7e24c12009-10-30 11:49:00 +00001500
Steve Block8defd9f2010-07-08 12:39:36 +01001501 V8EXPORT Local<Value> Get(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001502
Steve Block8defd9f2010-07-08 12:39:36 +01001503 V8EXPORT Local<Value> Get(uint32_t index);
Steve Block6ded16b2010-05-10 14:33:55 +01001504
Steve Blocka7e24c12009-10-30 11:49:00 +00001505 // TODO(1245389): Replace the type-specific versions of these
1506 // functions with generic ones that accept a Handle<Value> key.
Steve Block8defd9f2010-07-08 12:39:36 +01001507 V8EXPORT bool Has(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001508
Steve Block8defd9f2010-07-08 12:39:36 +01001509 V8EXPORT bool Delete(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001510
1511 // Delete a property on this object bypassing interceptors and
1512 // ignoring dont-delete attributes.
Steve Block8defd9f2010-07-08 12:39:36 +01001513 V8EXPORT bool ForceDelete(Handle<Value> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001514
Steve Block8defd9f2010-07-08 12:39:36 +01001515 V8EXPORT bool Has(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001516
Steve Block8defd9f2010-07-08 12:39:36 +01001517 V8EXPORT bool Delete(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001518
Steve Block8defd9f2010-07-08 12:39:36 +01001519 V8EXPORT bool SetAccessor(Handle<String> name,
1520 AccessorGetter getter,
1521 AccessorSetter setter = 0,
1522 Handle<Value> data = Handle<Value>(),
1523 AccessControl settings = DEFAULT,
1524 PropertyAttribute attribute = None);
Leon Clarkef7060e22010-06-03 12:02:55 +01001525
Steve Blocka7e24c12009-10-30 11:49:00 +00001526 /**
1527 * Returns an array containing the names of the enumerable properties
1528 * of this object, including properties from prototype objects. The
1529 * array returned by this method contains the same values as would
1530 * be enumerated by a for-in statement over this object.
1531 */
Steve Block8defd9f2010-07-08 12:39:36 +01001532 V8EXPORT Local<Array> GetPropertyNames();
Steve Blocka7e24c12009-10-30 11:49:00 +00001533
1534 /**
1535 * Get the prototype object. This does not skip objects marked to
1536 * be skipped by __proto__ and it does not consult the security
1537 * handler.
1538 */
Steve Block8defd9f2010-07-08 12:39:36 +01001539 V8EXPORT Local<Value> GetPrototype();
Steve Blocka7e24c12009-10-30 11:49:00 +00001540
1541 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00001542 * Set the prototype object. This does not skip objects marked to
1543 * be skipped by __proto__ and it does not consult the security
1544 * handler.
1545 */
Steve Block8defd9f2010-07-08 12:39:36 +01001546 V8EXPORT bool SetPrototype(Handle<Value> prototype);
Andrei Popescu402d9372010-02-26 13:31:12 +00001547
1548 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00001549 * Finds an instance of the given function template in the prototype
1550 * chain.
1551 */
Steve Block8defd9f2010-07-08 12:39:36 +01001552 V8EXPORT Local<Object> FindInstanceInPrototypeChain(
1553 Handle<FunctionTemplate> tmpl);
Steve Blocka7e24c12009-10-30 11:49:00 +00001554
1555 /**
1556 * Call builtin Object.prototype.toString on this object.
1557 * This is different from Value::ToString() that may call
1558 * user-defined toString function. This one does not.
1559 */
Steve Block8defd9f2010-07-08 12:39:36 +01001560 V8EXPORT Local<String> ObjectProtoToString();
Steve Blocka7e24c12009-10-30 11:49:00 +00001561
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08001562 /**
1563 * Returns the name of the function invoked as a constructor for this object.
1564 */
1565 V8EXPORT Local<String> GetConstructorName();
1566
Steve Blocka7e24c12009-10-30 11:49:00 +00001567 /** Gets the number of internal fields for this Object. */
Steve Block8defd9f2010-07-08 12:39:36 +01001568 V8EXPORT int InternalFieldCount();
Steve Blocka7e24c12009-10-30 11:49:00 +00001569 /** Gets the value in an internal field. */
1570 inline Local<Value> GetInternalField(int index);
1571 /** Sets the value in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001572 V8EXPORT void SetInternalField(int index, Handle<Value> value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001573
1574 /** Gets a native pointer from an internal field. */
1575 inline void* GetPointerFromInternalField(int index);
Steve Block3ce2e202009-11-05 08:53:23 +00001576
Steve Blocka7e24c12009-10-30 11:49:00 +00001577 /** Sets a native pointer in an internal field. */
Steve Block8defd9f2010-07-08 12:39:36 +01001578 V8EXPORT void SetPointerInInternalField(int index, void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001579
1580 // Testers for local properties.
Steve Block8defd9f2010-07-08 12:39:36 +01001581 V8EXPORT bool HasRealNamedProperty(Handle<String> key);
1582 V8EXPORT bool HasRealIndexedProperty(uint32_t index);
1583 V8EXPORT bool HasRealNamedCallbackProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001584
1585 /**
1586 * If result.IsEmpty() no real property was located in the prototype chain.
1587 * This means interceptors in the prototype chain are not called.
1588 */
Steve Block8defd9f2010-07-08 12:39:36 +01001589 V8EXPORT Local<Value> GetRealNamedPropertyInPrototypeChain(
1590 Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001591
1592 /**
1593 * If result.IsEmpty() no real property was located on the object or
1594 * in the prototype chain.
1595 * This means interceptors in the prototype chain are not called.
1596 */
Steve Block8defd9f2010-07-08 12:39:36 +01001597 V8EXPORT Local<Value> GetRealNamedProperty(Handle<String> key);
Steve Blocka7e24c12009-10-30 11:49:00 +00001598
1599 /** Tests for a named lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001600 V8EXPORT bool HasNamedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001601
1602 /** Tests for an index lookup interceptor.*/
Steve Block8defd9f2010-07-08 12:39:36 +01001603 V8EXPORT bool HasIndexedLookupInterceptor();
Steve Blocka7e24c12009-10-30 11:49:00 +00001604
1605 /**
1606 * Turns on access check on the object if the object is an instance of
1607 * a template that has access check callbacks. If an object has no
1608 * access check info, the object cannot be accessed by anyone.
1609 */
Steve Block8defd9f2010-07-08 12:39:36 +01001610 V8EXPORT void TurnOnAccessCheck();
Steve Blocka7e24c12009-10-30 11:49:00 +00001611
1612 /**
1613 * Returns the identity hash for this object. The current implemenation uses
1614 * a hidden property on the object to store the identity hash.
1615 *
1616 * The return value will never be 0. Also, it is not guaranteed to be
1617 * unique.
1618 */
Steve Block8defd9f2010-07-08 12:39:36 +01001619 V8EXPORT int GetIdentityHash();
Steve Blocka7e24c12009-10-30 11:49:00 +00001620
1621 /**
1622 * Access hidden properties on JavaScript objects. These properties are
1623 * hidden from the executing JavaScript and only accessible through the V8
1624 * C++ API. Hidden properties introduced by V8 internally (for example the
1625 * identity hash) are prefixed with "v8::".
1626 */
Steve Block8defd9f2010-07-08 12:39:36 +01001627 V8EXPORT bool SetHiddenValue(Handle<String> key, Handle<Value> value);
1628 V8EXPORT Local<Value> GetHiddenValue(Handle<String> key);
1629 V8EXPORT bool DeleteHiddenValue(Handle<String> key);
Steve Block3ce2e202009-11-05 08:53:23 +00001630
Steve Blocka7e24c12009-10-30 11:49:00 +00001631 /**
1632 * Returns true if this is an instance of an api function (one
1633 * created from a function created from a function template) and has
1634 * been modified since it was created. Note that this method is
1635 * conservative and may return true for objects that haven't actually
1636 * been modified.
1637 */
Steve Block8defd9f2010-07-08 12:39:36 +01001638 V8EXPORT bool IsDirty();
Steve Blocka7e24c12009-10-30 11:49:00 +00001639
1640 /**
1641 * Clone this object with a fast but shallow copy. Values will point
1642 * to the same values as the original object.
1643 */
Steve Block8defd9f2010-07-08 12:39:36 +01001644 V8EXPORT Local<Object> Clone();
Steve Blocka7e24c12009-10-30 11:49:00 +00001645
1646 /**
1647 * Set the backing store of the indexed properties to be managed by the
1648 * embedding layer. Access to the indexed properties will follow the rules
1649 * spelled out in CanvasPixelArray.
1650 * Note: The embedding program still owns the data and needs to ensure that
1651 * the backing store is preserved while V8 has a reference.
1652 */
Steve Block8defd9f2010-07-08 12:39:36 +01001653 V8EXPORT void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001654 bool HasIndexedPropertiesInPixelData();
1655 uint8_t* GetIndexedPropertiesPixelData();
1656 int GetIndexedPropertiesPixelDataLength();
Steve Blocka7e24c12009-10-30 11:49:00 +00001657
Steve Block3ce2e202009-11-05 08:53:23 +00001658 /**
1659 * Set the backing store of the indexed properties to be managed by the
1660 * embedding layer. Access to the indexed properties will follow the rules
1661 * spelled out for the CanvasArray subtypes in the WebGL specification.
1662 * Note: The embedding program still owns the data and needs to ensure that
1663 * the backing store is preserved while V8 has a reference.
1664 */
Steve Block8defd9f2010-07-08 12:39:36 +01001665 V8EXPORT void SetIndexedPropertiesToExternalArrayData(
1666 void* data,
1667 ExternalArrayType array_type,
1668 int number_of_elements);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001669 bool HasIndexedPropertiesInExternalArrayData();
1670 void* GetIndexedPropertiesExternalArrayData();
1671 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
1672 int GetIndexedPropertiesExternalArrayDataLength();
Steve Block3ce2e202009-11-05 08:53:23 +00001673
Steve Block8defd9f2010-07-08 12:39:36 +01001674 V8EXPORT static Local<Object> New();
Steve Blocka7e24c12009-10-30 11:49:00 +00001675 static inline Object* Cast(Value* obj);
1676 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001677 V8EXPORT Object();
1678 V8EXPORT static void CheckCast(Value* obj);
1679 V8EXPORT Local<Value> CheckedGetInternalField(int index);
1680 V8EXPORT void* SlowGetPointerFromInternalField(int index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001681
1682 /**
1683 * If quick access to the internal field is possible this method
Steve Block3ce2e202009-11-05 08:53:23 +00001684 * returns the value. Otherwise an empty handle is returned.
Steve Blocka7e24c12009-10-30 11:49:00 +00001685 */
1686 inline Local<Value> UncheckedGetInternalField(int index);
1687};
1688
1689
1690/**
1691 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
1692 */
Steve Block8defd9f2010-07-08 12:39:36 +01001693class Array : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001694 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001695 V8EXPORT uint32_t Length() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001696
1697 /**
1698 * Clones an element at index |index|. Returns an empty
1699 * handle if cloning fails (for any reason).
1700 */
Steve Block8defd9f2010-07-08 12:39:36 +01001701 V8EXPORT Local<Object> CloneElementAt(uint32_t index);
Steve Blocka7e24c12009-10-30 11:49:00 +00001702
Steve Block8defd9f2010-07-08 12:39:36 +01001703 V8EXPORT static Local<Array> New(int length = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001704 static inline Array* Cast(Value* obj);
1705 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001706 V8EXPORT Array();
Steve Blocka7e24c12009-10-30 11:49:00 +00001707 static void CheckCast(Value* obj);
1708};
1709
1710
1711/**
1712 * A JavaScript function object (ECMA-262, 15.3).
1713 */
Steve Block8defd9f2010-07-08 12:39:36 +01001714class Function : public Object {
Steve Blocka7e24c12009-10-30 11:49:00 +00001715 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001716 V8EXPORT Local<Object> NewInstance() const;
1717 V8EXPORT Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
1718 V8EXPORT Local<Value> Call(Handle<Object> recv,
1719 int argc,
1720 Handle<Value> argv[]);
1721 V8EXPORT void SetName(Handle<String> name);
1722 V8EXPORT Handle<Value> GetName() const;
Andrei Popescu402d9372010-02-26 13:31:12 +00001723
1724 /**
1725 * Returns zero based line number of function body and
1726 * kLineOffsetNotFound if no information available.
1727 */
Steve Block8defd9f2010-07-08 12:39:36 +01001728 V8EXPORT int GetScriptLineNumber() const;
1729 V8EXPORT ScriptOrigin GetScriptOrigin() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001730 static inline Function* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001731 V8EXPORT static const int kLineOffsetNotFound;
Steve Blocka7e24c12009-10-30 11:49:00 +00001732 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001733 V8EXPORT Function();
1734 V8EXPORT static void CheckCast(Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001735};
1736
1737
1738/**
1739 * A JavaScript value that wraps a C++ void*. This type of value is
1740 * mainly used to associate C++ data structures with JavaScript
1741 * objects.
1742 *
1743 * The Wrap function V8 will return the most optimal Value object wrapping the
1744 * C++ void*. The type of the value is not guaranteed to be an External object
1745 * and no assumptions about its type should be made. To access the wrapped
1746 * value Unwrap should be used, all other operations on that object will lead
1747 * to unpredictable results.
1748 */
Steve Block8defd9f2010-07-08 12:39:36 +01001749class External : public Value {
Steve Blocka7e24c12009-10-30 11:49:00 +00001750 public:
Steve Block8defd9f2010-07-08 12:39:36 +01001751 V8EXPORT static Local<Value> Wrap(void* data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001752 static inline void* Unwrap(Handle<Value> obj);
1753
Steve Block8defd9f2010-07-08 12:39:36 +01001754 V8EXPORT static Local<External> New(void* value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001755 static inline External* Cast(Value* obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001756 V8EXPORT void* Value() const;
Steve Blocka7e24c12009-10-30 11:49:00 +00001757 private:
Steve Block8defd9f2010-07-08 12:39:36 +01001758 V8EXPORT External();
1759 V8EXPORT static void CheckCast(v8::Value* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001760 static inline void* QuickUnwrap(Handle<v8::Value> obj);
Steve Block8defd9f2010-07-08 12:39:36 +01001761 V8EXPORT static void* FullUnwrap(Handle<v8::Value> obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00001762};
1763
1764
1765// --- T e m p l a t e s ---
1766
1767
1768/**
1769 * The superclass of object and function templates.
1770 */
1771class V8EXPORT Template : public Data {
1772 public:
1773 /** Adds a property to each instance created by this template.*/
1774 void Set(Handle<String> name, Handle<Data> value,
1775 PropertyAttribute attributes = None);
1776 inline void Set(const char* name, Handle<Data> value);
1777 private:
1778 Template();
1779
1780 friend class ObjectTemplate;
1781 friend class FunctionTemplate;
1782};
1783
1784
1785/**
1786 * The argument information given to function call callbacks. This
1787 * class provides access to information about the context of the call,
1788 * including the receiver, the number and values of arguments, and
1789 * the holder of the function.
1790 */
Steve Block8defd9f2010-07-08 12:39:36 +01001791class Arguments {
Steve Blocka7e24c12009-10-30 11:49:00 +00001792 public:
1793 inline int Length() const;
1794 inline Local<Value> operator[](int i) const;
1795 inline Local<Function> Callee() const;
1796 inline Local<Object> This() const;
1797 inline Local<Object> Holder() const;
1798 inline bool IsConstructCall() const;
1799 inline Local<Value> Data() const;
1800 private:
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001801 static const int kDataIndex = 0;
1802 static const int kCalleeIndex = -1;
1803 static const int kHolderIndex = -2;
1804
Steve Blocka7e24c12009-10-30 11:49:00 +00001805 friend class ImplementationUtilities;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001806 inline Arguments(internal::Object** implicit_args,
1807 internal::Object** values,
1808 int length,
1809 bool is_construct_call);
1810 internal::Object** implicit_args_;
1811 internal::Object** values_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001812 int length_;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001813 bool is_construct_call_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001814};
1815
1816
1817/**
1818 * The information passed to an accessor callback about the context
1819 * of the property access.
1820 */
1821class V8EXPORT AccessorInfo {
1822 public:
1823 inline AccessorInfo(internal::Object** args)
1824 : args_(args) { }
1825 inline Local<Value> Data() const;
1826 inline Local<Object> This() const;
1827 inline Local<Object> Holder() const;
1828 private:
1829 internal::Object** args_;
1830};
1831
1832
1833typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
1834
Steve Blocka7e24c12009-10-30 11:49:00 +00001835/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001836 * NamedProperty[Getter|Setter] are used as interceptors on object.
1837 * See ObjectTemplate::SetNamedPropertyHandler.
1838 */
1839typedef Handle<Value> (*NamedPropertyGetter)(Local<String> property,
1840 const AccessorInfo& info);
1841
1842
1843/**
1844 * Returns the value if the setter intercepts the request.
1845 * Otherwise, returns an empty handle.
1846 */
1847typedef Handle<Value> (*NamedPropertySetter)(Local<String> property,
1848 Local<Value> value,
1849 const AccessorInfo& info);
1850
Steve Blocka7e24c12009-10-30 11:49:00 +00001851/**
1852 * Returns a non-empty handle if the interceptor intercepts the request.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001853 * The result is an integer encoding property attributes (like v8::None,
1854 * v8::DontEnum, etc.)
Steve Blocka7e24c12009-10-30 11:49:00 +00001855 */
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001856typedef Handle<Integer> (*NamedPropertyQuery)(Local<String> property,
1857 const AccessorInfo& info);
Steve Blocka7e24c12009-10-30 11:49:00 +00001858
1859
1860/**
1861 * Returns a non-empty handle if the deleter intercepts the request.
1862 * The return value is true if the property could be deleted and false
1863 * otherwise.
1864 */
1865typedef Handle<Boolean> (*NamedPropertyDeleter)(Local<String> property,
1866 const AccessorInfo& info);
1867
1868/**
1869 * Returns an array containing the names of the properties the named
1870 * property getter intercepts.
1871 */
1872typedef Handle<Array> (*NamedPropertyEnumerator)(const AccessorInfo& info);
1873
1874
1875/**
1876 * Returns the value of the property if the getter intercepts the
1877 * request. Otherwise, returns an empty handle.
1878 */
1879typedef Handle<Value> (*IndexedPropertyGetter)(uint32_t index,
1880 const AccessorInfo& info);
1881
1882
1883/**
1884 * Returns the value if the setter intercepts the request.
1885 * Otherwise, returns an empty handle.
1886 */
1887typedef Handle<Value> (*IndexedPropertySetter)(uint32_t index,
1888 Local<Value> value,
1889 const AccessorInfo& info);
1890
1891
1892/**
1893 * Returns a non-empty handle if the interceptor intercepts the request.
Iain Merrick75681382010-08-19 15:07:18 +01001894 * The result is an integer encoding property attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00001895 */
Iain Merrick75681382010-08-19 15:07:18 +01001896typedef Handle<Integer> (*IndexedPropertyQuery)(uint32_t index,
Steve Blocka7e24c12009-10-30 11:49:00 +00001897 const AccessorInfo& info);
1898
1899/**
1900 * Returns a non-empty handle if the deleter intercepts the request.
1901 * The return value is true if the property could be deleted and false
1902 * otherwise.
1903 */
1904typedef Handle<Boolean> (*IndexedPropertyDeleter)(uint32_t index,
1905 const AccessorInfo& info);
1906
1907/**
1908 * Returns an array containing the indices of the properties the
1909 * indexed property getter intercepts.
1910 */
1911typedef Handle<Array> (*IndexedPropertyEnumerator)(const AccessorInfo& info);
1912
1913
1914/**
Steve Blocka7e24c12009-10-30 11:49:00 +00001915 * Access type specification.
1916 */
1917enum AccessType {
1918 ACCESS_GET,
1919 ACCESS_SET,
1920 ACCESS_HAS,
1921 ACCESS_DELETE,
1922 ACCESS_KEYS
1923};
1924
1925
1926/**
1927 * Returns true if cross-context access should be allowed to the named
1928 * property with the given key on the host object.
1929 */
1930typedef bool (*NamedSecurityCallback)(Local<Object> host,
1931 Local<Value> key,
1932 AccessType type,
1933 Local<Value> data);
1934
1935
1936/**
1937 * Returns true if cross-context access should be allowed to the indexed
1938 * property with the given index on the host object.
1939 */
1940typedef bool (*IndexedSecurityCallback)(Local<Object> host,
1941 uint32_t index,
1942 AccessType type,
1943 Local<Value> data);
1944
1945
1946/**
1947 * A FunctionTemplate is used to create functions at runtime. There
1948 * can only be one function created from a FunctionTemplate in a
1949 * context. The lifetime of the created function is equal to the
1950 * lifetime of the context. So in case the embedder needs to create
1951 * temporary functions that can be collected using Scripts is
1952 * preferred.
1953 *
1954 * A FunctionTemplate can have properties, these properties are added to the
1955 * function object when it is created.
1956 *
1957 * A FunctionTemplate has a corresponding instance template which is
1958 * used to create object instances when the function is used as a
1959 * constructor. Properties added to the instance template are added to
1960 * each object instance.
1961 *
1962 * A FunctionTemplate can have a prototype template. The prototype template
1963 * is used to create the prototype object of the function.
1964 *
1965 * The following example shows how to use a FunctionTemplate:
1966 *
1967 * \code
1968 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
1969 * t->Set("func_property", v8::Number::New(1));
1970 *
1971 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
1972 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
1973 * proto_t->Set("proto_const", v8::Number::New(2));
1974 *
1975 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
1976 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
1977 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
1978 * instance_t->Set("instance_property", Number::New(3));
1979 *
1980 * v8::Local<v8::Function> function = t->GetFunction();
1981 * v8::Local<v8::Object> instance = function->NewInstance();
1982 * \endcode
1983 *
1984 * Let's use "function" as the JS variable name of the function object
1985 * and "instance" for the instance object created above. The function
1986 * and the instance will have the following properties:
1987 *
1988 * \code
1989 * func_property in function == true;
1990 * function.func_property == 1;
1991 *
1992 * function.prototype.proto_method() invokes 'InvokeCallback'
1993 * function.prototype.proto_const == 2;
1994 *
1995 * instance instanceof function == true;
1996 * instance.instance_accessor calls 'InstanceAccessorCallback'
1997 * instance.instance_property == 3;
1998 * \endcode
1999 *
2000 * A FunctionTemplate can inherit from another one by calling the
2001 * FunctionTemplate::Inherit method. The following graph illustrates
2002 * the semantics of inheritance:
2003 *
2004 * \code
2005 * FunctionTemplate Parent -> Parent() . prototype -> { }
2006 * ^ ^
2007 * | Inherit(Parent) | .__proto__
2008 * | |
2009 * FunctionTemplate Child -> Child() . prototype -> { }
2010 * \endcode
2011 *
2012 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
2013 * object of the Child() function has __proto__ pointing to the
2014 * Parent() function's prototype object. An instance of the Child
2015 * function has all properties on Parent's instance templates.
2016 *
2017 * Let Parent be the FunctionTemplate initialized in the previous
2018 * section and create a Child FunctionTemplate by:
2019 *
2020 * \code
2021 * Local<FunctionTemplate> parent = t;
2022 * Local<FunctionTemplate> child = FunctionTemplate::New();
2023 * child->Inherit(parent);
2024 *
2025 * Local<Function> child_function = child->GetFunction();
2026 * Local<Object> child_instance = child_function->NewInstance();
2027 * \endcode
2028 *
2029 * The Child function and Child instance will have the following
2030 * properties:
2031 *
2032 * \code
2033 * child_func.prototype.__proto__ == function.prototype;
2034 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
2035 * child_instance.instance_property == 3;
2036 * \endcode
2037 */
2038class V8EXPORT FunctionTemplate : public Template {
2039 public:
2040 /** Creates a function template.*/
2041 static Local<FunctionTemplate> New(
2042 InvocationCallback callback = 0,
2043 Handle<Value> data = Handle<Value>(),
2044 Handle<Signature> signature = Handle<Signature>());
2045 /** Returns the unique function instance in the current execution context.*/
2046 Local<Function> GetFunction();
2047
2048 /**
2049 * Set the call-handler callback for a FunctionTemplate. This
2050 * callback is called whenever the function created from this
2051 * FunctionTemplate is called.
2052 */
2053 void SetCallHandler(InvocationCallback callback,
2054 Handle<Value> data = Handle<Value>());
2055
2056 /** Get the InstanceTemplate. */
2057 Local<ObjectTemplate> InstanceTemplate();
2058
2059 /** Causes the function template to inherit from a parent function template.*/
2060 void Inherit(Handle<FunctionTemplate> parent);
2061
2062 /**
2063 * A PrototypeTemplate is the template used to create the prototype object
2064 * of the function created by this template.
2065 */
2066 Local<ObjectTemplate> PrototypeTemplate();
2067
2068
2069 /**
2070 * Set the class name of the FunctionTemplate. This is used for
2071 * printing objects created with the function created from the
2072 * FunctionTemplate as its constructor.
2073 */
2074 void SetClassName(Handle<String> name);
2075
2076 /**
2077 * Determines whether the __proto__ accessor ignores instances of
2078 * the function template. If instances of the function template are
2079 * ignored, __proto__ skips all instances and instead returns the
2080 * next object in the prototype chain.
2081 *
2082 * Call with a value of true to make the __proto__ accessor ignore
2083 * instances of the function template. Call with a value of false
2084 * to make the __proto__ accessor not ignore instances of the
2085 * function template. By default, instances of a function template
2086 * are not ignored.
2087 */
2088 void SetHiddenPrototype(bool value);
2089
2090 /**
2091 * Returns true if the given object is an instance of this function
2092 * template.
2093 */
2094 bool HasInstance(Handle<Value> object);
2095
2096 private:
2097 FunctionTemplate();
2098 void AddInstancePropertyAccessor(Handle<String> name,
2099 AccessorGetter getter,
2100 AccessorSetter setter,
2101 Handle<Value> data,
2102 AccessControl settings,
2103 PropertyAttribute attributes);
2104 void SetNamedInstancePropertyHandler(NamedPropertyGetter getter,
2105 NamedPropertySetter setter,
2106 NamedPropertyQuery query,
2107 NamedPropertyDeleter remover,
2108 NamedPropertyEnumerator enumerator,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002109 Handle<Value> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00002110 void SetIndexedInstancePropertyHandler(IndexedPropertyGetter getter,
2111 IndexedPropertySetter setter,
2112 IndexedPropertyQuery query,
2113 IndexedPropertyDeleter remover,
2114 IndexedPropertyEnumerator enumerator,
2115 Handle<Value> data);
2116 void SetInstanceCallAsFunctionHandler(InvocationCallback callback,
2117 Handle<Value> data);
2118
2119 friend class Context;
2120 friend class ObjectTemplate;
2121};
2122
2123
2124/**
2125 * An ObjectTemplate is used to create objects at runtime.
2126 *
2127 * Properties added to an ObjectTemplate are added to each object
2128 * created from the ObjectTemplate.
2129 */
2130class V8EXPORT ObjectTemplate : public Template {
2131 public:
2132 /** Creates an ObjectTemplate. */
2133 static Local<ObjectTemplate> New();
2134
2135 /** Creates a new instance of this template.*/
2136 Local<Object> NewInstance();
2137
2138 /**
2139 * Sets an accessor on the object template.
2140 *
2141 * Whenever the property with the given name is accessed on objects
2142 * created from this ObjectTemplate the getter and setter callbacks
2143 * are called instead of getting and setting the property directly
2144 * on the JavaScript object.
2145 *
2146 * \param name The name of the property for which an accessor is added.
2147 * \param getter The callback to invoke when getting the property.
2148 * \param setter The callback to invoke when setting the property.
2149 * \param data A piece of data that will be passed to the getter and setter
2150 * callbacks whenever they are invoked.
2151 * \param settings Access control settings for the accessor. This is a bit
2152 * field consisting of one of more of
2153 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
2154 * The default is to not allow cross-context access.
2155 * ALL_CAN_READ means that all cross-context reads are allowed.
2156 * ALL_CAN_WRITE means that all cross-context writes are allowed.
2157 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
2158 * cross-context access.
2159 * \param attribute The attributes of the property for which an accessor
2160 * is added.
2161 */
2162 void SetAccessor(Handle<String> name,
2163 AccessorGetter getter,
2164 AccessorSetter setter = 0,
2165 Handle<Value> data = Handle<Value>(),
2166 AccessControl settings = DEFAULT,
2167 PropertyAttribute attribute = None);
2168
2169 /**
2170 * Sets a named property handler on the object template.
2171 *
2172 * Whenever a named property is accessed on objects created from
2173 * this object template, the provided callback is invoked instead of
2174 * accessing the property directly on the JavaScript object.
2175 *
2176 * \param getter The callback to invoke when getting a property.
2177 * \param setter The callback to invoke when setting a property.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002178 * \param query The callback to invoke to check if a property is present,
2179 * and if present, get its attributes.
Steve Blocka7e24c12009-10-30 11:49:00 +00002180 * \param deleter The callback to invoke when deleting a property.
2181 * \param enumerator The callback to invoke to enumerate all the named
2182 * properties of an object.
2183 * \param data A piece of data that will be passed to the callbacks
2184 * whenever they are invoked.
2185 */
2186 void SetNamedPropertyHandler(NamedPropertyGetter getter,
2187 NamedPropertySetter setter = 0,
2188 NamedPropertyQuery query = 0,
2189 NamedPropertyDeleter deleter = 0,
2190 NamedPropertyEnumerator enumerator = 0,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002191 Handle<Value> data = Handle<Value>());
Steve Blocka7e24c12009-10-30 11:49:00 +00002192
2193 /**
2194 * Sets an indexed property handler on the object template.
2195 *
2196 * Whenever an indexed property is accessed on objects created from
2197 * this object template, the provided callback is invoked instead of
2198 * accessing the property directly on the JavaScript object.
2199 *
2200 * \param getter The callback to invoke when getting a property.
2201 * \param setter The callback to invoke when setting a property.
2202 * \param query The callback to invoke to check is an object has a property.
2203 * \param deleter The callback to invoke when deleting a property.
2204 * \param enumerator The callback to invoke to enumerate all the indexed
2205 * properties of an object.
2206 * \param data A piece of data that will be passed to the callbacks
2207 * whenever they are invoked.
2208 */
2209 void SetIndexedPropertyHandler(IndexedPropertyGetter getter,
2210 IndexedPropertySetter setter = 0,
2211 IndexedPropertyQuery query = 0,
2212 IndexedPropertyDeleter deleter = 0,
2213 IndexedPropertyEnumerator enumerator = 0,
2214 Handle<Value> data = Handle<Value>());
Iain Merrick75681382010-08-19 15:07:18 +01002215
Steve Blocka7e24c12009-10-30 11:49:00 +00002216 /**
2217 * Sets the callback to be used when calling instances created from
2218 * this template as a function. If no callback is set, instances
2219 * behave like normal JavaScript objects that cannot be called as a
2220 * function.
2221 */
2222 void SetCallAsFunctionHandler(InvocationCallback callback,
2223 Handle<Value> data = Handle<Value>());
2224
2225 /**
2226 * Mark object instances of the template as undetectable.
2227 *
2228 * In many ways, undetectable objects behave as though they are not
2229 * there. They behave like 'undefined' in conditionals and when
2230 * printed. However, properties can be accessed and called as on
2231 * normal objects.
2232 */
2233 void MarkAsUndetectable();
2234
2235 /**
2236 * Sets access check callbacks on the object template.
2237 *
2238 * When accessing properties on instances of this object template,
2239 * the access check callback will be called to determine whether or
2240 * not to allow cross-context access to the properties.
2241 * The last parameter specifies whether access checks are turned
2242 * on by default on instances. If access checks are off by default,
2243 * they can be turned on on individual instances by calling
2244 * Object::TurnOnAccessCheck().
2245 */
2246 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
2247 IndexedSecurityCallback indexed_handler,
2248 Handle<Value> data = Handle<Value>(),
2249 bool turned_on_by_default = true);
2250
2251 /**
2252 * Gets the number of internal fields for objects generated from
2253 * this template.
2254 */
2255 int InternalFieldCount();
2256
2257 /**
2258 * Sets the number of internal fields for objects generated from
2259 * this template.
2260 */
2261 void SetInternalFieldCount(int value);
2262
2263 private:
2264 ObjectTemplate();
2265 static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
2266 friend class FunctionTemplate;
2267};
2268
2269
2270/**
2271 * A Signature specifies which receivers and arguments a function can
2272 * legally be called with.
2273 */
2274class V8EXPORT Signature : public Data {
2275 public:
2276 static Local<Signature> New(Handle<FunctionTemplate> receiver =
2277 Handle<FunctionTemplate>(),
2278 int argc = 0,
2279 Handle<FunctionTemplate> argv[] = 0);
2280 private:
2281 Signature();
2282};
2283
2284
2285/**
2286 * A utility for determining the type of objects based on the template
2287 * they were constructed from.
2288 */
2289class V8EXPORT TypeSwitch : public Data {
2290 public:
2291 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
2292 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
2293 int match(Handle<Value> value);
2294 private:
2295 TypeSwitch();
2296};
2297
2298
2299// --- E x t e n s i o n s ---
2300
2301
2302/**
2303 * Ignore
2304 */
2305class V8EXPORT Extension { // NOLINT
2306 public:
2307 Extension(const char* name,
2308 const char* source = 0,
2309 int dep_count = 0,
2310 const char** deps = 0);
2311 virtual ~Extension() { }
2312 virtual v8::Handle<v8::FunctionTemplate>
2313 GetNativeFunction(v8::Handle<v8::String> name) {
2314 return v8::Handle<v8::FunctionTemplate>();
2315 }
2316
2317 const char* name() { return name_; }
2318 const char* source() { return source_; }
2319 int dependency_count() { return dep_count_; }
2320 const char** dependencies() { return deps_; }
2321 void set_auto_enable(bool value) { auto_enable_ = value; }
2322 bool auto_enable() { return auto_enable_; }
2323
2324 private:
2325 const char* name_;
2326 const char* source_;
2327 int dep_count_;
2328 const char** deps_;
2329 bool auto_enable_;
2330
2331 // Disallow copying and assigning.
2332 Extension(const Extension&);
2333 void operator=(const Extension&);
2334};
2335
2336
2337void V8EXPORT RegisterExtension(Extension* extension);
2338
2339
2340/**
2341 * Ignore
2342 */
2343class V8EXPORT DeclareExtension {
2344 public:
2345 inline DeclareExtension(Extension* extension) {
2346 RegisterExtension(extension);
2347 }
2348};
2349
2350
2351// --- S t a t i c s ---
2352
2353
2354Handle<Primitive> V8EXPORT Undefined();
2355Handle<Primitive> V8EXPORT Null();
2356Handle<Boolean> V8EXPORT True();
2357Handle<Boolean> V8EXPORT False();
2358
2359
2360/**
2361 * A set of constraints that specifies the limits of the runtime's memory use.
2362 * You must set the heap size before initializing the VM - the size cannot be
2363 * adjusted after the VM is initialized.
2364 *
2365 * If you are using threads then you should hold the V8::Locker lock while
2366 * setting the stack limit and you must set a non-default stack limit separately
2367 * for each thread.
2368 */
2369class V8EXPORT ResourceConstraints {
2370 public:
2371 ResourceConstraints();
2372 int max_young_space_size() const { return max_young_space_size_; }
2373 void set_max_young_space_size(int value) { max_young_space_size_ = value; }
2374 int max_old_space_size() const { return max_old_space_size_; }
2375 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
Russell Brenner90bac252010-11-18 13:33:46 -08002376 int max_executable_size() { return max_executable_size_; }
2377 void set_max_executable_size(int value) { max_executable_size_ = value; }
Steve Blocka7e24c12009-10-30 11:49:00 +00002378 uint32_t* stack_limit() const { return stack_limit_; }
2379 // Sets an address beyond which the VM's stack may not grow.
2380 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
2381 private:
2382 int max_young_space_size_;
2383 int max_old_space_size_;
Russell Brenner90bac252010-11-18 13:33:46 -08002384 int max_executable_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002385 uint32_t* stack_limit_;
2386};
2387
2388
Kristian Monsen25f61362010-05-21 11:50:48 +01002389bool V8EXPORT SetResourceConstraints(ResourceConstraints* constraints);
Steve Blocka7e24c12009-10-30 11:49:00 +00002390
2391
2392// --- E x c e p t i o n s ---
2393
2394
2395typedef void (*FatalErrorCallback)(const char* location, const char* message);
2396
2397
2398typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> data);
2399
2400
2401/**
2402 * Schedules an exception to be thrown when returning to JavaScript. When an
2403 * exception has been scheduled it is illegal to invoke any JavaScript
2404 * operation; the caller must return immediately and only after the exception
2405 * has been handled does it become legal to invoke JavaScript operations.
2406 */
2407Handle<Value> V8EXPORT ThrowException(Handle<Value> exception);
2408
2409/**
2410 * Create new error objects by calling the corresponding error object
2411 * constructor with the message.
2412 */
2413class V8EXPORT Exception {
2414 public:
2415 static Local<Value> RangeError(Handle<String> message);
2416 static Local<Value> ReferenceError(Handle<String> message);
2417 static Local<Value> SyntaxError(Handle<String> message);
2418 static Local<Value> TypeError(Handle<String> message);
2419 static Local<Value> Error(Handle<String> message);
2420};
2421
2422
2423// --- C o u n t e r s C a l l b a c k s ---
2424
2425typedef int* (*CounterLookupCallback)(const char* name);
2426
2427typedef void* (*CreateHistogramCallback)(const char* name,
2428 int min,
2429 int max,
2430 size_t buckets);
2431
2432typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
2433
Iain Merrick9ac36c92010-09-13 15:29:50 +01002434// --- M e m o r y A l l o c a t i o n C a l l b a c k ---
2435 enum ObjectSpace {
2436 kObjectSpaceNewSpace = 1 << 0,
2437 kObjectSpaceOldPointerSpace = 1 << 1,
2438 kObjectSpaceOldDataSpace = 1 << 2,
2439 kObjectSpaceCodeSpace = 1 << 3,
2440 kObjectSpaceMapSpace = 1 << 4,
2441 kObjectSpaceLoSpace = 1 << 5,
2442
2443 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
2444 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
2445 kObjectSpaceLoSpace
2446 };
2447
2448 enum AllocationAction {
2449 kAllocationActionAllocate = 1 << 0,
2450 kAllocationActionFree = 1 << 1,
2451 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
2452 };
2453
2454typedef void (*MemoryAllocationCallback)(ObjectSpace space,
2455 AllocationAction action,
2456 int size);
2457
Steve Blocka7e24c12009-10-30 11:49:00 +00002458// --- 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 ---
2459typedef void (*FailedAccessCheckCallback)(Local<Object> target,
2460 AccessType type,
2461 Local<Value> data);
2462
2463// --- 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
2464
2465/**
Steve Block6ded16b2010-05-10 14:33:55 +01002466 * Applications can register callback functions which will be called
2467 * before and after a garbage collection. Allocations are not
2468 * allowed in the callback functions, you therefore cannot manipulate
Steve Blocka7e24c12009-10-30 11:49:00 +00002469 * objects (set or delete properties for example) since it is possible
2470 * such operations will result in the allocation of objects.
2471 */
Steve Block6ded16b2010-05-10 14:33:55 +01002472enum GCType {
2473 kGCTypeScavenge = 1 << 0,
2474 kGCTypeMarkSweepCompact = 1 << 1,
2475 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
2476};
2477
2478enum GCCallbackFlags {
2479 kNoGCCallbackFlags = 0,
2480 kGCCallbackFlagCompacted = 1 << 0
2481};
2482
2483typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
2484typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
2485
Steve Blocka7e24c12009-10-30 11:49:00 +00002486typedef void (*GCCallback)();
2487
2488
Steve Blocka7e24c12009-10-30 11:49:00 +00002489/**
2490 * Profiler modules.
2491 *
2492 * In V8, profiler consists of several modules: CPU profiler, and different
2493 * kinds of heap profiling. Each can be turned on / off independently.
2494 * When PROFILER_MODULE_HEAP_SNAPSHOT flag is passed to ResumeProfilerEx,
2495 * modules are enabled only temporarily for making a snapshot of the heap.
2496 */
2497enum ProfilerModules {
2498 PROFILER_MODULE_NONE = 0,
2499 PROFILER_MODULE_CPU = 1,
2500 PROFILER_MODULE_HEAP_STATS = 1 << 1,
2501 PROFILER_MODULE_JS_CONSTRUCTORS = 1 << 2,
2502 PROFILER_MODULE_HEAP_SNAPSHOT = 1 << 16
2503};
2504
2505
2506/**
Steve Block3ce2e202009-11-05 08:53:23 +00002507 * Collection of V8 heap information.
2508 *
2509 * Instances of this class can be passed to v8::V8::HeapStatistics to
2510 * get heap statistics from V8.
2511 */
2512class V8EXPORT HeapStatistics {
2513 public:
2514 HeapStatistics();
2515 size_t total_heap_size() { return total_heap_size_; }
Russell Brenner90bac252010-11-18 13:33:46 -08002516 size_t total_heap_size_executable() { return total_heap_size_executable_; }
Steve Block3ce2e202009-11-05 08:53:23 +00002517 size_t used_heap_size() { return used_heap_size_; }
2518
2519 private:
2520 void set_total_heap_size(size_t size) { total_heap_size_ = size; }
Russell Brenner90bac252010-11-18 13:33:46 -08002521 void set_total_heap_size_executable(size_t size) {
2522 total_heap_size_executable_ = size;
2523 }
Steve Block3ce2e202009-11-05 08:53:23 +00002524 void set_used_heap_size(size_t size) { used_heap_size_ = size; }
2525
2526 size_t total_heap_size_;
Russell Brenner90bac252010-11-18 13:33:46 -08002527 size_t total_heap_size_executable_;
Steve Block3ce2e202009-11-05 08:53:23 +00002528 size_t used_heap_size_;
2529
2530 friend class V8;
2531};
2532
2533
2534/**
Steve Blocka7e24c12009-10-30 11:49:00 +00002535 * Container class for static utility functions.
2536 */
2537class V8EXPORT V8 {
2538 public:
2539 /** Set the callback to invoke in case of fatal errors. */
2540 static void SetFatalErrorHandler(FatalErrorCallback that);
2541
2542 /**
2543 * Ignore out-of-memory exceptions.
2544 *
2545 * V8 running out of memory is treated as a fatal error by default.
2546 * This means that the fatal error handler is called and that V8 is
2547 * terminated.
2548 *
2549 * IgnoreOutOfMemoryException can be used to not treat a
2550 * out-of-memory situation as a fatal error. This way, the contexts
2551 * that did not cause the out of memory problem might be able to
2552 * continue execution.
2553 */
2554 static void IgnoreOutOfMemoryException();
2555
2556 /**
2557 * Check if V8 is dead and therefore unusable. This is the case after
2558 * fatal errors such as out-of-memory situations.
2559 */
2560 static bool IsDead();
2561
2562 /**
2563 * Adds a message listener.
2564 *
2565 * The same message listener can be added more than once and it that
2566 * case it will be called more than once for each message.
2567 */
2568 static bool AddMessageListener(MessageCallback that,
2569 Handle<Value> data = Handle<Value>());
2570
2571 /**
2572 * Remove all message listeners from the specified callback function.
2573 */
2574 static void RemoveMessageListeners(MessageCallback that);
2575
2576 /**
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002577 * Tells V8 to capture current stack trace when uncaught exception occurs
2578 * and report it to the message listeners. The option is off by default.
2579 */
2580 static void SetCaptureStackTraceForUncaughtExceptions(
2581 bool capture,
2582 int frame_limit = 10,
2583 StackTrace::StackTraceOptions options = StackTrace::kOverview);
2584
2585 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002586 * Sets V8 flags from a string.
2587 */
2588 static void SetFlagsFromString(const char* str, int length);
2589
2590 /**
2591 * Sets V8 flags from the command line.
2592 */
2593 static void SetFlagsFromCommandLine(int* argc,
2594 char** argv,
2595 bool remove_flags);
2596
2597 /** Get the version string. */
2598 static const char* GetVersion();
2599
2600 /**
2601 * Enables the host application to provide a mechanism for recording
2602 * statistics counters.
2603 */
2604 static void SetCounterFunction(CounterLookupCallback);
2605
2606 /**
2607 * Enables the host application to provide a mechanism for recording
2608 * histograms. The CreateHistogram function returns a
2609 * histogram which will later be passed to the AddHistogramSample
2610 * function.
2611 */
2612 static void SetCreateHistogramFunction(CreateHistogramCallback);
2613 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
2614
2615 /**
2616 * Enables the computation of a sliding window of states. The sliding
2617 * window information is recorded in statistics counters.
2618 */
2619 static void EnableSlidingStateWindow();
2620
2621 /** Callback function for reporting failed access checks.*/
2622 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
2623
2624 /**
2625 * Enables the host application to receive a notification before a
Steve Block6ded16b2010-05-10 14:33:55 +01002626 * garbage collection. Allocations are not allowed in the
2627 * callback function, you therefore cannot manipulate objects (set
2628 * or delete properties for example) since it is possible such
2629 * operations will result in the allocation of objects. It is possible
2630 * to specify the GCType filter for your callback. But it is not possible to
2631 * register the same callback function two times with different
2632 * GCType filters.
2633 */
2634 static void AddGCPrologueCallback(
2635 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
2636
2637 /**
2638 * This function removes callback which was installed by
2639 * AddGCPrologueCallback function.
2640 */
2641 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
2642
2643 /**
2644 * The function is deprecated. Please use AddGCPrologueCallback instead.
2645 * Enables the host application to receive a notification before a
2646 * garbage collection. Allocations are not allowed in the
Steve Blocka7e24c12009-10-30 11:49:00 +00002647 * callback function, you therefore cannot manipulate objects (set
2648 * or delete properties for example) since it is possible such
2649 * operations will result in the allocation of objects.
2650 */
2651 static void SetGlobalGCPrologueCallback(GCCallback);
2652
2653 /**
2654 * Enables the host application to receive a notification after a
Steve Block6ded16b2010-05-10 14:33:55 +01002655 * garbage collection. Allocations are not allowed in the
2656 * callback function, you therefore cannot manipulate objects (set
2657 * or delete properties for example) since it is possible such
2658 * operations will result in the allocation of objects. It is possible
2659 * to specify the GCType filter for your callback. But it is not possible to
2660 * register the same callback function two times with different
2661 * GCType filters.
2662 */
2663 static void AddGCEpilogueCallback(
2664 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
2665
2666 /**
2667 * This function removes callback which was installed by
2668 * AddGCEpilogueCallback function.
2669 */
2670 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
2671
2672 /**
2673 * The function is deprecated. Please use AddGCEpilogueCallback instead.
2674 * Enables the host application to receive a notification after a
Steve Blocka7e24c12009-10-30 11:49:00 +00002675 * major garbage collection. Allocations are not allowed in the
2676 * callback function, you therefore cannot manipulate objects (set
2677 * or delete properties for example) since it is possible such
2678 * operations will result in the allocation of objects.
2679 */
2680 static void SetGlobalGCEpilogueCallback(GCCallback);
2681
2682 /**
Iain Merrick9ac36c92010-09-13 15:29:50 +01002683 * Enables the host application to provide a mechanism to be notified
2684 * and perform custom logging when V8 Allocates Executable Memory.
2685 */
2686 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
2687 ObjectSpace space,
2688 AllocationAction action);
2689
2690 /**
2691 * This function removes callback which was installed by
2692 * AddMemoryAllocationCallback function.
2693 */
2694 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
2695
2696 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002697 * Allows the host application to group objects together. If one
2698 * object in the group is alive, all objects in the group are alive.
2699 * After each garbage collection, object groups are removed. It is
2700 * intended to be used in the before-garbage-collection callback
2701 * function, for instance to simulate DOM tree connections among JS
2702 * wrapper objects.
2703 */
2704 static void AddObjectGroup(Persistent<Value>* objects, size_t length);
2705
2706 /**
2707 * Initializes from snapshot if possible. Otherwise, attempts to
2708 * initialize from scratch. This function is called implicitly if
2709 * you use the API without calling it first.
2710 */
2711 static bool Initialize();
2712
2713 /**
2714 * Adjusts the amount of registered external memory. Used to give
2715 * V8 an indication of the amount of externally allocated memory
2716 * that is kept alive by JavaScript objects. V8 uses this to decide
2717 * when to perform global garbage collections. Registering
2718 * externally allocated memory will trigger global garbage
2719 * collections more often than otherwise in an attempt to garbage
2720 * collect the JavaScript objects keeping the externally allocated
2721 * memory alive.
2722 *
2723 * \param change_in_bytes the change in externally allocated memory
2724 * that is kept alive by JavaScript objects.
2725 * \returns the adjusted value.
2726 */
2727 static int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
2728
2729 /**
2730 * Suspends recording of tick samples in the profiler.
2731 * When the V8 profiling mode is enabled (usually via command line
2732 * switches) this function suspends recording of tick samples.
2733 * Profiling ticks are discarded until ResumeProfiler() is called.
2734 *
2735 * See also the --prof and --prof_auto command line switches to
2736 * enable V8 profiling.
2737 */
2738 static void PauseProfiler();
2739
2740 /**
2741 * Resumes recording of tick samples in the profiler.
2742 * See also PauseProfiler().
2743 */
2744 static void ResumeProfiler();
2745
2746 /**
2747 * Return whether profiler is currently paused.
2748 */
2749 static bool IsProfilerPaused();
2750
2751 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002752 * Resumes specified profiler modules. Can be called several times to
2753 * mark the opening of a profiler events block with the given tag.
2754 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002755 * "ResumeProfiler" is equivalent to "ResumeProfilerEx(PROFILER_MODULE_CPU)".
2756 * See ProfilerModules enum.
2757 *
2758 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002759 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002760 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002761 static void ResumeProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002762
2763 /**
Andrei Popescu402d9372010-02-26 13:31:12 +00002764 * Pauses specified profiler modules. Each call to "PauseProfilerEx" closes
2765 * a block of profiler events opened by a call to "ResumeProfilerEx" with the
2766 * same tag value. There is no need for blocks to be properly nested.
2767 * The profiler is paused when the last opened block is closed.
2768 *
Steve Blocka7e24c12009-10-30 11:49:00 +00002769 * "PauseProfiler" is equivalent to "PauseProfilerEx(PROFILER_MODULE_CPU)".
2770 * See ProfilerModules enum.
2771 *
2772 * \param flags Flags specifying profiler modules.
Andrei Popescu402d9372010-02-26 13:31:12 +00002773 * \param tag Profile tag.
Steve Blocka7e24c12009-10-30 11:49:00 +00002774 */
Andrei Popescu402d9372010-02-26 13:31:12 +00002775 static void PauseProfilerEx(int flags, int tag = 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002776
2777 /**
2778 * Returns active (resumed) profiler modules.
2779 * See ProfilerModules enum.
2780 *
2781 * \returns active profiler modules.
2782 */
2783 static int GetActiveProfilerModules();
2784
2785 /**
2786 * If logging is performed into a memory buffer (via --logfile=*), allows to
2787 * retrieve previously written messages. This can be used for retrieving
2788 * profiler log data in the application. This function is thread-safe.
2789 *
2790 * Caller provides a destination buffer that must exist during GetLogLines
2791 * call. Only whole log lines are copied into the buffer.
2792 *
2793 * \param from_pos specified a point in a buffer to read from, 0 is the
2794 * beginning of a buffer. It is assumed that caller updates its current
2795 * position using returned size value from the previous call.
2796 * \param dest_buf destination buffer for log data.
2797 * \param max_size size of the destination buffer.
2798 * \returns actual size of log data copied into buffer.
2799 */
2800 static int GetLogLines(int from_pos, char* dest_buf, int max_size);
2801
2802 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002803 * The minimum allowed size for a log lines buffer. If the size of
2804 * the buffer given will not be enough to hold a line of the maximum
2805 * length, an attempt to find a log line end in GetLogLines will
2806 * fail, and an empty result will be returned.
2807 */
2808 static const int kMinimumSizeForLogLinesBuffer = 2048;
2809
2810 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002811 * Retrieve the V8 thread id of the calling thread.
2812 *
2813 * The thread id for a thread should only be retrieved after the V8
2814 * lock has been acquired with a Locker object with that thread.
2815 */
2816 static int GetCurrentThreadId();
2817
2818 /**
2819 * Forcefully terminate execution of a JavaScript thread. This can
2820 * be used to terminate long-running scripts.
2821 *
2822 * TerminateExecution should only be called when then V8 lock has
2823 * been acquired with a Locker object. Therefore, in order to be
2824 * able to terminate long-running threads, preemption must be
2825 * enabled to allow the user of TerminateExecution to acquire the
2826 * lock.
2827 *
2828 * The termination is achieved by throwing an exception that is
2829 * uncatchable by JavaScript exception handlers. Termination
2830 * exceptions act as if they were caught by a C++ TryCatch exception
2831 * handlers. If forceful termination is used, any C++ TryCatch
2832 * exception handler that catches an exception should check if that
2833 * exception is a termination exception and immediately return if
2834 * that is the case. Returning immediately in that case will
2835 * continue the propagation of the termination exception if needed.
2836 *
2837 * The thread id passed to TerminateExecution must have been
2838 * obtained by calling GetCurrentThreadId on the thread in question.
2839 *
2840 * \param thread_id The thread id of the thread to terminate.
2841 */
2842 static void TerminateExecution(int thread_id);
2843
2844 /**
2845 * Forcefully terminate the current thread of JavaScript execution.
2846 *
2847 * This method can be used by any thread even if that thread has not
2848 * acquired the V8 lock with a Locker object.
2849 */
2850 static void TerminateExecution();
2851
2852 /**
Steve Block6ded16b2010-05-10 14:33:55 +01002853 * Is V8 terminating JavaScript execution.
2854 *
2855 * Returns true if JavaScript execution is currently terminating
2856 * because of a call to TerminateExecution. In that case there are
2857 * still JavaScript frames on the stack and the termination
2858 * exception is still active.
2859 */
2860 static bool IsExecutionTerminating();
2861
2862 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002863 * Releases any resources used by v8 and stops any utility threads
2864 * that may be running. Note that disposing v8 is permanent, it
2865 * cannot be reinitialized.
2866 *
2867 * It should generally not be necessary to dispose v8 before exiting
2868 * a process, this should happen automatically. It is only necessary
2869 * to use if the process needs the resources taken up by v8.
2870 */
2871 static bool Dispose();
2872
Steve Block3ce2e202009-11-05 08:53:23 +00002873 /**
2874 * Get statistics about the heap memory usage.
2875 */
2876 static void GetHeapStatistics(HeapStatistics* heap_statistics);
Steve Blocka7e24c12009-10-30 11:49:00 +00002877
2878 /**
2879 * Optional notification that the embedder is idle.
2880 * V8 uses the notification to reduce memory footprint.
2881 * This call can be used repeatedly if the embedder remains idle.
Steve Blocka7e24c12009-10-30 11:49:00 +00002882 * Returns true if the embedder should stop calling IdleNotification
2883 * until real work has been done. This indicates that V8 has done
2884 * as much cleanup as it will be able to do.
2885 */
Steve Block3ce2e202009-11-05 08:53:23 +00002886 static bool IdleNotification();
Steve Blocka7e24c12009-10-30 11:49:00 +00002887
2888 /**
2889 * Optional notification that the system is running low on memory.
2890 * V8 uses these notifications to attempt to free memory.
2891 */
2892 static void LowMemoryNotification();
2893
Steve Block6ded16b2010-05-10 14:33:55 +01002894 /**
2895 * Optional notification that a context has been disposed. V8 uses
2896 * these notifications to guide the GC heuristic. Returns the number
2897 * of context disposals - including this one - since the last time
2898 * V8 had a chance to clean up.
2899 */
2900 static int ContextDisposedNotification();
2901
Steve Blocka7e24c12009-10-30 11:49:00 +00002902 private:
2903 V8();
2904
2905 static internal::Object** GlobalizeReference(internal::Object** handle);
2906 static void DisposeGlobal(internal::Object** global_handle);
2907 static void MakeWeak(internal::Object** global_handle,
2908 void* data,
2909 WeakReferenceCallback);
2910 static void ClearWeak(internal::Object** global_handle);
2911 static bool IsGlobalNearDeath(internal::Object** global_handle);
2912 static bool IsGlobalWeak(internal::Object** global_handle);
2913
2914 template <class T> friend class Handle;
2915 template <class T> friend class Local;
2916 template <class T> friend class Persistent;
2917 friend class Context;
2918};
2919
2920
2921/**
2922 * An external exception handler.
2923 */
2924class V8EXPORT TryCatch {
2925 public:
2926
2927 /**
2928 * Creates a new try/catch block and registers it with v8.
2929 */
2930 TryCatch();
2931
2932 /**
2933 * Unregisters and deletes this try/catch block.
2934 */
2935 ~TryCatch();
2936
2937 /**
2938 * Returns true if an exception has been caught by this try/catch block.
2939 */
2940 bool HasCaught() const;
2941
2942 /**
2943 * For certain types of exceptions, it makes no sense to continue
2944 * execution.
2945 *
2946 * Currently, the only type of exception that can be caught by a
2947 * TryCatch handler and for which it does not make sense to continue
2948 * is termination exception. Such exceptions are thrown when the
2949 * TerminateExecution methods are called to terminate a long-running
2950 * script.
2951 *
2952 * If CanContinue returns false, the correct action is to perform
2953 * any C++ cleanup needed and then return.
2954 */
2955 bool CanContinue() const;
2956
2957 /**
Steve Blockd0582a62009-12-15 09:54:21 +00002958 * Throws the exception caught by this TryCatch in a way that avoids
2959 * it being caught again by this same TryCatch. As with ThrowException
2960 * it is illegal to execute any JavaScript operations after calling
2961 * ReThrow; the caller must return immediately to where the exception
2962 * is caught.
2963 */
2964 Handle<Value> ReThrow();
2965
2966 /**
Steve Blocka7e24c12009-10-30 11:49:00 +00002967 * Returns the exception caught by this try/catch block. If no exception has
2968 * been caught an empty handle is returned.
2969 *
2970 * The returned handle is valid until this TryCatch block has been destroyed.
2971 */
2972 Local<Value> Exception() const;
2973
2974 /**
2975 * Returns the .stack property of the thrown object. If no .stack
2976 * property is present an empty handle is returned.
2977 */
2978 Local<Value> StackTrace() const;
2979
2980 /**
2981 * Returns the message associated with this exception. If there is
2982 * no message associated an empty handle is returned.
2983 *
2984 * The returned handle is valid until this TryCatch block has been
2985 * destroyed.
2986 */
2987 Local<v8::Message> Message() const;
2988
2989 /**
2990 * Clears any exceptions that may have been caught by this try/catch block.
2991 * After this method has been called, HasCaught() will return false.
2992 *
2993 * It is not necessary to clear a try/catch block before using it again; if
2994 * another exception is thrown the previously caught exception will just be
2995 * overwritten. However, it is often a good idea since it makes it easier
2996 * to determine which operation threw a given exception.
2997 */
2998 void Reset();
2999
3000 /**
3001 * Set verbosity of the external exception handler.
3002 *
3003 * By default, exceptions that are caught by an external exception
3004 * handler are not reported. Call SetVerbose with true on an
3005 * external exception handler to have exceptions caught by the
3006 * handler reported as if they were not caught.
3007 */
3008 void SetVerbose(bool value);
3009
3010 /**
3011 * Set whether or not this TryCatch should capture a Message object
3012 * which holds source information about where the exception
3013 * occurred. True by default.
3014 */
3015 void SetCaptureMessage(bool value);
3016
Steve Blockd0582a62009-12-15 09:54:21 +00003017 private:
3018 void* next_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003019 void* exception_;
3020 void* message_;
Steve Blockd0582a62009-12-15 09:54:21 +00003021 bool is_verbose_ : 1;
3022 bool can_continue_ : 1;
3023 bool capture_message_ : 1;
3024 bool rethrow_ : 1;
3025
3026 friend class v8::internal::Top;
Steve Blocka7e24c12009-10-30 11:49:00 +00003027};
3028
3029
3030// --- C o n t e x t ---
3031
3032
3033/**
3034 * Ignore
3035 */
3036class V8EXPORT ExtensionConfiguration {
3037 public:
3038 ExtensionConfiguration(int name_count, const char* names[])
3039 : name_count_(name_count), names_(names) { }
3040 private:
3041 friend class ImplementationUtilities;
3042 int name_count_;
3043 const char** names_;
3044};
3045
3046
3047/**
3048 * A sandboxed execution context with its own set of built-in objects
3049 * and functions.
3050 */
3051class V8EXPORT Context {
3052 public:
3053 /** Returns the global object of the context. */
3054 Local<Object> Global();
3055
3056 /**
3057 * Detaches the global object from its context before
3058 * the global object can be reused to create a new context.
3059 */
3060 void DetachGlobal();
3061
Andrei Popescu74b3c142010-03-29 12:03:09 +01003062 /**
3063 * Reattaches a global object to a context. This can be used to
3064 * restore the connection between a global object and a context
3065 * after DetachGlobal has been called.
3066 *
3067 * \param global_object The global object to reattach to the
3068 * context. For this to work, the global object must be the global
3069 * object that was associated with this context before a call to
3070 * DetachGlobal.
3071 */
3072 void ReattachGlobal(Handle<Object> global_object);
3073
Leon Clarkef7060e22010-06-03 12:02:55 +01003074 /** Creates a new context.
3075 *
3076 * Returns a persistent handle to the newly allocated context. This
3077 * persistent handle has to be disposed when the context is no
3078 * longer used so the context can be garbage collected.
3079 */
Steve Blocka7e24c12009-10-30 11:49:00 +00003080 static Persistent<Context> New(
Andrei Popescu31002712010-02-23 13:46:05 +00003081 ExtensionConfiguration* extensions = NULL,
Steve Blocka7e24c12009-10-30 11:49:00 +00003082 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
3083 Handle<Value> global_object = Handle<Value>());
3084
3085 /** Returns the last entered context. */
3086 static Local<Context> GetEntered();
3087
3088 /** Returns the context that is on the top of the stack. */
3089 static Local<Context> GetCurrent();
3090
3091 /**
3092 * Returns the context of the calling JavaScript code. That is the
3093 * context of the top-most JavaScript frame. If there are no
3094 * JavaScript frames an empty handle is returned.
3095 */
3096 static Local<Context> GetCalling();
3097
3098 /**
3099 * Sets the security token for the context. To access an object in
3100 * another context, the security tokens must match.
3101 */
3102 void SetSecurityToken(Handle<Value> token);
3103
3104 /** Restores the security token to the default value. */
3105 void UseDefaultSecurityToken();
3106
3107 /** Returns the security token of this context.*/
3108 Handle<Value> GetSecurityToken();
3109
3110 /**
3111 * Enter this context. After entering a context, all code compiled
3112 * and run is compiled and run in this context. If another context
3113 * is already entered, this old context is saved so it can be
3114 * restored when the new context is exited.
3115 */
3116 void Enter();
3117
3118 /**
3119 * Exit this context. Exiting the current context restores the
3120 * context that was in place when entering the current context.
3121 */
3122 void Exit();
3123
3124 /** Returns true if the context has experienced an out of memory situation. */
3125 bool HasOutOfMemoryException();
3126
3127 /** Returns true if V8 has a current context. */
3128 static bool InContext();
3129
3130 /**
3131 * Associate an additional data object with the context. This is mainly used
3132 * with the debugger to provide additional information on the context through
3133 * the debugger API.
3134 */
Steve Blockd0582a62009-12-15 09:54:21 +00003135 void SetData(Handle<String> data);
Steve Blocka7e24c12009-10-30 11:49:00 +00003136 Local<Value> GetData();
3137
3138 /**
3139 * Stack-allocated class which sets the execution context for all
3140 * operations executed within a local scope.
3141 */
Steve Block8defd9f2010-07-08 12:39:36 +01003142 class Scope {
Steve Blocka7e24c12009-10-30 11:49:00 +00003143 public:
3144 inline Scope(Handle<Context> context) : context_(context) {
3145 context_->Enter();
3146 }
3147 inline ~Scope() { context_->Exit(); }
3148 private:
3149 Handle<Context> context_;
3150 };
3151
3152 private:
3153 friend class Value;
3154 friend class Script;
3155 friend class Object;
3156 friend class Function;
3157};
3158
3159
3160/**
3161 * Multiple threads in V8 are allowed, but only one thread at a time
3162 * is allowed to use V8. The definition of 'using V8' includes
3163 * accessing handles or holding onto object pointers obtained from V8
3164 * handles. It is up to the user of V8 to ensure (perhaps with
3165 * locking) that this constraint is not violated.
3166 *
3167 * If you wish to start using V8 in a thread you can do this by constructing
3168 * a v8::Locker object. After the code using V8 has completed for the
3169 * current thread you can call the destructor. This can be combined
3170 * with C++ scope-based construction as follows:
3171 *
3172 * \code
3173 * ...
3174 * {
3175 * v8::Locker locker;
3176 * ...
3177 * // Code using V8 goes here.
3178 * ...
3179 * } // Destructor called here
3180 * \endcode
3181 *
3182 * If you wish to stop using V8 in a thread A you can do this by either
3183 * by destroying the v8::Locker object as above or by constructing a
3184 * v8::Unlocker object:
3185 *
3186 * \code
3187 * {
3188 * v8::Unlocker unlocker;
3189 * ...
3190 * // Code not using V8 goes here while V8 can run in another thread.
3191 * ...
3192 * } // Destructor called here.
3193 * \endcode
3194 *
3195 * The Unlocker object is intended for use in a long-running callback
3196 * from V8, where you want to release the V8 lock for other threads to
3197 * use.
3198 *
3199 * The v8::Locker is a recursive lock. That is, you can lock more than
3200 * once in a given thread. This can be useful if you have code that can
3201 * be called either from code that holds the lock or from code that does
3202 * not. The Unlocker is not recursive so you can not have several
3203 * Unlockers on the stack at once, and you can not use an Unlocker in a
3204 * thread that is not inside a Locker's scope.
3205 *
3206 * An unlocker will unlock several lockers if it has to and reinstate
3207 * the correct depth of locking on its destruction. eg.:
3208 *
3209 * \code
3210 * // V8 not locked.
3211 * {
3212 * v8::Locker locker;
3213 * // V8 locked.
3214 * {
3215 * v8::Locker another_locker;
3216 * // V8 still locked (2 levels).
3217 * {
3218 * v8::Unlocker unlocker;
3219 * // V8 not locked.
3220 * }
3221 * // V8 locked again (2 levels).
3222 * }
3223 * // V8 still locked (1 level).
3224 * }
3225 * // V8 Now no longer locked.
3226 * \endcode
3227 */
3228class V8EXPORT Unlocker {
3229 public:
3230 Unlocker();
3231 ~Unlocker();
3232};
3233
3234
3235class V8EXPORT Locker {
3236 public:
3237 Locker();
3238 ~Locker();
3239
3240 /**
3241 * Start preemption.
3242 *
3243 * When preemption is started, a timer is fired every n milli seconds
3244 * that will switch between multiple threads that are in contention
3245 * for the V8 lock.
3246 */
3247 static void StartPreemption(int every_n_ms);
3248
3249 /**
3250 * Stop preemption.
3251 */
3252 static void StopPreemption();
3253
3254 /**
3255 * Returns whether or not the locker is locked by the current thread.
3256 */
3257 static bool IsLocked();
3258
3259 /**
3260 * Returns whether v8::Locker is being used by this V8 instance.
3261 */
3262 static bool IsActive() { return active_; }
3263
3264 private:
3265 bool has_lock_;
3266 bool top_level_;
3267
3268 static bool active_;
3269
3270 // Disallow copying and assigning.
3271 Locker(const Locker&);
3272 void operator=(const Locker&);
3273};
3274
3275
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003276/**
3277 * An interface for exporting data from V8, using "push" model.
3278 */
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003279class V8EXPORT OutputStream { // NOLINT
3280 public:
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003281 enum OutputEncoding {
3282 kAscii = 0 // 7-bit ASCII.
3283 };
3284 enum WriteResult {
3285 kContinue = 0,
3286 kAbort = 1
3287 };
3288 virtual ~OutputStream() {}
3289 /** Notify about the end of stream. */
3290 virtual void EndOfStream() = 0;
3291 /** Get preferred output chunk size. Called only once. */
3292 virtual int GetChunkSize() { return 1024; }
3293 /** Get preferred output encoding. Called only once. */
3294 virtual OutputEncoding GetOutputEncoding() { return kAscii; }
3295 /**
3296 * Writes the next chunk of snapshot data into the stream. Writing
3297 * can be stopped by returning kAbort as function result. EndOfStream
3298 * will not be called in case writing was aborted.
3299 */
3300 virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
3301};
3302
3303
Ben Murdochb0fe1622011-05-05 13:52:32 +01003304/**
3305 * An interface for reporting progress and controlling long-running
3306 * activities.
3307 */
3308class V8EXPORT ActivityControl { // NOLINT
3309 public:
3310 enum ControlOption {
3311 kContinue = 0,
3312 kAbort = 1
3313 };
3314 virtual ~ActivityControl() {}
3315 /**
3316 * Notify about current progress. The activity can be stopped by
3317 * returning kAbort as the callback result.
3318 */
3319 virtual ControlOption ReportProgressValue(int done, int total) = 0;
3320};
3321
Steve Blocka7e24c12009-10-30 11:49:00 +00003322
3323// --- I m p l e m e n t a t i o n ---
3324
3325
3326namespace internal {
3327
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003328static const int kApiPointerSize = sizeof(void*); // NOLINT
3329static const int kApiIntSize = sizeof(int); // NOLINT
Steve Blocka7e24c12009-10-30 11:49:00 +00003330
3331// Tag information for HeapObject.
3332const int kHeapObjectTag = 1;
3333const int kHeapObjectTagSize = 2;
3334const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
3335
Steve Blocka7e24c12009-10-30 11:49:00 +00003336// Tag information for Smi.
3337const int kSmiTag = 0;
3338const int kSmiTagSize = 1;
3339const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
3340
Ben Murdochb0fe1622011-05-05 13:52:32 +01003341template <size_t ptr_size> struct SmiConstants;
Steve Block3ce2e202009-11-05 08:53:23 +00003342
3343// Smi constants for 32-bit systems.
Ben Murdochb0fe1622011-05-05 13:52:32 +01003344template <> struct SmiConstants<4> {
Steve Block3ce2e202009-11-05 08:53:23 +00003345 static const int kSmiShiftSize = 0;
3346 static const int kSmiValueSize = 31;
3347 static inline int SmiToInt(internal::Object* value) {
3348 int shift_bits = kSmiTagSize + kSmiShiftSize;
3349 // Throw away top 32 bits and shift down (requires >> to be sign extending).
3350 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
3351 }
3352};
3353
3354// Smi constants for 64-bit systems.
Ben Murdochb0fe1622011-05-05 13:52:32 +01003355template <> struct SmiConstants<8> {
Steve Block3ce2e202009-11-05 08:53:23 +00003356 static const int kSmiShiftSize = 31;
3357 static const int kSmiValueSize = 32;
3358 static inline int SmiToInt(internal::Object* value) {
3359 int shift_bits = kSmiTagSize + kSmiShiftSize;
3360 // Shift down and throw away top 32 bits.
3361 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
3362 }
3363};
3364
Ben Murdochb0fe1622011-05-05 13:52:32 +01003365const int kSmiShiftSize = SmiConstants<kApiPointerSize>::kSmiShiftSize;
3366const int kSmiValueSize = SmiConstants<kApiPointerSize>::kSmiValueSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003367
Steve Blockd0582a62009-12-15 09:54:21 +00003368template <size_t ptr_size> struct InternalConstants;
3369
3370// Internal constants for 32-bit systems.
3371template <> struct InternalConstants<4> {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003372 static const int kStringResourceOffset = 3 * kApiPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003373};
3374
3375// Internal constants for 64-bit systems.
3376template <> struct InternalConstants<8> {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003377 static const int kStringResourceOffset = 3 * kApiPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003378};
3379
Steve Blocka7e24c12009-10-30 11:49:00 +00003380/**
3381 * This class exports constants and functionality from within v8 that
3382 * is necessary to implement inline functions in the v8 api. Don't
3383 * depend on functions and constants defined here.
3384 */
3385class Internals {
3386 public:
3387
3388 // These values match non-compiler-dependent values defined within
3389 // the implementation of v8.
3390 static const int kHeapObjectMapOffset = 0;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003391 static const int kMapInstanceTypeOffset = kApiPointerSize + kApiIntSize;
Steve Blockd0582a62009-12-15 09:54:21 +00003392 static const int kStringResourceOffset =
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003393 InternalConstants<kApiPointerSize>::kStringResourceOffset;
Steve Blockd0582a62009-12-15 09:54:21 +00003394
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003395 static const int kProxyProxyOffset = kApiPointerSize;
3396 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00003397 static const int kFullStringRepresentationMask = 0x07;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003398 static const int kExternalTwoByteRepresentationTag = 0x02;
Steve Blocka7e24c12009-10-30 11:49:00 +00003399
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003400 static const int kJSObjectType = 0x9f;
3401 static const int kFirstNonstringType = 0x80;
3402 static const int kProxyType = 0x85;
Steve Blocka7e24c12009-10-30 11:49:00 +00003403
3404 static inline bool HasHeapObjectTag(internal::Object* value) {
3405 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
3406 kHeapObjectTag);
3407 }
3408
3409 static inline bool HasSmiTag(internal::Object* value) {
3410 return ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag);
3411 }
3412
3413 static inline int SmiValue(internal::Object* value) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01003414 return SmiConstants<kApiPointerSize>::SmiToInt(value);
Steve Block3ce2e202009-11-05 08:53:23 +00003415 }
3416
3417 static inline int GetInstanceType(internal::Object* obj) {
3418 typedef internal::Object O;
3419 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
3420 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
3421 }
3422
3423 static inline void* GetExternalPointer(internal::Object* obj) {
3424 if (HasSmiTag(obj)) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01003425 return obj;
Steve Block3ce2e202009-11-05 08:53:23 +00003426 } else if (GetInstanceType(obj) == kProxyType) {
3427 return ReadField<void*>(obj, kProxyProxyOffset);
3428 } else {
3429 return NULL;
3430 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003431 }
3432
3433 static inline bool IsExternalTwoByteString(int instance_type) {
3434 int representation = (instance_type & kFullStringRepresentationMask);
3435 return representation == kExternalTwoByteRepresentationTag;
3436 }
3437
3438 template <typename T>
3439 static inline T ReadField(Object* ptr, int offset) {
3440 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
3441 return *reinterpret_cast<T*>(addr);
3442 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003443};
3444
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003445} // namespace internal
Steve Blocka7e24c12009-10-30 11:49:00 +00003446
3447
3448template <class T>
3449Handle<T>::Handle() : val_(0) { }
3450
3451
3452template <class T>
3453Local<T>::Local() : Handle<T>() { }
3454
3455
3456template <class T>
3457Local<T> Local<T>::New(Handle<T> that) {
3458 if (that.IsEmpty()) return Local<T>();
3459 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3460 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(*p)));
3461}
3462
3463
3464template <class T>
3465Persistent<T> Persistent<T>::New(Handle<T> that) {
3466 if (that.IsEmpty()) return Persistent<T>();
3467 internal::Object** p = reinterpret_cast<internal::Object**>(*that);
3468 return Persistent<T>(reinterpret_cast<T*>(V8::GlobalizeReference(p)));
3469}
3470
3471
3472template <class T>
3473bool Persistent<T>::IsNearDeath() const {
3474 if (this->IsEmpty()) return false;
3475 return V8::IsGlobalNearDeath(reinterpret_cast<internal::Object**>(**this));
3476}
3477
3478
3479template <class T>
3480bool Persistent<T>::IsWeak() const {
3481 if (this->IsEmpty()) return false;
3482 return V8::IsGlobalWeak(reinterpret_cast<internal::Object**>(**this));
3483}
3484
3485
3486template <class T>
3487void Persistent<T>::Dispose() {
3488 if (this->IsEmpty()) return;
3489 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(**this));
3490}
3491
3492
3493template <class T>
3494Persistent<T>::Persistent() : Handle<T>() { }
3495
3496template <class T>
3497void Persistent<T>::MakeWeak(void* parameters, WeakReferenceCallback callback) {
3498 V8::MakeWeak(reinterpret_cast<internal::Object**>(**this),
3499 parameters,
3500 callback);
3501}
3502
3503template <class T>
3504void Persistent<T>::ClearWeak() {
3505 V8::ClearWeak(reinterpret_cast<internal::Object**>(**this));
3506}
3507
Steve Block8defd9f2010-07-08 12:39:36 +01003508
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003509Arguments::Arguments(internal::Object** implicit_args,
3510 internal::Object** values, int length,
3511 bool is_construct_call)
3512 : implicit_args_(implicit_args),
3513 values_(values),
3514 length_(length),
3515 is_construct_call_(is_construct_call) { }
Steve Block8defd9f2010-07-08 12:39:36 +01003516
3517
Steve Blocka7e24c12009-10-30 11:49:00 +00003518Local<Value> Arguments::operator[](int i) const {
3519 if (i < 0 || length_ <= i) return Local<Value>(*Undefined());
3520 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
3521}
3522
3523
3524Local<Function> Arguments::Callee() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003525 return Local<Function>(reinterpret_cast<Function*>(
3526 &implicit_args_[kCalleeIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003527}
3528
3529
3530Local<Object> Arguments::This() const {
3531 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
3532}
3533
3534
3535Local<Object> Arguments::Holder() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003536 return Local<Object>(reinterpret_cast<Object*>(
3537 &implicit_args_[kHolderIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003538}
3539
3540
3541Local<Value> Arguments::Data() const {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08003542 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003543}
3544
3545
3546bool Arguments::IsConstructCall() const {
3547 return is_construct_call_;
3548}
3549
3550
3551int Arguments::Length() const {
3552 return length_;
3553}
3554
3555
3556template <class T>
3557Local<T> HandleScope::Close(Handle<T> value) {
3558 internal::Object** before = reinterpret_cast<internal::Object**>(*value);
3559 internal::Object** after = RawClose(before);
3560 return Local<T>(reinterpret_cast<T*>(after));
3561}
3562
3563Handle<Value> ScriptOrigin::ResourceName() const {
3564 return resource_name_;
3565}
3566
3567
3568Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
3569 return resource_line_offset_;
3570}
3571
3572
3573Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
3574 return resource_column_offset_;
3575}
3576
3577
3578Handle<Boolean> Boolean::New(bool value) {
3579 return value ? True() : False();
3580}
3581
3582
3583void Template::Set(const char* name, v8::Handle<Data> value) {
3584 Set(v8::String::New(name), value);
3585}
3586
3587
3588Local<Value> Object::GetInternalField(int index) {
3589#ifndef V8_ENABLE_CHECKS
3590 Local<Value> quick_result = UncheckedGetInternalField(index);
3591 if (!quick_result.IsEmpty()) return quick_result;
3592#endif
3593 return CheckedGetInternalField(index);
3594}
3595
3596
3597Local<Value> Object::UncheckedGetInternalField(int index) {
3598 typedef internal::Object O;
3599 typedef internal::Internals I;
3600 O* obj = *reinterpret_cast<O**>(this);
Steve Block3ce2e202009-11-05 08:53:23 +00003601 if (I::GetInstanceType(obj) == I::kJSObjectType) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003602 // If the object is a plain JSObject, which is the common case,
3603 // we know where to find the internal fields and can return the
3604 // value directly.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003605 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003606 O* value = I::ReadField<O*>(obj, offset);
3607 O** result = HandleScope::CreateHandle(value);
3608 return Local<Value>(reinterpret_cast<Value*>(result));
3609 } else {
3610 return Local<Value>();
3611 }
3612}
3613
3614
3615void* External::Unwrap(Handle<v8::Value> obj) {
3616#ifdef V8_ENABLE_CHECKS
3617 return FullUnwrap(obj);
3618#else
3619 return QuickUnwrap(obj);
3620#endif
3621}
3622
3623
3624void* External::QuickUnwrap(Handle<v8::Value> wrapper) {
3625 typedef internal::Object O;
Steve Blocka7e24c12009-10-30 11:49:00 +00003626 O* obj = *reinterpret_cast<O**>(const_cast<v8::Value*>(*wrapper));
Steve Block3ce2e202009-11-05 08:53:23 +00003627 return internal::Internals::GetExternalPointer(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00003628}
3629
3630
3631void* Object::GetPointerFromInternalField(int index) {
Steve Block3ce2e202009-11-05 08:53:23 +00003632 typedef internal::Object O;
3633 typedef internal::Internals I;
3634
3635 O* obj = *reinterpret_cast<O**>(this);
3636
3637 if (I::GetInstanceType(obj) == I::kJSObjectType) {
3638 // If the object is a plain JSObject, which is the common case,
3639 // we know where to find the internal fields and can return the
3640 // value directly.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003641 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
Steve Block3ce2e202009-11-05 08:53:23 +00003642 O* value = I::ReadField<O*>(obj, offset);
3643 return I::GetExternalPointer(value);
3644 }
3645
3646 return SlowGetPointerFromInternalField(index);
Steve Blocka7e24c12009-10-30 11:49:00 +00003647}
3648
3649
3650String* String::Cast(v8::Value* value) {
3651#ifdef V8_ENABLE_CHECKS
3652 CheckCast(value);
3653#endif
3654 return static_cast<String*>(value);
3655}
3656
3657
3658String::ExternalStringResource* String::GetExternalStringResource() const {
3659 typedef internal::Object O;
3660 typedef internal::Internals I;
3661 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
Steve Blocka7e24c12009-10-30 11:49:00 +00003662 String::ExternalStringResource* result;
Steve Block3ce2e202009-11-05 08:53:23 +00003663 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003664 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
3665 result = reinterpret_cast<String::ExternalStringResource*>(value);
3666 } else {
3667 result = NULL;
3668 }
3669#ifdef V8_ENABLE_CHECKS
3670 VerifyExternalStringResource(result);
3671#endif
3672 return result;
3673}
3674
3675
3676bool Value::IsString() const {
3677#ifdef V8_ENABLE_CHECKS
3678 return FullIsString();
3679#else
3680 return QuickIsString();
3681#endif
3682}
3683
3684bool Value::QuickIsString() const {
3685 typedef internal::Object O;
3686 typedef internal::Internals I;
3687 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
3688 if (!I::HasHeapObjectTag(obj)) return false;
Steve Block3ce2e202009-11-05 08:53:23 +00003689 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
Steve Blocka7e24c12009-10-30 11:49:00 +00003690}
3691
3692
3693Number* Number::Cast(v8::Value* value) {
3694#ifdef V8_ENABLE_CHECKS
3695 CheckCast(value);
3696#endif
3697 return static_cast<Number*>(value);
3698}
3699
3700
3701Integer* Integer::Cast(v8::Value* value) {
3702#ifdef V8_ENABLE_CHECKS
3703 CheckCast(value);
3704#endif
3705 return static_cast<Integer*>(value);
3706}
3707
3708
3709Date* Date::Cast(v8::Value* value) {
3710#ifdef V8_ENABLE_CHECKS
3711 CheckCast(value);
3712#endif
3713 return static_cast<Date*>(value);
3714}
3715
3716
Ben Murdochf87a2032010-10-22 12:50:53 +01003717RegExp* RegExp::Cast(v8::Value* value) {
3718#ifdef V8_ENABLE_CHECKS
3719 CheckCast(value);
3720#endif
3721 return static_cast<RegExp*>(value);
3722}
3723
3724
Steve Blocka7e24c12009-10-30 11:49:00 +00003725Object* Object::Cast(v8::Value* value) {
3726#ifdef V8_ENABLE_CHECKS
3727 CheckCast(value);
3728#endif
3729 return static_cast<Object*>(value);
3730}
3731
3732
3733Array* Array::Cast(v8::Value* value) {
3734#ifdef V8_ENABLE_CHECKS
3735 CheckCast(value);
3736#endif
3737 return static_cast<Array*>(value);
3738}
3739
3740
3741Function* Function::Cast(v8::Value* value) {
3742#ifdef V8_ENABLE_CHECKS
3743 CheckCast(value);
3744#endif
3745 return static_cast<Function*>(value);
3746}
3747
3748
3749External* External::Cast(v8::Value* value) {
3750#ifdef V8_ENABLE_CHECKS
3751 CheckCast(value);
3752#endif
3753 return static_cast<External*>(value);
3754}
3755
3756
3757Local<Value> AccessorInfo::Data() const {
Steve Block6ded16b2010-05-10 14:33:55 +01003758 return Local<Value>(reinterpret_cast<Value*>(&args_[-2]));
Steve Blocka7e24c12009-10-30 11:49:00 +00003759}
3760
3761
3762Local<Object> AccessorInfo::This() const {
3763 return Local<Object>(reinterpret_cast<Object*>(&args_[0]));
3764}
3765
3766
3767Local<Object> AccessorInfo::Holder() const {
3768 return Local<Object>(reinterpret_cast<Object*>(&args_[-1]));
3769}
3770
3771
3772/**
3773 * \example shell.cc
3774 * A simple shell that takes a list of expressions on the
3775 * command-line and executes them.
3776 */
3777
3778
3779/**
3780 * \example process.cc
3781 */
3782
3783
3784} // namespace v8
3785
3786
3787#undef V8EXPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00003788#undef TYPE_CHECK
3789
3790
3791#endif // V8_H_