/* vim: set ts=4 sw=4 tw=99 et:
 *
 * Copyright (C) 2012 David Anderson
 *
 * This file is part of SourcePawn.
 *
 * SourcePawn 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.
 * 
 * SourcePawn 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
 * SourcePawn. If not, see http://www.gnu.org/licenses/.
 */
#include <string.h>
#include "Array.h"
#include "FixedArray.h"
#include "Heap.h"
#include "Zone.h"
#include "Structures.h"
#include "Heap-inl.h"

using namespace ke;

ArrayMap *
ArrayMap::New(Zone *zone, Handle<ArrayType> type)
{
    Local<Map> obj(zone, zone->allocateMap(MapKind_Array, sizeof(ArrayMap), MapKind_MetaArray));
    if (!obj)
        return NULL;

    Local<ArrayMap> map(zone, ArrayMap::cast(obj));
    map->type_ = type;
    return map;
}

ArrayMap *
ArrayMap::NewDependent(Zone *zone, Handle<ArrayType> type)
{
    Local<Map> obj(zone, zone->allocateMap(MapKind_DependentArray, sizeof(ArrayMap), MapKind_MetaArray));
    if (!obj)
        return NULL;

    Local<ArrayMap> map(zone, ArrayMap::cast(obj));
    map->type_ = type;
    return map;
}

ArrayMap *
ArrayMap::Attach(Zone *zone, Handle<ArrayType> type)
{
    if (type->newMap())
        return ArrayMap::cast(type->newMap());

    Local<ArrayMap> map(zone, ArrayMap::New(zone, type));
    if (!map)
        return NULL;

    // Ensure the inner type has an ArrayMap if needed.
    if (type->contained()->isArray()) {
        Local<ArrayType> contained(zone, ArrayType::cast(type->contained()));
        if (!ArrayMap::Attach(zone, contained))
            return NULL;
    }

    type->setNewMap(map);
    return map;
}

Array *
Array::NewRaw(Zone *zone, Handle<ArrayMap> map, unsigned nelements, Heap::Tenure tenure)
{
    assert(!map->type()->isFixedLength() || nelements == map->type()->fixedLength());

    if (nelements > (INT_MAX / SizeForElement(map->type()))) {
        zone->reportError(Message_ArraySizeTooBig);
        return NULL;
    }

    size_t bytes = sizeof(Array);
    if (map->type()->hasInlineElements())
        bytes += SizeForElement(map->type()) * nelements;

    Local<Array> array(zone, Array::cast(zone->allocate(map, bytes, tenure)));
    if (!array)
        return NULL;

    array->length_ = 0;
    array->elements_ = NULL;

    if (map->type()->hasInlineElements()) {
        // This must be a fixed array containing no traceables.
        assert(nelements > 0);
        assert(map->type()->isFixedLength());
        assert(!map->type()->contained()->isTraceable());

        // Compute an interior |elements_| pointer, such that if elements_
        // is accessed like a FixedArray, we reach the appropriate vector.
        array->elements_ = Address((Array *)array + 1) - ByteArray::offsetToElements();
        array->length_ = nelements;
        memset(array->bytes(), 0, SizeForElement(map->type()) * nelements);
        return array;
    }

    // If there is nothing to allocate, we don't bother creating elements yet.
    if (!nelements)
        return array;

    if (!map->type()->contained()->isTraceable()) {
        size_t nbytes = SizeForElement(map->type()) * nelements;
        Local<ByteArray> elements(zone, ByteArray::New(zone, nbytes, tenure));
        if (!elements)
            return NULL;

        array->updateLengthAndElements(zone, nelements, elements);
        return array;
    }

    Local<FixedArray> elements(zone, FixedArray::New(zone, nelements, tenure));
    if (!elements)
        return NULL;

    array->updateLengthAndElements(zone, nelements, elements);

    // If this is an array of structs, we're required to allocate those structs now.
    if (map->type()->contained()->isStruct()) {
        Local<StructType> childType(zone, StructType::cast(map->type()->contained()));
        Local<StructMap> childMap(zone, childType->newMap());
        Local<Struct> child(zone);
        for (unsigned i = 0; i < nelements; i++) {
            child = Struct::New(zone, childMap, tenure);
            if (!child)
                return NULL;

            elements->set(zone, i, child);
        }
    }

    return array;
}

static Array *
ConstructSizedArray(Zone *zone, Handle<ArrayMap> map, int dims[MAX_ARRAY_DEPTH],
                    unsigned level, Heap::Tenure tenure)
{
    Local<Array> array(zone, Array::NewRaw(zone, map, dims[level], tenure));
    if (!array)
        return NULL;

    if (map->type()->contained()->isArray()) {
        Local<ArrayType> childType(zone, ArrayType::cast(map->type()->contained()));
        Local<ArrayMap> childMap(zone, childType->newMap());
        Local<Array> child(zone);

        for (unsigned i = 0; i < unsigned(dims[level]); i++) {
            child = ConstructSizedArray(zone, childMap, dims, level + 1, tenure);
            if (!child)
                return NULL;

            array->writeObject(zone, i, child);
        }
    }

    return array;
}

Array *
Array::NewSized(Zone *zone, Handle<ArrayMap> map, int dims[MAX_ARRAY_DEPTH], Heap::Tenure tenure)
{
    for (size_t i = 0; i < map->type()->levels(); i++) {
        if (dims[i] < 0) {
            zone->reportError(Message_InvalidDimensionSize, dims[i], i);
            return NULL;
        }
    }

    return ConstructSizedArray(zone, map, dims, 0, tenure);
}

static Array *
ConstructFixedArray(Zone *zone, Handle<ArrayMap> map, Heap::Tenure tenure)
{
    unsigned length = map->type()->fixedLength();
    Local<Array> array(zone, Array::NewRaw(zone, map, length, tenure));
    if (!array)
        return NULL;

    if (map->type()->contained()->isArray()) {
        Local<ArrayType> childType(zone, ArrayType::cast(map->type()->contained()));
        Local<ArrayMap> childMap(zone, childType->newMap());
        Local<Array> child(zone);

        if (childMap->type()->isFixedLength()) {
            for (unsigned i = 0; i < length; i++) {
                child = ConstructFixedArray(zone, childMap, tenure);
                if (!child)
                    return NULL;

                array->writeObject(zone, i, child);
            }
        } else {
            for (unsigned i = 0; i < length; i++) {
                child = Array::NewRaw(zone, childMap, 0, tenure);
                if (!child)
                    return NULL;

                array->writeObject(zone, i, child);
            }
        }
    }

    return array;
}

Array *
Array::NewFixed(Zone *zone, Handle<ArrayMap> map, Heap::Tenure tenure)
{
    return ConstructFixedArray(zone, map, tenure);
}

Array *
Array::NewString(Zone *zone, Handle<ArrayMap> map, char *buffer, size_t length, Heap::Tenure tenure)
{
    assert(map->type()->isCharArray());

    Local<Array> array(zone);
    
    if (map->type()->isFixedLength())
        array = Array::NewFixed(zone, map, tenure);
    else
        array = Array::New1D(zone, map, length + 1, tenure);
    if (!array)
        return NULL;

    assert(array->length() >= length + 1);
    memcpy(array->chars(), buffer, length + 1);
    return array;
}

Array *
Array::New1D(Zone *zone, Handle<ArrayMap> map, uint32 elements, Heap::Tenure tenure)
{
    assert(map->type()->levels());
    return Array::NewRaw(zone, map, elements, tenure);
}

Array *
Array::NewEmpty(Zone *zone, Handle<ArrayMap> map, Heap::Tenure tenure)
{
    assert(!map->type()->isFixedLength());

    return Array::NewRaw(zone, map, 0, tenure);
}

Array *
Array::NewExternal(Zone *zone, Handle<ArrayMap> map, void *buffer, unsigned length,
                   Heap::Tenure tenure)
{
    Local<Array> array(zone, Array::cast(zone->allocate(map, sizeof(Array), tenure)));
    if (!array)
        return NULL;

    array->length_ = length;
    array->elements_ = Address(buffer) - ByteArray::offsetToElements();
    return array;
}

static bool
CopyArrayElements(Zone *zone, Handle<Type> contained, Handle<Array> dest, Handle<Array> source)
{
    if (contained->isTraceable()) {
        if (contained->isStruct()) {
            assert(dest->type()->contained() == contained);
            assert(source->length() == dest->length());

            Local<Struct> left(zone);
            Local<Struct> right(zone);
            for (unsigned i = 0; i < source->length(); i++) {
                left = Struct::cast(dest->readObject(i));
                right = Struct::cast(source->readObject(i));
                if (!Struct::Copy(zone, left, right))
                    return false;
            }
        } else if (contained->isArray() && ArrayType::cast(contained)->isFixedLength()) {
            assert(ArrayType::cast(source->type())->fixedLength() ==
                   ArrayType::cast(contained)->fixedLength());

            Local<Array> left(zone);
            Local<Array> right(zone);
            for (unsigned i = 0; i < source->length(); i++) {
                left = Array::cast(dest->readObject(i));
                right = Array::cast(source->readObject(i));
                if (!Array::ShallowCopy(zone, left, right))
                    return false;
            }
        } else {
            assert(dest->length() == source->length());
            for (unsigned i = 0; i < source->length(); i++)
                dest->writeObject(zone, i, source->readObject(i));
        }
    } else {
        assert(contained->pod() == dest->type()->contained()->pod());
        assert(contained->pod() == PrimitiveType_Char
               ? source->length() <= dest->length()
               : source->length() == dest->length());
    
        assert(dest->length());
        memcpy(dest->bytes(), source->bytes(), source->length() * Array::SizeForElement(dest->type()));
    }
    return true;
}

// Shallow copy an array. Fixed slots in the destination are copied from
// the source, but otherwise, references are assigned.
bool
Array::ShallowCopy(Zone *zone, Handle<Array> dest, Handle<Array> source)
{
    Local<Type> contained(zone, dest->type()->contained());

    return CopyArrayElements(zone, contained, dest, source);
}

Array *
Array::DeepCopy(Zone *zone, Handle<Array> source, Heap::Tenure tenure)
{
    Local<ArrayMap> map(zone, ArrayMap::cast(source->map()));

    Local<Array> dest(zone, Array::NewRaw(zone, map, source->length(), tenure));
    if (!dest)
        return NULL;

    Local<Type> contained(zone, source->type()->contained());
    if (contained->isArray()) {
        assert(false);
        Local<Array> sub(zone);
        for (size_t i = 0; i < source->length(); i++) {
            sub = Array::cast(source->readObject(i));
            sub = DeepCopy(zone, sub, tenure);
            if (!sub)
                return NULL;
            dest->writeObject(zone, i, sub);
        }
    } else {
        if (!CopyArrayElements(zone, contained, dest, source))
            return NULL;
    }

    return dest;
}

Array *
DependentArray::New(Zone *zone, Handle<Array> source, Handle<ArrayMap> map, unsigned index)
{
    Local<ArrayType> sourcetype(zone, source->type());

    // Right now we only support char arrays, to avoid nasty deep cloning
    // and to maybe cut off this feature as far as we can.
    assert(sourcetype->isCharArray());
    assert(map->type()->isCharArray());

    // We allow taking 0-length dependent strings. It's safe because any reads
    // or writes will fail.
    assert(index <= source->length());

    unsigned newlen = source->length() - index;
    unsigned eltsize = SizeForElement(sourcetype);
    
    if (!sourcetype->isFixedLength()) {
        // Simple case, just copy the array.
        Local<ArrayMap> map(zone, sourcetype->newMap());
        
        Local<Array> dest(zone, Array::NewRaw(zone, map, newlen, Heap::Tenure_Default));
        if (!dest)
            return NULL;

        memcpy(dest->bytes(),
               (Address)source->bytes() + (index * eltsize),
               newlen * eltsize);
        return dest;
    }

    Local<DependentArray> array(zone, DependentArray::cast(zone->allocate(map, sizeof(DependentArray), Heap::Tenure_Default)));
    if (!array)
        return NULL;

    // :GC: This is currently not safe for moving GC! Although we will mark
    // the object owning the interior pointer, the interior pointer could be
    // moved later. We will eventually need some way of dealing with this.
    Address elements = Address(source->bytes()) + (index * eltsize);

    array->root_ = source;
    array->length_ = newlen;
    array->elements_ = elements - ByteArray::offsetToElements();
    return array;
}
