Merge mozilla-central and tracemonkey. (a=blockers)
[mozilla-central.git] / js / src / jsobj.h
blob27d59fa0212119c81e9ac0ee97e4be0cc4ea929b
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 StrictPropertyOp
84 CastAsStrictPropertyOp(JSObject *object)
86 return JS_DATA_TO_FUNC_PTR(StrictPropertyOp, object);
89 static inline JSPropertyOp
90 CastAsJSPropertyOp(JSObject *object)
92 return JS_DATA_TO_FUNC_PTR(JSPropertyOp, object);
95 static inline JSStrictPropertyOp
96 CastAsJSStrictPropertyOp(JSObject *object)
98 return JS_DATA_TO_FUNC_PTR(JSStrictPropertyOp, object);
101 inline JSObject *
102 CastAsObject(PropertyOp op)
104 return JS_FUNC_TO_DATA_PTR(JSObject *, op);
107 inline JSObject *
108 CastAsObject(StrictPropertyOp op)
110 return JS_FUNC_TO_DATA_PTR(JSObject *, op);
113 inline Value
114 CastAsObjectJsval(PropertyOp op)
116 return ObjectOrNullValue(CastAsObject(op));
119 inline Value
120 CastAsObjectJsval(StrictPropertyOp op)
122 return ObjectOrNullValue(CastAsObject(op));
125 } /* namespace js */
128 * A representation of ECMA-262 ed. 5's internal property descriptor data
129 * structure.
131 struct PropDesc {
132 friend class js::AutoPropDescArrayRooter;
134 PropDesc();
136 public:
137 /* 8.10.5 ToPropertyDescriptor(Obj) */
138 bool initialize(JSContext* cx, jsid id, const js::Value &v);
140 /* 8.10.1 IsAccessorDescriptor(desc) */
141 bool isAccessorDescriptor() const {
142 return hasGet || hasSet;
145 /* 8.10.2 IsDataDescriptor(desc) */
146 bool isDataDescriptor() const {
147 return hasValue || hasWritable;
150 /* 8.10.3 IsGenericDescriptor(desc) */
151 bool isGenericDescriptor() const {
152 return !isAccessorDescriptor() && !isDataDescriptor();
155 bool configurable() const {
156 return (attrs & JSPROP_PERMANENT) == 0;
159 bool enumerable() const {
160 return (attrs & JSPROP_ENUMERATE) != 0;
163 bool writable() const {
164 return (attrs & JSPROP_READONLY) == 0;
167 JSObject* getterObject() const {
168 return get.isUndefined() ? NULL : &get.toObject();
170 JSObject* setterObject() const {
171 return set.isUndefined() ? NULL : &set.toObject();
174 const js::Value &getterValue() const {
175 return get;
177 const js::Value &setterValue() const {
178 return set;
181 js::PropertyOp getter() const {
182 return js::CastAsPropertyOp(getterObject());
184 js::StrictPropertyOp setter() const {
185 return js::CastAsStrictPropertyOp(setterObject());
188 js::Value pd;
189 jsid id;
190 js::Value value, get, set;
192 /* Property descriptor boolean fields. */
193 uint8 attrs;
195 /* Bits indicating which values are set. */
196 bool hasGet : 1;
197 bool hasSet : 1;
198 bool hasValue : 1;
199 bool hasWritable : 1;
200 bool hasEnumerable : 1;
201 bool hasConfigurable : 1;
204 namespace js {
206 typedef Vector<PropDesc, 1> PropDescArray;
208 } /* namespace js */
210 struct JSObjectMap {
211 uint32 shape; /* shape identifier */
212 uint32 slotSpan; /* one more than maximum live slot number */
214 static JS_FRIEND_DATA(const JSObjectMap) sharedNonNative;
216 explicit JSObjectMap(uint32 shape) : shape(shape), slotSpan(0) {}
217 JSObjectMap(uint32 shape, uint32 slotSpan) : shape(shape), slotSpan(slotSpan) {}
219 enum { INVALID_SHAPE = 0x8fffffff, SHAPELESS = 0xffffffff };
221 bool isNative() const { return this != &sharedNonNative; }
223 private:
224 /* No copy or assignment semantics. */
225 JSObjectMap(JSObjectMap &);
226 void operator=(JSObjectMap &);
230 * Unlike js_DefineNativeProperty, propp must be non-null. On success, and if
231 * id was found, return true with *objp non-null and with a property of *objp
232 * stored in *propp. If successful but id was not found, return true with both
233 * *objp and *propp null.
235 extern JS_FRIEND_API(JSBool)
236 js_LookupProperty(JSContext *cx, JSObject *obj, jsid id, JSObject **objp,
237 JSProperty **propp);
239 extern JSBool
240 js_DefineProperty(JSContext *cx, JSObject *obj, jsid id, const js::Value *value,
241 js::PropertyOp getter, js::StrictPropertyOp setter, uintN attrs);
243 extern JSBool
244 js_GetProperty(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, js::Value *vp);
246 inline JSBool
247 js_GetProperty(JSContext *cx, JSObject *obj, jsid id, js::Value *vp)
249 return js_GetProperty(cx, obj, obj, id, vp);
252 namespace js {
254 extern JSBool
255 GetPropertyDefault(JSContext *cx, JSObject *obj, jsid id, const Value &def, Value *vp);
257 } /* namespace js */
259 extern JSBool
260 js_SetProperty(JSContext *cx, JSObject *obj, jsid id, js::Value *vp, JSBool strict);
262 extern JSBool
263 js_GetAttributes(JSContext *cx, JSObject *obj, jsid id, uintN *attrsp);
265 extern JSBool
266 js_SetAttributes(JSContext *cx, JSObject *obj, jsid id, uintN *attrsp);
268 extern JSBool
269 js_DeleteProperty(JSContext *cx, JSObject *obj, jsid id, js::Value *rval, JSBool strict);
271 extern JS_FRIEND_API(JSBool)
272 js_Enumerate(JSContext *cx, JSObject *obj, JSIterateOp enum_op,
273 js::Value *statep, jsid *idp);
275 extern JSType
276 js_TypeOf(JSContext *cx, JSObject *obj);
278 namespace js {
280 struct NativeIterator;
284 struct JSFunction;
286 namespace nanojit {
287 class ValidateWriter;
291 * JSObject struct, with members sized to fit in 32 bytes on 32-bit targets,
292 * 64 bytes on 64-bit systems. The JSFunction struct is an extension of this
293 * struct allocated from a larger GC size-class.
295 * The clasp member stores the js::Class pointer for this object. We do *not*
296 * synchronize updates of clasp or flags -- API clients must take care.
298 * An object is a delegate if it is on another object's prototype (the proto
299 * field) or scope chain (the parent field), and therefore the delegate might
300 * be asked implicitly to get or set a property on behalf of another object.
301 * Delegates may be accessed directly too, as may any object, but only those
302 * objects linked after the head of any prototype or scope chain are flagged
303 * as delegates. This definition helps to optimize shape-based property cache
304 * invalidation (see Purge{Scope,Proto}Chain in jsobj.cpp).
306 * The meaning of the system object bit is defined by the API client. It is
307 * set in JS_NewSystemObject and is queried by JS_IsSystemObject (jsdbgapi.h),
308 * but it has no intrinsic meaning to SpiderMonkey. Further, JSFILENAME_SYSTEM
309 * and JS_FlagScriptFilenamePrefix (also exported via jsdbgapi.h) are intended
310 * to be complementary to this bit, but it is up to the API client to implement
311 * any such association.
313 * Both these flag bits are initially zero; they may be set or queried using
314 * the (is|set)(Delegate|System) inline methods.
316 * The slots member is a pointer to the slot vector for the object.
317 * This can be either a fixed array allocated immediately after the object,
318 * or a dynamically allocated array. A dynamic array can be tested for with
319 * hasSlotsArray(). In all cases, capacity gives the number of usable slots.
320 * Two objects with the same shape have the same number of fixed slots,
321 * and either both have or neither have dynamically allocated slot arrays.
323 * If you change this struct, you'll probably need to change the AccSet values
324 * in jsbuiltins.h.
326 struct JSObject : js::gc::Cell {
328 * TraceRecorder must be a friend because it generates code that
329 * manipulates JSObjects, which requires peeking under any encapsulation.
330 * ValidateWriter must be a friend because it works in tandem with
331 * TraceRecorder.
333 friend class js::TraceRecorder;
334 friend class nanojit::ValidateWriter;
335 friend class GetPropCompiler;
338 * Private pointer to the last added property and methods to manipulate the
339 * list it links among properties in this scope. The {remove,insert} pair
340 * for DictionaryProperties assert that the scope is in dictionary mode and
341 * any reachable properties are flagged as dictionary properties.
343 * For native objects, this field is always a Shape. For non-native objects,
344 * it points to the singleton sharedNonNative JSObjectMap, whose shape field
345 * is SHAPELESS.
347 * NB: these private methods do *not* update this scope's shape to track
348 * lastProp->shape after they finish updating the linked list in the case
349 * where lastProp is updated. It is up to calling code in jsscope.cpp to
350 * call updateShape(cx) after updating lastProp.
352 union {
353 js::Shape *lastProp;
354 JSObjectMap *map;
357 js::Class *clasp;
359 private:
360 inline void setLastProperty(const js::Shape *shape);
361 inline void removeLastProperty();
363 #ifdef DEBUG
364 void checkShapeConsistency();
365 #endif
367 public:
368 inline const js::Shape *lastProperty() const;
370 inline js::Shape **nativeSearch(jsid id, bool adding = false);
371 inline const js::Shape *nativeLookup(jsid id);
373 inline bool nativeContains(jsid id);
374 inline bool nativeContains(const js::Shape &shape);
376 enum {
377 DELEGATE = 0x01,
378 SYSTEM = 0x02,
379 NOT_EXTENSIBLE = 0x04,
380 BRANDED = 0x08,
381 GENERIC = 0x10,
382 METHOD_BARRIER = 0x20,
383 INDEXED = 0x40,
384 OWN_SHAPE = 0x80,
385 BOUND_FUNCTION = 0x100,
386 HAS_EQUALITY = 0x200,
387 METHOD_THRASH_COUNT_MASK = 0xc00,
388 METHOD_THRASH_COUNT_SHIFT = 10,
389 METHOD_THRASH_COUNT_MAX = METHOD_THRASH_COUNT_MASK >> METHOD_THRASH_COUNT_SHIFT
393 * Impose a sane upper bound, originally checked only for dense arrays, on
394 * number of slots in an object.
396 enum {
397 NSLOTS_BITS = 29,
398 NSLOTS_LIMIT = JS_BIT(NSLOTS_BITS)
401 uint32 flags; /* flags */
402 uint32 objShape; /* copy of lastProp->shape, or override if different */
404 /* If prototype, lazily filled array of empty shapes for each object size. */
405 js::EmptyShape **emptyShapes;
407 JSObject *proto; /* object's prototype */
408 JSObject *parent; /* object's parent */
409 void *privateData; /* private data */
410 jsuword capacity; /* capacity of slots */
411 js::Value *slots; /* dynamically allocated slots,
412 or pointer to fixedSlots() */
415 * Return an immutable, shareable, empty shape with the same clasp as this
416 * and the same slotSpan as this had when empty.
418 * If |this| is the scope of an object |proto|, the resulting scope can be
419 * used as the scope of a new object whose prototype is |proto|.
421 inline bool canProvideEmptyShape(js::Class *clasp);
422 inline js::EmptyShape *getEmptyShape(JSContext *cx, js::Class *aclasp,
423 /* gc::FinalizeKind */ unsigned kind);
425 bool isNative() const { return map->isNative(); }
427 js::Class *getClass() const { return clasp; }
428 JSClass *getJSClass() const { return Jsvalify(clasp); }
430 bool hasClass(const js::Class *c) const {
431 return c == clasp;
434 const js::ObjectOps *getOps() const {
435 return &getClass()->ops;
438 inline void trace(JSTracer *trc);
440 uint32 shape() const {
441 JS_ASSERT(objShape != JSObjectMap::INVALID_SHAPE);
442 return objShape;
445 bool isDelegate() const { return !!(flags & DELEGATE); }
446 void setDelegate() { flags |= DELEGATE; }
447 void clearDelegate() { flags &= ~DELEGATE; }
449 bool isBoundFunction() const { return !!(flags & BOUND_FUNCTION); }
451 static void setDelegateNullSafe(JSObject *obj) {
452 if (obj)
453 obj->setDelegate();
456 bool isSystem() const { return !!(flags & SYSTEM); }
457 void setSystem() { flags |= SYSTEM; }
460 * A branded object contains plain old methods (function-valued properties
461 * without magic getters and setters), and its shape evolves whenever a
462 * function value changes.
464 bool branded() { return !!(flags & BRANDED); }
467 * NB: these return false on shape overflow but do not report any error.
468 * Callers who depend on shape guarantees should therefore bail off trace,
469 * e.g., on false returns.
471 bool brand(JSContext *cx);
472 bool unbrand(JSContext *cx);
474 bool generic() { return !!(flags & GENERIC); }
475 void setGeneric() { flags |= GENERIC; }
477 uintN getMethodThrashCount() const {
478 return (flags & METHOD_THRASH_COUNT_MASK) >> METHOD_THRASH_COUNT_SHIFT;
481 void setMethodThrashCount(uintN count) {
482 JS_ASSERT(count <= METHOD_THRASH_COUNT_MAX);
483 flags = (flags & ~METHOD_THRASH_COUNT_MASK) | (count << METHOD_THRASH_COUNT_SHIFT);
486 bool hasSpecialEquality() const { return !!(flags & HAS_EQUALITY); }
487 void assertSpecialEqualitySynced() const {
488 JS_ASSERT(!!clasp->ext.equality == hasSpecialEquality());
491 /* Sets an object's HAS_EQUALITY flag based on its clasp. */
492 inline void syncSpecialEquality();
494 private:
495 void generateOwnShape(JSContext *cx);
497 void setOwnShape(uint32 s) { flags |= OWN_SHAPE; objShape = s; }
498 void clearOwnShape() { flags &= ~OWN_SHAPE; objShape = map->shape; }
500 public:
501 inline bool nativeEmpty() const;
503 bool hasOwnShape() const { return !!(flags & OWN_SHAPE); }
505 void setMap(const JSObjectMap *amap) {
506 JS_ASSERT(!hasOwnShape());
507 map = const_cast<JSObjectMap *>(amap);
508 objShape = map->shape;
511 void setSharedNonNativeMap() {
512 setMap(&JSObjectMap::sharedNonNative);
515 void deletingShapeChange(JSContext *cx, const js::Shape &shape);
516 const js::Shape *methodShapeChange(JSContext *cx, const js::Shape &shape);
517 bool methodShapeChange(JSContext *cx, uint32 slot);
518 void protoShapeChange(JSContext *cx);
519 void shadowingShapeChange(JSContext *cx, const js::Shape &shape);
520 bool globalObjectOwnShapeChange(JSContext *cx);
521 void watchpointOwnShapeChange(JSContext *cx) { generateOwnShape(cx); }
523 void extensibleShapeChange(JSContext *cx) {
524 /* This will do for now. */
525 generateOwnShape(cx);
529 * A scope has a method barrier when some compiler-created "null closure"
530 * function objects (functions that do not use lexical bindings above their
531 * scope, only free variable names) that have a correct JSSLOT_PARENT value
532 * thanks to the COMPILE_N_GO optimization are stored as newly added direct
533 * property values of the scope's object.
535 * The de-facto standard JS language requires each evaluation of such a
536 * closure to result in a unique (according to === and observable effects)
537 * function object. ES3 tried to allow implementations to "join" such
538 * objects to a single compiler-created object, but this makes an overt
539 * mutation hazard, also an "identity hazard" against interoperation among
540 * implementations that join and do not join.
542 * To stay compatible with the de-facto standard, we store the compiler-
543 * created function object as the method value and set the METHOD_BARRIER
544 * flag.
546 * The method value is part of the method property tree node's identity, so
547 * it effectively brands the scope with a predictable shape corresponding
548 * to the method value, but without the overhead of setting the BRANDED
549 * flag, which requires assigning a new shape peculiar to each branded
550 * scope. Instead the shape is shared via the property tree among all the
551 * scopes referencing the method property tree node.
553 * Then when reading from a scope for which scope->hasMethodBarrier() is
554 * true, we count on the scope's qualified/guarded shape being unique and
555 * add a read barrier that clones the compiler-created function object on
556 * demand, reshaping the scope.
558 * This read barrier is bypassed when evaluating the callee sub-expression
559 * of a call expression (see the JOF_CALLOP opcodes in jsopcode.tbl), since
560 * such ops do not present an identity or mutation hazard. The compiler
561 * performs this optimization only for null closures that do not use their
562 * own name or equivalent built-in references (arguments.callee).
564 * The BRANDED write barrier, JSObject::methodWriteBarrer, must check for
565 * METHOD_BARRIER too, and regenerate this scope's shape if the method's
566 * value is in fact changing.
568 bool hasMethodBarrier() { return !!(flags & METHOD_BARRIER); }
569 void setMethodBarrier() { flags |= METHOD_BARRIER; }
572 * Test whether this object may be branded due to method calls, which means
573 * any assignment to a function-valued property must regenerate shape; else
574 * test whether this object has method properties, which require a method
575 * write barrier.
577 bool brandedOrHasMethodBarrier() { return !!(flags & (BRANDED | METHOD_BARRIER)); }
580 * Read barrier to clone a joined function object stored as a method.
581 * Defined in jsobjinlines.h, but not declared inline per standard style in
582 * order to avoid gcc warnings.
584 const js::Shape *methodReadBarrier(JSContext *cx, const js::Shape &shape, js::Value *vp);
587 * Write barrier to check for a change of method value. Defined inline in
588 * jsobjinlines.h after methodReadBarrier. The slot flavor is required by
589 * JSOP_*GVAR, which deals in slots not shapes, while not deoptimizing to
590 * map slot to shape unless JSObject::flags show that this is necessary.
591 * The methodShapeChange overload (above) parallels this.
593 const js::Shape *methodWriteBarrier(JSContext *cx, const js::Shape &shape, const js::Value &v);
594 bool methodWriteBarrier(JSContext *cx, uint32 slot, const js::Value &v);
596 bool isIndexed() const { return !!(flags & INDEXED); }
597 void setIndexed() { flags |= INDEXED; }
600 * Return true if this object is a native one that has been converted from
601 * shared-immutable prototype-rooted shape storage to dictionary-shapes in
602 * a doubly-linked list.
604 inline bool inDictionaryMode() const;
606 inline uint32 propertyCount() const;
608 inline bool hasPropertyTable() const;
610 /* gc::FinalizeKind */ unsigned finalizeKind() const;
612 uint32 numSlots() const { return capacity; }
614 size_t slotsAndStructSize(uint32 nslots) const;
615 size_t slotsAndStructSize() const { return slotsAndStructSize(numSlots()); }
617 inline js::Value* fixedSlots() const;
618 inline size_t numFixedSlots() const;
620 static inline size_t getFixedSlotOffset(size_t slot);
622 public:
623 /* Minimum size for dynamically allocated slots. */
624 static const uint32 SLOT_CAPACITY_MIN = 8;
626 bool allocSlots(JSContext *cx, size_t nslots);
627 bool growSlots(JSContext *cx, size_t nslots);
628 void shrinkSlots(JSContext *cx, size_t nslots);
630 bool ensureSlots(JSContext *cx, size_t nslots) {
631 if (numSlots() < nslots)
632 return growSlots(cx, nslots);
633 return true;
637 * Ensure that the object has at least JSCLASS_RESERVED_SLOTS(clasp) +
638 * nreserved slots.
640 * This method may be called only for native objects freshly created using
641 * NewObject or one of its variant where the new object will both (a) never
642 * escape to script and (b) never be extended with ad-hoc properties that
643 * would try to allocate higher slots without the fresh object first having
644 * its map set to a shape path that maps those slots.
646 * Block objects satisfy (a) and (b), as there is no evil eval-based way to
647 * add ad-hoc properties to a Block instance. Call objects satisfy (a) and
648 * (b) as well, because the compiler-created Shape path that covers args,
649 * vars, and upvars, stored in their callee function in u.i.names, becomes
650 * their initial map.
652 bool ensureInstanceReservedSlots(JSContext *cx, size_t nreserved);
655 * Get a direct pointer to the object's slots.
656 * This can be reallocated if the object is modified, watch out!
658 js::Value *getSlots() const {
659 return slots;
663 * NB: ensureClassReservedSlotsForEmptyObject asserts that nativeEmpty()
664 * Use ensureClassReservedSlots for any object, either empty or already
665 * extended with properties.
667 bool ensureClassReservedSlotsForEmptyObject(JSContext *cx);
669 inline bool ensureClassReservedSlots(JSContext *cx);
671 uint32 slotSpan() const { return map->slotSpan; }
673 bool containsSlot(uint32 slot) const { return slot < slotSpan(); }
675 js::Value& getSlotRef(uintN slot) {
676 JS_ASSERT(slot < capacity);
677 return slots[slot];
680 js::Value &nativeGetSlotRef(uintN slot) {
681 JS_ASSERT(isNative());
682 JS_ASSERT(containsSlot(slot));
683 return getSlotRef(slot);
686 const js::Value &getSlot(uintN slot) const {
687 JS_ASSERT(slot < capacity);
688 return slots[slot];
691 const js::Value &nativeGetSlot(uintN slot) const {
692 JS_ASSERT(isNative());
693 JS_ASSERT(containsSlot(slot));
694 return getSlot(slot);
697 void setSlot(uintN slot, const js::Value &value) {
698 JS_ASSERT(slot < capacity);
699 slots[slot] = value;
702 void nativeSetSlot(uintN slot, const js::Value &value) {
703 JS_ASSERT(isNative());
704 JS_ASSERT(containsSlot(slot));
705 return setSlot(slot, value);
708 inline js::Value getReservedSlot(uintN index) const;
710 /* Defined in jsscopeinlines.h to avoid including implementation dependencies here. */
711 inline void updateShape(JSContext *cx);
712 inline void updateFlags(const js::Shape *shape, bool isDefinitelyAtom = false);
714 /* Extend this object to have shape as its last-added property. */
715 inline void extend(JSContext *cx, const js::Shape *shape, bool isDefinitelyAtom = false);
717 JSObject *getProto() const { return proto; }
718 void clearProto() { proto = NULL; }
720 void setProto(JSObject *newProto) {
721 #ifdef DEBUG
722 for (JSObject *obj = newProto; obj; obj = obj->getProto())
723 JS_ASSERT(obj != this);
724 #endif
725 setDelegateNullSafe(newProto);
726 proto = newProto;
729 JSObject *getParent() const {
730 return parent;
733 void clearParent() {
734 parent = NULL;
737 void setParent(JSObject *newParent) {
738 #ifdef DEBUG
739 for (JSObject *obj = newParent; obj; obj = obj->getParent())
740 JS_ASSERT(obj != this);
741 #endif
742 setDelegateNullSafe(newParent);
743 parent = newParent;
746 JS_FRIEND_API(JSObject *) getGlobal() const;
748 bool isGlobal() const {
749 return !!(getClass()->flags & JSCLASS_IS_GLOBAL);
752 void *getPrivate() const {
753 JS_ASSERT(getClass()->flags & JSCLASS_HAS_PRIVATE);
754 return privateData;
757 void setPrivate(void *data) {
758 JS_ASSERT(getClass()->flags & JSCLASS_HAS_PRIVATE);
759 privateData = data;
764 * ES5 meta-object properties and operations.
767 private:
768 enum ImmutabilityType { SEAL, FREEZE };
771 * The guts of Object.seal (ES5 15.2.3.8) and Object.freeze (ES5 15.2.3.9): mark the
772 * object as non-extensible, and adjust each property's attributes appropriately: each
773 * property becomes non-configurable, and if |freeze|, data properties become
774 * read-only as well.
776 bool sealOrFreeze(JSContext *cx, ImmutabilityType it);
778 public:
779 bool isExtensible() const { return !(flags & NOT_EXTENSIBLE); }
780 bool preventExtensions(JSContext *cx, js::AutoIdVector *props);
782 /* ES5 15.2.3.8: non-extensible, all props non-configurable */
783 inline bool seal(JSContext *cx) { return sealOrFreeze(cx, SEAL); }
784 /* ES5 15.2.3.9: non-extensible, all properties non-configurable, all data props read-only */
785 bool freeze(JSContext *cx) { return sealOrFreeze(cx, FREEZE); }
788 * Primitive-specific getters and setters.
791 private:
792 static const uint32 JSSLOT_PRIMITIVE_THIS = 0;
794 public:
795 inline const js::Value &getPrimitiveThis() const;
796 inline void setPrimitiveThis(const js::Value &pthis);
799 * Array-specific getters and setters (for both dense and slow arrays).
802 inline uint32 getArrayLength() const;
803 inline void setArrayLength(uint32 length);
805 inline uint32 getDenseArrayCapacity();
806 inline js::Value* getDenseArrayElements();
807 inline const js::Value &getDenseArrayElement(uintN idx);
808 inline js::Value* addressOfDenseArrayElement(uintN idx);
809 inline void setDenseArrayElement(uintN idx, const js::Value &val);
810 inline void shrinkDenseArrayElements(JSContext *cx, uintN cap);
813 * ensureDenseArrayElements ensures that the dense array can hold at least
814 * index + extra elements. It returns ED_OK on success, ED_FAILED on
815 * failure to grow the array, ED_SPARSE when the array is too sparse to
816 * grow (this includes the case of index + extra overflow). In the last
817 * two cases the array is kept intact.
819 enum EnsureDenseResult { ED_OK, ED_FAILED, ED_SPARSE };
820 inline EnsureDenseResult ensureDenseArrayElements(JSContext *cx, uintN index, uintN extra);
823 * Check if after growing the dense array will be too sparse.
824 * newElementsHint is an estimated number of elements to be added.
826 bool willBeSparseDenseArray(uintN requiredCapacity, uintN newElementsHint);
828 JSBool makeDenseArraySlow(JSContext *cx);
831 * Arguments-specific getters and setters.
834 private:
836 * We represent arguments objects using js_ArgumentsClass and
837 * js::StrictArgumentsClass. The two are structured similarly, and methods
838 * valid on arguments objects of one class are also generally valid on
839 * arguments objects of the other.
841 * Arguments objects of either class store arguments length in a slot:
843 * JSSLOT_ARGS_LENGTH - the number of actual arguments and a flag
844 * indicating whether arguments.length was
845 * overwritten. This slot is not used to represent
846 * arguments.length after that property has been
847 * assigned, even if the new value is integral: it's
848 * always the original length.
850 * Both arguments classes use a slot for storing arguments data:
852 * JSSLOT_ARGS_DATA - pointer to an ArgumentsData structure
854 * ArgumentsData for normal arguments stores the value of arguments.callee,
855 * as long as that property has not been overwritten. If arguments.callee
856 * is overwritten, the corresponding value in ArgumentsData is set to
857 * MagicValue(JS_ARGS_HOLE). Strict arguments do not store this value
858 * because arguments.callee is a poison pill for strict mode arguments.
860 * The ArgumentsData structure also stores argument values. For normal
861 * arguments this occurs after the corresponding function has returned, and
862 * for strict arguments this occurs when the arguments object is created,
863 * or sometimes shortly after (but not observably so). arguments[i] is
864 * stored in ArgumentsData.slots[i], accessible via getArgsElement() and
865 * setArgsElement(). Deletion of arguments[i] overwrites that slot with
866 * MagicValue(JS_ARGS_HOLE); subsequent redefinition of arguments[i] will
867 * use a normal property to store the value, ignoring the slot.
869 * Non-strict arguments have a private:
871 * private - the function's stack frame until the function
872 * returns, when it is replaced with null; also,
873 * JS_ARGUMENTS_OBJECT_ON_TRACE while on trace, if
874 * arguments was created on trace
876 * Technically strict arguments have a private, but it's always null.
877 * Conceptually it would be better to remove this oddity, but preserving it
878 * allows us to work with arguments objects of either kind more abstractly,
879 * so we keep it for now.
881 static const uint32 JSSLOT_ARGS_DATA = 1;
883 public:
884 /* Number of extra fixed arguments object slots besides JSSLOT_PRIVATE. */
885 static const uint32 JSSLOT_ARGS_LENGTH = 0;
886 static const uint32 ARGS_CLASS_RESERVED_SLOTS = 2;
887 static const uint32 ARGS_FIRST_FREE_SLOT = ARGS_CLASS_RESERVED_SLOTS + 1;
889 /* Lower-order bit stolen from the length slot. */
890 static const uint32 ARGS_LENGTH_OVERRIDDEN_BIT = 0x1;
891 static const uint32 ARGS_PACKED_BITS_COUNT = 1;
894 * Set the initial length of the arguments, and mark it as not overridden.
896 inline void setArgsLength(uint32 argc);
899 * Return the initial length of the arguments. This may differ from the
900 * current value of arguments.length!
902 inline uint32 getArgsInitialLength() const;
904 inline void setArgsLengthOverridden();
905 inline bool isArgsLengthOverridden() const;
907 inline js::ArgumentsData *getArgsData() const;
908 inline void setArgsData(js::ArgumentsData *data);
910 inline const js::Value &getArgsCallee() const;
911 inline void setArgsCallee(const js::Value &callee);
913 inline const js::Value &getArgsElement(uint32 i) const;
914 inline js::Value *getArgsElements() const;
915 inline js::Value *addressOfArgsElement(uint32 i);
916 inline void setArgsElement(uint32 i, const js::Value &v);
918 private:
920 * Reserved slot structure for Call objects:
922 * private - the stack frame corresponding to the Call object
923 * until js_PutCallObject or its on-trace analog
924 * is called, null thereafter
925 * JSSLOT_CALL_CALLEE - callee function for the stack frame, or null if
926 * the stack frame is for strict mode eval code
927 * JSSLOT_CALL_ARGUMENTS - arguments object for non-strict mode eval stack
928 * frames (not valid for strict mode eval frames)
930 static const uint32 JSSLOT_CALL_CALLEE = 0;
931 static const uint32 JSSLOT_CALL_ARGUMENTS = 1;
933 public:
934 /* Number of reserved slots. */
935 static const uint32 CALL_RESERVED_SLOTS = 2;
937 /* True if this is for a strict mode eval frame or for a function call. */
938 inline bool callIsForEval() const;
940 /* The stack frame for this Call object, if the frame is still active. */
941 inline JSStackFrame *maybeCallObjStackFrame() const;
944 * The callee function if this Call object was created for a function
945 * invocation, or null if it was created for a strict mode eval frame.
947 inline JSObject *getCallObjCallee() const;
948 inline JSFunction *getCallObjCalleeFunction() const;
949 inline void setCallObjCallee(JSObject *callee);
951 inline const js::Value &getCallObjArguments() const;
952 inline void setCallObjArguments(const js::Value &v);
954 /* Returns the formal argument at the given index. */
955 inline const js::Value &callObjArg(uintN i) const;
956 inline js::Value &callObjArg(uintN i);
958 /* Returns the variable at the given index. */
959 inline const js::Value &callObjVar(uintN i) const;
960 inline js::Value &callObjVar(uintN i);
963 * Date-specific getters and setters.
966 static const uint32 JSSLOT_DATE_UTC_TIME = 0;
969 * Cached slots holding local properties of the date.
970 * These are undefined until the first actual lookup occurs
971 * and are reset to undefined whenever the date's time is modified.
973 static const uint32 JSSLOT_DATE_COMPONENTS_START = 1;
975 static const uint32 JSSLOT_DATE_LOCAL_TIME = 1;
976 static const uint32 JSSLOT_DATE_LOCAL_YEAR = 2;
977 static const uint32 JSSLOT_DATE_LOCAL_MONTH = 3;
978 static const uint32 JSSLOT_DATE_LOCAL_DATE = 4;
979 static const uint32 JSSLOT_DATE_LOCAL_DAY = 5;
980 static const uint32 JSSLOT_DATE_LOCAL_HOURS = 6;
981 static const uint32 JSSLOT_DATE_LOCAL_MINUTES = 7;
982 static const uint32 JSSLOT_DATE_LOCAL_SECONDS = 8;
984 static const uint32 DATE_CLASS_RESERVED_SLOTS = 9;
986 inline const js::Value &getDateUTCTime() const;
987 inline void setDateUTCTime(const js::Value &pthis);
990 * Function-specific getters and setters.
993 private:
994 friend struct JSFunction;
995 friend class js::mjit::Compiler;
998 * Flat closures with one or more upvars snapshot the upvars' values into a
999 * vector of js::Values referenced from this slot.
1001 static const uint32 JSSLOT_FLAT_CLOSURE_UPVARS = 0;
1004 * Null closures set or initialized as methods have these slots. See the
1005 * "method barrier" comments and methods.
1008 static const uint32 JSSLOT_FUN_METHOD_ATOM = 0;
1009 static const uint32 JSSLOT_FUN_METHOD_OBJ = 1;
1011 static const uint32 JSSLOT_BOUND_FUNCTION_THIS = 0;
1012 static const uint32 JSSLOT_BOUND_FUNCTION_ARGS_COUNT = 1;
1014 public:
1015 static const uint32 FUN_CLASS_RESERVED_SLOTS = 2;
1017 inline JSFunction *getFunctionPrivate() const;
1019 inline js::Value *getFlatClosureUpvars() const;
1020 inline js::Value getFlatClosureUpvar(uint32 i) const;
1021 inline js::Value &getFlatClosureUpvar(uint32 i);
1022 inline void setFlatClosureUpvars(js::Value *upvars);
1024 inline bool hasMethodObj(const JSObject& obj) const;
1025 inline void setMethodObj(JSObject& obj);
1027 inline bool initBoundFunction(JSContext *cx, const js::Value &thisArg,
1028 const js::Value *args, uintN argslen);
1030 inline JSObject *getBoundFunctionTarget() const;
1031 inline const js::Value &getBoundFunctionThis() const;
1032 inline const js::Value *getBoundFunctionArguments(uintN &argslen) const;
1035 * RegExp-specific getters and setters.
1038 private:
1039 static const uint32 JSSLOT_REGEXP_LAST_INDEX = 0;
1041 public:
1042 static const uint32 REGEXP_CLASS_RESERVED_SLOTS = 1;
1044 inline const js::Value &getRegExpLastIndex() const;
1045 inline void setRegExpLastIndex(const js::Value &v);
1046 inline void setRegExpLastIndex(jsdouble d);
1047 inline void zeroRegExpLastIndex();
1050 * Iterator-specific getters and setters.
1053 inline js::NativeIterator *getNativeIterator() const;
1054 inline void setNativeIterator(js::NativeIterator *);
1057 * XML-related getters and setters.
1061 * Slots for XML-related classes are as follows:
1062 * - js_NamespaceClass.base reserves the *_NAME_* and *_NAMESPACE_* slots.
1063 * - js_QNameClass.base, js_AttributeNameClass, js_AnyNameClass reserve
1064 * the *_NAME_* and *_QNAME_* slots.
1065 * - Others (js_XMLClass, js_XMLFilterClass) don't reserve any slots.
1067 private:
1068 static const uint32 JSSLOT_NAME_PREFIX = 0; // shared
1069 static const uint32 JSSLOT_NAME_URI = 1; // shared
1071 static const uint32 JSSLOT_NAMESPACE_DECLARED = 2;
1073 static const uint32 JSSLOT_QNAME_LOCAL_NAME = 2;
1075 public:
1076 static const uint32 NAMESPACE_CLASS_RESERVED_SLOTS = 3;
1077 static const uint32 QNAME_CLASS_RESERVED_SLOTS = 3;
1079 inline JSLinearString *getNamePrefix() const;
1080 inline jsval getNamePrefixVal() const;
1081 inline void setNamePrefix(JSLinearString *prefix);
1082 inline void clearNamePrefix();
1084 inline JSLinearString *getNameURI() const;
1085 inline jsval getNameURIVal() const;
1086 inline void setNameURI(JSLinearString *uri);
1088 inline jsval getNamespaceDeclared() const;
1089 inline void setNamespaceDeclared(jsval decl);
1091 inline JSLinearString *getQNameLocalName() const;
1092 inline jsval getQNameLocalNameVal() const;
1093 inline void setQNameLocalName(JSLinearString *name);
1096 * Proxy-specific getters and setters.
1099 inline js::JSProxyHandler *getProxyHandler() const;
1100 inline const js::Value &getProxyPrivate() const;
1101 inline void setProxyPrivate(const js::Value &priv);
1102 inline const js::Value &getProxyExtra() const;
1103 inline void setProxyExtra(const js::Value &extra);
1106 * With object-specific getters and setters.
1108 inline JSObject *getWithThis() const;
1109 inline void setWithThis(JSObject *thisp);
1112 * Back to generic stuff.
1114 inline bool isCallable();
1116 /* The map field is not initialized here and should be set separately. */
1117 void init(JSContext *cx, js::Class *aclasp, JSObject *proto, JSObject *parent,
1118 void *priv, bool useHoles);
1120 inline void finish(JSContext *cx);
1121 JS_ALWAYS_INLINE void finalize(JSContext *cx);
1124 * Like init, but also initializes map. The catch: proto must be the result
1125 * of a call to js_InitClass(...clasp, ...).
1127 inline bool initSharingEmptyShape(JSContext *cx,
1128 js::Class *clasp,
1129 JSObject *proto,
1130 JSObject *parent,
1131 void *priv,
1132 /* gc::FinalizeKind */ unsigned kind);
1134 inline bool hasSlotsArray() const;
1136 /* This method can only be called when hasSlotsArray() returns true. */
1137 inline void freeSlotsArray(JSContext *cx);
1139 /* Free the slots array and copy slots that fit into the fixed array. */
1140 inline void revertToFixedSlots(JSContext *cx);
1142 inline bool hasProperty(JSContext *cx, jsid id, bool *foundp, uintN flags = 0);
1145 * Allocate and free an object slot. Note that freeSlot is infallible: it
1146 * returns true iff this is a dictionary-mode object and the freed slot was
1147 * added to the freelist.
1149 * FIXME: bug 593129 -- slot allocation should be done by object methods
1150 * after calling object-parameter-free shape methods, avoiding coupling
1151 * logic across the object vs. shape module wall.
1153 bool allocSlot(JSContext *cx, uint32 *slotp);
1154 bool freeSlot(JSContext *cx, uint32 slot);
1156 public:
1157 bool reportReadOnly(JSContext* cx, jsid id, uintN report = JSREPORT_ERROR);
1158 bool reportNotConfigurable(JSContext* cx, jsid id, uintN report = JSREPORT_ERROR);
1159 bool reportNotExtensible(JSContext *cx, uintN report = JSREPORT_ERROR);
1161 private:
1162 js::Shape *getChildProperty(JSContext *cx, js::Shape *parent, js::Shape &child);
1165 * Internal helper that adds a shape not yet mapped by this object.
1167 * Notes:
1168 * 1. getter and setter must be normalized based on flags (see jsscope.cpp).
1169 * 2. !isExtensible() checking must be done by callers.
1171 const js::Shape *addPropertyInternal(JSContext *cx, jsid id,
1172 js::PropertyOp getter, js::StrictPropertyOp setter,
1173 uint32 slot, uintN attrs,
1174 uintN flags, intN shortid,
1175 js::Shape **spp);
1177 bool toDictionaryMode(JSContext *cx);
1179 public:
1180 /* Add a property whose id is not yet in this scope. */
1181 const js::Shape *addProperty(JSContext *cx, jsid id,
1182 js::PropertyOp getter, js::StrictPropertyOp setter,
1183 uint32 slot, uintN attrs,
1184 uintN flags, intN shortid);
1186 /* Add a data property whose id is not yet in this scope. */
1187 const js::Shape *addDataProperty(JSContext *cx, jsid id, uint32 slot, uintN attrs) {
1188 JS_ASSERT(!(attrs & (JSPROP_GETTER | JSPROP_SETTER)));
1189 return addProperty(cx, id, NULL, NULL, slot, attrs, 0, 0);
1192 /* Add or overwrite a property for id in this scope. */
1193 const js::Shape *putProperty(JSContext *cx, jsid id,
1194 js::PropertyOp getter, js::StrictPropertyOp setter,
1195 uint32 slot, uintN attrs,
1196 uintN flags, intN shortid);
1198 /* Change the given property into a sibling with the same id in this scope. */
1199 const js::Shape *changeProperty(JSContext *cx, const js::Shape *shape, uintN attrs, uintN mask,
1200 js::PropertyOp getter, js::StrictPropertyOp setter);
1202 /* Remove the property named by id from this object. */
1203 bool removeProperty(JSContext *cx, jsid id);
1205 /* Clear the scope, making it empty. */
1206 void clear(JSContext *cx);
1208 JSBool lookupProperty(JSContext *cx, jsid id, JSObject **objp, JSProperty **propp) {
1209 js::LookupPropOp op = getOps()->lookupProperty;
1210 return (op ? op : js_LookupProperty)(cx, this, id, objp, propp);
1213 JSBool defineProperty(JSContext *cx, jsid id, const js::Value &value,
1214 js::PropertyOp getter = js::PropertyStub,
1215 js::StrictPropertyOp setter = js::StrictPropertyStub,
1216 uintN attrs = JSPROP_ENUMERATE) {
1217 js::DefinePropOp op = getOps()->defineProperty;
1218 return (op ? op : js_DefineProperty)(cx, this, id, &value, getter, setter, attrs);
1221 JSBool getProperty(JSContext *cx, JSObject *receiver, jsid id, js::Value *vp) {
1222 js::PropertyIdOp op = getOps()->getProperty;
1223 return (op ? op : (js::PropertyIdOp)js_GetProperty)(cx, this, receiver, id, vp);
1226 JSBool getProperty(JSContext *cx, jsid id, js::Value *vp) {
1227 return getProperty(cx, this, id, vp);
1230 JSBool setProperty(JSContext *cx, jsid id, js::Value *vp, JSBool strict) {
1231 js::StrictPropertyIdOp op = getOps()->setProperty;
1232 return (op ? op : js_SetProperty)(cx, this, id, vp, strict);
1235 JSBool getAttributes(JSContext *cx, jsid id, uintN *attrsp) {
1236 js::AttributesOp op = getOps()->getAttributes;
1237 return (op ? op : js_GetAttributes)(cx, this, id, attrsp);
1240 JSBool setAttributes(JSContext *cx, jsid id, uintN *attrsp) {
1241 js::AttributesOp op = getOps()->setAttributes;
1242 return (op ? op : js_SetAttributes)(cx, this, id, attrsp);
1245 JSBool deleteProperty(JSContext *cx, jsid id, js::Value *rval, JSBool strict) {
1246 js::DeleteIdOp op = getOps()->deleteProperty;
1247 return (op ? op : js_DeleteProperty)(cx, this, id, rval, strict);
1250 JSBool enumerate(JSContext *cx, JSIterateOp iterop, js::Value *statep, jsid *idp) {
1251 js::NewEnumerateOp op = getOps()->enumerate;
1252 return (op ? op : js_Enumerate)(cx, this, iterop, statep, idp);
1255 JSType typeOf(JSContext *cx) {
1256 js::TypeOfOp op = getOps()->typeOf;
1257 return (op ? op : js_TypeOf)(cx, this);
1260 /* These four are time-optimized to avoid stub calls. */
1261 JSObject *thisObject(JSContext *cx) {
1262 JSObjectOp op = getOps()->thisObject;
1263 return op ? op(cx, this) : this;
1266 static bool thisObject(JSContext *cx, const js::Value &v, js::Value *vp);
1268 inline JSCompartment *getCompartment() const;
1270 inline JSObject *getThrowTypeError() const;
1272 JS_FRIEND_API(JSObject *) clone(JSContext *cx, JSObject *proto, JSObject *parent);
1273 JS_FRIEND_API(bool) copyPropertiesFrom(JSContext *cx, JSObject *obj);
1274 bool swap(JSContext *cx, JSObject *other);
1276 const js::Shape *defineBlockVariable(JSContext *cx, jsid id, intN index);
1278 inline bool canHaveMethodBarrier() const;
1280 inline bool isArguments() const;
1281 inline bool isNormalArguments() const;
1282 inline bool isStrictArguments() const;
1283 inline bool isArray() const;
1284 inline bool isDenseArray() const;
1285 inline bool isSlowArray() const;
1286 inline bool isNumber() const;
1287 inline bool isBoolean() const;
1288 inline bool isString() const;
1289 inline bool isPrimitive() const;
1290 inline bool isDate() const;
1291 inline bool isFunction() const;
1292 inline bool isObject() const;
1293 inline bool isWith() const;
1294 inline bool isBlock() const;
1295 inline bool isStaticBlock() const;
1296 inline bool isClonedBlock() const;
1297 inline bool isCall() const;
1298 inline bool isRegExp() const;
1299 inline bool isXML() const;
1300 inline bool isXMLId() const;
1301 inline bool isNamespace() const;
1302 inline bool isQName() const;
1304 inline bool isProxy() const;
1305 inline bool isObjectProxy() const;
1306 inline bool isFunctionProxy() const;
1308 JS_FRIEND_API(bool) isWrapper() const;
1309 JS_FRIEND_API(JSObject *) unwrap(uintN *flagsp = NULL);
1311 inline void initArrayClass();
1314 /* Check alignment for any fixed slots allocated after the object. */
1315 JS_STATIC_ASSERT(sizeof(JSObject) % sizeof(js::Value) == 0);
1317 inline js::Value*
1318 JSObject::fixedSlots() const {
1319 return (js::Value*) (jsuword(this) + sizeof(JSObject));
1322 inline bool
1323 JSObject::hasSlotsArray() const { return this->slots != fixedSlots(); }
1325 /* static */ inline size_t
1326 JSObject::getFixedSlotOffset(size_t slot) {
1327 return sizeof(JSObject) + (slot * sizeof(js::Value));
1330 struct JSObject_Slots2 : JSObject { js::Value fslots[2]; };
1331 struct JSObject_Slots4 : JSObject { js::Value fslots[4]; };
1332 struct JSObject_Slots8 : JSObject { js::Value fslots[8]; };
1333 struct JSObject_Slots12 : JSObject { js::Value fslots[12]; };
1334 struct JSObject_Slots16 : JSObject { js::Value fslots[16]; };
1336 #define JSSLOT_FREE(clasp) JSCLASS_RESERVED_SLOTS(clasp)
1338 #ifdef JS_THREADSAFE
1341 * The GC runs only when all threads except the one on which the GC is active
1342 * are suspended at GC-safe points, so calling obj->getSlot() from the GC's
1343 * thread is safe when rt->gcRunning is set. See jsgc.cpp for details.
1345 #define THREAD_IS_RUNNING_GC(rt, thread) \
1346 ((rt)->gcRunning && (rt)->gcThread == (thread))
1348 #define CX_THREAD_IS_RUNNING_GC(cx) \
1349 THREAD_IS_RUNNING_GC((cx)->runtime, (cx)->thread)
1351 #endif /* JS_THREADSAFE */
1353 inline void
1354 OBJ_TO_INNER_OBJECT(JSContext *cx, JSObject *&obj)
1356 if (JSObjectOp op = obj->getClass()->ext.innerObject)
1357 obj = op(cx, obj);
1360 inline void
1361 OBJ_TO_OUTER_OBJECT(JSContext *cx, JSObject *&obj)
1363 if (JSObjectOp op = obj->getClass()->ext.outerObject)
1364 obj = op(cx, obj);
1367 class JSValueArray {
1368 public:
1369 jsval *array;
1370 size_t length;
1372 JSValueArray(jsval *v, size_t c) : array(v), length(c) {}
1375 class ValueArray {
1376 public:
1377 js::Value *array;
1378 size_t length;
1380 ValueArray(js::Value *v, size_t c) : array(v), length(c) {}
1383 extern js::Class js_ObjectClass;
1384 extern js::Class js_WithClass;
1385 extern js::Class js_BlockClass;
1387 inline bool JSObject::isObject() const { return getClass() == &js_ObjectClass; }
1388 inline bool JSObject::isWith() const { return getClass() == &js_WithClass; }
1389 inline bool JSObject::isBlock() const { return getClass() == &js_BlockClass; }
1392 * Block scope object macros. The slots reserved by js_BlockClass are:
1394 * private JSStackFrame * active frame pointer or null
1395 * JSSLOT_BLOCK_DEPTH int depth of block slots in frame
1397 * After JSSLOT_BLOCK_DEPTH come one or more slots for the block locals.
1399 * A With object is like a Block object, in that both have one reserved slot
1400 * telling the stack depth of the relevant slots (the slot whose value is the
1401 * object named in the with statement, the slots containing the block's local
1402 * variables); and both have a private slot referring to the JSStackFrame in
1403 * whose activation they were created (or null if the with or block object
1404 * outlives the frame).
1406 static const uint32 JSSLOT_BLOCK_DEPTH = 0;
1407 static const uint32 JSSLOT_BLOCK_FIRST_FREE_SLOT = JSSLOT_BLOCK_DEPTH + 1;
1409 inline bool
1410 JSObject::isStaticBlock() const
1412 return isBlock() && !getProto();
1415 inline bool
1416 JSObject::isClonedBlock() const
1418 return isBlock() && !!getProto();
1421 static const uint32 JSSLOT_WITH_THIS = 1;
1423 #define OBJ_BLOCK_COUNT(cx,obj) \
1424 (obj)->propertyCount()
1425 #define OBJ_BLOCK_DEPTH(cx,obj) \
1426 (obj)->getSlot(JSSLOT_BLOCK_DEPTH).toInt32()
1427 #define OBJ_SET_BLOCK_DEPTH(cx,obj,depth) \
1428 (obj)->setSlot(JSSLOT_BLOCK_DEPTH, Value(Int32Value(depth)))
1431 * To make sure this slot is well-defined, always call js_NewWithObject to
1432 * create a With object, don't call js_NewObject directly. When creating a
1433 * With object that does not correspond to a stack slot, pass -1 for depth.
1435 * When popping the stack across this object's "with" statement, client code
1436 * must call withobj->setPrivate(NULL).
1438 extern JS_REQUIRES_STACK JSObject *
1439 js_NewWithObject(JSContext *cx, JSObject *proto, JSObject *parent, jsint depth);
1441 inline JSObject *
1442 js_UnwrapWithObject(JSContext *cx, JSObject *withobj)
1444 JS_ASSERT(withobj->getClass() == &js_WithClass);
1445 return withobj->getProto();
1449 * Create a new block scope object not linked to any proto or parent object.
1450 * Blocks are created by the compiler to reify let blocks and comprehensions.
1451 * Only when dynamic scope is captured do they need to be cloned and spliced
1452 * into an active scope chain.
1454 extern JSObject *
1455 js_NewBlockObject(JSContext *cx);
1457 extern JSObject *
1458 js_CloneBlockObject(JSContext *cx, JSObject *proto, JSStackFrame *fp);
1460 extern JS_REQUIRES_STACK JSBool
1461 js_PutBlockObject(JSContext *cx, JSBool normalUnwind);
1463 JSBool
1464 js_XDRBlockObject(JSXDRState *xdr, JSObject **objp);
1466 struct JSSharpObjectMap {
1467 jsrefcount depth;
1468 jsatomid sharpgen;
1469 JSHashTable *table;
1472 #define SHARP_BIT ((jsatomid) 1)
1473 #define BUSY_BIT ((jsatomid) 2)
1474 #define SHARP_ID_SHIFT 2
1475 #define IS_SHARP(he) (uintptr_t((he)->value) & SHARP_BIT)
1476 #define MAKE_SHARP(he) ((he)->value = (void *) (uintptr_t((he)->value)|SHARP_BIT))
1477 #define IS_BUSY(he) (uintptr_t((he)->value) & BUSY_BIT)
1478 #define MAKE_BUSY(he) ((he)->value = (void *) (uintptr_t((he)->value)|BUSY_BIT))
1479 #define CLEAR_BUSY(he) ((he)->value = (void *) (uintptr_t((he)->value)&~BUSY_BIT))
1481 extern JSHashEntry *
1482 js_EnterSharpObject(JSContext *cx, JSObject *obj, JSIdArray **idap,
1483 jschar **sp);
1485 extern void
1486 js_LeaveSharpObject(JSContext *cx, JSIdArray **idap);
1489 * Mark objects stored in map if GC happens between js_EnterSharpObject
1490 * and js_LeaveSharpObject. GC calls this when map->depth > 0.
1492 extern void
1493 js_TraceSharpMap(JSTracer *trc, JSSharpObjectMap *map);
1495 extern JSBool
1496 js_HasOwnPropertyHelper(JSContext *cx, js::LookupPropOp lookup, uintN argc,
1497 js::Value *vp);
1499 extern JSBool
1500 js_HasOwnProperty(JSContext *cx, js::LookupPropOp lookup, JSObject *obj, jsid id,
1501 JSObject **objp, JSProperty **propp);
1503 extern JSBool
1504 js_NewPropertyDescriptorObject(JSContext *cx, jsid id, uintN attrs,
1505 const js::Value &getter, const js::Value &setter,
1506 const js::Value &value, js::Value *vp);
1508 extern JSBool
1509 js_PropertyIsEnumerable(JSContext *cx, JSObject *obj, jsid id, js::Value *vp);
1511 #ifdef OLD_GETTER_SETTER_METHODS
1512 JS_FRIEND_API(JSBool) js_obj_defineGetter(JSContext *cx, uintN argc, js::Value *vp);
1513 JS_FRIEND_API(JSBool) js_obj_defineSetter(JSContext *cx, uintN argc, js::Value *vp);
1514 #endif
1516 extern JSObject *
1517 js_InitObjectClass(JSContext *cx, JSObject *obj);
1519 namespace js {
1520 JSObject *
1521 DefineConstructorAndPrototype(JSContext *cx, JSObject *obj, JSProtoKey key, JSAtom *atom,
1522 JSObject *protoProto, Class *clasp,
1523 Native constructor, uintN nargs,
1524 JSPropertySpec *ps, JSFunctionSpec *fs,
1525 JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
1528 extern JSObject *
1529 js_InitClass(JSContext *cx, JSObject *obj, JSObject *parent_proto,
1530 js::Class *clasp, js::Native constructor, uintN nargs,
1531 JSPropertySpec *ps, JSFunctionSpec *fs,
1532 JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
1535 * Select Object.prototype method names shared between jsapi.cpp and jsobj.cpp.
1537 extern const char js_watch_str[];
1538 extern const char js_unwatch_str[];
1539 extern const char js_hasOwnProperty_str[];
1540 extern const char js_isPrototypeOf_str[];
1541 extern const char js_propertyIsEnumerable_str[];
1543 #ifdef OLD_GETTER_SETTER_METHODS
1544 extern const char js_defineGetter_str[];
1545 extern const char js_defineSetter_str[];
1546 extern const char js_lookupGetter_str[];
1547 extern const char js_lookupSetter_str[];
1548 #endif
1550 extern JSBool
1551 js_PopulateObject(JSContext *cx, JSObject *newborn, JSObject *props);
1554 * Fast access to immutable standard objects (constructors and prototypes).
1556 extern JSBool
1557 js_GetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key,
1558 JSObject **objp);
1560 extern JSBool
1561 js_SetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key,
1562 JSObject *cobj, JSObject *prototype);
1565 * If protoKey is not JSProto_Null, then clasp is ignored. If protoKey is
1566 * JSProto_Null, clasp must non-null.
1568 extern JSBool
1569 js_FindClassObject(JSContext *cx, JSObject *start, JSProtoKey key,
1570 js::Value *vp, js::Class *clasp = NULL);
1572 extern JSObject *
1573 js_ConstructObject(JSContext *cx, js::Class *clasp, JSObject *proto,
1574 JSObject *parent, uintN argc, js::Value *argv);
1576 // Specialized call for constructing |this| with a known function callee,
1577 // and a known prototype.
1578 extern JSObject *
1579 js_CreateThisForFunctionWithProto(JSContext *cx, JSObject *callee, JSObject *proto);
1581 // Specialized call for constructing |this| with a known function callee.
1582 extern JSObject *
1583 js_CreateThisForFunction(JSContext *cx, JSObject *callee);
1585 // Generic call for constructing |this|.
1586 extern JSObject *
1587 js_CreateThis(JSContext *cx, JSObject *callee);
1589 extern jsid
1590 js_CheckForStringIndex(jsid id);
1593 * js_PurgeScopeChain does nothing if obj is not itself a prototype or parent
1594 * scope, else it reshapes the scope and prototype chains it links. It calls
1595 * js_PurgeScopeChainHelper, which asserts that obj is flagged as a delegate
1596 * (i.e., obj has ever been on a prototype or parent chain).
1598 extern void
1599 js_PurgeScopeChainHelper(JSContext *cx, JSObject *obj, jsid id);
1601 inline void
1602 js_PurgeScopeChain(JSContext *cx, JSObject *obj, jsid id)
1604 if (obj->isDelegate())
1605 js_PurgeScopeChainHelper(cx, obj, id);
1609 * Find or create a property named by id in obj's scope, with the given getter
1610 * and setter, slot, attributes, and other members.
1612 extern const js::Shape *
1613 js_AddNativeProperty(JSContext *cx, JSObject *obj, jsid id,
1614 js::PropertyOp getter, js::StrictPropertyOp setter, uint32 slot,
1615 uintN attrs, uintN flags, intN shortid);
1618 * Change shape to have the given attrs, getter, and setter in scope, morphing
1619 * it into a potentially new js::Shape. Return a pointer to the changed
1620 * or identical property.
1622 extern const js::Shape *
1623 js_ChangeNativePropertyAttrs(JSContext *cx, JSObject *obj,
1624 const js::Shape *shape, uintN attrs, uintN mask,
1625 js::PropertyOp getter, js::StrictPropertyOp setter);
1627 extern JSBool
1628 js_DefineOwnProperty(JSContext *cx, JSObject *obj, jsid id,
1629 const js::Value &descriptor, JSBool *bp);
1632 * Flags for the defineHow parameter of js_DefineNativeProperty.
1634 const uintN JSDNP_CACHE_RESULT = 1; /* an interpreter call from JSOP_INITPROP */
1635 const uintN JSDNP_DONT_PURGE = 2; /* suppress js_PurgeScopeChain */
1636 const uintN JSDNP_SET_METHOD = 4; /* js_{DefineNativeProperty,SetPropertyHelper}
1637 must pass the js::Shape::METHOD
1638 flag on to JSObject::{add,put}Property */
1639 const uintN JSDNP_UNQUALIFIED = 8; /* Unqualified property set. Only used in
1640 the defineHow argument of
1641 js_SetPropertyHelper. */
1644 * On error, return false. On success, if propp is non-null, return true with
1645 * obj locked and with a held property in *propp; if propp is null, return true
1646 * but release obj's lock first.
1648 extern JSBool
1649 js_DefineNativeProperty(JSContext *cx, JSObject *obj, jsid id, const js::Value &value,
1650 js::PropertyOp getter, js::StrictPropertyOp setter, uintN attrs,
1651 uintN flags, intN shortid, JSProperty **propp,
1652 uintN defineHow = 0);
1655 * Specialized subroutine that allows caller to preset JSRESOLVE_* flags and
1656 * returns the index along the prototype chain in which *propp was found, or
1657 * the last index if not found, or -1 on error.
1659 extern int
1660 js_LookupPropertyWithFlags(JSContext *cx, JSObject *obj, jsid id, uintN flags,
1661 JSObject **objp, JSProperty **propp);
1665 * We cache name lookup results only for the global object or for native
1666 * non-global objects without prototype or with prototype that never mutates,
1667 * see bug 462734 and bug 487039.
1669 inline bool
1670 js_IsCacheableNonGlobalScope(JSObject *obj)
1672 extern JS_FRIEND_DATA(js::Class) js_CallClass;
1673 extern JS_FRIEND_DATA(js::Class) js_DeclEnvClass;
1674 JS_ASSERT(obj->getParent());
1676 js::Class *clasp = obj->getClass();
1677 bool cacheable = (clasp == &js_CallClass ||
1678 clasp == &js_BlockClass ||
1679 clasp == &js_DeclEnvClass);
1681 JS_ASSERT_IF(cacheable, !obj->getOps()->lookupProperty);
1682 return cacheable;
1686 * If cacheResult is false, return JS_NO_PROP_CACHE_FILL on success.
1688 extern js::PropertyCacheEntry *
1689 js_FindPropertyHelper(JSContext *cx, jsid id, JSBool cacheResult,
1690 JSObject **objp, JSObject **pobjp, JSProperty **propp);
1693 * Return the index along the scope chain in which id was found, or the last
1694 * index if not found, or -1 on error.
1696 extern JS_FRIEND_API(JSBool)
1697 js_FindProperty(JSContext *cx, jsid id, JSObject **objp, JSObject **pobjp,
1698 JSProperty **propp);
1700 extern JS_REQUIRES_STACK JSObject *
1701 js_FindIdentifierBase(JSContext *cx, JSObject *scopeChain, jsid id);
1703 extern JSObject *
1704 js_FindVariableScope(JSContext *cx, JSFunction **funp);
1707 * JSGET_CACHE_RESULT is the analogue of JSDNP_CACHE_RESULT for js_GetMethod.
1709 * JSGET_METHOD_BARRIER (the default, hence 0 but provided for documentation)
1710 * enables a read barrier that preserves standard function object semantics (by
1711 * default we assume our caller won't leak a joined callee to script, where it
1712 * would create hazardous mutable object sharing as well as observable identity
1713 * according to == and ===.
1715 * JSGET_NO_METHOD_BARRIER avoids the performance overhead of the method read
1716 * barrier, which is not needed when invoking a lambda that otherwise does not
1717 * leak its callee reference (via arguments.callee or its name).
1719 const uintN JSGET_CACHE_RESULT = 1; // from a caching interpreter opcode
1720 const uintN JSGET_METHOD_BARRIER = 0; // get can leak joined function object
1721 const uintN JSGET_NO_METHOD_BARRIER = 2; // call to joined function can't leak
1724 * NB: js_NativeGet and js_NativeSet are called with the scope containing shape
1725 * (pobj's scope for Get, obj's for Set) locked, and on successful return, that
1726 * scope is again locked. But on failure, both functions return false with the
1727 * scope containing shape unlocked.
1729 extern JSBool
1730 js_NativeGet(JSContext *cx, JSObject *obj, JSObject *pobj, const js::Shape *shape, uintN getHow,
1731 js::Value *vp);
1733 extern JSBool
1734 js_NativeSet(JSContext *cx, JSObject *obj, const js::Shape *shape, bool added,
1735 bool strict, js::Value *vp);
1737 extern JSBool
1738 js_GetPropertyHelper(JSContext *cx, JSObject *obj, jsid id, uint32 getHow, js::Value *vp);
1740 extern bool
1741 js_GetPropertyHelperWithShape(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id,
1742 uint32 getHow, js::Value *vp,
1743 const js::Shape **shapeOut, JSObject **holderOut);
1745 extern JSBool
1746 js_GetOwnPropertyDescriptor(JSContext *cx, JSObject *obj, jsid id, js::Value *vp);
1748 extern JSBool
1749 js_GetMethod(JSContext *cx, JSObject *obj, jsid id, uintN getHow, js::Value *vp);
1752 * Check whether it is OK to assign an undeclared property with name
1753 * propname of the global object in the current script on cx. Reports
1754 * an error if one needs to be reported (in particular in all cases
1755 * when it returns false).
1757 extern JS_FRIEND_API(bool)
1758 js_CheckUndeclaredVarAssignment(JSContext *cx, JSString *propname);
1760 extern JSBool
1761 js_SetPropertyHelper(JSContext *cx, JSObject *obj, jsid id, uintN defineHow,
1762 js::Value *vp, JSBool strict);
1765 * Change attributes for the given native property. The caller must ensure
1766 * that obj is locked and this function always unlocks obj on return.
1768 extern JSBool
1769 js_SetNativeAttributes(JSContext *cx, JSObject *obj, js::Shape *shape,
1770 uintN attrs);
1772 namespace js {
1775 * If obj has a data property methodid which is a function object for the given
1776 * native, return that function object. Otherwise, return NULL.
1778 extern JSObject *
1779 HasNativeMethod(JSObject *obj, jsid methodid, Native native);
1781 extern bool
1782 DefaultValue(JSContext *cx, JSObject *obj, JSType hint, Value *vp);
1784 extern JSBool
1785 CheckAccess(JSContext *cx, JSObject *obj, jsid id, JSAccessMode mode,
1786 js::Value *vp, uintN *attrsp);
1788 } /* namespace js */
1790 extern bool
1791 js_IsDelegate(JSContext *cx, JSObject *obj, const js::Value &v);
1794 * If protoKey is not JSProto_Null, then clasp is ignored. If protoKey is
1795 * JSProto_Null, clasp must non-null.
1797 extern JS_FRIEND_API(JSBool)
1798 js_GetClassPrototype(JSContext *cx, JSObject *scope, JSProtoKey protoKey,
1799 JSObject **protop, js::Class *clasp = NULL);
1801 extern JSBool
1802 js_SetClassPrototype(JSContext *cx, JSObject *ctor, JSObject *proto,
1803 uintN attrs);
1806 * Wrap boolean, number or string as Boolean, Number or String object.
1807 * *vp must not be an object, null or undefined.
1809 extern JSBool
1810 js_PrimitiveToObject(JSContext *cx, js::Value *vp);
1813 * v and vp may alias. On successful return, vp->isObjectOrNull(). If vp is not
1814 * rooted, the caller must root vp before the next possible GC.
1816 extern JSBool
1817 js_ValueToObjectOrNull(JSContext *cx, const js::Value &v, JSObject **objp);
1819 namespace js {
1822 * Invokes the ES5 ToObject algorithm on *vp, writing back the object to vp.
1823 * If *vp might already be an object, use ToObject.
1825 extern JSObject *
1826 ToObjectSlow(JSContext *cx, js::Value *vp);
1828 JS_ALWAYS_INLINE JSObject *
1829 ToObject(JSContext *cx, js::Value *vp)
1831 if (vp->isObject())
1832 return &vp->toObject();
1833 return ToObjectSlow(cx, vp);
1839 * v and vp may alias. On successful return, vp->isObject(). If vp is not
1840 * rooted, the caller must root vp before the next possible GC.
1842 extern JSObject *
1843 js_ValueToNonNullObject(JSContext *cx, const js::Value &v);
1845 extern JSBool
1846 js_TryValueOf(JSContext *cx, JSObject *obj, JSType type, js::Value *rval);
1848 extern JSBool
1849 js_TryMethod(JSContext *cx, JSObject *obj, JSAtom *atom,
1850 uintN argc, js::Value *argv, js::Value *rval);
1852 extern JSBool
1853 js_XDRObject(JSXDRState *xdr, JSObject **objp);
1855 extern void
1856 js_TraceObject(JSTracer *trc, JSObject *obj);
1858 extern void
1859 js_PrintObjectSlotName(JSTracer *trc, char *buf, size_t bufsize);
1861 extern void
1862 js_ClearNative(JSContext *cx, JSObject *obj);
1864 extern bool
1865 js_GetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, js::Value *vp);
1867 extern bool
1868 js_SetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, const js::Value &v);
1870 extern JSBool
1871 js_CheckPrincipalsAccess(JSContext *cx, JSObject *scopeobj,
1872 JSPrincipals *principals, JSAtom *caller);
1874 /* For CSP -- checks if eval() and friends are allowed to run. */
1875 extern JSBool
1876 js_CheckContentSecurityPolicy(JSContext *cx, JSObject *scopeObj);
1878 /* NB: Infallible. */
1879 extern const char *
1880 js_ComputeFilename(JSContext *cx, JSStackFrame *caller,
1881 JSPrincipals *principals, uintN *linenop);
1883 extern JSBool
1884 js_ReportGetterOnlyAssignment(JSContext *cx);
1886 extern JS_FRIEND_API(JSBool)
1887 js_GetterOnlyPropertyStub(JSContext *cx, JSObject *obj, jsid id, JSBool strict, jsval *vp);
1889 #ifdef DEBUG
1890 JS_FRIEND_API(void) js_DumpChars(const jschar *s, size_t n);
1891 JS_FRIEND_API(void) js_DumpString(JSString *str);
1892 JS_FRIEND_API(void) js_DumpAtom(JSAtom *atom);
1893 JS_FRIEND_API(void) js_DumpObject(JSObject *obj);
1894 JS_FRIEND_API(void) js_DumpValue(const js::Value &val);
1895 JS_FRIEND_API(void) js_DumpId(jsid id);
1896 JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, JSStackFrame *start = NULL);
1897 #endif
1899 extern uintN
1900 js_InferFlags(JSContext *cx, uintN defaultFlags);
1902 /* Object constructor native. Exposed only so the JIT can know its address. */
1903 JSBool
1904 js_Object(JSContext *cx, uintN argc, js::Value *vp);
1907 namespace js {
1909 extern bool
1910 SetProto(JSContext *cx, JSObject *obj, JSObject *proto, bool checkForCycles);
1912 extern JSString *
1913 obj_toStringHelper(JSContext *cx, JSObject *obj);
1915 enum EvalType { INDIRECT_EVAL, DIRECT_EVAL };
1918 * Common code implementing direct and indirect eval.
1920 * Evaluate vp[2], if it is a string, in the context of the given calling
1921 * frame, with the provided scope chain, with the semantics of either a direct
1922 * or indirect eval (see ES5 10.4.2). If this is an indirect eval, scopeobj
1923 * must be a global object.
1925 * On success, store the completion value in *vp and return true.
1927 extern bool
1928 EvalKernel(JSContext *cx, uintN argc, js::Value *vp, EvalType evalType, JSStackFrame *caller,
1929 JSObject *scopeobj);
1931 extern JS_FRIEND_API(bool)
1932 IsBuiltinEvalFunction(JSFunction *fun);
1936 #ifdef JS_OBJ_UNDEFD_MOZALLOC_WRAPPERS
1937 # include "mozilla/mozalloc_macro_wrappers.h"
1938 #endif
1940 #endif /* jsobj_h___ */