/* vim: set ts=4 sw=4 tw=99 et:
 *
 * Copyright (C) 2012 David Anderson
 *
 * This file is part of JITCraft.
 *
 * JITCraft is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * Foobar 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * JITCraft. If not, see http://www.gnu.org/licenses/.
 */
#include <string.h>
#include "../include/keima.h"
#include "Zone.h"
#include "RootScopes.h"
#include "compiler/CompileContext.h"
#include "Modules.h"
#include "GlobalRoots.h"
#include "Reference.h"
#include "Array.h"
#include "Interpreter.h"
#include "Stack.h"
#include "Strings.h"
#include "NativeTable.h"
#include "Spaces-inl.h"
#include "Heap-inl.h"

using namespace ke;

bool
Ke::Keima::Initialize()
{
    SingleThreadedZone = new Zone();
    if (!SingleThreadedZone || !SingleThreadedZone->initialize())
        return false;
    return true;
}

void
Ke::Keima::Shutdown()
{
    delete SingleThreadedZone;
    SingleThreadedZone = NULL;
}

Ke::HandleScope::HandleScope()
  : zone_(ke::ZONE()),
    position_(zone_->rootScopes().position()),
    prev_(*zone_->rootScopes().scope())
{
    *zone_->rootScopes().scope() = this;
}

Ke::HandleScope::~HandleScope()
{
    zone_->rootScopes().unwind(position_);
    *zone_->rootScopes().scope() = prev_;
}

ke::Object **
Ke::HandleScope::CreateHandle(ke::Object *obj)
{
    if (!obj)
        return NULL;

    return ZONE()->rootScopes().make(obj);
}

template <typename From, typename To> static inline To *
Open(Ke::Handle<From> from)
{
    return *reinterpret_cast<To **>(*from);
}

template <typename From, typename To> static inline To *
Open(From *from)
{
    return *reinterpret_cast<To **>(from);
}

template <typename From, typename To> static inline Ke::Local<To>
ToLocal(From *from)
{
    return Ke::Local<To>(reinterpret_cast<To *>(Ke::HandleScope::CreateHandle(from)));
}

ke::Module *
InternalCompile(const char *path)
{
    PoolScope poolScope(ZONE()->pool());
    RootScope roots(ZONE());
    CompileContext cc(ZONE(), path);

    TranslationUnit *unit = new (ZONE()->pool()) TranslationUnit();
    unit->path_ = path;

    if (!cc.addTranslationUnit(unit))
        return NULL;

    if (!cc.compile())
        return NULL;

    return NULL;

#if 0
    ke::Local<ke::Module> module(ZONE(),  CompileFromSource(cc, path, bytes, length));
    delete [] bytes;
    if (!module)
        return NULL;

    ke::Local<ke::String> pathstr(ZONE(), ke::String::New(ZONE(), path, Heap::Tenure_Old));
    if (!pathstr)
        return NULL;

    module->setPath(pathstr);
    return module;
#endif
    return NULL;
}

// This is split out from InternalCompile so the RootScope doesn't conflict
// with making a return handle.
Ke::Local<Ke::Module>
Ke::Compile(const char *path)
{
    ke::Local<ke::Module> module(ZONE(), InternalCompile(path));
    return ToLocal<ke::Module, Ke::Module>(module);
}

void
Ke::Keima::InstallMessageReporter(Ke::IMessageReporter *reporter)
{
    ZONE()->installErrorReporter(reporter);
}

class StackFrameIterator : public Ke::IStackFrameIterator
{
    StackIter iter_;

  public:
    StackFrameIterator()
      : iter_(ZONE())
    {
    }

    virtual bool done() {
        return iter_.done();
    }

    const char *function() {
        return iter_.function();
    }

    const char *source() {
        return iter_.source();
    }

    unsigned lineNumber() {
        return iter_.lineNumber();
    }

    void prev() {
        iter_.prev();
    }
};

Ke::IStackFrameIterator *
Ke::Keima::NewStackFrameIterator()
{
    return new StackFrameIterator();
}

static inline ke::HeapRoot *
FromAPI(ke::HeapRoot *from)
{
    ke::Address address = reinterpret_cast<ke::Address>(from);
    address -= offsetof(ke::HeapRoot, obj);
    return reinterpret_cast<ke::HeapRoot *>(address);
}

ke::HeapRoot *
Ke::Internals::NewHeapRoot()
{
    ke::HeapRoot *root = ke::ZONE()->globalRoots()->create();
    if (!root)
        return NULL;

    // Compute an interior pointer, so it looks like a Handle to an object.
    return reinterpret_cast<ke::HeapRoot *>(&root->obj);
}

void
Ke::Internals::Destroy(ke::HeapRoot *root)
{
    ZONE()->globalRoots()->destroy(FromAPI(root));
}

bool
Ke::Keima::IsInCallStack(Handle<Module> argModule)
{
    ke::Local<ke::Module> module(ke::ZONE(), Open<Ke::Module, ke::Module>(argModule));
    return ZONE()->stack().isInCallStack(module);
}

void
Ke::Keima::CollectGarbage()
{
    ke::ZONE()->heap().reclaim();
}

void
Ke::Keima::ClearPendingException()
{
    ke::ZONE()->clearPendingException();
}

void
Ke::Module::setNativeIdentity(void *identity)
{
    ke::Local<ke::Module> module(ke::ZONE(), Open<Ke::Module, ke::Module>(this));
    module->setNativeIdentity(identity);
}

unsigned
Ke::String::length()
{
    ke::Local<ke::String> obj(ke::ZONE(), Open<Ke::String, ke::String>(this));
    return obj->length();
}

const char *
Ke::String::chars()
{
    ke::Local<ke::String> obj(ke::ZONE(), Open<Ke::String, ke::String>(this));
    return obj->chars();
}

Ke::Local<Ke::String>
Ke::Function::name()
{
    ke::Local<ke::Function> fun(ke::ZONE(), Open<Ke::Function, ke::Function>(this));
    return ToLocal<ke::String, Ke::String>(fun->name());
}

static inline const char *
GetInvokeTypeName(Ke::Parameter::Type type)
{
    switch (type) {
      case Ke::Parameter::Array:
        return "array";
      case Ke::Parameter::CharArray:
        return "String";
      case Ke::Parameter::Float:
        return "Float";
      case Ke::Parameter::FloatRef:
        return "&Float";
      case Ke::Parameter::Int:
        return "int";
      case Ke::Parameter::IntRef:
        return "&int";
      default:
        return "<unknown>";
    }
}

static inline bool
CheckInvokeType(const Ke::Parameter &param, Type *type)
{
    switch (param.type()) {
      case Ke::Parameter::Array:
        return type->isArray() &&
               type->levels() == 1 &&
               (type->contained()->isPrimitive() || type->contained()->isEnum()) &&
               (type->contained()->primitive() != PrimitiveType_Char);
      case Ke::Parameter::CharArray:
        return type->isCharArray();
      case Ke::Parameter::Float:
        return type->isFloat();
      case Ke::Parameter::FloatRef:
        return type->isReference() && type->contained()->isFloat();
      case Ke::Parameter::Int:
        return type->isInt32() || type->isEnum();
      case Ke::Parameter::IntRef:
       return type->isReference() && (type->contained()->isInt32() || type->contained()->isEnum());
      default:
        return false;
    }
}

static bool
CheckInvokeTypes(Ke::Handle<Ke::Function> argFun, const Ke::Parameter *params, unsigned nparams)
{
    ke::Local<ke::Function> fun(ke::ZONE(), Open<Ke::Function, ke::Function>(argFun));

    if (fun->nargs() != nparams)
        return false;

    for (unsigned i = 0; i < nparams; i++) {
        if (!CheckInvokeType(params[i], fun->argType(i))) {
            ke::ZONE()->reportError(Message_TypeMismatchDuringInvoke,
                                    GetInvokeTypeName(params[i].type()),
                                    GetTypeName(fun->argType(i)));
            return false;
        }
    }

    // Functions can only return tagged cells, for ISPE1-compatible Invoke().
    ke::Local<ke::Type> returnType(ke::ZONE(), fun->type()->returnType());
    if (!returnType->isPrimitive() &&
        !returnType->isEnum() &&
        !returnType->isVoid())
    {
        ke::ZONE()->reportError(Message_CannotInvokeReturnType, GetTypeName(returnType));
        return false;
    }

    return true;
}

bool
Ke::Keima::Invoke(Handle<Function> argFun, const Parameter *params, unsigned nparams,
                  bool checkTypes, int *retval)
{
    assert(CheckInvokeTypes(argFun, params, nparams));

    ke::Local<ke::Function> fun(ke::ZONE(), Open<Ke::Function, ke::Function>(argFun));

    if (fun->nargs() != nparams) {
        // :TODO: report error
        assert(false);
        return false;
    }

    ke::InvokeArgs args;
    if (!ke::ZONE()->stack().pushInvokeFrame(fun, args))
        return false;

    if (checkTypes && !CheckInvokeTypes(argFun, params, nparams))
        return false;

    for (unsigned i = 0; i < nparams; i++) {
        ke::LocalSlot &slot = args.arg(i);
        switch (params[i].type()) {
          case Ke::Parameter::Int:
            slot.i32 = params[i].i32();
            break;

          case Ke::Parameter::Float:
            slot.f = params[i].f();
            break;

          case Ke::Parameter::IntRef:
            if (params[i].writeback()) {
                slot.ref = Reference::NewStack(ke::ZONE(), params[i].i32p(), Heap::Tenure_Stack);
            } else {
                LocalSlot other;
                other.i32 = *params[i].i32p();
                slot.ref = Reference::NewStack(ke::ZONE(), other, Heap::Tenure_Stack);
            }
            if (!slot.ref)
                return false;
            break;

          case Ke::Parameter::FloatRef:
            if (params[i].writeback()) {
                slot.ref = Reference::NewStack(ke::ZONE(), params[i].fp(), Heap::Tenure_Stack);
            } else {
                LocalSlot other;
                other.f = *params[i].fp();
                slot.ref = Reference::NewStack(ke::ZONE(), other, Heap::Tenure_Stack);
            }
            if (!slot.ref)
                return false;
            break;

          case Ke::Parameter::Array:
          {
            ke::Local<ke::ArrayMap> map(ke::ZONE(), ke::ZONE()->externalGenericArrayMap());
            if (params[i].writeback()) {
                slot.obj = Array::NewExternal(ke::ZONE(), map, params[i].buffer(),
                                              params[i].length(), Heap::Tenure_Stack);
                if (!slot.obj)
                    return false;
            } else {
                Array *array = Array::New1D(ke::ZONE(), map, params[i].length(), Heap::Tenure_Stack);
                if (!slot.obj)
                    return false;
                if (params[i].length())
                    memcpy(array->bytes(), params[i].buffer(), params[i].length() * sizeof(int));
            }
            break;
          }

          case Ke::Parameter::CharArray:
          {
            ke::Local<ke::ArrayMap> map(ke::ZONE(), ke::ZONE()->externalCharArrayMap());
            if (params[i].writeback()) {
                slot.obj = Array::NewExternal(ke::ZONE(), map, params[i].buffer(),
                                              params[i].length(), Heap::Tenure_Stack);
                if (!slot.obj)
                    return false;
            } else {
                Array *array = Array::New1D(ke::ZONE(), map, params[i].length(), Heap::Tenure_Stack);
                if (!slot.obj)
                    return false;
                if (params[i].length())
                    memcpy(array->bytes(), params[i].buffer(), params[i].length() * sizeof(char));
            }
            break;
          }
        }
    }

    LocalSlot result;
    if (!Interpret(ke::ZONE(), NULL, &result))
        return false;

    if (fun->type()->returnType()->isVoid())
        result.i32 = 0;

    *retval = result.i32;
    return true;
}

bool
Ke::Keima::BindNative(const char *name, void *address)
{
    return ke::ZONE()->nativeTable()->bind(name, address);
}

void
Ke::Keima::SetPublicFunctionListener(IPublicFunctionListener *listener)
{
    ke::ZONE()->setPublicFunctionListener(listener);
}

void
Zone::registerPublic(ke::Handle<Function> fun)
{
    if (!publicFunctionListener_)
        return;

    Ke::Local<Ke::Function> local = ToLocal<ke::Function, Ke::Function>(fun);
    publicFunctionListener_->registerPublic(local);
}
