/*!
  \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);
}
/*!
  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();
    }
}