JSValue.cpp 10.9 KB
Newer Older
1 2 3
/*
 *  Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
 *  Copyright (C) 2001 Peter Kelly (pmk@post.com)
4
 *  Copyright (C) 2003, 2007, 2008, 2012 Apple Inc. All rights reserved.
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
mjs's avatar
mjs committed
18
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19
 *  Boston, MA 02110-1301, USA.
20 21 22
 *
 */

mjs's avatar
mjs committed
23
#include "config.h"
darin@apple.com's avatar
darin@apple.com committed
24
#include "JSValue.h"
darin's avatar
darin committed
25

26 27
#include "BooleanConstructor.h"
#include "BooleanPrototype.h"
28
#include "Error.h"
29
#include "ExceptionHelpers.h"
30
#include "GetterSetter.h"
31
#include "JSGlobalObject.h"
32
#include "JSFunction.h"
33 34
#include "JSNotAnObject.h"
#include "NumberObject.h"
darin's avatar
darin committed
35
#include <wtf/MathExtras.h>
36
#include <wtf/StringExtras.h>
37

38
namespace JSC {
39

darin's avatar
darin committed
40
static const double D32 = 4294967296.0;
41 42

// ECMA 9.4
ggaren@apple.com's avatar
ggaren@apple.com committed
43
double JSValue::toInteger(ExecState* exec) const
44
{
45 46
    if (isInt32())
        return asInt32();
darin's avatar
darin committed
47
    double d = toNumber(exec);
48
    return isnan(d) ? 0.0 : trunc(d);
darin's avatar
darin committed
49 50
}

ggaren@apple.com's avatar
ggaren@apple.com committed
51
double JSValue::toIntegerPreserveNaN(ExecState* exec) const
darin's avatar
darin committed
52
{
53 54
    if (isInt32())
        return asInt32();
darin's avatar
darin committed
55
    return trunc(toNumber(exec));
56 57
}

58 59 60 61 62 63 64
double JSValue::toNumberSlowCase(ExecState* exec) const
{
    ASSERT(!isInt32() && !isDouble());
    if (isCell())
        return asCell()->toNumber(exec);
    if (isTrue())
        return 1.0;
65
    return isUndefined() ? QNaN : 0; // null and false both convert to 0.
66 67
}

68
JSObject* JSValue::toObjectSlowCase(ExecState* exec, JSGlobalObject* globalObject) const
69 70 71 72
{
    ASSERT(!isCell());

    if (isInt32() || isDouble())
73
        return constructNumber(exec, globalObject, asValue());
74
    if (isTrue() || isFalse())
75
        return constructBooleanFromImmediateBoolean(exec, globalObject, asValue());
76

77
    ASSERT(isUndefinedOrNull());
78
    throwError(exec, createNotAnObjectError(exec, *this));
79
    return JSNotAnObject::create(exec);
80 81 82 83 84 85 86
}

JSObject* JSValue::toThisObjectSlowCase(ExecState* exec) const
{
    ASSERT(!isCell());

    if (isInt32() || isDouble())
87
        return constructNumber(exec, exec->lexicalGlobalObject(), asValue());
88
    if (isTrue() || isFalse())
89
        return constructBooleanFromImmediateBoolean(exec, exec->lexicalGlobalObject(), asValue());
90 91 92 93 94 95
    ASSERT(isUndefinedOrNull());
    return exec->globalThisValue();
}

JSObject* JSValue::synthesizePrototype(ExecState* exec) const
{
96 97 98 99 100
    if (isCell()) {
        ASSERT(isString());
        return exec->lexicalGlobalObject()->stringPrototype();
    }

101 102 103 104 105
    if (isNumber())
        return exec->lexicalGlobalObject()->numberPrototype();
    if (isBoolean())
        return exec->lexicalGlobalObject()->booleanPrototype();

106 107
    ASSERT(isUndefinedOrNull());
    throwError(exec, createNotAnObjectError(exec, *this));
108
    return JSNotAnObject::create(exec);
109 110
}

111
// ECMA 8.7.2
112
void JSValue::putToPrimitive(ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
113 114 115
{
    JSGlobalData& globalData = exec->globalData();

116 117 118 119 120 121
    unsigned index = propertyName.asIndex();
    if (index != PropertyName::NotAnIndex) {
        putToPrimitiveByIndex(exec, index, value, slot.isStrictMode());
        return;
    }

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    // Check if there are any setters or getters in the prototype chain
    JSObject* obj = synthesizePrototype(exec);
    JSValue prototype;
    if (propertyName != exec->propertyNames().underscoreProto) {
        for (; !obj->structure()->hasReadOnlyOrGetterSetterPropertiesExcludingProto(); obj = asObject(prototype)) {
            prototype = obj->prototype();
            if (prototype.isNull()) {
                if (slot.isStrictMode())
                    throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
                return;
            }
        }
    }

    for (; ; obj = asObject(prototype)) {
        unsigned attributes;
        JSCell* specificValue;
139 140
        PropertyOffset offset = obj->structure()->get(globalData, propertyName, attributes, specificValue);
        if (offset != invalidOffset) {
141 142 143 144 145 146 147 148 149 150 151
            if (attributes & ReadOnly) {
                if (slot.isStrictMode())
                    throwError(exec, createTypeError(exec, StrictModeReadonlyPropertyWriteError));
                return;
            }

            JSValue gs = obj->getDirectOffset(offset);
            if (gs.isGetterSetter()) {
                JSObject* setterFunc = asGetterSetter(gs)->setter();        
                if (!setterFunc) {
                    if (slot.isStrictMode())
152
                        throwError(exec, createTypeError(exec, ASCIILiteral("setting a property that has only a getter")));
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
                    return;
                }
                
                CallData callData;
                CallType callType = setterFunc->methodTable()->getCallData(setterFunc, callData);
                MarkedArgumentBuffer args;
                args.append(value);

                // If this is WebCore's global object then we need to substitute the shell.
                call(exec, setterFunc, callType, callData, *this, args);
                return;
            }

            // If there's an existing property on the object or one of its 
            // prototypes it should be replaced, so break here.
            break;
        }

        prototype = obj->prototype();
        if (prototype.isNull())
            break;
    }
    
    if (slot.isStrictMode())
        throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
    return;
}

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
void JSValue::putToPrimitiveByIndex(ExecState* exec, unsigned propertyName, JSValue value, bool shouldThrow)
{
    if (propertyName > MAX_ARRAY_INDEX) {
        PutPropertySlot slot(shouldThrow);
        putToPrimitive(exec, Identifier::from(exec, propertyName), value, slot);
        return;
    }
    
    if (synthesizePrototype(exec)->attemptToInterceptPutByIndexOnHoleForPrototype(exec, *this, propertyName, value, shouldThrow))
        return;
    
    if (shouldThrow)
        throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
}

196
char* JSValue::description() const
197
{
198
    static const size_t size = 256;
199
    static char description[size];
200 201 202 203

    if (!*this)
        snprintf(description, size, "<JSValue()>");
    else if (isInt32())
204
        snprintf(description, size, "Int32: %d", asInt32());
205 206
    else if (isDouble()) {
#if USE(JSVALUE64)
207
        snprintf(description, size, "Double: %lld, %lf", (long long)reinterpretDoubleToInt64(asDouble()), asDouble());
208 209 210 211 212 213
#else
        union {
            double asDouble;
            uint32_t asTwoInt32s[2];
        } u;
        u.asDouble = asDouble();
214
        snprintf(description, size, "Double: %08x:%08x, %lf", u.asTwoInt32s[1], u.asTwoInt32s[0], asDouble());
215
#endif
216 217 218 219 220 221
    } else if (isCell()) {
        snprintf(
            description, size, "Cell: %p (%p: %s, %s)",
            asCell(), asCell()->structure(), asCell()->structure()->classInfo()->className,
            indexingTypeToString(asCell()->structure()->indexingTypeIncludingHistory()));
    } else if (isTrue())
222 223 224 225 226
        snprintf(description, size, "True");
    else if (isFalse())
        snprintf(description, size, "False");
    else if (isNull())
        snprintf(description, size, "Null");
227
    else if (isUndefined())
228
        snprintf(description, size, "Undefined");
229 230
    else
        snprintf(description, size, "INVALID");
231 232 233 234

    return description;
}

235 236 237 238 239 240 241 242
// This in the ToInt32 operation is defined in section 9.5 of the ECMA-262 spec.
// Note that this operation is identical to ToUInt32 other than to interpretation
// of the resulting bit-pattern (as such this metod is also called to implement
// ToUInt32).
//
// The operation can be descibed as round towards zero, then select the 32 least
// bits of the resulting value in 2s-complement representation.
int32_t toInt32(double number)
243
{
244 245 246 247 248 249 250 251 252
    int64_t bits = WTF::bitwise_cast<int64_t>(number);
    int32_t exp = (static_cast<int32_t>(bits >> 52) & 0x7ff) - 0x3ff;

    // If exponent < 0 there will be no bits to the left of the decimal point
    // after rounding; if the exponent is > 83 then no bits of precision can be
    // left in the low 32-bit range of the result (IEEE-754 doubles have 52 bits
    // of fractional precision).
    // Note this case handles 0, -0, and all infinte, NaN, & denormal value. 
    if (exp < 0 || exp > 83)
darin's avatar
darin committed
253
        return 0;
254

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    // Select the appropriate 32-bits from the floating point mantissa.  If the
    // exponent is 52 then the bits we need to select are already aligned to the
    // lowest bits of the 64-bit integer representation of tghe number, no need
    // to shift.  If the exponent is greater than 52 we need to shift the value
    // left by (exp - 52), if the value is less than 52 we need to shift right
    // accordingly.
    int32_t result = (exp > 52)
        ? static_cast<int32_t>(bits << (exp - 52))
        : static_cast<int32_t>(bits >> (52 - exp));

    // IEEE-754 double precision values are stored omitting an implicit 1 before
    // the decimal point; we need to reinsert this now.  We may also the shifted
    // invalid bits into the result that are not a part of the mantissa (the sign
    // and exponent bits from the floatingpoint representation); mask these out.
    if (exp < 32) {
        int32_t missingOne = 1 << exp;
        result &= missingOne - 1;
        result += missingOne;
ap's avatar
ap committed
273
    }
274

275 276 277
    // If the input value was negative (we could test either 'number' or 'bits',
    // but testing 'bits' is likely faster) invert the result appropriately.
    return bits < 0 ? -result : result;
278 279
}

280 281
bool JSValue::isValidCallee()
{
282
    return asObject(asCell())->globalObject();
283 284
}

285
JSString* JSValue::toStringSlowCase(ExecState* exec) const
286
{
287
    JSGlobalData& globalData = exec->globalData();
288
    ASSERT(!isString());
289
    if (isInt32())
290
        return jsString(&globalData, globalData.numericStrings.add(asInt32()));
291
    if (isDouble())
292
        return jsString(&globalData, globalData.numericStrings.add(asDouble()));
293
    if (isTrue())
294
        return globalData.smallStrings.trueString(&globalData);
295
    if (isFalse())
296
        return globalData.smallStrings.falseString(&globalData);
297
    if (isNull())
298
        return globalData.smallStrings.nullString(&globalData);
299
    if (isUndefined())
300
        return globalData.smallStrings.undefinedString(&globalData);
301 302

    ASSERT(isCell());
303 304 305 306 307
    JSValue value = asCell()->toPrimitive(exec, PreferString);
    if (exec->hadException())
        return jsEmptyString(exec);
    ASSERT(!value.isObject());
    return value.toString(exec);
308 309
}

310
String JSValue::toWTFStringSlowCase(ExecState* exec) const
311
{
312
    return inlineJSValueNotStringtoString(*this, exec);
313 314
}

315
} // namespace JSC