Merge the backout head.
[mozilla-central.git] / js / src / jsobj.h
blob00d676f5dbf91cb7f0239dbc0022efc13a3550cf
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sw=4 et tw=78:
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
17 * The Original Code is Mozilla Communicator client code, released
18 * March 31, 1998.
20 * The Initial Developer of the Original Code is
21 * Netscape Communications Corporation.
22 * Portions created by the Initial Developer are Copyright (C) 1998
23 * the Initial Developer. All Rights Reserved.
25 * Contributor(s):
27 * Alternatively, the contents of this file may be used under the terms of
28 * either of the GNU General Public License Version 2 or later (the "GPL"),
29 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
39 * ***** END LICENSE BLOCK ***** */
41 #ifndef jsobj_h___
42 #define jsobj_h___
44 /* Gross special case for Gecko, which defines malloc/calloc/free. */
45 #ifdef mozilla_mozalloc_macro_wrappers_h
46 # define JS_OBJ_UNDEFD_MOZALLOC_WRAPPERS
47 /* The "anti-header" */
48 # include "mozilla/mozalloc_undef_macro_wrappers.h"
49 #endif
52 * JS object definitions.
54 * A JS object consists of a possibly-shared object descriptor containing
55 * ordered property names, called the map; and a dense vector of property
56 * values, called slots. The map/slot pointer pair is GC'ed, while the map
57 * is reference counted and the slot vector is malloc'ed.
59 #include "jsapi.h"
60 #include "jshash.h"
61 #include "jspubtd.h"
62 #include "jsprvtd.h"
63 #include "jslock.h"
64 #include "jsvalue.h"
65 #include "jsvector.h"
66 #include "jscell.h"
68 namespace js {
70 class JSProxyHandler;
71 class AutoPropDescArrayRooter;
73 namespace mjit {
74 class Compiler;
77 static inline PropertyOp
78 CastAsPropertyOp(JSObject *object)
80 return JS_DATA_TO_FUNC_PTR(PropertyOp, object);
83 static inline JSPropertyOp
84 CastAsJSPropertyOp(JSObject *object)
86 return JS_DATA_TO_FUNC_PTR(JSPropertyOp, object);
89 inline JSObject *
90 CastAsObject(PropertyOp op)
92 return JS_FUNC_TO_DATA_PTR(JSObject *, op);
95 inline Value
96 CastAsObjectJsval(PropertyOp op)
98 return ObjectOrNullValue(CastAsObject(op));
101 } /* namespace js */
104 * A representation of ECMA-262 ed. 5's internal property descriptor data
105 * structure.
107 struct PropDesc {
108 friend class js::AutoPropDescArrayRooter;
110 PropDesc();
112 public:
113 /* 8.10.5 ToPropertyDescriptor(Obj) */
114 bool initialize(JSContext* cx, jsid id, const js::Value &v);
116 /* 8.10.1 IsAccessorDescriptor(desc) */
117 bool isAccessorDescriptor() const {
118 return hasGet || hasSet;
121 /* 8.10.2 IsDataDescriptor(desc) */
122 bool isDataDescriptor() const {
123 return hasValue || hasWritable;
126 /* 8.10.3 IsGenericDescriptor(desc) */
127 bool isGenericDescriptor() const {
128 return !isAccessorDescriptor() && !isDataDescriptor();
131 bool configurable() const {
132 return (attrs & JSPROP_PERMANENT) == 0;
135 bool enumerable() const {
136 return (attrs & JSPROP_ENUMERATE) != 0;
139 bool writable() const {
140 return (attrs & JSPROP_READONLY) == 0;
143 JSObject* getterObject() const {
144 return get.isUndefined() ? NULL : &get.toObject();
146 JSObject* setterObject() const {
147 return set.isUndefined() ? NULL : &set.toObject();
150 const js::Value &getterValue() const {
151 return get;
153 const js::Value &setterValue() const {
154 return set;
157 js::PropertyOp getter() const {
158 return js::CastAsPropertyOp(getterObject());
160 js::PropertyOp setter() const {
161 return js::CastAsPropertyOp(setterObject());
164 js::Value pd;
165 jsid id;
166 js::Value value, get, set;
168 /* Property descriptor boolean fields. */
169 uint8 attrs;
171 /* Bits indicating which values are set. */
172 bool hasGet : 1;
173 bool hasSet : 1;
174 bool hasValue : 1;
175 bool hasWritable : 1;
176 bool hasEnumerable : 1;
177 bool hasConfigurable : 1;
180 namespace js {
182 typedef Vector<PropDesc, 1> PropDescArray;
184 } /* namespace js */
186 struct JSObjectMap {
187 uint32 shape; /* shape identifier */
188 uint32 slotSpan; /* one more than maximum live slot number */
190 static JS_FRIEND_DATA(const JSObjectMap) sharedNonNative;
192 explicit JSObjectMap(uint32 shape) : shape(shape), slotSpan(0) {}
193 JSObjectMap(uint32 shape, uint32 slotSpan) : shape(shape), slotSpan(slotSpan) {}
195 enum { INVALID_SHAPE = 0x8fffffff, SHAPELESS = 0xffffffff };
197 bool isNative() const { return this != &sharedNonNative; }
199 private:
200 /* No copy or assignment semantics. */
201 JSObjectMap(JSObjectMap &);
202 void operator=(JSObjectMap &);
206 * Unlike js_DefineNativeProperty, propp must be non-null. On success, and if
207 * id was found, return true with *objp non-null and with a property of *objp
208 * stored in *propp. If successful but id was not found, return true with both
209 * *objp and *propp null.
211 extern JS_FRIEND_API(JSBool)
212 js_LookupProperty(JSContext *cx, JSObject *obj, jsid id, JSObject **objp,
213 JSProperty **propp);
215 extern JSBool
216 js_DefineProperty(JSContext *cx, JSObject *obj, jsid id, const js::Value *value,
217 js::PropertyOp getter, js::PropertyOp setter, uintN attrs);
219 extern JSBool
220 js_GetProperty(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, js::Value *vp);
222 inline JSBool
223 js_GetProperty(JSContext *cx, JSObject *obj, jsid id, js::Value *vp)
225 return js_GetProperty(cx, obj, obj, id, vp);
228 namespace js {
230 extern JSBool
231 GetPropertyDefault(JSContext *cx, JSObject *obj, jsid id, const Value &def, Value *vp);
233 } /* namespace js */
235 extern JSBool
236 js_SetProperty(JSContext *cx, JSObject *obj, jsid id, js::Value *vp, JSBool strict);
238 extern JSBool
239 js_GetAttributes(JSContext *cx, JSObject *obj, jsid id, uintN *attrsp);
241 extern JSBool
242 js_SetAttributes(JSContext *cx, JSObject *obj, jsid id, uintN *attrsp);
244 extern JSBool
245 js_DeleteProperty(JSContext *cx, JSObject *obj, jsid id, js::Value *rval, JSBool strict);
247 extern JS_FRIEND_API(JSBool)
248 js_Enumerate(JSContext *cx, JSObject *obj, JSIterateOp enum_op,
249 js::Value *statep, jsid *idp);
251 extern JSType
252 js_TypeOf(JSContext *cx, JSObject *obj);
254 namespace js {
256 struct NativeIterator;
260 struct JSFunction;
262 namespace nanojit {
263 class ValidateWriter;
267 * JSObject struct, with members sized to fit in 32 bytes on 32-bit targets,
268 * 64 bytes on 64-bit systems. The JSFunction struct is an extension of this
269 * struct allocated from a larger GC size-class.
271 * The clasp member stores the js::Class pointer for this object. We do *not*
272 * synchronize updates of clasp or flags -- API clients must take care.
274 * An object is a delegate if it is on another object's prototype (the proto
275 * field) or scope chain (the parent field), and therefore the delegate might
276 * be asked implicitly to get or set a property on behalf of another object.
277 * Delegates may be accessed directly too, as may any object, but only those
278 * objects linked after the head of any prototype or scope chain are flagged
279 * as delegates. This definition helps to optimize shape-based property cache
280 * invalidation (see Purge{Scope,Proto}Chain in jsobj.cpp).
282 * The meaning of the system object bit is defined by the API client. It is
283 * set in JS_NewSystemObject and is queried by JS_IsSystemObject (jsdbgapi.h),
284 * but it has no intrinsic meaning to SpiderMonkey. Further, JSFILENAME_SYSTEM
285 * and JS_FlagScriptFilenamePrefix (also exported via jsdbgapi.h) are intended
286 * to be complementary to this bit, but it is up to the API client to implement
287 * any such association.
289 * Both these flag bits are initially zero; they may be set or queried using
290 * the (is|set)(Delegate|System) inline methods.
292 * The slots member is a pointer to the slot vector for the object.
293 * This can be either a fixed array allocated immediately after the object,
294 * or a dynamically allocated array. A dynamic array can be tested for with
295 * hasSlotsArray(). In all cases, capacity gives the number of usable slots.
296 * Two objects with the same shape have the same number of fixed slots,
297 * and either both have or neither have dynamically allocated slot arrays.
299 * If you change this struct, you'll probably need to change the AccSet values
300 * in jsbuiltins.h.
302 struct JSObject : js::gc::Cell {
304 * TraceRecorder must be a friend because it generates code that
305 * manipulates JSObjects, which requires peeking under any encapsulation.
306 * ValidateWriter must be a friend because it works in tandem with
307 * TraceRecorder.
309 friend class js::TraceRecorder;
310 friend class nanojit::ValidateWriter;
311 friend class GetPropCompiler;
314 * Private pointer to the last added property and methods to manipulate the
315 * list it links among properties in this scope. The {remove,insert} pair
316 * for DictionaryProperties assert that the scope is in dictionary mode and
317 * any reachable properties are flagged as dictionary properties.
319 * For native objects, this field is always a Shape. For non-native objects,
320 * it points to the singleton sharedNonNative JSObjectMap, whose shape field
321 * is SHAPELESS.
323 * NB: these private methods do *not* update this scope's shape to track
324 * lastProp->shape after they finish updating the linked list in the case
325 * where lastProp is updated. It is up to calling code in jsscope.cpp to
326 * call updateShape(cx) after updating lastProp.
328 union {
329 js::Shape *lastProp;
330 JSObjectMap *map;
333 js::Class *clasp;
335 private:
336 inline void setLastProperty(const js::Shape *shape);
337 inline void removeLastProperty();
339 #ifdef DEBUG
340 void checkShapeConsistency();
341 #endif
343 public:
344 inline const js::Shape *lastProperty() const;
346 inline js::Shape **nativeSearch(jsid id, bool adding = false);
347 inline const js::Shape *nativeLookup(jsid id);
349 inline bool nativeContains(jsid id);
350 inline bool nativeContains(const js::Shape &shape);
352 enum {
353 DELEGATE = 0x01,
354 SYSTEM = 0x02,
355 NOT_EXTENSIBLE = 0x04,
356 BRANDED = 0x08,
357 GENERIC = 0x10,
358 METHOD_BARRIER = 0x20,
359 INDEXED = 0x40,
360 OWN_SHAPE = 0x80,
361 BOUND_FUNCTION = 0x100,
362 HAS_EQUALITY = 0x200,
363 METHOD_THRASH_COUNT_MASK = 0xc00,
364 METHOD_THRASH_COUNT_SHIFT = 10,
365 METHOD_THRASH_COUNT_MAX = METHOD_THRASH_COUNT_MASK >> METHOD_THRASH_COUNT_SHIFT
369 * Impose a sane upper bound, originally checked only for dense arrays, on
370 * number of slots in an object.
372 enum {
373 NSLOTS_BITS = 29,
374 NSLOTS_LIMIT = JS_BIT(NSLOTS_BITS)
377 uint32 flags; /* flags */
378 uint32 objShape; /* copy of lastProp->shape, or override if different */
380 /* If prototype, lazily filled array of empty shapes for each object size. */
381 js::EmptyShape **emptyShapes;
383 JSObject *proto; /* object's prototype */
384 JSObject *parent; /* object's parent */
385 void *privateData; /* private data */
386 jsuword capacity; /* capacity of slots */
387 js::Value *slots; /* dynamically allocated slots,
388 or pointer to fixedSlots() */
391 * Return an immutable, shareable, empty shape with the same clasp as this
392 * and the same slotSpan as this had when empty.
394 * If |this| is the scope of an object |proto|, the resulting scope can be
395 * used as the scope of a new object whose prototype is |proto|.
397 inline bool canProvideEmptyShape(js::Class *clasp);
398 inline js::EmptyShape *getEmptyShape(JSContext *cx, js::Class *aclasp,
399 /* gc::FinalizeKind */ unsigned kind);
401 bool isNative() const { return map->isNative(); }
403 js::Class *getClass() const { return clasp; }
404 JSClass *getJSClass() const { return Jsvalify(clasp); }
406 bool hasClass(const js::Class *c) const {
407 return c == clasp;
410 const js::ObjectOps *getOps() const {
411 return &getClass()->ops;
414 inline void trace(JSTracer *trc);
416 uint32 shape() const {
417 JS_ASSERT(objShape != JSObjectMap::INVALID_SHAPE);
418 return objShape;
421 bool isDelegate() const { return !!(flags & DELEGATE); }
422 void setDelegate() { flags |= DELEGATE; }
423 void clearDelegate() { flags &= ~DELEGATE; }
425 bool isBoundFunction() const { return !!(flags & BOUND_FUNCTION); }
427 static void setDelegateNullSafe(JSObject *obj) {
428 if (obj)
429 obj->setDelegate();
432 bool isSystem() const { return !!(flags & SYSTEM); }
433 void setSystem() { flags |= SYSTEM; }
436 * A branded object contains plain old methods (function-valued properties
437 * without magic getters and setters), and its shape evolves whenever a
438 * function value changes.
440 bool branded() { return !!(flags & BRANDED); }
443 * NB: these return false on shape overflow but do not report any error.
444 * Callers who depend on shape guarantees should therefore bail off trace,
445 * e.g., on false returns.
447 bool brand(JSContext *cx);
448 bool unbrand(JSContext *cx);
450 bool generic() { return !!(flags & GENERIC); }
451 void setGeneric() { flags |= GENERIC; }
453 uintN getMethodThrashCount() const {
454 return (flags & METHOD_THRASH_COUNT_MASK) >> METHOD_THRASH_COUNT_SHIFT;
457 void setMethodThrashCount(uintN count) {
458 JS_ASSERT(count <= METHOD_THRASH_COUNT_MAX);
459 flags = (flags & ~METHOD_THRASH_COUNT_MASK) | (count << METHOD_THRASH_COUNT_SHIFT);
462 bool hasSpecialEquality() const { return !!(flags & HAS_EQUALITY); }
463 void assertSpecialEqualitySynced() const {
464 JS_ASSERT(!!clasp->ext.equality == hasSpecialEquality());
467 /* Sets an object's HAS_EQUALITY flag based on its clasp. */
468 inline void syncSpecialEquality();
470 private:
471 void generateOwnShape(JSContext *cx);
473 void setOwnShape(uint32 s) { flags |= OWN_SHAPE; objShape = s; }
474 void clearOwnShape() { flags &= ~OWN_SHAPE; objShape = map->shape; }
476 public:
477 inline bool nativeEmpty() const;
479 bool hasOwnShape() const { return !!(flags & OWN_SHAPE); }
481 void setMap(const JSObjectMap *amap) {
482 JS_ASSERT(!hasOwnShape());
483 map = const_cast<JSObjectMap *>(amap);
484 objShape = map->shape;
487 void setSharedNonNativeMap() {
488 setMap(&JSObjectMap::sharedNonNative);
491 void deletingShapeChange(JSContext *cx, const js::Shape &shape);
492 const js::Shape *methodShapeChange(JSContext *cx, const js::Shape &shape);
493 bool methodShapeChange(JSContext *cx, uint32 slot);
494 void protoShapeChange(JSContext *cx);
495 void shadowingShapeChange(JSContext *cx, const js::Shape &shape);
496 bool globalObjectOwnShapeChange(JSContext *cx);
498 void extensibleShapeChange(JSContext *cx) {
499 /* This will do for now. */
500 generateOwnShape(cx);
504 * A scope has a method barrier when some compiler-created "null closure"
505 * function objects (functions that do not use lexical bindings above their
506 * scope, only free variable names) that have a correct JSSLOT_PARENT value
507 * thanks to the COMPILE_N_GO optimization are stored as newly added direct
508 * property values of the scope's object.
510 * The de-facto standard JS language requires each evaluation of such a
511 * closure to result in a unique (according to === and observable effects)
512 * function object. ES3 tried to allow implementations to "join" such
513 * objects to a single compiler-created object, but this makes an overt
514 * mutation hazard, also an "identity hazard" against interoperation among
515 * implementations that join and do not join.
517 * To stay compatible with the de-facto standard, we store the compiler-
518 * created function object as the method value and set the METHOD_BARRIER
519 * flag.
521 * The method value is part of the method property tree node's identity, so
522 * it effectively brands the scope with a predictable shape corresponding
523 * to the method value, but without the overhead of setting the BRANDED
524 * flag, which requires assigning a new shape peculiar to each branded
525 * scope. Instead the shape is shared via the property tree among all the
526 * scopes referencing the method property tree node.
528 * Then when reading from a scope for which scope->hasMethodBarrier() is
529 * true, we count on the scope's qualified/guarded shape being unique and
530 * add a read barrier that clones the compiler-created function object on
531 * demand, reshaping the scope.
533 * This read barrier is bypassed when evaluating the callee sub-expression
534 * of a call expression (see the JOF_CALLOP opcodes in jsopcode.tbl), since
535 * such ops do not present an identity or mutation hazard. The compiler
536 * performs this optimization only for null closures that do not use their
537 * own name or equivalent built-in references (arguments.callee).
539 * The BRANDED write barrier, JSObject::methodWriteBarrer, must check for
540 * METHOD_BARRIER too, and regenerate this scope's shape if the method's
541 * value is in fact changing.
543 bool hasMethodBarrier() { return !!(flags & METHOD_BARRIER); }
544 void setMethodBarrier() { flags |= METHOD_BARRIER; }
547 * Test whether this object may be branded due to method calls, which means
548 * any assignment to a function-valued property must regenerate shape; else
549 * test whether this object has method properties, which require a method
550 * write barrier.
552 bool brandedOrHasMethodBarrier() { return !!(flags & (BRANDED | METHOD_BARRIER)); }
555 * Read barrier to clone a joined function object stored as a method.
556 * Defined in jsobjinlines.h, but not declared inline per standard style in
557 * order to avoid gcc warnings.
559 bool methodReadBarrier(JSContext *cx, const js::Shape &shape, js::Value *vp);
562 * Write barrier to check for a change of method value. Defined inline in
563 * jsobjinlines.h after methodReadBarrier. The slot flavor is required by
564 * JSOP_*GVAR, which deals in slots not shapes, while not deoptimizing to
565 * map slot to shape unless JSObject::flags show that this is necessary.
566 * The methodShapeChange overload (above) parallels this.
568 const js::Shape *methodWriteBarrier(JSContext *cx, const js::Shape &shape, const js::Value &v);
569 bool methodWriteBarrier(JSContext *cx, uint32 slot, const js::Value &v);
571 bool isIndexed() const { return !!(flags & INDEXED); }
572 void setIndexed() { flags |= INDEXED; }
575 * Return true if this object is a native one that has been converted from
576 * shared-immutable prototype-rooted shape storage to dictionary-shapes in
577 * a doubly-linked list.
579 inline bool inDictionaryMode() const;
581 inline uint32 propertyCount() const;
583 inline bool hasPropertyTable() const;
585 /* gc::FinalizeKind */ unsigned finalizeKind() const;
587 uint32 numSlots() const { return capacity; }
589 size_t slotsAndStructSize(uint32 nslots) const;
590 size_t slotsAndStructSize() const { return slotsAndStructSize(numSlots()); }
592 inline js::Value* fixedSlots() const;
593 inline size_t numFixedSlots() const;
595 static inline size_t getFixedSlotOffset(size_t slot);
597 public:
598 /* Minimum size for dynamically allocated slots. */
599 static const uint32 SLOT_CAPACITY_MIN = 8;
601 bool allocSlots(JSContext *cx, size_t nslots);
602 bool growSlots(JSContext *cx, size_t nslots);
603 void shrinkSlots(JSContext *cx, size_t nslots);
605 bool ensureSlots(JSContext *cx, size_t nslots) {
606 if (numSlots() < nslots)
607 return growSlots(cx, nslots);
608 return true;
612 * Ensure that the object has at least JSCLASS_RESERVED_SLOTS(clasp) +
613 * nreserved slots.
615 * This method may be called only for native objects freshly created using
616 * NewObject or one of its variant where the new object will both (a) never
617 * escape to script and (b) never be extended with ad-hoc properties that
618 * would try to allocate higher slots without the fresh object first having
619 * its map set to a shape path that maps those slots.
621 * Block objects satisfy (a) and (b), as there is no evil eval-based way to
622 * add ad-hoc properties to a Block instance. Call objects satisfy (a) and
623 * (b) as well, because the compiler-created Shape path that covers args,
624 * vars, and upvars, stored in their callee function in u.i.names, becomes
625 * their initial map.
627 bool ensureInstanceReservedSlots(JSContext *cx, size_t nreserved);
630 * Get a direct pointer to the object's slots.
631 * This can be reallocated if the object is modified, watch out!
633 js::Value *getSlots() const {
634 return slots;
638 * NB: ensureClassReservedSlotsForEmptyObject asserts that nativeEmpty()
639 * Use ensureClassReservedSlots for any object, either empty or already
640 * extended with properties.
642 bool ensureClassReservedSlotsForEmptyObject(JSContext *cx);
644 inline bool ensureClassReservedSlots(JSContext *cx);
646 uint32 slotSpan() const { return map->slotSpan; }
648 bool containsSlot(uint32 slot) const { return slot < slotSpan(); }
650 js::Value& getSlotRef(uintN slot) {
651 JS_ASSERT(slot < capacity);
652 return slots[slot];
655 js::Value &nativeGetSlotRef(uintN slot) {
656 JS_ASSERT(isNative());
657 JS_ASSERT(containsSlot(slot));
658 return getSlotRef(slot);
661 const js::Value &getSlot(uintN slot) const {
662 JS_ASSERT(slot < capacity);
663 return slots[slot];
666 const js::Value &nativeGetSlot(uintN slot) const {
667 JS_ASSERT(isNative());
668 JS_ASSERT(containsSlot(slot));
669 return getSlot(slot);
672 void setSlot(uintN slot, const js::Value &value) {
673 JS_ASSERT(slot < capacity);
674 slots[slot] = value;
677 void nativeSetSlot(uintN slot, const js::Value &value) {
678 JS_ASSERT(isNative());
679 JS_ASSERT(containsSlot(slot));
680 return setSlot(slot, value);
683 inline js::Value getReservedSlot(uintN index) const;
685 /* Defined in jsscopeinlines.h to avoid including implementation dependencies here. */
686 inline void updateShape(JSContext *cx);
687 inline void updateFlags(const js::Shape *shape, bool isDefinitelyAtom = false);
689 /* Extend this object to have shape as its last-added property. */
690 inline void extend(JSContext *cx, const js::Shape *shape, bool isDefinitelyAtom = false);
692 JSObject *getProto() const { return proto; }
693 void clearProto() { proto = NULL; }
695 void setProto(JSObject *newProto) {
696 #ifdef DEBUG
697 for (JSObject *obj = newProto; obj; obj = obj->getProto())
698 JS_ASSERT(obj != this);
699 #endif
700 setDelegateNullSafe(newProto);
701 proto = newProto;
704 JSObject *getParent() const {
705 return parent;
708 void clearParent() {
709 parent = NULL;
712 void setParent(JSObject *newParent) {
713 #ifdef DEBUG
714 for (JSObject *obj = newParent; obj; obj = obj->getParent())
715 JS_ASSERT(obj != this);
716 #endif
717 setDelegateNullSafe(newParent);
718 parent = newParent;
721 JS_FRIEND_API(JSObject *) getGlobal() const;
723 bool isGlobal() const {
724 return !!(getClass()->flags & JSCLASS_IS_GLOBAL);
727 void *getPrivate() const {
728 JS_ASSERT(getClass()->flags & JSCLASS_HAS_PRIVATE);
729 return privateData;
732 void setPrivate(void *data) {
733 JS_ASSERT(getClass()->flags & JSCLASS_HAS_PRIVATE);
734 privateData = data;
739 * ES5 meta-object properties and operations.
742 private:
743 enum ImmutabilityType { SEAL, FREEZE };
746 * The guts of Object.seal (ES5 15.2.3.8) and Object.freeze (ES5 15.2.3.9): mark the
747 * object as non-extensible, and adjust each property's attributes appropriately: each
748 * property becomes non-configurable, and if |freeze|, data properties become
749 * read-only as well.
751 bool sealOrFreeze(JSContext *cx, ImmutabilityType it);
753 public:
754 bool isExtensible() const { return !(flags & NOT_EXTENSIBLE); }
755 bool preventExtensions(JSContext *cx, js::AutoIdVector *props);
757 /* ES5 15.2.3.8: non-extensible, all props non-configurable */
758 inline bool seal(JSContext *cx) { return sealOrFreeze(cx, SEAL); }
759 /* ES5 15.2.3.9: non-extensible, all properties non-configurable, all data props read-only */
760 bool freeze(JSContext *cx) { return sealOrFreeze(cx, FREEZE); }
763 * Primitive-specific getters and setters.
766 private:
767 static const uint32 JSSLOT_PRIMITIVE_THIS = 0;
769 public:
770 inline const js::Value &getPrimitiveThis() const;
771 inline void setPrimitiveThis(const js::Value &pthis);
774 * Array-specific getters and setters (for both dense and slow arrays).
777 inline uint32 getArrayLength() const;
778 inline void setArrayLength(uint32 length);
780 inline uint32 getDenseArrayCapacity();
781 inline js::Value* getDenseArrayElements();
782 inline const js::Value &getDenseArrayElement(uintN idx);
783 inline js::Value* addressOfDenseArrayElement(uintN idx);
784 inline void setDenseArrayElement(uintN idx, const js::Value &val);
785 inline void shrinkDenseArrayElements(JSContext *cx, uintN cap);
788 * ensureDenseArrayElements ensures that the dense array can hold at least
789 * index + extra elements. It returns ED_OK on success, ED_FAILED on
790 * failure to grow the array, ED_SPARSE when the array is too sparse to
791 * grow (this includes the case of index + extra overflow). In the last
792 * two cases the array is kept intact.
794 enum EnsureDenseResult { ED_OK, ED_FAILED, ED_SPARSE };
795 inline EnsureDenseResult ensureDenseArrayElements(JSContext *cx, uintN index, uintN extra);
798 * Check if after growing the dense array will be too sparse.
799 * newElementsHint is an estimated number of elements to be added.
801 bool willBeSparseDenseArray(uintN requiredCapacity, uintN newElementsHint);
803 JSBool makeDenseArraySlow(JSContext *cx);
806 * Arguments-specific getters and setters.
809 private:
811 * We represent arguments objects using js_ArgumentsClass and
812 * js::StrictArgumentsClass. The two are structured similarly, and methods
813 * valid on arguments objects of one class are also generally valid on
814 * arguments objects of the other.
816 * Arguments objects of either class store arguments length in a slot:
818 * JSSLOT_ARGS_LENGTH - the number of actual arguments and a flag
819 * indicating whether arguments.length was
820 * overwritten. This slot is not used to represent
821 * arguments.length after that property has been
822 * assigned, even if the new value is integral: it's
823 * always the original length.
825 * Both arguments classes use a slot for storing arguments data:
827 * JSSLOT_ARGS_DATA - pointer to an ArgumentsData structure
829 * ArgumentsData for normal arguments stores the value of arguments.callee,
830 * as long as that property has not been overwritten. If arguments.callee
831 * is overwritten, the corresponding value in ArgumentsData is set to
832 * MagicValue(JS_ARGS_HOLE). Strict arguments do not store this value
833 * because arguments.callee is a poison pill for strict mode arguments.
835 * The ArgumentsData structure also stores argument values. For normal
836 * arguments this occurs after the corresponding function has returned, and
837 * for strict arguments this occurs when the arguments object is created,
838 * or sometimes shortly after (but not observably so). arguments[i] is
839 * stored in ArgumentsData.slots[i], accessible via getArgsElement() and
840 * setArgsElement(). Deletion of arguments[i] overwrites that slot with
841 * MagicValue(JS_ARGS_HOLE); subsequent redefinition of arguments[i] will
842 * use a normal property to store the value, ignoring the slot.
844 * Non-strict arguments have a private:
846 * private - the function's stack frame until the function
847 * returns, when it is replaced with null; also,
848 * JS_ARGUMENTS_OBJECT_ON_TRACE while on trace, if
849 * arguments was created on trace
851 * Technically strict arguments have a private, but it's always null.
852 * Conceptually it would be better to remove this oddity, but preserving it
853 * allows us to work with arguments objects of either kind more abstractly,
854 * so we keep it for now.
856 static const uint32 JSSLOT_ARGS_DATA = 1;
858 public:
859 /* Number of extra fixed arguments object slots besides JSSLOT_PRIVATE. */
860 static const uint32 JSSLOT_ARGS_LENGTH = 0;
861 static const uint32 ARGS_CLASS_RESERVED_SLOTS = 2;
862 static const uint32 ARGS_FIRST_FREE_SLOT = ARGS_CLASS_RESERVED_SLOTS + 1;
864 /* Lower-order bit stolen from the length slot. */
865 static const uint32 ARGS_LENGTH_OVERRIDDEN_BIT = 0x1;
866 static const uint32 ARGS_PACKED_BITS_COUNT = 1;
869 * Set the initial length of the arguments, and mark it as not overridden.
871 inline void setArgsLength(uint32 argc);
874 * Return the initial length of the arguments. This may differ from the
875 * current value of arguments.length!
877 inline uint32 getArgsInitialLength() const;
879 inline void setArgsLengthOverridden();
880 inline bool isArgsLengthOverridden() const;
882 inline js::ArgumentsData *getArgsData() const;
883 inline void setArgsData(js::ArgumentsData *data);
885 inline const js::Value &getArgsCallee() const;
886 inline void setArgsCallee(const js::Value &callee);
888 inline const js::Value &getArgsElement(uint32 i) const;
889 inline js::Value *getArgsElements() const;
890 inline js::Value *addressOfArgsElement(uint32 i);
891 inline void setArgsElement(uint32 i, const js::Value &v);
893 private:
895 * Reserved slot structure for Call objects:
897 * private - the stack frame corresponding to the Call object
898 * until js_PutCallObject or its on-trace analog
899 * is called, null thereafter
900 * JSSLOT_CALL_CALLEE - callee function for the stack frame, or null if
901 * the stack frame is for strict mode eval code
902 * JSSLOT_CALL_ARGUMENTS - arguments object for non-strict mode eval stack
903 * frames (not valid for strict mode eval frames)
905 static const uint32 JSSLOT_CALL_CALLEE = 0;
906 static const uint32 JSSLOT_CALL_ARGUMENTS = 1;
908 public:
909 /* Number of reserved slots. */
910 static const uint32 CALL_RESERVED_SLOTS = 2;
912 /* True if this is for a strict mode eval frame or for a function call. */
913 inline bool callIsForEval() const;
915 /* The stack frame for this Call object, if the frame is still active. */
916 inline JSStackFrame *maybeCallObjStackFrame() const;
919 * The callee function if this Call object was created for a function
920 * invocation, or null if it was created for a strict mode eval frame.
922 inline JSObject *getCallObjCallee() const;
923 inline JSFunction *getCallObjCalleeFunction() const;
924 inline void setCallObjCallee(JSObject *callee);
926 inline const js::Value &getCallObjArguments() const;
927 inline void setCallObjArguments(const js::Value &v);
929 /* Returns the formal argument at the given index. */
930 inline const js::Value &callObjArg(uintN i) const;
931 inline js::Value &callObjArg(uintN i);
933 /* Returns the variable at the given index. */
934 inline const js::Value &callObjVar(uintN i) const;
935 inline js::Value &callObjVar(uintN i);
938 * Date-specific getters and setters.
941 static const uint32 JSSLOT_DATE_UTC_TIME = 0;
944 * Cached slots holding local properties of the date.
945 * These are undefined until the first actual lookup occurs
946 * and are reset to undefined whenever the date's time is modified.
948 static const uint32 JSSLOT_DATE_COMPONENTS_START = 1;
950 static const uint32 JSSLOT_DATE_LOCAL_TIME = 1;
951 static const uint32 JSSLOT_DATE_LOCAL_YEAR = 2;
952 static const uint32 JSSLOT_DATE_LOCAL_MONTH = 3;
953 static const uint32 JSSLOT_DATE_LOCAL_DATE = 4;
954 static const uint32 JSSLOT_DATE_LOCAL_DAY = 5;
955 static const uint32 JSSLOT_DATE_LOCAL_HOURS = 6;
956 static const uint32 JSSLOT_DATE_LOCAL_MINUTES = 7;
957 static const uint32 JSSLOT_DATE_LOCAL_SECONDS = 8;
959 static const uint32 DATE_CLASS_RESERVED_SLOTS = 9;
961 inline const js::Value &getDateUTCTime() const;
962 inline void setDateUTCTime(const js::Value &pthis);
965 * Function-specific getters and setters.
968 private:
969 friend struct JSFunction;
970 friend class js::mjit::Compiler;
973 * Flat closures with one or more upvars snapshot the upvars' values into a
974 * vector of js::Values referenced from this slot.
976 static const uint32 JSSLOT_FLAT_CLOSURE_UPVARS = 0;
979 * Null closures set or initialized as methods have these slots. See the
980 * "method barrier" comments and methods.
983 static const uint32 JSSLOT_FUN_METHOD_ATOM = 0;
984 static const uint32 JSSLOT_FUN_METHOD_OBJ = 1;
986 static const uint32 JSSLOT_BOUND_FUNCTION_THIS = 0;
987 static const uint32 JSSLOT_BOUND_FUNCTION_ARGS_COUNT = 1;
989 public:
990 static const uint32 FUN_CLASS_RESERVED_SLOTS = 2;
992 inline JSFunction *getFunctionPrivate() const;
994 inline js::Value *getFlatClosureUpvars() const;
995 inline js::Value getFlatClosureUpvar(uint32 i) const;
996 inline js::Value &getFlatClosureUpvar(uint32 i);
997 inline void setFlatClosureUpvars(js::Value *upvars);
999 inline bool hasMethodObj(const JSObject& obj) const;
1000 inline void setMethodObj(JSObject& obj);
1002 inline bool initBoundFunction(JSContext *cx, const js::Value &thisArg,
1003 const js::Value *args, uintN argslen);
1005 inline JSObject *getBoundFunctionTarget() const;
1006 inline const js::Value &getBoundFunctionThis() const;
1007 inline const js::Value *getBoundFunctionArguments(uintN &argslen) const;
1010 * RegExp-specific getters and setters.
1013 private:
1014 static const uint32 JSSLOT_REGEXP_LAST_INDEX = 0;
1016 public:
1017 static const uint32 REGEXP_CLASS_RESERVED_SLOTS = 1;
1019 inline const js::Value &getRegExpLastIndex() const;
1020 inline void setRegExpLastIndex(const js::Value &v);
1021 inline void setRegExpLastIndex(jsdouble d);
1022 inline void zeroRegExpLastIndex();
1025 * Iterator-specific getters and setters.
1028 inline js::NativeIterator *getNativeIterator() const;
1029 inline void setNativeIterator(js::NativeIterator *);
1032 * XML-related getters and setters.
1036 * Slots for XML-related classes are as follows:
1037 * - js_NamespaceClass.base reserves the *_NAME_* and *_NAMESPACE_* slots.
1038 * - js_QNameClass.base, js_AttributeNameClass, js_AnyNameClass reserve
1039 * the *_NAME_* and *_QNAME_* slots.
1040 * - Others (js_XMLClass, js_XMLFilterClass) don't reserve any slots.
1042 private:
1043 static const uint32 JSSLOT_NAME_PREFIX = 0; // shared
1044 static const uint32 JSSLOT_NAME_URI = 1; // shared
1046 static const uint32 JSSLOT_NAMESPACE_DECLARED = 2;
1048 static const uint32 JSSLOT_QNAME_LOCAL_NAME = 2;
1050 public:
1051 static const uint32 NAMESPACE_CLASS_RESERVED_SLOTS = 3;
1052 static const uint32 QNAME_CLASS_RESERVED_SLOTS = 3;
1054 inline JSLinearString *getNamePrefix() const;
1055 inline jsval getNamePrefixVal() const;
1056 inline void setNamePrefix(JSLinearString *prefix);
1057 inline void clearNamePrefix();
1059 inline JSLinearString *getNameURI() const;
1060 inline jsval getNameURIVal() const;
1061 inline void setNameURI(JSLinearString *uri);
1063 inline jsval getNamespaceDeclared() const;
1064 inline void setNamespaceDeclared(jsval decl);
1066 inline JSLinearString *getQNameLocalName() const;
1067 inline jsval getQNameLocalNameVal() const;
1068 inline void setQNameLocalName(JSLinearString *name);
1071 * Proxy-specific getters and setters.
1074 inline js::JSProxyHandler *getProxyHandler() const;
1075 inline const js::Value &getProxyPrivate() const;
1076 inline void setProxyPrivate(const js::Value &priv);
1077 inline const js::Value &getProxyExtra() const;
1078 inline void setProxyExtra(const js::Value &extra);
1081 * With object-specific getters and setters.
1083 inline JSObject *getWithThis() const;
1084 inline void setWithThis(JSObject *thisp);
1087 * Back to generic stuff.
1089 inline bool isCallable();
1091 /* The map field is not initialized here and should be set separately. */
1092 void init(JSContext *cx, js::Class *aclasp, JSObject *proto, JSObject *parent,
1093 void *priv, bool useHoles);
1095 inline void finish(JSContext *cx);
1096 JS_ALWAYS_INLINE void finalize(JSContext *cx);
1099 * Like init, but also initializes map. The catch: proto must be the result
1100 * of a call to js_InitClass(...clasp, ...).
1102 inline bool initSharingEmptyShape(JSContext *cx,
1103 js::Class *clasp,
1104 JSObject *proto,
1105 JSObject *parent,
1106 void *priv,
1107 /* gc::FinalizeKind */ unsigned kind);
1109 inline bool hasSlotsArray() const;
1111 /* This method can only be called when hasSlotsArray() returns true. */
1112 inline void freeSlotsArray(JSContext *cx);
1114 /* Free the slots array and copy slots that fit into the fixed array. */
1115 inline void revertToFixedSlots(JSContext *cx);
1117 inline bool hasProperty(JSContext *cx, jsid id, bool *foundp, uintN flags = 0);
1120 * Allocate and free an object slot. Note that freeSlot is infallible: it
1121 * returns true iff this is a dictionary-mode object and the freed slot was
1122 * added to the freelist.
1124 * FIXME: bug 593129 -- slot allocation should be done by object methods
1125 * after calling object-parameter-free shape methods, avoiding coupling
1126 * logic across the object vs. shape module wall.
1128 bool allocSlot(JSContext *cx, uint32 *slotp);
1129 bool freeSlot(JSContext *cx, uint32 slot);
1131 public:
1132 bool reportReadOnly(JSContext* cx, jsid id, uintN report = JSREPORT_ERROR);
1133 bool reportNotConfigurable(JSContext* cx, jsid id, uintN report = JSREPORT_ERROR);
1134 bool reportNotExtensible(JSContext *cx, uintN report = JSREPORT_ERROR);
1136 private:
1137 js::Shape *getChildProperty(JSContext *cx, js::Shape *parent, js::Shape &child);
1140 * Internal helper that adds a shape not yet mapped by this object.
1142 * Notes:
1143 * 1. getter and setter must be normalized based on flags (see jsscope.cpp).
1144 * 2. !isExtensible() checking must be done by callers.
1146 const js::Shape *addPropertyInternal(JSContext *cx, jsid id,
1147 js::PropertyOp getter, js::PropertyOp setter,
1148 uint32 slot, uintN attrs,
1149 uintN flags, intN shortid,
1150 js::Shape **spp);
1152 bool toDictionaryMode(JSContext *cx);
1154 public:
1155 /* Add a property whose id is not yet in this scope. */
1156 const js::Shape *addProperty(JSContext *cx, jsid id,
1157 js::PropertyOp getter, js::PropertyOp setter,
1158 uint32 slot, uintN attrs,
1159 uintN flags, intN shortid);
1161 /* Add a data property whose id is not yet in this scope. */
1162 const js::Shape *addDataProperty(JSContext *cx, jsid id, uint32 slot, uintN attrs) {
1163 JS_ASSERT(!(attrs & (JSPROP_GETTER | JSPROP_SETTER)));
1164 return addProperty(cx, id, NULL, NULL, slot, attrs, 0, 0);
1167 /* Add or overwrite a property for id in this scope. */
1168 const js::Shape *putProperty(JSContext *cx, jsid id,
1169 js::PropertyOp getter, js::PropertyOp setter,
1170 uint32 slot, uintN attrs,
1171 uintN flags, intN shortid);
1173 /* Change the given property into a sibling with the same id in this scope. */
1174 const js::Shape *changeProperty(JSContext *cx, const js::Shape *shape, uintN attrs, uintN mask,
1175 js::PropertyOp getter, js::PropertyOp setter);
1177 /* Remove the property named by id from this object. */
1178 bool removeProperty(JSContext *cx, jsid id);
1180 /* Clear the scope, making it empty. */
1181 void clear(JSContext *cx);
1183 JSBool lookupProperty(JSContext *cx, jsid id, JSObject **objp, JSProperty **propp) {
1184 js::LookupPropOp op = getOps()->lookupProperty;
1185 return (op ? op : js_LookupProperty)(cx, this, id, objp, propp);
1188 JSBool defineProperty(JSContext *cx, jsid id, const js::Value &value,
1189 js::PropertyOp getter = js::PropertyStub,
1190 js::PropertyOp setter = js::PropertyStub,
1191 uintN attrs = JSPROP_ENUMERATE) {
1192 js::DefinePropOp op = getOps()->defineProperty;
1193 return (op ? op : js_DefineProperty)(cx, this, id, &value, getter, setter, attrs);
1196 JSBool getProperty(JSContext *cx, JSObject *receiver, jsid id, js::Value *vp) {
1197 js::PropertyIdOp op = getOps()->getProperty;
1198 return (op ? op : (js::PropertyIdOp)js_GetProperty)(cx, this, receiver, id, vp);
1201 JSBool getProperty(JSContext *cx, jsid id, js::Value *vp) {
1202 return getProperty(cx, this, id, vp);
1205 JSBool setProperty(JSContext *cx, jsid id, js::Value *vp, JSBool strict) {
1206 js::StrictPropertyIdOp op = getOps()->setProperty;
1207 return (op ? op : js_SetProperty)(cx, this, id, vp, strict);
1210 JSBool getAttributes(JSContext *cx, jsid id, uintN *attrsp) {
1211 js::AttributesOp op = getOps()->getAttributes;
1212 return (op ? op : js_GetAttributes)(cx, this, id, attrsp);
1215 JSBool setAttributes(JSContext *cx, jsid id, uintN *attrsp) {
1216 js::AttributesOp op = getOps()->setAttributes;
1217 return (op ? op : js_SetAttributes)(cx, this, id, attrsp);
1220 JSBool deleteProperty(JSContext *cx, jsid id, js::Value *rval, JSBool strict) {
1221 js::DeleteIdOp op = getOps()->deleteProperty;
1222 return (op ? op : js_DeleteProperty)(cx, this, id, rval, strict);
1225 JSBool enumerate(JSContext *cx, JSIterateOp iterop, js::Value *statep, jsid *idp) {
1226 js::NewEnumerateOp op = getOps()->enumerate;
1227 return (op ? op : js_Enumerate)(cx, this, iterop, statep, idp);
1230 JSType typeOf(JSContext *cx) {
1231 js::TypeOfOp op = getOps()->typeOf;
1232 return (op ? op : js_TypeOf)(cx, this);
1235 /* These four are time-optimized to avoid stub calls. */
1236 JSObject *thisObject(JSContext *cx) {
1237 JSObjectOp op = getOps()->thisObject;
1238 return op ? op(cx, this) : this;
1241 static bool thisObject(JSContext *cx, const js::Value &v, js::Value *vp);
1243 inline JSCompartment *getCompartment() const;
1245 inline JSObject *getThrowTypeError() const;
1247 JS_FRIEND_API(JSObject *) clone(JSContext *cx, JSObject *proto, JSObject *parent);
1248 JS_FRIEND_API(bool) copyPropertiesFrom(JSContext *cx, JSObject *obj);
1249 bool swap(JSContext *cx, JSObject *other);
1251 const js::Shape *defineBlockVariable(JSContext *cx, jsid id, intN index);
1253 inline bool canHaveMethodBarrier() const;
1255 inline bool isArguments() const;
1256 inline bool isNormalArguments() const;
1257 inline bool isStrictArguments() const;
1258 inline bool isArray() const;
1259 inline bool isDenseArray() const;
1260 inline bool isSlowArray() const;
1261 inline bool isNumber() const;
1262 inline bool isBoolean() const;
1263 inline bool isString() const;
1264 inline bool isPrimitive() const;
1265 inline bool isDate() const;
1266 inline bool isFunction() const;
1267 inline bool isObject() const;
1268 inline bool isWith() const;
1269 inline bool isBlock() const;
1270 inline bool isStaticBlock() const;
1271 inline bool isClonedBlock() const;
1272 inline bool isCall() const;
1273 inline bool isRegExp() const;
1274 inline bool isXML() const;
1275 inline bool isXMLId() const;
1276 inline bool isNamespace() const;
1277 inline bool isQName() const;
1279 inline bool isProxy() const;
1280 inline bool isObjectProxy() const;
1281 inline bool isFunctionProxy() const;
1283 JS_FRIEND_API(bool) isWrapper() const;
1284 JS_FRIEND_API(JSObject *) unwrap(uintN *flagsp = NULL);
1286 inline void initArrayClass();
1289 /* Check alignment for any fixed slots allocated after the object. */
1290 JS_STATIC_ASSERT(sizeof(JSObject) % sizeof(js::Value) == 0);
1292 inline js::Value*
1293 JSObject::fixedSlots() const {
1294 return (js::Value*) (jsuword(this) + sizeof(JSObject));
1297 inline bool
1298 JSObject::hasSlotsArray() const { return this->slots != fixedSlots(); }
1300 /* static */ inline size_t
1301 JSObject::getFixedSlotOffset(size_t slot) {
1302 return sizeof(JSObject) + (slot * sizeof(js::Value));
1305 struct JSObject_Slots2 : JSObject { js::Value fslots[2]; };
1306 struct JSObject_Slots4 : JSObject { js::Value fslots[4]; };
1307 struct JSObject_Slots8 : JSObject { js::Value fslots[8]; };
1308 struct JSObject_Slots12 : JSObject { js::Value fslots[12]; };
1309 struct JSObject_Slots16 : JSObject { js::Value fslots[16]; };
1311 #define JSSLOT_FREE(clasp) JSCLASS_RESERVED_SLOTS(clasp)
1313 #ifdef JS_THREADSAFE
1316 * The GC runs only when all threads except the one on which the GC is active
1317 * are suspended at GC-safe points, so calling obj->getSlot() from the GC's
1318 * thread is safe when rt->gcRunning is set. See jsgc.cpp for details.
1320 #define THREAD_IS_RUNNING_GC(rt, thread) \
1321 ((rt)->gcRunning && (rt)->gcThread == (thread))
1323 #define CX_THREAD_IS_RUNNING_GC(cx) \
1324 THREAD_IS_RUNNING_GC((cx)->runtime, (cx)->thread)
1326 #endif /* JS_THREADSAFE */
1328 inline void
1329 OBJ_TO_INNER_OBJECT(JSContext *cx, JSObject *&obj)
1331 if (JSObjectOp op = obj->getClass()->ext.innerObject)
1332 obj = op(cx, obj);
1335 inline void
1336 OBJ_TO_OUTER_OBJECT(JSContext *cx, JSObject *&obj)
1338 if (JSObjectOp op = obj->getClass()->ext.outerObject)
1339 obj = op(cx, obj);
1342 class JSValueArray {
1343 public:
1344 jsval *array;
1345 size_t length;
1347 JSValueArray(jsval *v, size_t c) : array(v), length(c) {}
1350 class ValueArray {
1351 public:
1352 js::Value *array;
1353 size_t length;
1355 ValueArray(js::Value *v, size_t c) : array(v), length(c) {}
1358 extern js::Class js_ObjectClass;
1359 extern js::Class js_WithClass;
1360 extern js::Class js_BlockClass;
1362 inline bool JSObject::isObject() const { return getClass() == &js_ObjectClass; }
1363 inline bool JSObject::isWith() const { return getClass() == &js_WithClass; }
1364 inline bool JSObject::isBlock() const { return getClass() == &js_BlockClass; }
1367 * Block scope object macros. The slots reserved by js_BlockClass are:
1369 * private JSStackFrame * active frame pointer or null
1370 * JSSLOT_BLOCK_DEPTH int depth of block slots in frame
1372 * After JSSLOT_BLOCK_DEPTH come one or more slots for the block locals.
1374 * A With object is like a Block object, in that both have one reserved slot
1375 * telling the stack depth of the relevant slots (the slot whose value is the
1376 * object named in the with statement, the slots containing the block's local
1377 * variables); and both have a private slot referring to the JSStackFrame in
1378 * whose activation they were created (or null if the with or block object
1379 * outlives the frame).
1381 static const uint32 JSSLOT_BLOCK_DEPTH = 0;
1382 static const uint32 JSSLOT_BLOCK_FIRST_FREE_SLOT = JSSLOT_BLOCK_DEPTH + 1;
1384 inline bool
1385 JSObject::isStaticBlock() const
1387 return isBlock() && !getProto();
1390 inline bool
1391 JSObject::isClonedBlock() const
1393 return isBlock() && !!getProto();
1396 static const uint32 JSSLOT_WITH_THIS = 1;
1398 #define OBJ_BLOCK_COUNT(cx,obj) \
1399 (obj)->propertyCount()
1400 #define OBJ_BLOCK_DEPTH(cx,obj) \
1401 (obj)->getSlot(JSSLOT_BLOCK_DEPTH).toInt32()
1402 #define OBJ_SET_BLOCK_DEPTH(cx,obj,depth) \
1403 (obj)->setSlot(JSSLOT_BLOCK_DEPTH, Value(Int32Value(depth)))
1406 * To make sure this slot is well-defined, always call js_NewWithObject to
1407 * create a With object, don't call js_NewObject directly. When creating a
1408 * With object that does not correspond to a stack slot, pass -1 for depth.
1410 * When popping the stack across this object's "with" statement, client code
1411 * must call withobj->setPrivate(NULL).
1413 extern JS_REQUIRES_STACK JSObject *
1414 js_NewWithObject(JSContext *cx, JSObject *proto, JSObject *parent, jsint depth);
1416 inline JSObject *
1417 js_UnwrapWithObject(JSContext *cx, JSObject *withobj)
1419 JS_ASSERT(withobj->getClass() == &js_WithClass);
1420 return withobj->getProto();
1424 * Create a new block scope object not linked to any proto or parent object.
1425 * Blocks are created by the compiler to reify let blocks and comprehensions.
1426 * Only when dynamic scope is captured do they need to be cloned and spliced
1427 * into an active scope chain.
1429 extern JSObject *
1430 js_NewBlockObject(JSContext *cx);
1432 extern JSObject *
1433 js_CloneBlockObject(JSContext *cx, JSObject *proto, JSStackFrame *fp);
1435 extern JS_REQUIRES_STACK JSBool
1436 js_PutBlockObject(JSContext *cx, JSBool normalUnwind);
1438 JSBool
1439 js_XDRBlockObject(JSXDRState *xdr, JSObject **objp);
1441 struct JSSharpObjectMap {
1442 jsrefcount depth;
1443 jsatomid sharpgen;
1444 JSHashTable *table;
1447 #define SHARP_BIT ((jsatomid) 1)
1448 #define BUSY_BIT ((jsatomid) 2)
1449 #define SHARP_ID_SHIFT 2
1450 #define IS_SHARP(he) (uintptr_t((he)->value) & SHARP_BIT)
1451 #define MAKE_SHARP(he) ((he)->value = (void *) (uintptr_t((he)->value)|SHARP_BIT))
1452 #define IS_BUSY(he) (uintptr_t((he)->value) & BUSY_BIT)
1453 #define MAKE_BUSY(he) ((he)->value = (void *) (uintptr_t((he)->value)|BUSY_BIT))
1454 #define CLEAR_BUSY(he) ((he)->value = (void *) (uintptr_t((he)->value)&~BUSY_BIT))
1456 extern JSHashEntry *
1457 js_EnterSharpObject(JSContext *cx, JSObject *obj, JSIdArray **idap,
1458 jschar **sp);
1460 extern void
1461 js_LeaveSharpObject(JSContext *cx, JSIdArray **idap);
1464 * Mark objects stored in map if GC happens between js_EnterSharpObject
1465 * and js_LeaveSharpObject. GC calls this when map->depth > 0.
1467 extern void
1468 js_TraceSharpMap(JSTracer *trc, JSSharpObjectMap *map);
1470 extern JSBool
1471 js_HasOwnPropertyHelper(JSContext *cx, js::LookupPropOp lookup, uintN argc,
1472 js::Value *vp);
1474 extern JSBool
1475 js_HasOwnProperty(JSContext *cx, js::LookupPropOp lookup, JSObject *obj, jsid id,
1476 JSObject **objp, JSProperty **propp);
1478 extern JSBool
1479 js_NewPropertyDescriptorObject(JSContext *cx, jsid id, uintN attrs,
1480 const js::Value &getter, const js::Value &setter,
1481 const js::Value &value, js::Value *vp);
1483 extern JSBool
1484 js_PropertyIsEnumerable(JSContext *cx, JSObject *obj, jsid id, js::Value *vp);
1486 #ifdef OLD_GETTER_SETTER_METHODS
1487 JS_FRIEND_API(JSBool) js_obj_defineGetter(JSContext *cx, uintN argc, js::Value *vp);
1488 JS_FRIEND_API(JSBool) js_obj_defineSetter(JSContext *cx, uintN argc, js::Value *vp);
1489 #endif
1491 extern JSObject *
1492 js_InitObjectClass(JSContext *cx, JSObject *obj);
1494 extern JSObject *
1495 js_InitClass(JSContext *cx, JSObject *obj, JSObject *parent_proto,
1496 js::Class *clasp, js::Native constructor, uintN nargs,
1497 JSPropertySpec *ps, JSFunctionSpec *fs,
1498 JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
1501 * Select Object.prototype method names shared between jsapi.cpp and jsobj.cpp.
1503 extern const char js_watch_str[];
1504 extern const char js_unwatch_str[];
1505 extern const char js_hasOwnProperty_str[];
1506 extern const char js_isPrototypeOf_str[];
1507 extern const char js_propertyIsEnumerable_str[];
1509 #ifdef OLD_GETTER_SETTER_METHODS
1510 extern const char js_defineGetter_str[];
1511 extern const char js_defineSetter_str[];
1512 extern const char js_lookupGetter_str[];
1513 extern const char js_lookupSetter_str[];
1514 #endif
1516 extern JSBool
1517 js_PopulateObject(JSContext *cx, JSObject *newborn, JSObject *props);
1520 * Fast access to immutable standard objects (constructors and prototypes).
1522 extern JSBool
1523 js_GetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key,
1524 JSObject **objp);
1526 extern JSBool
1527 js_SetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key,
1528 JSObject *cobj, JSObject *prototype);
1531 * If protoKey is not JSProto_Null, then clasp is ignored. If protoKey is
1532 * JSProto_Null, clasp must non-null.
1534 extern JSBool
1535 js_FindClassObject(JSContext *cx, JSObject *start, JSProtoKey key,
1536 js::Value *vp, js::Class *clasp = NULL);
1538 extern JSObject *
1539 js_ConstructObject(JSContext *cx, js::Class *clasp, JSObject *proto,
1540 JSObject *parent, uintN argc, js::Value *argv);
1542 // Specialized call for constructing |this| with a known function callee,
1543 // and a known prototype.
1544 extern JSObject *
1545 js_CreateThisForFunctionWithProto(JSContext *cx, JSObject *callee, JSObject *proto);
1547 // Specialized call for constructing |this| with a known function callee.
1548 extern JSObject *
1549 js_CreateThisForFunction(JSContext *cx, JSObject *callee);
1551 // Generic call for constructing |this|.
1552 extern JSObject *
1553 js_CreateThis(JSContext *cx, JSObject *callee);
1555 extern jsid
1556 js_CheckForStringIndex(jsid id);
1559 * js_PurgeScopeChain does nothing if obj is not itself a prototype or parent
1560 * scope, else it reshapes the scope and prototype chains it links. It calls
1561 * js_PurgeScopeChainHelper, which asserts that obj is flagged as a delegate
1562 * (i.e., obj has ever been on a prototype or parent chain).
1564 extern void
1565 js_PurgeScopeChainHelper(JSContext *cx, JSObject *obj, jsid id);
1567 inline void
1568 js_PurgeScopeChain(JSContext *cx, JSObject *obj, jsid id)
1570 if (obj->isDelegate())
1571 js_PurgeScopeChainHelper(cx, obj, id);
1575 * Find or create a property named by id in obj's scope, with the given getter
1576 * and setter, slot, attributes, and other members.
1578 extern const js::Shape *
1579 js_AddNativeProperty(JSContext *cx, JSObject *obj, jsid id,
1580 js::PropertyOp getter, js::PropertyOp setter, uint32 slot,
1581 uintN attrs, uintN flags, intN shortid);
1584 * Change shape to have the given attrs, getter, and setter in scope, morphing
1585 * it into a potentially new js::Shape. Return a pointer to the changed
1586 * or identical property.
1588 extern const js::Shape *
1589 js_ChangeNativePropertyAttrs(JSContext *cx, JSObject *obj,
1590 const js::Shape *shape, uintN attrs, uintN mask,
1591 js::PropertyOp getter, js::PropertyOp setter);
1593 extern JSBool
1594 js_DefineOwnProperty(JSContext *cx, JSObject *obj, jsid id,
1595 const js::Value &descriptor, JSBool *bp);
1598 * Flags for the defineHow parameter of js_DefineNativeProperty.
1600 const uintN JSDNP_CACHE_RESULT = 1; /* an interpreter call from JSOP_INITPROP */
1601 const uintN JSDNP_DONT_PURGE = 2; /* suppress js_PurgeScopeChain */
1602 const uintN JSDNP_SET_METHOD = 4; /* js_{DefineNativeProperty,SetPropertyHelper}
1603 must pass the js::Shape::METHOD
1604 flag on to JSObject::{add,put}Property */
1605 const uintN JSDNP_UNQUALIFIED = 8; /* Unqualified property set. Only used in
1606 the defineHow argument of
1607 js_SetPropertyHelper. */
1610 * On error, return false. On success, if propp is non-null, return true with
1611 * obj locked and with a held property in *propp; if propp is null, return true
1612 * but release obj's lock first.
1614 extern JSBool
1615 js_DefineNativeProperty(JSContext *cx, JSObject *obj, jsid id, const js::Value &value,
1616 js::PropertyOp getter, js::PropertyOp setter, uintN attrs,
1617 uintN flags, intN shortid, JSProperty **propp,
1618 uintN defineHow = 0);
1621 * Specialized subroutine that allows caller to preset JSRESOLVE_* flags and
1622 * returns the index along the prototype chain in which *propp was found, or
1623 * the last index if not found, or -1 on error.
1625 extern int
1626 js_LookupPropertyWithFlags(JSContext *cx, JSObject *obj, jsid id, uintN flags,
1627 JSObject **objp, JSProperty **propp);
1631 * We cache name lookup results only for the global object or for native
1632 * non-global objects without prototype or with prototype that never mutates,
1633 * see bug 462734 and bug 487039.
1635 inline bool
1636 js_IsCacheableNonGlobalScope(JSObject *obj)
1638 extern JS_FRIEND_DATA(js::Class) js_CallClass;
1639 extern JS_FRIEND_DATA(js::Class) js_DeclEnvClass;
1640 JS_ASSERT(obj->getParent());
1642 js::Class *clasp = obj->getClass();
1643 bool cacheable = (clasp == &js_CallClass ||
1644 clasp == &js_BlockClass ||
1645 clasp == &js_DeclEnvClass);
1647 JS_ASSERT_IF(cacheable, !obj->getOps()->lookupProperty);
1648 return cacheable;
1652 * If cacheResult is false, return JS_NO_PROP_CACHE_FILL on success.
1654 extern js::PropertyCacheEntry *
1655 js_FindPropertyHelper(JSContext *cx, jsid id, JSBool cacheResult,
1656 JSObject **objp, JSObject **pobjp, JSProperty **propp);
1659 * Return the index along the scope chain in which id was found, or the last
1660 * index if not found, or -1 on error.
1662 extern JS_FRIEND_API(JSBool)
1663 js_FindProperty(JSContext *cx, jsid id, JSObject **objp, JSObject **pobjp,
1664 JSProperty **propp);
1666 extern JS_REQUIRES_STACK JSObject *
1667 js_FindIdentifierBase(JSContext *cx, JSObject *scopeChain, jsid id);
1669 extern JSObject *
1670 js_FindVariableScope(JSContext *cx, JSFunction **funp);
1673 * JSGET_CACHE_RESULT is the analogue of JSDNP_CACHE_RESULT for js_GetMethod.
1675 * JSGET_METHOD_BARRIER (the default, hence 0 but provided for documentation)
1676 * enables a read barrier that preserves standard function object semantics (by
1677 * default we assume our caller won't leak a joined callee to script, where it
1678 * would create hazardous mutable object sharing as well as observable identity
1679 * according to == and ===.
1681 * JSGET_NO_METHOD_BARRIER avoids the performance overhead of the method read
1682 * barrier, which is not needed when invoking a lambda that otherwise does not
1683 * leak its callee reference (via arguments.callee or its name).
1685 const uintN JSGET_CACHE_RESULT = 1; // from a caching interpreter opcode
1686 const uintN JSGET_METHOD_BARRIER = 0; // get can leak joined function object
1687 const uintN JSGET_NO_METHOD_BARRIER = 2; // call to joined function can't leak
1690 * NB: js_NativeGet and js_NativeSet are called with the scope containing shape
1691 * (pobj's scope for Get, obj's for Set) locked, and on successful return, that
1692 * scope is again locked. But on failure, both functions return false with the
1693 * scope containing shape unlocked.
1695 extern JSBool
1696 js_NativeGet(JSContext *cx, JSObject *obj, JSObject *pobj, const js::Shape *shape, uintN getHow,
1697 js::Value *vp);
1699 extern JSBool
1700 js_NativeSet(JSContext *cx, JSObject *obj, const js::Shape *shape, bool added,
1701 js::Value *vp);
1703 extern JSBool
1704 js_GetPropertyHelper(JSContext *cx, JSObject *obj, jsid id, uint32 getHow, js::Value *vp);
1706 extern bool
1707 js_GetPropertyHelperWithShape(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id,
1708 uint32 getHow, js::Value *vp,
1709 const js::Shape **shapeOut, JSObject **holderOut);
1711 extern JSBool
1712 js_GetOwnPropertyDescriptor(JSContext *cx, JSObject *obj, jsid id, js::Value *vp);
1714 extern JSBool
1715 js_GetMethod(JSContext *cx, JSObject *obj, jsid id, uintN getHow, js::Value *vp);
1718 * Check whether it is OK to assign an undeclared property with name
1719 * propname of the global object in the current script on cx. Reports
1720 * an error if one needs to be reported (in particular in all cases
1721 * when it returns false).
1723 extern JS_FRIEND_API(bool)
1724 js_CheckUndeclaredVarAssignment(JSContext *cx, JSString *propname);
1726 extern JSBool
1727 js_SetPropertyHelper(JSContext *cx, JSObject *obj, jsid id, uintN defineHow,
1728 js::Value *vp, JSBool strict);
1731 * Change attributes for the given native property. The caller must ensure
1732 * that obj is locked and this function always unlocks obj on return.
1734 extern JSBool
1735 js_SetNativeAttributes(JSContext *cx, JSObject *obj, js::Shape *shape,
1736 uintN attrs);
1738 namespace js {
1741 * If obj has a data property methodid which is a function object for the given
1742 * native, return that function object. Otherwise, return NULL.
1744 extern JSObject *
1745 HasNativeMethod(JSObject *obj, jsid methodid, Native native);
1747 extern bool
1748 DefaultValue(JSContext *cx, JSObject *obj, JSType hint, Value *vp);
1750 extern JSBool
1751 CheckAccess(JSContext *cx, JSObject *obj, jsid id, JSAccessMode mode,
1752 js::Value *vp, uintN *attrsp);
1754 } /* namespace js */
1756 extern bool
1757 js_IsDelegate(JSContext *cx, JSObject *obj, const js::Value &v);
1760 * If protoKey is not JSProto_Null, then clasp is ignored. If protoKey is
1761 * JSProto_Null, clasp must non-null.
1763 extern JS_FRIEND_API(JSBool)
1764 js_GetClassPrototype(JSContext *cx, JSObject *scope, JSProtoKey protoKey,
1765 JSObject **protop, js::Class *clasp = NULL);
1767 extern JSBool
1768 js_SetClassPrototype(JSContext *cx, JSObject *ctor, JSObject *proto,
1769 uintN attrs);
1772 * Wrap boolean, number or string as Boolean, Number or String object.
1773 * *vp must not be an object, null or undefined.
1775 extern JSBool
1776 js_PrimitiveToObject(JSContext *cx, js::Value *vp);
1779 * v and vp may alias. On successful return, vp->isObjectOrNull(). If vp is not
1780 * rooted, the caller must root vp before the next possible GC.
1782 extern JSBool
1783 js_ValueToObjectOrNull(JSContext *cx, const js::Value &v, JSObject **objp);
1786 * v and vp may alias. On successful return, vp->isObject(). If vp is not
1787 * rooted, the caller must root vp before the next possible GC.
1789 extern JSObject *
1790 js_ValueToNonNullObject(JSContext *cx, const js::Value &v);
1792 extern JSBool
1793 js_TryValueOf(JSContext *cx, JSObject *obj, JSType type, js::Value *rval);
1795 extern JSBool
1796 js_TryMethod(JSContext *cx, JSObject *obj, JSAtom *atom,
1797 uintN argc, js::Value *argv, js::Value *rval);
1799 extern JSBool
1800 js_XDRObject(JSXDRState *xdr, JSObject **objp);
1802 extern void
1803 js_TraceObject(JSTracer *trc, JSObject *obj);
1805 extern void
1806 js_PrintObjectSlotName(JSTracer *trc, char *buf, size_t bufsize);
1808 extern void
1809 js_ClearNative(JSContext *cx, JSObject *obj);
1811 extern bool
1812 js_GetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, js::Value *vp);
1814 extern bool
1815 js_SetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, const js::Value &v);
1817 extern JSBool
1818 js_CheckPrincipalsAccess(JSContext *cx, JSObject *scopeobj,
1819 JSPrincipals *principals, JSAtom *caller);
1821 /* For CSP -- checks if eval() and friends are allowed to run. */
1822 extern JSBool
1823 js_CheckContentSecurityPolicy(JSContext *cx, JSObject *scopeObj);
1825 /* NB: Infallible. */
1826 extern const char *
1827 js_ComputeFilename(JSContext *cx, JSStackFrame *caller,
1828 JSPrincipals *principals, uintN *linenop);
1830 extern JSBool
1831 js_ReportGetterOnlyAssignment(JSContext *cx);
1833 extern JS_FRIEND_API(JSBool)
1834 js_GetterOnlyPropertyStub(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
1836 #ifdef DEBUG
1837 JS_FRIEND_API(void) js_DumpChars(const jschar *s, size_t n);
1838 JS_FRIEND_API(void) js_DumpString(JSString *str);
1839 JS_FRIEND_API(void) js_DumpAtom(JSAtom *atom);
1840 JS_FRIEND_API(void) js_DumpObject(JSObject *obj);
1841 JS_FRIEND_API(void) js_DumpValue(const js::Value &val);
1842 JS_FRIEND_API(void) js_DumpId(jsid id);
1843 JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, JSStackFrame *start = NULL);
1844 bool IsSaneThisObject(JSObject &obj);
1845 #endif
1847 extern uintN
1848 js_InferFlags(JSContext *cx, uintN defaultFlags);
1850 /* Object constructor native. Exposed only so the JIT can know its address. */
1851 JSBool
1852 js_Object(JSContext *cx, uintN argc, js::Value *vp);
1855 namespace js {
1857 extern bool
1858 SetProto(JSContext *cx, JSObject *obj, JSObject *proto, bool checkForCycles);
1860 extern JSString *
1861 obj_toStringHelper(JSContext *cx, JSObject *obj);
1863 enum EvalType { INDIRECT_EVAL, DIRECT_EVAL };
1866 * Common code implementing direct and indirect eval.
1868 * Evaluate vp[2], if it is a string, in the context of the given calling
1869 * frame, with the provided scope chain, with the semantics of either a direct
1870 * or indirect eval (see ES5 10.4.2). If this is an indirect eval, scopeobj
1871 * must be a global object.
1873 * On success, store the completion value in *vp and return true.
1875 extern bool
1876 EvalKernel(JSContext *cx, uintN argc, js::Value *vp, EvalType evalType, JSStackFrame *caller,
1877 JSObject *scopeobj);
1879 extern JS_FRIEND_API(bool)
1880 IsBuiltinEvalFunction(JSFunction *fun);
1884 #ifdef JS_OBJ_UNDEFD_MOZALLOC_WRAPPERS
1885 # include "mozilla/mozalloc_macro_wrappers.h"
1886 #endif
1888 #endif /* jsobj_h___ */