/* 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<Type> 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::Attach(Zone *zone, Handle<Type> 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<Type> contained(zone, 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)
{
    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<StructMap> childMap(zone, StructMap::cast(map->type()->contained()->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<ArrayMap> childMap(zone, ArrayMap::cast(map->type()->contained()->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<ArrayMap> childMap(zone, ArrayMap::cast(map->type()->contained()->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, Address buffer, size_t length, Heap::Tenure tenure)
{
    assert(map->type()->isCharArray());

    Local<Array> array(zone, Array::New1D(zone, map, length, tenure));
    if (!array)
        return NULL;

    assert(array->length() >= length);
    memcpy(array->chars(), buffer, length);
    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;
}

