]> git.saurik.com Git - apple/javascriptcore.git/blame - runtime/JSCJSValue.cpp
JavaScriptCore-7601.1.46.3.tar.gz
[apple/javascriptcore.git] / runtime / JSCJSValue.cpp
CommitLineData
9dae56ea
A
1/*
2 * Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
3 * Copyright (C) 2001 Peter Kelly (pmk@post.com)
93a37866 4 * Copyright (C) 2003, 2007, 2008, 2012 Apple Inc. All rights reserved.
9dae56ea
A
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 *
21 */
22
23#include "config.h"
93a37866 24#include "JSCJSValue.h"
9dae56ea 25
ba379fdc
A
26#include "BooleanConstructor.h"
27#include "BooleanPrototype.h"
81345200 28#include "CustomGetterSetter.h"
14957cd0 29#include "Error.h"
ba379fdc 30#include "ExceptionHelpers.h"
6fe7ccc8 31#include "GetterSetter.h"
93a37866 32#include "JSCJSValueInlines.h"
9dae56ea 33#include "JSFunction.h"
93a37866 34#include "JSGlobalObject.h"
ba379fdc
A
35#include "JSNotAnObject.h"
36#include "NumberObject.h"
81345200 37#include "StructureInlines.h"
9dae56ea 38#include <wtf/MathExtras.h>
ba379fdc 39#include <wtf/StringExtras.h>
9dae56ea
A
40
41namespace JSC {
42
9dae56ea 43// ECMA 9.4
ba379fdc 44double JSValue::toInteger(ExecState* exec) const
9dae56ea 45{
ba379fdc
A
46 if (isInt32())
47 return asInt32();
9dae56ea 48 double d = toNumber(exec);
93a37866 49 return std::isnan(d) ? 0.0 : trunc(d);
9dae56ea
A
50}
51
ba379fdc 52double JSValue::toIntegerPreserveNaN(ExecState* exec) const
9dae56ea 53{
ba379fdc
A
54 if (isInt32())
55 return asInt32();
9dae56ea
A
56 return trunc(toNumber(exec));
57}
58
6fe7ccc8
A
59double JSValue::toNumberSlowCase(ExecState* exec) const
60{
61 ASSERT(!isInt32() && !isDouble());
62 if (isCell())
63 return asCell()->toNumber(exec);
64 if (isTrue())
65 return 1.0;
81345200 66 return isUndefined() ? PNaN : 0; // null and false both convert to 0.
6fe7ccc8
A
67}
68
14957cd0 69JSObject* JSValue::toObjectSlowCase(ExecState* exec, JSGlobalObject* globalObject) const
ba379fdc
A
70{
71 ASSERT(!isCell());
72
73 if (isInt32() || isDouble())
14957cd0 74 return constructNumber(exec, globalObject, asValue());
ba379fdc 75 if (isTrue() || isFalse())
14957cd0
A
76 return constructBooleanFromImmediateBoolean(exec, globalObject, asValue());
77
ba379fdc 78 ASSERT(isUndefinedOrNull());
81345200
A
79 VM& vm = exec->vm();
80 vm.throwException(exec, createNotAnObjectError(exec, *this));
81 return JSNotAnObject::create(vm);
ba379fdc
A
82}
83
81345200 84JSValue JSValue::toThisSlowCase(ExecState* exec, ECMAMode ecmaMode) const
ba379fdc
A
85{
86 ASSERT(!isCell());
87
81345200
A
88 if (ecmaMode == StrictMode)
89 return *this;
90
ba379fdc 91 if (isInt32() || isDouble())
14957cd0 92 return constructNumber(exec, exec->lexicalGlobalObject(), asValue());
ba379fdc 93 if (isTrue() || isFalse())
14957cd0 94 return constructBooleanFromImmediateBoolean(exec, exec->lexicalGlobalObject(), asValue());
ba379fdc
A
95 ASSERT(isUndefinedOrNull());
96 return exec->globalThisValue();
97}
98
6fe7ccc8 99JSObject* JSValue::synthesizePrototype(ExecState* exec) const
ba379fdc 100{
6fe7ccc8 101 if (isCell()) {
ed1e77d3
A
102 if (isString())
103 return exec->lexicalGlobalObject()->stringPrototype();
104 ASSERT(isSymbol());
105 return exec->lexicalGlobalObject()->symbolPrototype();
6fe7ccc8
A
106 }
107
ba379fdc 108 if (isNumber())
6fe7ccc8 109 return exec->lexicalGlobalObject()->numberPrototype();
ba379fdc 110 if (isBoolean())
6fe7ccc8 111 return exec->lexicalGlobalObject()->booleanPrototype();
14957cd0
A
112
113 ASSERT(isUndefinedOrNull());
81345200
A
114 VM& vm = exec->vm();
115 vm.throwException(exec, createNotAnObjectError(exec, *this));
116 return JSNotAnObject::create(vm);
ba379fdc
A
117}
118
6fe7ccc8 119// ECMA 8.7.2
93a37866 120void JSValue::putToPrimitive(ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
ba379fdc 121{
93a37866
A
122 VM& vm = exec->vm();
123
ed1e77d3
A
124 if (Optional<uint32_t> index = parseIndex(propertyName)) {
125 putToPrimitiveByIndex(exec, index.value(), value, slot.isStrictMode());
93a37866
A
126 return;
127 }
ba379fdc 128
6fe7ccc8
A
129 // Check if there are any setters or getters in the prototype chain
130 JSObject* obj = synthesizePrototype(exec);
131 JSValue prototype;
132 if (propertyName != exec->propertyNames().underscoreProto) {
133 for (; !obj->structure()->hasReadOnlyOrGetterSetterPropertiesExcludingProto(); obj = asObject(prototype)) {
134 prototype = obj->prototype();
135 if (prototype.isNull()) {
136 if (slot.isStrictMode())
137 throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
138 return;
139 }
140 }
141 }
142
143 for (; ; obj = asObject(prototype)) {
144 unsigned attributes;
ed1e77d3 145 PropertyOffset offset = obj->structure()->get(vm, propertyName, attributes);
93a37866 146 if (offset != invalidOffset) {
6fe7ccc8
A
147 if (attributes & ReadOnly) {
148 if (slot.isStrictMode())
81345200 149 exec->vm().throwException(exec, createTypeError(exec, StrictModeReadonlyPropertyWriteError));
6fe7ccc8
A
150 return;
151 }
152
93a37866 153 JSValue gs = obj->getDirect(offset);
6fe7ccc8 154 if (gs.isGetterSetter()) {
81345200
A
155 callSetter(exec, *this, gs, value, slot.isStrictMode() ? StrictMode : NotStrictMode);
156 return;
157 }
158
159 if (gs.isCustomGetterSetter()) {
160 callCustomSetter(exec, gs, obj, slot.thisValue(), value);
6fe7ccc8
A
161 return;
162 }
163
164 // If there's an existing property on the object or one of its
165 // prototypes it should be replaced, so break here.
166 break;
167 }
168
169 prototype = obj->prototype();
170 if (prototype.isNull())
171 break;
172 }
173
174 if (slot.isStrictMode())
175 throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
176 return;
ba379fdc
A
177}
178
93a37866 179void JSValue::putToPrimitiveByIndex(ExecState* exec, unsigned propertyName, JSValue value, bool shouldThrow)
ba379fdc 180{
93a37866 181 if (propertyName > MAX_ARRAY_INDEX) {
81345200 182 PutPropertySlot slot(*this, shouldThrow);
93a37866
A
183 putToPrimitive(exec, Identifier::from(exec, propertyName), value, slot);
184 return;
185 }
186
187 if (synthesizePrototype(exec)->attemptToInterceptPutByIndexOnHoleForPrototype(exec, *this, propertyName, value, shouldThrow))
188 return;
189
190 if (shouldThrow)
191 throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
192}
f9bf01c6 193
93a37866 194void JSValue::dump(PrintStream& out) const
81345200
A
195{
196 dumpInContext(out, 0);
197}
198
199void JSValue::dumpInContext(PrintStream& out, DumpContext* context) const
ed1e77d3
A
200{
201 dumpInContextAssumingStructure(
202 out, context, (!!*this && isCell()) ? asCell()->structure() : nullptr);
203}
204
205void JSValue::dumpInContextAssumingStructure(
206 PrintStream& out, DumpContext* context, Structure* structure) const
93a37866 207{
f9bf01c6 208 if (!*this)
93a37866 209 out.print("<JSValue()>");
f9bf01c6 210 else if (isInt32())
93a37866 211 out.printf("Int32: %d", asInt32());
6fe7ccc8
A
212 else if (isDouble()) {
213#if USE(JSVALUE64)
93a37866 214 out.printf("Double: %lld, %lf", (long long)reinterpretDoubleToInt64(asDouble()), asDouble());
6fe7ccc8
A
215#else
216 union {
217 double asDouble;
218 uint32_t asTwoInt32s[2];
219 } u;
220 u.asDouble = asDouble();
93a37866 221 out.printf("Double: %08x:%08x, %lf", u.asTwoInt32s[1], u.asTwoInt32s[0], asDouble());
6fe7ccc8 222#endif
93a37866 223 } else if (isCell()) {
ed1e77d3 224 if (structure->classInfo()->isSubClassOf(JSString::info())) {
93a37866 225 JSString* string = jsCast<JSString*>(asCell());
81345200 226 out.print("String");
93a37866 227 if (string->isRope())
81345200
A
228 out.print(" (rope)");
229 const StringImpl* impl = string->tryGetValueImpl();
230 if (impl) {
231 if (impl->isAtomic())
232 out.print(" (atomic)");
233 if (impl->isAtomic())
234 out.print(" (identifier)");
ed1e77d3
A
235 if (impl->isSymbol())
236 out.print(" (symbol)");
81345200
A
237 } else
238 out.print(" (unresolved)");
239 out.print(": ", impl);
ed1e77d3 240 } else if (structure->classInfo()->isSubClassOf(Structure::info()))
81345200
A
241 out.print("Structure: ", inContext(*jsCast<Structure*>(asCell()), context));
242 else {
93a37866 243 out.print("Cell: ", RawPointer(asCell()));
ed1e77d3 244 out.print(" (", inContext(*structure, context), ")");
81345200
A
245 }
246#if USE(JSVALUE64)
247 out.print(", ID: ", asCell()->structureID());
248#endif
249 } else if (isTrue())
250 out.print("True");
251 else if (isFalse())
252 out.print("False");
253 else if (isNull())
254 out.print("Null");
255 else if (isUndefined())
256 out.print("Undefined");
257 else
258 out.print("INVALID");
259}
260
261void JSValue::dumpForBacktrace(PrintStream& out) const
262{
263 if (!*this)
264 out.print("<JSValue()>");
265 else if (isInt32())
266 out.printf("%d", asInt32());
267 else if (isDouble())
268 out.printf("%lf", asDouble());
269 else if (isCell()) {
270 if (asCell()->inherits(JSString::info())) {
271 JSString* string = jsCast<JSString*>(asCell());
272 const StringImpl* impl = string->tryGetValueImpl();
273 if (impl)
274 out.print("\"", impl, "\"");
275 else
276 out.print("(unresolved string)");
277 } else if (asCell()->inherits(Structure::info())) {
278 out.print("Structure[ ", asCell()->structure()->classInfo()->className);
279#if USE(JSVALUE64)
280 out.print(" ID: ", asCell()->structureID());
281#endif
282 out.print("]: ", RawPointer(asCell()));
283 } else {
284 out.print("Cell[", asCell()->structure()->classInfo()->className);
285#if USE(JSVALUE64)
286 out.print(" ID: ", asCell()->structureID());
287#endif
288 out.print("]: ", RawPointer(asCell()));
93a37866
A
289 }
290 } else if (isTrue())
291 out.print("True");
ba379fdc 292 else if (isFalse())
93a37866 293 out.print("False");
ba379fdc 294 else if (isNull())
93a37866 295 out.print("Null");
14957cd0 296 else if (isUndefined())
93a37866 297 out.print("Undefined");
14957cd0 298 else
93a37866 299 out.print("INVALID");
ba379fdc 300}
ba379fdc 301
14957cd0
A
302// This in the ToInt32 operation is defined in section 9.5 of the ECMA-262 spec.
303// Note that this operation is identical to ToUInt32 other than to interpretation
304// of the resulting bit-pattern (as such this metod is also called to implement
305// ToUInt32).
306//
307// The operation can be descibed as round towards zero, then select the 32 least
308// bits of the resulting value in 2s-complement representation.
309int32_t toInt32(double number)
9dae56ea 310{
14957cd0
A
311 int64_t bits = WTF::bitwise_cast<int64_t>(number);
312 int32_t exp = (static_cast<int32_t>(bits >> 52) & 0x7ff) - 0x3ff;
313
314 // If exponent < 0 there will be no bits to the left of the decimal point
315 // after rounding; if the exponent is > 83 then no bits of precision can be
316 // left in the low 32-bit range of the result (IEEE-754 doubles have 52 bits
317 // of fractional precision).
318 // Note this case handles 0, -0, and all infinte, NaN, & denormal value.
319 if (exp < 0 || exp > 83)
9dae56ea 320 return 0;
9dae56ea 321
14957cd0
A
322 // Select the appropriate 32-bits from the floating point mantissa. If the
323 // exponent is 52 then the bits we need to select are already aligned to the
324 // lowest bits of the 64-bit integer representation of tghe number, no need
325 // to shift. If the exponent is greater than 52 we need to shift the value
326 // left by (exp - 52), if the value is less than 52 we need to shift right
327 // accordingly.
328 int32_t result = (exp > 52)
329 ? static_cast<int32_t>(bits << (exp - 52))
330 : static_cast<int32_t>(bits >> (52 - exp));
331
332 // IEEE-754 double precision values are stored omitting an implicit 1 before
333 // the decimal point; we need to reinsert this now. We may also the shifted
334 // invalid bits into the result that are not a part of the mantissa (the sign
335 // and exponent bits from the floatingpoint representation); mask these out.
336 if (exp < 32) {
337 int32_t missingOne = 1 << exp;
338 result &= missingOne - 1;
339 result += missingOne;
9dae56ea
A
340 }
341
14957cd0
A
342 // If the input value was negative (we could test either 'number' or 'bits',
343 // but testing 'bits' is likely faster) invert the result appropriately.
344 return bits < 0 ? -result : result;
9dae56ea
A
345}
346
6fe7ccc8 347bool JSValue::isValidCallee()
ba379fdc 348{
6fe7ccc8 349 return asObject(asCell())->globalObject();
ba379fdc
A
350}
351
6fe7ccc8
A
352JSString* JSValue::toStringSlowCase(ExecState* exec) const
353{
93a37866 354 VM& vm = exec->vm();
6fe7ccc8 355 ASSERT(!isString());
ed1e77d3
A
356 if (isInt32()) {
357 auto integer = asInt32();
358 if (static_cast<unsigned>(integer) <= 9)
359 return vm.smallStrings.singleCharacterString(integer + '0');
360 return jsNontrivialString(&vm, vm.numericStrings.add(integer));
361 }
6fe7ccc8 362 if (isDouble())
93a37866 363 return jsString(&vm, vm.numericStrings.add(asDouble()));
6fe7ccc8 364 if (isTrue())
93a37866 365 return vm.smallStrings.trueString();
6fe7ccc8 366 if (isFalse())
93a37866 367 return vm.smallStrings.falseString();
6fe7ccc8 368 if (isNull())
93a37866 369 return vm.smallStrings.nullString();
6fe7ccc8 370 if (isUndefined())
93a37866 371 return vm.smallStrings.undefinedString();
ed1e77d3
A
372 if (isSymbol()) {
373 throwTypeError(exec);
374 return jsEmptyString(exec);
375 }
6fe7ccc8
A
376
377 ASSERT(isCell());
378 JSValue value = asCell()->toPrimitive(exec, PreferString);
379 if (exec->hadException())
380 return jsEmptyString(exec);
381 ASSERT(!value.isObject());
382 return value.toString(exec);
383}
384
93a37866 385String JSValue::toWTFStringSlowCase(ExecState* exec) const
14957cd0 386{
ed1e77d3
A
387 VM& vm = exec->vm();
388 if (isInt32())
389 return vm.numericStrings.add(asInt32());
390 if (isDouble())
391 return vm.numericStrings.add(asDouble());
392 if (isTrue())
393 return vm.propertyNames->trueKeyword.string();
394 if (isFalse())
395 return vm.propertyNames->falseKeyword.string();
396 if (isNull())
397 return vm.propertyNames->nullKeyword.string();
398 if (isUndefined())
399 return vm.propertyNames->undefinedKeyword.string();
400 return toString(exec)->value(exec);
14957cd0
A
401}
402
9dae56ea 403} // namespace JSC