/*
 * Copyright (C) 2011 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#pragma once

#include "CatchScope.h"
#include "Error.h"
#include "ExceptionHelpers.h"
#include "Handle.h"
#include "Identifier.h"
#include "InternalFunction.h"
#include "JSBigInt.h"
#include "JSCellInlines.h"
#include "JSObject.h"
#include "JSFunction.h"
#include "JSStringInlines.h"
#include "JSValue.h"
#include "MathCommon.h"
#include "ThrowScope.h"
#include <wtf/text/StringImpl.h>

namespace JSC {

ALWAYS_INLINE int32_t JSValue::toInt32(ExecState* exec) const
{
	if (isInt32())
		return asInt32();

    double d = toNumber(exec);
    return JSC::toInt32(d);
}

ALWAYS_INLINE uint32_t JSValue::toUInt32(ExecState* exec) const
{
    // The only difference between toInt32 and toUint32 is that toUint32 reinterprets resulted int32_t value as uint32_t.
    // https://tc39.es/ecma262/#sec-touint32
	return toInt32(exec);
}

inline uint32_t JSValue::toIndex(VM& vm, ExecState* exec, const char* errorName) const
{
    //auto scope = DECLARE_THROW_SCOPE(vm);

    double d = toNumber(exec);
    RETURN_IF_EXCEPTION(vm, 0);

    if (d <= -1) {
    	vm.throwException(exec, createRangeError(exec, tryMakeString(errorName, " cannot be negative")));
        return 0;
    }
    if (d > std::numeric_limits<unsigned>::max()) {
    	vm.throwException(exec, createRangeError(exec, tryMakeString(errorName, " too large")));
        return 0;
    }

    if (isInt32())
        return asInt32();
    return JSC::toInt32(d);
}

// https://tc39.es/ecma262/#sec-tointegerorinfinity
inline double JSValue::toIntegerOrInfinity(ExecState* exec) const
{
    if (isInt32())
        return asInt32();
    double d = toNumber(exec);
    if (std::isnan(d) || !d)
        return 0.0;
    return trunc(d);
}

ALWAYS_INLINE bool JSValue::isUInt32() const
{
	return isInt32() && asInt32() >= 0;
}

ALWAYS_INLINE uint32_t JSValue::asUInt32() const
{
	ASSERT(isUInt32());
	return asInt32();
}

ALWAYS_INLINE double JSValue::asNumber() const
{
	ASSERT(isNumber());
	return isInt32() ? asInt32() : asDouble();
}

ALWAYS_INLINE Optional<uint32_t> JSValue::tryGetAsUint32Index()
{
    if (isUInt32()) {
        ASSERT(isIndex(asUInt32()));
        return asUInt32();
    }
    if (isDouble()) {
        double number = asDouble();
        uint32_t asUint = static_cast<uint32_t>(number);
        if (static_cast<double>(asUint) == number && isIndex(asUint))
            return asUint;
    }
    return WTF::Nullopt;
}

ALWAYS_INLINE Optional<int32_t> JSValue::tryGetAsInt32()
{
    if (isInt32())
        return asInt32();
    if (isDouble()) {
        double number = asDouble();
        int32_t asInt = static_cast<int32_t>(number);
        if (static_cast<double>(asInt) == number)
            return asInt;
    }
    return WTF::Nullopt;
}

ALWAYS_INLINE JSValue jsNaN()
{
    return JSValue(JSValue::EncodeAsDouble, PNaN);
}

ALWAYS_INLINE JSValue::JSValue(char i)
{
	*this = JSValue(static_cast<int32_t>(i));
}

ALWAYS_INLINE JSValue::JSValue(unsigned char i)
{
	*this = JSValue(static_cast<int32_t>(i));
}

ALWAYS_INLINE JSValue::JSValue(short i)
{
	*this = JSValue(static_cast<int32_t>(i));
}

ALWAYS_INLINE JSValue::JSValue(unsigned short i)
{
	*this = JSValue(static_cast<int32_t>(i));
}

ALWAYS_INLINE JSValue::JSValue(unsigned i)
{
	if (static_cast<int32_t>(i) < 0) {
		*this = JSValue(EncodeAsDouble, static_cast<double>(i));
		return;
	}
	*this = JSValue(static_cast<int32_t>(i));
}

ALWAYS_INLINE JSValue::JSValue(long i)
{
	if (static_cast<int32_t>(i) != i) {
		*this = JSValue(EncodeAsDouble, static_cast<double>(i));
		return;
	}
	*this = JSValue(static_cast<int32_t>(i));
}

ALWAYS_INLINE JSValue::JSValue(unsigned long i)
{
	if (static_cast<uint32_t>(i) != i) {
		*this = JSValue(EncodeAsDouble, static_cast<double>(i));
		return;
	}
	*this = JSValue(static_cast<uint32_t>(i));
}

ALWAYS_INLINE JSValue::JSValue(long long i)
{
	if (static_cast<int32_t>(i) != i) {
		*this = JSValue(EncodeAsDouble, static_cast<double>(i));
		return;
	}
	*this = JSValue(static_cast<int32_t>(i));
}

ALWAYS_INLINE JSValue::JSValue(unsigned long long i)
{
	if (static_cast<uint32_t>(i) != i) {
		*this = JSValue(EncodeAsDouble, static_cast<double>(i));
		return;
	}
	*this = JSValue(static_cast<uint32_t>(i));
}

ALWAYS_INLINE JSValue::JSValue(double d)
{
    if (canBeStrictInt32(d)) {
        *this = JSValue(static_cast<int32_t>(d));
        return;
    }
    *this = JSValue(EncodeAsDouble, d);
}

ALWAYS_INLINE EncodedJSValue JSValue::encode(JSValue value)
{
	return value.u.asInt64;
}

ALWAYS_INLINE JSValue JSValue::decode(EncodedJSValue encodedJSValue)
{
	JSValue v;
	v.u.asInt64 = encodedJSValue;
	return v;
}

#if USE(JSVALUE32_64)
ALWAYS_INLINE JSValue::JSValue()
{
	u.asBits.tag = EmptyValueTag;
	u.asBits.payload = 0;
}

ALWAYS_INLINE JSValue::JSValue(JSNullTag)
{
	u.asBits.tag = NullTag;
	u.asBits.payload = 0;
}

ALWAYS_INLINE JSValue::JSValue(JSUndefinedTag)
{
	u.asBits.tag = UndefinedTag;
	u.asBits.payload = 0;
}

ALWAYS_INLINE JSValue::JSValue(JSTrueTag)
{
	u.asBits.tag = BooleanTag;
	u.asBits.payload = 1;
}

ALWAYS_INLINE JSValue::JSValue(JSFalseTag)
{
	u.asBits.tag = BooleanTag;
	u.asBits.payload = 0;
}

ALWAYS_INLINE JSValue::JSValue(HashTableDeletedValueTag)
{
	u.asBits.tag = DeletedValueTag;
	u.asBits.payload = 0;
}

ALWAYS_INLINE JSValue::JSValue(JSCell* ptr)
{
	if (LIKELY(ptr != nullptr))
		u.asBits.tag = CellTag;
	else
		u.asBits.tag = EmptyValueTag;
	u.asBits.payload = reinterpret_cast<int32_t>(ptr);
}

ALWAYS_INLINE JSValue::JSValue(const JSCell* ptr)
{
	if (LIKELY(ptr != nullptr))
		u.asBits.tag = CellTag;
	else
		u.asBits.tag = EmptyValueTag;
	u.asBits.payload = reinterpret_cast<int32_t>(const_cast<JSCell*>(ptr));
}

ALWAYS_INLINE JSValue::operator bool() const
{
    ASSERT(tag() != DeletedValueTag);
    return tag() != EmptyValueTag;
}

ALWAYS_INLINE bool JSValue::operator==(const JSValue& other) const
{
	return u.asInt64 == other.u.asInt64;
}

ALWAYS_INLINE bool JSValue::operator!=(const JSValue& other) const
{
	return u.asInt64 != other.u.asInt64;
}

ALWAYS_INLINE bool JSValue::isEmpty() const
{
	return tag() == EmptyValueTag;
}

ALWAYS_INLINE bool JSValue::isUndefined() const
{
	return tag() == UndefinedTag;
}

ALWAYS_INLINE bool JSValue::isNull() const
{
	return tag() == NullTag;
}

ALWAYS_INLINE bool JSValue::isUndefinedOrNull() const
{
	return isUndefined() || isNull();
}

ALWAYS_INLINE bool JSValue::isCell() const
{
	return tag() == CellTag;
}

ALWAYS_INLINE bool JSValue::isInt32() const
{
	return tag() == Int32Tag;
}

ALWAYS_INLINE bool JSValue::isDouble() const
{
	return tag() < LowestTag;
}

ALWAYS_INLINE bool JSValue::isTrue() const
{
	return tag() == BooleanTag && payload();
}

ALWAYS_INLINE bool JSValue::isFalse() const
{
	return tag() == BooleanTag && !payload();
}

ALWAYS_INLINE uint32_t JSValue::tag() const
{
	return u.asBits.tag;
}

ALWAYS_INLINE int32_t JSValue::payload() const
{
	return u.asBits.payload;
}

ALWAYS_INLINE int32_t JSValue::asInt32() const
{
	ASSERT(isInt32());
	return u.asBits.payload;
}

ALWAYS_INLINE double JSValue::asDouble() const
{
	ASSERT(isDouble());
	return u.asDouble;
}

ALWAYS_INLINE JSCell* JSValue::asCell() const
{
	ASSERT(isCell());
	return reinterpret_cast<JSCell*>(u.asBits.payload);
}

ALWAYS_INLINE JSBigInt* JSValue::asHeapBigInt() const
{
    ASSERT(isHeapBigInt());
    return reinterpret_cast<JSBigInt*>(u.asBits.payload);
}

ALWAYS_INLINE JSValue::JSValue(EncodeAsDoubleTag, double d)
{
    ASSERT(!isImpureNaN(d));
	u.asDouble = d;
}

ALWAYS_INLINE JSValue::JSValue(int i)
{
	u.asBits.tag = Int32Tag;
	u.asBits.payload = i;
}

inline JSValue::JSValue(int32_t tag, int32_t payload)
{
    u.asBits.tag = tag;
    u.asBits.payload = payload;
}

ALWAYS_INLINE bool JSValue::isNumber() const
{
	return isInt32() || isDouble();
}

ALWAYS_INLINE bool JSValue::isBoolean() const
{
    return tag() == BooleanTag;
}

ALWAYS_INLINE bool JSValue::asBoolean() const
{
	ASSERT(isBoolean());
	return payload();
}

#else // USE(JSVALUE32_64)

// 0x0 can never occur naturally because it has a tag of 00, indicating a pointer value, but a payload of 0x0, which is in the (invalid) zero page.
ALWAYS_INLINE JSValue::JSValue()
{
	u.asInt64 = ValueEmpty;
}

// 0x4 can never occur naturally because it has a tag of 00, indicating a pointer value, but a payload of 0x4, which is in the (invalid) zero page.
ALWAYS_INLINE JSValue::JSValue(HashTableDeletedValueTag)
{
	u.asInt64 = ValueDeleted;
}

extern void reportJSValueWithNullJSCell();

ALWAYS_INLINE JSValue::JSValue(JSCell* ptr)
{
	u.asInt64 = reinterpret_cast<uintptr_t>(ptr);
	if (UNLIKELY(ptr == nullptr))
		reportJSValueWithNullJSCell();
}

ALWAYS_INLINE JSValue::JSValue(const JSCell* ptr)
{
	u.asInt64 = reinterpret_cast<uintptr_t>(const_cast<JSCell*>(ptr));
	if (UNLIKELY(ptr == nullptr))
		reportJSValueWithNullJSCell();
}

inline JSValue::operator bool() const
{
    return u.asInt64;
}

ALWAYS_INLINE bool JSValue::operator==(const JSValue& other) const
{
	return u.asInt64 == other.u.asInt64;
}

ALWAYS_INLINE bool JSValue::operator!=(const JSValue& other) const
{
	return u.asInt64 != other.u.asInt64;
}

ALWAYS_INLINE bool JSValue::isEmpty() const
{
	return u.asInt64 == ValueEmpty;
}

ALWAYS_INLINE bool JSValue::isUndefined() const
{
	return asValue() == JSValue(JSUndefined);
}

ALWAYS_INLINE bool JSValue::isNull() const
{
	return asValue() == JSValue(JSNull);
}

ALWAYS_INLINE bool JSValue::isTrue() const
{
	return asValue() == JSValue(JSTrue);
}

ALWAYS_INLINE bool JSValue::isFalse() const
{
	return asValue() == JSValue(JSFalse);
}

ALWAYS_INLINE bool JSValue::asBoolean() const
{
	ASSERT(isBoolean());
	return asValue() == JSValue(JSTrue);
}

ALWAYS_INLINE int32_t JSValue::asInt32() const
{
	ASSERT(isInt32());
	return static_cast<int32_t>(u.asInt64);
}

ALWAYS_INLINE bool JSValue::isDouble() const
{
	return isNumber() && !isInt32();
}

ALWAYS_INLINE JSValue::JSValue(JSNullTag)
{
	u.asInt64 = ValueNull;
}

ALWAYS_INLINE JSValue::JSValue(JSUndefinedTag)
{
	u.asInt64 = ValueUndefined;
}

ALWAYS_INLINE JSValue::JSValue(JSTrueTag)
{
	u.asInt64 = ValueTrue;
}

ALWAYS_INLINE JSValue::JSValue(JSFalseTag)
{
	u.asInt64 = ValueFalse;
}

ALWAYS_INLINE bool JSValue::isUndefinedOrNull() const
{
	// Undefined and null share the same value, bar the 'undefined' bit in the extended tag.
	return (u.asInt64 & ~TagBitUndefined) == ValueNull;
}

ALWAYS_INLINE bool JSValue::isBoolean() const
{
	return (u.asInt64 & ~1) == ValueFalse;
}

ALWAYS_INLINE bool JSValue::isCell() const
{
	return !(u.asInt64 & TagMask);
}

ALWAYS_INLINE bool JSValue::isInt32() const
{
	return (u.asInt64 & TagTypeNumber) == TagTypeNumber;
}

ALWAYS_INLINE int64_t reinterpretDoubleToInt64(double value)
{
	return bitwise_cast<int64_t>(value);
}
ALWAYS_INLINE double reinterpretInt64ToDouble(int64_t value)
{
	return bitwise_cast<double>(value);
}

ALWAYS_INLINE JSValue::JSValue(EncodeAsDoubleTag, double d)
{
    ASSERT(!isImpureNaN(d));
	u.asInt64 = reinterpretDoubleToInt64(d) + DoubleEncodeOffset;
}

ALWAYS_INLINE JSValue::JSValue(int i)
{
	u.asInt64 = TagTypeNumber | static_cast<uint32_t>(i);
}

ALWAYS_INLINE double JSValue::asDouble() const
{
	ASSERT(isDouble());
	return reinterpretInt64ToDouble(u.asInt64 - DoubleEncodeOffset);
}

ALWAYS_INLINE bool JSValue::isNumber() const
{
	return u.asInt64 & TagTypeNumber;
}

ALWAYS_INLINE JSCell* JSValue::asCell() const
{
	ASSERT(isCell());
	return u.ptr;
}

ALWAYS_INLINE JSBigInt* JSValue::asHeapBigInt() const
{
    ASSERT(isHeapBigInt());
    return static_cast<JSBigInt*>(u.ptr);
}

#endif // USE(JSVALUE64)

#if USE(BIGINT32)
inline JSValue::JSValue(JSBigInt32Tag, int32_t value)
{
    uint64_t shiftedValue = static_cast<uint64_t>(static_cast<uint32_t>(value)) << 16;
    ASSERT(!(shiftedValue & NumberTag));
    u.asInt64 = shiftedValue | BigInt32Tag;
}
#endif // USE(BIGINT32)

inline int64_t tryConvertToInt52(double number)
{
    if (number != number)
        return JSValue::notInt52;
#if OS(WINDOWS) && CPU(X86)
    // The VS Compiler for 32-bit builds generates a floating point error when attempting to cast
    // from an infinity to a 64-bit integer. We leave this routine with the floating point error
    // left in a register, causing undefined behavior in later floating point operations.
    //
    // To avoid this issue, we check for infinity here, and return false in that case.
    if (std::isinf(number))
        return JSValue::notInt52;
#endif
    int64_t asInt64 = static_cast<int64_t>(number);
    if (asInt64 != number)
        return JSValue::notInt52;
    if (!asInt64 && std::signbit(number))
        return JSValue::notInt52;
    if (asInt64 >= (static_cast<int64_t>(1) << (JSValue::numberOfInt52Bits - 1)))
        return JSValue::notInt52;
    if (asInt64 < -(static_cast<int64_t>(1) << (JSValue::numberOfInt52Bits - 1)))
        return JSValue::notInt52;
    return asInt64;
}

inline bool isInt52(double number)
{
    return tryConvertToInt52(number) != JSValue::notInt52;
}

inline bool JSValue::isAnyInt() const
{
    if (isInt32())
        return true;
    if (!isNumber())
        return false;
    return isInt52(asDouble());
}

ALWAYS_INLINE int64_t JSValue::asAnyInt() const
{
    ASSERT(isAnyInt());
    if (isInt32())
        return asInt32();
    return static_cast<int64_t>(asDouble());
}

inline bool JSValue::isInt32AsAnyInt() const
{
    if (!isAnyInt())
        return false;
    int64_t value = asAnyInt();
    return value >= INT32_MIN && value <= INT32_MAX;
}

inline int32_t JSValue::asInt32AsAnyInt() const
{
    ASSERT(isInt32AsAnyInt());
    if (isInt32())
        return asInt32();
    return static_cast<int32_t>(asDouble());
}

inline bool JSValue::isUInt32AsAnyInt() const
{
    if (!isAnyInt())
        return false;
    int64_t value = asAnyInt();
    return value >= 0 && value <= UINT32_MAX;
}

inline uint32_t JSValue::asUInt32AsAnyInt() const
{
    ASSERT(isUInt32AsAnyInt());
    if (isUInt32())
        return asUInt32();
    return static_cast<uint32_t>(asDouble());
}

ALWAYS_INLINE bool JSValue::isString() const
{
	return isCell() && asCell()->isString();
}

inline bool JSValue::isBigInt() const
{
    return isBigInt32() || isHeapBigInt();
}

inline bool JSValue::isHeapBigInt() const
{
    return isCell() && asCell()->isHeapBigInt();
}

inline bool JSValue::isBigInt32() const
{
#if USE(BIGINT32)
    return (u.asInt64 & BigInt32Mask) == BigInt32Tag;
#else
    return false;
#endif
}

#if USE(BIGINT32)
inline int32_t JSValue::bigInt32AsInt32() const
{
    ASSERT(isBigInt32());
    return static_cast<int32_t>(u.asInt64 >> 16);
}
#endif // USE(BIGINT32)

ALWAYS_INLINE bool JSValue::isSymbol() const
{
    return isCell() && asCell()->isSymbol();
}

ALWAYS_INLINE bool JSValue::isPrimitive() const
{
    return !isCell() || asCell()->isString() || asCell()->isSymbol() || asCell()->isHeapBigInt();
}

ALWAYS_INLINE bool JSValue::isGetterSetter() const
{
	return isCell() && asCell()->isGetterSetter();
}

ALWAYS_INLINE bool JSValue::isCustomGetterSetter() const
{
    return isCell() && asCell()->isCustomGetterSetter();
}

ALWAYS_INLINE bool JSValue::isObject() const
{
	return isCell() && asCell()->isObject();
}

ALWAYS_INLINE bool JSValue::getString(ExecState* exec, String& s) const
{
	return isCell() && asCell()->getString(exec, s);
}

ALWAYS_INLINE String JSValue::getString(ExecState* exec) const
{
	return isCell() ? asCell()->getString(exec) : String();
}

template <typename Base> ALWAYS_INLINE String HandleConverter<Base, Unknown>::getString(ExecState* exec) const
{
	return jsValue().getString(exec);
}

ALWAYS_INLINE JSObject* JSValue::getObject() const
{
	return isCell() ? asCell()->getObject() : 0;
}

ALWAYS_INLINE bool JSValue::getUInt32(uint32_t& v) const
{
	if (isInt32()) {
		int32_t i = asInt32();
		v = static_cast<uint32_t>(i);
		return i >= 0;
	}
	if (isDouble()) {
		double d = asDouble();
		v = static_cast<uint32_t>(d);
		return v == d;
	}
	return false;
}

ALWAYS_INLINE Identifier JSValue::toPropertyKey(JSGlobalData& vm, ExecState* exec) const
{
    if (isString())
        return asString(*this)->toIdentifier(vm, exec);

    JSValue primitive = toPrimitive(exec, PreferString);
    RETURN_IF_EXCEPTION(vm, vm.propertyNames->emptyIdentifier);
    if (primitive.isSymbol())
        return Identifier::fromUid(asSymbol(primitive)->privateName());
    return primitive.toString(exec)->toIdentifier(vm, exec);
}

ALWAYS_INLINE JSValue JSValue::toPropertyKeyValue(JSGlobalData& vm, ExecState* exec) const
{
    auto scope = DECLARE_THROW_SCOPE(vm);

    if (isString() || isSymbol())
        return *this;

    JSValue primitive = toPrimitive(exec, PreferString);
    RETURN_IF_EXCEPTION(scope, jsUndefined());
    if (primitive.isSymbol())
        return primitive;

    RELEASE_AND_RETURN(scope, primitive.toString(exec));
}

ALWAYS_INLINE JSValue JSValue::toPrimitive(ExecState* exec, PreferredPrimitiveType preferredType) const
{
	return isCell() ? asCell()->toPrimitive(exec, preferredType) : asValue();
}

inline PreferredPrimitiveType toPreferredPrimitiveType(ExecState* exec, JSValue value)
{
	VM& vm = exec->vm();
    if (!value.isString()) {
        throwTypeError(exec, vm, ASCIILiteral("Primitive hint is not a string."));
        return NoPreference;
    }

    String hintString = asString(value)->value(exec);
    RETURN_IF_EXCEPTION(vm, NoPreference);

    if (WTF::equal(hintString, "default"))
        return NoPreference;
    if (WTF::equal(hintString, "number"))
        return PreferNumber;
    if (WTF::equal(hintString, "string"))
        return PreferString;

    throwTypeError(exec, vm, ASCIILiteral("Expected primitive hint to match one of 'default', 'number', 'string'."));
    return NoPreference;
}

ALWAYS_INLINE double JSValue::toNumber(ExecState* exec) const
{
	if (isInt32())
		return asInt32();
	if (isDouble())
		return asDouble();
	return toNumberSlowCase(exec);
}

ALWAYS_INLINE JSValue JSValue::toNumeric(ExecState* exec) const
{
    VM& vm = exec->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    if (isInt32() || isDouble() || isBigInt())
        return *this;

    JSValue primValue = this->toPrimitive(exec, PreferNumber);
    RETURN_IF_EXCEPTION(scope, JSValue());

    if (primValue.isDouble() || primValue.isBigInt())
        return primValue;

    double value = primValue.toNumber(exec);
    RETURN_IF_EXCEPTION(scope, JSValue());

    return jsNumber(value);
}

ALWAYS_INLINE Optional<uint32_t> JSValue::toUInt32AfterToNumeric(ExecState* exec) const
{
    VM& vm = exec->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);
    auto result = toBigIntOrInt32(exec);
    RETURN_IF_EXCEPTION(scope, WTF::Nullopt);
    if (LIKELY(result.isInt32()))
        return static_cast<uint32_t>(result.asInt32());
    return WTF::Nullopt;
}

ALWAYS_INLINE JSValue JSValue::toBigIntOrInt32(ExecState* exec) const
{
    VM& vm = exec->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    if (isInt32() || isBigInt())
        return *this;
    if (isDouble() && canBeInt32(asDouble()))
        return jsNumber(static_cast<int32_t>(asDouble()));

    JSValue primValue = this->toPrimitive(exec, PreferNumber);
    RETURN_IF_EXCEPTION(scope, JSValue());

    if (primValue.isInt32() || primValue.isBigInt())
        return primValue;

    int32_t value = primValue.toInt32(exec);
    RETURN_IF_EXCEPTION(scope, JSValue());
    return jsNumber(value);
}

ALWAYS_INLINE JSObject* JSValue::toObject(ExecState* exec) const
{
	return isCell() ? asCell()->toObject(exec, exec->lexicalGlobalObject()) : toObjectSlowCase(exec, exec->lexicalGlobalObject());
}

ALWAYS_INLINE JSObject* JSValue::toObject(ExecState* exec, JSGlobalObject* globalObject) const
{
	return isCell() ? asCell()->toObject(exec, globalObject) : toObjectSlowCase(exec, globalObject);
}

inline bool JSValue::isCallable() const
{
    return isCell() && asCell()->isCallable();
}

inline bool JSValue::isCallable(VM&) const
{
	return isCallable();
}

inline bool JSValue::isConstructor() const
{
    return isCell() && asCell()->isConstructor();
}

// this method is here to be after the inline declaration of JSCell::inherits
ALWAYS_INLINE bool JSValue::inherits(const ClassInfo* classInfo) const
{
    return isCell() && asCell()->inherits(classInfo);
}

template<typename T>
ALWAYS_INLINE bool JSValue::inherits() const
{
    return isCell() && asCell()->inherits<T>();
}

template<typename T>
ALWAYS_INLINE bool JSValue::inherits(VM& vm) const
{
    return isCell() && asCell()->inherits<T>(vm);
}

ALWAYS_INLINE JSValue JSValue::toThis(ExecState* exec, ECMAMode ecmaMode) const
{
	if (isObject()) {
		if (asObject(*this)->inherits<JSScope>())
			return ecmaMode.isStrict() ? jsUndefined() : exec->globalThisValue();
		return *this;
	}

	if (ecmaMode.isStrict())
		return *this;

	ASSERT(!ecmaMode.isStrict());
	if (isUndefinedOrNull())
		return exec->globalThisValue();

	return toThisSloppySlowCase(exec);
}

ALWAYS_INLINE JSValue JSValue::get(VM& vm, ExecState* exec, PropertyName propertyName) const
{
    PropertySlot slot(asValue(), PropertySlot::InternalMethodType::Get);
    return get(vm, exec, propertyName, slot);
}

ALWAYS_INLINE JSValue JSValue::get(VM& vm, ExecState* exec, PropertyName propertyName, PropertySlot& slot) const
{
    bool hasSlot = getPropertySlot(vm, exec, propertyName, slot);
    ASSERT(!exec->vm().exception() || !hasSlot);
    if (!hasSlot)
        return jsUndefined();
    return slot.getValue(exec, propertyName);
}

#if 0
template<typename CallbackWhenNoException>
ALWAYS_INLINE typename std::result_of<CallbackWhenNoException(bool, PropertySlot&)>::type JSValue::getPropertySlot(ExecState* exec, PropertyName propertyName, CallbackWhenNoException callback) const
{
    PropertySlot slot(asValue(), PropertySlot::InternalMethodType::Get);
    return getPropertySlot(exec, propertyName, slot, callback);
}

template<typename CallbackWhenNoException>
ALWAYS_INLINE typename std::result_of<CallbackWhenNoException(bool, PropertySlot&)>::type JSValue::getPropertySlot(ExecState* exec, PropertyName propertyName, PropertySlot& slot, CallbackWhenNoException callback) const
{
	VM& vm = exec->vm();
    bool found = getPropertySlot(exec, propertyName, slot);
    if (UNLIKELY(vm.exception()))
        return { };
    return callback(found, slot);
}
#endif

template<bool maybeIndex>
ALWAYS_INLINE bool JSValue::getPropertySlot(JSGlobalData& vm, ExecState* exec, const PropertyName& propertyName, PropertySlot& slot) const
{
    // If this is a primitive, we'll need to synthesize the prototype -
    // and if it's a string there are special properties to check first.
    JSObject* object;
    if (UNLIKELY(!isObject())) {
        if (isString()) {
            bool hasProperty = asString(*this)->getStringPropertySlot<maybeIndex>(vm, exec, propertyName, slot);
            RETURN_IF_EXCEPTION(vm, false);
            if (hasProperty)
                return true;
        }
        object = synthesizePrototype(exec);
        if (UNLIKELY(!object))
            return false;
    } else
        object = asObject(asCell());

    return object->getPropertySlot<maybeIndex>(vm, exec, propertyName, slot);
}

ALWAYS_INLINE bool JSValue::getOwnPropertySlot(ExecState* exec, const PropertyName& propertyName, PropertySlot& slot) const
{
    // If this is a primitive, we'll need to synthesize the prototype -
    // and if it's a string there are special properties to check first.
	VM& vm = exec->vm();
	ThrowScope scope(vm);
    if (UNLIKELY(!isObject())) {
        if (isString()) {
            scope.release();
            return asString(*this)->getStringPropertySlot(vm, exec, propertyName, slot);
        }
        if (isUndefinedOrNull())
            throwException(exec, scope, createNotAnObjectError(exec, *this));
        return false;
    }
    scope.release();
    return asObject(asCell())->getOwnPropertySlotInline(vm, exec, propertyName, slot);
}

ALWAYS_INLINE JSValue JSValue::get(VM& vm, ExecState* exec, unsigned propertyName) const
{
    PropertySlot slot(asValue(), PropertySlot::InternalMethodType::Get);
    return get(vm, exec, propertyName, slot);
}

ALWAYS_INLINE JSValue JSValue::get(VM& vm, ExecState* exec, unsigned propertyName, PropertySlot& slot) const
{
    // If this is a primitive, we'll need to synthesize the prototype -
    // and if it's a string there are special properties to check first.
    JSObject* object;
    if (UNLIKELY(!isObject())) {
        if (isString()) {
            bool hasProperty = asString(*this)->getStringPropertySlot(vm, exec, propertyName, slot);
            RETURN_IF_EXCEPTION(vm, jsUndefined());
            if (hasProperty) {
                return slot.getValue(vm, exec, propertyName);
            }
        }
        object = synthesizePrototype(exec);
        if (UNLIKELY(!object))
            return jsUndefined();
    } else
        object = asObject(asCell());

    bool hasSlot = object->getPropertySlot(vm, exec, propertyName, slot);
    // EXCEPTION_ASSERT(!scope.exception() || !hasSlot);
    if (!hasSlot)
        return jsUndefined();
    // scope.release();
    return slot.getValue(vm, exec, propertyName);
}

ALWAYS_INLINE JSValue JSValue::get(VM& vm, ExecState* exec, uint64_t propertyName) const
{
    if (LIKELY(propertyName <= std::numeric_limits<unsigned>::max()))
        return get(vm, exec, static_cast<unsigned>(propertyName));
    return get(vm, exec, Identifier::from(vm, static_cast<double>(propertyName)));
}

ALWAYS_INLINE bool JSValue::put(ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
    if (LIKELY(isCell()))
    	return asCell()->methodTable()->put(asCell(), exec, propertyName, value, slot);
    return putToPrimitive(exec, propertyName, value, slot);
}

ALWAYS_INLINE bool JSValue::putInline(ExecState* exec, VM& vm, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
    if (UNLIKELY(!isCell()))
        return putToPrimitive(exec, propertyName, value, slot);
    return asCell()->putInline(exec, vm, propertyName, value, slot);
}

ALWAYS_INLINE bool JSValue::putByIndex(ExecState* exec, unsigned propertyName, JSValue value, bool shouldThrow)
{
    if (LIKELY(isCell()))
    	return asCell()->methodTable()->putByIndex(asCell(), exec, propertyName, value, shouldThrow);
    return putToPrimitiveByIndex(exec, propertyName, value, shouldThrow);
}

ALWAYS_INLINE JSValue JSValue::getPrototype(VM& vm, ExecState* exec) const
{
    if (isObject())
        return asObject(asCell())->getPrototype(vm, exec);
    return synthesizePrototype(exec);
}

inline Structure* JSValue::structureOrNull() const
{
    if (isCell())
        return asCell()->structure();
    return 0;
}

ALWAYS_INLINE JSValue JSValue::structureOrUndefined() const
{
	if (isCell())
		return JSValue(asCell()->structure());
	return jsUndefined();
}

// ECMA 11.9.3
ALWAYS_INLINE bool JSValue::equal(ExecState* exec, JSValue v1, JSValue v2)
{
	if (v1.isInt32() && v2.isInt32())
		return v1 == v2;

	return equalSlowCase(exec, v1, v2);
}

inline bool JSValue::equalSlowCaseInline(ExecState* exec, JSValue v1, JSValue v2)
{
    VM& vm = exec->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);
	do {
        if (v1.isNumber()) {
            if (v2.isNumber())
                return v1.asNumber() == v2.asNumber();
            // Guaranteeing that if we have a number it is v2 makes some of the cases below simpler.
            std::swap(v1, v2);
        }

        // This deals with Booleans, BigInt32, Objects, and is a shortcut for a few more types.
        // It has to come here and not before, because it is NOT true that NaN == NaN
        if (v1 == v2)
            return true;

		if (v1.isUndefinedOrNull()) {
			if (v2.isUndefinedOrNull())
				return true;
			if (!v2.isCell())
				return false;
			return v2.asCell()->structure()->masqueradesAsUndefined(exec->lexicalGlobalObject());
		}

		if (v2.isUndefinedOrNull()) {
			if (!v1.isCell())
				return false;
			return v1.asCell()->structure()->masqueradesAsUndefined(exec->lexicalGlobalObject());
		}

		if (v1.isObject()) {
			if (v2.isObject())
                return false; // v1 == v2 is already dealt with previously
			JSValue p1 = v1.toPrimitive(exec);
            RETURN_IF_EXCEPTION(vm, false);
			v1 = p1;
			if (v1.isInt32() && v2.isInt32())
				return v1 == v2;
			continue;
		}

		if (v2.isObject()) {
			JSValue p2 = v2.toPrimitive(exec);
            RETURN_IF_EXCEPTION(vm, false);
			v2 = p2;
			if (v1.isInt32() && v2.isInt32())
				return v1 == v2;
			continue;
		}

        bool sym1 = v1.isSymbol();
        bool sym2 = v2.isSymbol();
        if (sym1 || sym2) {
            if (sym1 && sym2)
                return false; // v1 == v2 is already dealt with previously
            return false;
        }

        bool s1 = v1.isString();
        bool s2 = v2.isString();
        if (s1) {
            if (s2)
                RELEASE_AND_RETURN(scope, asString(v1)->equal(exec, asString(v2)));
            std::swap(v1, v2);
            // We are guaranteed to enter the next case, so losing the invariant of only v2 being a number is fine
        }
        if (s1 || s2) {
            // We are guaranteed that the string is v2 (thanks to the swap above)
            if (v1.isBigInt()) {
                String v2String = asString(v2)->value(exec);
                RETURN_IF_EXCEPTION(scope, false);
                v2 = JSBigInt::stringToBigInt(exec, v2String);
                RETURN_IF_EXCEPTION(scope, false);
                if (!v2)
                    return false;
                if (v1 == v2)
                    return true; // For BigInt32
                // We fallthrough to the generic code for comparing BigInts (which is only missing the BigInt32/BigInt32 case, hence the check above)
            } else {
                ASSERT(v1.isNumber() || v1.isBoolean());
				double d1 = v1.toNumber(exec);
				RETURN_IF_EXCEPTION(vm, false);
				double d2 = v2.toNumber(exec);
				RETURN_IF_EXCEPTION(vm, false);
				return d1 == d2;
            }
		}

        if (v1.isBoolean()) {
            if (v2.isNumber())
                return static_cast<double>(v1.asBoolean()) == v2.asNumber();
            v1 = JSValue(v1.toNumber(exec));
            RETURN_IF_EXCEPTION(scope, false);
            // We fallthrough to the BigInt/Number comparison below
            // We just need one more swap to repair the rule that only v2 is allowed to be a number in these comparisons
            std::swap(v1, v2);
        } else if (v2.isBoolean()) {
            v2 = JSValue(v2.toNumber(exec));
            RETURN_IF_EXCEPTION(scope, false);
            // We fallthrough to the BigInt/Number comparison below
        }

#if USE(BIGINT32)
        if (v1.isBigInt32()) {
            if (v2.isInt32())
                return v1.bigInt32AsInt32() == v2.asInt32();
            if (v2.isDouble())
                return static_cast<double>(v1.bigInt32AsInt32()) == v2.asDouble();
            std::swap(v1, v2);
        }
#endif // USE(BIGINT32)

        if (v1.isHeapBigInt()) {
            if (v2.isHeapBigInt())
                return JSBigInt::equals(v1.asHeapBigInt(), v2.asHeapBigInt());
#if USE(BIGINT32)
            if (v2.isBigInt32())
                return v1.asHeapBigInt()->equalsToInt32(v2.bigInt32AsInt32());
#endif // USE(BIGINT32)
            if (v2.isNumber())
                return v1.asHeapBigInt()->equalsToNumber(v2);
        }

        return false;
    } while (true);

    return false;
}

// ECMA 11.9.3
ALWAYS_INLINE bool JSValue::strictEqualForCells(ExecState* exec, JSCell* v1, JSCell* v2)
{
    if (v1->isString() && v2->isString())
        return asString(v1)->equal(exec, asString(v2));
    if (v1->isHeapBigInt() && v2->isHeapBigInt())
        return JSBigInt::equals(static_cast<JSBigInt*>(v1), static_cast<JSBigInt*>(v2));
    return v1 == v2;
}

inline bool JSValue::strictEqual(ExecState* exec, JSValue v1, JSValue v2)
{
	if (v1.isInt32() && v2.isInt32())
		return v1 == v2;

	if (v1.isNumber() && v2.isNumber())
		return v1.asNumber() == v2.asNumber();

#if USE(BIGINT32)
    if (v1.isHeapBigInt() && v2.isBigInt32())
        return v1.asHeapBigInt()->equalsToInt32(v2.bigInt32AsInt32());
    if (v1.isBigInt32() && v2.isHeapBigInt())
        return v2.asHeapBigInt()->equalsToInt32(v1.bigInt32AsInt32());
#endif

    if (v1.isCell() && v2.isCell())
        return strictEqualForCells(exec, v1.asCell(), v2.asCell());

    return v1 == v2;
}

inline int32_t JSValue::asInt32ForArithmetic() const
{
    if (isBoolean())
        return asBoolean();
    return asInt32();
}

inline TriState JSValue::pureStrictEqual(JSValue v1, JSValue v2)
{
    if (v1.isInt32() && v2.isInt32())
        return triState(v1 == v2);

    if (v1.isNumber() && v2.isNumber())
        return triState(v1.asNumber() == v2.asNumber());

#if USE(BIGINT32)
    if (v1.isHeapBigInt() && v2.isBigInt32())
        return triState(v1.asHeapBigInt()->equalsToInt32(v2.bigInt32AsInt32()));
    if (v1.isBigInt32() && v2.isHeapBigInt())
        return triState(v2.asHeapBigInt()->equalsToInt32(v1.bigInt32AsInt32()));
#endif

    if (v1.isCell() && v2.isCell()) {
		if (v1.asCell()->isString() && v2.asCell()->isString()) {
			const StringImpl* v1String = asString(v1)->tryGetValueImpl();
			const StringImpl* v2String = asString(v2)->tryGetValueImpl();
			if (!v1String || !v2String)
				return MixedTriState;
			return triState(WTF::equal(*v1String, *v2String));
		}
        if (v1.asCell()->isHeapBigInt() && v2.asCell()->isHeapBigInt())
            return triState(JSBigInt::equals(v1.asHeapBigInt(), v2.asHeapBigInt()));
    }

    return triState(v1 == v2);
}

inline TriState JSValue::pureToBoolean() const
{
    if (isInt32())
        return asInt32() ? TrueTriState : FalseTriState;
    if (isDouble())
		return isNotZeroAndOrdered(asDouble()) ? TrueTriState : FalseTriState; // false for NaN
	if (isCell())
        return asCell()->pureToBoolean();
#if USE(BIGINT32)
    if (isBigInt32())
        return bigInt32AsInt32() ? TrueTriState : FalseTriState;
#endif
    return isTrue() ? TrueTriState : FalseTriState;
}

ALWAYS_INLINE bool JSValue::requireObjectCoercible(VM& vm, ExecState* exec) const
{
    if (LIKELY(!isUndefinedOrNull()))
        return true;
    vm.throwException(exec, createNotAnObjectError(exec, *this));
    return false;
}

ALWAYS_INLINE bool isThisValueAltered(const PutPropertySlot& slot, JSObject* baseObject)
{
    JSValue thisValue = slot.thisValue();
    if (LIKELY(thisValue == baseObject))
        return false;

    if (!thisValue.isObject())
        return true;
    JSObject* thisObject = asObject(thisValue);
    // Only PureForwardingProxyType can be seen as the same to the original target object.
    if (thisObject->structure()->typeInfo().type() == PureForwardingProxyType && jsCast<JSProxy*>(thisObject)->target() == baseObject)
        return false;
    return true;
}

// See section 7.2.9: https://tc39.github.io/ecma262/#sec-samevalue
ALWAYS_INLINE bool sameValue(ExecState* exec, JSValue a, JSValue b)
{
    if (!a.isNumber())
        return JSValue::strictEqual(exec, a, b);
    if (!b.isNumber())
        return false;
    double x = a.asNumber();
    double y = b.asNumber();
    bool xIsNaN = std::isnan(x);
    bool yIsNaN = std::isnan(y);
    if (xIsNaN || yIsNaN)
        return xIsNaN && yIsNaN;
    return bitwise_cast<uint64_t>(x) == bitwise_cast<uint64_t>(y);
}

} // namespace JSC
