Debian Codegraph @

rhino/src/org/mozilla/javascript/ScriptableObject.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // API class
8
9 package org.mozilla.javascript;
10
11 import java.io.IOException;
12 import java.io.ObjectInputStream;
13 import java.io.ObjectOutputStream;
14 import java.io.Serializable;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.AccessibleObject;
17 import java.lang.reflect.Constructor;
18 import java.lang.reflect.InvocationTargetException;
19 import java.lang.reflect.Member;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Modifier;
22 import java.util.Arrays;
23 import java.util.Comparator;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Map;
27
28 import org.mozilla.javascript.debug.DebuggableObject;
29 import org.mozilla.javascript.annotations.JSConstructor;
30 import org.mozilla.javascript.annotations.JSFunction;
31 import org.mozilla.javascript.annotations.JSGetter;
32 import org.mozilla.javascript.annotations.JSSetter;
33 import org.mozilla.javascript.annotations.JSStaticFunction;
34
35 /**
36 * This is the default implementation of the Scriptable interface. This
37 * class provides convenient default behavior that makes it easier to
38 * define host objects.
39 * <p>
40 * Various properties and methods of JavaScript objects can be conveniently
41 * defined using methods of ScriptableObject.
42 * <p>
43 * Classes extending ScriptableObject must define the getClassName method.
44 *
45 * @see org.mozilla.javascript.Scriptable
46 * @author Norris Boyd
47 */
48
49 public abstract class ScriptableObject implements Scriptable,
50 SymbolScriptable,
51 Serializable,
52 DebuggableObject,
53 ConstProperties
54 {
55
56 static final long serialVersionUID = 2829861078851942586L;
57
58 /**
59 * The empty property attribute.
60 *
61 * Used by getAttributes() and setAttributes().
62 *
63 * @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
64 * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
65 */
66 public static final int EMPTY = 0x00;
67
68 /**
69 * Property attribute indicating assignment to this property is ignored.
70 *
71 * @see org.mozilla.javascript.ScriptableObject
72 * #put(String, Scriptable, Object)
73 * @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
74 * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
75 */
76 public static final int READONLY = 0x01;
77
78 /**
79 * Property attribute indicating property is not enumerated.
80 *
81 * Only enumerated properties will be returned by getIds().
82 *
83 * @see org.mozilla.javascript.ScriptableObject#getIds()
84 * @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
85 * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
86 */
87 public static final int DONTENUM = 0x02;
88
89 /**
90 * Property attribute indicating property cannot be deleted.
91 *
92 * @see org.mozilla.javascript.ScriptableObject#delete(String)
93 * @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
94 * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
95 */
96 public static final int PERMANENT = 0x04;
97
98 /**
99 * Property attribute indicating that this is a const property that has not
100 * been assigned yet. The first 'const' assignment to the property will
101 * clear this bit.
102 */
103 public static final int UNINITIALIZED_CONST = 0x08;
104
105 public static final int CONST = PERMANENT|READONLY|UNINITIALIZED_CONST;
106 /**
107 * The prototype of this object.
108 */
109 private Scriptable prototypeObject;
110
111 /**
112 * The parent scope of this object.
113 */
114 private Scriptable parentScopeObject;
115
116 private transient Slot[] slots;
117 // If count >= 0, it gives number of keys or if count < 0,
118 // it indicates sealed object where ~count gives number of keys
119 private int count;
120
121 // Where external array data is stored.
122 private transient ExternalArrayData externalData;
123
124 // gateways into the definition-order linked list of slots
125 private transient Slot firstAdded;
126 private transient Slot lastAdded;
127
128
129 private volatile Map<Object,Object> associatedValues;
130
131 private static final int SLOT_QUERY = 1;
132 private static final int SLOT_MODIFY = 2;
133 private static final int SLOT_MODIFY_CONST = 3;
134 private static final int SLOT_MODIFY_GETTER_SETTER = 4;
135 private static final int SLOT_CONVERT_ACCESSOR_TO_DATA = 5;
136
137 // initial slot array size, must be a power of 2
138 private static final int INITIAL_SLOT_SIZE = 4;
139
140 private boolean isExtensible = true;
141
142 private static final Method GET_ARRAY_LENGTH;
143
144 static {
145 try {
146 GET_ARRAY_LENGTH = ScriptableObject.class.getMethod("getExternalArrayLength");
147 } catch (NoSuchMethodException nsm) {
148 throw new RuntimeException(nsm);
149 }
150 }
151
152 private static class Slot implements Serializable
153 {
154 private static final long serialVersionUID = -6090581677123995491L;
155 Object name; // This can change due to caching
156 int indexOrHash;
157 private volatile short attributes;
158 transient volatile boolean wasDeleted;
159 volatile Object value;
160 transient Slot next; // next in hash table bucket
161 transient volatile Slot orderedNext; // next in linked list
162
163 Slot(Object name, int indexOrHash, int attributes)
164 {
165 this.name = name;
166 this.indexOrHash = indexOrHash;
167 this.attributes = (short)attributes;
168 }
169
170 private void readObject(ObjectInputStream in)
171 throws IOException, ClassNotFoundException
172 {
173 in.defaultReadObject();
174 if (name != null) {
175 indexOrHash = name.hashCode();
176 }
177 }
178
179 boolean setValue(Object value, Scriptable owner, Scriptable start) {
180 if ((attributes & READONLY) != 0) {
181 Context cx = Context.getContext();
182 if (cx.isStrictMode()) {
183 throw ScriptRuntime.typeError1("msg.modify.readonly", name);
184 }
185 return true;
186 }
187 if (owner == start) {
188 this.value = value;
189 return true;
190 } else {
191 return false;
192 }
193 }
194
195 Object getValue(Scriptable start) {
196 return value;
197 }
198
199 int getAttributes()
200 {
201 return attributes;
202 }
203
204 synchronized void setAttributes(int value)
205 {
206 checkValidAttributes(value);
207 attributes = (short)value;
208 }
209
210 void markDeleted() {
211 wasDeleted = true;
212 value = null;
213 name = null;
214 }
215
216 ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
217 return buildDataDescriptor(scope, value, attributes);
218 }
219
220 }
221
222 protected static ScriptableObject buildDataDescriptor(Scriptable scope,
223 Object value,
224 int attributes) {
225 ScriptableObject desc = new NativeObject();
226 ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object);
227 desc.defineProperty("value", value, EMPTY);
228 desc.defineProperty("writable", (attributes & READONLY) == 0, EMPTY);
229 desc.defineProperty("enumerable", (attributes & DONTENUM) == 0, EMPTY);
230 desc.defineProperty("configurable", (attributes & PERMANENT) == 0, EMPTY);
231 return desc;
232 }
233
234 private static final class GetterSlot extends Slot
235 {
236 static final long serialVersionUID = -4900574849788797588L;
237
238 Object getter;
239 Object setter;
240
241 GetterSlot(Object name, int indexOrHash, int attributes)
242 {
243 super(name, indexOrHash, attributes);
244 }
245
246 @Override
247 ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
248 int attr = getAttributes();
249 ScriptableObject desc = new NativeObject();
250 ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object);
251 desc.defineProperty("enumerable", (attr & DONTENUM) == 0, EMPTY);
252 desc.defineProperty("configurable", (attr & PERMANENT) == 0, EMPTY);
253 if (getter == null && setter == null) {
254 desc.defineProperty("writable", (attr & READONLY) == 0, EMPTY);
255 }
256 if (getter != null) desc.defineProperty("get", getter, EMPTY);
257 if (setter != null) desc.defineProperty("set", setter, EMPTY);
258 return desc;
259 }
260
261 @Override
262 boolean setValue(Object value, Scriptable owner, Scriptable start) {
263 if (setter == null) {
264 if (getter != null) {
265 Context cx = Context.getContext();
266 if (cx.isStrictMode() ||
267 // Based on TC39 ES3.1 Draft of 9-Feb-2009, 8.12.4, step 2,
268 // we should throw a TypeError in this case.
269 cx.hasFeature(Context.FEATURE_STRICT_MODE)) {
270 throw ScriptRuntime.typeError1("msg.set.prop.no.setter", name);
271 }
272 // Assignment to a property with only a getter defined. The
273 // assignment is ignored. See bug 478047.
274 return true;
275 }
276 } else {
277 Context cx = Context.getContext();
278 if (setter instanceof MemberBox) {
279 MemberBox nativeSetter = (MemberBox)setter;
280 Class<?> pTypes[] = nativeSetter.argTypes;
281 // XXX: cache tag since it is already calculated in
282 // defineProperty ?
283 Class<?> valueType = pTypes[pTypes.length - 1];
284 int tag = FunctionObject.getTypeTag(valueType);
285 Object actualArg = FunctionObject.convertArg(cx, start,
286 value, tag);
287 Object setterThis;
288 Object[] args;
289 if (nativeSetter.delegateTo == null) {
290 setterThis = start;
291 args = new Object[] { actualArg };
292 } else {
293 setterThis = nativeSetter.delegateTo;
294 args = new Object[] { start, actualArg };
295 }
296 nativeSetter.invoke(setterThis, args);
297 } else if (setter instanceof Function) {
298 Function f = (Function)setter;
299 f.call(cx, f.getParentScope(), start,
300 new Object[] { value });
301 }
302 return true;
303 }
304 return super.setValue(value, owner, start);
305 }
306
307 @Override
308 Object getValue(Scriptable start) {
309 if (getter != null) {
310 if (getter instanceof MemberBox) {
311 MemberBox nativeGetter = (MemberBox)getter;
312 Object getterThis;
313 Object[] args;
314 if (nativeGetter.delegateTo == null) {
315 getterThis = start;
316 args = ScriptRuntime.emptyArgs;
317 } else {
318 getterThis = nativeGetter.delegateTo;
319 args = new Object[] { start };
320 }
321 return nativeGetter.invoke(getterThis, args);
322 } else if (getter instanceof Function) {
323 Function f = (Function)getter;
324 Context cx = Context.getContext();
325 return f.call(cx, f.getParentScope(), start,
326 ScriptRuntime.emptyArgs);
327 }
328 }
329 Object val = this.value;
330 if (val instanceof LazilyLoadedCtor) {
331 LazilyLoadedCtor initializer = (LazilyLoadedCtor)val;
332 try {
333 initializer.init();
334 } finally {
335 this.value = val = initializer.getValue();
336 }
337 }
338 return val;
339 }
340
341 @Override
342 void markDeleted() {
343 super.markDeleted();
344 getter = null;
345 setter = null;
346 }
347 }
348
349 /**
350 * A wrapper around a slot that allows the slot to be used in a new slot
351 * table while keeping it functioning in its old slot table/linked list
352 * context. This is used when linked slots are copied to a new slot table.
353 * In a multi-threaded environment, these slots may still be accessed
354 * through their old slot table. See bug 688458.
355 */
356 private static class RelinkedSlot extends Slot {
357
358 final Slot slot;
359
360 RelinkedSlot(Slot slot) {
361 super(slot.name, slot.indexOrHash, slot.attributes);
362 // Make sure we always wrap the actual slot, not another relinked one
363 this.slot = unwrapSlot(slot);
364 }
365
366 @Override
367 boolean setValue(Object value, Scriptable owner, Scriptable start) {
368 return slot.setValue(value, owner, start);
369 }
370
371 @Override
372 Object getValue(Scriptable start) {
373 return slot.getValue(start);
374 }
375
376 @Override
377 ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
378 return slot.getPropertyDescriptor(cx, scope);
379 }
380
381 @Override
382 int getAttributes() {
383 return slot.getAttributes();
384 }
385
386 @Override
387 void setAttributes(int value) {
388 slot.setAttributes(value);
389 }
390
391 @Override
392 void markDeleted() {
393 super.markDeleted();
394 slot.markDeleted();
395 }
396
397 private void writeObject(ObjectOutputStream out) throws IOException {
398 out.writeObject(slot); // just serialize the wrapped slot
399 }
400
401 }
402
403 static void checkValidAttributes(int attributes)
404 {
405 final int mask = READONLY | DONTENUM | PERMANENT | UNINITIALIZED_CONST;
406 if ((attributes & ~mask) != 0) {
407 throw new IllegalArgumentException(String.valueOf(attributes));
408 }
409 }
410
411 public ScriptableObject()
412 {
413 }
414
415 public ScriptableObject(Scriptable scope, Scriptable prototype)
416 {
417 if (scope == null)
418 throw new IllegalArgumentException();
419
420 parentScopeObject = scope;
421 prototypeObject = prototype;
422 }
423
424 /**
425 * Gets the value that will be returned by calling the typeof operator on this object.
426 * @return default is "object" unless {@link #avoidObjectDetection()} is <code>true</code> in which
427 * case it returns "undefined"
428 */
429 public String getTypeOf() {
430 return avoidObjectDetection() ? "undefined" : "object";
431 }
432
433 /**
434 * Return the name of the class.
435 *
436 * This is typically the same name as the constructor.
437 * Classes extending ScriptableObject must implement this abstract
438 * method.
439 */
440 public abstract String getClassName();
441
442 /**
443 * Returns true if the named property is defined.
444 *
445 * @param name the name of the property
446 * @param start the object in which the lookup began
447 * @return true if and only if the property was found in the object
448 */
449 public boolean has(String name, Scriptable start)
450 {
451 return null != getSlot(name, 0, SLOT_QUERY);
452 }
453
454 /**
455 * Returns true if the property index is defined.
456 *
457 * @param index the numeric index for the property
458 * @param start the object in which the lookup began
459 * @return true if and only if the property was found in the object
460 */
461 public boolean has(int index, Scriptable start)
462 {
463 if (externalData != null) {
464 return (index < externalData.getArrayLength());
465 }
466 return null != getSlot(null, index, SLOT_QUERY);
467 }
468
469 /**
470 * A version of "has" that supports symbols.
471 */
472 public boolean has(Symbol key, Scriptable start)
473 {
474 return null != getSlot(key, 0, SLOT_QUERY);
475 }
476
477 /**
478 * Returns the value of the named property or NOT_FOUND.
479 *
480 * If the property was created using defineProperty, the
481 * appropriate getter method is called.
482 *
483 * @param name the name of the property
484 * @param start the object in which the lookup began
485 * @return the value of the property (may be null), or NOT_FOUND
486 */
487 public Object get(String name, Scriptable start)
488 {
489 Slot slot = getSlot(name, 0, SLOT_QUERY);
490 if (slot == null) {
491 return Scriptable.NOT_FOUND;
492 }
493 return slot.getValue(start);
494 }
495
496 /**
497 * Returns the value of the indexed property or NOT_FOUND.
498 *
499 * @param index the numeric index for the property
500 * @param start the object in which the lookup began
501 * @return the value of the property (may be null), or NOT_FOUND
502 */
503 public Object get(int index, Scriptable start)
504 {
505 if (externalData != null) {
506 if (index < externalData.getArrayLength()) {
507 return externalData.getArrayElement(index);
508 }
509 return Scriptable.NOT_FOUND;
510 }
511
512 Slot slot = getSlot(null, index, SLOT_QUERY);
513 if (slot == null) {
514 return Scriptable.NOT_FOUND;
515 }
516 return slot.getValue(start);
517 }
518
519 /**
520 * Another version of Get that supports Symbol keyed properties.
521 */
522 public Object get(Symbol key, Scriptable start)
523 {
524 Slot slot = getSlot(key, 0, SLOT_QUERY);
525 if (slot == null) {
526 return Scriptable.NOT_FOUND;
527 }
528 return slot.getValue(start);
529 }
530
531 /**
532 * Sets the value of the named property, creating it if need be.
533 *
534 * If the property was created using defineProperty, the
535 * appropriate setter method is called. <p>
536 *
537 * If the property's attributes include READONLY, no action is
538 * taken.
539 * This method will actually set the property in the start
540 * object.
541 *
542 * @param name the name of the property
543 * @param start the object whose property is being set
544 * @param value value to set the property to
545 */
546 public void put(String name, Scriptable start, Object value)
547 {
548 if (putImpl(name, 0, start, value))
549 return;
550
551 if (start == this) throw Kit.codeBug();
552 start.put(name, start, value);
553 }
554
555 /**
556 * Sets the value of the indexed property, creating it if need be.
557 *
558 * @param index the numeric index for the property
559 * @param start the object whose property is being set
560 * @param value value to set the property to
561 */
562 public void put(int index, Scriptable start, Object value)
563 {
564 if (externalData != null) {
565 if (index < externalData.getArrayLength()) {
566 externalData.setArrayElement(index, value);
567 } else {
568 throw new JavaScriptException(
569 ScriptRuntime.newNativeError(Context.getCurrentContext(), this,
570 TopLevel.NativeErrors.RangeError,
571 new Object[] { "External array index out of bounds " }),
572 null, 0);
573 }
574 return;
575 }
576
577 if (putImpl(null, index, start, value))
578 return;
579
580 if (start == this) throw Kit.codeBug();
581 start.put(index, start, value);
582 }
583
584 /**
585 * Implementation of put required by SymbolScriptable objects.
586 */
587 public void put(Symbol key, Scriptable start, Object value)
588 {
589 if (putImpl(key, 0, start, value))
590 return;
591
592 if (start == this) throw Kit.codeBug();
593 ensureSymbolScriptable(start).put(key, start, value);
594 }
595
596 /**
597 * Removes a named property from the object.
598 *
599 * If the property is not found, or it has the PERMANENT attribute,
600 * no action is taken.
601 *
602 * @param name the name of the property
603 */
604 public void delete(String name)
605 {
606 checkNotSealed(name, 0);
607 removeSlot(name, 0);
608 }
609
610 /**
611 * Removes the indexed property from the object.
612 *
613 * If the property is not found, or it has the PERMANENT attribute,
614 * no action is taken.
615 *
616 * @param index the numeric index for the property
617 */
618 public void delete(int index)
619 {
620 checkNotSealed(null, index);
621 removeSlot(null, index);
622 }
623
624 /**
625 * Removes an object like the others, but using a Symbol as the key.
626 */
627 public void delete(Symbol key)
628 {
629 checkNotSealed(key, 0);
630 removeSlot(key, 0);
631 }
632
633 /**
634 * Sets the value of the named const property, creating it if need be.
635 *
636 * If the property was created using defineProperty, the
637 * appropriate setter method is called. <p>
638 *
639 * If the property's attributes include READONLY, no action is
640 * taken.
641 * This method will actually set the property in the start
642 * object.
643 *
644 * @param name the name of the property
645 * @param start the object whose property is being set
646 * @param value value to set the property to
647 */
648 public void putConst(String name, Scriptable start, Object value)
649 {
650 if (putConstImpl(name, 0, start, value, READONLY))
651 return;
652
653 if (start == this) throw Kit.codeBug();
654 if (start instanceof ConstProperties)
655 ((ConstProperties)start).putConst(name, start, value);
656 else
657 start.put(name, start, value);
658 }
659
660 public void defineConst(String name, Scriptable start)
661 {
662 if (putConstImpl(name, 0, start, Undefined.instance, UNINITIALIZED_CONST))
663 return;
664
665 if (start == this) throw Kit.codeBug();
666 if (start instanceof ConstProperties)
667 ((ConstProperties)start).defineConst(name, start);
668 }
669
670 /**
671 * Returns true if the named property is defined as a const on this object.
672 * @param name
673 * @return true if the named property is defined as a const, false
674 * otherwise.
675 */
676 public boolean isConst(String name)
677 {
678 Slot slot = getSlot(name, 0, SLOT_QUERY);
679 if (slot == null) {
680 return false;
681 }
682 return (slot.getAttributes() & (PERMANENT|READONLY)) ==
683 (PERMANENT|READONLY);
684
685 }
686
687 /**
688 * @deprecated Use {@link #getAttributes(String name)}. The engine always
689 * ignored the start argument.
690 */
691 @Deprecated
692 public final int getAttributes(String name, Scriptable start)
693 {
694 return getAttributes(name);
695 }
696
697 /**
698 * @deprecated Use {@link #getAttributes(int index)}. The engine always
699 * ignored the start argument.
700 */
701 @Deprecated
702 public final int getAttributes(int index, Scriptable start)
703 {
704 return getAttributes(index);
705 }
706
707 /**
708 * @deprecated Use {@link #setAttributes(String name, int attributes)}.
709 * The engine always ignored the start argument.
710 */
711 @Deprecated
712 public final void setAttributes(String name, Scriptable start,
713 int attributes)
714 {
715 setAttributes(name, attributes);
716 }
717
718 /**
719 * @deprecated Use {@link #setAttributes(int index, int attributes)}.
720 * The engine always ignored the start argument.
721 */
722 @Deprecated
723 public void setAttributes(int index, Scriptable start,
724 int attributes)
725 {
726 setAttributes(index, attributes);
727 }
728
729 /**
730 * Get the attributes of a named property.
731 *
732 * The property is specified by <code>name</code>
733 * as defined for <code>has</code>.<p>
734 *
735 * @param name the identifier for the property
736 * @return the bitset of attributes
737 * @exception EvaluatorException if the named property is not found
738 * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
739 * @see org.mozilla.javascript.ScriptableObject#READONLY
740 * @see org.mozilla.javascript.ScriptableObject#DONTENUM
741 * @see org.mozilla.javascript.ScriptableObject#PERMANENT
742 * @see org.mozilla.javascript.ScriptableObject#EMPTY
743 */
744 public int getAttributes(String name)
745 {
746 return findAttributeSlot(name, 0, SLOT_QUERY).getAttributes();
747 }
748
749 /**
750 * Get the attributes of an indexed property.
751 *
752 * @param index the numeric index for the property
753 * @exception EvaluatorException if the named property is not found
754 * is not found
755 * @return the bitset of attributes
756 * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
757 * @see org.mozilla.javascript.ScriptableObject#READONLY
758 * @see org.mozilla.javascript.ScriptableObject#DONTENUM
759 * @see org.mozilla.javascript.ScriptableObject#PERMANENT
760 * @see org.mozilla.javascript.ScriptableObject#EMPTY
761 */
762 public int getAttributes(int index)
763 {
764 return findAttributeSlot(null, index, SLOT_QUERY).getAttributes();
765 }
766
767 public int getAttributes(Symbol sym)
768 {
769 return findAttributeSlot(sym, SLOT_QUERY).getAttributes();
770 }
771
772
773 /**
774 * Set the attributes of a named property.
775 *
776 * The property is specified by <code>name</code>
777 * as defined for <code>has</code>.<p>
778 *
779 * The possible attributes are READONLY, DONTENUM,
780 * and PERMANENT. Combinations of attributes
781 * are expressed by the bitwise OR of attributes.
782 * EMPTY is the state of no attributes set. Any unused
783 * bits are reserved for future use.
784 *
785 * @param name the name of the property
786 * @param attributes the bitset of attributes
787 * @exception EvaluatorException if the named property is not found
788 * @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
789 * @see org.mozilla.javascript.ScriptableObject#READONLY
790 * @see org.mozilla.javascript.ScriptableObject#DONTENUM
791 * @see org.mozilla.javascript.ScriptableObject#PERMANENT
792 * @see org.mozilla.javascript.ScriptableObject#EMPTY
793 */
794 public void setAttributes(String name, int attributes)
795 {
796 checkNotSealed(name, 0);
797 findAttributeSlot(name, 0, SLOT_MODIFY).setAttributes(attributes);
798 }
799
800 /**
801 * Set the attributes of an indexed property.
802 *
803 * @param index the numeric index for the property
804 * @param attributes the bitset of attributes
805 * @exception EvaluatorException if the named property is not found
806 * @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
807 * @see org.mozilla.javascript.ScriptableObject#READONLY
808 * @see org.mozilla.javascript.ScriptableObject#DONTENUM
809 * @see org.mozilla.javascript.ScriptableObject#PERMANENT
810 * @see org.mozilla.javascript.ScriptableObject#EMPTY
811 */
812 public void setAttributes(int index, int attributes)
813 {
814 checkNotSealed(null, index);
815 findAttributeSlot(null, index, SLOT_MODIFY).setAttributes(attributes);
816 }
817
818 /**
819 * Set attributes of a Symbol-keyed property.
820 */
821 public void setAttributes(Symbol key, int attributes)
822 {
823 checkNotSealed(key, 0);
824 findAttributeSlot(key, SLOT_MODIFY).setAttributes(attributes);
825 }
826
827 /**
828 * XXX: write docs.
829 */
830 public void setGetterOrSetter(String name, int index,
831 Callable getterOrSetter, boolean isSetter)
832 {
833 setGetterOrSetter(name, index, getterOrSetter, isSetter, false);
834 }
835
836 private void setGetterOrSetter(String name, int index, Callable getterOrSetter,
837 boolean isSetter, boolean force)
838 {
839 if (name != null && index != 0)
840 throw new IllegalArgumentException(name);
841
842 if (!force) {
843 checkNotSealed(name, index);
844 }
845
846 final GetterSlot gslot;
847 if (isExtensible()) {
848 gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER);
849 } else {
850 Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY));
851 if (!(slot instanceof GetterSlot))
852 return;
853 gslot = (GetterSlot) slot;
854 }
855
856 if (!force) {
857 int attributes = gslot.getAttributes();
858 if ((attributes & READONLY) != 0) {
859 throw Context.reportRuntimeError1("msg.modify.readonly", name);
860 }
861 }
862 if (isSetter) {
863 gslot.setter = getterOrSetter;
864 } else {
865 gslot.getter = getterOrSetter;
866 }
867 gslot.value = Undefined.instance;
868 }
869
870 /**
871 * Get the getter or setter for a given property. Used by __lookupGetter__
872 * and __lookupSetter__.
873 *
874 * @param name Name of the object. If nonnull, index must be 0.
875 * @param index Index of the object. If nonzero, name must be null.
876 * @param isSetter If true, return the setter, otherwise return the getter.
877 * @exception IllegalArgumentException if both name and index are nonnull
878 * and nonzero respectively.
879 * @return Null if the property does not exist. Otherwise returns either
880 * the getter or the setter for the property, depending on
881 * the value of isSetter (may be undefined if unset).
882 */
883 public Object getGetterOrSetter(String name, int index, boolean isSetter)
884 {
885 if (name != null && index != 0)
886 throw new IllegalArgumentException(name);
887 Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY));
888 if (slot == null)
889 return null;
890 if (slot instanceof GetterSlot) {
891 GetterSlot gslot = (GetterSlot)slot;
892 Object result = isSetter ? gslot.setter : gslot.getter;
893 return result != null ? result : Undefined.instance;
894 } else
895 return Undefined.instance;
896 }
897
898 /**
899 * Returns whether a property is a getter or a setter
900 * @param name property name
901 * @param index property index
902 * @param setter true to check for a setter, false for a getter
903 * @return whether the property is a getter or a setter
904 */
905 protected boolean isGetterOrSetter(String name, int index, boolean setter) {
906 Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY));
907 if (slot instanceof GetterSlot) {
908 if (setter && ((GetterSlot)slot).setter != null) return true;
909 if (!setter && ((GetterSlot)slot).getter != null) return true;
910 }
911 return false;
912 }
913
914 void addLazilyInitializedValue(String name, int index,
915 LazilyLoadedCtor init, int attributes)
916 {
917 if (name != null && index != 0)
918 throw new IllegalArgumentException(name);
919 checkNotSealed(name, index);
920 GetterSlot gslot = (GetterSlot)getSlot(name, index,
921 SLOT_MODIFY_GETTER_SETTER);
922 gslot.setAttributes(attributes);
923 gslot.getter = null;
924 gslot.setter = null;
925 gslot.value = init;
926 }
927
928 /**
929 * Attach the specified object to this object, and delegate all indexed property lookups to it. In other words,
930 * if the object has 3 elements, then an attempt to look up or modify "[0]", "[1]", or "[2]" will be delegated
931 * to this object. Additional indexed properties outside the range specified, and additional non-indexed
932 * properties, may still be added. The object specified must implement the ExternalArrayData interface.
933 *
934 * @param array the List to use for delegated property access. Set this to null to revert back to regular
935 * property access.
936 * @since 1.7.6
937 */
938 public void setExternalArrayData(ExternalArrayData array)
939 {
940 externalData = array;
941
942 if (array == null) {
943 delete("length");
944 } else {
945 // Define "length" to return whatever length the List gives us.
946 defineProperty("length", null,
947 GET_ARRAY_LENGTH, null, READONLY | DONTENUM);
948 }
949 }
950
951 /**
952 * Return the array that was previously set by the call to "setExternalArrayData".
953 *
954 * @return the array, or null if it was never set
955 * @since 1.7.6
956 */
957 public ExternalArrayData getExternalArrayData()
958 {
959 return externalData;
960 }
961
962 /**
963 * This is a function used by setExternalArrayData to dynamically get the "length" property value.
964 */
965 public Object getExternalArrayLength()
966 {
967 return (externalData == null ? 0 : externalData.getArrayLength());
968 }
969
970 /**
971 * Returns the prototype of the object.
972 */
973 public Scriptable getPrototype()
974 {
975 return prototypeObject;
976 }
977
978 /**
979 * Sets the prototype of the object.
980 */
981 public void setPrototype(Scriptable m)
982 {
983 prototypeObject = m;
984 }
985
986 /**
987 * Returns the parent (enclosing) scope of the object.
988 */
989 public Scriptable getParentScope()
990 {
991 return parentScopeObject;
992 }
993
994 /**
995 * Sets the parent (enclosing) scope of the object.
996 */
997 public void setParentScope(Scriptable m)
998 {
999 parentScopeObject = m;
1000 }
1001
1002 /**
1003 * Returns an array of ids for the properties of the object.
1004 *
1005 * <p>Any properties with the attribute DONTENUM are not listed. <p>
1006 *
1007 * @return an array of java.lang.Objects with an entry for every
1008 * listed property. Properties accessed via an integer index will
1009 * have a corresponding
1010 * Integer entry in the returned array. Properties accessed by
1011 * a String will have a String entry in the returned array.
1012 */
1013 public Object[] getIds() {
1014 return getIds(false, false);
1015 }
1016
1017 /**
1018 * Returns an array of ids for the properties of the object.
1019 *
1020 * <p>All properties, even those with attribute DONTENUM, are listed. <p>
1021 *
1022 * @return an array of java.lang.Objects with an entry for every
1023 * listed property. Properties accessed via an integer index will
1024 * have a corresponding
1025 * Integer entry in the returned array. Properties accessed by
1026 * a String will have a String entry in the returned array.
1027 */
1028 public Object[] getAllIds() {
1029 return getIds(true, false);
1030 }
1031
1032 /**
1033 * Implements the [[DefaultValue]] internal method.
1034 *
1035 * <p>Note that the toPrimitive conversion is a no-op for
1036 * every type other than Object, for which [[DefaultValue]]
1037 * is called. See ECMA 9.1.<p>
1038 *
1039 * A <code>hint</code> of null means "no hint".
1040 *
1041 * @param typeHint the type hint
1042 * @return the default value for the object
1043 *
1044 * See ECMA 8.6.2.6.
1045 */
1046 public Object getDefaultValue(Class<?> typeHint)
1047 {
1048 return getDefaultValue(this, typeHint);
1049 }
1050
1051 public static Object getDefaultValue(Scriptable object, Class<?> typeHint)
1052 {
1053 Context cx = null;
1054 for (int i=0; i < 2; i++) {
1055 boolean tryToString;
1056 if (typeHint == ScriptRuntime.StringClass) {
1057 tryToString = (i == 0);
1058 } else {
1059 tryToString = (i == 1);
1060 }
1061
1062 String methodName;
1063 Object[] args;
1064 if (tryToString) {
1065 methodName = "toString";
1066 args = ScriptRuntime.emptyArgs;
1067 } else {
1068 methodName = "valueOf";
1069 args = new Object[1];
1070 String hint;
1071 if (typeHint == null) {
1072 hint = "undefined";
1073 } else if (typeHint == ScriptRuntime.StringClass) {
1074 hint = "string";
1075 } else if (typeHint == ScriptRuntime.ScriptableClass) {
1076 hint = "object";
1077 } else if (typeHint == ScriptRuntime.FunctionClass) {
1078 hint = "function";
1079 } else if (typeHint == ScriptRuntime.BooleanClass
1080 || typeHint == Boolean.TYPE)
1081 {
1082 hint = "boolean";
1083 } else if (typeHint == ScriptRuntime.NumberClass ||
1084 typeHint == ScriptRuntime.ByteClass ||
1085 typeHint == Byte.TYPE ||
1086 typeHint == ScriptRuntime.ShortClass ||
1087 typeHint == Short.TYPE ||
1088 typeHint == ScriptRuntime.IntegerClass ||
1089 typeHint == Integer.TYPE ||
1090 typeHint == ScriptRuntime.FloatClass ||
1091 typeHint == Float.TYPE ||
1092 typeHint == ScriptRuntime.DoubleClass ||
1093 typeHint == Double.TYPE)
1094 {
1095 hint = "number";
1096 } else {
1097 throw Context.reportRuntimeError1(
1098 "msg.invalid.type", typeHint.toString());
1099 }
1100 args[0] = hint;
1101 }
1102 Object v = getProperty(object, methodName);
1103 if (!(v instanceof Function))
1104 continue;
1105 Function fun = (Function) v;
1106 if (cx == null)
1107 cx = Context.getContext();
1108 v = fun.call(cx, fun.getParentScope(), object, args);
1109 if (v != null) {
1110 if (!(v instanceof Scriptable)) {
1111 return v;
1112 }
1113 if (typeHint == ScriptRuntime.ScriptableClass
1114 || typeHint == ScriptRuntime.FunctionClass)
1115 {
1116 return v;
1117 }
1118 if (tryToString && v instanceof Wrapper) {
1119 // Let a wrapped java.lang.String pass for a primitive
1120 // string.
1121 Object u = ((Wrapper)v).unwrap();
1122 if (u instanceof String)
1123 return u;
1124 }
1125 }
1126 }
1127 // fall through to error
1128 String arg = (typeHint == null) ? "undefined" : typeHint.getName();
1129 throw ScriptRuntime.typeError1("msg.default.value", arg);
1130 }
1131
1132 /**
1133 * Implements the instanceof operator.
1134 *
1135 * <p>This operator has been proposed to ECMA.
1136 *
1137 * @param instance The value that appeared on the LHS of the instanceof
1138 * operator
1139 * @return true if "this" appears in value's prototype chain
1140 *
1141 */
1142 public boolean hasInstance(Scriptable instance) {
1143 // Default for JS objects (other than Function) is to do prototype
1144 // chasing. This will be overridden in NativeFunction and non-JS
1145 // objects.
1146
1147 return ScriptRuntime.jsDelegatesTo(instance, this);
1148 }
1149
1150 /**
1151 * Emulate the SpiderMonkey (and Firefox) feature of allowing
1152 * custom objects to avoid detection by normal "object detection"
1153 * code patterns. This is used to implement document.all.
1154 * See https://bugzilla.mozilla.org/show_bug.cgi?id=412247.
1155 * This is an analog to JOF_DETECTING from SpiderMonkey; see
1156 * https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
1157 * Other than this special case, embeddings should return false.
1158 * @return true if this object should avoid object detection
1159 * @since 1.7R1
1160 */
1161 public boolean avoidObjectDetection() {
1162 return false;
1163 }
1164
1165 /**
1166 * Custom <tt>==</tt> operator.
1167 * Must return {@link Scriptable#NOT_FOUND} if this object does not
1168 * have custom equality operator for the given value,
1169 * <tt>Boolean.TRUE</tt> if this object is equivalent to <tt>value</tt>,
1170 * <tt>Boolean.FALSE</tt> if this object is not equivalent to
1171 * <tt>value</tt>.
1172 * <p>
1173 * The default implementation returns Boolean.TRUE
1174 * if <tt>this == value</tt> or {@link Scriptable#NOT_FOUND} otherwise.
1175 * It indicates that by default custom equality is available only if
1176 * <tt>value</tt> is <tt>this</tt> in which case true is returned.
1177 */
1178 protected Object equivalentValues(Object value)
1179 {
1180 return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND;
1181 }
1182
1183 /**
1184 * Defines JavaScript objects from a Java class that implements Scriptable.
1185 *
1186 * If the given class has a method
1187 * <pre>
1188 * static void init(Context cx, Scriptable scope, boolean sealed);</pre>
1189 *
1190 * or its compatibility form
1191 * <pre>
1192 * static void init(Scriptable scope);</pre>
1193 *
1194 * then it is invoked and no further initialization is done.<p>
1195 *
1196 * However, if no such a method is found, then the class's constructors and
1197 * methods are used to initialize a class in the following manner.<p>
1198 *
1199 * First, the zero-parameter constructor of the class is called to
1200 * create the prototype. If no such constructor exists,
1201 * a {@link EvaluatorException} is thrown. <p>
1202 *
1203 * Next, all methods are scanned for special prefixes that indicate that they
1204 * have special meaning for defining JavaScript objects.
1205 * These special prefixes are
1206 * <ul>
1207 * <li><code>jsFunction_</code> for a JavaScript function
1208 * <li><code>jsStaticFunction_</code> for a JavaScript function that
1209 * is a property of the constructor
1210 * <li><code>jsGet_</code> for a getter of a JavaScript property
1211 * <li><code>jsSet_</code> for a setter of a JavaScript property
1212 * <li><code>jsConstructor</code> for a JavaScript function that
1213 * is the constructor
1214 * </ul><p>
1215 *
1216 * If the method's name begins with "jsFunction_", a JavaScript function
1217 * is created with a name formed from the rest of the Java method name
1218 * following "jsFunction_". So a Java method named "jsFunction_foo" will
1219 * define a JavaScript method "foo". Calling this JavaScript function
1220 * will cause the Java method to be called. The parameters of the method
1221 * must be of number and types as defined by the FunctionObject class.
1222 * The JavaScript function is then added as a property
1223 * of the prototype. <p>
1224 *
1225 * If the method's name begins with "jsStaticFunction_", it is handled
1226 * similarly except that the resulting JavaScript function is added as a
1227 * property of the constructor object. The Java method must be static.
1228 *
1229 * If the method's name begins with "jsGet_" or "jsSet_", the method is
1230 * considered to define a property. Accesses to the defined property
1231 * will result in calls to these getter and setter methods. If no
1232 * setter is defined, the property is defined as READONLY.<p>
1233 *
1234 * If the method's name is "jsConstructor", the method is
1235 * considered to define the body of the constructor. Only one
1236 * method of this name may be defined. You may use the varargs forms
1237 * for constructors documented in {@link FunctionObject#FunctionObject(String, Member, Scriptable)}
1238 *
1239 * If no method is found that can serve as constructor, a Java
1240 * constructor will be selected to serve as the JavaScript
1241 * constructor in the following manner. If the class has only one
1242 * Java constructor, that constructor is used to define
1243 * the JavaScript constructor. If the the class has two constructors,
1244 * one must be the zero-argument constructor (otherwise an
1245 * {@link EvaluatorException} would have already been thrown
1246 * when the prototype was to be created). In this case
1247 * the Java constructor with one or more parameters will be used
1248 * to define the JavaScript constructor. If the class has three
1249 * or more constructors, an {@link EvaluatorException}
1250 * will be thrown.<p>
1251 *
1252 * Finally, if there is a method
1253 * <pre>
1254 * static void finishInit(Scriptable scope, FunctionObject constructor,
1255 * Scriptable prototype)</pre>
1256 *
1257 * it will be called to finish any initialization. The <code>scope</code>
1258 * argument will be passed, along with the newly created constructor and
1259 * the newly created prototype.<p>
1260 *
1261 * @param scope The scope in which to define the constructor.
1262 * @param clazz The Java class to use to define the JavaScript objects
1263 * and properties.
1264 * @exception IllegalAccessException if access is not available
1265 * to a reflected class member
1266 * @exception InstantiationException if unable to instantiate
1267 * the named class
1268 * @exception InvocationTargetException if an exception is thrown
1269 * during execution of methods of the named class
1270 * @see org.mozilla.javascript.Function
1271 * @see org.mozilla.javascript.FunctionObject
1272 * @see org.mozilla.javascript.ScriptableObject#READONLY
1273 * @see org.mozilla.javascript.ScriptableObject
1274 * #defineProperty(String, Class, int)
1275 */
1276 public static <T extends Scriptable> void defineClass(
1277 Scriptable scope, Class<T> clazz)
1278 throws IllegalAccessException, InstantiationException,
1279 InvocationTargetException
1280 {
1281 defineClass(scope, clazz, false, false);
1282 }
1283
1284 /**
1285 * Defines JavaScript objects from a Java class, optionally
1286 * allowing sealing.
1287 *
1288 * Similar to <code>defineClass(Scriptable scope, Class clazz)</code>
1289 * except that sealing is allowed. An object that is sealed cannot have
1290 * properties added or removed. Note that sealing is not allowed in
1291 * the current ECMA/ISO language specification, but is likely for
1292 * the next version.
1293 *
1294 * @param scope The scope in which to define the constructor.
1295 * @param clazz The Java class to use to define the JavaScript objects
1296 * and properties. The class must implement Scriptable.
1297 * @param sealed Whether or not to create sealed standard objects that
1298 * cannot be modified.
1299 * @exception IllegalAccessException if access is not available
1300 * to a reflected class member
1301 * @exception InstantiationException if unable to instantiate
1302 * the named class
1303 * @exception InvocationTargetException if an exception is thrown
1304 * during execution of methods of the named class
1305 * @since 1.4R3
1306 */
1307 public static <T extends Scriptable> void defineClass(
1308 Scriptable scope, Class<T> clazz, boolean sealed)
1309 throws IllegalAccessException, InstantiationException,
1310 InvocationTargetException
1311 {
1312 defineClass(scope, clazz, sealed, false);
1313 }
1314
1315 /**
1316 * Defines JavaScript objects from a Java class, optionally
1317 * allowing sealing and mapping of Java inheritance to JavaScript
1318 * prototype-based inheritance.
1319 *
1320 * Similar to <code>defineClass(Scriptable scope, Class clazz)</code>
1321 * except that sealing and inheritance mapping are allowed. An object
1322 * that is sealed cannot have properties added or removed. Note that
1323 * sealing is not allowed in the current ECMA/ISO language specification,
1324 * but is likely for the next version.
1325 *
1326 * @param scope The scope in which to define the constructor.
1327 * @param clazz The Java class to use to define the JavaScript objects
1328 * and properties. The class must implement Scriptable.
1329 * @param sealed Whether or not to create sealed standard objects that
1330 * cannot be modified.
1331 * @param mapInheritance Whether or not to map Java inheritance to
1332 * JavaScript prototype-based inheritance.
1333 * @return the class name for the prototype of the specified class
1334 * @exception IllegalAccessException if access is not available
1335 * to a reflected class member
1336 * @exception InstantiationException if unable to instantiate
1337 * the named class
1338 * @exception InvocationTargetException if an exception is thrown
1339 * during execution of methods of the named class
1340 * @since 1.6R2
1341 */
1342 public static <T extends Scriptable> String defineClass(
1343 Scriptable scope, Class<T> clazz, boolean sealed,
1344 boolean mapInheritance)
1345 throws IllegalAccessException, InstantiationException,
1346 InvocationTargetException
1347 {
1348 BaseFunction ctor = buildClassCtor(scope, clazz, sealed,
1349 mapInheritance);
1350 if (ctor == null)
1351 return null;
1352 String name = ctor.getClassPrototype().getClassName();
1353 defineProperty(scope, name, ctor, ScriptableObject.DONTENUM);
1354 return name;
1355 }
1356
1357 static <T extends Scriptable> BaseFunction buildClassCtor(
1358 Scriptable scope, Class<T> clazz,
1359 boolean sealed,
1360 boolean mapInheritance)
1361 throws IllegalAccessException, InstantiationException,
1362 InvocationTargetException
1363 {
1364 Method[] methods = FunctionObject.getMethodList(clazz);
1365 for (int i=0; i < methods.length; i++) {
1366 Method method = methods[i];
1367 if (!method.getName().equals("init"))
1368 continue;
1369 Class<?>[] parmTypes = method.getParameterTypes();
1370 if (parmTypes.length == 3 &&
1371 parmTypes[0] == ScriptRuntime.ContextClass &&
1372 parmTypes[1] == ScriptRuntime.ScriptableClass &&
1373 parmTypes[2] == Boolean.TYPE &&
1374 Modifier.isStatic(method.getModifiers()))
1375 {
1376 Object args[] = { Context.getContext(), scope,
1377 sealed ? Boolean.TRUE : Boolean.FALSE };
1378 method.invoke(null, args);
1379 return null;
1380 }
1381 if (parmTypes.length == 1 &&
1382 parmTypes[0] == ScriptRuntime.ScriptableClass &&
1383 Modifier.isStatic(method.getModifiers()))
1384 {
1385 Object args[] = { scope };
1386 method.invoke(null, args);
1387 return null;
1388 }
1389
1390 }
1391
1392 // If we got here, there isn't an "init" method with the right
1393 // parameter types.
1394
1395 Constructor<?>[] ctors = clazz.getConstructors();
1396 Constructor<?> protoCtor = null;
1397 for (int i=0; i < ctors.length; i++) {
1398 if (ctors[i].getParameterTypes().length == 0) {
1399 protoCtor = ctors[i];
1400 break;
1401 }
1402 }
1403 if (protoCtor == null) {
1404 throw Context.reportRuntimeError1(
1405 "msg.zero.arg.ctor", clazz.getName());
1406 }
1407
1408 Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs);
1409 String className = proto.getClassName();
1410
1411 // check for possible redefinition
1412 Object existing = getProperty(getTopLevelScope(scope), className);
1413 if (existing instanceof BaseFunction) {
1414 Object existingProto = ((BaseFunction)existing).getPrototypeProperty();
1415 if (existingProto != null && clazz.equals(existingProto.getClass())) {
1416 return (BaseFunction)existing;
1417 }
1418 }
1419
1420 // Set the prototype's prototype, trying to map Java inheritance to JS
1421 // prototype-based inheritance if requested to do so.
1422 Scriptable superProto = null;
1423 if (mapInheritance) {
1424 Class<? super T> superClass = clazz.getSuperclass();
1425 if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) &&
1426 !Modifier.isAbstract(superClass.getModifiers()))
1427 {
1428 Class<? extends Scriptable> superScriptable =
1429 extendsScriptable(superClass);
1430 String name = ScriptableObject.defineClass(scope,
1431 superScriptable, sealed, mapInheritance);
1432 if (name != null) {
1433 superProto = ScriptableObject.getClassPrototype(scope, name);
1434 }
1435 }
1436 }
1437 if (superProto == null) {
1438 superProto = ScriptableObject.getObjectPrototype(scope);
1439 }
1440 proto.setPrototype(superProto);
1441
1442 // Find out whether there are any methods that begin with
1443 // "js". If so, then only methods that begin with special
1444 // prefixes will be defined as JavaScript entities.
1445 final String functionPrefix = "jsFunction_";
1446 final String staticFunctionPrefix = "jsStaticFunction_";
1447 final String getterPrefix = "jsGet_";
1448 final String setterPrefix = "jsSet_";
1449 final String ctorName = "jsConstructor";
1450
1451 Member ctorMember = findAnnotatedMember(methods, JSConstructor.class);
1452 if (ctorMember == null) {
1453 ctorMember = findAnnotatedMember(ctors, JSConstructor.class);
1454 }
1455 if (ctorMember == null) {
1456 ctorMember = FunctionObject.findSingleMethod(methods, ctorName);
1457 }
1458 if (ctorMember == null) {
1459 if (ctors.length == 1) {
1460 ctorMember = ctors[0];
1461 } else if (ctors.length == 2) {
1462 if (ctors[0].getParameterTypes().length == 0)
1463 ctorMember = ctors[1];
1464 else if (ctors[1].getParameterTypes().length == 0)
1465 ctorMember = ctors[0];
1466 }
1467 if (ctorMember == null) {
1468 throw Context.reportRuntimeError1(
1469 "msg.ctor.multiple.parms", clazz.getName());
1470 }
1471 }
1472
1473 FunctionObject ctor = new FunctionObject(className, ctorMember, scope);
1474 if (ctor.isVarArgsMethod()) {
1475 throw Context.reportRuntimeError1
1476 ("msg.varargs.ctor", ctorMember.getName());
1477 }
1478 ctor.initAsConstructor(scope, proto);
1479
1480 Method finishInit = null;
1481 HashSet<String> staticNames = new HashSet<String>(),
1482 instanceNames = new HashSet<String>();
1483 for (Method method : methods) {
1484 if (method == ctorMember) {
1485 continue;
1486 }
1487 String name = method.getName();
1488 if (name.equals("finishInit")) {
1489 Class<?>[] parmTypes = method.getParameterTypes();
1490 if (parmTypes.length == 3 &&
1491 parmTypes[0] == ScriptRuntime.ScriptableClass &&
1492 parmTypes[1] == FunctionObject.class &&
1493 parmTypes[2] == ScriptRuntime.ScriptableClass &&
1494 Modifier.isStatic(method.getModifiers()))
1495 {
1496 finishInit = method;
1497 continue;
1498 }
1499 }
1500 // ignore any compiler generated methods.
1501 if (name.indexOf('$') != -1)
1502 continue;
1503 if (name.equals(ctorName))
1504 continue;
1505
1506 Annotation annotation = null;
1507 String prefix = null;
1508 if (method.isAnnotationPresent(JSFunction.class)) {
1509 annotation = method.getAnnotation(JSFunction.class);
1510 } else if (method.isAnnotationPresent(JSStaticFunction.class)) {
1511 annotation = method.getAnnotation(JSStaticFunction.class);
1512 } else if (method.isAnnotationPresent(JSGetter.class)) {
1513 annotation = method.getAnnotation(JSGetter.class);
1514 } else if (method.isAnnotationPresent(JSSetter.class)) {
1515 continue;
1516 }
1517
1518 if (annotation == null) {
1519 if (name.startsWith(functionPrefix)) {
1520 prefix = functionPrefix;
1521 } else if (name.startsWith(staticFunctionPrefix)) {
1522 prefix = staticFunctionPrefix;
1523 } else if (name.startsWith(getterPrefix)) {
1524 prefix = getterPrefix;
1525 } else if (annotation == null) {
1526 // note that setterPrefix is among the unhandled names here -
1527 // we deal with that when we see the getter
1528 continue;
1529 }
1530 }
1531
1532 boolean isStatic = annotation instanceof JSStaticFunction
1533 || prefix == staticFunctionPrefix;
1534 HashSet<String> names = isStatic ? staticNames : instanceNames;
1535 String propName = getPropertyName(name, prefix, annotation);
1536 if (names.contains(propName)) {
1537 throw Context.reportRuntimeError2("duplicate.defineClass.name",
1538 name, propName);
1539 }
1540 names.add(propName);
1541 name = propName;
1542
1543 if (annotation instanceof JSGetter || prefix == getterPrefix) {
1544 if (!(proto instanceof ScriptableObject)) {
1545 throw Context.reportRuntimeError2(
1546 "msg.extend.scriptable",
1547 proto.getClass().toString(), name);
1548 }
1549 Method setter = findSetterMethod(methods, name, setterPrefix);
1550 int attr = ScriptableObject.PERMANENT |
1551 ScriptableObject.DONTENUM |
1552 (setter != null ? 0
1553 : ScriptableObject.READONLY);
1554 ((ScriptableObject) proto).defineProperty(name, null,
1555 method, setter,
1556 attr);
1557 continue;
1558 }
1559
1560 if (isStatic && !Modifier.isStatic(method.getModifiers())) {
1561 throw Context.reportRuntimeError(
1562 "jsStaticFunction must be used with static method.");
1563 }
1564
1565 FunctionObject f = new FunctionObject(name, method, proto);
1566 if (f.isVarArgsConstructor()) {
1567 throw Context.reportRuntimeError1
1568 ("msg.varargs.fun", ctorMember.getName());
1569 }
1570 defineProperty(isStatic ? ctor : proto, name, f, DONTENUM);
1571 if (sealed) {
1572 f.sealObject();
1573 }
1574 }
1575
1576 // Call user code to complete initialization if necessary.
1577 if (finishInit != null) {
1578 Object[] finishArgs = { scope, ctor, proto };
1579 finishInit.invoke(null, finishArgs);
1580 }
1581
1582 // Seal the object if necessary.
1583 if (sealed) {
1584 ctor.sealObject();
1585 if (proto instanceof ScriptableObject) {
1586 ((ScriptableObject) proto).sealObject();
1587 }
1588 }
1589
1590 return ctor;
1591 }
1592
1593 private static Member findAnnotatedMember(AccessibleObject[] members,
1594 Class<? extends Annotation> annotation) {
1595 for (AccessibleObject member : members) {
1596 if (member.isAnnotationPresent(annotation)) {
1597 return (Member) member;
1598 }
1599 }
1600 return null;
1601 }
1602
1603 private static Method findSetterMethod(Method[] methods,
1604 String name,
1605 String prefix) {
1606 String newStyleName = "set"
1607 + Character.toUpperCase(name.charAt(0))
1608 + name.substring(1);
1609 for (Method method : methods) {
1610 JSSetter annotation = method.getAnnotation(JSSetter.class);
1611 if (annotation != null) {
1612 if (name.equals(annotation.value()) ||
1613 ("".equals(annotation.value()) && newStyleName.equals(method.getName()))) {
1614 return method;
1615 }
1616 }
1617 }
1618 String oldStyleName = prefix + name;
1619 for (Method method : methods) {
1620 if (oldStyleName.equals(method.getName())) {
1621 return method;
1622 }
1623 }
1624 return null;
1625 }
1626
1627 private static String getPropertyName(String methodName,
1628 String prefix,
1629 Annotation annotation) {
1630 if (prefix != null) {
1631 return methodName.substring(prefix.length());
1632 }
1633 String propName = null;
1634 if (annotation instanceof JSGetter) {
1635 propName = ((JSGetter) annotation).value();
1636 if (propName == null || propName.length() == 0) {
1637 if (methodName.length() > 3 && methodName.startsWith("get")) {
1638 propName = methodName.substring(3);
1639 if (Character.isUpperCase(propName.charAt(0))) {
1640 if (propName.length() == 1) {
1641 propName = propName.toLowerCase();
1642 } else if (!Character.isUpperCase(propName.charAt(1))){
1643 propName = Character.toLowerCase(propName.charAt(0))
1644 + propName.substring(1);
1645 }
1646 }
1647 }
1648 }
1649 } else if (annotation instanceof JSFunction) {
1650 propName = ((JSFunction) annotation).value();
1651 } else if (annotation instanceof JSStaticFunction) {
1652 propName = ((JSStaticFunction) annotation).value();
1653 }
1654 if (propName == null || propName.length() == 0) {
1655 propName = methodName;
1656 }
1657 return propName;
1658 }
1659
1660 @SuppressWarnings({"unchecked"})
1661 private static <T extends Scriptable> Class<T> extendsScriptable(Class<?> c)
1662 {
1663 if (ScriptRuntime.ScriptableClass.isAssignableFrom(c))
1664 return (Class<T>) c;
1665 return null;
1666 }
1667
1668 /**
1669 * Define a JavaScript property.
1670 *
1671 * Creates the property with an initial value and sets its attributes.
1672 *
1673 * @param propertyName the name of the property to define.
1674 * @param value the initial value of the property
1675 * @param attributes the attributes of the JavaScript property
1676 * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
1677 */
1678 public void defineProperty(String propertyName, Object value,
1679 int attributes)
1680 {
1681 checkNotSealed(propertyName, 0);
1682 put(propertyName, this, value);
1683 setAttributes(propertyName, attributes);
1684 }
1685
1686 /**
1687 * A version of defineProperty that uses a Symbol key.
1688 */
1689 public void defineProperty(Symbol key, Object value,
1690 int attributes)
1691 {
1692 checkNotSealed(key, 0);
1693 put(key, this, value);
1694 setAttributes(key, attributes);
1695 }
1696
1697 /**
1698 * Utility method to add properties to arbitrary Scriptable object.
1699 * If destination is instance of ScriptableObject, calls
1700 * defineProperty there, otherwise calls put in destination
1701 * ignoring attributes
1702 */
1703 public static void defineProperty(Scriptable destination,
1704 String propertyName, Object value,
1705 int attributes)
1706 {
1707 if (!(destination instanceof ScriptableObject)) {
1708 destination.put(propertyName, destination, value);
1709 return;
1710 }
1711 ScriptableObject so = (ScriptableObject)destination;
1712 so.defineProperty(propertyName, value, attributes);
1713 }
1714
1715 /**
1716 * Utility method to add properties to arbitrary Scriptable object.
1717 * If destination is instance of ScriptableObject, calls
1718 * defineProperty there, otherwise calls put in destination
1719 * ignoring attributes
1720 */
1721 public static void defineConstProperty(Scriptable destination,
1722 String propertyName)
1723 {
1724 if (destination instanceof ConstProperties) {
1725 ConstProperties cp = (ConstProperties)destination;
1726 cp.defineConst(propertyName, destination);
1727 } else
1728 defineProperty(destination, propertyName, Undefined.instance, CONST);
1729 }
1730
1731 /**
1732 * Define a JavaScript property with getter and setter side effects.
1733 *
1734 * If the setter is not found, the attribute READONLY is added to
1735 * the given attributes. <p>
1736 *
1737 * The getter must be a method with zero parameters, and the setter, if
1738 * found, must be a method with one parameter.<p>
1739 *
1740 * @param propertyName the name of the property to define. This name
1741 * also affects the name of the setter and getter
1742 * to search for. If the propertyId is "foo", then
1743 * <code>clazz</code> will be searched for "getFoo"
1744 * and "setFoo" methods.
1745 * @param clazz the Java class to search for the getter and setter
1746 * @param attributes the attributes of the JavaScript property
1747 * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
1748 */
1749 public void defineProperty(String propertyName, Class<?> clazz,
1750 int attributes)
1751 {
1752 int length = propertyName.length();
1753 if (length == 0) throw new IllegalArgumentException();
1754 char[] buf = new char[3 + length];
1755 propertyName.getChars(0, length, buf, 3);
1756 buf[3] = Character.toUpperCase(buf[3]);
1757 buf[0] = 'g';
1758 buf[1] = 'e';
1759 buf[2] = 't';
1760 String getterName = new String(buf);
1761 buf[0] = 's';
1762 String setterName = new String(buf);
1763
1764 Method[] methods = FunctionObject.getMethodList(clazz);
1765 Method getter = FunctionObject.findSingleMethod(methods, getterName);
1766 Method setter = FunctionObject.findSingleMethod(methods, setterName);
1767 if (setter == null)
1768 attributes |= ScriptableObject.READONLY;
1769 defineProperty(propertyName, null, getter,
1770 setter == null ? null : setter, attributes);
1771 }
1772
1773 /**
1774 * Define a JavaScript property.
1775 *
1776 * Use this method only if you wish to define getters and setters for
1777 * a given property in a ScriptableObject. To create a property without
1778 * special getter or setter side effects, use
1779 * <code>defineProperty(String,int)</code>.
1780 *
1781 * If <code>setter</code> is null, the attribute READONLY is added to
1782 * the given attributes.<p>
1783 *
1784 * Several forms of getters or setters are allowed. In all cases the
1785 * type of the value parameter can be any one of the following types:
1786 * Object, String, boolean, Scriptable, byte, short, int, long, float,
1787 * or double. The runtime will perform appropriate conversions based
1788 * upon the type of the parameter (see description in FunctionObject).
1789 * The first forms are nonstatic methods of the class referred to
1790 * by 'this':
1791 * <pre>
1792 * Object getFoo();
1793 * void setFoo(SomeType value);</pre>
1794 * Next are static methods that may be of any class; the object whose
1795 * property is being accessed is passed in as an extra argument:
1796 * <pre>
1797 * static Object getFoo(Scriptable obj);
1798 * static void setFoo(Scriptable obj, SomeType value);</pre>
1799 * Finally, it is possible to delegate to another object entirely using
1800 * the <code>delegateTo</code> parameter. In this case the methods are
1801 * nonstatic methods of the class delegated to, and the object whose
1802 * property is being accessed is passed in as an extra argument:
1803 * <pre>
1804 * Object getFoo(Scriptable obj);
1805 * void setFoo(Scriptable obj, SomeType value);</pre>
1806 *
1807 * @param propertyName the name of the property to define.
1808 * @param delegateTo an object to call the getter and setter methods on,
1809 * or null, depending on the form used above.
1810 * @param getter the method to invoke to get the value of the property
1811 * @param setter the method to invoke to set the value of the property
1812 * @param attributes the attributes of the JavaScript property
1813 */
1814 public void defineProperty(String propertyName, Object delegateTo,
1815 Method getter, Method setter, int attributes)
1816 {
1817 MemberBox getterBox = null;
1818 if (getter != null) {
1819 getterBox = new MemberBox(getter);
1820
1821 boolean delegatedForm;
1822 if (!Modifier.isStatic(getter.getModifiers())) {
1823 delegatedForm = (delegateTo != null);
1824 getterBox.delegateTo = delegateTo;
1825 } else {
1826 delegatedForm = true;
1827 // Ignore delegateTo for static getter but store
1828 // non-null delegateTo indicator.
1829 getterBox.delegateTo = Void.TYPE;
1830 }
1831
1832 String errorId = null;
1833 Class<?>[] parmTypes = getter.getParameterTypes();
1834 if (parmTypes.length == 0) {
1835 if (delegatedForm) {
1836 errorId = "msg.obj.getter.parms";
1837 }
1838 } else if (parmTypes.length == 1) {
1839 Object argType = parmTypes[0];
1840 // Allow ScriptableObject for compatibility
1841 if (!(argType == ScriptRuntime.ScriptableClass ||
1842 argType == ScriptRuntime.ScriptableObjectClass))
1843 {
1844 errorId = "msg.bad.getter.parms";
1845 } else if (!delegatedForm) {
1846 errorId = "msg.bad.getter.parms";
1847 }
1848 } else {
1849 errorId = "msg.bad.getter.parms";
1850 }
1851 if (errorId != null) {
1852 throw Context.reportRuntimeError1(errorId, getter.toString());
1853 }
1854 }
1855
1856 MemberBox setterBox = null;
1857 if (setter != null) {
1858 if (setter.getReturnType() != Void.TYPE)
1859 throw Context.reportRuntimeError1("msg.setter.return",
1860 setter.toString());
1861
1862 setterBox = new MemberBox(setter);
1863
1864 boolean delegatedForm;
1865 if (!Modifier.isStatic(setter.getModifiers())) {
1866 delegatedForm = (delegateTo != null);
1867 setterBox.delegateTo = delegateTo;
1868 } else {
1869 delegatedForm = true;
1870 // Ignore delegateTo for static setter but store
1871 // non-null delegateTo indicator.
1872 setterBox.delegateTo = Void.TYPE;
1873 }
1874
1875 String errorId = null;
1876 Class<?>[] parmTypes = setter.getParameterTypes();
1877 if (parmTypes.length == 1) {
1878 if (delegatedForm) {
1879 errorId = "msg.setter2.expected";
1880 }
1881 } else if (parmTypes.length == 2) {
1882 Object argType = parmTypes[0];
1883 // Allow ScriptableObject for compatibility
1884 if (!(argType == ScriptRuntime.ScriptableClass ||
1885 argType == ScriptRuntime.ScriptableObjectClass))
1886 {
1887 errorId = "msg.setter2.parms";
1888 } else if (!delegatedForm) {
1889 errorId = "msg.setter1.parms";
1890 }
1891 } else {
1892 errorId = "msg.setter.parms";
1893 }
1894 if (errorId != null) {
1895 throw Context.reportRuntimeError1(errorId, setter.toString());
1896 }
1897 }
1898
1899 GetterSlot gslot = (GetterSlot)getSlot(propertyName, 0,
1900 SLOT_MODIFY_GETTER_SETTER);
1901 gslot.setAttributes(attributes);
1902 gslot.getter = getterBox;
1903 gslot.setter = setterBox;
1904 }
1905
1906 /**
1907 * Defines one or more properties on this object.
1908 *
1909 * @param cx the current Context
1910 * @param props a map of property ids to property descriptors
1911 */
1912 public void defineOwnProperties(Context cx, ScriptableObject props) {
1913 Object[] ids = props.getIds(false, true);
1914 ScriptableObject[] descs = new ScriptableObject[ids.length];
1915 for (int i = 0, len = ids.length; i < len; ++i) {
1916 Object descObj = ScriptRuntime.getObjectElem(props, ids[i], cx);
1917 ScriptableObject desc = ensureScriptableObject(descObj);
1918 checkPropertyDefinition(desc);
1919 descs[i] = desc;
1920 }
1921 for (int i = 0, len = ids.length; i < len; ++i) {
1922 defineOwnProperty(cx, ids[i], descs[i]);
1923 }
1924 }
1925
1926 /**
1927 * Defines a property on an object.
1928 *
1929 * @param cx the current Context
1930 * @param id the name/index of the property
1931 * @param desc the new property descriptor, as described in 8.6.1
1932 */
1933 public void defineOwnProperty(Context cx, Object id, ScriptableObject desc) {
1934 checkPropertyDefinition(desc);
1935 defineOwnProperty(cx, id, desc, true);
1936 }
1937
1938 /**
1939 * Defines a property on an object.
1940 *
1941 * Based on [[DefineOwnProperty]] from 8.12.10 of the spec.
1942 *
1943 * @param cx the current Context
1944 * @param id the name/index of the property
1945 * @param desc the new property descriptor, as described in 8.6.1
1946 * @param checkValid whether to perform validity checks
1947 */
1948 protected void defineOwnProperty(Context cx, Object id, ScriptableObject desc,
1949 boolean checkValid) {
1950
1951 Slot slot = getSlot(cx, id, SLOT_QUERY);
1952 boolean isNew = slot == null;
1953
1954 if (checkValid) {
1955 ScriptableObject current = slot == null ?
1956 null : slot.getPropertyDescriptor(cx, this);
1957 checkPropertyChange(id, current, desc);
1958 }
1959
1960 boolean isAccessor = isAccessorDescriptor(desc);
1961 final int attributes;
1962
1963 if (slot == null) { // new slot
1964 slot = getSlot(cx, id, isAccessor ? SLOT_MODIFY_GETTER_SETTER : SLOT_MODIFY);
1965 attributes = applyDescriptorToAttributeBitset(DONTENUM|READONLY|PERMANENT, desc);
1966 } else {
1967 attributes = applyDescriptorToAttributeBitset(slot.getAttributes(), desc);
1968 }
1969
1970 slot = unwrapSlot(slot);
1971
1972 if (isAccessor) {
1973 if ( !(slot instanceof GetterSlot) ) {
1974 slot = getSlot(cx, id, SLOT_MODIFY_GETTER_SETTER);
1975 }
1976
1977 GetterSlot gslot = (GetterSlot) slot;
1978
1979 Object getter = getProperty(desc, "get");
1980 if (getter != NOT_FOUND) {
1981 gslot.getter = getter;
1982 }
1983 Object setter = getProperty(desc, "set");
1984 if (setter != NOT_FOUND) {
1985 gslot.setter = setter;
1986 }
1987
1988 gslot.value = Undefined.instance;
1989 gslot.setAttributes(attributes);
1990 } else {
1991 if (slot instanceof GetterSlot && isDataDescriptor(desc)) {
1992 slot = getSlot(cx, id, SLOT_CONVERT_ACCESSOR_TO_DATA);
1993 }
1994
1995 Object value = getProperty(desc, "value");
1996 if (value != NOT_FOUND) {
1997 slot.value = value;
1998 } else if (isNew) {
1999 slot.value = Undefined.instance;
2000 }
2001 slot.setAttributes(attributes);
2002 }
2003 }
2004
2005 protected void checkPropertyDefinition(ScriptableObject desc) {
2006 Object getter = getProperty(desc, "get");
2007 if (getter != NOT_FOUND && getter != Undefined.instance
2008 && !(getter instanceof Callable)) {
2009 throw ScriptRuntime.notFunctionError(getter);
2010 }
2011 Object setter = getProperty(desc, "set");
2012 if (setter != NOT_FOUND && setter != Undefined.instance
2013 && !(setter instanceof Callable)) {
2014 throw ScriptRuntime.notFunctionError(setter);
2015 }
2016 if (isDataDescriptor(desc) && isAccessorDescriptor(desc)) {
2017 throw ScriptRuntime.typeError0("msg.both.data.and.accessor.desc");
2018 }
2019 }
2020
2021 protected void checkPropertyChange(Object id, ScriptableObject current,
2022 ScriptableObject desc) {
2023 if (current == null) { // new property
2024 if (!isExtensible()) throw ScriptRuntime.typeError0("msg.not.extensible");
2025 } else {
2026 if (isFalse(current.get("configurable", current))) {
2027 if (isTrue(getProperty(desc, "configurable")))
2028 throw ScriptRuntime.typeError1(
2029 "msg.change.configurable.false.to.true", id);
2030 if (isTrue(current.get("enumerable", current)) != isTrue(getProperty(desc, "enumerable")))
2031 throw ScriptRuntime.typeError1(
2032 "msg.change.enumerable.with.configurable.false", id);
2033 boolean isData = isDataDescriptor(desc);
2034 boolean isAccessor = isAccessorDescriptor(desc);
2035 if (!isData && !isAccessor) {
2036 // no further validation required for generic descriptor
2037 } else if (isData && isDataDescriptor(current)) {
2038 if (isFalse(current.get("writable", current))) {
2039 if (isTrue(getProperty(desc, "writable")))
2040 throw ScriptRuntime.typeError1(
2041 "msg.change.writable.false.to.true.with.configurable.false", id);
2042
2043 if (!sameValue(getProperty(desc, "value"), current.get("value", current)))
2044 throw ScriptRuntime.typeError1(
2045 "msg.change.value.with.writable.false", id);
2046 }
2047 } else if (isAccessor && isAccessorDescriptor(current)) {
2048 if (!sameValue(getProperty(desc, "set"), current.get("set", current)))
2049 throw ScriptRuntime.typeError1(
2050 "msg.change.setter.with.configurable.false", id);
2051
2052 if (!sameValue(getProperty(desc, "get"), current.get("get", current)))
2053 throw ScriptRuntime.typeError1(
2054 "msg.change.getter.with.configurable.false", id);
2055 } else {
2056 if (isDataDescriptor(current))
2057 throw ScriptRuntime.typeError1(
2058 "msg.change.property.data.to.accessor.with.configurable.false", id);
2059 else
2060 throw ScriptRuntime.typeError1(
2061 "msg.change.property.accessor.to.data.with.configurable.false", id);
2062 }
2063 }
2064 }
2065 }
2066
2067 protected static boolean isTrue(Object value) {
2068 return (value != NOT_FOUND) && ScriptRuntime.toBoolean(value);
2069 }
2070
2071 protected static boolean isFalse(Object value) {
2072 return !isTrue(value);
2073 }
2074
2075 /**
2076 * Implements SameValue as described in ES5 9.12, additionally checking
2077 * if new value is defined.
2078 * @param newValue the new value
2079 * @param currentValue the current value
2080 * @return true if values are the same as defined by ES5 9.12
2081 */
2082 protected boolean sameValue(Object newValue, Object currentValue) {
2083 if (newValue == NOT_FOUND) {
2084 return true;
2085 }
2086 if (currentValue == NOT_FOUND) {
2087 currentValue = Undefined.instance;
2088 }
2089 // Special rules for numbers: NaN is considered the same value,
2090 // while zeroes with different signs are considered different.
2091 if (currentValue instanceof Number && newValue instanceof Number) {
2092 double d1 = ((Number)currentValue).doubleValue();
2093 double d2 = ((Number)newValue).doubleValue();
2094 if (Double.isNaN(d1) && Double.isNaN(d2)) {
2095 return true;
2096 }
2097 if (d1 == 0.0 && Double.doubleToLongBits(d1) != Double.doubleToLongBits(d2)) {
2098 return false;
2099 }
2100 }
2101 return ScriptRuntime.shallowEq(currentValue, newValue);
2102 }
2103
2104 protected int applyDescriptorToAttributeBitset(int attributes,
2105 ScriptableObject desc)
2106 {
2107 Object enumerable = getProperty(desc, "enumerable");
2108 if (enumerable != NOT_FOUND) {
2109 attributes = ScriptRuntime.toBoolean(enumerable)
2110 ? attributes & ~DONTENUM : attributes | DONTENUM;
2111 }
2112
2113 Object writable = getProperty(desc, "writable");
2114 if (writable != NOT_FOUND) {
2115 attributes = ScriptRuntime.toBoolean(writable)
2116 ? attributes & ~READONLY : attributes | READONLY;
2117 }
2118
2119 Object configurable = getProperty(desc, "configurable");
2120 if (configurable != NOT_FOUND) {
2121 attributes = ScriptRuntime.toBoolean(configurable)
2122 ? attributes & ~PERMANENT : attributes | PERMANENT;
2123 }
2124
2125 return attributes;
2126 }
2127
2128 /**
2129 * Implements IsDataDescriptor as described in ES5 8.10.2
2130 * @param desc a property descriptor
2131 * @return true if this is a data descriptor.
2132 */
2133 protected boolean isDataDescriptor(ScriptableObject desc) {
2134 return hasProperty(desc, "value") || hasProperty(desc, "writable");
2135 }
2136
2137 /**
2138 * Implements IsAccessorDescriptor as described in ES5 8.10.1
2139 * @param desc a property descriptor
2140 * @return true if this is an accessor descriptor.
2141 */
2142 protected boolean isAccessorDescriptor(ScriptableObject desc) {
2143 return hasProperty(desc, "get") || hasProperty(desc, "set");
2144 }
2145
2146 /**
2147 * Implements IsGenericDescriptor as described in ES5 8.10.3
2148 * @param desc a property descriptor
2149 * @return true if this is a generic descriptor.
2150 */
2151 protected boolean isGenericDescriptor(ScriptableObject desc) {
2152 return !isDataDescriptor(desc) && !isAccessorDescriptor(desc);
2153 }
2154
2155 protected static Scriptable ensureScriptable(Object arg) {
2156 if ( !(arg instanceof Scriptable) )
2157 throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg));
2158 return (Scriptable) arg;
2159 }
2160
2161 protected static SymbolScriptable ensureSymbolScriptable(Object arg) {
2162 if ( !(arg instanceof SymbolScriptable) )
2163 throw ScriptRuntime.typeError1("msg.object.not.symbolscriptable", ScriptRuntime.typeof(arg));
2164 return (SymbolScriptable) arg;
2165 }
2166
2167 protected static ScriptableObject ensureScriptableObject(Object arg) {
2168 if ( !(arg instanceof ScriptableObject) )
2169 throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg));
2170 return (ScriptableObject) arg;
2171 }
2172
2173 /**
2174 * Search for names in a class, adding the resulting methods
2175 * as properties.
2176 *
2177 * <p> Uses reflection to find the methods of the given names. Then
2178 * FunctionObjects are constructed from the methods found, and
2179 * are added to this object as properties with the given names.
2180 *
2181 * @param names the names of the Methods to add as function properties
2182 * @param clazz the class to search for the Methods
2183 * @param attributes the attributes of the new properties
2184 * @see org.mozilla.javascript.FunctionObject
2185 */
2186 public void defineFunctionProperties(String[] names, Class<?> clazz,
2187 int attributes)
2188 {
2189 Method[] methods = FunctionObject.getMethodList(clazz);
2190 for (int i=0; i < names.length; i++) {
2191 String name = names[i];
2192 Method m = FunctionObject.findSingleMethod(methods, name);
2193 if (m == null) {
2194 throw Context.reportRuntimeError2(
2195 "msg.method.not.found", name, clazz.getName());
2196 }
2197 FunctionObject f = new FunctionObject(name, m, this);
2198 defineProperty(name, f, attributes);
2199 }
2200 }
2201
2202 /**
2203 * Get the Object.prototype property.
2204 * See ECMA 15.2.4.
2205 */
2206 public static Scriptable getObjectPrototype(Scriptable scope) {
2207 return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
2208 TopLevel.Builtins.Object);
2209 }
2210
2211 /**
2212 * Get the Function.prototype property.
2213 * See ECMA 15.3.4.
2214 */
2215 public static Scriptable getFunctionPrototype(Scriptable scope) {
2216 return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
2217 TopLevel.Builtins.Function);
2218 }
2219
2220 public static Scriptable getArrayPrototype(Scriptable scope) {
2221 return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
2222 TopLevel.Builtins.Array);
2223 }
2224
2225 /**
2226 * Get the prototype for the named class.
2227 *
2228 * For example, <code>getClassPrototype(s, "Date")</code> will first
2229 * walk up the parent chain to find the outermost scope, then will
2230 * search that scope for the Date constructor, and then will
2231 * return Date.prototype. If any of the lookups fail, or
2232 * the prototype is not a JavaScript object, then null will
2233 * be returned.
2234 *
2235 * @param scope an object in the scope chain
2236 * @param className the name of the constructor
2237 * @return the prototype for the named class, or null if it
2238 * cannot be found.
2239 */
2240 public static Scriptable getClassPrototype(Scriptable scope,
2241 String className)
2242 {
2243 scope = getTopLevelScope(scope);
2244 Object ctor = getProperty(scope, className);
2245 Object proto;
2246 if (ctor instanceof BaseFunction) {
2247 proto = ((BaseFunction)ctor).getPrototypeProperty();
2248 } else if (ctor instanceof Scriptable) {
2249 Scriptable ctorObj = (Scriptable)ctor;
2250 proto = ctorObj.get("prototype", ctorObj);
2251 } else {
2252 return null;
2253 }
2254 if (proto instanceof Scriptable) {
2255 return (Scriptable)proto;
2256 }
2257 return null;
2258 }
2259
2260 /**
2261 * Get the global scope.
2262 *
2263 * <p>Walks the parent scope chain to find an object with a null
2264 * parent scope (the global object).
2265 *
2266 * @param obj a JavaScript object
2267 * @return the corresponding global scope
2268 */
2269 public static Scriptable getTopLevelScope(Scriptable obj)
2270 {
2271 for (;;) {
2272 Scriptable parent = obj.getParentScope();
2273 if (parent == null) {
2274 return obj;
2275 }
2276 obj = parent;
2277 }
2278 }
2279
2280 public boolean isExtensible() {
2281 return isExtensible;
2282 }
2283
2284 public void preventExtensions() {
2285 isExtensible = false;
2286 }
2287
2288 /**
2289 * Seal this object.
2290 *
2291 * It is an error to add properties to or delete properties from
2292 * a sealed object. It is possible to change the value of an
2293 * existing property. Once an object is sealed it may not be unsealed.
2294 *
2295 * @since 1.4R3
2296 */
2297 public synchronized void sealObject() {
2298 if (count >= 0) {
2299 // Make sure all LazilyLoadedCtors are initialized before sealing.
2300 Slot slot = firstAdded;
2301 while (slot != null) {
2302 Object value = slot.value;
2303 if (value instanceof LazilyLoadedCtor) {
2304 LazilyLoadedCtor initializer = (LazilyLoadedCtor) value;
2305 try {
2306 initializer.init();
2307 } finally {
2308 slot.value = initializer.getValue();
2309 }
2310 }
2311 slot = slot.orderedNext;
2312 }
2313 count = ~count;
2314 }
2315 }
2316
2317 /**
2318 * Return true if this object is sealed.
2319 *
2320 * @return true if sealed, false otherwise.
2321 * @since 1.4R3
2322 * @see #sealObject()
2323 */
2324 public final boolean isSealed() {
2325 return count < 0;
2326 }
2327
2328 private void checkNotSealed(Object key, int index)
2329 {
2330 if (!isSealed())
2331 return;
2332
2333 String str = (key != null) ? key.toString() : Integer.toString(index);
2334 throw Context.reportRuntimeError1("msg.modify.sealed", str);
2335 }
2336
2337 /**
2338 * Gets a named property from an object or any object in its prototype chain.
2339 * <p>
2340 * Searches the prototype chain for a property named <code>name</code>.
2341 * <p>
2342 * @param obj a JavaScript object
2343 * @param name a property name
2344 * @return the value of a property with name <code>name</code> found in
2345 * <code>obj</code> or any object in its prototype chain, or
2346 * <code>Scriptable.NOT_FOUND</code> if not found
2347 * @since 1.5R2
2348 */
2349 public static Object getProperty(Scriptable obj, String name)
2350 {
2351 Scriptable start = obj;
2352 Object result;
2353 do {
2354 result = obj.get(name, start);
2355 if (result != Scriptable.NOT_FOUND)
2356 break;
2357 obj = obj.getPrototype();
2358 } while (obj != null);
2359 return result;
2360 }
2361
2362 /**
2363 * This is a version of getProperty that works with Symbols.
2364 */
2365 public static Object getProperty(Scriptable obj, Symbol key)
2366 {
2367 Scriptable start = obj;
2368 Object result;
2369 do {
2370 result = ensureSymbolScriptable(obj).get(key, start);
2371 if (result != Scriptable.NOT_FOUND)
2372 break;
2373 obj = obj.getPrototype();
2374 } while (obj != null);
2375 return result;
2376 }
2377
2378 /**
2379 * Gets an indexed property from an object or any object in its prototype
2380 * chain and coerces it to the requested Java type.
2381 * <p>
2382 * Searches the prototype chain for a property with integral index
2383 * <code>index</code>. Note that if you wish to look for properties with numerical
2384 * but non-integral indicies, you should use getProperty(Scriptable,String) with
2385 * the string value of the index.
2386 * <p>
2387 * @param s a JavaScript object
2388 * @param index an integral index
2389 * @param type the required Java type of the result
2390 * @return the value of a property with name <code>name</code> found in
2391 * <code>obj</code> or any object in its prototype chain, or
2392 * null if not found. Note that it does not return
2393 * {@link Scriptable#NOT_FOUND} as it can ordinarily not be
2394 * converted to most of the types.
2395 * @since 1.7R3
2396 */
2397 public static <T> T getTypedProperty(Scriptable s, int index, Class<T> type) {
2398 Object val = getProperty(s, index);
2399 if(val == Scriptable.NOT_FOUND) {
2400 val = null;
2401 }
2402 return type.cast(Context.jsToJava(val, type));
2403 }
2404
2405 /**
2406 * Gets an indexed property from an object or any object in its prototype chain.
2407 * <p>
2408 * Searches the prototype chain for a property with integral index
2409 * <code>index</code>. Note that if you wish to look for properties with numerical
2410 * but non-integral indicies, you should use getProperty(Scriptable,String) with
2411 * the string value of the index.
2412 * <p>
2413 * @param obj a JavaScript object
2414 * @param index an integral index
2415 * @return the value of a property with index <code>index</code> found in
2416 * <code>obj</code> or any object in its prototype chain, or
2417 * <code>Scriptable.NOT_FOUND</code> if not found
2418 * @since 1.5R2
2419 */
2420 public static Object getProperty(Scriptable obj, int index)
2421 {
2422 Scriptable start = obj;
2423 Object result;
2424 do {
2425 result = obj.get(index, start);
2426 if (result != Scriptable.NOT_FOUND)
2427 break;
2428 obj = obj.getPrototype();
2429 } while (obj != null);
2430 return result;
2431 }
2432
2433 /**
2434 * Gets a named property from an object or any object in its prototype chain
2435 * and coerces it to the requested Java type.
2436 * <p>
2437 * Searches the prototype chain for a property named <code>name</code>.
2438 * <p>
2439 * @param s a JavaScript object
2440 * @param name a property name
2441 * @param type the required Java type of the result
2442 * @return the value of a property with name <code>name</code> found in
2443 * <code>obj</code> or any object in its prototype chain, or
2444 * null if not found. Note that it does not return
2445 * {@link Scriptable#NOT_FOUND} as it can ordinarily not be
2446 * converted to most of the types.
2447 * @since 1.7R3
2448 */
2449 public static <T> T getTypedProperty(Scriptable s, String name, Class<T> type) {
2450 Object val = getProperty(s, name);
2451 if(val == Scriptable.NOT_FOUND) {
2452 val = null;
2453 }
2454 return type.cast(Context.jsToJava(val, type));
2455 }
2456
2457 /**
2458 * Returns whether a named property is defined in an object or any object
2459 * in its prototype chain.
2460 * <p>
2461 * Searches the prototype chain for a property named <code>name</code>.
2462 * <p>
2463 * @param obj a JavaScript object
2464 * @param name a property name
2465 * @return the true if property was found
2466 * @since 1.5R2
2467 */
2468 public static boolean hasProperty(Scriptable obj, String name)
2469 {
2470 return null != getBase(obj, name);
2471 }
2472
2473 /**
2474 * If hasProperty(obj, name) would return true, then if the property that
2475 * was found is compatible with the new property, this method just returns.
2476 * If the property is not compatible, then an exception is thrown.
2477 *
2478 * A property redefinition is incompatible if the first definition was a
2479 * const declaration or if this one is. They are compatible only if neither
2480 * was const.
2481 */
2482 public static void redefineProperty(Scriptable obj, String name,
2483 boolean isConst)
2484 {
2485 Scriptable base = getBase(obj, name);
2486 if (base == null)
2487 return;
2488 if (base instanceof ConstProperties) {
2489 ConstProperties cp = (ConstProperties)base;
2490
2491 if (cp.isConst(name))
2492 throw ScriptRuntime.typeError1("msg.const.redecl", name);
2493 }
2494 if (isConst)
2495 throw ScriptRuntime.typeError1("msg.var.redecl", name);
2496 }
2497 /**
2498 * Returns whether an indexed property is defined in an object or any object
2499 * in its prototype chain.
2500 * <p>
2501 * Searches the prototype chain for a property with index <code>index</code>.
2502 * <p>
2503 * @param obj a JavaScript object
2504 * @param index a property index
2505 * @return the true if property was found
2506 * @since 1.5R2
2507 */
2508 public static boolean hasProperty(Scriptable obj, int index)
2509 {
2510 return null != getBase(obj, index);
2511 }
2512
2513 /**
2514 * A version of hasProperty for properties with Symbol keys.
2515 */
2516 public static boolean hasProperty(Scriptable obj, Symbol key)
2517 {
2518 return null != getBase(obj, key);
2519 }
2520
2521 /**
2522 * Puts a named property in an object or in an object in its prototype chain.
2523 * <p>
2524 * Searches for the named property in the prototype chain. If it is found,
2525 * the value of the property in <code>obj</code> is changed through a call
2526 * to {@link Scriptable#put(String, Scriptable, Object)} on the
2527 * prototype passing <code>obj</code> as the <code>start</code> argument.
2528 * This allows the prototype to veto the property setting in case the
2529 * prototype defines the property with [[ReadOnly]] attribute. If the
2530 * property is not found, it is added in <code>obj</code>.
2531 * @param obj a JavaScript object
2532 * @param name a property name
2533 * @param value any JavaScript value accepted by Scriptable.put
2534 * @since 1.5R2
2535 */
2536 public static void putProperty(Scriptable obj, String name, Object value)
2537 {
2538 Scriptable base = getBase(obj, name);
2539 if (base == null)
2540 base = obj;
2541 base.put(name, obj, value);
2542 }
2543
2544 /**
2545 * This is a version of putProperty for Symbol keys.
2546 */
2547 public static void putProperty(Scriptable obj, Symbol key, Object value)
2548 {
2549 Scriptable base = getBase(obj, key);
2550 if (base == null)
2551 base = obj;
2552 ensureSymbolScriptable(base).put(key, obj, value);
2553 }
2554
2555 /**
2556 * Puts a named property in an object or in an object in its prototype chain.
2557 * <p>
2558 * Searches for the named property in the prototype chain. If it is found,
2559 * the value of the property in <code>obj</code> is changed through a call
2560 * to {@link Scriptable#put(String, Scriptable, Object)} on the
2561 * prototype passing <code>obj</code> as the <code>start</code> argument.
2562 * This allows the prototype to veto the property setting in case the
2563 * prototype defines the property with [[ReadOnly]] attribute. If the
2564 * property is not found, it is added in <code>obj</code>.
2565 * @param obj a JavaScript object
2566 * @param name a property name
2567 * @param value any JavaScript value accepted by Scriptable.put
2568 * @since 1.5R2
2569 */
2570 public static void putConstProperty(Scriptable obj, String name, Object value)
2571 {
2572 Scriptable base = getBase(obj, name);
2573 if (base == null)
2574 base = obj;
2575 if (base instanceof ConstProperties)
2576 ((ConstProperties)base).putConst(name, obj, value);
2577 }
2578
2579 /**
2580 * Puts an indexed property in an object or in an object in its prototype chain.
2581 * <p>
2582 * Searches for the indexed property in the prototype chain. If it is found,
2583 * the value of the property in <code>obj</code> is changed through a call
2584 * to {@link Scriptable#put(int, Scriptable, Object)} on the prototype
2585 * passing <code>obj</code> as the <code>start</code> argument. This allows
2586 * the prototype to veto the property setting in case the prototype defines
2587 * the property with [[ReadOnly]] attribute. If the property is not found,
2588 * it is added in <code>obj</code>.
2589 * @param obj a JavaScript object
2590 * @param index a property index
2591 * @param value any JavaScript value accepted by Scriptable.put
2592 * @since 1.5R2
2593 */
2594 public static void putProperty(Scriptable obj, int index, Object value)
2595 {
2596 Scriptable base = getBase(obj, index);
2597 if (base == null)
2598 base = obj;
2599 base.put(index, obj, value);
2600 }
2601
2602 /**
2603 * Removes the property from an object or its prototype chain.
2604 * <p>
2605 * Searches for a property with <code>name</code> in obj or
2606 * its prototype chain. If it is found, the object's delete
2607 * method is called.
2608 * @param obj a JavaScript object
2609 * @param name a property name
2610 * @return true if the property doesn't exist or was successfully removed
2611 * @since 1.5R2
2612 */
2613 public static boolean deleteProperty(Scriptable obj, String name)
2614 {
2615 Scriptable base = getBase(obj, name);
2616 if (base == null)
2617 return true;
2618 base.delete(name);
2619 return !base.has(name, obj);
2620 }
2621
2622 /**
2623 * Removes the property from an object or its prototype chain.
2624 * <p>
2625 * Searches for a property with <code>index</code> in obj or
2626 * its prototype chain. If it is found, the object's delete
2627 * method is called.
2628 * @param obj a JavaScript object
2629 * @param index a property index
2630 * @return true if the property doesn't exist or was successfully removed
2631 * @since 1.5R2
2632 */
2633 public static boolean deleteProperty(Scriptable obj, int index)
2634 {
2635 Scriptable base = getBase(obj, index);
2636 if (base == null)
2637 return true;
2638 base.delete(index);
2639 return !base.has(index, obj);
2640 }
2641
2642 /**
2643 * Returns an array of all ids from an object and its prototypes.
2644 * <p>
2645 * @param obj a JavaScript object
2646 * @return an array of all ids from all object in the prototype chain.
2647 * If a given id occurs multiple times in the prototype chain,
2648 * it will occur only once in this list.
2649 * @since 1.5R2
2650 */
2651 public static Object[] getPropertyIds(Scriptable obj)
2652 {
2653 if (obj == null) {
2654 return ScriptRuntime.emptyArgs;
2655 }
2656 Object[] result = obj.getIds();
2657 ObjToIntMap map = null;
2658 for (;;) {
2659 obj = obj.getPrototype();
2660 if (obj == null) {
2661 break;
2662 }
2663 Object[] ids = obj.getIds();
2664 if (ids.length == 0) {
2665 continue;
2666 }
2667 if (map == null) {
2668 if (result.length == 0) {
2669 result = ids;
2670 continue;
2671 }
2672 map = new ObjToIntMap(result.length + ids.length);
2673 for (int i = 0; i != result.length; ++i) {
2674 map.intern(result[i]);
2675 }
2676 result = null; // Allow to GC the result
2677 }
2678 for (int i = 0; i != ids.length; ++i) {
2679 map.intern(ids[i]);
2680 }
2681 }
2682 if (map != null) {
2683 result = map.getKeys();
2684 }
2685 return result;
2686 }
2687
2688 /**
2689 * Call a method of an object.
2690 * @param obj the JavaScript object
2691 * @param methodName the name of the function property
2692 * @param args the arguments for the call
2693 *
2694 * @see Context#getCurrentContext()
2695 */
2696 public static Object callMethod(Scriptable obj, String methodName,
2697 Object[] args)
2698 {
2699 return callMethod(null, obj, methodName, args);
2700 }
2701
2702 /**
2703 * Call a method of an object.
2704 * @param cx the Context object associated with the current thread.
2705 * @param obj the JavaScript object
2706 * @param methodName the name of the function property
2707 * @param args the arguments for the call
2708 */
2709 public static Object callMethod(Context cx, Scriptable obj,
2710 String methodName,
2711 Object[] args)
2712 {
2713 Object funObj = getProperty(obj, methodName);
2714 if (!(funObj instanceof Function)) {
2715 throw ScriptRuntime.notFunctionError(obj, methodName);
2716 }
2717 Function fun = (Function)funObj;
2718 // XXX: What should be the scope when calling funObj?
2719 // The following favor scope stored in the object on the assumption
2720 // that is more useful especially under dynamic scope setup.
2721 // An alternative is to check for dynamic scope flag
2722 // and use ScriptableObject.getTopLevelScope(fun) if the flag is not
2723 // set. But that require access to Context and messy code
2724 // so for now it is not checked.
2725 Scriptable scope = ScriptableObject.getTopLevelScope(obj);
2726 if (cx != null) {
2727 return fun.call(cx, scope, obj, args);
2728 } else {
2729 return Context.call(null, fun, scope, obj, args);
2730 }
2731 }
2732
2733 private static Scriptable getBase(Scriptable obj, String name)
2734 {
2735 do {
2736 if (obj.has(name, obj))
2737 break;
2738 obj = obj.getPrototype();
2739 } while(obj != null);
2740 return obj;
2741 }
2742
2743 private static Scriptable getBase(Scriptable obj, int index)
2744 {
2745 do {
2746 if (obj.has(index, obj))
2747 break;
2748 obj = obj.getPrototype();
2749 } while(obj != null);
2750 return obj;
2751 }
2752
2753 private static Scriptable getBase(Scriptable obj, Symbol key)
2754 {
2755 do {
2756 if (ensureSymbolScriptable(obj).has(key, obj))
2757 break;
2758 obj = obj.getPrototype();
2759 } while(obj != null);
2760 return obj;
2761 }
2762
2763 /**
2764 * Get arbitrary application-specific value associated with this object.
2765 * @param key key object to select particular value.
2766 * @see #associateValue(Object key, Object value)
2767 */
2768 public final Object getAssociatedValue(Object key)
2769 {
2770 Map<Object,Object> h = associatedValues;
2771 if (h == null)
2772 return null;
2773 return h.get(key);
2774 }
2775
2776 /**
2777 * Get arbitrary application-specific value associated with the top scope
2778 * of the given scope.
2779 * The method first calls {@link #getTopLevelScope(Scriptable scope)}
2780 * and then searches the prototype chain of the top scope for the first
2781 * object containing the associated value with the given key.
2782 *
2783 * @param scope the starting scope.
2784 * @param key key object to select particular value.
2785 * @see #getAssociatedValue(Object key)
2786 */
2787 public static Object getTopScopeValue(Scriptable scope, Object key)
2788 {
2789 scope = ScriptableObject.getTopLevelScope(scope);
2790 for (;;) {
2791 if (scope instanceof ScriptableObject) {
2792 ScriptableObject so = (ScriptableObject)scope;
2793 Object value = so.getAssociatedValue(key);
2794 if (value != null) {
2795 return value;
2796 }
2797 }
2798 scope = scope.getPrototype();
2799 if (scope == null) {
2800 return null;
2801 }
2802 }
2803 }
2804
2805 /**
2806 * Associate arbitrary application-specific value with this object.
2807 * Value can only be associated with the given object and key only once.
2808 * The method ignores any subsequent attempts to change the already
2809 * associated value.
2810 * <p> The associated values are not serialized.
2811 * @param key key object to select particular value.
2812 * @param value the value to associate
2813 * @return the passed value if the method is called first time for the
2814 * given key or old value for any subsequent calls.
2815 * @see #getAssociatedValue(Object key)
2816 */
2817 public synchronized final Object associateValue(Object key, Object value)
2818 {
2819 if (value == null) throw new IllegalArgumentException();
2820 Map<Object,Object> h = associatedValues;
2821 if (h == null) {
2822 h = new HashMap<Object,Object>();
2823 associatedValues = h;
2824 }
2825 return Kit.initHash(h, key, value);
2826 }
2827
2828 /**
2829 *
2830 * @param key
2831 * @param index
2832 * @param start
2833 * @param value
2834 * @return false if this != start and no slot was found. true if this == start
2835 * or this != start and a READONLY slot was found.
2836 */
2837 private boolean putImpl(Object key, int index, Scriptable start,
2838 Object value)
2839 {
2840 // This method is very hot (basically called on each assignment)
2841 // so we inline the extensible/sealed checks below.
2842 if (!isExtensible) {
2843 Context cx = Context.getContext();
2844 if (cx.isStrictMode()) {
2845 throw ScriptRuntime.typeError0("msg.not.extensible");
2846 }
2847 }
2848 Slot slot;
2849 if (this != start) {
2850 slot = getSlot(key, index, SLOT_QUERY);
2851 if (slot == null) {
2852 return false;
2853 }
2854 } else if (!isExtensible) {
2855 slot = getSlot(key, index, SLOT_QUERY);
2856 if (slot == null) {
2857 return true;
2858 }
2859 } else {
2860 if (count < 0) checkNotSealed(key, index);
2861 slot = getSlot(key, index, SLOT_MODIFY);
2862 }
2863 return slot.setValue(value, this, start);
2864 }
2865
2866
2867 /**
2868 *
2869 * @param name
2870 * @param index
2871 * @param start
2872 * @param value
2873 * @param constFlag EMPTY means normal put. UNINITIALIZED_CONST means
2874 * defineConstProperty. READONLY means const initialization expression.
2875 * @return false if this != start and no slot was found. true if this == start
2876 * or this != start and a READONLY slot was found.
2877 */
2878 private boolean putConstImpl(String name, int index, Scriptable start,
2879 Object value, int constFlag)
2880 {
2881 assert (constFlag != EMPTY);
2882 if (!isExtensible) {
2883 Context cx = Context.getContext();
2884 if (cx.isStrictMode()) {
2885 throw ScriptRuntime.typeError0("msg.not.extensible");
2886 }
2887 }
2888 Slot slot;
2889 if (this != start) {
2890 slot = getSlot(name, index, SLOT_QUERY);
2891 if (slot == null) {
2892 return false;
2893 }
2894 } else if (!isExtensible()) {
2895 slot = getSlot(name, index, SLOT_QUERY);
2896 if (slot == null) {
2897 return true;
2898 }
2899 } else {
2900 checkNotSealed(name, index);
2901 // either const hoisted declaration or initialization
2902 slot = unwrapSlot(getSlot(name, index, SLOT_MODIFY_CONST));
2903 int attr = slot.getAttributes();
2904 if ((attr & READONLY) == 0)
2905 throw Context.reportRuntimeError1("msg.var.redecl", name);
2906 if ((attr & UNINITIALIZED_CONST) != 0) {
2907 slot.value = value;
2908 // clear the bit on const initialization
2909 if (constFlag != UNINITIALIZED_CONST)
2910 slot.setAttributes(attr & ~UNINITIALIZED_CONST);
2911 }
2912 return true;
2913 }
2914 return slot.setValue(value, this, start);
2915 }
2916
2917 private Slot findAttributeSlot(String name, int index, int accessType)
2918 {
2919 Slot slot = getSlot(name, index, accessType);
2920 if (slot == null) {
2921 String str = (name != null ? name : Integer.toString(index));
2922 throw Context.reportRuntimeError1("msg.prop.not.found", str);
2923 }
2924 return slot;
2925 }
2926
2927 private Slot findAttributeSlot(Symbol key, int accessType)
2928 {
2929 Slot slot = getSlot(key, 0, accessType);
2930 if (slot == null) {
2931 throw Context.reportRuntimeError1("msg.prop.not.found", key);
2932 }
2933 return slot;
2934 }
2935
2936 private static Slot unwrapSlot(Slot slot) {
2937 return (slot instanceof RelinkedSlot) ? ((RelinkedSlot)slot).slot : slot;
2938 }
2939
2940 /**
2941 * Locate the slot with given name or index. Depending on the accessType
2942 * parameter and the current slot status, a new slot may be allocated.
2943 *
2944 * @param key either a String or a Symbol object that identifies the property
2945 * @param index index or 0 if slot holds property name.
2946 */
2947 private Slot getSlot(Object key, int index, int accessType)
2948 {
2949 // Check the hashtable without using synchronization
2950 Slot[] slotsLocalRef = slots; // Get stable local reference
2951 if (slotsLocalRef == null && accessType == SLOT_QUERY) {
2952 return null;
2953 }
2954
2955 int indexOrHash = (key != null ? key.hashCode() : index);
2956 if (slotsLocalRef != null) {
2957 Slot slot;
2958 int slotIndex = getSlotIndex(slotsLocalRef.length, indexOrHash);
2959 for (slot = slotsLocalRef[slotIndex];
2960 slot != null;
2961 slot = slot.next) {
2962 Object skey = slot.name;
2963 if (indexOrHash == slot.indexOrHash &&
2964 (skey == key ||
2965 (key != null && key.equals(skey)))) {
2966 break;
2967 }
2968 }
2969 switch (accessType) {
2970 case SLOT_QUERY:
2971 return slot;
2972 case SLOT_MODIFY:
2973 case SLOT_MODIFY_CONST:
2974 if (slot != null)
2975 return slot;
2976 break;
2977 case SLOT_MODIFY_GETTER_SETTER:
2978 slot = unwrapSlot(slot);
2979 if (slot instanceof GetterSlot)
2980 return slot;
2981 break;
2982 case SLOT_CONVERT_ACCESSOR_TO_DATA:
2983 slot = unwrapSlot(slot);
2984 if ( !(slot instanceof GetterSlot) )
2985 return slot;
2986 break;
2987 }
2988 }
2989
2990 // A new slot has to be inserted or the old has to be replaced
2991 // by GetterSlot. Time to synchronize.
2992 return createSlot(key, indexOrHash, accessType);
2993 }
2994
2995 private synchronized Slot createSlot(Object key, int indexOrHash, int accessType) {
2996 Slot[] slotsLocalRef = slots;
2997 int insertPos;
2998 if (count == 0) {
2999 // Always throw away old slots if any on empty insert.
3000 slotsLocalRef = new Slot[INITIAL_SLOT_SIZE];
3001 slots = slotsLocalRef;
3002 insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash);
3003 } else {
3004 int tableSize = slotsLocalRef.length;
3005 insertPos = getSlotIndex(tableSize, indexOrHash);
3006 Slot prev = slotsLocalRef[insertPos];
3007 Slot slot = prev;
3008 while (slot != null) {
3009 if (slot.indexOrHash == indexOrHash &&
3010 (slot.name == key ||
3011 (key != null && key.equals(slot.name))))
3012 {
3013 break;
3014 }
3015 prev = slot;
3016 slot = slot.next;
3017 }
3018
3019 if (slot != null) {
3020 // A slot with same name/index already exists. This means that
3021 // a slot is being redefined from a value to a getter slot or
3022 // vice versa, or it could be a race in application code.
3023 // Check if we need to replace the slot depending on the
3024 // accessType flag and return the appropriate slot instance.
3025
3026 Slot inner = unwrapSlot(slot);
3027 Slot newSlot;
3028
3029 if (accessType == SLOT_MODIFY_GETTER_SETTER
3030 && !(inner instanceof GetterSlot)) {
3031 newSlot = new GetterSlot(key, indexOrHash, inner.getAttributes());
3032 } else if (accessType == SLOT_CONVERT_ACCESSOR_TO_DATA
3033 && (inner instanceof GetterSlot)) {
3034 newSlot = new Slot(key, indexOrHash, inner.getAttributes());
3035 } else if (accessType == SLOT_MODIFY_CONST) {
3036 return null;
3037 } else {
3038 return inner;
3039 }
3040
3041 newSlot.value = inner.value;
3042 newSlot.next = slot.next;
3043 // add new slot to linked list
3044 if (lastAdded != null) {
3045 lastAdded.orderedNext = newSlot;
3046 }
3047 if (firstAdded == null) {
3048 firstAdded = newSlot;
3049 }
3050 lastAdded = newSlot;
3051 // add new slot to hash table
3052 if (prev == slot) {
3053 slotsLocalRef[insertPos] = newSlot;
3054 } else {
3055 prev.next = newSlot;
3056 }
3057 // other housekeeping
3058 slot.markDeleted();
3059 return newSlot;
3060 } else {
3061 // Check if the table is not too full before inserting.
3062 if (4 * (count + 1) > 3 * slotsLocalRef.length) {
3063 // table size must be a power of 2, always grow by x2
3064 slotsLocalRef = new Slot[slotsLocalRef.length * 2];
3065 copyTable(slots, slotsLocalRef, count);
3066 slots = slotsLocalRef;
3067 insertPos = getSlotIndex(slotsLocalRef.length,
3068 indexOrHash);
3069 }
3070 }
3071 }
3072 Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER
3073 ? new GetterSlot(key, indexOrHash, 0)
3074 : new Slot(key, indexOrHash, 0));
3075 if (accessType == SLOT_MODIFY_CONST)
3076 newSlot.setAttributes(CONST);
3077 ++count;
3078 // add new slot to linked list
3079 if (lastAdded != null)
3080 lastAdded.orderedNext = newSlot;
3081 if (firstAdded == null)
3082 firstAdded = newSlot;
3083 lastAdded = newSlot;
3084 // add new slot to hash table, return it
3085 addKnownAbsentSlot(slotsLocalRef, newSlot, insertPos);
3086 return newSlot;
3087 }
3088
3089 private synchronized void removeSlot(Object key, int index) {
3090 int indexOrHash = (key != null ? key.hashCode() : index);
3091
3092 Slot[] slotsLocalRef = slots;
3093 if (count != 0) {
3094 int tableSize = slotsLocalRef.length;
3095 int slotIndex = getSlotIndex(tableSize, indexOrHash);
3096 Slot prev = slotsLocalRef[slotIndex];
3097 Slot slot = prev;
3098 while (slot != null) {
3099 if (slot.indexOrHash == indexOrHash &&
3100 (slot.name == key ||
3101 (key != null && key.equals(slot.name))))
3102 {
3103 break;
3104 }
3105 prev = slot;
3106 slot = slot.next;
3107 }
3108 if (slot != null) {
3109 // non-configurable
3110 if ((slot.getAttributes() & PERMANENT) != 0) {
3111 Context cx = Context.getContext();
3112 if (cx.isStrictMode()) {
3113 throw ScriptRuntime.typeError1("msg.delete.property.with.configurable.false", key);
3114 }
3115 return;
3116 }
3117 count--;
3118 // remove slot from hash table
3119 if (prev == slot) {
3120 slotsLocalRef[slotIndex] = slot.next;
3121 } else {
3122 prev.next = slot.next;
3123 }
3124
3125 // remove from ordered list. Previously this was done lazily in
3126 // getIds() but delete is an infrequent operation so O(n)
3127 // should be ok
3128
3129 // ordered list always uses the actual slot
3130 Slot deleted = unwrapSlot(slot);
3131 if (deleted == firstAdded) {
3132 prev = null;
3133 firstAdded = deleted.orderedNext;
3134 } else {
3135 prev = firstAdded;
3136 while (prev.orderedNext != deleted) {
3137 prev = prev.orderedNext;
3138 }
3139 prev.orderedNext = deleted.orderedNext;
3140 }
3141 if (deleted == lastAdded) {
3142 lastAdded = prev;
3143 }
3144
3145 // Mark the slot as removed.
3146 slot.markDeleted();
3147 }
3148 }
3149 }
3150
3151 private static int getSlotIndex(int tableSize, int indexOrHash)
3152 {
3153 // tableSize is a power of 2
3154 return indexOrHash & (tableSize - 1);
3155 }
3156
3157 // Must be inside synchronized (this)
3158 private static void copyTable(Slot[] oldSlots, Slot[] newSlots, int count)
3159 {
3160 if (count == 0) throw Kit.codeBug();
3161
3162 int tableSize = newSlots.length;
3163 int i = oldSlots.length;
3164 for (;;) {
3165 --i;
3166 Slot slot = oldSlots[i];
3167 while (slot != null) {
3168 int insertPos = getSlotIndex(tableSize, slot.indexOrHash);
3169 // If slot has next chain in old table use a new
3170 // RelinkedSlot wrapper to keep old table valid
3171 Slot insSlot = slot.next == null ? slot : new RelinkedSlot(slot);
3172 addKnownAbsentSlot(newSlots, insSlot, insertPos);
3173 slot = slot.next;
3174 if (--count == 0)
3175 return;
3176 }
3177 }
3178 }
3179
3180 /**
3181 * Add slot with keys that are known to absent from the table.
3182 * This is an optimization to use when inserting into empty table,
3183 * after table growth or during deserialization.
3184 */
3185 private static void addKnownAbsentSlot(Slot[] slots, Slot slot,
3186 int insertPos)
3187 {
3188 if (slots[insertPos] == null) {
3189 slots[insertPos] = slot;
3190 } else {
3191 Slot prev = slots[insertPos];
3192 Slot next = prev.next;
3193 while (next != null) {
3194 prev = next;
3195 next = prev.next;
3196 }
3197 prev.next = slot;
3198 }
3199 }
3200
3201 Object[] getIds(boolean getNonEnumerable, boolean getSymbols) {
3202 Slot[] s = slots;
3203 Object[] a;
3204 int externalLen = (externalData == null ? 0 : externalData.getArrayLength());
3205
3206 if (externalLen == 0) {
3207 a = ScriptRuntime.emptyArgs;
3208 } else {
3209 a = new Object[externalLen];
3210 for (int i = 0; i < externalLen; i++) {
3211 a[i] = Integer.valueOf(i);
3212 }
3213 }
3214 if (s == null) {
3215 return a;
3216 }
3217
3218 int c = externalLen;
3219 Slot slot = firstAdded;
3220 while (slot != null && slot.wasDeleted) {
3221 // we used to removed deleted slots from the linked list here
3222 // but this is now done in removeSlot(). There may still be deleted
3223 // slots (e.g. from slot conversion) but we don't want to mess
3224 // with the list in unsynchronized code.
3225 slot = slot.orderedNext;
3226 }
3227 while (slot != null) {
3228 if ((getNonEnumerable || (slot.getAttributes() & DONTENUM) == 0) &&
3229 (getSymbols || !(slot.name instanceof Symbol))) {
3230 if (c == externalLen) {
3231 // Special handling to combine external array with additional properties
3232 Object[] oldA = a;
3233 a = new Object[s.length + externalLen];
3234 if (oldA != null) {
3235 System.arraycopy(oldA, 0, a, 0, externalLen);
3236 }
3237 }
3238 a[c++] = slot.name != null
3239 ? slot.name
3240 : Integer.valueOf(slot.indexOrHash);
3241 }
3242 slot = slot.orderedNext;
3243 while (slot != null && slot.wasDeleted) {
3244 // skip deleted slots, see comment above
3245 slot = slot.orderedNext;
3246 }
3247 }
3248 if (c == (a.length + externalLen)) {
3249 return a;
3250 }
3251 Object[] result = new Object[c];
3252 System.arraycopy(a, 0, result, 0, c);
3253
3254 Context cx = Context.getCurrentContext();
3255 if ((cx != null) && cx.hasFeature(Context.FEATURE_ENUMERATE_IDS_FIRST)) {
3256 // Move all the numeric IDs to the front in numeric order
3257 Arrays.sort(result, KEY_COMPARATOR);
3258 }
3259
3260 return result;
3261 }
3262
3263 private synchronized void writeObject(ObjectOutputStream out)
3264 throws IOException
3265 {
3266 out.defaultWriteObject();
3267 int objectsCount = count;
3268 if (objectsCount < 0) {
3269 // "this" was sealed
3270 objectsCount = ~objectsCount;
3271 }
3272 if (objectsCount == 0) {
3273 out.writeInt(0);
3274 } else {
3275 out.writeInt(slots.length);
3276 Slot slot = firstAdded;
3277 while (slot != null && slot.wasDeleted) {
3278 // as long as we're traversing the order-added linked list,
3279 // remove deleted slots
3280 slot = slot.orderedNext;
3281 }
3282 firstAdded = slot;
3283 while (slot != null) {
3284 out.writeObject(slot);
3285 Slot next = slot.orderedNext;
3286 while (next != null && next.wasDeleted) {
3287 // remove deleted slots
3288 next = next.orderedNext;
3289 }
3290 slot.orderedNext = next;
3291 slot = next;
3292 }
3293 }
3294 }
3295
3296 private void readObject(ObjectInputStream in)
3297 throws IOException, ClassNotFoundException
3298 {
3299 in.defaultReadObject();
3300
3301 int tableSize = in.readInt();
3302 if (tableSize != 0) {
3303 // If tableSize is not a power of 2 find the closest
3304 // power of 2 >= the original size.
3305 if ((tableSize & (tableSize - 1)) != 0) {
3306 if (tableSize > 1 << 30)
3307 throw new RuntimeException("Property table overflow");
3308 int newSize = INITIAL_SLOT_SIZE;
3309 while (newSize < tableSize)
3310 newSize <<= 1;
3311 tableSize = newSize;
3312 }
3313 slots = new Slot[tableSize];
3314 int objectsCount = count;
3315 if (objectsCount < 0) {
3316 // "this" was sealed
3317 objectsCount = ~objectsCount;
3318 }
3319 Slot prev = null;
3320 for (int i=0; i != objectsCount; ++i) {
3321 lastAdded = (Slot)in.readObject();
3322 if (i==0) {
3323 firstAdded = lastAdded;
3324 } else {
3325 prev.orderedNext = lastAdded;
3326 }
3327 int slotIndex = getSlotIndex(tableSize, lastAdded.indexOrHash);
3328 addKnownAbsentSlot(slots, lastAdded, slotIndex);
3329 prev = lastAdded;
3330 }
3331 }
3332 }
3333
3334 protected ScriptableObject getOwnPropertyDescriptor(Context cx, Object id) {
3335 Slot slot = getSlot(cx, id, SLOT_QUERY);
3336 if (slot == null) return null;
3337 Scriptable scope = getParentScope();
3338 return slot.getPropertyDescriptor(cx, (scope == null ? this : scope));
3339 }
3340
3341 protected Slot getSlot(Context cx, Object id, int accessType) {
3342 if (id instanceof Symbol) {
3343 return getSlot(id, 0, accessType);
3344 }
3345 String name = ScriptRuntime.toStringIdOrIndex(cx, id);
3346 if (name == null) {
3347 return getSlot(null, ScriptRuntime.lastIndexResult(cx), accessType);
3348 } else {
3349 return getSlot(name, 0, accessType);
3350 }
3351 }
3352
3353 // Partial implementation of java.util.Map. See NativeObject for
3354 // a subclass that implements java.util.Map.
3355
3356 public int size() {
3357 return count < 0 ? ~count : count;
3358 }
3359
3360 public boolean isEmpty() {
3361 return count == 0 || count == -1;
3362 }
3363
3364
3365 public Object get(Object key) {
3366 Object value = null;
3367 if (key instanceof String) {
3368 value = get((String) key, this);
3369 } else if (key instanceof Symbol) {
3370 value = get((Symbol) key, this);
3371 } else if (key instanceof Number) {
3372 value = get(((Number) key).intValue(), this);
3373 }
3374 if (value == Scriptable.NOT_FOUND || value == Undefined.instance) {
3375 return null;
3376 } else if (value instanceof Wrapper) {
3377 return ((Wrapper) value).unwrap();
3378 } else {
3379 return value;
3380 }
3381 }
3382
3383 private static final Comparator<Object> KEY_COMPARATOR = new KeyComparator();
3384
3385 /**
3386 * This comparator sorts property fields in spec-compliant order. Numeric ids first, in numeric
3387 * order, followed by string ids, in insertion order. Since this class already keeps string keys
3388 * in insertion-time order, we treat all as equal. The "Arrays.sort" method will then not
3389 * change their order, but simply move all the numeric properties to the front, since this
3390 * method is defined to be stable.
3391 */
3392 public static final class KeyComparator
3393 implements Comparator<Object>
3394 {
3395 @Override
3396 public int compare(Object o1, Object o2)
3397 {
3398 if (o1 instanceof Integer) {
3399 if (o2 instanceof Integer) {
3400 int i1 = (Integer) o1;
3401 int i2 = (Integer) o2;
3402 if (i1 < i2) {
3403 return -1;
3404 }
3405 if (i1 > i2) {
3406 return 1;
3407 }
3408 return 0;
3409 }
3410 return -1;
3411 }
3412 if (o2 instanceof Integer) {
3413 return 1;
3414 }
3415 return 0;
3416 }
3417 }
3418 }