/* 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 "Structures.h"
#include "Zone.h"
#include "Types.h"
#include "Array.h"
#include "Spaces-inl.h"
#include "Heap-inl.h"

using namespace ke;

StructureBufferBuilder::StructureBufferBuilder()
  : size_(0)
{
}

bool
StructureBufferBuilder::add(Handle<Type> type, unsigned *offset)
{
    *offset = size_;

    if (!type->isTraceable()) {
        // For now, assume the size of primitives is 4-byte.
        assert(type->isInt32() || type->isFloat());
        size_ += 4;
        return true;
    }

    if (!offsets_.append(size_))
        return false;

    size_ += sizeof(Object *);
    return true;
}

Descriptor *
Descriptor::New(Zone *zone, Handle<String> name, Handle<Type> type)
{
    Local<Descriptor> desc(zone,
        Descriptor::cast(zone->allocate(MapKind_Descriptor, sizeof(Descriptor), Heap::Tenure_Old)));
    if (!desc)
        return NULL;

    desc->name_ = name;
    desc->type_ = type;
    desc->offset_ = unsigned(-1);
    return desc;
}

StructMap *
StructMap::New(Zone *zone, const StructureBufferBuilder &builder, Handle<StructType> type)
{
    Vector<unsigned> composedIndexes;
    for (size_t i = 0; i < type->fields()->length(); i++) {
        Descriptor *desc = Descriptor::cast(type->fields()->at(i));
        if (desc->type()->isArray() || desc->type()->isStruct()) {
            if (!composedIndexes.append(i))
                return NULL;
        }
    }

    Local<FixedArray> composed(zone, FixedArray::New(zone, composedIndexes.length(), Heap::Tenure_Old));
    if (!composed)
        return NULL;

    for (size_t i = 0; i < composedIndexes.length(); i++) {
        Descriptor *desc = Descriptor::cast(type->fields()->at(composedIndexes[i]));
        composed->set(zone, i, desc);
    }

    size_t bytesNeeded = sizeof(StructMap) +
                         (builder.traceableOffsetCount() * sizeof(unsigned));

    Local<StructMap> map(zone);
    map = StructMap::cast(zone->allocateMap(MapKind_Struct, bytesNeeded, MapKind_MetaStruct));
    if (!map)
        return NULL;

    map->structureSize_ = builder.structureSize();
    map->traceOffsetCount_ = builder.traceableOffsetCount();
    map->type_ = type;
    map->composed_ = composed;
    memcpy(const_cast<unsigned *>(map->traceOffsets()), builder.offsets(),
           sizeof(unsigned) * builder.traceableOffsetCount());

    return map;
}

Struct *
Struct::New(Zone *zone, Handle<StructMap> map, Heap::Tenure tenure)
{
    size_t bytesNeeded = sizeof(Struct) + map->structureSize();
    Local<Struct> obj(zone, Struct::cast(zone->allocate(map, bytesNeeded, tenure)));
    if (!obj)
        return NULL;

    memset((Struct *)obj + 1, 0, map->structureSize());

    // Initialize any sub-structures. Right now, this is performed as part of
    // struct allocation, rather than inlined in bytecode, for simplicity.
    if (map->composed()) {
        Local<Descriptor> desc(zone);
        Local<Object> child(zone);
        Local<StructMap> childStructMap(zone);
        Local<ArrayMap> childArrayMap(zone);

        for (unsigned i = 0; i < map->composed()->length(); i++) {
            desc = Descriptor::cast(map->composed()->at(i));

            if (desc->type()->isStruct()) {
                childStructMap = StructMap::cast(StructType::cast(desc->type())->newMap());
                child = Struct::New(zone, childStructMap, tenure);
            } else if (desc->type()->isArray()) {
                assert(false);
#if 0
                childArrayMap = ArrayMap::cast(desc->type()->newMap());
                if (desc->type()->isFixedLength())
                    child = Array::NewFixed(zone, childArrayMap, tenure);
                else
                    child = Array::NewEmpty(zone, childArrayMap, tenure);
#endif
            }
            if (!child)
                return NULL;

            obj->set(zone, desc, child);
        }
    }

    return obj;
}

