source: webkit/trunk/JavaScriptCore/kjs/JSArray.cpp@ 37681

Last change on this file since 37681 was 37681, checked in by Darin Adler, 17 years ago

JavaScriptCore:

2008-10-18 Darin Adler <Darin Adler>

Reviewed by Oliver Hunt.

Remove casts from JSValue* to derived classes, replacing them with
calls to inline casting functions. These functions are also a bit
better than aidrect cast because they also do a runtime assertion.

Removed use of 0 as for JSValue*, changing call sites to use a
noValue() function instead.

Move things needed by classes derived from JSValue out of the class,
since the classes won't be deriving from JSValue any more soon.

I did most of these changes by changing JSValue to not be JSValue* any
more, then fixing a lot of the compilation problems, then rolling out
the JSValue change.

1.011x as fast on SunSpider (presumably due to some of the Machine.cpp changes)

  • API/APICast.h: Removed unneeded forward declarations.
  • API/JSCallbackObject.h: Added an asCallbackObject function for casting.
  • API/JSCallbackObjectFunctions.h: (JSC::JSCallbackObject::asCallbackObject): Added. (JSC::JSCallbackObject::getOwnPropertySlot): Use asObject. (JSC::JSCallbackObject::call): Use noValue. (JSC::JSCallbackObject::staticValueGetter): Use asCallbackObject. (JSC::JSCallbackObject::staticFunctionGetter): Ditto. (JSC::JSCallbackObject::callbackGetter): Ditto.
  • JavaScriptCore.xcodeproj/project.pbxproj: Added RegExpMatchesArray.h.
  • VM/CTI.cpp: (JSC::CTI::asInteger): Added. For use casting a JSValue to an integer. (JSC::CTI::emitGetArg): Use asInteger. (JSC::CTI::emitGetPutArg): Ditto. (JSC::CTI::getConstantImmediateNumericArg): Ditto. Also use noValue. (JSC::CTI::emitInitRegister): Use asInteger. (JSC::CTI::getDeTaggedConstantImmediate): Ditto. (JSC::CTI::compileOpCallInitializeCallFrame): Ditto. (JSC::CTI::compileOpCall): Ditto. (JSC::CTI::compileOpStrictEq): Ditto. (JSC::CTI::privateCompileMainPass): Ditto. (JSC::CTI::privateCompileGetByIdProto): Ditto. (JSC::CTI::privateCompileGetByIdChain): Ditto. (JSC::CTI::privateCompilePutByIdTransition): Ditto.
  • VM/CTI.h: Rewrite the ARG-related macros to use C++ casts instead of C casts and get rid of some extra parentheses. Addd declaration of asInteger.
  • VM/CodeGenerator.cpp: (JSC::CodeGenerator::emitEqualityOp): Use asString. (JSC::CodeGenerator::emitLoad): Use noValue. (JSC::CodeGenerator::findScopedProperty): Change globalObject argument to JSObject* instead of JSValue*. (JSC::CodeGenerator::emitResolve): Remove unneeded cast. (JSC::CodeGenerator::emitGetScopedVar): Use asCell. (JSC::CodeGenerator::emitPutScopedVar): Ditto.
  • VM/CodeGenerator.h: Changed out argument of findScopedProperty. Also change the JSValueMap to use PtrHash explicitly instead of getting it from DefaultHash.
  • VM/JSPropertyNameIterator.cpp: (JSC::JSPropertyNameIterator::toPrimitive): Use noValue.
  • VM/JSPropertyNameIterator.h: (JSC::JSPropertyNameIterator::next): Ditto.
  • VM/Machine.cpp: (JSC::fastIsNumber): Moved isImmediate check here instead of checking for 0 inside Heap::isNumber. Use asCell and asNumberCell. (JSC::fastToInt32): Ditto. (JSC::fastToUInt32): Ditto. (JSC::jsLess): Use asString. (JSC::jsLessEq): Ditto. (JSC::jsAdd): Ditto. (JSC::jsTypeStringForValue): Use asObject. (JSC::jsIsObjectType): Ditto. (JSC::jsIsFunctionType): Ditto. (JSC::inlineResolveBase): Use noValue. (JSC::Machine::callEval): Use asString. Initialize result to undefined, not 0. (JSC::Machine::Machine): Remove unneeded casts to JSCell*. (JSC::Machine::throwException): Use asObject. (JSC::Machine::debug): Remove explicit calls to the DebuggerCallFrame constructor. (JSC::Machine::checkTimeout): Use noValue. (JSC::cachePrototypeChain): Use asObject. (JSC::Machine::tryCachePutByID): Use asCell. (JSC::Machine::tryCacheGetByID): Use aCell and asObject. (JSC::Machine::privateExecute): Use noValue, asCell, asObject, asString, asArray, asActivation, asFunction. Changed code that creates call frames for host functions to pass 0 for the function pointer -- the call frame needs a JSFunction* and a host function object is not one. This was caught by the assertions in the casting functions. Also remove some unneeded casts in cases where two values are compared. (JSC::Machine::retrieveLastCaller): Use noValue. (JSC::Machine::tryCTICachePutByID): Use asCell. (JSC::Machine::tryCTICacheGetByID): Use aCell and asObject. (JSC::setUpThrowTrampolineReturnAddress): Added this function to restore the PIC-branch-avoidance that was recently lost. (JSC::Machine::cti_op_add): Use asString. (JSC::Machine::cti_op_instanceof): Use asCell and asObject. (JSC::Machine::cti_op_call_JSFunction): Use asFunction. (JSC::Machine::cti_op_call_NotJSFunction): Changed code to pass 0 for the function pointer, since we don't have a JSFunction. Use asObject. (JSC::Machine::cti_op_tear_off_activation): Use asActivation. (JSC::Machine::cti_op_construct_JSConstruct): Use asFunction and asObject. (JSC::Machine::cti_op_construct_NotJSConstruct): use asObject. (JSC::Machine::cti_op_get_by_val): Use asArray and asString. (JSC::Machine::cti_op_resolve_func): Use asPointer; this helps prepare us for a situation where JSValue is not a pointer. (JSC::Machine::cti_op_put_by_val): Use asArray. (JSC::Machine::cti_op_put_by_val_array): Ditto. (JSC::Machine::cti_op_resolve_global): Use asGlobalObject. (JSC::Machine::cti_op_post_inc): Change VM_CHECK_EXCEPTION_2 to VM_CHECK_EXCEPTION_AT_END, since there's no observable work done after that point. Also use asPointer. (JSC::Machine::cti_op_resolve_with_base): Use asPointer. (JSC::Machine::cti_op_post_dec): Change VM_CHECK_EXCEPTION_2 to VM_CHECK_EXCEPTION_AT_END, since there's no observable work done after that point. Also use asPointer. (JSC::Machine::cti_op_call_eval): Use asObject, noValue, and change VM_CHECK_EXCEPTION_ARG to VM_THROW_EXCEPTION_AT_END. (JSC::Machine::cti_op_throw): Change return value to a JSValue*. (JSC::Machine::cti_op_in): Use asObject. (JSC::Machine::cti_op_switch_char): Use asString. (JSC::Machine::cti_op_switch_string): Ditto. (JSC::Machine::cti_op_put_getter): Use asObject. (JSC::Machine::cti_op_put_setter): Ditto. (JSC::Machine::cti_vm_throw): Change return value to a JSValue*. Use noValue.
  • VM/Machine.h: Change return values of both cti_op_throw and cti_vm_throw to JSValue*.
  • VM/Register.h: Remove nullJSValue, which is the same thing as noValue(). Also removed unneeded definition of JSValue.
  • kjs/ArgList.h: Removed unneeded definition of JSValue.
  • kjs/Arguments.h: (JSC::asArguments): Added.
  • kjs/ArrayPrototype.cpp: (JSC::getProperty): Use noValue. (JSC::arrayProtoFuncToString): Use asArray. (JSC::arrayProtoFuncToLocaleString): Ditto. (JSC::arrayProtoFuncConcat): Ditto. (JSC::arrayProtoFuncPop): Ditto. Also removed unneeded initialization of the result, which is set in both sides of the branch. (JSC::arrayProtoFuncPush): Ditto. (JSC::arrayProtoFuncShift): Removed unneeded initialization of the result, which is set in both sides of the branch. (JSC::arrayProtoFuncSort): Use asArray.
  • kjs/BooleanObject.h: (JSC::asBooleanObject): Added.
  • kjs/BooleanPrototype.cpp: (JSC::booleanProtoFuncToString): Use asBooleanObject. (JSC::booleanProtoFuncValueOf): Ditto.
  • kjs/CallData.cpp: (JSC::call): Use asObject and asFunction.
  • kjs/ConstructData.cpp: (JSC::construct): Ditto.
  • kjs/DateConstructor.cpp: (JSC::constructDate): Use asDateInstance.
  • kjs/DateInstance.h: (JSC::asDateInstance): Added.
  • kjs/DatePrototype.cpp: (JSC::dateProtoFuncToString): Use asDateInstance. (JSC::dateProtoFuncToUTCString): Ditto. (JSC::dateProtoFuncToDateString): Ditto. (JSC::dateProtoFuncToTimeString): Ditto. (JSC::dateProtoFuncToLocaleString): Ditto. (JSC::dateProtoFuncToLocaleDateString): Ditto. (JSC::dateProtoFuncToLocaleTimeString): Ditto. (JSC::dateProtoFuncValueOf): Ditto. (JSC::dateProtoFuncGetTime): Ditto. (JSC::dateProtoFuncGetFullYear): Ditto. (JSC::dateProtoFuncGetUTCFullYear): Ditto. (JSC::dateProtoFuncToGMTString): Ditto. (JSC::dateProtoFuncGetMonth): Ditto. (JSC::dateProtoFuncGetUTCMonth): Ditto. (JSC::dateProtoFuncGetDate): Ditto. (JSC::dateProtoFuncGetUTCDate): Ditto. (JSC::dateProtoFuncGetDay): Ditto. (JSC::dateProtoFuncGetUTCDay): Ditto. (JSC::dateProtoFuncGetHours): Ditto. (JSC::dateProtoFuncGetUTCHours): Ditto. (JSC::dateProtoFuncGetMinutes): Ditto. (JSC::dateProtoFuncGetUTCMinutes): Ditto. (JSC::dateProtoFuncGetSeconds): Ditto. (JSC::dateProtoFuncGetUTCSeconds): Ditto. (JSC::dateProtoFuncGetMilliSeconds): Ditto. (JSC::dateProtoFuncGetUTCMilliseconds): Ditto. (JSC::dateProtoFuncGetTimezoneOffset): Ditto. (JSC::dateProtoFuncSetTime): Ditto. (JSC::setNewValueFromTimeArgs): Ditto. (JSC::setNewValueFromDateArgs): Ditto. (JSC::dateProtoFuncSetYear): Ditto. (JSC::dateProtoFuncGetYear): Ditto.
  • kjs/DebuggerCallFrame.cpp: (JSC::DebuggerCallFrame::thisObject): Use asObject. (JSC::DebuggerCallFrame::evaluate): Use noValue.
  • kjs/DebuggerCallFrame.h: Added a constructor that takes only a callFrame.
  • kjs/ExecState.h: (JSC::ExecState::clearException): Use noValue.
  • kjs/FunctionPrototype.cpp: (JSC::functionProtoFuncToString): Use asFunction. (JSC::functionProtoFuncApply): Use asArguments and asArray.
  • kjs/GetterSetter.cpp: (JSC::GetterSetter::getPrimitiveNumber): Use noValue.
  • kjs/GetterSetter.h: (JSC::asGetterSetter): Added.
  • kjs/InternalFunction.cpp: (JSC::InternalFunction::name): Use asString.
  • kjs/InternalFunction.h: (JSC::asInternalFunction): Added.
  • kjs/JSActivation.cpp: (JSC::JSActivation::argumentsGetter): Use asActivation.
  • kjs/JSActivation.h: (JSC::asActivation): Added.
  • kjs/JSArray.cpp: (JSC::JSArray::putSlowCase): Use noValue. (JSC::JSArray::deleteProperty): Ditto. (JSC::JSArray::increaseVectorLength): Ditto. (JSC::JSArray::setLength): Ditto. (JSC::JSArray::pop): Ditto. (JSC::JSArray::sort): Ditto. (JSC::JSArray::compactForSorting): Ditto.
  • kjs/JSArray.h: (JSC::asArray): Added.
  • kjs/JSCell.cpp: (JSC::JSCell::getJSNumber): Use noValue.
  • kjs/JSCell.h: (JSC::asCell): Added. (JSC::JSValue::asCell): Changed to not preserve const. Given the wide use of JSValue* and JSCell*, it's not really useful to use const. (JSC::JSValue::isNumber): Use asValue. (JSC::JSValue::isString): Ditto. (JSC::JSValue::isGetterSetter): Ditto. (JSC::JSValue::isObject): Ditto. (JSC::JSValue::getNumber): Ditto. (JSC::JSValue::getString): Ditto. (JSC::JSValue::getObject): Ditto. (JSC::JSValue::getCallData): Ditto. (JSC::JSValue::getConstructData): Ditto. (JSC::JSValue::getUInt32): Ditto. (JSC::JSValue::getTruncatedInt32): Ditto. (JSC::JSValue::getTruncatedUInt32): Ditto. (JSC::JSValue::mark): Ditto. (JSC::JSValue::marked): Ditto. (JSC::JSValue::toPrimitive): Ditto. (JSC::JSValue::getPrimitiveNumber): Ditto. (JSC::JSValue::toBoolean): Ditto. (JSC::JSValue::toNumber): Ditto. (JSC::JSValue::toString): Ditto. (JSC::JSValue::toObject): Ditto. (JSC::JSValue::toThisObject): Ditto. (JSC::JSValue::needsThisConversion): Ditto. (JSC::JSValue::toThisString): Ditto. (JSC::JSValue::getJSNumber): Ditto.
  • kjs/JSFunction.cpp: (JSC::JSFunction::argumentsGetter): Use asFunction. (JSC::JSFunction::callerGetter): Ditto. (JSC::JSFunction::lengthGetter): Ditto. (JSC::JSFunction::construct): Use asObject.
  • kjs/JSFunction.h: (JSC::asFunction): Added.
  • kjs/JSGlobalObject.cpp: (JSC::lastInPrototypeChain): Use asObject.
  • kjs/JSGlobalObject.h: (JSC::asGlobalObject): Added. (JSC::ScopeChainNode::globalObject): Use asGlobalObject.
  • kjs/JSImmediate.h: Added noValue, asPointer, and makeValue functions. Use rawValue, makeValue, and noValue consistently instead of doing reinterpret_cast in various functions.
  • kjs/JSNumberCell.h: (JSC::asNumberCell): Added. (JSC::JSValue::uncheckedGetNumber): Use asValue and asNumberCell. (JSC::JSValue::toJSNumber): Use asValue.
  • kjs/JSObject.cpp: (JSC::JSObject::put): Use asObject and asGetterSetter. (JSC::callDefaultValueFunction): Use noValue. (JSC::JSObject::defineGetter): Use asGetterSetter. (JSC::JSObject::defineSetter): Ditto. (JSC::JSObject::lookupGetter): Ditto. Also use asObject. (JSC::JSObject::lookupSetter): Ditto. (JSC::JSObject::hasInstance): Use asObject. (JSC::JSObject::fillGetterPropertySlot): Use asGetterSetter.
  • kjs/JSObject.h: (JSC::JSObject::getDirect): Use noValue. (JSC::asObject): Added. (JSC::JSValue::isObject): Use asValue. (JSC::JSObject::get): Removed unneeded const_cast. (JSC::JSObject::getPropertySlot): Use asObject. (JSC::JSValue::get): Removed unneeded const_cast. Use asValue, asCell, and asObject. (JSC::JSValue::put): Ditto. (JSC::JSObject::allocatePropertyStorageInline): Fixed spelling of "oldPropertStorage".
  • kjs/JSString.cpp: (JSC::JSString::getOwnPropertySlot): Use asObject.
  • kjs/JSString.h: (JSC::asString): Added. (JSC::JSValue::toThisJSString): Use asValue.
  • kjs/JSValue.h: Make PreferredPrimitiveType a top level enum instead of a member of JSValue. Added an asValue function that returns this. Removed overload of asCell for const. Use asValue instead of getting right at this.
  • kjs/ObjectPrototype.cpp: (JSC::objectProtoFuncIsPrototypeOf): Use asObject. (JSC::objectProtoFuncDefineGetter): Ditto. (JSC::objectProtoFuncDefineSetter): Ditto.
  • kjs/PropertySlot.h: (JSC::PropertySlot::PropertySlot): Take a const JSValue* so the callers don't have to worry about const. (JSC::PropertySlot::clearBase): Use noValue. (JSC::PropertySlot::clearValue): Ditto.
  • kjs/RegExpConstructor.cpp: (JSC::regExpConstructorDollar1): Use asRegExpConstructor. (JSC::regExpConstructorDollar2): Ditto. (JSC::regExpConstructorDollar3): Ditto. (JSC::regExpConstructorDollar4): Ditto. (JSC::regExpConstructorDollar5): Ditto. (JSC::regExpConstructorDollar6): Ditto. (JSC::regExpConstructorDollar7): Ditto. (JSC::regExpConstructorDollar8): Ditto. (JSC::regExpConstructorDollar9): Ditto. (JSC::regExpConstructorInput): Ditto. (JSC::regExpConstructorMultiline): Ditto. (JSC::regExpConstructorLastMatch): Ditto. (JSC::regExpConstructorLastParen): Ditto. (JSC::regExpConstructorLeftContext): Ditto. (JSC::regExpConstructorRightContext): Ditto. (JSC::setRegExpConstructorInput): Ditto. (JSC::setRegExpConstructorMultiline): Ditto. (JSC::constructRegExp): Use asObject.
  • kjs/RegExpConstructor.h: (JSC::asRegExpConstructor): Added.
  • kjs/RegExpObject.cpp: (JSC::regExpObjectGlobal): Use asRegExpObject. (JSC::regExpObjectIgnoreCase): Ditto. (JSC::regExpObjectMultiline): Ditto. (JSC::regExpObjectSource): Ditto. (JSC::regExpObjectLastIndex): Ditto. (JSC::setRegExpObjectLastIndex): Ditto. (JSC::callRegExpObject): Ditto.
  • kjs/RegExpObject.h: (JSC::asRegExpObject): Added.
  • kjs/RegExpPrototype.cpp: (JSC::regExpProtoFuncTest): Use asRegExpObject. (JSC::regExpProtoFuncExec): Ditto. (JSC::regExpProtoFuncCompile): Ditto. (JSC::regExpProtoFuncToString): Ditto.
  • kjs/StringObject.h: (JSC::StringObject::internalValue): Use asString. (JSC::asStringObject): Added.
  • kjs/StringPrototype.cpp: (JSC::stringProtoFuncReplace): Use asRegExpObject. (JSC::stringProtoFuncToString): Ue asStringObject. (JSC::stringProtoFuncMatch): Use asRegExpObject. (JSC::stringProtoFuncSearch): Ditto. (JSC::stringProtoFuncSplit): Ditto.
  • kjs/StructureID.cpp: (JSC::StructureID::getEnumerablePropertyNames): Use asObject. (JSC::StructureID::createCachedPrototypeChain): Ditto. (JSC::StructureIDChain::StructureIDChain): Use asCell and asObject.
  • kjs/collector.h: (JSC::Heap::isNumber): Removed null handling. This can only be called on valid cells. (JSC::Heap::cellBlock): Removed overload for const and non-const. Whether the JSCell* is const or not really should have no effect on whether you can modify the collector block it's in.
  • kjs/interpreter.cpp: (JSC::Interpreter::evaluate): Use noValue and noObject.
  • kjs/nodes.cpp: (JSC::FunctionCallResolveNode::emitCode): Use JSObject for the global object rather than JSValue. (JSC::PostfixResolveNode::emitCode): Ditto. (JSC::PrefixResolveNode::emitCode): Ditto. (JSC::ReadModifyResolveNode::emitCode): Ditto. (JSC::AssignResolveNode::emitCode): Ditto.
  • kjs/operations.h: (JSC::equalSlowCaseInline): Use asString, asCell, asNumberCell, (JSC::strictEqualSlowCaseInline): Ditto.

WebCore:

2008-10-18 Darin Adler <Darin Adler>

Reviewed by Oliver Hunt.

Update for change to make PreferredPrimitiveType no longer
a member of JSValue.

  • bridge/c/c_instance.cpp: (JSC::Bindings::CInstance::defaultValue): Removed JSValue:: prefix.
  • bridge/jni/jni_instance.cpp: (JavaInstance::defaultValue): Ditto.
  • bridge/objc/objc_instance.mm: (ObjcInstance::defaultValue): Ditto.
  • bridge/qt/qt_instance.cpp: (JSC::Bindings::QtInstance::defaultValue): Ditto.
  • bridge/runtime.h: Ditto. Also removed typedef.
  • Property svn:eol-style set to native
File size: 34.0 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
3 * Copyright (C) 2003, 2007, 2008 Apple Inc. All rights reserved.
4 * Copyright (C) 2003 Peter Kelly ([email protected])
5 * Copyright (C) 2006 Alexey Proskuryakov ([email protected])
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 *
21 */
22
23#include "config.h"
24#include "JSArray.h"
25
26#include "ArrayPrototype.h"
27#include "PropertyNameArray.h"
28#include <wtf/AVLTree.h>
29#include <wtf/Assertions.h>
30#include <operations.h>
31
32#define CHECK_ARRAY_CONSISTENCY 0
33
34using namespace std;
35
36namespace JSC {
37
38ASSERT_CLASS_FITS_IN_CELL(JSArray);
39
40// Overview of JSArray
41//
42// Properties of JSArray objects may be stored in one of three locations:
43// * The regular JSObject property map.
44// * A storage vector.
45// * A sparse map of array entries.
46//
47// Properties with non-numeric identifiers, with identifiers that are not representable
48// as an unsigned integer, or where the value is greater than MAX_ARRAY_INDEX
49// (specifically, this is only one property - the value 0xFFFFFFFFU as an unsigned 32-bit
50// integer) are not considered array indices and will be stored in the JSObject property map.
51//
52// All properties with a numeric identifer, representable as an unsigned integer i,
53// where (i <= MAX_ARRAY_INDEX), are an array index and will be stored in either the
54// storage vector or the sparse map. An array index i will be handled in the following
55// fashion:
56//
57// * Where (i < MIN_SPARSE_ARRAY_INDEX) the value will be stored in the storage vector.
58// * Where (MIN_SPARSE_ARRAY_INDEX <= i <= MAX_STORAGE_VECTOR_INDEX) the value will either
59// be stored in the storage vector or in the sparse array, depending on the density of
60// data that would be stored in the vector (a vector being used where at least
61// (1 / minDensityMultiplier) of the entries would be populated).
62// * Where (MAX_STORAGE_VECTOR_INDEX < i <= MAX_ARRAY_INDEX) the value will always be stored
63// in the sparse array.
64
65// The definition of MAX_STORAGE_VECTOR_LENGTH is dependant on the definition storageSize
66// function below - the MAX_STORAGE_VECTOR_LENGTH limit is defined such that the storage
67// size calculation cannot overflow. (sizeof(ArrayStorage) - sizeof(JSValue*)) +
68// (vectorLength * sizeof(JSValue*)) must be <= 0xFFFFFFFFU (which is maximum value of size_t).
69#define MAX_STORAGE_VECTOR_LENGTH static_cast<unsigned>((0xFFFFFFFFU - (sizeof(ArrayStorage) - sizeof(JSValue*))) / sizeof(JSValue*))
70
71// These values have to be macros to be used in max() and min() without introducing
72// a PIC branch in Mach-O binaries, see <rdar://problem/5971391>.
73#define MIN_SPARSE_ARRAY_INDEX 10000U
74#define MAX_STORAGE_VECTOR_INDEX (MAX_STORAGE_VECTOR_LENGTH - 1)
75// 0xFFFFFFFF is a bit weird -- is not an array index even though it's an integer.
76#define MAX_ARRAY_INDEX 0xFFFFFFFEU
77
78// Our policy for when to use a vector and when to use a sparse map.
79// For all array indices under MIN_SPARSE_ARRAY_INDEX, we always use a vector.
80// When indices greater than MIN_SPARSE_ARRAY_INDEX are involved, we use a vector
81// as long as it is 1/8 full. If more sparse than that, we use a map.
82static const unsigned minDensityMultiplier = 8;
83
84const ClassInfo JSArray::info = {"Array", 0, 0, 0};
85
86static inline size_t storageSize(unsigned vectorLength)
87{
88 ASSERT(vectorLength <= MAX_STORAGE_VECTOR_LENGTH);
89
90 // MAX_STORAGE_VECTOR_LENGTH is defined such that provided (vectorLength <= MAX_STORAGE_VECTOR_LENGTH)
91 // - as asserted above - the following calculation cannot overflow.
92 size_t size = (sizeof(ArrayStorage) - sizeof(JSValue*)) + (vectorLength * sizeof(JSValue*));
93 // Assertion to detect integer overflow in previous calculation (should not be possible, provided that
94 // MAX_STORAGE_VECTOR_LENGTH is correctly defined).
95 ASSERT(((size - (sizeof(ArrayStorage) - sizeof(JSValue*))) / sizeof(JSValue*) == vectorLength) && (size >= (sizeof(ArrayStorage) - sizeof(JSValue*))));
96
97 return size;
98}
99
100static inline unsigned increasedVectorLength(unsigned newLength)
101{
102 ASSERT(newLength <= MAX_STORAGE_VECTOR_LENGTH);
103
104 // Mathematically equivalent to:
105 // increasedLength = (newLength * 3 + 1) / 2;
106 // or:
107 // increasedLength = (unsigned)ceil(newLength * 1.5));
108 // This form is not prone to internal overflow.
109 unsigned increasedLength = newLength + (newLength >> 1) + (newLength & 1);
110 ASSERT(increasedLength >= newLength);
111
112 return min(increasedLength, MAX_STORAGE_VECTOR_LENGTH);
113}
114
115static inline bool isDenseEnoughForVector(unsigned length, unsigned numValues)
116{
117 return length / minDensityMultiplier <= numValues;
118}
119
120#if !CHECK_ARRAY_CONSISTENCY
121
122inline void JSArray::checkConsistency(ConsistencyCheckType)
123{
124}
125
126#endif
127
128JSArray::JSArray(PassRefPtr<StructureID> structureID)
129 : JSObject(structureID)
130{
131 unsigned initialCapacity = 0;
132
133 m_storage = static_cast<ArrayStorage*>(fastZeroedMalloc(storageSize(initialCapacity)));
134 m_fastAccessCutoff = 0;
135 m_storage->m_vectorLength = initialCapacity;
136 m_storage->m_length = 0;
137
138 checkConsistency();
139}
140
141JSArray::JSArray(PassRefPtr<StructureID> structure, unsigned initialLength)
142 : JSObject(structure)
143{
144 unsigned initialCapacity = min(initialLength, MIN_SPARSE_ARRAY_INDEX);
145
146 m_storage = static_cast<ArrayStorage*>(fastZeroedMalloc(storageSize(initialCapacity)));
147 m_fastAccessCutoff = 0;
148 m_storage->m_vectorLength = initialCapacity;
149 m_storage->m_length = initialLength;
150
151 Heap::heap(this)->reportExtraMemoryCost(initialCapacity * sizeof(JSValue*));
152
153 checkConsistency();
154}
155
156JSArray::JSArray(ExecState* exec, PassRefPtr<StructureID> structure, const ArgList& list)
157 : JSObject(structure)
158{
159 unsigned length = list.size();
160
161 m_fastAccessCutoff = length;
162
163 ArrayStorage* storage = static_cast<ArrayStorage*>(fastMalloc(storageSize(length)));
164
165 storage->m_vectorLength = length;
166 storage->m_numValuesInVector = length;
167 storage->m_sparseValueMap = 0;
168 storage->m_length = length;
169
170 size_t i = 0;
171 ArgList::const_iterator end = list.end();
172 for (ArgList::const_iterator it = list.begin(); it != end; ++it, ++i)
173 storage->m_vector[i] = (*it).jsValue(exec);
174
175 m_storage = storage;
176
177 // When the array is created non-empty, its cells are filled, so it's really no worse than
178 // a property map. Therefore don't report extra memory cost.
179
180 checkConsistency();
181}
182
183JSArray::~JSArray()
184{
185 checkConsistency(DestructorConsistencyCheck);
186
187 delete m_storage->m_sparseValueMap;
188 fastFree(m_storage);
189}
190
191bool JSArray::getOwnPropertySlot(ExecState* exec, unsigned i, PropertySlot& slot)
192{
193 ArrayStorage* storage = m_storage;
194
195 if (i >= storage->m_length) {
196 if (i > MAX_ARRAY_INDEX)
197 return getOwnPropertySlot(exec, Identifier::from(exec, i), slot);
198 return false;
199 }
200
201 if (i < storage->m_vectorLength) {
202 JSValue*& valueSlot = storage->m_vector[i];
203 if (valueSlot) {
204 slot.setValueSlot(&valueSlot);
205 return true;
206 }
207 } else if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
208 if (i >= MIN_SPARSE_ARRAY_INDEX) {
209 SparseArrayValueMap::iterator it = map->find(i);
210 if (it != map->end()) {
211 slot.setValueSlot(&it->second);
212 return true;
213 }
214 }
215 }
216
217 return false;
218}
219
220bool JSArray::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
221{
222 if (propertyName == exec->propertyNames().length) {
223 slot.setValue(jsNumber(exec, length()));
224 return true;
225 }
226
227 bool isArrayIndex;
228 unsigned i = propertyName.toArrayIndex(&isArrayIndex);
229 if (isArrayIndex)
230 return JSArray::getOwnPropertySlot(exec, i, slot);
231
232 return JSObject::getOwnPropertySlot(exec, propertyName, slot);
233}
234
235// ECMA 15.4.5.1
236void JSArray::put(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot& slot)
237{
238 bool isArrayIndex;
239 unsigned i = propertyName.toArrayIndex(&isArrayIndex);
240 if (isArrayIndex) {
241 put(exec, i, value);
242 return;
243 }
244
245 if (propertyName == exec->propertyNames().length) {
246 unsigned newLength = value->toUInt32(exec);
247 if (value->toNumber(exec) != static_cast<double>(newLength)) {
248 throwError(exec, RangeError, "Invalid array length.");
249 return;
250 }
251 setLength(newLength);
252 return;
253 }
254
255 JSObject::put(exec, propertyName, value, slot);
256}
257
258void JSArray::put(ExecState* exec, unsigned i, JSValue* value)
259{
260 checkConsistency();
261
262 unsigned length = m_storage->m_length;
263 if (i >= length && i <= MAX_ARRAY_INDEX) {
264 length = i + 1;
265 m_storage->m_length = length;
266 }
267
268 if (i < m_storage->m_vectorLength) {
269 JSValue*& valueSlot = m_storage->m_vector[i];
270 if (valueSlot) {
271 valueSlot = value;
272 checkConsistency();
273 return;
274 }
275 valueSlot = value;
276 if (++m_storage->m_numValuesInVector == m_storage->m_length)
277 m_fastAccessCutoff = m_storage->m_length;
278 checkConsistency();
279 return;
280 }
281
282 putSlowCase(exec, i, value);
283}
284
285NEVER_INLINE void JSArray::putSlowCase(ExecState* exec, unsigned i, JSValue* value)
286{
287 ArrayStorage* storage = m_storage;
288 SparseArrayValueMap* map = storage->m_sparseValueMap;
289
290 if (i >= MIN_SPARSE_ARRAY_INDEX) {
291 if (i > MAX_ARRAY_INDEX) {
292 PutPropertySlot slot;
293 put(exec, Identifier::from(exec, i), value, slot);
294 return;
295 }
296
297 // We miss some cases where we could compact the storage, such as a large array that is being filled from the end
298 // (which will only be compacted as we reach indices that are less than cutoff) - but this makes the check much faster.
299 if ((i > MAX_STORAGE_VECTOR_INDEX) || !isDenseEnoughForVector(i + 1, storage->m_numValuesInVector + 1)) {
300 if (!map) {
301 map = new SparseArrayValueMap;
302 storage->m_sparseValueMap = map;
303 }
304 map->set(i, value);
305 return;
306 }
307 }
308
309 // We have decided that we'll put the new item into the vector.
310 // Fast case is when there is no sparse map, so we can increase the vector size without moving values from it.
311 if (!map || map->isEmpty()) {
312 if (increaseVectorLength(i + 1)) {
313 storage = m_storage;
314 storage->m_vector[i] = value;
315 if (++storage->m_numValuesInVector == storage->m_length)
316 m_fastAccessCutoff = storage->m_length;
317 checkConsistency();
318 } else
319 throwOutOfMemoryError(exec);
320 return;
321 }
322
323 // Decide how many values it would be best to move from the map.
324 unsigned newNumValuesInVector = storage->m_numValuesInVector + 1;
325 unsigned newVectorLength = increasedVectorLength(i + 1);
326 for (unsigned j = max(storage->m_vectorLength, MIN_SPARSE_ARRAY_INDEX); j < newVectorLength; ++j)
327 newNumValuesInVector += map->contains(j);
328 if (i >= MIN_SPARSE_ARRAY_INDEX)
329 newNumValuesInVector -= map->contains(i);
330 if (isDenseEnoughForVector(newVectorLength, newNumValuesInVector)) {
331 unsigned proposedNewNumValuesInVector = newNumValuesInVector;
332 // If newVectorLength is already the maximum - MAX_STORAGE_VECTOR_LENGTH - then do not attempt to grow any further.
333 while (newVectorLength < MAX_STORAGE_VECTOR_LENGTH) {
334 unsigned proposedNewVectorLength = increasedVectorLength(newVectorLength + 1);
335 for (unsigned j = max(newVectorLength, MIN_SPARSE_ARRAY_INDEX); j < proposedNewVectorLength; ++j)
336 proposedNewNumValuesInVector += map->contains(j);
337 if (!isDenseEnoughForVector(proposedNewVectorLength, proposedNewNumValuesInVector))
338 break;
339 newVectorLength = proposedNewVectorLength;
340 newNumValuesInVector = proposedNewNumValuesInVector;
341 }
342 }
343
344 storage = static_cast<ArrayStorage*>(tryFastRealloc(storage, storageSize(newVectorLength)));
345 if (!storage) {
346 throwOutOfMemoryError(exec);
347 return;
348 }
349
350 unsigned vectorLength = storage->m_vectorLength;
351 if (newNumValuesInVector == storage->m_numValuesInVector + 1) {
352 for (unsigned j = vectorLength; j < newVectorLength; ++j)
353 storage->m_vector[j] = noValue();
354 if (i > MIN_SPARSE_ARRAY_INDEX)
355 map->remove(i);
356 } else {
357 for (unsigned j = vectorLength; j < max(vectorLength, MIN_SPARSE_ARRAY_INDEX); ++j)
358 storage->m_vector[j] = noValue();
359 for (unsigned j = max(vectorLength, MIN_SPARSE_ARRAY_INDEX); j < newVectorLength; ++j)
360 storage->m_vector[j] = map->take(j);
361 }
362
363 storage->m_vector[i] = value;
364
365 storage->m_vectorLength = newVectorLength;
366 storage->m_numValuesInVector = newNumValuesInVector;
367
368 m_storage = storage;
369
370 checkConsistency();
371}
372
373bool JSArray::deleteProperty(ExecState* exec, const Identifier& propertyName)
374{
375 bool isArrayIndex;
376 unsigned i = propertyName.toArrayIndex(&isArrayIndex);
377 if (isArrayIndex)
378 return deleteProperty(exec, i);
379
380 if (propertyName == exec->propertyNames().length)
381 return false;
382
383 return JSObject::deleteProperty(exec, propertyName);
384}
385
386bool JSArray::deleteProperty(ExecState* exec, unsigned i)
387{
388 checkConsistency();
389
390 ArrayStorage* storage = m_storage;
391
392 if (i < storage->m_vectorLength) {
393 JSValue*& valueSlot = storage->m_vector[i];
394 if (!valueSlot) {
395 checkConsistency();
396 return false;
397 }
398 valueSlot = noValue();
399 --storage->m_numValuesInVector;
400 if (m_fastAccessCutoff > i)
401 m_fastAccessCutoff = i;
402 checkConsistency();
403 return true;
404 }
405
406 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
407 if (i >= MIN_SPARSE_ARRAY_INDEX) {
408 SparseArrayValueMap::iterator it = map->find(i);
409 if (it != map->end()) {
410 map->remove(it);
411 checkConsistency();
412 return true;
413 }
414 }
415 }
416
417 checkConsistency();
418
419 if (i > MAX_ARRAY_INDEX)
420 return deleteProperty(exec, Identifier::from(exec, i));
421
422 return false;
423}
424
425void JSArray::getPropertyNames(ExecState* exec, PropertyNameArray& propertyNames)
426{
427 // FIXME: Filling PropertyNameArray with an identifier for every integer
428 // is incredibly inefficient for large arrays. We need a different approach,
429 // which almost certainly means a different structure for PropertyNameArray.
430
431 ArrayStorage* storage = m_storage;
432
433 unsigned usedVectorLength = min(storage->m_length, storage->m_vectorLength);
434 for (unsigned i = 0; i < usedVectorLength; ++i) {
435 if (storage->m_vector[i])
436 propertyNames.add(Identifier::from(exec, i));
437 }
438
439 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
440 SparseArrayValueMap::iterator end = map->end();
441 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it)
442 propertyNames.add(Identifier::from(exec, it->first));
443 }
444
445 JSObject::getPropertyNames(exec, propertyNames);
446}
447
448bool JSArray::increaseVectorLength(unsigned newLength)
449{
450 // This function leaves the array in an internally inconsistent state, because it does not move any values from sparse value map
451 // to the vector. Callers have to account for that, because they can do it more efficiently.
452
453 ArrayStorage* storage = m_storage;
454
455 unsigned vectorLength = storage->m_vectorLength;
456 ASSERT(newLength > vectorLength);
457 ASSERT(newLength <= MAX_STORAGE_VECTOR_INDEX);
458 unsigned newVectorLength = increasedVectorLength(newLength);
459
460 storage = static_cast<ArrayStorage*>(tryFastRealloc(storage, storageSize(newVectorLength)));
461 if (!storage)
462 return false;
463
464 storage->m_vectorLength = newVectorLength;
465
466 for (unsigned i = vectorLength; i < newVectorLength; ++i)
467 storage->m_vector[i] = noValue();
468
469 m_storage = storage;
470 return true;
471}
472
473void JSArray::setLength(unsigned newLength)
474{
475 checkConsistency();
476
477 ArrayStorage* storage = m_storage;
478
479 unsigned length = m_storage->m_length;
480
481 if (newLength < length) {
482 if (m_fastAccessCutoff > newLength)
483 m_fastAccessCutoff = newLength;
484
485 unsigned usedVectorLength = min(length, storage->m_vectorLength);
486 for (unsigned i = newLength; i < usedVectorLength; ++i) {
487 JSValue*& valueSlot = storage->m_vector[i];
488 bool hadValue = valueSlot;
489 valueSlot = noValue();
490 storage->m_numValuesInVector -= hadValue;
491 }
492
493 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
494 SparseArrayValueMap copy = *map;
495 SparseArrayValueMap::iterator end = copy.end();
496 for (SparseArrayValueMap::iterator it = copy.begin(); it != end; ++it) {
497 if (it->first >= newLength)
498 map->remove(it->first);
499 }
500 if (map->isEmpty()) {
501 delete map;
502 storage->m_sparseValueMap = 0;
503 }
504 }
505 }
506
507 m_storage->m_length = newLength;
508
509 checkConsistency();
510}
511
512JSValue* JSArray::pop()
513{
514 checkConsistency();
515
516 unsigned length = m_storage->m_length;
517 if (!length)
518 return jsUndefined();
519
520 --length;
521
522 JSValue* result;
523
524 if (m_fastAccessCutoff > length) {
525 JSValue*& valueSlot = m_storage->m_vector[length];
526 result = valueSlot;
527 ASSERT(result);
528 valueSlot = noValue();
529 --m_storage->m_numValuesInVector;
530 m_fastAccessCutoff = length;
531 } else if (length < m_storage->m_vectorLength) {
532 JSValue*& valueSlot = m_storage->m_vector[length];
533 result = valueSlot;
534 valueSlot = noValue();
535 if (result)
536 --m_storage->m_numValuesInVector;
537 else
538 result = jsUndefined();
539 } else {
540 result = jsUndefined();
541 if (SparseArrayValueMap* map = m_storage->m_sparseValueMap) {
542 SparseArrayValueMap::iterator it = map->find(length);
543 if (it != map->end()) {
544 result = it->second;
545 map->remove(it);
546 if (map->isEmpty()) {
547 delete map;
548 m_storage->m_sparseValueMap = 0;
549 }
550 }
551 }
552 }
553
554 m_storage->m_length = length;
555
556 checkConsistency();
557
558 return result;
559}
560
561void JSArray::push(ExecState* exec, JSValue* value)
562{
563 checkConsistency();
564
565 if (m_storage->m_length < m_storage->m_vectorLength) {
566 ASSERT(!m_storage->m_vector[m_storage->m_length]);
567 m_storage->m_vector[m_storage->m_length] = value;
568 if (++m_storage->m_numValuesInVector == ++m_storage->m_length)
569 m_fastAccessCutoff = m_storage->m_length;
570 checkConsistency();
571 return;
572 }
573
574 if (m_storage->m_length < MIN_SPARSE_ARRAY_INDEX) {
575 SparseArrayValueMap* map = m_storage->m_sparseValueMap;
576 if (!map || map->isEmpty()) {
577 if (increaseVectorLength(m_storage->m_length + 1)) {
578 m_storage->m_vector[m_storage->m_length] = value;
579 if (++m_storage->m_numValuesInVector == ++m_storage->m_length)
580 m_fastAccessCutoff = m_storage->m_length;
581 checkConsistency();
582 return;
583 }
584 checkConsistency();
585 throwOutOfMemoryError(exec);
586 return;
587 }
588 }
589
590 putSlowCase(exec, m_storage->m_length++, value);
591}
592
593void JSArray::mark()
594{
595 JSObject::mark();
596
597 ArrayStorage* storage = m_storage;
598
599 unsigned usedVectorLength = min(storage->m_length, storage->m_vectorLength);
600 for (unsigned i = 0; i < usedVectorLength; ++i) {
601 JSValue* value = storage->m_vector[i];
602 if (value && !value->marked())
603 value->mark();
604 }
605
606 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
607 SparseArrayValueMap::iterator end = map->end();
608 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it) {
609 JSValue* value = it->second;
610 if (!value->marked())
611 value->mark();
612 }
613 }
614}
615
616typedef std::pair<JSValue*, UString> ArrayQSortPair;
617
618static int compareByStringPairForQSort(const void* a, const void* b)
619{
620 const ArrayQSortPair* va = static_cast<const ArrayQSortPair*>(a);
621 const ArrayQSortPair* vb = static_cast<const ArrayQSortPair*>(b);
622 return compare(va->second, vb->second);
623}
624
625void JSArray::sort(ExecState* exec)
626{
627 unsigned lengthNotIncludingUndefined = compactForSorting();
628 if (m_storage->m_sparseValueMap) {
629 throwOutOfMemoryError(exec);
630 return;
631 }
632
633 if (!lengthNotIncludingUndefined)
634 return;
635
636 // Converting JavaScript values to strings can be expensive, so we do it once up front and sort based on that.
637 // This is a considerable improvement over doing it twice per comparison, though it requires a large temporary
638 // buffer. Besides, this protects us from crashing if some objects have custom toString methods that return
639 // random or otherwise changing results, effectively making compare function inconsistent.
640
641 Vector<ArrayQSortPair> values(lengthNotIncludingUndefined);
642 if (!values.begin()) {
643 throwOutOfMemoryError(exec);
644 return;
645 }
646
647 for (size_t i = 0; i < lengthNotIncludingUndefined; i++) {
648 JSValue* value = m_storage->m_vector[i];
649 ASSERT(!value->isUndefined());
650 values[i].first = value;
651 }
652
653 // FIXME: While calling these toString functions, the array could be mutated.
654 // In that case, objects pointed to by values in this vector might get garbage-collected!
655
656 // FIXME: The following loop continues to call toString on subsequent values even after
657 // a toString call raises an exception.
658
659 for (size_t i = 0; i < lengthNotIncludingUndefined; i++)
660 values[i].second = values[i].first->toString(exec);
661
662 if (exec->hadException())
663 return;
664
665 // FIXME: Since we sort by string value, a fast algorithm might be to use a radix sort. That would be O(N) rather
666 // than O(N log N).
667
668#if HAVE(MERGESORT)
669 mergesort(values.begin(), values.size(), sizeof(ArrayQSortPair), compareByStringPairForQSort);
670#else
671 // FIXME: The qsort library function is likely to not be a stable sort.
672 // ECMAScript-262 does not specify a stable sort, but in practice, browsers perform a stable sort.
673 qsort(values.begin(), values.size(), sizeof(ArrayQSortPair), compareByStringPairForQSort);
674#endif
675
676 // FIXME: If the toString function changed the length of the array, this might be
677 // modifying the vector incorrectly.
678
679 for (size_t i = 0; i < lengthNotIncludingUndefined; i++)
680 m_storage->m_vector[i] = values[i].first;
681
682 checkConsistency(SortConsistencyCheck);
683}
684
685struct AVLTreeNodeForArrayCompare {
686 JSValue* value;
687
688 // Child pointers. The high bit of gt is robbed and used as the
689 // balance factor sign. The high bit of lt is robbed and used as
690 // the magnitude of the balance factor.
691 int32_t gt;
692 int32_t lt;
693};
694
695struct AVLTreeAbstractorForArrayCompare {
696 typedef int32_t handle; // Handle is an index into m_nodes vector.
697 typedef JSValue* key;
698 typedef int32_t size;
699
700 Vector<AVLTreeNodeForArrayCompare> m_nodes;
701 ExecState* m_exec;
702 JSValue* m_compareFunction;
703 CallType m_compareCallType;
704 const CallData* m_compareCallData;
705 JSValue* m_globalThisValue;
706
707 handle get_less(handle h) { return m_nodes[h].lt & 0x7FFFFFFF; }
708 void set_less(handle h, handle lh) { m_nodes[h].lt &= 0x80000000; m_nodes[h].lt |= lh; }
709 handle get_greater(handle h) { return m_nodes[h].gt & 0x7FFFFFFF; }
710 void set_greater(handle h, handle gh) { m_nodes[h].gt &= 0x80000000; m_nodes[h].gt |= gh; }
711
712 int get_balance_factor(handle h)
713 {
714 if (m_nodes[h].gt & 0x80000000)
715 return -1;
716 return static_cast<unsigned>(m_nodes[h].lt) >> 31;
717 }
718
719 void set_balance_factor(handle h, int bf)
720 {
721 if (bf == 0) {
722 m_nodes[h].lt &= 0x7FFFFFFF;
723 m_nodes[h].gt &= 0x7FFFFFFF;
724 } else {
725 m_nodes[h].lt |= 0x80000000;
726 if (bf < 0)
727 m_nodes[h].gt |= 0x80000000;
728 else
729 m_nodes[h].gt &= 0x7FFFFFFF;
730 }
731 }
732
733 int compare_key_key(key va, key vb)
734 {
735 ASSERT(!va->isUndefined());
736 ASSERT(!vb->isUndefined());
737
738 if (m_exec->hadException())
739 return 1;
740
741 ArgList arguments;
742 arguments.append(va);
743 arguments.append(vb);
744 double compareResult = call(m_exec, m_compareFunction, m_compareCallType, *m_compareCallData, m_globalThisValue, arguments)->toNumber(m_exec);
745 return (compareResult < 0) ? -1 : 1; // Not passing equality through, because we need to store all values, even if equivalent.
746 }
747
748 int compare_key_node(key k, handle h) { return compare_key_key(k, m_nodes[h].value); }
749 int compare_node_node(handle h1, handle h2) { return compare_key_key(m_nodes[h1].value, m_nodes[h2].value); }
750
751 static handle null() { return 0x7FFFFFFF; }
752};
753
754void JSArray::sort(ExecState* exec, JSValue* compareFunction, CallType callType, const CallData& callData)
755{
756 checkConsistency();
757
758 // FIXME: This ignores exceptions raised in the compare function or in toNumber.
759
760 // The maximum tree depth is compiled in - but the caller is clearly up to no good
761 // if a larger array is passed.
762 ASSERT(m_storage->m_length <= static_cast<unsigned>(std::numeric_limits<int>::max()));
763 if (m_storage->m_length > static_cast<unsigned>(std::numeric_limits<int>::max()))
764 return;
765
766 if (!m_storage->m_length)
767 return;
768
769 unsigned usedVectorLength = min(m_storage->m_length, m_storage->m_vectorLength);
770
771 AVLTree<AVLTreeAbstractorForArrayCompare, 44> tree; // Depth 44 is enough for 2^31 items
772 tree.abstractor().m_exec = exec;
773 tree.abstractor().m_compareFunction = compareFunction;
774 tree.abstractor().m_compareCallType = callType;
775 tree.abstractor().m_compareCallData = &callData;
776 tree.abstractor().m_globalThisValue = exec->globalThisValue();
777 tree.abstractor().m_nodes.resize(usedVectorLength + (m_storage->m_sparseValueMap ? m_storage->m_sparseValueMap->size() : 0));
778
779 if (!tree.abstractor().m_nodes.begin()) {
780 throwOutOfMemoryError(exec);
781 return;
782 }
783
784 // FIXME: If the compare function modifies the array, the vector, map, etc. could be modified
785 // right out from under us while we're building the tree here.
786
787 unsigned numDefined = 0;
788 unsigned numUndefined = 0;
789
790 // Iterate over the array, ignoring missing values, counting undefined ones, and inserting all other ones into the tree.
791 for (; numDefined < usedVectorLength; ++numDefined) {
792 JSValue* v = m_storage->m_vector[numDefined];
793 if (!v || v->isUndefined())
794 break;
795 tree.abstractor().m_nodes[numDefined].value = v;
796 tree.insert(numDefined);
797 }
798 for (unsigned i = numDefined; i < usedVectorLength; ++i) {
799 if (JSValue* v = m_storage->m_vector[i]) {
800 if (v->isUndefined())
801 ++numUndefined;
802 else {
803 tree.abstractor().m_nodes[numDefined].value = v;
804 tree.insert(numDefined);
805 ++numDefined;
806 }
807 }
808 }
809
810 unsigned newUsedVectorLength = numDefined + numUndefined;
811
812 if (SparseArrayValueMap* map = m_storage->m_sparseValueMap) {
813 newUsedVectorLength += map->size();
814 if (newUsedVectorLength > m_storage->m_vectorLength) {
815 // Check that it is possible to allocate an array large enough to hold all the entries.
816 if ((newUsedVectorLength > MAX_STORAGE_VECTOR_LENGTH) || !increaseVectorLength(newUsedVectorLength)) {
817 throwOutOfMemoryError(exec);
818 return;
819 }
820 }
821
822 SparseArrayValueMap::iterator end = map->end();
823 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it) {
824 tree.abstractor().m_nodes[numDefined].value = it->second;
825 tree.insert(numDefined);
826 ++numDefined;
827 }
828
829 delete map;
830 m_storage->m_sparseValueMap = 0;
831 }
832
833 ASSERT(tree.abstractor().m_nodes.size() >= numDefined);
834
835 // FIXME: If the compare function changed the length of the array, the following might be
836 // modifying the vector incorrectly.
837
838 // Copy the values back into m_storage.
839 AVLTree<AVLTreeAbstractorForArrayCompare, 44>::Iterator iter;
840 iter.start_iter_least(tree);
841 for (unsigned i = 0; i < numDefined; ++i) {
842 m_storage->m_vector[i] = tree.abstractor().m_nodes[*iter].value;
843 ++iter;
844 }
845
846 // Put undefined values back in.
847 for (unsigned i = numDefined; i < newUsedVectorLength; ++i)
848 m_storage->m_vector[i] = jsUndefined();
849
850 // Ensure that unused values in the vector are zeroed out.
851 for (unsigned i = newUsedVectorLength; i < usedVectorLength; ++i)
852 m_storage->m_vector[i] = noValue();
853
854 m_fastAccessCutoff = newUsedVectorLength;
855 m_storage->m_numValuesInVector = newUsedVectorLength;
856
857 checkConsistency(SortConsistencyCheck);
858}
859
860void JSArray::fillArgList(ExecState* exec, ArgList& args)
861{
862 unsigned fastAccessLength = min(m_storage->m_length, m_fastAccessCutoff);
863 unsigned i = 0;
864 for (; i < fastAccessLength; ++i)
865 args.append(getIndex(i));
866 for (; i < m_storage->m_length; ++i)
867 args.append(get(exec, i));
868}
869
870unsigned JSArray::compactForSorting()
871{
872 checkConsistency();
873
874 ArrayStorage* storage = m_storage;
875
876 unsigned usedVectorLength = min(m_storage->m_length, storage->m_vectorLength);
877
878 unsigned numDefined = 0;
879 unsigned numUndefined = 0;
880
881 for (; numDefined < usedVectorLength; ++numDefined) {
882 JSValue* v = storage->m_vector[numDefined];
883 if (!v || v->isUndefined())
884 break;
885 }
886 for (unsigned i = numDefined; i < usedVectorLength; ++i) {
887 if (JSValue* v = storage->m_vector[i]) {
888 if (v->isUndefined())
889 ++numUndefined;
890 else
891 storage->m_vector[numDefined++] = v;
892 }
893 }
894
895 unsigned newUsedVectorLength = numDefined + numUndefined;
896
897 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
898 newUsedVectorLength += map->size();
899 if (newUsedVectorLength > storage->m_vectorLength) {
900 // Check that it is possible to allocate an array large enough to hold all the entries - if not,
901 // exception is thrown by caller.
902 if ((newUsedVectorLength > MAX_STORAGE_VECTOR_LENGTH) || !increaseVectorLength(newUsedVectorLength))
903 return 0;
904 storage = m_storage;
905 }
906
907 SparseArrayValueMap::iterator end = map->end();
908 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it)
909 storage->m_vector[numDefined++] = it->second;
910
911 delete map;
912 storage->m_sparseValueMap = 0;
913 }
914
915 for (unsigned i = numDefined; i < newUsedVectorLength; ++i)
916 storage->m_vector[i] = jsUndefined();
917 for (unsigned i = newUsedVectorLength; i < usedVectorLength; ++i)
918 storage->m_vector[i] = noValue();
919
920 m_fastAccessCutoff = newUsedVectorLength;
921 storage->m_numValuesInVector = newUsedVectorLength;
922
923 checkConsistency(SortConsistencyCheck);
924
925 return numDefined;
926}
927
928void* JSArray::lazyCreationData()
929{
930 return m_storage->lazyCreationData;
931}
932
933void JSArray::setLazyCreationData(void* d)
934{
935 m_storage->lazyCreationData = d;
936}
937
938#if CHECK_ARRAY_CONSISTENCY
939
940void JSArray::checkConsistency(ConsistencyCheckType type)
941{
942 ASSERT(m_storage);
943 if (type == SortConsistencyCheck)
944 ASSERT(!m_storage->m_sparseValueMap);
945
946 ASSERT(m_fastAccessCutoff <= m_storage->m_length);
947 ASSERT(m_fastAccessCutoff <= m_storage->m_numValuesInVector);
948
949 unsigned numValuesInVector = 0;
950 for (unsigned i = 0; i < m_storage->m_vectorLength; ++i) {
951 if (JSValue* value = m_storage->m_vector[i]) {
952 ASSERT(i < m_storage->m_length);
953 if (type != DestructorConsistencyCheck)
954 value->type(); // Likely to crash if the object was deallocated.
955 ++numValuesInVector;
956 } else {
957 ASSERT(i >= m_fastAccessCutoff);
958 if (type == SortConsistencyCheck)
959 ASSERT(i >= m_storage->m_numValuesInVector);
960 }
961 }
962 ASSERT(numValuesInVector == m_storage->m_numValuesInVector);
963
964 if (m_storage->m_sparseValueMap) {
965 SparseArrayValueMap::iterator end = m_storage->m_sparseValueMap->end();
966 for (SparseArrayValueMap::iterator it = m_storage->m_sparseValueMap->begin(); it != end; ++it) {
967 unsigned index = it->first;
968 ASSERT(index < m_storage->m_length);
969 ASSERT(index >= m_storage->m_vectorLength);
970 ASSERT(index <= MAX_ARRAY_INDEX);
971 ASSERT(it->second);
972 if (type != DestructorConsistencyCheck)
973 it->second->type(); // Likely to crash if the object was deallocated.
974 }
975 }
976}
977
978#endif
979
980JSArray* constructEmptyArray(ExecState* exec)
981{
982 return new (exec) JSArray(exec->lexicalGlobalObject()->arrayStructure());
983}
984
985JSArray* constructEmptyArray(ExecState* exec, unsigned initialLength)
986{
987 return new (exec) JSArray(exec->lexicalGlobalObject()->arrayStructure(), initialLength);
988}
989
990JSArray* constructArray(ExecState* exec, JSValue* singleItemValue)
991{
992 ArgList values;
993 values.append(singleItemValue);
994 return new (exec) JSArray(exec, exec->lexicalGlobalObject()->arrayStructure(), values);
995}
996
997JSArray* constructArray(ExecState* exec, const ArgList& values)
998{
999 return new (exec) JSArray(exec, exec->lexicalGlobalObject()->arrayStructure(), values);
1000}
1001
1002} // namespace JSC
Note: See TracBrowser for help on using the repository browser.