/*
 *  Copyright (C) 1999-2002 Harri Porten (porten@kde.org)
 *  Copyright (C) 2001 Peter Kelly (pmk@post.com)
 *  Copyright (C) 2004, 2007, 2008 Apple Inc. All rights reserved.
 *
 *  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
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 *
 */

#include "config.h"
#include "InternalFunction.h"

#include "FunctionPrototype.h"
#include "JSBoundFunction.h"
#include "JSGlobalObject.h"
#include "JSString.h"
#include "Operations.h"
#include "ProxyObject.h"

namespace JSC {

ASSERT_HAS_TRIVIAL_DESTRUCTOR(InternalFunction);

const ClassInfo InternalFunction::s_info = { "Function", &Base::s_info, 0, CREATE_METHOD_TABLE(InternalFunction) };

InternalFunction::InternalFunction(VM& vm, Structure* structure, NativeFunction functionForCall, NativeFunction functionForConstruct)
    : Base(vm, structure)
	, m_functionForCall(functionForCall)
	, m_functionForConstruct(functionForConstruct ? functionForConstruct : callHostFunctionAsConstructor)
	, m_globalObject(vm, this, structure->globalObject())
{
    ASSERT_WITH_MESSAGE(m_functionForCall, "[[Call]] must be implemented");
    ASSERT(m_functionForConstruct);

    ASSERT(inherits(info()));
    ASSERT(methodTable(vm)->getCallData == InternalFunction::info()->methodTable.getCallData);
    ASSERT(methodTable(vm)->getConstructData == InternalFunction::info()->methodTable.getConstructData);
    ASSERT(type() == InternalFunctionType || type() == NullSetterFunctionType);
}

void InternalFunction::finishCreation(JSGlobalData& vm, const String& name)
{
    Base::finishCreation(vm);

    JSString* nameString = jsString(vm, name);
	m_originalName.set(vm, this, nameString);
	putDirect(vm, vm.propertyNames->name, nameString, ReadOnly | DontEnum);
}

void InternalFunction::finishCreation(VM& vm)
{
    Base::finishCreation(vm);
}

void InternalFunction::visitChildren(JSCell* cell, SlotVisitor& visitor)
{
	InternalFunction* thisObject = jsCast<InternalFunction*>(cell);
	ASSERT_GC_OBJECT_INHERITS(thisObject, info());
	Base::visitChildren(thisObject, visitor);

	visitor.append(thisObject->m_originalName);
    visitor.append(thisObject->m_globalObject);
}

const String& InternalFunction::name()
{
	const String& name = m_originalName->tryGetValue();
	ASSERT(name); // m_originalName was built from a String, and hence, there is no rope to resolve.
	return name;
}

const String InternalFunction::displayName(VM& vm)
{
    JSValue displayName = getDirect(vm, vm.propertyNames->displayName);
    
    if (displayName && isJSString(displayName))
        return asString(displayName)->tryGetValue();
    
    return String();
}

CallData InternalFunction::getCallData(JSCell* cell)
{
    auto* function = jsCast<InternalFunction*>(cell);
    ASSERT(function->m_functionForCall);
    CallData callData;
    callData.type = CallData::Type::Native;
    callData.native.function = function->m_functionForCall;
    return callData;
}

CallData InternalFunction::getConstructData(JSCell* cell)
{
    CallData constructData;
    auto* function = jsCast<InternalFunction*>(cell);
    if (function->m_functionForConstruct != callHostFunctionAsConstructor) {
        constructData.type = CallData::Type::Native;
        constructData.native.function = function->m_functionForConstruct;
    }
    return constructData;
}

const String InternalFunction::calculatedDisplayName(VM& vm)
{
    const String explicitName = displayName(vm);
    
    if (!explicitName.isEmpty())
        return explicitName;
    
    return name();
}

Structure* InternalFunction::createSubclassStructure(ExecState* exec, JSGlobalObject* globalObject, JSObject* newTarget, Structure* baseClass)
{
    VM& vm = globalObject->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);
    JSGlobalObject* baseGlobalObject = baseClass->globalObject();

    ASSERT(!newTarget || newTarget.isCallable());
    ASSERT(newTarget && newTarget != exec->jsCallee());

	// newTarget may be an InternalFunction if we were called from Reflect.construct.
	JSFunction* targetFunction = jsDynamicCast<JSFunction*>(newTarget);

    if (UNLIKELY(!targetFunction || !targetFunction->canUseAllocationProfiles(vm))) {
        JSValue prototypeValue = newTarget->get(vm, exec, vm.propertyNames->prototype);
        RETURN_IF_EXCEPTION(scope, nullptr);
        if (JSObject* prototype = jsDynamicCast<JSObject*>(prototypeValue)) {
            // This only happens if someone Reflect.constructs our builtin constructor with another builtin constructor or weird .prototype property on a
            // JSFunction as the new.target. Thus, we don't care about the cost of looking up the structure from our hash table every time.
            return baseGlobalObject->structureCache().emptyStructureForPrototypeFromBaseStructure(baseGlobalObject, prototype, baseClass);
        }
        return baseClass;
    }

	FunctionRareData* rareData = targetFunction->rareData(vm);
	Structure* structure = rareData->internalFunctionAllocationStructure();
	if (LIKELY(structure && structure->classInfo() == baseClass->classInfo() && structure->globalObject() == baseGlobalObject))
		return structure;

	// .prototype can't be a getter if we canUseAllocationProfiles().
	JSValue prototypeValue = newTarget->get(vm, exec, vm.propertyNames->prototype);
	scope.assertNoException();

	if (JSObject* prototype = jsDynamicCast<JSObject*>(prototypeValue))
		return rareData->createInternalFunctionAllocationStructureFromBase(vm, baseGlobalObject, prototype, baseClass);

    return baseClass;
}

InternalFunction* InternalFunction::createFunctionThatMasqueradesAsUndefined(VM& vm, JSGlobalObject* globalObject, int length, const String& name, NativeFunction nativeFunction)
{
    Structure* structure = Structure::create(vm, globalObject, globalObject->objectPrototype(), TypeInfo(InternalFunctionType, InternalFunction::StructureFlags | MasqueradesAsUndefined), InternalFunction::info());
    globalObject->masqueradesAsUndefinedWatchpoint()->fireAll(globalObject->vm(), "Allocated masquerading object");
    InternalFunction* function = new (NotNull, allocateCell<InternalFunction>(vm.heap)) InternalFunction(vm, structure, nativeFunction);
    function->finishCreation(vm, name/*, NameAdditionMode::WithoutStructureTransition*/);
    function->putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(length), PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum);
    return function;
}

// https://tc39.es/ecma262/#sec-getfunctionrealm
JSGlobalObject* getFunctionRealm(ExecState* exec, JSGlobalObject* globalObject, JSObject* object)
{
    VM& vm = globalObject->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    ASSERT(object->isCallable(vm));

    while (true) {
        if (object->inherits<JSBoundFunction>(vm)) {
            object = jsCast<JSBoundFunction*>(object)->targetFunction();
            continue;
        }

        if (object->structure()->typeInfo().type() == ProxyObjectType) {
            auto* proxy = jsCast<ProxyObject*>(object);
            if (proxy->isRevoked()) {
                throwTypeError(exec, vm, "Cannot get function realm from revoked Proxy");
                return nullptr;
            }
			object = proxy->target();
			continue;
        }

        return object->globalObject();
    }

    return nullptr;
}

} // namespace JSC
