The data contained in this repository can be downloaded to your computer using one of several clients.
Please see the documentation of your version control software client for more information.

Please select the desired protocol below to get the URL.

This URL has Read-Only access.

Statistics
| Branch: | Revision:

main_repo / deps / v8 / include / v8.h @ f230a1cf

History | View | Annotate | Download (197 KB)

1
// Copyright 2012 the V8 project authors. All rights reserved.
2
// Redistribution and use in source and binary forms, with or without
3
// modification, are permitted provided that the following conditions are
4
// met:
5
//
6
//     * Redistributions of source code must retain the above copyright
7
//       notice, this list of conditions and the following disclaimer.
8
//     * Redistributions in binary form must reproduce the above
9
//       copyright notice, this list of conditions and the following
10
//       disclaimer in the documentation and/or other materials provided
11
//       with the distribution.
12
//     * Neither the name of Google Inc. nor the names of its
13
//       contributors may be used to endorse or promote products derived
14
//       from this software without specific prior written permission.
15
//
16
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27

    
28
/** \mainpage V8 API Reference Guide
29
 *
30
 * V8 is Google's open source JavaScript engine.
31
 *
32
 * This set of documents provides reference material generated from the
33
 * V8 header file, include/v8.h.
34
 *
35
 * For other documentation see http://code.google.com/apis/v8/
36
 */
37

    
38
#ifndef V8_H_
39
#define V8_H_
40

    
41
#include "v8stdint.h"
42

    
43
// We reserve the V8_* prefix for macros defined in V8 public API and
44
// assume there are no name conflicts with the embedder's code.
45

    
46
#ifdef V8_OS_WIN
47

    
48
// Setup for Windows DLL export/import. When building the V8 DLL the
49
// BUILDING_V8_SHARED needs to be defined. When building a program which uses
50
// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
51
// static library or building a program which uses the V8 static library neither
52
// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
53
#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
54
#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
55
  build configuration to ensure that at most one of these is set
56
#endif
57

    
58
#ifdef BUILDING_V8_SHARED
59
# define V8_EXPORT __declspec(dllexport)
60
#elif USING_V8_SHARED
61
# define V8_EXPORT __declspec(dllimport)
62
#else
63
# define V8_EXPORT
64
#endif  // BUILDING_V8_SHARED
65

    
66
#else  // V8_OS_WIN
67

    
68
// Setup for Linux shared library export.
69
#if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
70
# ifdef BUILDING_V8_SHARED
71
#  define V8_EXPORT __attribute__ ((visibility("default")))
72
# else
73
#  define V8_EXPORT
74
# endif
75
#else
76
# define V8_EXPORT
77
#endif
78

    
79
#endif  // V8_OS_WIN
80

    
81
/**
82
 * The v8 JavaScript engine.
83
 */
84
namespace v8 {
85

    
86
class AccessorSignature;
87
class Array;
88
class Boolean;
89
class BooleanObject;
90
class Context;
91
class CpuProfiler;
92
class Data;
93
class Date;
94
class DeclaredAccessorDescriptor;
95
class External;
96
class Function;
97
class FunctionTemplate;
98
class HeapProfiler;
99
class ImplementationUtilities;
100
class Int32;
101
class Integer;
102
class Isolate;
103
class Number;
104
class NumberObject;
105
class Object;
106
class ObjectOperationDescriptor;
107
class ObjectTemplate;
108
class Primitive;
109
class RawOperationDescriptor;
110
class Signature;
111
class StackFrame;
112
class StackTrace;
113
class String;
114
class StringObject;
115
class Symbol;
116
class SymbolObject;
117
class Uint32;
118
class Utils;
119
class Value;
120
template <class T> class Handle;
121
template <class T> class Local;
122
template <class T> class Eternal;
123
template<class T> class NonCopyablePersistentTraits;
124
template<class T,
125
         class M = NonCopyablePersistentTraits<T> > class Persistent;
126
template<class T, class P> class WeakCallbackObject;
127
class FunctionTemplate;
128
class ObjectTemplate;
129
class Data;
130
template<typename T> class PropertyCallbackInfo;
131
class StackTrace;
132
class StackFrame;
133
class Isolate;
134
class DeclaredAccessorDescriptor;
135
class ObjectOperationDescriptor;
136
class RawOperationDescriptor;
137
class CallHandlerHelper;
138
class EscapableHandleScope;
139

    
140
namespace internal {
141
class Arguments;
142
class Heap;
143
class HeapObject;
144
class Isolate;
145
class Object;
146
template<typename T> class CustomArguments;
147
class PropertyCallbackArguments;
148
class FunctionCallbackArguments;
149
class GlobalHandles;
150
}
151

    
152

    
153
/**
154
 * General purpose unique identifier.
155
 */
156
class UniqueId {
157
 public:
158
  explicit UniqueId(intptr_t data)
159
      : data_(data) {}
160

    
161
  bool operator==(const UniqueId& other) const {
162
    return data_ == other.data_;
163
  }
164

    
165
  bool operator!=(const UniqueId& other) const {
166
    return data_ != other.data_;
167
  }
168

    
169
  bool operator<(const UniqueId& other) const {
170
    return data_ < other.data_;
171
  }
172

    
173
 private:
174
  intptr_t data_;
175
};
176

    
177
// --- Handles ---
178

    
179
#define TYPE_CHECK(T, S)                                       \
180
  while (false) {                                              \
181
    *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);      \
182
  }
183

    
184

    
185
/**
186
 * An object reference managed by the v8 garbage collector.
187
 *
188
 * All objects returned from v8 have to be tracked by the garbage
189
 * collector so that it knows that the objects are still alive.  Also,
190
 * because the garbage collector may move objects, it is unsafe to
191
 * point directly to an object.  Instead, all objects are stored in
192
 * handles which are known by the garbage collector and updated
193
 * whenever an object moves.  Handles should always be passed by value
194
 * (except in cases like out-parameters) and they should never be
195
 * allocated on the heap.
196
 *
197
 * There are two types of handles: local and persistent handles.
198
 * Local handles are light-weight and transient and typically used in
199
 * local operations.  They are managed by HandleScopes.  Persistent
200
 * handles can be used when storing objects across several independent
201
 * operations and have to be explicitly deallocated when they're no
202
 * longer used.
203
 *
204
 * It is safe to extract the object stored in the handle by
205
 * dereferencing the handle (for instance, to extract the Object* from
206
 * a Handle<Object>); the value will still be governed by a handle
207
 * behind the scenes and the same rules apply to these values as to
208
 * their handles.
209
 */
210
template <class T> class Handle {
211
 public:
212
  /**
213
   * Creates an empty handle.
214
   */
215
  V8_INLINE Handle() : val_(0) {}
216

    
217
  /**
218
   * Creates a handle for the contents of the specified handle.  This
219
   * constructor allows you to pass handles as arguments by value and
220
   * to assign between handles.  However, if you try to assign between
221
   * incompatible handles, for instance from a Handle<String> to a
222
   * Handle<Number> it will cause a compile-time error.  Assigning
223
   * between compatible handles, for instance assigning a
224
   * Handle<String> to a variable declared as Handle<Value>, is legal
225
   * because String is a subclass of Value.
226
   */
227
  template <class S> V8_INLINE Handle(Handle<S> that)
228
      : val_(reinterpret_cast<T*>(*that)) {
229
    /**
230
     * This check fails when trying to convert between incompatible
231
     * handles. For example, converting from a Handle<String> to a
232
     * Handle<Number>.
233
     */
234
    TYPE_CHECK(T, S);
235
  }
236

    
237
  /**
238
   * Returns true if the handle is empty.
239
   */
240
  V8_INLINE bool IsEmpty() const { return val_ == 0; }
241

    
242
  /**
243
   * Sets the handle to be empty. IsEmpty() will then return true.
244
   */
245
  V8_INLINE void Clear() { val_ = 0; }
246

    
247
  V8_INLINE T* operator->() const { return val_; }
248

    
249
  V8_INLINE T* operator*() const { return val_; }
250

    
251
  /**
252
   * Checks whether two handles are the same.
253
   * Returns true if both are empty, or if the objects
254
   * to which they refer are identical.
255
   * The handles' references are not checked.
256
   */
257
  template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
258
    internal::Object** a = reinterpret_cast<internal::Object**>(**this);
259
    internal::Object** b = reinterpret_cast<internal::Object**>(*that);
260
    if (a == 0) return b == 0;
261
    if (b == 0) return false;
262
    return *a == *b;
263
  }
264

    
265
  template <class S> V8_INLINE bool operator==(
266
      const Persistent<S>& that) const {
267
    internal::Object** a = reinterpret_cast<internal::Object**>(**this);
268
    internal::Object** b = reinterpret_cast<internal::Object**>(*that);
269
    if (a == 0) return b == 0;
270
    if (b == 0) return false;
271
    return *a == *b;
272
  }
273

    
274
  /**
275
   * Checks whether two handles are different.
276
   * Returns true if only one of the handles is empty, or if
277
   * the objects to which they refer are different.
278
   * The handles' references are not checked.
279
   */
280
  template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
281
    return !operator==(that);
282
  }
283

    
284
  template <class S> V8_INLINE bool operator!=(
285
      const Persistent<S>& that) const {
286
    return !operator==(that);
287
  }
288

    
289
  template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
290
#ifdef V8_ENABLE_CHECKS
291
    // If we're going to perform the type check then we have to check
292
    // that the handle isn't empty before doing the checked cast.
293
    if (that.IsEmpty()) return Handle<T>();
294
#endif
295
    return Handle<T>(T::Cast(*that));
296
  }
297

    
298
  template <class S> V8_INLINE Handle<S> As() {
299
    return Handle<S>::Cast(*this);
300
  }
301

    
302
  V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
303
    return New(isolate, that.val_);
304
  }
305
  V8_INLINE static Handle<T> New(Isolate* isolate, const Persistent<T>& that) {
306
    return New(isolate, that.val_);
307
  }
308

    
309
#ifndef V8_ALLOW_ACCESS_TO_RAW_HANDLE_CONSTRUCTOR
310

    
311
 private:
312
#endif
313
  /**
314
   * Creates a new handle for the specified value.
315
   */
316
  V8_INLINE explicit Handle(T* val) : val_(val) {}
317

    
318
 private:
319
  friend class Utils;
320
  template<class F, class M> friend class Persistent;
321
  template<class F> friend class Local;
322
  template<class F> friend class FunctionCallbackInfo;
323
  template<class F> friend class PropertyCallbackInfo;
324
  template<class F> friend class internal::CustomArguments;
325
  friend Handle<Primitive> Undefined(Isolate* isolate);
326
  friend Handle<Primitive> Null(Isolate* isolate);
327
  friend Handle<Boolean> True(Isolate* isolate);
328
  friend Handle<Boolean> False(Isolate* isolate);
329
  friend class Context;
330
  friend class HandleScope;
331

    
332
  V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
333

    
334
  T* val_;
335
};
336

    
337

    
338
/**
339
 * A light-weight stack-allocated object handle.  All operations
340
 * that return objects from within v8 return them in local handles.  They
341
 * are created within HandleScopes, and all local handles allocated within a
342
 * handle scope are destroyed when the handle scope is destroyed.  Hence it
343
 * is not necessary to explicitly deallocate local handles.
344
 */
345
template <class T> class Local : public Handle<T> {
346
 public:
347
  V8_INLINE Local();
348
  template <class S> V8_INLINE Local(Local<S> that)
349
      : Handle<T>(reinterpret_cast<T*>(*that)) {
350
    /**
351
     * This check fails when trying to convert between incompatible
352
     * handles. For example, converting from a Handle<String> to a
353
     * Handle<Number>.
354
     */
355
    TYPE_CHECK(T, S);
356
  }
357

    
358

    
359
  template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
360
#ifdef V8_ENABLE_CHECKS
361
    // If we're going to perform the type check then we have to check
362
    // that the handle isn't empty before doing the checked cast.
363
    if (that.IsEmpty()) return Local<T>();
364
#endif
365
    return Local<T>(T::Cast(*that));
366
  }
367
  template <class S> V8_INLINE Local(Handle<S> that)
368
      : Handle<T>(reinterpret_cast<T*>(*that)) {
369
    TYPE_CHECK(T, S);
370
  }
371

    
372
  template <class S> V8_INLINE Local<S> As() {
373
    return Local<S>::Cast(*this);
374
  }
375

    
376
  /**
377
   * Create a local handle for the content of another handle.
378
   * The referee is kept alive by the local handle even when
379
   * the original handle is destroyed/disposed.
380
   */
381
  V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
382
  template<class M>
383
  V8_INLINE static Local<T> New(Isolate* isolate,
384
                                const Persistent<T, M>& that);
385

    
386
#ifndef V8_ALLOW_ACCESS_TO_RAW_HANDLE_CONSTRUCTOR
387

    
388
 private:
389
#endif
390
  template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
391

    
392
 private:
393
  friend class Utils;
394
  template<class F> friend class Eternal;
395
  template<class F, class M> friend class Persistent;
396
  template<class F> friend class Handle;
397
  template<class F> friend class FunctionCallbackInfo;
398
  template<class F> friend class PropertyCallbackInfo;
399
  friend class String;
400
  friend class Object;
401
  friend class Context;
402
  template<class F> friend class internal::CustomArguments;
403
  friend class HandleScope;
404
  friend class EscapableHandleScope;
405

    
406
  V8_INLINE static Local<T> New(Isolate* isolate, T* that);
407
};
408

    
409

    
410
// Eternal handles are set-once handles that live for the life of the isolate.
411
template <class T> class Eternal {
412
 public:
413
  V8_INLINE Eternal() : index_(kInitialValue) { }
414
  template<class S>
415
  V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
416
    Set(isolate, handle);
417
  }
418
  // Can only be safely called if already set.
419
  V8_INLINE Local<T> Get(Isolate* isolate);
420
  V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
421
  template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
422

    
423
 private:
424
  static const int kInitialValue = -1;
425
  int index_;
426
};
427

    
428

    
429
template<class T, class P>
430
class WeakCallbackData {
431
 public:
432
  typedef void (*Callback)(const WeakCallbackData<T, P>& data);
433

    
434
  V8_INLINE Isolate* GetIsolate() const { return isolate_; }
435
  V8_INLINE Local<T> GetValue() const { return handle_; }
436
  V8_INLINE P* GetParameter() const { return parameter_; }
437

    
438
 private:
439
  friend class internal::GlobalHandles;
440
  WeakCallbackData(Isolate* isolate, Local<T> handle, P* parameter)
441
    : isolate_(isolate), handle_(handle), parameter_(parameter) { }
442
  Isolate* isolate_;
443
  Local<T> handle_;
444
  P* parameter_;
445
};
446

    
447

    
448
// TODO(dcarney): Remove this class.
449
template<typename T,
450
         typename P,
451
         typename M = NonCopyablePersistentTraits<T> >
452
class WeakReferenceCallbacks {
453
 public:
454
  typedef void (*Revivable)(Isolate* isolate,
455
                            Persistent<T, M>* object,
456
                            P* parameter);
457
};
458

    
459

    
460
/**
461
 * Default traits for Persistent. This class does not allow
462
 * use of the copy constructor or assignment operator.
463
 * At present kResetInDestructor is not set, but that will change in a future
464
 * version.
465
 */
466
template<class T>
467
class NonCopyablePersistentTraits {
468
 public:
469
  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
470
  static const bool kResetInDestructor = false;
471
  template<class S, class M>
472
  V8_INLINE static void Copy(const Persistent<S, M>& source,
473
                             NonCopyablePersistent* dest) {
474
    Uncompilable<Object>();
475
  }
476
  // TODO(dcarney): come up with a good compile error here.
477
  template<class O> V8_INLINE static void Uncompilable() {
478
    TYPE_CHECK(O, Primitive);
479
  }
480
};
481

    
482

    
483
/**
484
 * Helper class traits to allow copying and assignment of Persistent.
485
 * This will clone the contents of storage cell, but not any of the flags, etc.
486
 */
487
template<class T>
488
struct CopyablePersistentTraits {
489
  typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
490
  static const bool kResetInDestructor = true;
491
  template<class S, class M>
492
  static V8_INLINE void Copy(const Persistent<S, M>& source,
493
                             CopyablePersistent* dest) {
494
    // do nothing, just allow copy
495
  }
496
};
497

    
498

    
499
/**
500
 * An object reference that is independent of any handle scope.  Where
501
 * a Local handle only lives as long as the HandleScope in which it was
502
 * allocated, a Persistent handle remains valid until it is explicitly
503
 * disposed.
504
 *
505
 * A persistent handle contains a reference to a storage cell within
506
 * the v8 engine which holds an object value and which is updated by
507
 * the garbage collector whenever the object is moved.  A new storage
508
 * cell can be created using the constructor or Persistent::Reset and
509
 * existing handles can be disposed using Persistent::Reset.
510
 *
511
 * Copy, assignment and destructor bevavior is controlled by the traits
512
 * class M.
513
 */
514
template <class T, class M> class Persistent {
515
 public:
516
  /**
517
   * A Persistent with no storage cell.
518
   */
519
  V8_INLINE Persistent() : val_(0) { }
520
  /**
521
   * Construct a Persistent from a Handle.
522
   * When the Handle is non-empty, a new storage cell is created
523
   * pointing to the same object, and no flags are set.
524
   */
525
  template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
526
      : val_(New(isolate, *that)) {
527
    TYPE_CHECK(T, S);
528
  }
529
  /**
530
   * Construct a Persistent from a Persistent.
531
   * When the Persistent is non-empty, a new storage cell is created
532
   * pointing to the same object, and no flags are set.
533
   */
534
  template <class S, class M2>
535
  V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
536
    : val_(New(isolate, *that)) {
537
    TYPE_CHECK(T, S);
538
  }
539
  /**
540
   * The copy constructors and assignment operator create a Persistent
541
   * exactly as the Persistent constructor, but the Copy function from the
542
   * traits class is called, allowing the setting of flags based on the
543
   * copied Persistent.
544
   */
545
  V8_INLINE Persistent(const Persistent& that) : val_(0) {
546
    Copy(that);
547
  }
548
  template <class S, class M2>
549
  V8_INLINE Persistent(const Persistent<S, M2>& that) : val_(0) {
550
    Copy(that);
551
  }
552
  V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
553
    Copy(that);
554
    return *this;
555
  }
556
  template <class S, class M2>
557
  V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
558
    Copy(that);
559
    return *this;
560
  }
561
  /**
562
   * The destructor will dispose the Persistent based on the
563
   * kResetInDestructor flags in the traits class.  Since not calling dispose
564
   * can result in a memory leak, it is recommended to always set this flag.
565
   */
566
  V8_INLINE ~Persistent() {
567
    if (M::kResetInDestructor) Reset();
568
  }
569

    
570
  /**
571
   * If non-empty, destroy the underlying storage cell
572
   * IsEmpty() will return true after this call.
573
   */
574
  V8_INLINE void Reset();
575
  /**
576
   * If non-empty, destroy the underlying storage cell
577
   * and create a new one with the contents of other if other is non empty
578
   */
579
  template <class S>
580
  V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
581
  /**
582
   * If non-empty, destroy the underlying storage cell
583
   * and create a new one with the contents of other if other is non empty
584
   */
585
  template <class S, class M2>
586
  V8_INLINE void Reset(Isolate* isolate, const Persistent<S, M2>& other);
587

    
588
  V8_DEPRECATED("Use Reset instead",
589
                V8_INLINE void Dispose()) { Reset(); }
590

    
591
  V8_INLINE bool IsEmpty() const { return val_ == 0; }
592

    
593
  // TODO(dcarney): this is pretty useless, fix or remove
594
  template <class S>
595
  V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
596
#ifdef V8_ENABLE_CHECKS
597
    // If we're going to perform the type check then we have to check
598
    // that the handle isn't empty before doing the checked cast.
599
    if (!that.IsEmpty()) T::Cast(*that);
600
#endif
601
    return reinterpret_cast<Persistent<T>&>(that);
602
  }
603

    
604
  // TODO(dcarney): this is pretty useless, fix or remove
605
  template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
606
    return Persistent<S>::Cast(*this);
607
  }
608

    
609
  template <class S, class M2>
610
  V8_INLINE bool operator==(const Persistent<S, M2>& that) const {
611
    internal::Object** a = reinterpret_cast<internal::Object**>(**this);
612
    internal::Object** b = reinterpret_cast<internal::Object**>(*that);
613
    if (a == 0) return b == 0;
614
    if (b == 0) return false;
615
    return *a == *b;
616
  }
617

    
618
  template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
619
    internal::Object** a = reinterpret_cast<internal::Object**>(**this);
620
    internal::Object** b = reinterpret_cast<internal::Object**>(*that);
621
    if (a == 0) return b == 0;
622
    if (b == 0) return false;
623
    return *a == *b;
624
  }
625

    
626
  template <class S, class M2>
627
  V8_INLINE bool operator!=(const Persistent<S, M2>& that) const {
628
    return !operator==(that);
629
  }
630

    
631
  template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
632
    return !operator==(that);
633
  }
634

    
635
  template<typename P>
636
  V8_INLINE void SetWeak(
637
      P* parameter,
638
      typename WeakCallbackData<T, P>::Callback callback);
639

    
640
  template<typename S, typename P>
641
  V8_INLINE void SetWeak(
642
      P* parameter,
643
      typename WeakCallbackData<S, P>::Callback callback);
644

    
645
  template<typename S, typename P>
646
  V8_DEPRECATED(
647
      "Use SetWeak instead",
648
      V8_INLINE void MakeWeak(
649
          P* parameter,
650
          typename WeakReferenceCallbacks<S, P>::Revivable callback));
651

    
652
  template<typename P>
653
  V8_DEPRECATED(
654
      "Use SetWeak instead",
655
      V8_INLINE void MakeWeak(
656
          P* parameter,
657
          typename WeakReferenceCallbacks<T, P>::Revivable callback));
658

    
659
  V8_INLINE void ClearWeak();
660

    
661
  /**
662
   * Marks the reference to this object independent. Garbage collector is free
663
   * to ignore any object groups containing this object. Weak callback for an
664
   * independent handle should not assume that it will be preceded by a global
665
   * GC prologue callback or followed by a global GC epilogue callback.
666
   */
667
  V8_INLINE void MarkIndependent();
668

    
669
  /**
670
   * Marks the reference to this object partially dependent. Partially dependent
671
   * handles only depend on other partially dependent handles and these
672
   * dependencies are provided through object groups. It provides a way to build
673
   * smaller object groups for young objects that represent only a subset of all
674
   * external dependencies. This mark is automatically cleared after each
675
   * garbage collection.
676
   */
677
  V8_INLINE void MarkPartiallyDependent();
678

    
679
  V8_INLINE bool IsIndependent() const;
680

    
681
  /** Checks if the handle holds the only reference to an object. */
682
  V8_INLINE bool IsNearDeath() const;
683

    
684
  /** Returns true if the handle's reference is weak.  */
685
  V8_INLINE bool IsWeak() const;
686

    
687
  /**
688
   * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
689
   * description in v8-profiler.h for details.
690
   */
691
  V8_INLINE void SetWrapperClassId(uint16_t class_id);
692

    
693
  /**
694
   * Returns the class ID previously assigned to this handle or 0 if no class ID
695
   * was previously assigned.
696
   */
697
  V8_INLINE uint16_t WrapperClassId() const;
698

    
699
  V8_DEPRECATED("This will be removed",
700
                V8_INLINE T* ClearAndLeak());
701

    
702
  V8_DEPRECATED("This will be removed",
703
                V8_INLINE void Clear()) { val_ = 0; }
704

    
705
  // TODO(dcarney): remove
706
#ifndef V8_ALLOW_ACCESS_TO_RAW_HANDLE_CONSTRUCTOR
707

    
708
 private:
709
#endif
710
  template <class S> V8_INLINE Persistent(S* that) : val_(that) { }
711

    
712
  V8_INLINE T* operator*() const { return val_; }
713

    
714
 private:
715
  friend class Isolate;
716
  friend class Utils;
717
  template<class F> friend class Handle;
718
  template<class F> friend class Local;
719
  template<class F1, class F2> friend class Persistent;
720
  template<class F> friend class ReturnValue;
721

    
722
  V8_INLINE static T* New(Isolate* isolate, T* that);
723
  template<class S, class M2>
724
  V8_INLINE void Copy(const Persistent<S, M2>& that);
725

    
726
  T* val_;
727
};
728

    
729
 /**
730
 * A stack-allocated class that governs a number of local handles.
731
 * After a handle scope has been created, all local handles will be
732
 * allocated within that handle scope until either the handle scope is
733
 * deleted or another handle scope is created.  If there is already a
734
 * handle scope and a new one is created, all allocations will take
735
 * place in the new handle scope until it is deleted.  After that,
736
 * new handles will again be allocated in the original handle scope.
737
 *
738
 * After the handle scope of a local handle has been deleted the
739
 * garbage collector will no longer track the object stored in the
740
 * handle and may deallocate it.  The behavior of accessing a handle
741
 * for which the handle scope has been deleted is undefined.
742
 */
743
class V8_EXPORT HandleScope {
744
 public:
745
  HandleScope(Isolate* isolate);
746

    
747
  ~HandleScope();
748

    
749
  template <class T>
750
  V8_DEPRECATED("Use EscapableHandleScope::Escape instead",
751
                Local<T> Close(Handle<T> value));
752

    
753
  /**
754
   * Counts the number of allocated handles.
755
   */
756
  static int NumberOfHandles();
757

    
758
 private:
759
  /**
760
   * Creates a new handle with the given value.
761
   */
762
  static internal::Object** CreateHandle(internal::Isolate* isolate,
763
                                         internal::Object* value);
764
  // Uses HeapObject to obtain the current Isolate.
765
  static internal::Object** CreateHandle(internal::HeapObject* heap_object,
766
                                         internal::Object* value);
767

    
768
  V8_INLINE HandleScope() {}
769
  void Initialize(Isolate* isolate);
770

    
771
  // Make it hard to create heap-allocated or illegal handle scopes by
772
  // disallowing certain operations.
773
  HandleScope(const HandleScope&);
774
  void operator=(const HandleScope&);
775
  void* operator new(size_t size);
776
  void operator delete(void*, size_t);
777

    
778
  // This Data class is accessible internally as HandleScopeData through a
779
  // typedef in the ImplementationUtilities class.
780
  class V8_EXPORT Data {
781
   public:
782
    internal::Object** next;
783
    internal::Object** limit;
784
    int level;
785
    V8_INLINE void Initialize() {
786
      next = limit = NULL;
787
      level = 0;
788
    }
789
  };
790

    
791
  void Leave();
792

    
793
  internal::Isolate* isolate_;
794
  internal::Object** prev_next_;
795
  internal::Object** prev_limit_;
796

    
797
  // TODO(dcarney): remove this field
798
  // Allow for the active closing of HandleScopes which allows to pass a handle
799
  // from the HandleScope being closed to the next top most HandleScope.
800
  bool is_closed_;
801
  internal::Object** RawClose(internal::Object** value);
802

    
803
  friend class ImplementationUtilities;
804
  friend class EscapableHandleScope;
805
  template<class F> friend class Handle;
806
  template<class F> friend class Local;
807
  friend class Object;
808
  friend class Context;
809
};
810

    
811

    
812
/**
813
 * A HandleScope which first allocates a handle in the current scope
814
 * which will be later filled with the escape value.
815
 */
816
class V8_EXPORT EscapableHandleScope : public HandleScope {
817
 public:
818
  EscapableHandleScope(Isolate* isolate);
819
  V8_INLINE ~EscapableHandleScope() {}
820

    
821
  /**
822
   * Pushes the value into the previous scope and returns a handle to it.
823
   * Cannot be called twice.
824
   */
825
  template <class T>
826
  V8_INLINE Local<T> Escape(Local<T> value) {
827
    internal::Object** slot =
828
        Escape(reinterpret_cast<internal::Object**>(*value));
829
    return Local<T>(reinterpret_cast<T*>(slot));
830
  }
831

    
832
 private:
833
  internal::Object** Escape(internal::Object** escape_value);
834

    
835
  // Make it hard to create heap-allocated or illegal handle scopes by
836
  // disallowing certain operations.
837
  EscapableHandleScope(const EscapableHandleScope&);
838
  void operator=(const EscapableHandleScope&);
839
  void* operator new(size_t size);
840
  void operator delete(void*, size_t);
841

    
842
  internal::Object** escape_slot_;
843
};
844

    
845

    
846
/**
847
 * A simple Maybe type, representing an object which may or may not have a
848
 * value.
849
 */
850
template<class T>
851
struct Maybe {
852
  Maybe() : has_value(false) {}
853
  explicit Maybe(T t) : has_value(true), value(t) {}
854
  Maybe(bool has, T t) : has_value(has), value(t) {}
855

    
856
  bool has_value;
857
  T value;
858
};
859

    
860

    
861
// --- Special objects ---
862

    
863

    
864
/**
865
 * The superclass of values and API object templates.
866
 */
867
class V8_EXPORT Data {
868
 private:
869
  Data();
870
};
871

    
872

    
873
/**
874
 * Pre-compilation data that can be associated with a script.  This
875
 * data can be calculated for a script in advance of actually
876
 * compiling it, and can be stored between compilations.  When script
877
 * data is given to the compile method compilation will be faster.
878
 */
879
class V8_EXPORT ScriptData {  // NOLINT
880
 public:
881
  virtual ~ScriptData() { }
882

    
883
  /**
884
   * Pre-compiles the specified script (context-independent).
885
   *
886
   * \param input Pointer to UTF-8 script source code.
887
   * \param length Length of UTF-8 script source code.
888
   */
889
  static ScriptData* PreCompile(Isolate* isolate,
890
                                const char* input,
891
                                int length);
892

    
893
  /**
894
   * Pre-compiles the specified script (context-independent).
895
   *
896
   * NOTE: Pre-compilation using this method cannot happen on another thread
897
   * without using Lockers.
898
   *
899
   * \param source Script source code.
900
   */
901
  static ScriptData* PreCompile(Handle<String> source);
902

    
903
  /**
904
   * Load previous pre-compilation data.
905
   *
906
   * \param data Pointer to data returned by a call to Data() of a previous
907
   *   ScriptData. Ownership is not transferred.
908
   * \param length Length of data.
909
   */
910
  static ScriptData* New(const char* data, int length);
911

    
912
  /**
913
   * Returns the length of Data().
914
   */
915
  virtual int Length() = 0;
916

    
917
  /**
918
   * Returns a serialized representation of this ScriptData that can later be
919
   * passed to New(). NOTE: Serialized data is platform-dependent.
920
   */
921
  virtual const char* Data() = 0;
922

    
923
  /**
924
   * Returns true if the source code could not be parsed.
925
   */
926
  virtual bool HasError() = 0;
927
};
928

    
929

    
930
/**
931
 * The origin, within a file, of a script.
932
 */
933
class ScriptOrigin {
934
 public:
935
  V8_INLINE ScriptOrigin(
936
      Handle<Value> resource_name,
937
      Handle<Integer> resource_line_offset = Handle<Integer>(),
938
      Handle<Integer> resource_column_offset = Handle<Integer>(),
939
      Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>())
940
      : resource_name_(resource_name),
941
        resource_line_offset_(resource_line_offset),
942
        resource_column_offset_(resource_column_offset),
943
        resource_is_shared_cross_origin_(resource_is_shared_cross_origin) { }
944
  V8_INLINE Handle<Value> ResourceName() const;
945
  V8_INLINE Handle<Integer> ResourceLineOffset() const;
946
  V8_INLINE Handle<Integer> ResourceColumnOffset() const;
947
  V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
948
 private:
949
  Handle<Value> resource_name_;
950
  Handle<Integer> resource_line_offset_;
951
  Handle<Integer> resource_column_offset_;
952
  Handle<Boolean> resource_is_shared_cross_origin_;
953
};
954

    
955

    
956
/**
957
 * A compiled JavaScript script.
958
 */
959
class V8_EXPORT Script {
960
 public:
961
  /**
962
   * Compiles the specified script (context-independent).
963
   *
964
   * \param source Script source code.
965
   * \param origin Script origin, owned by caller, no references are kept
966
   *   when New() returns
967
   * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
968
   *   using pre_data speeds compilation if it's done multiple times.
969
   *   Owned by caller, no references are kept when New() returns.
970
   * \param script_data Arbitrary data associated with script. Using
971
   *   this has same effect as calling SetData(), but allows data to be
972
   *   available to compile event handlers.
973
   * \return Compiled script object (context independent; when run it
974
   *   will use the currently entered context).
975
   */
976
  static Local<Script> New(Handle<String> source,
977
                           ScriptOrigin* origin = NULL,
978
                           ScriptData* pre_data = NULL,
979
                           Handle<String> script_data = Handle<String>());
980

    
981
  /**
982
   * Compiles the specified script using the specified file name
983
   * object (typically a string) as the script's origin.
984
   *
985
   * \param source Script source code.
986
   * \param file_name file name object (typically a string) to be used
987
   *   as the script's origin.
988
   * \return Compiled script object (context independent; when run it
989
   *   will use the currently entered context).
990
   */
991
  static Local<Script> New(Handle<String> source,
992
                           Handle<Value> file_name);
993

    
994
  /**
995
   * Compiles the specified script (bound to current context).
996
   *
997
   * \param source Script source code.
998
   * \param origin Script origin, owned by caller, no references are kept
999
   *   when Compile() returns
1000
   * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1001
   *   using pre_data speeds compilation if it's done multiple times.
1002
   *   Owned by caller, no references are kept when Compile() returns.
1003
   * \param script_data Arbitrary data associated with script. Using
1004
   *   this has same effect as calling SetData(), but makes data available
1005
   *   earlier (i.e. to compile event handlers).
1006
   * \return Compiled script object, bound to the context that was active
1007
   *   when this function was called.  When run it will always use this
1008
   *   context.
1009
   */
1010
  static Local<Script> Compile(Handle<String> source,
1011
                               ScriptOrigin* origin = NULL,
1012
                               ScriptData* pre_data = NULL,
1013
                               Handle<String> script_data = Handle<String>());
1014

    
1015
  /**
1016
   * Compiles the specified script using the specified file name
1017
   * object (typically a string) as the script's origin.
1018
   *
1019
   * \param source Script source code.
1020
   * \param file_name File name to use as script's origin
1021
   * \param script_data Arbitrary data associated with script. Using
1022
   *   this has same effect as calling SetData(), but makes data available
1023
   *   earlier (i.e. to compile event handlers).
1024
   * \return Compiled script object, bound to the context that was active
1025
   *   when this function was called.  When run it will always use this
1026
   *   context.
1027
   */
1028
  static Local<Script> Compile(Handle<String> source,
1029
                               Handle<Value> file_name,
1030
                               Handle<String> script_data = Handle<String>());
1031

    
1032
  /**
1033
   * Runs the script returning the resulting value.  If the script is
1034
   * context independent (created using ::New) it will be run in the
1035
   * currently entered context.  If it is context specific (created
1036
   * using ::Compile) it will be run in the context in which it was
1037
   * compiled.
1038
   */
1039
  Local<Value> Run();
1040

    
1041
  /**
1042
   * Returns the script id value.
1043
   */
1044
  V8_DEPRECATED("Use GetId instead", Local<Value> Id());
1045

    
1046
  /**
1047
   * Returns the script id.
1048
   */
1049
  int GetId();
1050

    
1051
  /**
1052
   * Associate an additional data object with the script. This is mainly used
1053
   * with the debugger as this data object is only available through the
1054
   * debugger API.
1055
   */
1056
  void SetData(Handle<String> data);
1057

    
1058
  /**
1059
   * Returns the name value of one Script.
1060
   */
1061
  Handle<Value> GetScriptName();
1062

    
1063
  /**
1064
   * Returns zero based line number of the code_pos location in the script.
1065
   * -1 will be returned if no information available.
1066
   */
1067
  int GetLineNumber(int code_pos);
1068

    
1069
  static const int kNoScriptId = 0;
1070
};
1071

    
1072

    
1073
/**
1074
 * An error message.
1075
 */
1076
class V8_EXPORT Message {
1077
 public:
1078
  Local<String> Get() const;
1079
  Local<String> GetSourceLine() const;
1080

    
1081
  /**
1082
   * Returns the resource name for the script from where the function causing
1083
   * the error originates.
1084
   */
1085
  Handle<Value> GetScriptResourceName() const;
1086

    
1087
  /**
1088
   * Returns the resource data for the script from where the function causing
1089
   * the error originates.
1090
   */
1091
  Handle<Value> GetScriptData() const;
1092

    
1093
  /**
1094
   * Exception stack trace. By default stack traces are not captured for
1095
   * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1096
   * to change this option.
1097
   */
1098
  Handle<StackTrace> GetStackTrace() const;
1099

    
1100
  /**
1101
   * Returns the number, 1-based, of the line where the error occurred.
1102
   */
1103
  int GetLineNumber() const;
1104

    
1105
  /**
1106
   * Returns the index within the script of the first character where
1107
   * the error occurred.
1108
   */
1109
  int GetStartPosition() const;
1110

    
1111
  /**
1112
   * Returns the index within the script of the last character where
1113
   * the error occurred.
1114
   */
1115
  int GetEndPosition() const;
1116

    
1117
  /**
1118
   * Returns the index within the line of the first character where
1119
   * the error occurred.
1120
   */
1121
  int GetStartColumn() const;
1122

    
1123
  /**
1124
   * Returns the index within the line of the last character where
1125
   * the error occurred.
1126
   */
1127
  int GetEndColumn() const;
1128

    
1129
  /**
1130
   * Passes on the value set by the embedder when it fed the script from which
1131
   * this Message was generated to V8.
1132
   */
1133
  bool IsSharedCrossOrigin() const;
1134

    
1135
  // TODO(1245381): Print to a string instead of on a FILE.
1136
  static void PrintCurrentStackTrace(FILE* out);
1137

    
1138
  static const int kNoLineNumberInfo = 0;
1139
  static const int kNoColumnInfo = 0;
1140
  static const int kNoScriptIdInfo = 0;
1141
};
1142

    
1143

    
1144
/**
1145
 * Representation of a JavaScript stack trace. The information collected is a
1146
 * snapshot of the execution stack and the information remains valid after
1147
 * execution continues.
1148
 */
1149
class V8_EXPORT StackTrace {
1150
 public:
1151
  /**
1152
   * Flags that determine what information is placed captured for each
1153
   * StackFrame when grabbing the current stack trace.
1154
   */
1155
  enum StackTraceOptions {
1156
    kLineNumber = 1,
1157
    kColumnOffset = 1 << 1 | kLineNumber,
1158
    kScriptName = 1 << 2,
1159
    kFunctionName = 1 << 3,
1160
    kIsEval = 1 << 4,
1161
    kIsConstructor = 1 << 5,
1162
    kScriptNameOrSourceURL = 1 << 6,
1163
    kScriptId = 1 << 7,
1164
    kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1165
    kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1166
  };
1167

    
1168
  /**
1169
   * Returns a StackFrame at a particular index.
1170
   */
1171
  Local<StackFrame> GetFrame(uint32_t index) const;
1172

    
1173
  /**
1174
   * Returns the number of StackFrames.
1175
   */
1176
  int GetFrameCount() const;
1177

    
1178
  /**
1179
   * Returns StackTrace as a v8::Array that contains StackFrame objects.
1180
   */
1181
  Local<Array> AsArray();
1182

    
1183
  /**
1184
   * Grab a snapshot of the current JavaScript execution stack.
1185
   *
1186
   * \param frame_limit The maximum number of stack frames we want to capture.
1187
   * \param options Enumerates the set of things we will capture for each
1188
   *   StackFrame.
1189
   */
1190
  static Local<StackTrace> CurrentStackTrace(
1191
      int frame_limit,
1192
      StackTraceOptions options = kOverview);
1193
};
1194

    
1195

    
1196
/**
1197
 * A single JavaScript stack frame.
1198
 */
1199
class V8_EXPORT StackFrame {
1200
 public:
1201
  /**
1202
   * Returns the number, 1-based, of the line for the associate function call.
1203
   * This method will return Message::kNoLineNumberInfo if it is unable to
1204
   * retrieve the line number, or if kLineNumber was not passed as an option
1205
   * when capturing the StackTrace.
1206
   */
1207
  int GetLineNumber() const;
1208

    
1209
  /**
1210
   * Returns the 1-based column offset on the line for the associated function
1211
   * call.
1212
   * This method will return Message::kNoColumnInfo if it is unable to retrieve
1213
   * the column number, or if kColumnOffset was not passed as an option when
1214
   * capturing the StackTrace.
1215
   */
1216
  int GetColumn() const;
1217

    
1218
  /**
1219
   * Returns the id of the script for the function for this StackFrame.
1220
   * This method will return Message::kNoScriptIdInfo if it is unable to
1221
   * retrieve the script id, or if kScriptId was not passed as an option when
1222
   * capturing the StackTrace.
1223
   */
1224
  int GetScriptId() const;
1225

    
1226
  /**
1227
   * Returns the name of the resource that contains the script for the
1228
   * function for this StackFrame.
1229
   */
1230
  Local<String> GetScriptName() const;
1231

    
1232
  /**
1233
   * Returns the name of the resource that contains the script for the
1234
   * function for this StackFrame or sourceURL value if the script name
1235
   * is undefined and its source ends with //# sourceURL=... string or
1236
   * deprecated //@ sourceURL=... string.
1237
   */
1238
  Local<String> GetScriptNameOrSourceURL() const;
1239

    
1240
  /**
1241
   * Returns the name of the function associated with this stack frame.
1242
   */
1243
  Local<String> GetFunctionName() const;
1244

    
1245
  /**
1246
   * Returns whether or not the associated function is compiled via a call to
1247
   * eval().
1248
   */
1249
  bool IsEval() const;
1250

    
1251
  /**
1252
   * Returns whether or not the associated function is called as a
1253
   * constructor via "new".
1254
   */
1255
  bool IsConstructor() const;
1256
};
1257

    
1258

    
1259
/**
1260
 * A JSON Parser.
1261
 */
1262
class V8_EXPORT JSON {
1263
 public:
1264
  /**
1265
   * Tries to parse the string |json_string| and returns it as value if
1266
   * successful.
1267
   *
1268
   * \param json_string The string to parse.
1269
   * \return The corresponding value if successfully parsed.
1270
   */
1271
  static Local<Value> Parse(Local<String> json_string);
1272
};
1273

    
1274

    
1275
// --- Value ---
1276

    
1277

    
1278
/**
1279
 * The superclass of all JavaScript values and objects.
1280
 */
1281
class V8_EXPORT Value : public Data {
1282
 public:
1283
  /**
1284
   * Returns true if this value is the undefined value.  See ECMA-262
1285
   * 4.3.10.
1286
   */
1287
  V8_INLINE bool IsUndefined() const;
1288

    
1289
  /**
1290
   * Returns true if this value is the null value.  See ECMA-262
1291
   * 4.3.11.
1292
   */
1293
  V8_INLINE bool IsNull() const;
1294

    
1295
   /**
1296
   * Returns true if this value is true.
1297
   */
1298
  bool IsTrue() const;
1299

    
1300
  /**
1301
   * Returns true if this value is false.
1302
   */
1303
  bool IsFalse() const;
1304

    
1305
  /**
1306
   * Returns true if this value is an instance of the String type.
1307
   * See ECMA-262 8.4.
1308
   */
1309
  V8_INLINE bool IsString() const;
1310

    
1311
  /**
1312
   * Returns true if this value is a symbol.
1313
   * This is an experimental feature.
1314
   */
1315
  bool IsSymbol() const;
1316

    
1317
  /**
1318
   * Returns true if this value is a function.
1319
   */
1320
  bool IsFunction() const;
1321

    
1322
  /**
1323
   * Returns true if this value is an array.
1324
   */
1325
  bool IsArray() const;
1326

    
1327
  /**
1328
   * Returns true if this value is an object.
1329
   */
1330
  bool IsObject() const;
1331

    
1332
  /**
1333
   * Returns true if this value is boolean.
1334
   */
1335
  bool IsBoolean() const;
1336

    
1337
  /**
1338
   * Returns true if this value is a number.
1339
   */
1340
  bool IsNumber() const;
1341

    
1342
  /**
1343
   * Returns true if this value is external.
1344
   */
1345
  bool IsExternal() const;
1346

    
1347
  /**
1348
   * Returns true if this value is a 32-bit signed integer.
1349
   */
1350
  bool IsInt32() const;
1351

    
1352
  /**
1353
   * Returns true if this value is a 32-bit unsigned integer.
1354
   */
1355
  bool IsUint32() const;
1356

    
1357
  /**
1358
   * Returns true if this value is a Date.
1359
   */
1360
  bool IsDate() const;
1361

    
1362
  /**
1363
   * Returns true if this value is a Boolean object.
1364
   */
1365
  bool IsBooleanObject() const;
1366

    
1367
  /**
1368
   * Returns true if this value is a Number object.
1369
   */
1370
  bool IsNumberObject() const;
1371

    
1372
  /**
1373
   * Returns true if this value is a String object.
1374
   */
1375
  bool IsStringObject() const;
1376

    
1377
  /**
1378
   * Returns true if this value is a Symbol object.
1379
   * This is an experimental feature.
1380
   */
1381
  bool IsSymbolObject() const;
1382

    
1383
  /**
1384
   * Returns true if this value is a NativeError.
1385
   */
1386
  bool IsNativeError() const;
1387

    
1388
  /**
1389
   * Returns true if this value is a RegExp.
1390
   */
1391
  bool IsRegExp() const;
1392

    
1393

    
1394
  /**
1395
   * Returns true if this value is an ArrayBuffer.
1396
   * This is an experimental feature.
1397
   */
1398
  bool IsArrayBuffer() const;
1399

    
1400
  /**
1401
   * Returns true if this value is an ArrayBufferView.
1402
   * This is an experimental feature.
1403
   */
1404
  bool IsArrayBufferView() const;
1405

    
1406
  /**
1407
   * Returns true if this value is one of TypedArrays.
1408
   * This is an experimental feature.
1409
   */
1410
  bool IsTypedArray() const;
1411

    
1412
  /**
1413
   * Returns true if this value is an Uint8Array.
1414
   * This is an experimental feature.
1415
   */
1416
  bool IsUint8Array() const;
1417

    
1418
  /**
1419
   * Returns true if this value is an Uint8ClampedArray.
1420
   * This is an experimental feature.
1421
   */
1422
  bool IsUint8ClampedArray() const;
1423

    
1424
  /**
1425
   * Returns true if this value is an Int8Array.
1426
   * This is an experimental feature.
1427
   */
1428
  bool IsInt8Array() const;
1429

    
1430
  /**
1431
   * Returns true if this value is an Uint16Array.
1432
   * This is an experimental feature.
1433
   */
1434
  bool IsUint16Array() const;
1435

    
1436
  /**
1437
   * Returns true if this value is an Int16Array.
1438
   * This is an experimental feature.
1439
   */
1440
  bool IsInt16Array() const;
1441

    
1442
  /**
1443
   * Returns true if this value is an Uint32Array.
1444
   * This is an experimental feature.
1445
   */
1446
  bool IsUint32Array() const;
1447

    
1448
  /**
1449
   * Returns true if this value is an Int32Array.
1450
   * This is an experimental feature.
1451
   */
1452
  bool IsInt32Array() const;
1453

    
1454
  /**
1455
   * Returns true if this value is a Float32Array.
1456
   * This is an experimental feature.
1457
   */
1458
  bool IsFloat32Array() const;
1459

    
1460
  /**
1461
   * Returns true if this value is a Float64Array.
1462
   * This is an experimental feature.
1463
   */
1464
  bool IsFloat64Array() const;
1465

    
1466
  /**
1467
   * Returns true if this value is a DataView.
1468
   * This is an experimental feature.
1469
   */
1470
  bool IsDataView() const;
1471

    
1472
  Local<Boolean> ToBoolean() const;
1473
  Local<Number> ToNumber() const;
1474
  Local<String> ToString() const;
1475
  Local<String> ToDetailString() const;
1476
  Local<Object> ToObject() const;
1477
  Local<Integer> ToInteger() const;
1478
  Local<Uint32> ToUint32() const;
1479
  Local<Int32> ToInt32() const;
1480

    
1481
  /**
1482
   * Attempts to convert a string to an array index.
1483
   * Returns an empty handle if the conversion fails.
1484
   */
1485
  Local<Uint32> ToArrayIndex() const;
1486

    
1487
  bool BooleanValue() const;
1488
  double NumberValue() const;
1489
  int64_t IntegerValue() const;
1490
  uint32_t Uint32Value() const;
1491
  int32_t Int32Value() const;
1492

    
1493
  /** JS == */
1494
  bool Equals(Handle<Value> that) const;
1495
  bool StrictEquals(Handle<Value> that) const;
1496
  bool SameValue(Handle<Value> that) const;
1497

    
1498
  template <class T> V8_INLINE static Value* Cast(T* value);
1499

    
1500
 private:
1501
  V8_INLINE bool QuickIsUndefined() const;
1502
  V8_INLINE bool QuickIsNull() const;
1503
  V8_INLINE bool QuickIsString() const;
1504
  bool FullIsUndefined() const;
1505
  bool FullIsNull() const;
1506
  bool FullIsString() const;
1507
};
1508

    
1509

    
1510
/**
1511
 * The superclass of primitive values.  See ECMA-262 4.3.2.
1512
 */
1513
class V8_EXPORT Primitive : public Value { };
1514

    
1515

    
1516
/**
1517
 * A primitive boolean value (ECMA-262, 4.3.14).  Either the true
1518
 * or false value.
1519
 */
1520
class V8_EXPORT Boolean : public Primitive {
1521
 public:
1522
  bool Value() const;
1523
  V8_INLINE static Handle<Boolean> New(bool value);
1524
};
1525

    
1526

    
1527
/**
1528
 * A JavaScript string value (ECMA-262, 4.3.17).
1529
 */
1530
class V8_EXPORT String : public Primitive {
1531
 public:
1532
  enum Encoding {
1533
    UNKNOWN_ENCODING = 0x1,
1534
    TWO_BYTE_ENCODING = 0x0,
1535
    ASCII_ENCODING = 0x4,
1536
    ONE_BYTE_ENCODING = 0x4
1537
  };
1538
  /**
1539
   * Returns the number of characters in this string.
1540
   */
1541
  int Length() const;
1542

    
1543
  /**
1544
   * Returns the number of bytes in the UTF-8 encoded
1545
   * representation of this string.
1546
   */
1547
  int Utf8Length() const;
1548

    
1549
  /**
1550
   * Returns whether this string is known to contain only one byte data.
1551
   * Does not read the string.
1552
   * False negatives are possible.
1553
   */
1554
  bool IsOneByte() const;
1555

    
1556
  /**
1557
   * Returns whether this string contain only one byte data.
1558
   * Will read the entire string in some cases.
1559
   */
1560
  bool ContainsOnlyOneByte() const;
1561

    
1562
  /**
1563
   * Write the contents of the string to an external buffer.
1564
   * If no arguments are given, expects the buffer to be large
1565
   * enough to hold the entire string and NULL terminator. Copies
1566
   * the contents of the string and the NULL terminator into the
1567
   * buffer.
1568
   *
1569
   * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1570
   * before the end of the buffer.
1571
   *
1572
   * Copies up to length characters into the output buffer.
1573
   * Only null-terminates if there is enough space in the buffer.
1574
   *
1575
   * \param buffer The buffer into which the string will be copied.
1576
   * \param start The starting position within the string at which
1577
   * copying begins.
1578
   * \param length The number of characters to copy from the string.  For
1579
   *    WriteUtf8 the number of bytes in the buffer.
1580
   * \param nchars_ref The number of characters written, can be NULL.
1581
   * \param options Various options that might affect performance of this or
1582
   *    subsequent operations.
1583
   * \return The number of characters copied to the buffer excluding the null
1584
   *    terminator.  For WriteUtf8: The number of bytes copied to the buffer
1585
   *    including the null terminator (if written).
1586
   */
1587
  enum WriteOptions {
1588
    NO_OPTIONS = 0,
1589
    HINT_MANY_WRITES_EXPECTED = 1,
1590
    NO_NULL_TERMINATION = 2,
1591
    PRESERVE_ASCII_NULL = 4
1592
  };
1593

    
1594
  // 16-bit character codes.
1595
  int Write(uint16_t* buffer,
1596
            int start = 0,
1597
            int length = -1,
1598
            int options = NO_OPTIONS) const;
1599
  // One byte characters.
1600
  int WriteOneByte(uint8_t* buffer,
1601
                   int start = 0,
1602
                   int length = -1,
1603
                   int options = NO_OPTIONS) const;
1604
  // UTF-8 encoded characters.
1605
  int WriteUtf8(char* buffer,
1606
                int length = -1,
1607
                int* nchars_ref = NULL,
1608
                int options = NO_OPTIONS) const;
1609

    
1610
  /**
1611
   * A zero length string.
1612
   */
1613
  static v8::Local<v8::String> Empty();
1614
  V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
1615

    
1616
  /**
1617
   * Returns true if the string is external
1618
   */
1619
  bool IsExternal() const;
1620

    
1621
  /**
1622
   * Returns true if the string is both external and ASCII
1623
   */
1624
  bool IsExternalAscii() const;
1625

    
1626
  class V8_EXPORT ExternalStringResourceBase {  // NOLINT
1627
   public:
1628
    virtual ~ExternalStringResourceBase() {}
1629

    
1630
   protected:
1631
    ExternalStringResourceBase() {}
1632

    
1633
    /**
1634
     * Internally V8 will call this Dispose method when the external string
1635
     * resource is no longer needed. The default implementation will use the
1636
     * delete operator. This method can be overridden in subclasses to
1637
     * control how allocated external string resources are disposed.
1638
     */
1639
    virtual void Dispose() { delete this; }
1640

    
1641
   private:
1642
    // Disallow copying and assigning.
1643
    ExternalStringResourceBase(const ExternalStringResourceBase&);
1644
    void operator=(const ExternalStringResourceBase&);
1645

    
1646
    friend class v8::internal::Heap;
1647
  };
1648

    
1649
  /**
1650
   * An ExternalStringResource is a wrapper around a two-byte string
1651
   * buffer that resides outside V8's heap. Implement an
1652
   * ExternalStringResource to manage the life cycle of the underlying
1653
   * buffer.  Note that the string data must be immutable.
1654
   */
1655
  class V8_EXPORT ExternalStringResource
1656
      : public ExternalStringResourceBase {
1657
   public:
1658
    /**
1659
     * Override the destructor to manage the life cycle of the underlying
1660
     * buffer.
1661
     */
1662
    virtual ~ExternalStringResource() {}
1663

    
1664
    /**
1665
     * The string data from the underlying buffer.
1666
     */
1667
    virtual const uint16_t* data() const = 0;
1668

    
1669
    /**
1670
     * The length of the string. That is, the number of two-byte characters.
1671
     */
1672
    virtual size_t length() const = 0;
1673

    
1674
   protected:
1675
    ExternalStringResource() {}
1676
  };
1677

    
1678
  /**
1679
   * An ExternalAsciiStringResource is a wrapper around an ASCII
1680
   * string buffer that resides outside V8's heap. Implement an
1681
   * ExternalAsciiStringResource to manage the life cycle of the
1682
   * underlying buffer.  Note that the string data must be immutable
1683
   * and that the data must be strict (7-bit) ASCII, not Latin-1 or
1684
   * UTF-8, which would require special treatment internally in the
1685
   * engine and, in the case of UTF-8, do not allow efficient indexing.
1686
   * Use String::New or convert to 16 bit data for non-ASCII.
1687
   */
1688

    
1689
  class V8_EXPORT ExternalAsciiStringResource
1690
      : public ExternalStringResourceBase {
1691
   public:
1692
    /**
1693
     * Override the destructor to manage the life cycle of the underlying
1694
     * buffer.
1695
     */
1696
    virtual ~ExternalAsciiStringResource() {}
1697
    /** The string data from the underlying buffer.*/
1698
    virtual const char* data() const = 0;
1699
    /** The number of ASCII characters in the string.*/
1700
    virtual size_t length() const = 0;
1701
   protected:
1702
    ExternalAsciiStringResource() {}
1703
  };
1704

    
1705
  typedef ExternalAsciiStringResource ExternalOneByteStringResource;
1706

    
1707
  /**
1708
   * If the string is an external string, return the ExternalStringResourceBase
1709
   * regardless of the encoding, otherwise return NULL.  The encoding of the
1710
   * string is returned in encoding_out.
1711
   */
1712
  V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
1713
      Encoding* encoding_out) const;
1714

    
1715
  /**
1716
   * Get the ExternalStringResource for an external string.  Returns
1717
   * NULL if IsExternal() doesn't return true.
1718
   */
1719
  V8_INLINE ExternalStringResource* GetExternalStringResource() const;
1720

    
1721
  /**
1722
   * Get the ExternalAsciiStringResource for an external ASCII string.
1723
   * Returns NULL if IsExternalAscii() doesn't return true.
1724
   */
1725
  const ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
1726

    
1727
  V8_INLINE static String* Cast(v8::Value* obj);
1728

    
1729
  /**
1730
   * Allocates a new string from either UTF-8 encoded or ASCII data.
1731
   * The second parameter 'length' gives the buffer length. If omitted,
1732
   * the function calls 'strlen' to determine the buffer length.
1733
   */
1734
  V8_DEPRECATED(
1735
      "Use NewFromOneByte instead",
1736
      V8_INLINE static Local<String> New(const char* data, int length = -1));
1737

    
1738
  /** Allocates a new string from 16-bit character codes.*/
1739
  V8_DEPRECATED(
1740
      "Use NewFromTwoByte instead",
1741
      V8_INLINE static Local<String> New(
1742
          const uint16_t* data, int length = -1));
1743

    
1744
  /**
1745
   * Creates an internalized string (historically called a "symbol",
1746
   * not to be confused with ES6 symbols). Returns one if it exists already.
1747
   */
1748
  V8_DEPRECATED(
1749
      "Use NewFromUtf8 instead",
1750
      V8_INLINE static Local<String> NewSymbol(
1751
          const char* data, int length = -1));
1752

    
1753
  enum NewStringType {
1754
    kNormalString, kInternalizedString, kUndetectableString
1755
  };
1756

    
1757
  /** Allocates a new string from UTF-8 data.*/
1758
  static Local<String> NewFromUtf8(Isolate* isolate,
1759
                                  const char* data,
1760
                                  NewStringType type = kNormalString,
1761
                                  int length = -1);
1762

    
1763
  /** Allocates a new string from Latin-1 data.*/
1764
  static Local<String> NewFromOneByte(
1765
      Isolate* isolate,
1766
      const uint8_t* data,
1767
      NewStringType type = kNormalString,
1768
      int length = -1);
1769

    
1770
  /** Allocates a new string from UTF-16 data.*/
1771
  static Local<String> NewFromTwoByte(
1772
      Isolate* isolate,
1773
      const uint16_t* data,
1774
      NewStringType type = kNormalString,
1775
      int length = -1);
1776

    
1777
  /**
1778
   * Creates a new string by concatenating the left and the right strings
1779
   * passed in as parameters.
1780
   */
1781
  static Local<String> Concat(Handle<String> left, Handle<String> right);
1782

    
1783
  /**
1784
   * Creates a new external string using the data defined in the given
1785
   * resource. When the external string is no longer live on V8's heap the
1786
   * resource will be disposed by calling its Dispose method. The caller of
1787
   * this function should not otherwise delete or modify the resource. Neither
1788
   * should the underlying buffer be deallocated or modified except through the
1789
   * destructor of the external string resource.
1790
   */
1791
  static Local<String> NewExternal(ExternalStringResource* resource);
1792

    
1793
  /**
1794
   * Associate an external string resource with this string by transforming it
1795
   * in place so that existing references to this string in the JavaScript heap
1796
   * will use the external string resource. The external string resource's
1797
   * character contents need to be equivalent to this string.
1798
   * Returns true if the string has been changed to be an external string.
1799
   * The string is not modified if the operation fails. See NewExternal for
1800
   * information on the lifetime of the resource.
1801
   */
1802
  bool MakeExternal(ExternalStringResource* resource);
1803

    
1804
  /**
1805
   * Creates a new external string using the ASCII data defined in the given
1806
   * resource. When the external string is no longer live on V8's heap the
1807
   * resource will be disposed by calling its Dispose method. The caller of
1808
   * this function should not otherwise delete or modify the resource. Neither
1809
   * should the underlying buffer be deallocated or modified except through the
1810
   * destructor of the external string resource.
1811
   */
1812
  static Local<String> NewExternal(ExternalAsciiStringResource* resource);
1813

    
1814
  /**
1815
   * Associate an external string resource with this string by transforming it
1816
   * in place so that existing references to this string in the JavaScript heap
1817
   * will use the external string resource. The external string resource's
1818
   * character contents need to be equivalent to this string.
1819
   * Returns true if the string has been changed to be an external string.
1820
   * The string is not modified if the operation fails. See NewExternal for
1821
   * information on the lifetime of the resource.
1822
   */
1823
  bool MakeExternal(ExternalAsciiStringResource* resource);
1824

    
1825
  /**
1826
   * Returns true if this string can be made external.
1827
   */
1828
  bool CanMakeExternal();
1829

    
1830
  /** Creates an undetectable string from the supplied ASCII or UTF-8 data.*/
1831
  V8_DEPRECATED(
1832
      "Use NewFromUtf8 instead",
1833
      V8_INLINE static Local<String> NewUndetectable(const char* data,
1834
                                                     int length = -1));
1835

    
1836
  /** Creates an undetectable string from the supplied 16-bit character codes.*/
1837
  V8_DEPRECATED(
1838
      "Use NewFromTwoByte instead",
1839
      V8_INLINE static Local<String> NewUndetectable(const uint16_t* data,
1840
                                                     int length = -1));
1841

    
1842
  /**
1843
   * Converts an object to a UTF-8-encoded character array.  Useful if
1844
   * you want to print the object.  If conversion to a string fails
1845
   * (e.g. due to an exception in the toString() method of the object)
1846
   * then the length() method returns 0 and the * operator returns
1847
   * NULL.
1848
   */
1849
  class V8_EXPORT Utf8Value {
1850
   public:
1851
    explicit Utf8Value(Handle<v8::Value> obj);
1852
    ~Utf8Value();
1853
    char* operator*() { return str_; }
1854
    const char* operator*() const { return str_; }
1855
    int length() const { return length_; }
1856
   private:
1857
    char* str_;
1858
    int length_;
1859

    
1860
    // Disallow copying and assigning.
1861
    Utf8Value(const Utf8Value&);
1862
    void operator=(const Utf8Value&);
1863
  };
1864

    
1865
  /**
1866
   * Converts an object to an ASCII string.
1867
   * Useful if you want to print the object.
1868
   * If conversion to a string fails (eg. due to an exception in the toString()
1869
   * method of the object) then the length() method returns 0 and the * operator
1870
   * returns NULL.
1871
   */
1872
  class V8_EXPORT AsciiValue {
1873
   public:
1874
    V8_DEPRECATED("Use Utf8Value instead",
1875
                  explicit AsciiValue(Handle<v8::Value> obj));
1876
    ~AsciiValue();
1877
    char* operator*() { return str_; }
1878
    const char* operator*() const { return str_; }
1879
    int length() const { return length_; }
1880
   private:
1881
    char* str_;
1882
    int length_;
1883

    
1884
    // Disallow copying and assigning.
1885
    AsciiValue(const AsciiValue&);
1886
    void operator=(const AsciiValue&);
1887
  };
1888

    
1889
  /**
1890
   * Converts an object to a two-byte string.
1891
   * If conversion to a string fails (eg. due to an exception in the toString()
1892
   * method of the object) then the length() method returns 0 and the * operator
1893
   * returns NULL.
1894
   */
1895
  class V8_EXPORT Value {
1896
   public:
1897
    explicit Value(Handle<v8::Value> obj);
1898
    ~Value();
1899
    uint16_t* operator*() { return str_; }
1900
    const uint16_t* operator*() const { return str_; }
1901
    int length() const { return length_; }
1902
   private:
1903
    uint16_t* str_;
1904
    int length_;
1905

    
1906
    // Disallow copying and assigning.
1907
    Value(const Value&);
1908
    void operator=(const Value&);
1909
  };
1910

    
1911
 private:
1912
  void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
1913
                                        Encoding encoding) const;
1914
  void VerifyExternalStringResource(ExternalStringResource* val) const;
1915
  static void CheckCast(v8::Value* obj);
1916
};
1917

    
1918

    
1919
/**
1920
 * A JavaScript symbol (ECMA-262 edition 6)
1921
 *
1922
 * This is an experimental feature. Use at your own risk.
1923
 */
1924
class V8_EXPORT Symbol : public Primitive {
1925
 public:
1926
  // Returns the print name string of the symbol, or undefined if none.
1927
  Local<Value> Name() const;
1928

    
1929
  // Create a symbol without a print name.
1930
  static Local<Symbol> New(Isolate* isolate);
1931

    
1932
  // Create a symbol with a print name.
1933
  static Local<Symbol> New(Isolate *isolate, const char* data, int length = -1);
1934

    
1935
  V8_INLINE static Symbol* Cast(v8::Value* obj);
1936
 private:
1937
  Symbol();
1938
  static void CheckCast(v8::Value* obj);
1939
};
1940

    
1941

    
1942
/**
1943
 * A JavaScript number value (ECMA-262, 4.3.20)
1944
 */
1945
class V8_EXPORT Number : public Primitive {
1946
 public:
1947
  double Value() const;
1948
  static Local<Number> New(double value);
1949
  static Local<Number> New(Isolate* isolate, double value);
1950
  V8_INLINE static Number* Cast(v8::Value* obj);
1951
 private:
1952
  Number();
1953
  static void CheckCast(v8::Value* obj);
1954
};
1955

    
1956

    
1957
/**
1958
 * A JavaScript value representing a signed integer.
1959
 */
1960
class V8_EXPORT Integer : public Number {
1961
 public:
1962
  static Local<Integer> New(int32_t value);
1963
  static Local<Integer> NewFromUnsigned(uint32_t value);
1964
  static Local<Integer> New(int32_t value, Isolate*);
1965
  static Local<Integer> NewFromUnsigned(uint32_t value, Isolate*);
1966
  int64_t Value() const;
1967
  V8_INLINE static Integer* Cast(v8::Value* obj);
1968
 private:
1969
  Integer();
1970
  static void CheckCast(v8::Value* obj);
1971
};
1972

    
1973

    
1974
/**
1975
 * A JavaScript value representing a 32-bit signed integer.
1976
 */
1977
class V8_EXPORT Int32 : public Integer {
1978
 public:
1979
  int32_t Value() const;
1980
 private:
1981
  Int32();
1982
};
1983

    
1984

    
1985
/**
1986
 * A JavaScript value representing a 32-bit unsigned integer.
1987
 */
1988
class V8_EXPORT Uint32 : public Integer {
1989
 public:
1990
  uint32_t Value() const;
1991
 private:
1992
  Uint32();
1993
};
1994

    
1995

    
1996
enum PropertyAttribute {
1997
  None       = 0,
1998
  ReadOnly   = 1 << 0,
1999
  DontEnum   = 1 << 1,
2000
  DontDelete = 1 << 2
2001
};
2002

    
2003
enum ExternalArrayType {
2004
  kExternalByteArray = 1,
2005
  kExternalUnsignedByteArray,
2006
  kExternalShortArray,
2007
  kExternalUnsignedShortArray,
2008
  kExternalIntArray,
2009
  kExternalUnsignedIntArray,
2010
  kExternalFloatArray,
2011
  kExternalDoubleArray,
2012
  kExternalPixelArray
2013
};
2014

    
2015
/**
2016
 * Accessor[Getter|Setter] are used as callback functions when
2017
 * setting|getting a particular property. See Object and ObjectTemplate's
2018
 * method SetAccessor.
2019
 */
2020
typedef void (*AccessorGetterCallback)(
2021
    Local<String> property,
2022
    const PropertyCallbackInfo<Value>& info);
2023

    
2024

    
2025
typedef void (*AccessorSetterCallback)(
2026
    Local<String> property,
2027
    Local<Value> value,
2028
    const PropertyCallbackInfo<void>& info);
2029

    
2030

    
2031
/**
2032
 * Access control specifications.
2033
 *
2034
 * Some accessors should be accessible across contexts.  These
2035
 * accessors have an explicit access control parameter which specifies
2036
 * the kind of cross-context access that should be allowed.
2037
 *
2038
 * Additionally, for security, accessors can prohibit overwriting by
2039
 * accessors defined in JavaScript.  For objects that have such
2040
 * accessors either locally or in their prototype chain it is not
2041
 * possible to overwrite the accessor by using __defineGetter__ or
2042
 * __defineSetter__ from JavaScript code.
2043
 */
2044
enum AccessControl {
2045
  DEFAULT               = 0,
2046
  ALL_CAN_READ          = 1,
2047
  ALL_CAN_WRITE         = 1 << 1,
2048
  PROHIBITS_OVERWRITING = 1 << 2
2049
};
2050

    
2051

    
2052
/**
2053
 * A JavaScript object (ECMA-262, 4.3.3)
2054
 */
2055
class V8_EXPORT Object : public Value {
2056
 public:
2057
  bool Set(Handle<Value> key,
2058
           Handle<Value> value,
2059
           PropertyAttribute attribs = None);
2060

    
2061
  bool Set(uint32_t index, Handle<Value> value);
2062

    
2063
  // Sets a local property on this object bypassing interceptors and
2064
  // overriding accessors or read-only properties.
2065
  //
2066
  // Note that if the object has an interceptor the property will be set
2067
  // locally, but since the interceptor takes precedence the local property
2068
  // will only be returned if the interceptor doesn't return a value.
2069
  //
2070
  // Note also that this only works for named properties.
2071
  bool ForceSet(Handle<Value> key,
2072
                Handle<Value> value,
2073
                PropertyAttribute attribs = None);
2074

    
2075
  Local<Value> Get(Handle<Value> key);
2076

    
2077
  Local<Value> Get(uint32_t index);
2078

    
2079
  /**
2080
   * Gets the property attributes of a property which can be None or
2081
   * any combination of ReadOnly, DontEnum and DontDelete. Returns
2082
   * None when the property doesn't exist.
2083
   */
2084
  PropertyAttribute GetPropertyAttributes(Handle<Value> key);
2085

    
2086
  bool Has(Handle<Value> key);
2087

    
2088
  bool Delete(Handle<Value> key);
2089

    
2090
  // Delete a property on this object bypassing interceptors and
2091
  // ignoring dont-delete attributes.
2092
  bool ForceDelete(Handle<Value> key);
2093

    
2094
  bool Has(uint32_t index);
2095

    
2096
  bool Delete(uint32_t index);
2097

    
2098
  bool SetAccessor(Handle<String> name,
2099
                   AccessorGetterCallback getter,
2100
                   AccessorSetterCallback setter = 0,
2101
                   Handle<Value> data = Handle<Value>(),
2102
                   AccessControl settings = DEFAULT,
2103
                   PropertyAttribute attribute = None);
2104

    
2105
  // This function is not yet stable and should not be used at this time.
2106
  bool SetDeclaredAccessor(Local<String> name,
2107
                           Local<DeclaredAccessorDescriptor> descriptor,
2108
                           PropertyAttribute attribute = None,
2109
                           AccessControl settings = DEFAULT);
2110

    
2111
  /**
2112
   * Returns an array containing the names of the enumerable properties
2113
   * of this object, including properties from prototype objects.  The
2114
   * array returned by this method contains the same values as would
2115
   * be enumerated by a for-in statement over this object.
2116
   */
2117
  Local<Array> GetPropertyNames();
2118

    
2119
  /**
2120
   * This function has the same functionality as GetPropertyNames but
2121
   * the returned array doesn't contain the names of properties from
2122
   * prototype objects.
2123
   */
2124
  Local<Array> GetOwnPropertyNames();
2125

    
2126
  /**
2127
   * Get the prototype object.  This does not skip objects marked to
2128
   * be skipped by __proto__ and it does not consult the security
2129
   * handler.
2130
   */
2131
  Local<Value> GetPrototype();
2132

    
2133
  /**
2134
   * Set the prototype object.  This does not skip objects marked to
2135
   * be skipped by __proto__ and it does not consult the security
2136
   * handler.
2137
   */
2138
  bool SetPrototype(Handle<Value> prototype);
2139

    
2140
  /**
2141
   * Finds an instance of the given function template in the prototype
2142
   * chain.
2143
   */
2144
  Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2145

    
2146
  /**
2147
   * Call builtin Object.prototype.toString on this object.
2148
   * This is different from Value::ToString() that may call
2149
   * user-defined toString function. This one does not.
2150
   */
2151
  Local<String> ObjectProtoToString();
2152

    
2153
  /**
2154
   * Returns the function invoked as a constructor for this object.
2155
   * May be the null value.
2156
   */
2157
  Local<Value> GetConstructor();
2158

    
2159
  /**
2160
   * Returns the name of the function invoked as a constructor for this object.
2161
   */
2162
  Local<String> GetConstructorName();
2163

    
2164
  /** Gets the number of internal fields for this Object. */
2165
  int InternalFieldCount();
2166

    
2167
  /** Gets the value from an internal field. */
2168
  V8_INLINE Local<Value> GetInternalField(int index);
2169

    
2170
  /** Sets the value in an internal field. */
2171
  void SetInternalField(int index, Handle<Value> value);
2172

    
2173
  /**
2174
   * Gets a 2-byte-aligned native pointer from an internal field. This field
2175
   * must have been set by SetAlignedPointerInInternalField, everything else
2176
   * leads to undefined behavior.
2177
   */
2178
  V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2179

    
2180
  /**
2181
   * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2182
   * a field, GetAlignedPointerFromInternalField must be used, everything else
2183
   * leads to undefined behavior.
2184
   */
2185
  void SetAlignedPointerInInternalField(int index, void* value);
2186

    
2187
  // Testers for local properties.
2188
  bool HasOwnProperty(Handle<String> key);
2189
  bool HasRealNamedProperty(Handle<String> key);
2190
  bool HasRealIndexedProperty(uint32_t index);
2191
  bool HasRealNamedCallbackProperty(Handle<String> key);
2192

    
2193
  /**
2194
   * If result.IsEmpty() no real property was located in the prototype chain.
2195
   * This means interceptors in the prototype chain are not called.
2196
   */
2197
  Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
2198

    
2199
  /**
2200
   * If result.IsEmpty() no real property was located on the object or
2201
   * in the prototype chain.
2202
   * This means interceptors in the prototype chain are not called.
2203
   */
2204
  Local<Value> GetRealNamedProperty(Handle<String> key);
2205

    
2206
  /** Tests for a named lookup interceptor.*/
2207
  bool HasNamedLookupInterceptor();
2208

    
2209
  /** Tests for an index lookup interceptor.*/
2210
  bool HasIndexedLookupInterceptor();
2211

    
2212
  /**
2213
   * Turns on access check on the object if the object is an instance of
2214
   * a template that has access check callbacks. If an object has no
2215
   * access check info, the object cannot be accessed by anyone.
2216
   */
2217
  void TurnOnAccessCheck();
2218

    
2219
  /**
2220
   * Returns the identity hash for this object. The current implementation
2221
   * uses a hidden property on the object to store the identity hash.
2222
   *
2223
   * The return value will never be 0. Also, it is not guaranteed to be
2224
   * unique.
2225
   */
2226
  int GetIdentityHash();
2227

    
2228
  /**
2229
   * Access hidden properties on JavaScript objects. These properties are
2230
   * hidden from the executing JavaScript and only accessible through the V8
2231
   * C++ API. Hidden properties introduced by V8 internally (for example the
2232
   * identity hash) are prefixed with "v8::".
2233
   */
2234
  bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2235
  Local<Value> GetHiddenValue(Handle<String> key);
2236
  bool DeleteHiddenValue(Handle<String> key);
2237

    
2238
  /**
2239
   * Returns true if this is an instance of an api function (one
2240
   * created from a function created from a function template) and has
2241
   * been modified since it was created.  Note that this method is
2242
   * conservative and may return true for objects that haven't actually
2243
   * been modified.
2244
   */
2245
  bool IsDirty();
2246

    
2247
  /**
2248
   * Clone this object with a fast but shallow copy.  Values will point
2249
   * to the same values as the original object.
2250
   */
2251
  Local<Object> Clone();
2252

    
2253
  /**
2254
   * Returns the context in which the object was created.
2255
   */
2256
  Local<Context> CreationContext();
2257

    
2258
  /**
2259
   * Set the backing store of the indexed properties to be managed by the
2260
   * embedding layer. Access to the indexed properties will follow the rules
2261
   * spelled out in CanvasPixelArray.
2262
   * Note: The embedding program still owns the data and needs to ensure that
2263
   *       the backing store is preserved while V8 has a reference.
2264
   */
2265
  void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2266
  bool HasIndexedPropertiesInPixelData();
2267
  uint8_t* GetIndexedPropertiesPixelData();
2268
  int GetIndexedPropertiesPixelDataLength();
2269

    
2270
  /**
2271
   * Set the backing store of the indexed properties to be managed by the
2272
   * embedding layer. Access to the indexed properties will follow the rules
2273
   * spelled out for the CanvasArray subtypes in the WebGL specification.
2274
   * Note: The embedding program still owns the data and needs to ensure that
2275
   *       the backing store is preserved while V8 has a reference.
2276
   */
2277
  void SetIndexedPropertiesToExternalArrayData(void* data,
2278
                                               ExternalArrayType array_type,
2279
                                               int number_of_elements);
2280
  bool HasIndexedPropertiesInExternalArrayData();
2281
  void* GetIndexedPropertiesExternalArrayData();
2282
  ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2283
  int GetIndexedPropertiesExternalArrayDataLength();
2284

    
2285
  /**
2286
   * Checks whether a callback is set by the
2287
   * ObjectTemplate::SetCallAsFunctionHandler method.
2288
   * When an Object is callable this method returns true.
2289
   */
2290
  bool IsCallable();
2291

    
2292
  /**
2293
   * Call an Object as a function if a callback is set by the
2294
   * ObjectTemplate::SetCallAsFunctionHandler method.
2295
   */
2296
  Local<Value> CallAsFunction(Handle<Value> recv,
2297
                              int argc,
2298
                              Handle<Value> argv[]);
2299

    
2300
  /**
2301
   * Call an Object as a constructor if a callback is set by the
2302
   * ObjectTemplate::SetCallAsFunctionHandler method.
2303
   * Note: This method behaves like the Function::NewInstance method.
2304
   */
2305
  Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2306

    
2307
  static Local<Object> New();
2308
  V8_INLINE static Object* Cast(Value* obj);
2309

    
2310
 private:
2311
  Object();
2312
  static void CheckCast(Value* obj);
2313
  Local<Value> SlowGetInternalField(int index);
2314
  void* SlowGetAlignedPointerFromInternalField(int index);
2315
};
2316

    
2317

    
2318
/**
2319
 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2320
 */
2321
class V8_EXPORT Array : public Object {
2322
 public:
2323
  uint32_t Length() const;
2324

    
2325
  /**
2326
   * Clones an element at index |index|.  Returns an empty
2327
   * handle if cloning fails (for any reason).
2328
   */
2329
  Local<Object> CloneElementAt(uint32_t index);
2330

    
2331
  /**
2332
   * Creates a JavaScript array with the given length. If the length
2333
   * is negative the returned array will have length 0.
2334
   */
2335
  static Local<Array> New(int length = 0);
2336

    
2337
  V8_INLINE static Array* Cast(Value* obj);
2338
 private:
2339
  Array();
2340
  static void CheckCast(Value* obj);
2341
};
2342

    
2343

    
2344
template<typename T>
2345
class ReturnValue {
2346
 public:
2347
  template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2348
      : value_(that.value_) {
2349
    TYPE_CHECK(T, S);
2350
  }
2351
  // Handle setters
2352
  template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2353
  template <typename S> V8_INLINE void Set(const Handle<S> handle);
2354
  // Fast primitive setters
2355
  V8_INLINE void Set(bool value);
2356
  V8_INLINE void Set(double i);
2357
  V8_INLINE void Set(int32_t i);
2358
  V8_INLINE void Set(uint32_t i);
2359
  // Fast JS primitive setters
2360
  V8_INLINE void SetNull();
2361
  V8_INLINE void SetUndefined();
2362
  V8_INLINE void SetEmptyString();
2363
  // Convenience getter for Isolate
2364
  V8_INLINE Isolate* GetIsolate();
2365

    
2366
 private:
2367
  template<class F> friend class ReturnValue;
2368
  template<class F> friend class FunctionCallbackInfo;
2369
  template<class F> friend class PropertyCallbackInfo;
2370
  V8_INLINE internal::Object* GetDefaultValue();
2371
  V8_INLINE explicit ReturnValue(internal::Object** slot);
2372
  internal::Object** value_;
2373
};
2374

    
2375

    
2376
/**
2377
 * The argument information given to function call callbacks.  This
2378
 * class provides access to information about the context of the call,
2379
 * including the receiver, the number and values of arguments, and
2380
 * the holder of the function.
2381
 */
2382
template<typename T>
2383
class FunctionCallbackInfo {
2384
 public:
2385
  V8_INLINE int Length() const;
2386
  V8_INLINE Local<Value> operator[](int i) const;
2387
  V8_INLINE Local<Function> Callee() const;
2388
  V8_INLINE Local<Object> This() const;
2389
  V8_INLINE Local<Object> Holder() const;
2390
  V8_INLINE bool IsConstructCall() const;
2391
  V8_INLINE Local<Value> Data() const;
2392
  V8_INLINE Isolate* GetIsolate() const;
2393
  V8_INLINE ReturnValue<T> GetReturnValue() const;
2394
  // This shouldn't be public, but the arm compiler needs it.
2395
  static const int kArgsLength = 7;
2396

    
2397
 protected:
2398
  friend class internal::FunctionCallbackArguments;
2399
  friend class internal::CustomArguments<FunctionCallbackInfo>;
2400
  static const int kHolderIndex = 0;
2401
  static const int kIsolateIndex = 1;
2402
  static const int kReturnValueDefaultValueIndex = 2;
2403
  static const int kReturnValueIndex = 3;
2404
  static const int kDataIndex = 4;
2405
  static const int kCalleeIndex = 5;
2406
  static const int kContextSaveIndex = 6;
2407

    
2408
  V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2409
                   internal::Object** values,
2410
                   int length,
2411
                   bool is_construct_call);
2412
  internal::Object** implicit_args_;
2413
  internal::Object** values_;
2414
  int length_;
2415
  bool is_construct_call_;
2416
};
2417

    
2418

    
2419
/**
2420
 * The information passed to a property callback about the context
2421
 * of the property access.
2422
 */
2423
template<typename T>
2424
class PropertyCallbackInfo {
2425
 public:
2426
  V8_INLINE Isolate* GetIsolate() const;
2427
  V8_INLINE Local<Value> Data() const;
2428
  V8_INLINE Local<Object> This() const;
2429
  V8_INLINE Local<Object> Holder() const;
2430
  V8_INLINE ReturnValue<T> GetReturnValue() const;
2431
  // This shouldn't be public, but the arm compiler needs it.
2432
  static const int kArgsLength = 6;
2433

    
2434
 protected:
2435
  friend class MacroAssembler;
2436
  friend class internal::PropertyCallbackArguments;
2437
  friend class internal::CustomArguments<PropertyCallbackInfo>;
2438
  static const int kHolderIndex = 0;
2439
  static const int kIsolateIndex = 1;
2440
  static const int kReturnValueDefaultValueIndex = 2;
2441
  static const int kReturnValueIndex = 3;
2442
  static const int kDataIndex = 4;
2443
  static const int kThisIndex = 5;
2444

    
2445
  V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2446
  internal::Object** args_;
2447
};
2448

    
2449

    
2450
typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2451

    
2452

    
2453
/**
2454
 * A JavaScript function object (ECMA-262, 15.3).
2455
 */
2456
class V8_EXPORT Function : public Object {
2457
 public:
2458
  /**
2459
   * Create a function in the current execution context
2460
   * for a given FunctionCallback.
2461
   */
2462
  static Local<Function> New(Isolate* isolate,
2463
                             FunctionCallback callback,
2464
                             Local<Value> data = Local<Value>(),
2465
                             int length = 0);
2466

    
2467
  Local<Object> NewInstance() const;
2468
  Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2469
  Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2470
  void SetName(Handle<String> name);
2471
  Handle<Value> GetName() const;
2472

    
2473
  /**
2474
   * Name inferred from variable or property assignment of this function.
2475
   * Used to facilitate debugging and profiling of JavaScript code written
2476
   * in an OO style, where many functions are anonymous but are assigned
2477
   * to object properties.
2478
   */
2479
  Handle<Value> GetInferredName() const;
2480

    
2481
  /**
2482
   * User-defined name assigned to the "displayName" property of this function.
2483
   * Used to facilitate debugging and profiling of JavaScript code.
2484
   */
2485
  Handle<Value> GetDisplayName() const;
2486

    
2487
  /**
2488
   * Returns zero based line number of function body and
2489
   * kLineOffsetNotFound if no information available.
2490
   */
2491
  int GetScriptLineNumber() const;
2492
  /**
2493
   * Returns zero based column number of function body and
2494
   * kLineOffsetNotFound if no information available.
2495
   */
2496
  int GetScriptColumnNumber() const;
2497

    
2498
  /**
2499
   * Tells whether this function is builtin.
2500
   */
2501
  bool IsBuiltin() const;
2502

    
2503
  /**
2504
   * Returns scriptId object.
2505
   */
2506
  V8_DEPRECATED("Use ScriptId instead", Handle<Value> GetScriptId()) const;
2507

    
2508
  /**
2509
   * Returns scriptId.
2510
   */
2511
  int ScriptId() const;
2512

    
2513
  ScriptOrigin GetScriptOrigin() const;
2514
  V8_INLINE static Function* Cast(Value* obj);
2515
  static const int kLineOffsetNotFound;
2516

    
2517
 private:
2518
  Function();
2519
  static void CheckCast(Value* obj);
2520
};
2521

    
2522
#ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
2523
// The number of required internal fields can be defined by embedder.
2524
#define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
2525
#endif
2526

    
2527
/**
2528
 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
2529
 * This API is experimental and may change significantly.
2530
 */
2531
class V8_EXPORT ArrayBuffer : public Object {
2532
 public:
2533
  /**
2534
   * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
2535
   * The allocator is a global V8 setting. It should be set with
2536
   * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
2537
   *
2538
   * This API is experimental and may change significantly.
2539
   */
2540
  class V8_EXPORT Allocator { // NOLINT
2541
   public:
2542
    virtual ~Allocator() {}
2543

    
2544
    /**
2545
     * Allocate |length| bytes. Return NULL if allocation is not successful.
2546
     * Memory should be initialized to zeroes.
2547
     */
2548
    virtual void* Allocate(size_t length) = 0;
2549

    
2550
    /**
2551
     * Allocate |length| bytes. Return NULL if allocation is not successful.
2552
     * Memory does not have to be initialized.
2553
     */
2554
    virtual void* AllocateUninitialized(size_t length) = 0;
2555
    /**
2556
     * Free the memory block of size |length|, pointed to by |data|.
2557
     * That memory is guaranteed to be previously allocated by |Allocate|.
2558
     */
2559
    virtual void Free(void* data, size_t length) = 0;
2560
  };
2561

    
2562
  /**
2563
   * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
2564
   * returns an instance of this class, populated, with a pointer to data
2565
   * and byte length.
2566
   *
2567
   * The Data pointer of ArrayBuffer::Contents is always allocated with
2568
   * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
2569
   *
2570
   * This API is experimental and may change significantly.
2571
   */
2572
  class V8_EXPORT Contents { // NOLINT
2573
   public:
2574
    Contents() : data_(NULL), byte_length_(0) {}
2575

    
2576
    void* Data() const { return data_; }
2577
    size_t ByteLength() const { return byte_length_; }
2578

    
2579
   private:
2580
    void* data_;
2581
    size_t byte_length_;
2582

    
2583
    friend class ArrayBuffer;
2584
  };
2585

    
2586

    
2587
  /**
2588
   * Data length in bytes.
2589
   */
2590
  size_t ByteLength() const;
2591

    
2592
  /**
2593
   * Create a new ArrayBuffer. Allocate |byte_length| bytes.
2594
   * Allocated memory will be owned by a created ArrayBuffer and
2595
   * will be deallocated when it is garbage-collected,
2596
   * unless the object is externalized.
2597
   */
2598
  static Local<ArrayBuffer> New(size_t byte_length);
2599

    
2600
  /**
2601
   * Create a new ArrayBuffer over an existing memory block.
2602
   * The created array buffer is immediately in externalized state.
2603
   * The memory block will not be reclaimed when a created ArrayBuffer
2604
   * is garbage-collected.
2605
   */
2606
  static Local<ArrayBuffer> New(void* data, size_t byte_length);
2607

    
2608
  /**
2609
   * Returns true if ArrayBuffer is extrenalized, that is, does not
2610
   * own its memory block.
2611
   */
2612
  bool IsExternal() const;
2613

    
2614
  /**
2615
   * Neuters this ArrayBuffer and all its views (typed arrays).
2616
   * Neutering sets the byte length of the buffer and all typed arrays to zero,
2617
   * preventing JavaScript from ever accessing underlying backing store.
2618
   * ArrayBuffer should have been externalized.
2619
   */
2620
  void Neuter();
2621

    
2622
  /**
2623
   * Make this ArrayBuffer external. The pointer to underlying memory block
2624
   * and byte length are returned as |Contents| structure. After ArrayBuffer
2625
   * had been etxrenalized, it does no longer owns the memory block. The caller
2626
   * should take steps to free memory when it is no longer needed.
2627
   *
2628
   * The memory block is guaranteed to be allocated with |Allocator::Allocate|
2629
   * that has been set with V8::SetArrayBufferAllocator.
2630
   */
2631
  Contents Externalize();
2632

    
2633
  V8_INLINE static ArrayBuffer* Cast(Value* obj);
2634

    
2635
  static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
2636

    
2637
 private:
2638
  ArrayBuffer();
2639
  static void CheckCast(Value* obj);
2640
};
2641

    
2642

    
2643
#ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
2644
// The number of required internal fields can be defined by embedder.
2645
#define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
2646
#endif
2647

    
2648

    
2649
/**
2650
 * A base class for an instance of one of "views" over ArrayBuffer,
2651
 * including TypedArrays and DataView (ES6 draft 15.13).
2652
 *
2653
 * This API is experimental and may change significantly.
2654
 */
2655
class V8_EXPORT ArrayBufferView : public Object {
2656
 public:
2657
  /**
2658
   * Returns underlying ArrayBuffer.
2659
   */
2660
  Local<ArrayBuffer> Buffer();
2661
  /**
2662
   * Byte offset in |Buffer|.
2663
   */
2664
  size_t ByteOffset();
2665
  /**
2666
   * Size of a view in bytes.
2667
   */
2668
  size_t ByteLength();
2669

    
2670
  V8_INLINE static ArrayBufferView* Cast(Value* obj);
2671

    
2672
  static const int kInternalFieldCount =
2673
      V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
2674

    
2675
 private:
2676
  ArrayBufferView();
2677
  static void CheckCast(Value* obj);
2678
};
2679

    
2680

    
2681
/**
2682
 * A base class for an instance of TypedArray series of constructors
2683
 * (ES6 draft 15.13.6).
2684
 * This API is experimental and may change significantly.
2685
 */
2686
class V8_EXPORT TypedArray : public ArrayBufferView {
2687
 public:
2688
  /**
2689
   * Number of elements in this typed array
2690
   * (e.g. for Int16Array, |ByteLength|/2).
2691
   */
2692
  size_t Length();
2693

    
2694
  V8_INLINE static TypedArray* Cast(Value* obj);
2695

    
2696
 private:
2697
  TypedArray();
2698
  static void CheckCast(Value* obj);
2699
};
2700

    
2701

    
2702
/**
2703
 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
2704
 * This API is experimental and may change significantly.
2705
 */
2706
class V8_EXPORT Uint8Array : public TypedArray {
2707
 public:
2708
  static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
2709
                               size_t byte_offset, size_t length);
2710
  V8_INLINE static Uint8Array* Cast(Value* obj);
2711

    
2712
 private:
2713
  Uint8Array();
2714
  static void CheckCast(Value* obj);
2715
};
2716

    
2717

    
2718
/**
2719
 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
2720
 * This API is experimental and may change significantly.
2721
 */
2722
class V8_EXPORT Uint8ClampedArray : public TypedArray {
2723
 public:
2724
  static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
2725
                               size_t byte_offset, size_t length);
2726
  V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
2727

    
2728
 private:
2729
  Uint8ClampedArray();
2730
  static void CheckCast(Value* obj);
2731
};
2732

    
2733
/**
2734
 * An instance of Int8Array constructor (ES6 draft 15.13.6).
2735
 * This API is experimental and may change significantly.
2736
 */
2737
class V8_EXPORT Int8Array : public TypedArray {
2738
 public:
2739
  static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
2740
                               size_t byte_offset, size_t length);
2741
  V8_INLINE static Int8Array* Cast(Value* obj);
2742

    
2743
 private:
2744
  Int8Array();
2745
  static void CheckCast(Value* obj);
2746
};
2747

    
2748

    
2749
/**
2750
 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
2751
 * This API is experimental and may change significantly.
2752
 */
2753
class V8_EXPORT Uint16Array : public TypedArray {
2754
 public:
2755
  static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
2756
                               size_t byte_offset, size_t length);
2757
  V8_INLINE static Uint16Array* Cast(Value* obj);
2758

    
2759
 private:
2760
  Uint16Array();
2761
  static void CheckCast(Value* obj);
2762
};
2763

    
2764

    
2765
/**
2766
 * An instance of Int16Array constructor (ES6 draft 15.13.6).
2767
 * This API is experimental and may change significantly.
2768
 */
2769
class V8_EXPORT Int16Array : public TypedArray {
2770
 public:
2771
  static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
2772
                               size_t byte_offset, size_t length);
2773
  V8_INLINE static Int16Array* Cast(Value* obj);
2774

    
2775
 private:
2776
  Int16Array();
2777
  static void CheckCast(Value* obj);
2778
};
2779

    
2780

    
2781
/**
2782
 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
2783
 * This API is experimental and may change significantly.
2784
 */
2785
class V8_EXPORT Uint32Array : public TypedArray {
2786
 public:
2787
  static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
2788
                               size_t byte_offset, size_t length);
2789
  V8_INLINE static Uint32Array* Cast(Value* obj);
2790

    
2791
 private:
2792
  Uint32Array();
2793
  static void CheckCast(Value* obj);
2794
};
2795

    
2796

    
2797
/**
2798
 * An instance of Int32Array constructor (ES6 draft 15.13.6).
2799
 * This API is experimental and may change significantly.
2800
 */
2801
class V8_EXPORT Int32Array : public TypedArray {
2802
 public:
2803
  static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
2804
                               size_t byte_offset, size_t length);
2805
  V8_INLINE static Int32Array* Cast(Value* obj);
2806

    
2807
 private:
2808
  Int32Array();
2809
  static void CheckCast(Value* obj);
2810
};
2811

    
2812

    
2813
/**
2814
 * An instance of Float32Array constructor (ES6 draft 15.13.6).
2815
 * This API is experimental and may change significantly.
2816
 */
2817
class V8_EXPORT Float32Array : public TypedArray {
2818
 public:
2819
  static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
2820
                               size_t byte_offset, size_t length);
2821
  V8_INLINE static Float32Array* Cast(Value* obj);
2822

    
2823
 private:
2824
  Float32Array();
2825
  static void CheckCast(Value* obj);
2826
};
2827

    
2828

    
2829
/**
2830
 * An instance of Float64Array constructor (ES6 draft 15.13.6).
2831
 * This API is experimental and may change significantly.
2832
 */
2833
class V8_EXPORT Float64Array : public TypedArray {
2834
 public:
2835
  static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
2836
                               size_t byte_offset, size_t length);
2837
  V8_INLINE static Float64Array* Cast(Value* obj);
2838

    
2839
 private:
2840
  Float64Array();
2841
  static void CheckCast(Value* obj);
2842
};
2843

    
2844

    
2845
/**
2846
 * An instance of DataView constructor (ES6 draft 15.13.7).
2847
 * This API is experimental and may change significantly.
2848
 */
2849
class V8_EXPORT DataView : public ArrayBufferView {
2850
 public:
2851
  static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
2852
                             size_t byte_offset, size_t length);
2853
  V8_INLINE static DataView* Cast(Value* obj);
2854

    
2855
 private:
2856
  DataView();
2857
  static void CheckCast(Value* obj);
2858
};
2859

    
2860

    
2861
/**
2862
 * An instance of the built-in Date constructor (ECMA-262, 15.9).
2863
 */
2864
class V8_EXPORT Date : public Object {
2865
 public:
2866
  static Local<Value> New(double time);
2867

    
2868
  V8_DEPRECATED(
2869
      "Use ValueOf instead",
2870
      double NumberValue()) const { return ValueOf(); }
2871

    
2872
  /**
2873
   * A specialization of Value::NumberValue that is more efficient
2874
   * because we know the structure of this object.
2875
   */
2876
  double ValueOf() const;
2877

    
2878
  V8_INLINE static Date* Cast(v8::Value* obj);
2879

    
2880
  /**
2881
   * Notification that the embedder has changed the time zone,
2882
   * daylight savings time, or other date / time configuration
2883
   * parameters.  V8 keeps a cache of various values used for
2884
   * date / time computation.  This notification will reset
2885
   * those cached values for the current context so that date /
2886
   * time configuration changes would be reflected in the Date
2887
   * object.
2888
   *
2889
   * This API should not be called more than needed as it will
2890
   * negatively impact the performance of date operations.
2891
   */
2892
  static void DateTimeConfigurationChangeNotification();
2893

    
2894
 private:
2895
  static void CheckCast(v8::Value* obj);
2896
};
2897

    
2898

    
2899
/**
2900
 * A Number object (ECMA-262, 4.3.21).
2901
 */
2902
class V8_EXPORT NumberObject : public Object {
2903
 public:
2904
  static Local<Value> New(double value);
2905

    
2906
  V8_DEPRECATED(
2907
      "Use ValueOf instead",
2908
      double NumberValue()) const { return ValueOf(); }
2909

    
2910
  /**
2911
   * Returns the Number held by the object.
2912
   */
2913
  double ValueOf() const;
2914

    
2915
  V8_INLINE static NumberObject* Cast(v8::Value* obj);
2916

    
2917
 private:
2918
  static void CheckCast(v8::Value* obj);
2919
};
2920

    
2921

    
2922
/**
2923
 * A Boolean object (ECMA-262, 4.3.15).
2924
 */
2925
class V8_EXPORT BooleanObject : public Object {
2926
 public:
2927
  static Local<Value> New(bool value);
2928

    
2929
  V8_DEPRECATED(
2930
      "Use ValueOf instead",
2931
      bool BooleanValue()) const { return ValueOf(); }
2932

    
2933
  /**
2934
   * Returns the Boolean held by the object.
2935
   */
2936
  bool ValueOf() const;
2937

    
2938
  V8_INLINE static BooleanObject* Cast(v8::Value* obj);
2939

    
2940
 private:
2941
  static void CheckCast(v8::Value* obj);
2942
};
2943

    
2944

    
2945
/**
2946
 * A String object (ECMA-262, 4.3.18).
2947
 */
2948
class V8_EXPORT StringObject : public Object {
2949
 public:
2950
  static Local<Value> New(Handle<String> value);
2951

    
2952
  V8_DEPRECATED(
2953
      "Use ValueOf instead",
2954
      Local<String> StringValue()) const { return ValueOf(); }
2955

    
2956
  /**
2957
   * Returns the String held by the object.
2958
   */
2959
  Local<String> ValueOf() const;
2960

    
2961
  V8_INLINE static StringObject* Cast(v8::Value* obj);
2962

    
2963
 private:
2964
  static void CheckCast(v8::Value* obj);
2965
};
2966

    
2967

    
2968
/**
2969
 * A Symbol object (ECMA-262 edition 6).
2970
 *
2971
 * This is an experimental feature. Use at your own risk.
2972
 */
2973
class V8_EXPORT SymbolObject : public Object {
2974
 public:
2975
  static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
2976

    
2977
  V8_DEPRECATED(
2978
      "Use ValueOf instead",
2979
      Local<Symbol> SymbolValue()) const { return ValueOf(); }
2980

    
2981
  /**
2982
   * Returns the Symbol held by the object.
2983
   */
2984
  Local<Symbol> ValueOf() const;
2985

    
2986
  V8_INLINE static SymbolObject* Cast(v8::Value* obj);
2987

    
2988
 private:
2989
  static void CheckCast(v8::Value* obj);
2990
};
2991

    
2992

    
2993
/**
2994
 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
2995
 */
2996
class V8_EXPORT RegExp : public Object {
2997
 public:
2998
  /**
2999
   * Regular expression flag bits. They can be or'ed to enable a set
3000
   * of flags.
3001
   */
3002
  enum Flags {
3003
    kNone = 0,
3004
    kGlobal = 1,
3005
    kIgnoreCase = 2,
3006
    kMultiline = 4
3007
  };
3008

    
3009
  /**
3010
   * Creates a regular expression from the given pattern string and
3011
   * the flags bit field. May throw a JavaScript exception as
3012
   * described in ECMA-262, 15.10.4.1.
3013
   *
3014
   * For example,
3015
   *   RegExp::New(v8::String::New("foo"),
3016
   *               static_cast<RegExp::Flags>(kGlobal | kMultiline))
3017
   * is equivalent to evaluating "/foo/gm".
3018
   */
3019
  static Local<RegExp> New(Handle<String> pattern, Flags flags);
3020

    
3021
  /**
3022
   * Returns the value of the source property: a string representing
3023
   * the regular expression.
3024
   */
3025
  Local<String> GetSource() const;
3026

    
3027
  /**
3028
   * Returns the flags bit field.
3029
   */
3030
  Flags GetFlags() const;
3031

    
3032
  V8_INLINE static RegExp* Cast(v8::Value* obj);
3033

    
3034
 private:
3035
  static void CheckCast(v8::Value* obj);
3036
};
3037

    
3038

    
3039
/**
3040
 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3041
 * to associate C++ data structures with JavaScript objects.
3042
 */
3043
class V8_EXPORT External : public Value {
3044
 public:
3045
  static Local<External> New(void* value);
3046
  V8_INLINE static External* Cast(Value* obj);
3047
  void* Value() const;
3048
 private:
3049
  static void CheckCast(v8::Value* obj);
3050
};
3051

    
3052

    
3053
// --- Templates ---
3054

    
3055

    
3056
/**
3057
 * The superclass of object and function templates.
3058
 */
3059
class V8_EXPORT Template : public Data {
3060
 public:
3061
  /** Adds a property to each instance created by this template.*/
3062
  void Set(Handle<String> name, Handle<Data> value,
3063
           PropertyAttribute attributes = None);
3064
  V8_INLINE void Set(const char* name, Handle<Data> value);
3065

    
3066
  void SetAccessorProperty(
3067
     Local<String> name,
3068
     Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3069
     Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3070
     PropertyAttribute attribute = None,
3071
     AccessControl settings = DEFAULT);
3072

    
3073
  /**
3074
   * Whenever the property with the given name is accessed on objects
3075
   * created from this Template the getter and setter callbacks
3076
   * are called instead of getting and setting the property directly
3077
   * on the JavaScript object.
3078
   *
3079
   * \param name The name of the property for which an accessor is added.
3080
   * \param getter The callback to invoke when getting the property.
3081
   * \param setter The callback to invoke when setting the property.
3082
   * \param data A piece of data that will be passed to the getter and setter
3083
   *   callbacks whenever they are invoked.
3084
   * \param settings Access control settings for the accessor. This is a bit
3085
   *   field consisting of one of more of
3086
   *   DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3087
   *   The default is to not allow cross-context access.
3088
   *   ALL_CAN_READ means that all cross-context reads are allowed.
3089
   *   ALL_CAN_WRITE means that all cross-context writes are allowed.
3090
   *   The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3091
   *   cross-context access.
3092
   * \param attribute The attributes of the property for which an accessor
3093
   *   is added.
3094
   * \param signature The signature describes valid receivers for the accessor
3095
   *   and is used to perform implicit instance checks against them. If the
3096
   *   receiver is incompatible (i.e. is not an instance of the constructor as
3097
   *   defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3098
   *   thrown and no callback is invoked.
3099
   */
3100
  void SetNativeDataProperty(Local<String> name,
3101
                             AccessorGetterCallback getter,
3102
                             AccessorSetterCallback setter = 0,
3103
                             // TODO(dcarney): gcc can't handle Local below
3104
                             Handle<Value> data = Handle<Value>(),
3105
                             PropertyAttribute attribute = None,
3106
                             Local<AccessorSignature> signature =
3107
                                 Local<AccessorSignature>(),
3108
                             AccessControl settings = DEFAULT);
3109

    
3110
  // This function is not yet stable and should not be used at this time.
3111
  bool SetDeclaredAccessor(Local<String> name,
3112
                           Local<DeclaredAccessorDescriptor> descriptor,
3113
                           PropertyAttribute attribute = None,
3114
                           Local<AccessorSignature> signature =
3115
                               Local<AccessorSignature>(),
3116
                           AccessControl settings = DEFAULT);
3117

    
3118
 private:
3119
  Template();
3120

    
3121
  friend class ObjectTemplate;
3122
  friend class FunctionTemplate;
3123
};
3124

    
3125

    
3126
/**
3127
 * NamedProperty[Getter|Setter] are used as interceptors on object.
3128
 * See ObjectTemplate::SetNamedPropertyHandler.
3129
 */
3130
typedef void (*NamedPropertyGetterCallback)(
3131
    Local<String> property,
3132
    const PropertyCallbackInfo<Value>& info);
3133

    
3134

    
3135
/**
3136
 * Returns the value if the setter intercepts the request.
3137
 * Otherwise, returns an empty handle.
3138
 */
3139
typedef void (*NamedPropertySetterCallback)(
3140
    Local<String> property,
3141
    Local<Value> value,
3142
    const PropertyCallbackInfo<Value>& info);
3143

    
3144

    
3145
/**
3146
 * Returns a non-empty handle if the interceptor intercepts the request.
3147
 * The result is an integer encoding property attributes (like v8::None,
3148
 * v8::DontEnum, etc.)
3149
 */
3150
typedef void (*NamedPropertyQueryCallback)(
3151
    Local<String> property,
3152
    const PropertyCallbackInfo<Integer>& info);
3153

    
3154

    
3155
/**
3156
 * Returns a non-empty handle if the deleter intercepts the request.
3157
 * The return value is true if the property could be deleted and false
3158
 * otherwise.
3159
 */
3160
typedef void (*NamedPropertyDeleterCallback)(
3161
    Local<String> property,
3162
    const PropertyCallbackInfo<Boolean>& info);
3163

    
3164

    
3165
/**
3166
 * Returns an array containing the names of the properties the named
3167
 * property getter intercepts.
3168
 */
3169
typedef void (*NamedPropertyEnumeratorCallback)(
3170
    const PropertyCallbackInfo<Array>& info);
3171

    
3172

    
3173
/**
3174
 * Returns the value of the property if the getter intercepts the
3175
 * request.  Otherwise, returns an empty handle.
3176
 */
3177
typedef void (*IndexedPropertyGetterCallback)(
3178
    uint32_t index,
3179
    const PropertyCallbackInfo<Value>& info);
3180

    
3181

    
3182
/**
3183
 * Returns the value if the setter intercepts the request.
3184
 * Otherwise, returns an empty handle.
3185
 */
3186
typedef void (*IndexedPropertySetterCallback)(
3187
    uint32_t index,
3188
    Local<Value> value,
3189
    const PropertyCallbackInfo<Value>& info);
3190

    
3191

    
3192
/**
3193
 * Returns a non-empty handle if the interceptor intercepts the request.
3194
 * The result is an integer encoding property attributes.
3195
 */
3196
typedef void (*IndexedPropertyQueryCallback)(
3197
    uint32_t index,
3198
    const PropertyCallbackInfo<Integer>& info);
3199

    
3200

    
3201
/**
3202
 * Returns a non-empty handle if the deleter intercepts the request.
3203
 * The return value is true if the property could be deleted and false
3204
 * otherwise.
3205
 */
3206
typedef void (*IndexedPropertyDeleterCallback)(
3207
    uint32_t index,
3208
    const PropertyCallbackInfo<Boolean>& info);
3209

    
3210

    
3211
/**
3212
 * Returns an array containing the indices of the properties the
3213
 * indexed property getter intercepts.
3214
 */
3215
typedef void (*IndexedPropertyEnumeratorCallback)(
3216
    const PropertyCallbackInfo<Array>& info);
3217

    
3218

    
3219
/**
3220
 * Access type specification.
3221
 */
3222
enum AccessType {
3223
  ACCESS_GET,
3224
  ACCESS_SET,
3225
  ACCESS_HAS,
3226
  ACCESS_DELETE,
3227
  ACCESS_KEYS
3228
};
3229

    
3230

    
3231
/**
3232
 * Returns true if cross-context access should be allowed to the named
3233
 * property with the given key on the host object.
3234
 */
3235
typedef bool (*NamedSecurityCallback)(Local<Object> host,
3236
                                      Local<Value> key,
3237
                                      AccessType type,
3238
                                      Local<Value> data);
3239

    
3240

    
3241
/**
3242
 * Returns true if cross-context access should be allowed to the indexed
3243
 * property with the given index on the host object.
3244
 */
3245
typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3246
                                        uint32_t index,
3247
                                        AccessType type,
3248
                                        Local<Value> data);
3249

    
3250

    
3251
/**
3252
 * A FunctionTemplate is used to create functions at runtime. There
3253
 * can only be one function created from a FunctionTemplate in a
3254
 * context.  The lifetime of the created function is equal to the
3255
 * lifetime of the context.  So in case the embedder needs to create
3256
 * temporary functions that can be collected using Scripts is
3257
 * preferred.
3258
 *
3259
 * A FunctionTemplate can have properties, these properties are added to the
3260
 * function object when it is created.
3261
 *
3262
 * A FunctionTemplate has a corresponding instance template which is
3263
 * used to create object instances when the function is used as a
3264
 * constructor. Properties added to the instance template are added to
3265
 * each object instance.
3266
 *
3267
 * A FunctionTemplate can have a prototype template. The prototype template
3268
 * is used to create the prototype object of the function.
3269
 *
3270
 * The following example shows how to use a FunctionTemplate:
3271
 *
3272
 * \code
3273
 *    v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3274
 *    t->Set("func_property", v8::Number::New(1));
3275
 *
3276
 *    v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3277
 *    proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3278
 *    proto_t->Set("proto_const", v8::Number::New(2));
3279
 *
3280
 *    v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3281
 *    instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3282
 *    instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3283
 *    instance_t->Set("instance_property", Number::New(3));
3284
 *
3285
 *    v8::Local<v8::Function> function = t->GetFunction();
3286
 *    v8::Local<v8::Object> instance = function->NewInstance();
3287
 * \endcode
3288
 *
3289
 * Let's use "function" as the JS variable name of the function object
3290
 * and "instance" for the instance object created above.  The function
3291
 * and the instance will have the following properties:
3292
 *
3293
 * \code
3294
 *   func_property in function == true;
3295
 *   function.func_property == 1;
3296
 *
3297
 *   function.prototype.proto_method() invokes 'InvokeCallback'
3298
 *   function.prototype.proto_const == 2;
3299
 *
3300
 *   instance instanceof function == true;
3301
 *   instance.instance_accessor calls 'InstanceAccessorCallback'
3302
 *   instance.instance_property == 3;
3303
 * \endcode
3304
 *
3305
 * A FunctionTemplate can inherit from another one by calling the
3306
 * FunctionTemplate::Inherit method.  The following graph illustrates
3307
 * the semantics of inheritance:
3308
 *
3309
 * \code
3310
 *   FunctionTemplate Parent  -> Parent() . prototype -> { }
3311
 *     ^                                                  ^
3312
 *     | Inherit(Parent)                                  | .__proto__
3313
 *     |                                                  |
3314
 *   FunctionTemplate Child   -> Child()  . prototype -> { }
3315
 * \endcode
3316
 *
3317
 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3318
 * object of the Child() function has __proto__ pointing to the
3319
 * Parent() function's prototype object. An instance of the Child
3320
 * function has all properties on Parent's instance templates.
3321
 *
3322
 * Let Parent be the FunctionTemplate initialized in the previous
3323
 * section and create a Child FunctionTemplate by:
3324
 *
3325
 * \code
3326
 *   Local<FunctionTemplate> parent = t;
3327
 *   Local<FunctionTemplate> child = FunctionTemplate::New();
3328
 *   child->Inherit(parent);
3329
 *
3330
 *   Local<Function> child_function = child->GetFunction();
3331
 *   Local<Object> child_instance = child_function->NewInstance();
3332
 * \endcode
3333
 *
3334
 * The Child function and Child instance will have the following
3335
 * properties:
3336
 *
3337
 * \code
3338
 *   child_func.prototype.__proto__ == function.prototype;
3339
 *   child_instance.instance_accessor calls 'InstanceAccessorCallback'
3340
 *   child_instance.instance_property == 3;
3341
 * \endcode
3342
 */
3343
class V8_EXPORT FunctionTemplate : public Template {
3344
 public:
3345
  /** Creates a function template.*/
3346
  static Local<FunctionTemplate> New(
3347
      FunctionCallback callback = 0,
3348
      Handle<Value> data = Handle<Value>(),
3349
      Handle<Signature> signature = Handle<Signature>(),
3350
      int length = 0);
3351

    
3352
  /** Returns the unique function instance in the current execution context.*/
3353
  Local<Function> GetFunction();
3354

    
3355
  /**
3356
   * Set the call-handler callback for a FunctionTemplate.  This
3357
   * callback is called whenever the function created from this
3358
   * FunctionTemplate is called.
3359
   */
3360
  void SetCallHandler(FunctionCallback callback,
3361
                      Handle<Value> data = Handle<Value>());
3362

    
3363
  /** Set the predefined length property for the FunctionTemplate. */
3364
  void SetLength(int length);
3365

    
3366
  /** Get the InstanceTemplate. */
3367
  Local<ObjectTemplate> InstanceTemplate();
3368

    
3369
  /** Causes the function template to inherit from a parent function template.*/
3370
  void Inherit(Handle<FunctionTemplate> parent);
3371

    
3372
  /**
3373
   * A PrototypeTemplate is the template used to create the prototype object
3374
   * of the function created by this template.
3375
   */
3376
  Local<ObjectTemplate> PrototypeTemplate();
3377

    
3378
  /**
3379
   * Set the class name of the FunctionTemplate.  This is used for
3380
   * printing objects created with the function created from the
3381
   * FunctionTemplate as its constructor.
3382
   */
3383
  void SetClassName(Handle<String> name);
3384

    
3385
  /**
3386
   * Determines whether the __proto__ accessor ignores instances of
3387
   * the function template.  If instances of the function template are
3388
   * ignored, __proto__ skips all instances and instead returns the
3389
   * next object in the prototype chain.
3390
   *
3391
   * Call with a value of true to make the __proto__ accessor ignore
3392
   * instances of the function template.  Call with a value of false
3393
   * to make the __proto__ accessor not ignore instances of the
3394
   * function template.  By default, instances of a function template
3395
   * are not ignored.
3396
   */
3397
  void SetHiddenPrototype(bool value);
3398

    
3399
  /**
3400
   * Sets the ReadOnly flag in the attributes of the 'prototype' property
3401
   * of functions created from this FunctionTemplate to true.
3402
   */
3403
  void ReadOnlyPrototype();
3404

    
3405
  /**
3406
   * Removes the prototype property from functions created from this
3407
   * FunctionTemplate.
3408
   */
3409
  void RemovePrototype();
3410

    
3411
  /**
3412
   * Returns true if the given object is an instance of this function
3413
   * template.
3414
   */
3415
  bool HasInstance(Handle<Value> object);
3416

    
3417
 private:
3418
  FunctionTemplate();
3419
  friend class Context;
3420
  friend class ObjectTemplate;
3421
};
3422

    
3423

    
3424
/**
3425
 * An ObjectTemplate is used to create objects at runtime.
3426
 *
3427
 * Properties added to an ObjectTemplate are added to each object
3428
 * created from the ObjectTemplate.
3429
 */
3430
class V8_EXPORT ObjectTemplate : public Template {
3431
 public:
3432
  /** Creates an ObjectTemplate. */
3433
  static Local<ObjectTemplate> New();
3434

    
3435
  /** Creates a new instance of this template.*/
3436
  Local<Object> NewInstance();
3437

    
3438
  /**
3439
   * Sets an accessor on the object template.
3440
   *
3441
   * Whenever the property with the given name is accessed on objects
3442
   * created from this ObjectTemplate the getter and setter callbacks
3443
   * are called instead of getting and setting the property directly
3444
   * on the JavaScript object.
3445
   *
3446
   * \param name The name of the property for which an accessor is added.
3447
   * \param getter The callback to invoke when getting the property.
3448
   * \param setter The callback to invoke when setting the property.
3449
   * \param data A piece of data that will be passed to the getter and setter
3450
   *   callbacks whenever they are invoked.
3451
   * \param settings Access control settings for the accessor. This is a bit
3452
   *   field consisting of one of more of
3453
   *   DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3454
   *   The default is to not allow cross-context access.
3455
   *   ALL_CAN_READ means that all cross-context reads are allowed.
3456
   *   ALL_CAN_WRITE means that all cross-context writes are allowed.
3457
   *   The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3458
   *   cross-context access.
3459
   * \param attribute The attributes of the property for which an accessor
3460
   *   is added.
3461
   * \param signature The signature describes valid receivers for the accessor
3462
   *   and is used to perform implicit instance checks against them. If the
3463
   *   receiver is incompatible (i.e. is not an instance of the constructor as
3464
   *   defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3465
   *   thrown and no callback is invoked.
3466
   */
3467
  void SetAccessor(Handle<String> name,
3468
                   AccessorGetterCallback getter,
3469
                   AccessorSetterCallback setter = 0,
3470
                   Handle<Value> data = Handle<Value>(),
3471
                   AccessControl settings = DEFAULT,
3472
                   PropertyAttribute attribute = None,
3473
                   Handle<AccessorSignature> signature =
3474
                       Handle<AccessorSignature>());
3475

    
3476
  /**
3477
   * Sets a named property handler on the object template.
3478
   *
3479
   * Whenever a named property is accessed on objects created from
3480
   * this object template, the provided callback is invoked instead of
3481
   * accessing the property directly on the JavaScript object.
3482
   *
3483
   * \param getter The callback to invoke when getting a property.
3484
   * \param setter The callback to invoke when setting a property.
3485
   * \param query The callback to invoke to check if a property is present,
3486
   *   and if present, get its attributes.
3487
   * \param deleter The callback to invoke when deleting a property.
3488
   * \param enumerator The callback to invoke to enumerate all the named
3489
   *   properties of an object.
3490
   * \param data A piece of data that will be passed to the callbacks
3491
   *   whenever they are invoked.
3492
   */
3493
  void SetNamedPropertyHandler(
3494
      NamedPropertyGetterCallback getter,
3495
      NamedPropertySetterCallback setter = 0,
3496
      NamedPropertyQueryCallback query = 0,
3497
      NamedPropertyDeleterCallback deleter = 0,
3498
      NamedPropertyEnumeratorCallback enumerator = 0,
3499
      Handle<Value> data = Handle<Value>());
3500

    
3501
  /**
3502
   * Sets an indexed property handler on the object template.
3503
   *
3504
   * Whenever an indexed property is accessed on objects created from
3505
   * this object template, the provided callback is invoked instead of
3506
   * accessing the property directly on the JavaScript object.
3507
   *
3508
   * \param getter The callback to invoke when getting a property.
3509
   * \param setter The callback to invoke when setting a property.
3510
   * \param query The callback to invoke to check if an object has a property.
3511
   * \param deleter The callback to invoke when deleting a property.
3512
   * \param enumerator The callback to invoke to enumerate all the indexed
3513
   *   properties of an object.
3514
   * \param data A piece of data that will be passed to the callbacks
3515
   *   whenever they are invoked.
3516
   */
3517
  void SetIndexedPropertyHandler(
3518
      IndexedPropertyGetterCallback getter,
3519
      IndexedPropertySetterCallback setter = 0,
3520
      IndexedPropertyQueryCallback query = 0,
3521
      IndexedPropertyDeleterCallback deleter = 0,
3522
      IndexedPropertyEnumeratorCallback enumerator = 0,
3523
      Handle<Value> data = Handle<Value>());
3524

    
3525
  /**
3526
   * Sets the callback to be used when calling instances created from
3527
   * this template as a function.  If no callback is set, instances
3528
   * behave like normal JavaScript objects that cannot be called as a
3529
   * function.
3530
   */
3531
  void SetCallAsFunctionHandler(FunctionCallback callback,
3532
                                Handle<Value> data = Handle<Value>());
3533

    
3534
  /**
3535
   * Mark object instances of the template as undetectable.
3536
   *
3537
   * In many ways, undetectable objects behave as though they are not
3538
   * there.  They behave like 'undefined' in conditionals and when
3539
   * printed.  However, properties can be accessed and called as on
3540
   * normal objects.
3541
   */
3542
  void MarkAsUndetectable();
3543

    
3544
  /**
3545
   * Sets access check callbacks on the object template.
3546
   *
3547
   * When accessing properties on instances of this object template,
3548
   * the access check callback will be called to determine whether or
3549
   * not to allow cross-context access to the properties.
3550
   * The last parameter specifies whether access checks are turned
3551
   * on by default on instances. If access checks are off by default,
3552
   * they can be turned on on individual instances by calling
3553
   * Object::TurnOnAccessCheck().
3554
   */
3555
  void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
3556
                               IndexedSecurityCallback indexed_handler,
3557
                               Handle<Value> data = Handle<Value>(),
3558
                               bool turned_on_by_default = true);
3559

    
3560
  /**
3561
   * Gets the number of internal fields for objects generated from
3562
   * this template.
3563
   */
3564
  int InternalFieldCount();
3565

    
3566
  /**
3567
   * Sets the number of internal fields for objects generated from
3568
   * this template.
3569
   */
3570
  void SetInternalFieldCount(int value);
3571

    
3572
 private:
3573
  ObjectTemplate();
3574
  static Local<ObjectTemplate> New(Handle<FunctionTemplate> constructor);
3575
  friend class FunctionTemplate;
3576
};
3577

    
3578

    
3579
/**
3580
 * A Signature specifies which receivers and arguments are valid
3581
 * parameters to a function.
3582
 */
3583
class V8_EXPORT Signature : public Data {
3584
 public:
3585
  static Local<Signature> New(Handle<FunctionTemplate> receiver =
3586
                                  Handle<FunctionTemplate>(),
3587
                              int argc = 0,
3588
                              Handle<FunctionTemplate> argv[] = 0);
3589
 private:
3590
  Signature();
3591
};
3592

    
3593

    
3594
/**
3595
 * An AccessorSignature specifies which receivers are valid parameters
3596
 * to an accessor callback.
3597
 */
3598
class V8_EXPORT AccessorSignature : public Data {
3599
 public:
3600
  static Local<AccessorSignature> New(Handle<FunctionTemplate> receiver =
3601
                                          Handle<FunctionTemplate>());
3602
 private:
3603
  AccessorSignature();
3604
};
3605

    
3606

    
3607
class V8_EXPORT DeclaredAccessorDescriptor : public Data {
3608
 private:
3609
  DeclaredAccessorDescriptor();
3610
};
3611

    
3612

    
3613
class V8_EXPORT ObjectOperationDescriptor : public Data {
3614
 public:
3615
  // This function is not yet stable and should not be used at this time.
3616
  static Local<RawOperationDescriptor> NewInternalFieldDereference(
3617
      Isolate* isolate,
3618
      int internal_field);
3619
 private:
3620
  ObjectOperationDescriptor();
3621
};
3622

    
3623

    
3624
enum DeclaredAccessorDescriptorDataType {
3625
    kDescriptorBoolType,
3626
    kDescriptorInt8Type, kDescriptorUint8Type,
3627
    kDescriptorInt16Type, kDescriptorUint16Type,
3628
    kDescriptorInt32Type, kDescriptorUint32Type,
3629
    kDescriptorFloatType, kDescriptorDoubleType
3630
};
3631

    
3632

    
3633
class V8_EXPORT RawOperationDescriptor : public Data {
3634
 public:
3635
  Local<DeclaredAccessorDescriptor> NewHandleDereference(Isolate* isolate);
3636
  Local<RawOperationDescriptor> NewRawDereference(Isolate* isolate);
3637
  Local<RawOperationDescriptor> NewRawShift(Isolate* isolate,
3638
                                            int16_t byte_offset);
3639
  Local<DeclaredAccessorDescriptor> NewPointerCompare(Isolate* isolate,
3640
                                                      void* compare_value);
3641
  Local<DeclaredAccessorDescriptor> NewPrimitiveValue(
3642
      Isolate* isolate,
3643
      DeclaredAccessorDescriptorDataType data_type,
3644
      uint8_t bool_offset = 0);
3645
  Local<DeclaredAccessorDescriptor> NewBitmaskCompare8(Isolate* isolate,
3646
                                                       uint8_t bitmask,
3647
                                                       uint8_t compare_value);
3648
  Local<DeclaredAccessorDescriptor> NewBitmaskCompare16(
3649
      Isolate* isolate,
3650
      uint16_t bitmask,
3651
      uint16_t compare_value);
3652
  Local<DeclaredAccessorDescriptor> NewBitmaskCompare32(
3653
      Isolate* isolate,
3654
      uint32_t bitmask,
3655
      uint32_t compare_value);
3656

    
3657
 private:
3658
  RawOperationDescriptor();
3659
};
3660

    
3661

    
3662
/**
3663
 * A utility for determining the type of objects based on the template
3664
 * they were constructed from.
3665
 */
3666
class V8_EXPORT TypeSwitch : public Data {
3667
 public:
3668
  static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
3669
  static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
3670
  int match(Handle<Value> value);
3671
 private:
3672
  TypeSwitch();
3673
};
3674

    
3675

    
3676
// --- Extensions ---
3677

    
3678
class V8_EXPORT ExternalAsciiStringResourceImpl
3679
    : public String::ExternalAsciiStringResource {
3680
 public:
3681
  ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
3682
  ExternalAsciiStringResourceImpl(const char* data, size_t length)
3683
      : data_(data), length_(length) {}
3684
  const char* data() const { return data_; }
3685
  size_t length() const { return length_; }
3686

    
3687
 private:
3688
  const char* data_;
3689
  size_t length_;
3690
};
3691

    
3692
/**
3693
 * Ignore
3694
 */
3695
class V8_EXPORT Extension {  // NOLINT
3696
 public:
3697
  // Note that the strings passed into this constructor must live as long
3698
  // as the Extension itself.
3699
  Extension(const char* name,
3700
            const char* source = 0,
3701
            int dep_count = 0,
3702
            const char** deps = 0,
3703
            int source_length = -1);
3704
  virtual ~Extension() { }
3705
  virtual v8::Handle<v8::FunctionTemplate>
3706
      GetNativeFunction(v8::Handle<v8::String> name) {
3707
    return v8::Handle<v8::FunctionTemplate>();
3708
  }
3709

    
3710
  const char* name() const { return name_; }
3711
  size_t source_length() const { return source_length_; }
3712
  const String::ExternalAsciiStringResource* source() const {
3713
    return &source_; }
3714
  int dependency_count() { return dep_count_; }
3715
  const char** dependencies() { return deps_; }
3716
  void set_auto_enable(bool value) { auto_enable_ = value; }
3717
  bool auto_enable() { return auto_enable_; }
3718

    
3719
 private:
3720
  const char* name_;
3721
  size_t source_length_;  // expected to initialize before source_
3722
  ExternalAsciiStringResourceImpl source_;
3723
  int dep_count_;
3724
  const char** deps_;
3725
  bool auto_enable_;
3726

    
3727
  // Disallow copying and assigning.
3728
  Extension(const Extension&);
3729
  void operator=(const Extension&);
3730
};
3731

    
3732

    
3733
void V8_EXPORT RegisterExtension(Extension* extension);
3734

    
3735

    
3736
/**
3737
 * Ignore
3738
 */
3739
class V8_EXPORT DeclareExtension {
3740
 public:
3741
  V8_INLINE DeclareExtension(Extension* extension) {
3742
    RegisterExtension(extension);
3743
  }
3744
};
3745

    
3746

    
3747
// --- Statics ---
3748

    
3749

    
3750
Handle<Primitive> V8_EXPORT Undefined();
3751
Handle<Primitive> V8_EXPORT Null();
3752
Handle<Boolean> V8_EXPORT True();
3753
Handle<Boolean> V8_EXPORT False();
3754

    
3755
V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
3756
V8_INLINE Handle<Primitive> Null(Isolate* isolate);
3757
V8_INLINE Handle<Boolean> True(Isolate* isolate);
3758
V8_INLINE Handle<Boolean> False(Isolate* isolate);
3759

    
3760

    
3761
/**
3762
 * A set of constraints that specifies the limits of the runtime's memory use.
3763
 * You must set the heap size before initializing the VM - the size cannot be
3764
 * adjusted after the VM is initialized.
3765
 *
3766
 * If you are using threads then you should hold the V8::Locker lock while
3767
 * setting the stack limit and you must set a non-default stack limit separately
3768
 * for each thread.
3769
 */
3770
class V8_EXPORT ResourceConstraints {
3771
 public:
3772
  ResourceConstraints();
3773
  int max_young_space_size() const { return max_young_space_size_; }
3774
  void set_max_young_space_size(int value) { max_young_space_size_ = value; }
3775
  int max_old_space_size() const { return max_old_space_size_; }
3776
  void set_max_old_space_size(int value) { max_old_space_size_ = value; }
3777
  int max_executable_size() { return max_executable_size_; }
3778
  void set_max_executable_size(int value) { max_executable_size_ = value; }
3779
  uint32_t* stack_limit() const { return stack_limit_; }
3780
  // Sets an address beyond which the VM's stack may not grow.
3781
  void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
3782

    
3783
 private:
3784
  int max_young_space_size_;
3785
  int max_old_space_size_;
3786
  int max_executable_size_;
3787
  uint32_t* stack_limit_;
3788
};
3789

    
3790

    
3791
/**
3792
 * Sets the given ResourceConstraints on the current isolate.
3793
 */
3794
bool V8_EXPORT SetResourceConstraints(ResourceConstraints* constraints);
3795

    
3796

    
3797
// --- Exceptions ---
3798

    
3799

    
3800
typedef void (*FatalErrorCallback)(const char* location, const char* message);
3801

    
3802

    
3803
typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
3804

    
3805

    
3806
V8_DEPRECATED(
3807
    "Use Isolate::ThrowException instead",
3808
    Handle<Value> V8_EXPORT ThrowException(Handle<Value> exception));
3809

    
3810
/**
3811
 * Create new error objects by calling the corresponding error object
3812
 * constructor with the message.
3813
 */
3814
class V8_EXPORT Exception {
3815
 public:
3816
  static Local<Value> RangeError(Handle<String> message);
3817
  static Local<Value> ReferenceError(Handle<String> message);
3818
  static Local<Value> SyntaxError(Handle<String> message);
3819
  static Local<Value> TypeError(Handle<String> message);
3820
  static Local<Value> Error(Handle<String> message);
3821
};
3822

    
3823

    
3824
// --- Counters Callbacks ---
3825

    
3826
typedef int* (*CounterLookupCallback)(const char* name);
3827

    
3828
typedef void* (*CreateHistogramCallback)(const char* name,
3829
                                         int min,
3830
                                         int max,
3831
                                         size_t buckets);
3832

    
3833
typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
3834

    
3835
// --- Memory Allocation Callback ---
3836
  enum ObjectSpace {
3837
    kObjectSpaceNewSpace = 1 << 0,
3838
    kObjectSpaceOldPointerSpace = 1 << 1,
3839
    kObjectSpaceOldDataSpace = 1 << 2,
3840
    kObjectSpaceCodeSpace = 1 << 3,
3841
    kObjectSpaceMapSpace = 1 << 4,
3842
    kObjectSpaceLoSpace = 1 << 5,
3843

    
3844
    kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
3845
      kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
3846
      kObjectSpaceLoSpace
3847
  };
3848

    
3849
  enum AllocationAction {
3850
    kAllocationActionAllocate = 1 << 0,
3851
    kAllocationActionFree = 1 << 1,
3852
    kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
3853
  };
3854

    
3855
typedef void (*MemoryAllocationCallback)(ObjectSpace space,
3856
                                         AllocationAction action,
3857
                                         int size);
3858

    
3859
// --- Leave Script Callback ---
3860
typedef void (*CallCompletedCallback)();
3861

    
3862
// --- Failed Access Check Callback ---
3863
typedef void (*FailedAccessCheckCallback)(Local<Object> target,
3864
                                          AccessType type,
3865
                                          Local<Value> data);
3866

    
3867
// --- AllowCodeGenerationFromStrings callbacks ---
3868

    
3869
/**
3870
 * Callback to check if code generation from strings is allowed. See
3871
 * Context::AllowCodeGenerationFromStrings.
3872
 */
3873
typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
3874

    
3875
// --- Garbage Collection Callbacks ---
3876

    
3877
/**
3878
 * Applications can register callback functions which will be called
3879
 * before and after a garbage collection.  Allocations are not
3880
 * allowed in the callback functions, you therefore cannot manipulate
3881
 * objects (set or delete properties for example) since it is possible
3882
 * such operations will result in the allocation of objects.
3883
 */
3884
enum GCType {
3885
  kGCTypeScavenge = 1 << 0,
3886
  kGCTypeMarkSweepCompact = 1 << 1,
3887
  kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
3888
};
3889

    
3890
enum GCCallbackFlags {
3891
  kNoGCCallbackFlags = 0,
3892
  kGCCallbackFlagCompacted = 1 << 0,
3893
  kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1
3894
};
3895

    
3896
typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
3897
typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
3898

    
3899

    
3900
/**
3901
 * Collection of V8 heap information.
3902
 *
3903
 * Instances of this class can be passed to v8::V8::HeapStatistics to
3904
 * get heap statistics from V8.
3905
 */
3906
class V8_EXPORT HeapStatistics {
3907
 public:
3908
  HeapStatistics();
3909
  size_t total_heap_size() { return total_heap_size_; }
3910
  size_t total_heap_size_executable() { return total_heap_size_executable_; }
3911
  size_t total_physical_size() { return total_physical_size_; }
3912
  size_t used_heap_size() { return used_heap_size_; }
3913
  size_t heap_size_limit() { return heap_size_limit_; }
3914

    
3915
 private:
3916
  size_t total_heap_size_;
3917
  size_t total_heap_size_executable_;
3918
  size_t total_physical_size_;
3919
  size_t used_heap_size_;
3920
  size_t heap_size_limit_;
3921

    
3922
  friend class V8;
3923
  friend class Isolate;
3924
};
3925

    
3926

    
3927
class RetainedObjectInfo;
3928

    
3929
/**
3930
 * Isolate represents an isolated instance of the V8 engine.  V8
3931
 * isolates have completely separate states.  Objects from one isolate
3932
 * must not be used in other isolates.  When V8 is initialized a
3933
 * default isolate is implicitly created and entered.  The embedder
3934
 * can create additional isolates and use them in parallel in multiple
3935
 * threads.  An isolate can be entered by at most one thread at any
3936
 * given time.  The Locker/Unlocker API must be used to synchronize.
3937
 */
3938
class V8_EXPORT Isolate {
3939
 public:
3940
  /**
3941
   * Stack-allocated class which sets the isolate for all operations
3942
   * executed within a local scope.
3943
   */
3944
  class V8_EXPORT Scope {
3945
   public:
3946
    explicit Scope(Isolate* isolate) : isolate_(isolate) {
3947
      isolate->Enter();
3948
    }
3949

    
3950
    ~Scope() { isolate_->Exit(); }
3951

    
3952
   private:
3953
    Isolate* const isolate_;
3954

    
3955
    // Prevent copying of Scope objects.
3956
    Scope(const Scope&);
3957
    Scope& operator=(const Scope&);
3958
  };
3959

    
3960
  /**
3961
   * Creates a new isolate.  Does not change the currently entered
3962
   * isolate.
3963
   *
3964
   * When an isolate is no longer used its resources should be freed
3965
   * by calling Dispose().  Using the delete operator is not allowed.
3966
   */
3967
  static Isolate* New();
3968

    
3969
  /**
3970
   * Returns the entered isolate for the current thread or NULL in
3971
   * case there is no current isolate.
3972
   */
3973
  static Isolate* GetCurrent();
3974

    
3975
  /**
3976
   * Methods below this point require holding a lock (using Locker) in
3977
   * a multi-threaded environment.
3978
   */
3979

    
3980
  /**
3981
   * Sets this isolate as the entered one for the current thread.
3982
   * Saves the previously entered one (if any), so that it can be
3983
   * restored when exiting.  Re-entering an isolate is allowed.
3984
   */
3985
  void Enter();
3986

    
3987
  /**
3988
   * Exits this isolate by restoring the previously entered one in the
3989
   * current thread.  The isolate may still stay the same, if it was
3990
   * entered more than once.
3991
   *
3992
   * Requires: this == Isolate::GetCurrent().
3993
   */
3994
  void Exit();
3995

    
3996
  /**
3997
   * Disposes the isolate.  The isolate must not be entered by any
3998
   * thread to be disposable.
3999
   */
4000
  void Dispose();
4001

    
4002
  /**
4003
   * Associate embedder-specific data with the isolate
4004
   */
4005
  V8_INLINE void SetData(void* data);
4006

    
4007
  /**
4008
   * Retrieve embedder-specific data from the isolate.
4009
   * Returns NULL if SetData has never been called.
4010
   */
4011
  V8_INLINE void* GetData();
4012

    
4013
  /**
4014
   * Get statistics about the heap memory usage.
4015
   */
4016
  void GetHeapStatistics(HeapStatistics* heap_statistics);
4017

    
4018
  /**
4019
   * Adjusts the amount of registered external memory. Used to give V8 an
4020
   * indication of the amount of externally allocated memory that is kept alive
4021
   * by JavaScript objects. V8 uses this to decide when to perform global
4022
   * garbage collections. Registering externally allocated memory will trigger
4023
   * global garbage collections more often than it would otherwise in an attempt
4024
   * to garbage collect the JavaScript objects that keep the externally
4025
   * allocated memory alive.
4026
   *
4027
   * \param change_in_bytes the change in externally allocated memory that is
4028
   *   kept alive by JavaScript objects.
4029
   * \returns the adjusted value.
4030
   */
4031
  intptr_t AdjustAmountOfExternalAllocatedMemory(intptr_t change_in_bytes);
4032

    
4033
  /**
4034
   * Returns heap profiler for this isolate. Will return NULL until the isolate
4035
   * is initialized.
4036
   */
4037
  HeapProfiler* GetHeapProfiler();
4038

    
4039
  /**
4040
   * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4041
   * is initialized. It is the embedder's responsibility to stop all CPU
4042
   * profiling activities if it has started any.
4043
   */
4044
  CpuProfiler* GetCpuProfiler();
4045

    
4046
  /** Returns true if this isolate has a current context. */
4047
  bool InContext();
4048

    
4049
  /** Returns the context that is on the top of the stack. */
4050
  Local<Context> GetCurrentContext();
4051

    
4052
  /**
4053
   * Returns the context of the calling JavaScript code.  That is the
4054
   * context of the top-most JavaScript frame.  If there are no
4055
   * JavaScript frames an empty handle is returned.
4056
   */
4057
  Local<Context> GetCallingContext();
4058

    
4059
  /** Returns the last entered context. */
4060
  Local<Context> GetEnteredContext();
4061

    
4062
  /**
4063
   * Schedules an exception to be thrown when returning to JavaScript.  When an
4064
   * exception has been scheduled it is illegal to invoke any JavaScript
4065
   * operation; the caller must return immediately and only after the exception
4066
   * has been handled does it become legal to invoke JavaScript operations.
4067
   */
4068
  Local<Value> ThrowException(Local<Value> exception);
4069

    
4070
  /**
4071
   * Allows the host application to group objects together. If one
4072
   * object in the group is alive, all objects in the group are alive.
4073
   * After each garbage collection, object groups are removed. It is
4074
   * intended to be used in the before-garbage-collection callback
4075
   * function, for instance to simulate DOM tree connections among JS
4076
   * wrapper objects. Object groups for all dependent handles need to
4077
   * be provided for kGCTypeMarkSweepCompact collections, for all other
4078
   * garbage collection types it is sufficient to provide object groups
4079
   * for partially dependent handles only.
4080
   */
4081
  template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4082
                                             UniqueId id);
4083

    
4084
  /**
4085
   * Allows the host application to declare implicit references from an object
4086
   * group to an object. If the objects of the object group are alive, the child
4087
   * object is alive too. After each garbage collection, all implicit references
4088
   * are removed. It is intended to be used in the before-garbage-collection
4089
   * callback function.
4090
   */
4091
  template<typename T> void SetReferenceFromGroup(UniqueId id,
4092
                                                  const Persistent<T>& child);
4093

    
4094
  /**
4095
   * Allows the host application to declare implicit references from an object
4096
   * to another object. If the parent object is alive, the child object is alive
4097
   * too. After each garbage collection, all implicit references are removed. It
4098
   * is intended to be used in the before-garbage-collection callback function.
4099
   */
4100
  template<typename T, typename S>
4101
  void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4102

    
4103
  typedef void (*GCPrologueCallback)(Isolate* isolate,
4104
                                     GCType type,
4105
                                     GCCallbackFlags flags);
4106
  typedef void (*GCEpilogueCallback)(Isolate* isolate,
4107
                                     GCType type,
4108
                                     GCCallbackFlags flags);
4109

    
4110
  /**
4111
   * Enables the host application to receive a notification before a
4112
   * garbage collection.  Allocations are not allowed in the
4113
   * callback function, you therefore cannot manipulate objects (set
4114
   * or delete properties for example) since it is possible such
4115
   * operations will result in the allocation of objects. It is possible
4116
   * to specify the GCType filter for your callback. But it is not possible to
4117
   * register the same callback function two times with different
4118
   * GCType filters.
4119
   */
4120
  void AddGCPrologueCallback(
4121
      GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4122

    
4123
  /**
4124
   * This function removes callback which was installed by
4125
   * AddGCPrologueCallback function.
4126
   */
4127
  void RemoveGCPrologueCallback(GCPrologueCallback callback);
4128

    
4129
  /**
4130
   * Enables the host application to receive a notification after a
4131
   * garbage collection.  Allocations are not allowed in the
4132
   * callback function, you therefore cannot manipulate objects (set
4133
   * or delete properties for example) since it is possible such
4134
   * operations will result in the allocation of objects. It is possible
4135
   * to specify the GCType filter for your callback. But it is not possible to
4136
   * register the same callback function two times with different
4137
   * GCType filters.
4138
   */
4139
  void AddGCEpilogueCallback(
4140
      GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4141

    
4142
  /**
4143
   * This function removes callback which was installed by
4144
   * AddGCEpilogueCallback function.
4145
   */
4146
  void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4147

    
4148
 private:
4149
  Isolate();
4150
  Isolate(const Isolate&);
4151
  ~Isolate();
4152
  Isolate& operator=(const Isolate&);
4153
  void* operator new(size_t size);
4154
  void operator delete(void*, size_t);
4155

    
4156
  void SetObjectGroupId(internal::Object** object, UniqueId id);
4157
  void SetReferenceFromGroup(UniqueId id, internal::Object** object);
4158
  void SetReference(internal::Object** parent, internal::Object** child);
4159
};
4160

    
4161
class V8_EXPORT StartupData {
4162
 public:
4163
  enum CompressionAlgorithm {
4164
    kUncompressed,
4165
    kBZip2
4166
  };
4167

    
4168
  const char* data;
4169
  int compressed_size;
4170
  int raw_size;
4171
};
4172

    
4173

    
4174
/**
4175
 * A helper class for driving V8 startup data decompression.  It is based on
4176
 * "CompressedStartupData" API functions from the V8 class.  It isn't mandatory
4177
 * for an embedder to use this class, instead, API functions can be used
4178
 * directly.
4179
 *
4180
 * For an example of the class usage, see the "shell.cc" sample application.
4181
 */
4182
class V8_EXPORT StartupDataDecompressor {  // NOLINT
4183
 public:
4184
  StartupDataDecompressor();
4185
  virtual ~StartupDataDecompressor();
4186
  int Decompress();
4187

    
4188
 protected:
4189
  virtual int DecompressData(char* raw_data,
4190
                             int* raw_data_size,
4191
                             const char* compressed_data,
4192
                             int compressed_data_size) = 0;
4193

    
4194
 private:
4195
  char** raw_data;
4196
};
4197

    
4198

    
4199
/**
4200
 * EntropySource is used as a callback function when v8 needs a source
4201
 * of entropy.
4202
 */
4203
typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
4204

    
4205

    
4206
/**
4207
 * ReturnAddressLocationResolver is used as a callback function when v8 is
4208
 * resolving the location of a return address on the stack. Profilers that
4209
 * change the return address on the stack can use this to resolve the stack
4210
 * location to whereever the profiler stashed the original return address.
4211
 *
4212
 * \param return_addr_location points to a location on stack where a machine
4213
 *    return address resides.
4214
 * \returns either return_addr_location, or else a pointer to the profiler's
4215
 *    copy of the original return address.
4216
 *
4217
 * \note the resolver function must not cause garbage collection.
4218
 */
4219
typedef uintptr_t (*ReturnAddressLocationResolver)(
4220
    uintptr_t return_addr_location);
4221

    
4222

    
4223
/**
4224
 * FunctionEntryHook is the type of the profile entry hook called at entry to
4225
 * any generated function when function-level profiling is enabled.
4226
 *
4227
 * \param function the address of the function that's being entered.
4228
 * \param return_addr_location points to a location on stack where the machine
4229
 *    return address resides. This can be used to identify the caller of
4230
 *    \p function, and/or modified to divert execution when \p function exits.
4231
 *
4232
 * \note the entry hook must not cause garbage collection.
4233
 */
4234
typedef void (*FunctionEntryHook)(uintptr_t function,
4235
                                  uintptr_t return_addr_location);
4236

    
4237

    
4238
/**
4239
 * A JIT code event is issued each time code is added, moved or removed.
4240
 *
4241
 * \note removal events are not currently issued.
4242
 */
4243
struct JitCodeEvent {
4244
  enum EventType {
4245
    CODE_ADDED,
4246
    CODE_MOVED,
4247
    CODE_REMOVED,
4248
    CODE_ADD_LINE_POS_INFO,
4249
    CODE_START_LINE_INFO_RECORDING,
4250
    CODE_END_LINE_INFO_RECORDING
4251
  };
4252
  // Definition of the code position type. The "POSITION" type means the place
4253
  // in the source code which are of interest when making stack traces to
4254
  // pin-point the source location of a stack frame as close as possible.
4255
  // The "STATEMENT_POSITION" means the place at the beginning of each
4256
  // statement, and is used to indicate possible break locations.
4257
  enum PositionType {
4258
    POSITION,
4259
    STATEMENT_POSITION
4260
  };
4261

    
4262
  // Type of event.
4263
  EventType type;
4264
  // Start of the instructions.
4265
  void* code_start;
4266
  // Size of the instructions.
4267
  size_t code_len;
4268
  // Script info for CODE_ADDED event.
4269
  Handle<Script> script;
4270
  // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4271
  // code line information which is returned from the
4272
  // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4273
  // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4274
  void* user_data;
4275

    
4276
  struct name_t {
4277
    // Name of the object associated with the code, note that the string is not
4278
    // zero-terminated.
4279
    const char* str;
4280
    // Number of chars in str.
4281
    size_t len;
4282
  };
4283

    
4284
  struct line_info_t {
4285
    // PC offset
4286
    size_t offset;
4287
    // Code postion
4288
    size_t pos;
4289
    // The position type.
4290
    PositionType position_type;
4291
  };
4292

    
4293
  union {
4294
    // Only valid for CODE_ADDED.
4295
    struct name_t name;
4296

    
4297
    // Only valid for CODE_ADD_LINE_POS_INFO
4298
    struct line_info_t line_info;
4299

    
4300
    // New location of instructions. Only valid for CODE_MOVED.
4301
    void* new_code_start;
4302
  };
4303
};
4304

    
4305
/**
4306
 * Option flags passed to the SetJitCodeEventHandler function.
4307
 */
4308
enum JitCodeEventOptions {
4309
  kJitCodeEventDefault = 0,
4310
  // Generate callbacks for already existent code.
4311
  kJitCodeEventEnumExisting = 1
4312
};
4313

    
4314

    
4315
/**
4316
 * Callback function passed to SetJitCodeEventHandler.
4317
 *
4318
 * \param event code add, move or removal event.
4319
 */
4320
typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4321

    
4322

    
4323
/**
4324
 * Interface for iterating through all external resources in the heap.
4325
 */
4326
class V8_EXPORT ExternalResourceVisitor {  // NOLINT
4327
 public:
4328
  virtual ~ExternalResourceVisitor() {}
4329
  virtual void VisitExternalString(Handle<String> string) {}
4330
};
4331

    
4332

    
4333
/**
4334
 * Interface for iterating through all the persistent handles in the heap.
4335
 */
4336
class V8_EXPORT PersistentHandleVisitor {  // NOLINT
4337
 public:
4338
  virtual ~PersistentHandleVisitor() {}
4339
  virtual void VisitPersistentHandle(Persistent<Value>* value,
4340
                                     uint16_t class_id) {}
4341
};
4342

    
4343

    
4344
/**
4345
 * Asserts that no action is performed that could cause a handle's value
4346
 * to be modified. Useful when otherwise unsafe handle operations need to
4347
 * be performed.
4348
 */
4349
class V8_EXPORT AssertNoGCScope {
4350
#ifndef DEBUG
4351
  // TODO(yangguo): remove isolate argument.
4352
  V8_INLINE AssertNoGCScope(Isolate* isolate) {}
4353
#else
4354
  AssertNoGCScope(Isolate* isolate);
4355
  ~AssertNoGCScope();
4356
 private:
4357
  void* disallow_heap_allocation_;
4358
#endif
4359
};
4360

    
4361

    
4362
/**
4363
 * Container class for static utility functions.
4364
 */
4365
class V8_EXPORT V8 {
4366
 public:
4367
  /** Set the callback to invoke in case of fatal errors. */
4368
  static void SetFatalErrorHandler(FatalErrorCallback that);
4369

    
4370
  /**
4371
   * Set the callback to invoke to check if code generation from
4372
   * strings should be allowed.
4373
   */
4374
  static void SetAllowCodeGenerationFromStringsCallback(
4375
      AllowCodeGenerationFromStringsCallback that);
4376

    
4377
  /**
4378
   * Set allocator to use for ArrayBuffer memory.
4379
   * The allocator should be set only once. The allocator should be set
4380
   * before any code tha uses ArrayBuffers is executed.
4381
   * This allocator is used in all isolates.
4382
   */
4383
  static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
4384

    
4385
  /**
4386
   * Ignore out-of-memory exceptions.
4387
   *
4388
   * V8 running out of memory is treated as a fatal error by default.
4389
   * This means that the fatal error handler is called and that V8 is
4390
   * terminated.
4391
   *
4392
   * IgnoreOutOfMemoryException can be used to not treat an
4393
   * out-of-memory situation as a fatal error.  This way, the contexts
4394
   * that did not cause the out of memory problem might be able to
4395
   * continue execution.
4396
   */
4397
  static void IgnoreOutOfMemoryException();
4398

    
4399
  /**
4400
   * Check if V8 is dead and therefore unusable.  This is the case after
4401
   * fatal errors such as out-of-memory situations.
4402
   */
4403
  static bool IsDead();
4404

    
4405
  /**
4406
   * The following 4 functions are to be used when V8 is built with
4407
   * the 'compress_startup_data' flag enabled. In this case, the
4408
   * embedder must decompress startup data prior to initializing V8.
4409
   *
4410
   * This is how interaction with V8 should look like:
4411
   *   int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
4412
   *   v8::StartupData* compressed_data =
4413
   *     new v8::StartupData[compressed_data_count];
4414
   *   v8::V8::GetCompressedStartupData(compressed_data);
4415
   *   ... decompress data (compressed_data can be updated in-place) ...
4416
   *   v8::V8::SetDecompressedStartupData(compressed_data);
4417
   *   ... now V8 can be initialized
4418
   *   ... make sure the decompressed data stays valid until V8 shutdown
4419
   *
4420
   * A helper class StartupDataDecompressor is provided. It implements
4421
   * the protocol of the interaction described above, and can be used in
4422
   * most cases instead of calling these API functions directly.
4423
   */
4424
  static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
4425
  static int GetCompressedStartupDataCount();
4426
  static void GetCompressedStartupData(StartupData* compressed_data);
4427
  static void SetDecompressedStartupData(StartupData* decompressed_data);
4428

    
4429
  /**
4430
   * Adds a message listener.
4431
   *
4432
   * The same message listener can be added more than once and in that
4433
   * case it will be called more than once for each message.
4434
   *
4435
   * If data is specified, it will be passed to the callback when it is called.
4436
   * Otherwise, the exception object will be passed to the callback instead.
4437
   */
4438
  static bool AddMessageListener(MessageCallback that,
4439
                                 Handle<Value> data = Handle<Value>());
4440

    
4441
  /**
4442
   * Remove all message listeners from the specified callback function.
4443
   */
4444
  static void RemoveMessageListeners(MessageCallback that);
4445

    
4446
  /**
4447
   * Tells V8 to capture current stack trace when uncaught exception occurs
4448
   * and report it to the message listeners. The option is off by default.
4449
   */
4450
  static void SetCaptureStackTraceForUncaughtExceptions(
4451
      bool capture,
4452
      int frame_limit = 10,
4453
      StackTrace::StackTraceOptions options = StackTrace::kOverview);
4454

    
4455
  /**
4456
   * Sets V8 flags from a string.
4457
   */
4458
  static void SetFlagsFromString(const char* str, int length);
4459

    
4460
  /**
4461
   * Sets V8 flags from the command line.
4462
   */
4463
  static void SetFlagsFromCommandLine(int* argc,
4464
                                      char** argv,
4465
                                      bool remove_flags);
4466

    
4467
  /** Get the version string. */
4468
  static const char* GetVersion();
4469

    
4470
  /**
4471
   * Enables the host application to provide a mechanism for recording
4472
   * statistics counters.
4473
   */
4474
  static void SetCounterFunction(CounterLookupCallback);
4475

    
4476
  /**
4477
   * Enables the host application to provide a mechanism for recording
4478
   * histograms. The CreateHistogram function returns a
4479
   * histogram which will later be passed to the AddHistogramSample
4480
   * function.
4481
   */
4482
  static void SetCreateHistogramFunction(CreateHistogramCallback);
4483
  static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4484

    
4485
  /** Callback function for reporting failed access checks.*/
4486
  static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
4487

    
4488
  /**
4489
   * Enables the host application to receive a notification before a
4490
   * garbage collection.  Allocations are not allowed in the
4491
   * callback function, you therefore cannot manipulate objects (set
4492
   * or delete properties for example) since it is possible such
4493
   * operations will result in the allocation of objects. It is possible
4494
   * to specify the GCType filter for your callback. But it is not possible to
4495
   * register the same callback function two times with different
4496
   * GCType filters.
4497
   */
4498
  static void AddGCPrologueCallback(
4499
      GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4500

    
4501
  /**
4502
   * This function removes callback which was installed by
4503
   * AddGCPrologueCallback function.
4504
   */
4505
  static void RemoveGCPrologueCallback(GCPrologueCallback callback);
4506

    
4507
  /**
4508
   * Enables the host application to receive a notification after a
4509
   * garbage collection.  Allocations are not allowed in the
4510
   * callback function, you therefore cannot manipulate objects (set
4511
   * or delete properties for example) since it is possible such
4512
   * operations will result in the allocation of objects. It is possible
4513
   * to specify the GCType filter for your callback. But it is not possible to
4514
   * register the same callback function two times with different
4515
   * GCType filters.
4516
   */
4517
  static void AddGCEpilogueCallback(
4518
      GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4519

    
4520
  /**
4521
   * This function removes callback which was installed by
4522
   * AddGCEpilogueCallback function.
4523
   */
4524
  static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4525

    
4526
  /**
4527
   * Enables the host application to provide a mechanism to be notified
4528
   * and perform custom logging when V8 Allocates Executable Memory.
4529
   */
4530
  static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
4531
                                          ObjectSpace space,
4532
                                          AllocationAction action);
4533

    
4534
  /**
4535
   * Removes callback that was installed by AddMemoryAllocationCallback.
4536
   */
4537
  static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
4538

    
4539
  /**
4540
   * Adds a callback to notify the host application when a script finished
4541
   * running.  If a script re-enters the runtime during executing, the
4542
   * CallCompletedCallback is only invoked when the outer-most script
4543
   * execution ends.  Executing scripts inside the callback do not trigger
4544
   * further callbacks.
4545
   */
4546
  static void AddCallCompletedCallback(CallCompletedCallback callback);
4547

    
4548
  /**
4549
   * Removes callback that was installed by AddCallCompletedCallback.
4550
   */
4551
  static void RemoveCallCompletedCallback(CallCompletedCallback callback);
4552

    
4553
  /**
4554
   * Initializes from snapshot if possible. Otherwise, attempts to
4555
   * initialize from scratch.  This function is called implicitly if
4556
   * you use the API without calling it first.
4557
   */
4558
  static bool Initialize();
4559

    
4560
  /**
4561
   * Allows the host application to provide a callback which can be used
4562
   * as a source of entropy for random number generators.
4563
   */
4564
  static void SetEntropySource(EntropySource source);
4565

    
4566
  /**
4567
   * Allows the host application to provide a callback that allows v8 to
4568
   * cooperate with a profiler that rewrites return addresses on stack.
4569
   */
4570
  static void SetReturnAddressLocationResolver(
4571
      ReturnAddressLocationResolver return_address_resolver);
4572

    
4573
  /**
4574
   * Allows the host application to provide the address of a function that's
4575
   * invoked on entry to every V8-generated function.
4576
   * Note that \p entry_hook is invoked at the very start of each
4577
   * generated function.
4578
   *
4579
   * \param isolate the isolate to operate on.
4580
   * \param entry_hook a function that will be invoked on entry to every
4581
   *   V8-generated function.
4582
   * \returns true on success on supported platforms, false on failure.
4583
   * \note Setting an entry hook can only be done very early in an isolates
4584
   *   lifetime, and once set, the entry hook cannot be revoked.
4585
   */
4586
  static bool SetFunctionEntryHook(Isolate* isolate,
4587
                                   FunctionEntryHook entry_hook);
4588

    
4589
  /**
4590
   * Allows the host application to provide the address of a function that is
4591
   * notified each time code is added, moved or removed.
4592
   *
4593
   * \param options options for the JIT code event handler.
4594
   * \param event_handler the JIT code event handler, which will be invoked
4595
   *     each time code is added, moved or removed.
4596
   * \note \p event_handler won't get notified of existent code.
4597
   * \note since code removal notifications are not currently issued, the
4598
   *     \p event_handler may get notifications of code that overlaps earlier
4599
   *     code notifications. This happens when code areas are reused, and the
4600
   *     earlier overlapping code areas should therefore be discarded.
4601
   * \note the events passed to \p event_handler and the strings they point to
4602
   *     are not guaranteed to live past each call. The \p event_handler must
4603
   *     copy strings and other parameters it needs to keep around.
4604
   * \note the set of events declared in JitCodeEvent::EventType is expected to
4605
   *     grow over time, and the JitCodeEvent structure is expected to accrue
4606
   *     new members. The \p event_handler function must ignore event codes
4607
   *     it does not recognize to maintain future compatibility.
4608
   */
4609
  static void SetJitCodeEventHandler(JitCodeEventOptions options,
4610
                                     JitCodeEventHandler event_handler);
4611

    
4612
  V8_DEPRECATED(
4613
      "Use Isolate::AdjustAmountOfExternalAllocatedMemory instead",
4614
      static intptr_t AdjustAmountOfExternalAllocatedMemory(
4615
          intptr_t change_in_bytes));
4616

    
4617
  /**
4618
   * Forcefully terminate the current thread of JavaScript execution
4619
   * in the given isolate. If no isolate is provided, the default
4620
   * isolate is used.
4621
   *
4622
   * This method can be used by any thread even if that thread has not
4623
   * acquired the V8 lock with a Locker object.
4624
   *
4625
   * \param isolate The isolate in which to terminate the current JS execution.
4626
   */
4627
  static void TerminateExecution(Isolate* isolate = NULL);
4628

    
4629
  /**
4630
   * Is V8 terminating JavaScript execution.
4631
   *
4632
   * Returns true if JavaScript execution is currently terminating
4633
   * because of a call to TerminateExecution.  In that case there are
4634
   * still JavaScript frames on the stack and the termination
4635
   * exception is still active.
4636
   *
4637
   * \param isolate The isolate in which to check.
4638
   */
4639
  static bool IsExecutionTerminating(Isolate* isolate = NULL);
4640

    
4641
  /**
4642
   * Resume execution capability in the given isolate, whose execution
4643
   * was previously forcefully terminated using TerminateExecution().
4644
   *
4645
   * When execution is forcefully terminated using TerminateExecution(),
4646
   * the isolate can not resume execution until all JavaScript frames
4647
   * have propagated the uncatchable exception which is generated.  This
4648
   * method allows the program embedding the engine to handle the
4649
   * termination event and resume execution capability, even if
4650
   * JavaScript frames remain on the stack.
4651
   *
4652
   * This method can be used by any thread even if that thread has not
4653
   * acquired the V8 lock with a Locker object.
4654
   *
4655
   * \param isolate The isolate in which to resume execution capability.
4656
   */
4657
  static void CancelTerminateExecution(Isolate* isolate);
4658

    
4659
  /**
4660
   * Releases any resources used by v8 and stops any utility threads
4661
   * that may be running.  Note that disposing v8 is permanent, it
4662
   * cannot be reinitialized.
4663
   *
4664
   * It should generally not be necessary to dispose v8 before exiting
4665
   * a process, this should happen automatically.  It is only necessary
4666
   * to use if the process needs the resources taken up by v8.
4667
   */
4668
  static bool Dispose();
4669

    
4670
  /**
4671
   * Iterates through all external resources referenced from current isolate
4672
   * heap.  GC is not invoked prior to iterating, therefore there is no
4673
   * guarantee that visited objects are still alive.
4674
   */
4675
  static void VisitExternalResources(ExternalResourceVisitor* visitor);
4676

    
4677
  /**
4678
   * Iterates through all the persistent handles in the current isolate's heap
4679
   * that have class_ids.
4680
   */
4681
  static void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
4682

    
4683
  /**
4684
   * Iterates through all the persistent handles in the current isolate's heap
4685
   * that have class_ids and are candidates to be marked as partially dependent
4686
   * handles. This will visit handles to young objects created since the last
4687
   * garbage collection but is free to visit an arbitrary superset of these
4688
   * objects.
4689
   */
4690
  static void VisitHandlesForPartialDependence(
4691
      Isolate* isolate, PersistentHandleVisitor* visitor);
4692

    
4693
  /**
4694
   * Optional notification that the embedder is idle.
4695
   * V8 uses the notification to reduce memory footprint.
4696
   * This call can be used repeatedly if the embedder remains idle.
4697
   * Returns true if the embedder should stop calling IdleNotification
4698
   * until real work has been done.  This indicates that V8 has done
4699
   * as much cleanup as it will be able to do.
4700
   *
4701
   * The hint argument specifies the amount of work to be done in the function
4702
   * on scale from 1 to 1000. There is no guarantee that the actual work will
4703
   * match the hint.
4704
   */
4705
  static bool IdleNotification(int hint = 1000);
4706

    
4707
  /**
4708
   * Optional notification that the system is running low on memory.
4709
   * V8 uses these notifications to attempt to free memory.
4710
   */
4711
  static void LowMemoryNotification();
4712

    
4713
  /**
4714
   * Optional notification that a context has been disposed. V8 uses
4715
   * these notifications to guide the GC heuristic. Returns the number
4716
   * of context disposals - including this one - since the last time
4717
   * V8 had a chance to clean up.
4718
   */
4719
  static int ContextDisposedNotification();
4720

    
4721
  /**
4722
   * Initialize the ICU library bundled with V8. The embedder should only
4723
   * invoke this method when using the bundled ICU. Returns true on success.
4724
   */
4725
  static bool InitializeICU();
4726

    
4727
 private:
4728
  V8();
4729

    
4730
  static internal::Object** GlobalizeReference(internal::Isolate* isolate,
4731
                                               internal::Object** handle);
4732
  static internal::Object** CopyPersistent(internal::Object** handle);
4733
  static void DisposeGlobal(internal::Object** global_handle);
4734
  typedef WeakReferenceCallbacks<Value, void>::Revivable RevivableCallback;
4735
  typedef WeakCallbackData<Value, void>::Callback WeakCallback;
4736
  static void MakeWeak(internal::Object** global_handle,
4737
                       void* data,
4738
                       WeakCallback weak_callback,
4739
                       RevivableCallback weak_reference_callback);
4740
  static void ClearWeak(internal::Object** global_handle);
4741
  static void Eternalize(Isolate* isolate,
4742
                         Value* handle,
4743
                         int* index);
4744
  static Local<Value> GetEternal(Isolate* isolate, int index);
4745

    
4746
  template <class T> friend class Handle;
4747
  template <class T> friend class Local;
4748
  template <class T> friend class Eternal;
4749
  template <class T, class M> friend class Persistent;
4750
  friend class Context;
4751
};
4752

    
4753

    
4754
/**
4755
 * An external exception handler.
4756
 */
4757
class V8_EXPORT TryCatch {
4758
 public:
4759
  /**
4760
   * Creates a new try/catch block and registers it with v8.  Note that
4761
   * all TryCatch blocks should be stack allocated because the memory
4762
   * location itself is compared against JavaScript try/catch blocks.
4763
   */
4764
  TryCatch();
4765

    
4766
  /**
4767
   * Unregisters and deletes this try/catch block.
4768
   */
4769
  ~TryCatch();
4770

    
4771
  /**
4772
   * Returns true if an exception has been caught by this try/catch block.
4773
   */
4774
  bool HasCaught() const;
4775

    
4776
  /**
4777
   * For certain types of exceptions, it makes no sense to continue execution.
4778
   *
4779
   * If CanContinue returns false, the correct action is to perform any C++
4780
   * cleanup needed and then return.  If CanContinue returns false and
4781
   * HasTerminated returns true, it is possible to call
4782
   * CancelTerminateExecution in order to continue calling into the engine.
4783
   */
4784
  bool CanContinue() const;
4785

    
4786
  /**
4787
   * Returns true if an exception has been caught due to script execution
4788
   * being terminated.
4789
   *
4790
   * There is no JavaScript representation of an execution termination
4791
   * exception.  Such exceptions are thrown when the TerminateExecution
4792
   * methods are called to terminate a long-running script.
4793
   *
4794
   * If such an exception has been thrown, HasTerminated will return true,
4795
   * indicating that it is possible to call CancelTerminateExecution in order
4796
   * to continue calling into the engine.
4797
   */
4798
  bool HasTerminated() const;
4799

    
4800
  /**
4801
   * Throws the exception caught by this TryCatch in a way that avoids
4802
   * it being caught again by this same TryCatch.  As with ThrowException
4803
   * it is illegal to execute any JavaScript operations after calling
4804
   * ReThrow; the caller must return immediately to where the exception
4805
   * is caught.
4806
   */
4807
  Handle<Value> ReThrow();
4808

    
4809
  /**
4810
   * Returns the exception caught by this try/catch block.  If no exception has
4811
   * been caught an empty handle is returned.
4812
   *
4813
   * The returned handle is valid until this TryCatch block has been destroyed.
4814
   */
4815
  Local<Value> Exception() const;
4816

    
4817
  /**
4818
   * Returns the .stack property of the thrown object.  If no .stack
4819
   * property is present an empty handle is returned.
4820
   */
4821
  Local<Value> StackTrace() const;
4822

    
4823
  /**
4824
   * Returns the message associated with this exception.  If there is
4825
   * no message associated an empty handle is returned.
4826
   *
4827
   * The returned handle is valid until this TryCatch block has been
4828
   * destroyed.
4829
   */
4830
  Local<v8::Message> Message() const;
4831

    
4832
  /**
4833
   * Clears any exceptions that may have been caught by this try/catch block.
4834
   * After this method has been called, HasCaught() will return false.
4835
   *
4836
   * It is not necessary to clear a try/catch block before using it again; if
4837
   * another exception is thrown the previously caught exception will just be
4838
   * overwritten.  However, it is often a good idea since it makes it easier
4839
   * to determine which operation threw a given exception.
4840
   */
4841
  void Reset();
4842

    
4843
  /**
4844
   * Set verbosity of the external exception handler.
4845
   *
4846
   * By default, exceptions that are caught by an external exception
4847
   * handler are not reported.  Call SetVerbose with true on an
4848
   * external exception handler to have exceptions caught by the
4849
   * handler reported as if they were not caught.
4850
   */
4851
  void SetVerbose(bool value);
4852

    
4853
  /**
4854
   * Set whether or not this TryCatch should capture a Message object
4855
   * which holds source information about where the exception
4856
   * occurred.  True by default.
4857
   */
4858
  void SetCaptureMessage(bool value);
4859

    
4860
 private:
4861
  // Make it hard to create heap-allocated TryCatch blocks.
4862
  TryCatch(const TryCatch&);
4863
  void operator=(const TryCatch&);
4864
  void* operator new(size_t size);
4865
  void operator delete(void*, size_t);
4866

    
4867
  v8::internal::Isolate* isolate_;
4868
  void* next_;
4869
  void* exception_;
4870
  void* message_obj_;
4871
  void* message_script_;
4872
  int message_start_pos_;
4873
  int message_end_pos_;
4874
  bool is_verbose_ : 1;
4875
  bool can_continue_ : 1;
4876
  bool capture_message_ : 1;
4877
  bool rethrow_ : 1;
4878
  bool has_terminated_ : 1;
4879

    
4880
  friend class v8::internal::Isolate;
4881
};
4882

    
4883

    
4884
// --- Context ---
4885

    
4886

    
4887
/**
4888
 * Ignore
4889
 */
4890
class V8_EXPORT ExtensionConfiguration {
4891
 public:
4892
  ExtensionConfiguration(int name_count, const char* names[])
4893
      : name_count_(name_count), names_(names) { }
4894
 private:
4895
  friend class ImplementationUtilities;
4896
  int name_count_;
4897
  const char** names_;
4898
};
4899

    
4900

    
4901
/**
4902
 * A sandboxed execution context with its own set of built-in objects
4903
 * and functions.
4904
 */
4905
class V8_EXPORT Context {
4906
 public:
4907
  /**
4908
   * Returns the global proxy object or global object itself for
4909
   * detached contexts.
4910
   *
4911
   * Global proxy object is a thin wrapper whose prototype points to
4912
   * actual context's global object with the properties like Object, etc.
4913
   * This is done that way for security reasons (for more details see
4914
   * https://wiki.mozilla.org/Gecko:SplitWindow).
4915
   *
4916
   * Please note that changes to global proxy object prototype most probably
4917
   * would break VM---v8 expects only global object as a prototype of
4918
   * global proxy object.
4919
   *
4920
   * If DetachGlobal() has been invoked, Global() would return actual global
4921
   * object until global is reattached with ReattachGlobal().
4922
   */
4923
  Local<Object> Global();
4924

    
4925
  /**
4926
   * Detaches the global object from its context before
4927
   * the global object can be reused to create a new context.
4928
   */
4929
  void DetachGlobal();
4930

    
4931
  /**
4932
   * Reattaches a global object to a context.  This can be used to
4933
   * restore the connection between a global object and a context
4934
   * after DetachGlobal has been called.
4935
   *
4936
   * \param global_object The global object to reattach to the
4937
   *   context.  For this to work, the global object must be the global
4938
   *   object that was associated with this context before a call to
4939
   *   DetachGlobal.
4940
   */
4941
  void ReattachGlobal(Handle<Object> global_object);
4942

    
4943
  /**
4944
   * Creates a new context and returns a handle to the newly allocated
4945
   * context.
4946
   *
4947
   * \param isolate The isolate in which to create the context.
4948
   *
4949
   * \param extensions An optional extension configuration containing
4950
   * the extensions to be installed in the newly created context.
4951
   *
4952
   * \param global_template An optional object template from which the
4953
   * global object for the newly created context will be created.
4954
   *
4955
   * \param global_object An optional global object to be reused for
4956
   * the newly created context. This global object must have been
4957
   * created by a previous call to Context::New with the same global
4958
   * template. The state of the global object will be completely reset
4959
   * and only object identify will remain.
4960
   */
4961
  static Local<Context> New(
4962
      Isolate* isolate,
4963
      ExtensionConfiguration* extensions = NULL,
4964
      Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
4965
      Handle<Value> global_object = Handle<Value>());
4966

    
4967
  V8_DEPRECATED("Use Isolate::GetEnteredContext instead",
4968
                static Local<Context> GetEntered());
4969

    
4970
  V8_DEPRECATED("Use Isolate::GetCurrentContext instead",
4971
                static Local<Context> GetCurrent());
4972

    
4973
  V8_DEPRECATED("Use Isolate::GetCallingContext instead",
4974
                static Local<Context> GetCalling());
4975

    
4976
  /**
4977
   * Sets the security token for the context.  To access an object in
4978
   * another context, the security tokens must match.
4979
   */
4980
  void SetSecurityToken(Handle<Value> token);
4981

    
4982
  /** Restores the security token to the default value. */
4983
  void UseDefaultSecurityToken();
4984

    
4985
  /** Returns the security token of this context.*/
4986
  Handle<Value> GetSecurityToken();
4987

    
4988
  /**
4989
   * Enter this context.  After entering a context, all code compiled
4990
   * and run is compiled and run in this context.  If another context
4991
   * is already entered, this old context is saved so it can be
4992
   * restored when the new context is exited.
4993
   */
4994
  void Enter();
4995

    
4996
  /**
4997
   * Exit this context.  Exiting the current context restores the
4998
   * context that was in place when entering the current context.
4999
   */
5000
  void Exit();
5001

    
5002
  /** Returns true if the context has experienced an out of memory situation. */
5003
  bool HasOutOfMemoryException();
5004

    
5005
  V8_DEPRECATED("Use Isolate::InContext instead",
5006
                static bool InContext());
5007

    
5008
  /** Returns an isolate associated with a current context. */
5009
  v8::Isolate* GetIsolate();
5010

    
5011
  /**
5012
   * Gets the embedder data with the given index, which must have been set by a
5013
   * previous call to SetEmbedderData with the same index. Note that index 0
5014
   * currently has a special meaning for Chrome's debugger.
5015
   */
5016
  V8_INLINE Local<Value> GetEmbedderData(int index);
5017

    
5018
  /**
5019
   * Sets the embedder data with the given index, growing the data as
5020
   * needed. Note that index 0 currently has a special meaning for Chrome's
5021
   * debugger.
5022
   */
5023
  void SetEmbedderData(int index, Handle<Value> value);
5024

    
5025
  /**
5026
   * Gets a 2-byte-aligned native pointer from the embedder data with the given
5027
   * index, which must have bees set by a previous call to
5028
   * SetAlignedPointerInEmbedderData with the same index. Note that index 0
5029
   * currently has a special meaning for Chrome's debugger.
5030
   */
5031
  V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
5032

    
5033
  /**
5034
   * Sets a 2-byte-aligned native pointer in the embedder data with the given
5035
   * index, growing the data as needed. Note that index 0 currently has a
5036
   * special meaning for Chrome's debugger.
5037
   */
5038
  void SetAlignedPointerInEmbedderData(int index, void* value);
5039

    
5040
  /**
5041
   * Control whether code generation from strings is allowed. Calling
5042
   * this method with false will disable 'eval' and the 'Function'
5043
   * constructor for code running in this context. If 'eval' or the
5044
   * 'Function' constructor are used an exception will be thrown.
5045
   *
5046
   * If code generation from strings is not allowed the
5047
   * V8::AllowCodeGenerationFromStrings callback will be invoked if
5048
   * set before blocking the call to 'eval' or the 'Function'
5049
   * constructor. If that callback returns true, the call will be
5050
   * allowed, otherwise an exception will be thrown. If no callback is
5051
   * set an exception will be thrown.
5052
   */
5053
  void AllowCodeGenerationFromStrings(bool allow);
5054

    
5055
  /**
5056
   * Returns true if code generation from strings is allowed for the context.
5057
   * For more details see AllowCodeGenerationFromStrings(bool) documentation.
5058
   */
5059
  bool IsCodeGenerationFromStringsAllowed();
5060

    
5061
  /**
5062
   * Sets the error description for the exception that is thrown when
5063
   * code generation from strings is not allowed and 'eval' or the 'Function'
5064
   * constructor are called.
5065
   */
5066
  void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
5067

    
5068
  /**
5069
   * Stack-allocated class which sets the execution context for all
5070
   * operations executed within a local scope.
5071
   */
5072
  class Scope {
5073
   public:
5074
    explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
5075
      context_->Enter();
5076
    }
5077
    V8_DEPRECATED(
5078
        "Use Handle version instead",
5079
        V8_INLINE Scope(Isolate* isolate, Persistent<Context>& context)) // NOLINT
5080
    : context_(Handle<Context>::New(isolate, context)) {
5081
      context_->Enter();
5082
    }
5083
    V8_INLINE ~Scope() { context_->Exit(); }
5084

    
5085
   private:
5086
    Handle<Context> context_;
5087
  };
5088

    
5089
 private:
5090
  friend class Value;
5091
  friend class Script;
5092
  friend class Object;
5093
  friend class Function;
5094

    
5095
  Local<Value> SlowGetEmbedderData(int index);
5096
  void* SlowGetAlignedPointerFromEmbedderData(int index);
5097
};
5098

    
5099

    
5100
/**
5101
 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
5102
 * to use any given V8 isolate, see the comments in the Isolate class. The
5103
 * definition of 'using a V8 isolate' includes accessing handles or holding onto
5104
 * object pointers obtained from V8 handles while in the particular V8 isolate.
5105
 * It is up to the user of V8 to ensure, perhaps with locking, that this
5106
 * constraint is not violated. In addition to any other synchronization
5107
 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
5108
 * used to signal thead switches to V8.
5109
 *
5110
 * v8::Locker is a scoped lock object. While it's active, i.e. between its
5111
 * construction and destruction, the current thread is allowed to use the locked
5112
 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
5113
 * any time. In other words, the scope of a v8::Locker is a critical section.
5114
 *
5115
 * Sample usage:
5116
* \code
5117
 * ...
5118
 * {
5119
 *   v8::Locker locker(isolate);
5120
 *   v8::Isolate::Scope isolate_scope(isolate);
5121
 *   ...
5122
 *   // Code using V8 and isolate goes here.
5123
 *   ...
5124
 * } // Destructor called here
5125
 * \endcode
5126
 *
5127
 * If you wish to stop using V8 in a thread A you can do this either by
5128
 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
5129
 * object:
5130
 *
5131
 * \code
5132
 * {
5133
 *   isolate->Exit();
5134
 *   v8::Unlocker unlocker(isolate);
5135
 *   ...
5136
 *   // Code not using V8 goes here while V8 can run in another thread.
5137
 *   ...
5138
 * } // Destructor called here.
5139
 * isolate->Enter();
5140
 * \endcode
5141
 *
5142
 * The Unlocker object is intended for use in a long-running callback from V8,
5143
 * where you want to release the V8 lock for other threads to use.
5144
 *
5145
 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
5146
 * given thread. This can be useful if you have code that can be called either
5147
 * from code that holds the lock or from code that does not. The Unlocker is
5148
 * not recursive so you can not have several Unlockers on the stack at once, and
5149
 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
5150
 *
5151
 * An unlocker will unlock several lockers if it has to and reinstate the
5152
 * correct depth of locking on its destruction, e.g.:
5153
 *
5154
 * \code
5155
 * // V8 not locked.
5156
 * {
5157
 *   v8::Locker locker(isolate);
5158
 *   Isolate::Scope isolate_scope(isolate);
5159
 *   // V8 locked.
5160
 *   {
5161
 *     v8::Locker another_locker(isolate);
5162
 *     // V8 still locked (2 levels).
5163
 *     {
5164
 *       isolate->Exit();
5165
 *       v8::Unlocker unlocker(isolate);
5166
 *       // V8 not locked.
5167
 *     }
5168
 *     isolate->Enter();
5169
 *     // V8 locked again (2 levels).
5170
 *   }
5171
 *   // V8 still locked (1 level).
5172
 * }
5173
 * // V8 Now no longer locked.
5174
 * \endcode
5175
 */
5176
class V8_EXPORT Unlocker {
5177
 public:
5178
  /**
5179
   * Initialize Unlocker for a given Isolate.
5180
   */
5181
  V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
5182

    
5183
  ~Unlocker();
5184
 private:
5185
  void Initialize(Isolate* isolate);
5186

    
5187
  internal::Isolate* isolate_;
5188
};
5189

    
5190

    
5191
class V8_EXPORT Locker {
5192
 public:
5193
  /**
5194
   * Initialize Locker for a given Isolate.
5195
   */
5196
  V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
5197

    
5198
  ~Locker();
5199

    
5200
  /**
5201
   * Start preemption.
5202
   *
5203
   * When preemption is started, a timer is fired every n milliseconds
5204
   * that will switch between multiple threads that are in contention
5205
   * for the V8 lock.
5206
   */
5207
  static void StartPreemption(Isolate* isolate, int every_n_ms);
5208

    
5209
  /**
5210
   * Stop preemption.
5211
   */
5212
  static void StopPreemption(Isolate* isolate);
5213

    
5214
  /**
5215
   * Returns whether or not the locker for a given isolate, is locked by the
5216
   * current thread.
5217
   */
5218
  static bool IsLocked(Isolate* isolate);
5219

    
5220
  /**
5221
   * Returns whether v8::Locker is being used by this V8 instance.
5222
   */
5223
  static bool IsActive();
5224

    
5225
 private:
5226
  void Initialize(Isolate* isolate);
5227

    
5228
  bool has_lock_;
5229
  bool top_level_;
5230
  internal::Isolate* isolate_;
5231

    
5232
  static bool active_;
5233

    
5234
  // Disallow copying and assigning.
5235
  Locker(const Locker&);
5236
  void operator=(const Locker&);
5237
};
5238

    
5239

    
5240
/**
5241
 * A struct for exporting HeapStats data from V8, using "push" model.
5242
 */
5243
struct HeapStatsUpdate;
5244

    
5245

    
5246
/**
5247
 * An interface for exporting data from V8, using "push" model.
5248
 */
5249
class V8_EXPORT OutputStream {  // NOLINT
5250
 public:
5251
  enum OutputEncoding {
5252
    kAscii = 0  // 7-bit ASCII.
5253
  };
5254
  enum WriteResult {
5255
    kContinue = 0,
5256
    kAbort = 1
5257
  };
5258
  virtual ~OutputStream() {}
5259
  /** Notify about the end of stream. */
5260
  virtual void EndOfStream() = 0;
5261
  /** Get preferred output chunk size. Called only once. */
5262
  virtual int GetChunkSize() { return 1024; }
5263
  /** Get preferred output encoding. Called only once. */
5264
  virtual OutputEncoding GetOutputEncoding() { return kAscii; }
5265
  /**
5266
   * Writes the next chunk of snapshot data into the stream. Writing
5267
   * can be stopped by returning kAbort as function result. EndOfStream
5268
   * will not be called in case writing was aborted.
5269
   */
5270
  virtual WriteResult WriteAsciiChunk(char* data, int size) = 0;
5271
  /**
5272
   * Writes the next chunk of heap stats data into the stream. Writing
5273
   * can be stopped by returning kAbort as function result. EndOfStream
5274
   * will not be called in case writing was aborted.
5275
   */
5276
  virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) {
5277
    return kAbort;
5278
  };
5279
};
5280

    
5281

    
5282
/**
5283
 * An interface for reporting progress and controlling long-running
5284
 * activities.
5285
 */
5286
class V8_EXPORT ActivityControl {  // NOLINT
5287
 public:
5288
  enum ControlOption {
5289
    kContinue = 0,
5290
    kAbort = 1
5291
  };
5292
  virtual ~ActivityControl() {}
5293
  /**
5294
   * Notify about current progress. The activity can be stopped by
5295
   * returning kAbort as the callback result.
5296
   */
5297
  virtual ControlOption ReportProgressValue(int done, int total) = 0;
5298
};
5299

    
5300

    
5301
// --- Implementation ---
5302

    
5303

    
5304
namespace internal {
5305

    
5306
const int kApiPointerSize = sizeof(void*);  // NOLINT
5307
const int kApiIntSize = sizeof(int);  // NOLINT
5308

    
5309
// Tag information for HeapObject.
5310
const int kHeapObjectTag = 1;
5311
const int kHeapObjectTagSize = 2;
5312
const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
5313

    
5314
// Tag information for Smi.
5315
const int kSmiTag = 0;
5316
const int kSmiTagSize = 1;
5317
const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
5318

    
5319
template <size_t ptr_size> struct SmiTagging;
5320

    
5321
template<int kSmiShiftSize>
5322
V8_INLINE internal::Object* IntToSmi(int value) {
5323
  int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
5324
  intptr_t tagged_value =
5325
      (static_cast<intptr_t>(value) << smi_shift_bits) | kSmiTag;
5326
  return reinterpret_cast<internal::Object*>(tagged_value);
5327
}
5328

    
5329
// Smi constants for 32-bit systems.
5330
template <> struct SmiTagging<4> {
5331
  static const int kSmiShiftSize = 0;
5332
  static const int kSmiValueSize = 31;
5333
  V8_INLINE static int SmiToInt(internal::Object* value) {
5334
    int shift_bits = kSmiTagSize + kSmiShiftSize;
5335
    // Throw away top 32 bits and shift down (requires >> to be sign extending).
5336
    return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
5337
  }
5338
  V8_INLINE static internal::Object* IntToSmi(int value) {
5339
    return internal::IntToSmi<kSmiShiftSize>(value);
5340
  }
5341
  V8_INLINE static bool IsValidSmi(intptr_t value) {
5342
    // To be representable as an tagged small integer, the two
5343
    // most-significant bits of 'value' must be either 00 or 11 due to
5344
    // sign-extension. To check this we add 01 to the two
5345
    // most-significant bits, and check if the most-significant bit is 0
5346
    //
5347
    // CAUTION: The original code below:
5348
    // bool result = ((value + 0x40000000) & 0x80000000) == 0;
5349
    // may lead to incorrect results according to the C language spec, and
5350
    // in fact doesn't work correctly with gcc4.1.1 in some cases: The
5351
    // compiler may produce undefined results in case of signed integer
5352
    // overflow. The computation must be done w/ unsigned ints.
5353
    return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
5354
  }
5355
};
5356

    
5357
// Smi constants for 64-bit systems.
5358
template <> struct SmiTagging<8> {
5359
  static const int kSmiShiftSize = 31;
5360
  static const int kSmiValueSize = 32;
5361
  V8_INLINE static int SmiToInt(internal::Object* value) {
5362
    int shift_bits = kSmiTagSize + kSmiShiftSize;
5363
    // Shift down and throw away top 32 bits.
5364
    return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
5365
  }
5366
  V8_INLINE static internal::Object* IntToSmi(int value) {
5367
    return internal::IntToSmi<kSmiShiftSize>(value);
5368
  }
5369
  V8_INLINE static bool IsValidSmi(intptr_t value) {
5370
    // To be representable as a long smi, the value must be a 32-bit integer.
5371
    return (value == static_cast<int32_t>(value));
5372
  }
5373
};
5374

    
5375
typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
5376
const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
5377
const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
5378
V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
5379
V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
5380

    
5381
/**
5382
 * This class exports constants and functionality from within v8 that
5383
 * is necessary to implement inline functions in the v8 api.  Don't
5384
 * depend on functions and constants defined here.
5385
 */
5386
class Internals {
5387
 public:
5388
  // These values match non-compiler-dependent values defined within
5389
  // the implementation of v8.
5390
  static const int kHeapObjectMapOffset = 0;
5391
  static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
5392
  static const int kStringResourceOffset = 3 * kApiPointerSize;
5393

    
5394
  static const int kOddballKindOffset = 3 * kApiPointerSize;
5395
  static const int kForeignAddressOffset = kApiPointerSize;
5396
  static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
5397
  static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
5398
  static const int kContextHeaderSize = 2 * kApiPointerSize;
5399
  static const int kContextEmbedderDataIndex = 65;
5400
  static const int kFullStringRepresentationMask = 0x07;
5401
  static const int kStringEncodingMask = 0x4;
5402
  static const int kExternalTwoByteRepresentationTag = 0x02;
5403
  static const int kExternalAsciiRepresentationTag = 0x06;
5404

    
5405
  static const int kIsolateEmbedderDataOffset = 1 * kApiPointerSize;
5406
  static const int kIsolateRootsOffset = 3 * kApiPointerSize;
5407
  static const int kUndefinedValueRootIndex = 5;
5408
  static const int kNullValueRootIndex = 7;
5409
  static const int kTrueValueRootIndex = 8;
5410
  static const int kFalseValueRootIndex = 9;
5411
  static const int kEmptyStringRootIndex = 132;
5412

    
5413
  static const int kNodeClassIdOffset = 1 * kApiPointerSize;
5414
  static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
5415
  static const int kNodeStateMask = 0xf;
5416
  static const int kNodeStateIsWeakValue = 2;
5417
  static const int kNodeStateIsPendingValue = 3;
5418
  static const int kNodeStateIsNearDeathValue = 4;
5419
  static const int kNodeIsIndependentShift = 4;
5420
  static const int kNodeIsPartiallyDependentShift = 5;
5421

    
5422
  static const int kJSObjectType = 0xb2;
5423
  static const int kFirstNonstringType = 0x80;
5424
  static const int kOddballType = 0x83;
5425
  static const int kForeignType = 0x87;
5426

    
5427
  static const int kUndefinedOddballKind = 5;
5428
  static const int kNullOddballKind = 3;
5429

    
5430
  V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
5431
  V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
5432
#ifdef V8_ENABLE_CHECKS
5433
    CheckInitializedImpl(isolate);
5434
#endif
5435
  }
5436

    
5437
  V8_INLINE static bool HasHeapObjectTag(internal::Object* value) {
5438
    return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
5439
            kHeapObjectTag);
5440
  }
5441

    
5442
  V8_INLINE static int SmiValue(internal::Object* value) {
5443
    return PlatformSmiTagging::SmiToInt(value);
5444
  }
5445

    
5446
  V8_INLINE static internal::Object* IntToSmi(int value) {
5447
    return PlatformSmiTagging::IntToSmi(value);
5448
  }
5449

    
5450
  V8_INLINE static bool IsValidSmi(intptr_t value) {
5451
    return PlatformSmiTagging::IsValidSmi(value);
5452
  }
5453

    
5454
  V8_INLINE static int GetInstanceType(internal::Object* obj) {
5455
    typedef internal::Object O;
5456
    O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
5457
    return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
5458
  }
5459

    
5460
  V8_INLINE static int GetOddballKind(internal::Object* obj) {
5461
    typedef internal::Object O;
5462
    return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
5463
  }
5464

    
5465
  V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
5466
    int representation = (instance_type & kFullStringRepresentationMask);
5467
    return representation == kExternalTwoByteRepresentationTag;
5468
  }
5469

    
5470
  V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
5471
      uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5472
      return *addr & static_cast<uint8_t>(1U << shift);
5473
  }
5474

    
5475
  V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
5476
                                       bool value, int shift) {
5477
      uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5478
      uint8_t mask = static_cast<uint8_t>(1 << shift);
5479
      *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
5480
  }
5481

    
5482
  V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
5483
    uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5484
    return *addr & kNodeStateMask;
5485
  }
5486

    
5487
  V8_INLINE static void UpdateNodeState(internal::Object** obj,
5488
                                        uint8_t value) {
5489
    uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5490
    *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
5491
  }
5492

    
5493
  V8_INLINE static void SetEmbedderData(v8::Isolate* isolate, void* data) {
5494
    uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
5495
        kIsolateEmbedderDataOffset;
5496
    *reinterpret_cast<void**>(addr) = data;
5497
  }
5498

    
5499
  V8_INLINE static void* GetEmbedderData(v8::Isolate* isolate) {
5500
    uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
5501
        kIsolateEmbedderDataOffset;
5502
    return *reinterpret_cast<void**>(addr);
5503
  }
5504

    
5505
  V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
5506
                                              int index) {
5507
    uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
5508
    return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
5509
  }
5510

    
5511
  template <typename T> V8_INLINE static T ReadField(Object* ptr, int offset) {
5512
    uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
5513
    return *reinterpret_cast<T*>(addr);
5514
  }
5515

    
5516
  template <typename T>
5517
  V8_INLINE static T ReadEmbedderData(Context* context, int index) {
5518
    typedef internal::Object O;
5519
    typedef internal::Internals I;
5520
    O* ctx = *reinterpret_cast<O**>(context);
5521
    int embedder_data_offset = I::kContextHeaderSize +
5522
        (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
5523
    O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
5524
    int value_offset =
5525
        I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
5526
    return I::ReadField<T>(embedder_data, value_offset);
5527
  }
5528

    
5529
  V8_INLINE static bool CanCastToHeapObject(void* o) { return false; }
5530
  V8_INLINE static bool CanCastToHeapObject(Context* o) { return true; }
5531
  V8_INLINE static bool CanCastToHeapObject(String* o) { return true; }
5532
  V8_INLINE static bool CanCastToHeapObject(Object* o) { return true; }
5533
  V8_INLINE static bool CanCastToHeapObject(Message* o) { return true; }
5534
  V8_INLINE static bool CanCastToHeapObject(StackTrace* o) { return true; }
5535
  V8_INLINE static bool CanCastToHeapObject(StackFrame* o) { return true; }
5536
};
5537

    
5538
}  // namespace internal
5539

    
5540

    
5541
template <class T>
5542
Local<T>::Local() : Handle<T>() { }
5543

    
5544

    
5545
template <class T>
5546
Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
5547
  return New(isolate, that.val_);
5548
}
5549

    
5550
template <class T>
5551
template <class M>
5552
Local<T> Local<T>::New(Isolate* isolate, const Persistent<T, M>& that) {
5553
  return New(isolate, that.val_);
5554
}
5555

    
5556
template <class T>
5557
Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
5558
  if (that == NULL) return Handle<T>();
5559
  T* that_ptr = that;
5560
  internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5561
  return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5562
      reinterpret_cast<internal::Isolate*>(isolate), *p)));
5563
}
5564

    
5565

    
5566
template <class T>
5567
Local<T> Local<T>::New(Isolate* isolate, T* that) {
5568
  if (that == NULL) return Local<T>();
5569
  T* that_ptr = that;
5570
  internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5571
  return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5572
      reinterpret_cast<internal::Isolate*>(isolate), *p)));
5573
}
5574

    
5575

    
5576
template<class T>
5577
template<class S>
5578
void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
5579
  TYPE_CHECK(T, S);
5580
  V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
5581
}
5582

    
5583

    
5584
template<class T>
5585
Local<T> Eternal<T>::Get(Isolate* isolate) {
5586
  return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
5587
}
5588

    
5589

    
5590
template <class T, class M>
5591
T* Persistent<T, M>::New(Isolate* isolate, T* that) {
5592
  if (that == NULL) return NULL;
5593
  internal::Object** p = reinterpret_cast<internal::Object**>(that);
5594
  return reinterpret_cast<T*>(
5595
      V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
5596
                             p));
5597
}
5598

    
5599

    
5600
template <class T, class M>
5601
template <class S, class M2>
5602
void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
5603
  TYPE_CHECK(T, S);
5604
  Reset();
5605
  if (that.IsEmpty()) return;
5606
  internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
5607
  this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
5608
  M::Copy(that, this);
5609
}
5610

    
5611

    
5612
template <class T, class M>
5613
bool Persistent<T, M>::IsIndependent() const {
5614
  typedef internal::Internals I;
5615
  if (this->IsEmpty()) return false;
5616
  return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5617
                        I::kNodeIsIndependentShift);
5618
}
5619

    
5620

    
5621
template <class T, class M>
5622
bool Persistent<T, M>::IsNearDeath() const {
5623
  typedef internal::Internals I;
5624
  if (this->IsEmpty()) return false;
5625
  uint8_t node_state =
5626
      I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
5627
  return node_state == I::kNodeStateIsNearDeathValue ||
5628
      node_state == I::kNodeStateIsPendingValue;
5629
}
5630

    
5631

    
5632
template <class T, class M>
5633
bool Persistent<T, M>::IsWeak() const {
5634
  typedef internal::Internals I;
5635
  if (this->IsEmpty()) return false;
5636
  return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
5637
      I::kNodeStateIsWeakValue;
5638
}
5639

    
5640

    
5641
template <class T, class M>
5642
void Persistent<T, M>::Reset() {
5643
  if (this->IsEmpty()) return;
5644
  V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
5645
  val_ = 0;
5646
}
5647

    
5648

    
5649
template <class T, class M>
5650
template <class S>
5651
void Persistent<T, M>::Reset(Isolate* isolate, const Handle<S>& other) {
5652
  TYPE_CHECK(T, S);
5653
  Reset();
5654
  if (other.IsEmpty()) return;
5655
  this->val_ = New(isolate, other.val_);
5656
}
5657

    
5658

    
5659
template <class T,  class M>
5660
template <class S, class M2>
5661
void Persistent<T, M>::Reset(Isolate* isolate,
5662
                             const Persistent<S, M2>& other) {
5663
  TYPE_CHECK(T, S);
5664
  Reset();
5665
  if (other.IsEmpty()) return;
5666
  this->val_ = New(isolate, other.val_);
5667
}
5668

    
5669

    
5670
template <class T, class M>
5671
template <typename S, typename P>
5672
void Persistent<T, M>::SetWeak(
5673
    P* parameter,
5674
    typename WeakCallbackData<S, P>::Callback callback) {
5675
  TYPE_CHECK(S, T);
5676
  typedef typename WeakCallbackData<Value, void>::Callback Callback;
5677
  V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_),
5678
               parameter,
5679
               reinterpret_cast<Callback>(callback),
5680
               NULL);
5681
}
5682

    
5683

    
5684
template <class T, class M>
5685
template <typename P>
5686
void Persistent<T, M>::SetWeak(
5687
    P* parameter,
5688
    typename WeakCallbackData<T, P>::Callback callback) {
5689
  SetWeak<T, P>(parameter, callback);
5690
}
5691

    
5692

    
5693
template <class T, class M>
5694
template <typename S, typename P>
5695
void Persistent<T, M>::MakeWeak(
5696
    P* parameters,
5697
    typename WeakReferenceCallbacks<S, P>::Revivable callback) {
5698
  TYPE_CHECK(S, T);
5699
  typedef typename WeakReferenceCallbacks<Value, void>::Revivable Revivable;
5700
  V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_),
5701
               parameters,
5702
               NULL,
5703
               reinterpret_cast<Revivable>(callback));
5704
}
5705

    
5706

    
5707
template <class T, class M>
5708
template <typename P>
5709
void Persistent<T, M>::MakeWeak(
5710
    P* parameters,
5711
    typename WeakReferenceCallbacks<T, P>::Revivable callback) {
5712
  MakeWeak<T, P>(parameters, callback);
5713
}
5714

    
5715

    
5716
template <class T, class M>
5717
void Persistent<T, M>::ClearWeak() {
5718
  V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_));
5719
}
5720

    
5721

    
5722
template <class T, class M>
5723
void Persistent<T, M>::MarkIndependent() {
5724
  typedef internal::Internals I;
5725
  if (this->IsEmpty()) return;
5726
  I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5727
                    true,
5728
                    I::kNodeIsIndependentShift);
5729
}
5730

    
5731

    
5732
template <class T, class M>
5733
void Persistent<T, M>::MarkPartiallyDependent() {
5734
  typedef internal::Internals I;
5735
  if (this->IsEmpty()) return;
5736
  I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5737
                    true,
5738
                    I::kNodeIsPartiallyDependentShift);
5739
}
5740

    
5741

    
5742
template <class T, class M>
5743
T* Persistent<T, M>::ClearAndLeak() {
5744
  T* old;
5745
  old = val_;
5746
  val_ = NULL;
5747
  return old;
5748
}
5749

    
5750

    
5751
template <class T, class M>
5752
void Persistent<T, M>::SetWrapperClassId(uint16_t class_id) {
5753
  typedef internal::Internals I;
5754
  if (this->IsEmpty()) return;
5755
  internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
5756
  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
5757
  *reinterpret_cast<uint16_t*>(addr) = class_id;
5758
}
5759

    
5760

    
5761
template <class T, class M>
5762
uint16_t Persistent<T, M>::WrapperClassId() const {
5763
  typedef internal::Internals I;
5764
  if (this->IsEmpty()) return 0;
5765
  internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
5766
  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
5767
  return *reinterpret_cast<uint16_t*>(addr);
5768
}
5769

    
5770

    
5771
template<typename T>
5772
ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
5773

    
5774
template<typename T>
5775
template<typename S>
5776
void ReturnValue<T>::Set(const Persistent<S>& handle) {
5777
  TYPE_CHECK(T, S);
5778
  if (V8_UNLIKELY(handle.IsEmpty())) {
5779
    *value_ = GetDefaultValue();
5780
  } else {
5781
    *value_ = *reinterpret_cast<internal::Object**>(*handle);
5782
  }
5783
}
5784

    
5785
template<typename T>
5786
template<typename S>
5787
void ReturnValue<T>::Set(const Handle<S> handle) {
5788
  TYPE_CHECK(T, S);
5789
  if (V8_UNLIKELY(handle.IsEmpty())) {
5790
    *value_ = GetDefaultValue();
5791
  } else {
5792
    *value_ = *reinterpret_cast<internal::Object**>(*handle);
5793
  }
5794
}
5795

    
5796
template<typename T>
5797
void ReturnValue<T>::Set(double i) {
5798
  TYPE_CHECK(T, Number);
5799
  Set(Number::New(GetIsolate(), i));
5800
}
5801

    
5802
template<typename T>
5803
void ReturnValue<T>::Set(int32_t i) {
5804
  TYPE_CHECK(T, Integer);
5805
  typedef internal::Internals I;
5806
  if (V8_LIKELY(I::IsValidSmi(i))) {
5807
    *value_ = I::IntToSmi(i);
5808
    return;
5809
  }
5810
  Set(Integer::New(i, GetIsolate()));
5811
}
5812

    
5813
template<typename T>
5814
void ReturnValue<T>::Set(uint32_t i) {
5815
  TYPE_CHECK(T, Integer);
5816
  typedef internal::Internals I;
5817
  // Can't simply use INT32_MAX here for whatever reason.
5818
  bool fits_into_int32_t = (i & (1U << 31)) == 0;
5819
  if (V8_LIKELY(fits_into_int32_t)) {
5820
    Set(static_cast<int32_t>(i));
5821
    return;
5822
  }
5823
  Set(Integer::NewFromUnsigned(i, GetIsolate()));
5824
}
5825

    
5826
template<typename T>
5827
void ReturnValue<T>::Set(bool value) {
5828
  TYPE_CHECK(T, Boolean);
5829
  typedef internal::Internals I;
5830
  int root_index;
5831
  if (value) {
5832
    root_index = I::kTrueValueRootIndex;
5833
  } else {
5834
    root_index = I::kFalseValueRootIndex;
5835
  }
5836
  *value_ = *I::GetRoot(GetIsolate(), root_index);
5837
}
5838

    
5839
template<typename T>
5840
void ReturnValue<T>::SetNull() {
5841
  TYPE_CHECK(T, Primitive);
5842
  typedef internal::Internals I;
5843
  *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
5844
}
5845

    
5846
template<typename T>
5847
void ReturnValue<T>::SetUndefined() {
5848
  TYPE_CHECK(T, Primitive);
5849
  typedef internal::Internals I;
5850
  *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
5851
}
5852

    
5853
template<typename T>
5854
void ReturnValue<T>::SetEmptyString() {
5855
  TYPE_CHECK(T, String);
5856
  typedef internal::Internals I;
5857
  *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
5858
}
5859

    
5860
template<typename T>
5861
Isolate* ReturnValue<T>::GetIsolate() {
5862
  // Isolate is always the pointer below the default value on the stack.
5863
  return *reinterpret_cast<Isolate**>(&value_[-2]);
5864
}
5865

    
5866
template<typename T>
5867
internal::Object* ReturnValue<T>::GetDefaultValue() {
5868
  // Default value is always the pointer below value_ on the stack.
5869
  return value_[-1];
5870
}
5871

    
5872

    
5873
template<typename T>
5874
FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
5875
                                              internal::Object** values,
5876
                                              int length,
5877
                                              bool is_construct_call)
5878
    : implicit_args_(implicit_args),
5879
      values_(values),
5880
      length_(length),
5881
      is_construct_call_(is_construct_call) { }
5882

    
5883

    
5884
template<typename T>
5885
Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
5886
  if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
5887
  return Local<Value>(reinterpret_cast<Value*>(values_ - i));
5888
}
5889

    
5890

    
5891
template<typename T>
5892
Local<Function> FunctionCallbackInfo<T>::Callee() const {
5893
  return Local<Function>(reinterpret_cast<Function*>(
5894
      &implicit_args_[kCalleeIndex]));
5895
}
5896

    
5897

    
5898
template<typename T>
5899
Local<Object> FunctionCallbackInfo<T>::This() const {
5900
  return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
5901
}
5902

    
5903

    
5904
template<typename T>
5905
Local<Object> FunctionCallbackInfo<T>::Holder() const {
5906
  return Local<Object>(reinterpret_cast<Object*>(
5907
      &implicit_args_[kHolderIndex]));
5908
}
5909

    
5910

    
5911
template<typename T>
5912
Local<Value> FunctionCallbackInfo<T>::Data() const {
5913
  return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
5914
}
5915

    
5916

    
5917
template<typename T>
5918
Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
5919
  return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
5920
}
5921

    
5922

    
5923
template<typename T>
5924
ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
5925
  return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
5926
}
5927

    
5928

    
5929
template<typename T>
5930
bool FunctionCallbackInfo<T>::IsConstructCall() const {
5931
  return is_construct_call_;
5932
}
5933

    
5934

    
5935
template<typename T>
5936
int FunctionCallbackInfo<T>::Length() const {
5937
  return length_;
5938
}
5939

    
5940

    
5941
template <class T>
5942
Local<T> HandleScope::Close(Handle<T> value) {
5943
  internal::Object** before = reinterpret_cast<internal::Object**>(*value);
5944
  internal::Object** after = RawClose(before);
5945
  return Local<T>(reinterpret_cast<T*>(after));
5946
}
5947

    
5948
Handle<Value> ScriptOrigin::ResourceName() const {
5949
  return resource_name_;
5950
}
5951

    
5952

    
5953
Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
5954
  return resource_line_offset_;
5955
}
5956

    
5957

    
5958
Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
5959
  return resource_column_offset_;
5960
}
5961

    
5962
Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
5963
  return resource_is_shared_cross_origin_;
5964
}
5965

    
5966

    
5967
Handle<Boolean> Boolean::New(bool value) {
5968
  Isolate* isolate = Isolate::GetCurrent();
5969
  return value ? True(isolate) : False(isolate);
5970
}
5971

    
5972

    
5973
void Template::Set(const char* name, v8::Handle<Data> value) {
5974
  Set(v8::String::New(name), value);
5975
}
5976

    
5977

    
5978
Local<Value> Object::GetInternalField(int index) {
5979
#ifndef V8_ENABLE_CHECKS
5980
  typedef internal::Object O;
5981
  typedef internal::HeapObject HO;
5982
  typedef internal::Internals I;
5983
  O* obj = *reinterpret_cast<O**>(this);
5984
  // Fast path: If the object is a plain JSObject, which is the common case, we
5985
  // know where to find the internal fields and can return the value directly.
5986
  if (I::GetInstanceType(obj) == I::kJSObjectType) {
5987
    int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
5988
    O* value = I::ReadField<O*>(obj, offset);
5989
    O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
5990
    return Local<Value>(reinterpret_cast<Value*>(result));
5991
  }
5992
#endif
5993
  return SlowGetInternalField(index);
5994
}
5995

    
5996

    
5997
void* Object::GetAlignedPointerFromInternalField(int index) {
5998
#ifndef V8_ENABLE_CHECKS
5999
  typedef internal::Object O;
6000
  typedef internal::Internals I;
6001
  O* obj = *reinterpret_cast<O**>(this);
6002
  // Fast path: If the object is a plain JSObject, which is the common case, we
6003
  // know where to find the internal fields and can return the value directly.
6004
  if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
6005
    int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6006
    return I::ReadField<void*>(obj, offset);
6007
  }
6008
#endif
6009
  return SlowGetAlignedPointerFromInternalField(index);
6010
}
6011

    
6012

    
6013
String* String::Cast(v8::Value* value) {
6014
#ifdef V8_ENABLE_CHECKS
6015
  CheckCast(value);
6016
#endif
6017
  return static_cast<String*>(value);
6018
}
6019

    
6020

    
6021
Local<String> String::Empty(Isolate* isolate) {
6022
  typedef internal::Object* S;
6023
  typedef internal::Internals I;
6024
  I::CheckInitialized(isolate);
6025
  S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
6026
  return Local<String>(reinterpret_cast<String*>(slot));
6027
}
6028

    
6029

    
6030
Local<String> String::New(const char* data, int length) {
6031
  return NewFromUtf8(Isolate::GetCurrent(), data, kNormalString, length);
6032
}
6033

    
6034

    
6035
Local<String> String::New(const uint16_t* data, int length) {
6036
  return NewFromTwoByte(Isolate::GetCurrent(), data, kNormalString, length);
6037
}
6038

    
6039

    
6040
Local<String> String::NewSymbol(const char* data, int length) {
6041
  return NewFromUtf8(Isolate::GetCurrent(), data, kInternalizedString, length);
6042
}
6043

    
6044

    
6045
Local<String> String::NewUndetectable(const char* data, int length) {
6046
  return NewFromUtf8(Isolate::GetCurrent(), data, kUndetectableString, length);
6047
}
6048

    
6049

    
6050
Local<String> String::NewUndetectable(const uint16_t* data, int length) {
6051
  return NewFromTwoByte(
6052
      Isolate::GetCurrent(), data, kUndetectableString, length);
6053
}
6054

    
6055

    
6056
String::ExternalStringResource* String::GetExternalStringResource() const {
6057
  typedef internal::Object O;
6058
  typedef internal::Internals I;
6059
  O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
6060
  String::ExternalStringResource* result;
6061
  if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
6062
    void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6063
    result = reinterpret_cast<String::ExternalStringResource*>(value);
6064
  } else {
6065
    result = NULL;
6066
  }
6067
#ifdef V8_ENABLE_CHECKS
6068
  VerifyExternalStringResource(result);
6069
#endif
6070
  return result;
6071
}
6072

    
6073

    
6074
String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
6075
    String::Encoding* encoding_out) const {
6076
  typedef internal::Object O;
6077
  typedef internal::Internals I;
6078
  O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
6079
  int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
6080
  *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
6081
  ExternalStringResourceBase* resource = NULL;
6082
  if (type == I::kExternalAsciiRepresentationTag ||
6083
      type == I::kExternalTwoByteRepresentationTag) {
6084
    void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6085
    resource = static_cast<ExternalStringResourceBase*>(value);
6086
  }
6087
#ifdef V8_ENABLE_CHECKS
6088
    VerifyExternalStringResourceBase(resource, *encoding_out);
6089
#endif
6090
  return resource;
6091
}
6092

    
6093

    
6094
bool Value::IsUndefined() const {
6095
#ifdef V8_ENABLE_CHECKS
6096
  return FullIsUndefined();
6097
#else
6098
  return QuickIsUndefined();
6099
#endif
6100
}
6101

    
6102
bool Value::QuickIsUndefined() const {
6103
  typedef internal::Object O;
6104
  typedef internal::Internals I;
6105
  O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6106
  if (!I::HasHeapObjectTag(obj)) return false;
6107
  if (I::GetInstanceType(obj) != I::kOddballType) return false;
6108
  return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
6109
}
6110

    
6111

    
6112
bool Value::IsNull() const {
6113
#ifdef V8_ENABLE_CHECKS
6114
  return FullIsNull();
6115
#else
6116
  return QuickIsNull();
6117
#endif
6118
}
6119

    
6120
bool Value::QuickIsNull() const {
6121
  typedef internal::Object O;
6122
  typedef internal::Internals I;
6123
  O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6124
  if (!I::HasHeapObjectTag(obj)) return false;
6125
  if (I::GetInstanceType(obj) != I::kOddballType) return false;
6126
  return (I::GetOddballKind(obj) == I::kNullOddballKind);
6127
}
6128

    
6129

    
6130
bool Value::IsString() const {
6131
#ifdef V8_ENABLE_CHECKS
6132
  return FullIsString();
6133
#else
6134
  return QuickIsString();
6135
#endif
6136
}
6137

    
6138
bool Value::QuickIsString() const {
6139
  typedef internal::Object O;
6140
  typedef internal::Internals I;
6141
  O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6142
  if (!I::HasHeapObjectTag(obj)) return false;
6143
  return (I::GetInstanceType(obj) < I::kFirstNonstringType);
6144
}
6145

    
6146

    
6147
template <class T> Value* Value::Cast(T* value) {
6148
  return static_cast<Value*>(value);
6149
}
6150

    
6151

    
6152
Symbol* Symbol::Cast(v8::Value* value) {
6153
#ifdef V8_ENABLE_CHECKS
6154
  CheckCast(value);
6155
#endif
6156
  return static_cast<Symbol*>(value);
6157
}
6158

    
6159

    
6160
Number* Number::Cast(v8::Value* value) {
6161
#ifdef V8_ENABLE_CHECKS
6162
  CheckCast(value);
6163
#endif
6164
  return static_cast<Number*>(value);
6165
}
6166

    
6167

    
6168
Integer* Integer::Cast(v8::Value* value) {
6169
#ifdef V8_ENABLE_CHECKS
6170
  CheckCast(value);
6171
#endif
6172
  return static_cast<Integer*>(value);
6173
}
6174

    
6175

    
6176
Date* Date::Cast(v8::Value* value) {
6177
#ifdef V8_ENABLE_CHECKS
6178
  CheckCast(value);
6179
#endif
6180
  return static_cast<Date*>(value);
6181
}
6182

    
6183

    
6184
StringObject* StringObject::Cast(v8::Value* value) {
6185
#ifdef V8_ENABLE_CHECKS
6186
  CheckCast(value);
6187
#endif
6188
  return static_cast<StringObject*>(value);
6189
}
6190

    
6191

    
6192
SymbolObject* SymbolObject::Cast(v8::Value* value) {
6193
#ifdef V8_ENABLE_CHECKS
6194
  CheckCast(value);
6195
#endif
6196
  return static_cast<SymbolObject*>(value);
6197
}
6198

    
6199

    
6200
NumberObject* NumberObject::Cast(v8::Value* value) {
6201
#ifdef V8_ENABLE_CHECKS
6202
  CheckCast(value);
6203
#endif
6204
  return static_cast<NumberObject*>(value);
6205
}
6206

    
6207

    
6208
BooleanObject* BooleanObject::Cast(v8::Value* value) {
6209
#ifdef V8_ENABLE_CHECKS
6210
  CheckCast(value);
6211
#endif
6212
  return static_cast<BooleanObject*>(value);
6213
}
6214

    
6215

    
6216
RegExp* RegExp::Cast(v8::Value* value) {
6217
#ifdef V8_ENABLE_CHECKS
6218
  CheckCast(value);
6219
#endif
6220
  return static_cast<RegExp*>(value);
6221
}
6222

    
6223

    
6224
Object* Object::Cast(v8::Value* value) {
6225
#ifdef V8_ENABLE_CHECKS
6226
  CheckCast(value);
6227
#endif
6228
  return static_cast<Object*>(value);
6229
}
6230

    
6231

    
6232
Array* Array::Cast(v8::Value* value) {
6233
#ifdef V8_ENABLE_CHECKS
6234
  CheckCast(value);
6235
#endif
6236
  return static_cast<Array*>(value);
6237
}
6238

    
6239

    
6240
ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
6241
#ifdef V8_ENABLE_CHECKS
6242
  CheckCast(value);
6243
#endif
6244
  return static_cast<ArrayBuffer*>(value);
6245
}
6246

    
6247

    
6248
ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
6249
#ifdef V8_ENABLE_CHECKS
6250
  CheckCast(value);
6251
#endif
6252
  return static_cast<ArrayBufferView*>(value);
6253
}
6254

    
6255

    
6256
TypedArray* TypedArray::Cast(v8::Value* value) {
6257
#ifdef V8_ENABLE_CHECKS
6258
  CheckCast(value);
6259
#endif
6260
  return static_cast<TypedArray*>(value);
6261
}
6262

    
6263

    
6264
Uint8Array* Uint8Array::Cast(v8::Value* value) {
6265
#ifdef V8_ENABLE_CHECKS
6266
  CheckCast(value);
6267
#endif
6268
  return static_cast<Uint8Array*>(value);
6269
}
6270

    
6271

    
6272
Int8Array* Int8Array::Cast(v8::Value* value) {
6273
#ifdef V8_ENABLE_CHECKS
6274
  CheckCast(value);
6275
#endif
6276
  return static_cast<Int8Array*>(value);
6277
}
6278

    
6279

    
6280
Uint16Array* Uint16Array::Cast(v8::Value* value) {
6281
#ifdef V8_ENABLE_CHECKS
6282
  CheckCast(value);
6283
#endif
6284
  return static_cast<Uint16Array*>(value);
6285
}
6286

    
6287

    
6288
Int16Array* Int16Array::Cast(v8::Value* value) {
6289
#ifdef V8_ENABLE_CHECKS
6290
  CheckCast(value);
6291
#endif
6292
  return static_cast<Int16Array*>(value);
6293
}
6294

    
6295

    
6296
Uint32Array* Uint32Array::Cast(v8::Value* value) {
6297
#ifdef V8_ENABLE_CHECKS
6298
  CheckCast(value);
6299
#endif
6300
  return static_cast<Uint32Array*>(value);
6301
}
6302

    
6303

    
6304
Int32Array* Int32Array::Cast(v8::Value* value) {
6305
#ifdef V8_ENABLE_CHECKS
6306
  CheckCast(value);
6307
#endif
6308
  return static_cast<Int32Array*>(value);
6309
}
6310

    
6311

    
6312
Float32Array* Float32Array::Cast(v8::Value* value) {
6313
#ifdef V8_ENABLE_CHECKS
6314
  CheckCast(value);
6315
#endif
6316
  return static_cast<Float32Array*>(value);
6317
}
6318

    
6319

    
6320
Float64Array* Float64Array::Cast(v8::Value* value) {
6321
#ifdef V8_ENABLE_CHECKS
6322
  CheckCast(value);
6323
#endif
6324
  return static_cast<Float64Array*>(value);
6325
}
6326

    
6327

    
6328
Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
6329
#ifdef V8_ENABLE_CHECKS
6330
  CheckCast(value);
6331
#endif
6332
  return static_cast<Uint8ClampedArray*>(value);
6333
}
6334

    
6335

    
6336
DataView* DataView::Cast(v8::Value* value) {
6337
#ifdef V8_ENABLE_CHECKS
6338
  CheckCast(value);
6339
#endif
6340
  return static_cast<DataView*>(value);
6341
}
6342

    
6343

    
6344
Function* Function::Cast(v8::Value* value) {
6345
#ifdef V8_ENABLE_CHECKS
6346
  CheckCast(value);
6347
#endif
6348
  return static_cast<Function*>(value);
6349
}
6350

    
6351

    
6352
External* External::Cast(v8::Value* value) {
6353
#ifdef V8_ENABLE_CHECKS
6354
  CheckCast(value);
6355
#endif
6356
  return static_cast<External*>(value);
6357
}
6358

    
6359

    
6360
template<typename T>
6361
Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
6362
  return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
6363
}
6364

    
6365

    
6366
template<typename T>
6367
Local<Value> PropertyCallbackInfo<T>::Data() const {
6368
  return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
6369
}
6370

    
6371

    
6372
template<typename T>
6373
Local<Object> PropertyCallbackInfo<T>::This() const {
6374
  return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
6375
}
6376

    
6377

    
6378
template<typename T>
6379
Local<Object> PropertyCallbackInfo<T>::Holder() const {
6380
  return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
6381
}
6382

    
6383

    
6384
template<typename T>
6385
ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
6386
  return ReturnValue<T>(&args_[kReturnValueIndex]);
6387
}
6388

    
6389

    
6390
Handle<Primitive> Undefined(Isolate* isolate) {
6391
  typedef internal::Object* S;
6392
  typedef internal::Internals I;
6393
  I::CheckInitialized(isolate);
6394
  S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
6395
  return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6396
}
6397

    
6398

    
6399
Handle<Primitive> Null(Isolate* isolate) {
6400
  typedef internal::Object* S;
6401
  typedef internal::Internals I;
6402
  I::CheckInitialized(isolate);
6403
  S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
6404
  return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6405
}
6406

    
6407

    
6408
Handle<Boolean> True(Isolate* isolate) {
6409
  typedef internal::Object* S;
6410
  typedef internal::Internals I;
6411
  I::CheckInitialized(isolate);
6412
  S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
6413
  return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6414
}
6415

    
6416

    
6417
Handle<Boolean> False(Isolate* isolate) {
6418
  typedef internal::Object* S;
6419
  typedef internal::Internals I;
6420
  I::CheckInitialized(isolate);
6421
  S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
6422
  return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6423
}
6424

    
6425

    
6426
void Isolate::SetData(void* data) {
6427
  typedef internal::Internals I;
6428
  I::SetEmbedderData(this, data);
6429
}
6430

    
6431

    
6432
void* Isolate::GetData() {
6433
  typedef internal::Internals I;
6434
  return I::GetEmbedderData(this);
6435
}
6436

    
6437

    
6438
template<typename T>
6439
void Isolate::SetObjectGroupId(const Persistent<T>& object,
6440
                               UniqueId id) {
6441
  TYPE_CHECK(Value, T);
6442
  SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
6443
}
6444

    
6445

    
6446
template<typename T>
6447
void Isolate::SetReferenceFromGroup(UniqueId id,
6448
                                    const Persistent<T>& object) {
6449
  TYPE_CHECK(Value, T);
6450
  SetReferenceFromGroup(id,
6451
                        reinterpret_cast<v8::internal::Object**>(object.val_));
6452
}
6453

    
6454

    
6455
template<typename T, typename S>
6456
void Isolate::SetReference(const Persistent<T>& parent,
6457
                           const Persistent<S>& child) {
6458
  TYPE_CHECK(Object, T);
6459
  TYPE_CHECK(Value, S);
6460
  SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
6461
               reinterpret_cast<v8::internal::Object**>(child.val_));
6462
}
6463

    
6464

    
6465
Local<Value> Context::GetEmbedderData(int index) {
6466
#ifndef V8_ENABLE_CHECKS
6467
  typedef internal::Object O;
6468
  typedef internal::HeapObject HO;
6469
  typedef internal::Internals I;
6470
  HO* context = *reinterpret_cast<HO**>(this);
6471
  O** result =
6472
      HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
6473
  return Local<Value>(reinterpret_cast<Value*>(result));
6474
#else
6475
  return SlowGetEmbedderData(index);
6476
#endif
6477
}
6478

    
6479

    
6480
void* Context::GetAlignedPointerFromEmbedderData(int index) {
6481
#ifndef V8_ENABLE_CHECKS
6482
  typedef internal::Internals I;
6483
  return I::ReadEmbedderData<void*>(this, index);
6484
#else
6485
  return SlowGetAlignedPointerFromEmbedderData(index);
6486
#endif
6487
}
6488

    
6489

    
6490
/**
6491
 * \example shell.cc
6492
 * A simple shell that takes a list of expressions on the
6493
 * command-line and executes them.
6494
 */
6495

    
6496

    
6497
/**
6498
 * \example process.cc
6499
 */
6500

    
6501

    
6502
}  // namespace v8
6503

    
6504

    
6505
#undef TYPE_CHECK
6506

    
6507

    
6508
#endif  // V8_H_