/*!
  \internal
  \since 4.5

  Adds the given \a object to the front of this context's scope chain.

  If \a object is not an object, this function does nothing.
*/
void QScriptContext::pushScope(const QScriptValue &object)
{
    activationObject(); //ensure the creation of the normal scope for native context
    if (!object.isObject())
        return;
    else if (object.engine() != engine()) {
        qWarning("QScriptContext::pushScope() failed: "
                 "cannot push an object created in "
                 "a different engine");
        return;
    }
    JSC::CallFrame *frame = QScriptEnginePrivate::frameForContext(this);
    QScriptEnginePrivate *engine = QScript::scriptEngineFromExec(frame);
    QScript::APIShim shim(engine);
    JSC::JSObject *jscObject = JSC::asObject(engine->scriptValueToJSCValue(object));
    if (jscObject == engine->originalGlobalObjectProxy)
        jscObject = engine->originalGlobalObject();
    JSC::ScopeChainNode *scope = frame->scopeChain();
    Q_ASSERT(scope != 0);
    if (!scope->object) {
        // pushing to an "empty" chain
        if (!jscObject->isGlobalObject()) {
            qWarning("QScriptContext::pushScope() failed: initial object in scope chain has to be the Global Object");
            return;
        }
        scope->object = jscObject;
    }
    else
        frame->setScopeChain(scope->push(jscObject));
}
/*!
  Returns true if the function was called as a constructor
  (e.g. \c{"new foo()"}); otherwise returns false.

  When a function is called as constructor, the thisObject()
  contains the newly constructed object to be initialized.

  \note This function is only guaranteed to work for a context
  corresponding to native functions.
*/
bool QScriptContext::isCalledAsConstructor() const
{
    JSC::CallFrame *frame = const_cast<JSC::ExecState*>(QScriptEnginePrivate::frameForContext(this));
    QScript::APIShim shim(QScript::scriptEngineFromExec(frame));

    //For native functions, look up flags.
    uint flags = QScriptEnginePrivate::contextFlags(frame);
    if (flags & QScriptEnginePrivate::NativeContext)
        return flags & QScriptEnginePrivate::CalledAsConstructorContext;

    //Not a native function, try to look up in the bytecode if we where called from op_construct
    JSC::Instruction* returnPC = frame->returnPC();

    if (!returnPC)
        return false;

    JSC::CallFrame *callerFrame = QScriptEnginePrivate::frameForContext(parentContext());
    if (!callerFrame)
        return false;

    if (returnPC[-JSC::op_construct_length].u.opcode == frame->interpreter()->getOpcode(JSC::op_construct)) {
        //We are maybe called from the op_construct opcode which has 6 opperands.
        //But we need to check we are not called from op_call with 4 opperands

        //we make sure that the returnPC[-1] (thisRegister) is smaller than the returnPC[-3] (registerOffset)
        //as if it was an op_call, the returnPC[-1] would be the registerOffset, bigger than returnPC[-3] (funcRegister)
        return returnPC[-1].u.operand < returnPC[-3].u.operand;
    }
    return false;
}
/*!
  Sets the `this' object associated with this QScriptContext to be
  \a thisObject.

  If \a thisObject is not an object, this function does nothing.
*/
void QScriptContext::setThisObject(const QScriptValue &thisObject)
{
    JSC::CallFrame *frame = QScriptEnginePrivate::frameForContext(this);
    QScript::APIShim shim(QScript::scriptEngineFromExec(frame));
    if (!thisObject.isObject())
        return;
    if (thisObject.engine() != engine()) {
        qWarning("QScriptContext::setThisObject() failed: "
                 "cannot set an object created in "
                 "a different engine");
        return;
    }
    if (frame == frame->lexicalGlobalObject()->globalExec()) {
        engine()->setGlobalObject(thisObject);
        return;
    }
    JSC::JSValue jscThisObject = QScript::scriptEngineFromExec(frame)->scriptValueToJSCValue(thisObject);
    JSC::CodeBlock *cb = frame->codeBlock();
    if (cb != 0) {
        frame[cb->thisRegister()] = jscThisObject;
    } else {
        JSC::Register* thisRegister = QScriptEnginePrivate::thisRegisterForFrame(frame);
        thisRegister[0] = jscThisObject;
    }
}
/*!
  Throws an exception with the given \a value.
  Returns the value thrown (the same as the argument).

  \sa throwError(), state()
*/
QScriptValue QScriptContext::throwValue(const QScriptValue &value)
{
    JSC::CallFrame *frame = QScriptEnginePrivate::frameForContext(this);
    QScript::APIShim shim(QScript::scriptEngineFromExec(frame));
    JSC::JSValue jscValue = QScript::scriptEngineFromExec(frame)->scriptValueToJSCValue(value);
    frame->setException(jscValue);
    return value;
}
/*!
  Returns the `this' object associated with this QScriptContext.
*/
QScriptValue QScriptContext::thisObject() const
{
    JSC::CallFrame *frame = const_cast<JSC::ExecState*>(QScriptEnginePrivate::frameForContext(this));
    QScriptEnginePrivate *engine = QScript::scriptEngineFromExec(frame);
    QScript::APIShim shim(engine);
    JSC::JSValue result = engine->thisForContext(frame);
    if (!result || result.isNull())
        result = frame->globalThisValue();
    return engine->scriptValueFromJSCValue(result);
}
/*!
  \internal
*/
void QScriptContext::setReturnValue(const QScriptValue &result)
{
    JSC::CallFrame *frame = QScriptEnginePrivate::frameForContext(this);
    JSC::CallFrame *callerFrame = frame->callerFrame();
    if (!callerFrame->codeBlock())
        return;
    Q_ASSERT_X(false, Q_FUNC_INFO, "check me");
    int dst = frame->registers()[JSC::RegisterFile::ReturnValueRegister].i(); // returnValueRegister() is private
    callerFrame[dst] = QScript::scriptEngineFromExec(frame)->scriptValueToJSCValue(result);
}
QScriptValue QScriptContext::activationObject() const
{
    JSC::CallFrame *frame = const_cast<JSC::ExecState*>(QScriptEnginePrivate::frameForContext(this));
    QScript::APIShim shim(QScript::scriptEngineFromExec(frame));
    JSC::JSObject *result = 0;

    uint flags = QScriptEnginePrivate::contextFlags(frame);
    if ((flags & QScriptEnginePrivate::NativeContext) && !(flags & QScriptEnginePrivate::HasScopeContext)) {
        //For native functions, lazily create it if needed
        QScript::QScriptActivationObject *scope = new (frame) QScript::QScriptActivationObject(frame);
        frame->setScopeChain(frame->scopeChain()->copy()->push(scope));
        result = scope;
        QScriptEnginePrivate::setContextFlags(frame, flags | QScriptEnginePrivate::HasScopeContext);
    } else {
        // look in scope chain
        JSC::ScopeChainNode *node = frame->scopeChain();
        JSC::ScopeChainIterator it(node);
        for (it = node->begin(); it != node->end(); ++it) {
            if ((*it) && (*it)->isVariableObject()) {
                result = *it;
                break;
            }
        }
    }
    if (!result) {
        if (!parentContext())
            return engine()->globalObject();

        qWarning("QScriptContext::activationObject:  could not get activation object for frame");
        return QScriptValue();
        /*JSC::CodeBlock *codeBlock = frame->codeBlock();
        if (!codeBlock) {
            // non-Qt native function 
            Q_ASSERT(true); //### this should in theorry not happen
            result = new (frame)QScript::QScriptActivationObject(frame);
        } else {
            // ### this is wrong
            JSC::FunctionBodyNode *body = static_cast<JSC::FunctionBodyNode*>(codeBlock->ownerNode());
            result = new (frame)JSC::JSActivation(frame, body);
        }*/
    }

    if (result && result->inherits(&QScript::QScriptActivationObject::info)
        && (static_cast<QScript::QScriptActivationObject*>(result)->delegate() != 0)) {
        // Return the object that property access is being delegated to
        result = static_cast<QScript::QScriptActivationObject*>(result)->delegate();
    }

    return QScript::scriptEngineFromExec(frame)->scriptValueFromJSCValue(result);
}
/*!
  Sets the activation object of this QScriptContext to be the given \a
  activation.

  If \a activation is not an object, this function does nothing.

  \note For a context corresponding to a JavaScript function, this is only
  guaranteed to work if there was an QScriptEngineAgent active on the
  engine while the function was evaluated.
*/
void QScriptContext::setActivationObject(const QScriptValue &activation)
{
    if (!activation.isObject())
        return;
    else if (activation.engine() != engine()) {
        qWarning("QScriptContext::setActivationObject() failed: "
                 "cannot set an object created in "
                 "a different engine");
        return;
    }
    JSC::CallFrame *frame = QScriptEnginePrivate::frameForContext(this);
    QScriptEnginePrivate *engine = QScript::scriptEngineFromExec(frame);
    QScript::APIShim shim(engine);
    JSC::JSObject *object = JSC::asObject(engine->scriptValueToJSCValue(activation));
    if (object == engine->originalGlobalObjectProxy)
        object = engine->originalGlobalObject();

    uint flags = QScriptEnginePrivate::contextFlags(frame);
    if ((flags & QScriptEnginePrivate::NativeContext) && !(flags & QScriptEnginePrivate::HasScopeContext)) {
        //For native functions, we create a scope node
        JSC::JSObject *scope = object;
        if (!scope->isVariableObject()) {
            // Create a QScriptActivationObject that acts as a proxy
            scope = new (frame) QScript::QScriptActivationObject(frame, scope);
        }
        frame->setScopeChain(frame->scopeChain()->copy()->push(scope));
        QScriptEnginePrivate::setContextFlags(frame, flags | QScriptEnginePrivate::HasScopeContext);
        return;
    }

    // else replace the first activation object in the scope chain
    JSC::ScopeChainNode *node = frame->scopeChain();
    while (node != 0) {
        if (node->object && node->object->isVariableObject()) {
            if (!object->isVariableObject()) {
                if (node->object->inherits(&QScript::QScriptActivationObject::info)) {
                    static_cast<QScript::QScriptActivationObject*>(node->object)->setDelegate(object);
                } else {
                    // Create a QScriptActivationObject that acts as a proxy
                    node->object = new (frame) QScript::QScriptActivationObject(frame, object);
                }
            } else {
                node->object = object;
            }
            break;
        }
        node = node->next;
    }
}
/*!
  \internal
  \since 4.5

  Removes the front object from this context's scope chain, and
  returns the removed object.

  If the scope chain is already empty, this function returns an
  invalid QScriptValue.
*/
QScriptValue QScriptContext::popScope()
{
    activationObject(); //ensure the creation of the normal scope for native context
    JSC::CallFrame *frame = QScriptEnginePrivate::frameForContext(this);
    JSC::ScopeChainNode *scope = frame->scopeChain();
    Q_ASSERT(scope != 0);
    QScriptEnginePrivate *engine = QScript::scriptEngineFromExec(frame);
    QScript::APIShim shim(engine);
    QScriptValue result = engine->scriptValueFromJSCValue(scope->object);
    if (!scope->next) {
        // We cannot have a null scope chain, so just zap the object pointer.
        scope->object = 0;
    } else {
        frame->setScopeChain(scope->pop());
    }
    return result;
}
/*!
  Returns the arguments object of this QScriptContext.

  The arguments object has properties \c callee (equal to callee())
  and \c length (equal to argumentCount()), and properties \c 0, \c 1,
  ..., argumentCount() - 1 that provide access to the argument
  values. Initially, property \c P (0 <= \c P < argumentCount()) has
  the same value as argument(\c P). In the case when \c P is less
  than the number of formal parameters of the function, \c P shares
  its value with the corresponding property of the activation object
  (activationObject()). This means that changing this property changes
  the corresponding property of the activation object and vice versa.

  \sa argument(), activationObject()
*/
QScriptValue QScriptContext::argumentsObject() const
{
    JSC::CallFrame *frame = const_cast<JSC::ExecState*>(QScriptEnginePrivate::frameForContext(this));
    QScript::APIShim shim(QScript::scriptEngineFromExec(frame));

    if (frame == frame->lexicalGlobalObject()->globalExec()) {
        // <global> context doesn't have arguments. return an empty object
        return QScriptEnginePrivate::get(QScript::scriptEngineFromExec(frame))->newObject();
    }

    //for a js function
    if (frame->codeBlock() && frame->callee()) {
        if (!QScriptEnginePrivate::hasValidCodeBlockRegister(frame)) {
            // We have a built-in JS host call.
            // codeBlock is needed by retrieveArguments(), but since it
            // contains junk, we would crash. Return an invalid value for now.
            return QScriptValue();
        }
        JSC::JSValue result = frame->interpreter()->retrieveArguments(frame, JSC::asFunction(frame->callee()));
        return QScript::scriptEngineFromExec(frame)->scriptValueFromJSCValue(result);
    }

    if (frame->callerFrame()->hasHostCallFrameFlag()) {
        // <eval> context doesn't have arguments. return an empty object
        return QScriptEnginePrivate::get(QScript::scriptEngineFromExec(frame))->newObject();
    }

    //for a native function
    if (!frame->optionalCalleeArguments()
        && QScriptEnginePrivate::hasValidCodeBlockRegister(frame)) { // Make sure we don't go here for host JSFunctions
        Q_ASSERT(frame->argumentCount() > 0); //we need at least 'this' otherwise we'll crash later
        JSC::Arguments* arguments = new (&frame->globalData())JSC::Arguments(frame, JSC::Arguments::NoParameters);
        frame->setCalleeArguments(arguments);
    }
    return QScript::scriptEngineFromExec(frame)->scriptValueFromJSCValue(frame->optionalCalleeArguments());
}
/*!
  \internal
*/
QScriptContextInfoPrivate::QScriptContextInfoPrivate(const QScriptContext *context)
{
    Q_ASSERT(context);
    functionType = QScriptContextInfo::NativeFunction;
    functionMetaIndex = -1;
    functionStartLineNumber = -1;
    functionEndLineNumber = -1;
    scriptId = -1;
    lineNumber = -1;
    columnNumber = -1;

    JSC::CallFrame *frame = const_cast<JSC::CallFrame *>(QScriptEnginePrivate::frameForContext(context));

    // Get the line number:

    //We need to know the context directly up in the backtrace, in order to get the line number, and adjust the global context
    JSC::CallFrame *rewindContext = QScriptEnginePrivate::get(context->engine())->currentFrame;
    if (QScriptEnginePrivate::contextForFrame(rewindContext) == context) {  //top context
        frame = rewindContext; //for retreiving the global context's "fake" frame
        // An agent might have provided the line number.
        lineNumber = QScript::scriptEngineFromExec(frame)->agentLineNumber;
        if (lineNumber == -1)
            lineNumber = QScript::scriptEngineFromExec(frame)->uncaughtExceptionLineNumber;
    } else {
        // rewind the stack from the top in order to find the frame from the caller where the returnPC is stored
        while (rewindContext && QScriptEnginePrivate::contextForFrame(rewindContext->callerFrame()->removeHostCallFrameFlag()) != context)
            rewindContext = rewindContext->callerFrame()->removeHostCallFrameFlag();
        if (rewindContext) {
            frame = rewindContext->callerFrame()->removeHostCallFrameFlag(); //for retreiving the global context's "fake" frame

            JSC::Instruction *returnPC = rewindContext->returnPC();
            JSC::CodeBlock *codeBlock = frame->codeBlock();
            if (returnPC && codeBlock && QScriptEnginePrivate::hasValidCodeBlockRegister(frame)) {
#if ENABLE(JIT)
                JSC::JITCode code = codeBlock->getJITCode();
                uintptr_t jitOffset = reinterpret_cast<uintptr_t>(JSC::ReturnAddressPtr(returnPC).value()) - reinterpret_cast<uintptr_t>(code.addressForCall().executableAddress());
                // We can only use the JIT code offset if it's smaller than the JIT size;
                // otherwise calling getBytecodeIndex() is meaningless.
                if (jitOffset < code.size()) {
                    unsigned bytecodeOffset = codeBlock->getBytecodeIndex(frame, JSC::ReturnAddressPtr(returnPC));
#else
                unsigned bytecodeOffset = returnPC - codeBlock->instructions().begin();
#endif
                bytecodeOffset--; //because returnPC is on the next instruction. We want the current one
                lineNumber = codeBlock->lineNumberForBytecodeOffset(const_cast<JSC::ExecState *>(frame), bytecodeOffset);
#if ENABLE(JIT)
                }
#endif
            }
        }
    }

    // Get the filename and the scriptId:
    JSC::CodeBlock *codeBlock = frame->codeBlock();
    if (codeBlock && QScriptEnginePrivate::hasValidCodeBlockRegister(frame)) {
           JSC::SourceProvider *source = codeBlock->source();
           scriptId = source->asID();
           fileName = source->url();
    }

    // Get the others information:
    JSC::JSObject *callee = frame->callee();
    if (callee && callee->inherits(&JSC::InternalFunction::info))
        functionName = JSC::asInternalFunction(callee)->name(frame);
    if (callee && callee->inherits(&JSC::JSFunction::info)
        && !JSC::asFunction(callee)->isHostFunction()) {
        functionType = QScriptContextInfo::ScriptFunction;
        JSC::FunctionExecutable *body = JSC::asFunction(callee)->jsExecutable();
        functionStartLineNumber = body->lineNo();
        functionEndLineNumber = body->lastLine();
        for (size_t i = 0; i < body->parameterCount(); ++i)
            parameterNames.append(body->parameterName(i));
        // ### get the function name from the AST
    } else if (callee && callee->inherits(&QScript::QtFunction::info)) {
        functionType = QScriptContextInfo::QtFunction;
        functionMetaIndex = static_cast<QScript::QtFunction*>(callee)->specificIndex(context);
        const QMetaObject *meta = static_cast<QScript::QtFunction*>(callee)->metaObject();
        if (meta != 0) {
            QMetaMethod method = meta->method(functionMetaIndex);
            QList<QByteArray> formals = method.parameterNames();
            for (int i = 0; i < formals.count(); ++i)
                parameterNames.append(QLatin1String(formals.at(i)));
        }
    }
    else if (callee && callee->inherits(&QScript::QtPropertyFunction::info)) {
        functionType = QScriptContextInfo::QtPropertyFunction;
        functionMetaIndex = static_cast<QScript::QtPropertyFunction*>(callee)->propertyIndex();
    }
}