/* 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/.
 */
#ifndef _include_jitcraft_array_h_
#define _include_jitcraft_array_h_

#include "Heap.h"
#include "Handles.h"
#include "Types.h"
#include "FixedArray.h"

namespace ke {

class ArrayMap;

class Array : public Object
{
    friend class ArrayMap;

  protected:
    // Note: we do not write barrier |elements_|, since it can be set to
    // arbitrary pointers.
    uint32 length_;
    union {
        void *elements_;
        Object *objelements_;
    };

  protected:
    void updateLengthAndElements(Zone *zone, unsigned length, Object *array) {
        length_ = length;
        write(zone, &objelements_, array);
    }

  public:
    static Array *NewFixed(Zone *zone, Handle<ArrayMap> map, Heap::Tenure = Heap::Tenure_Default);
    static Array *NewString(Zone *zone, Handle<ArrayMap> map, char *buffer, size_t length, Heap::Tenure = Heap::Tenure_Default);
    static Array *NewSized(Zone *zone, Handle<ArrayMap> map, int sizes[MAX_ARRAY_DEPTH], Heap::Tenure = Heap::Tenure_Default);

    static Array *New1D(Zone *zone, Handle<ArrayMap> map, uint32 elements, Heap::Tenure tenure = Heap::Tenure_Default);
    static Array *NewEmpty(Zone *zone, Handle<ArrayMap> map, Heap::Tenure tenure = Heap::Tenure_Default);
    static Array *NewRaw(Zone *zone, Handle<ArrayMap> map, unsigned nelements, Heap::Tenure tenure);

    static Array *NewExternal(Zone *zone,
                              Handle<ArrayMap> map,
                              void *buffer,
                              unsigned length,
                              Heap::Tenure tenure = Heap::Tenure_Default);

    // Copies an array from one reference to another, obeying language semantics.
    static bool ShallowCopy(Zone *zone, Handle<Array> dest, Handle<Array> source);

    // Creates a full duplicate of an array, following all array references as if
    // they were fixed. Array references inside structs or objects use ShallowCopy
    // semantics, as this is only intended for duplicating array literals, which
    // cannot contain structs.
    static Array *DeepCopy(Zone *zone, Handle<Array> source, Heap::Tenure tenure);

    uint32 length() {
        return length_;
    }

    inline ArrayType *type();

    inline int *int32Vec();
    inline float *floatVec();
    inline char *chars();
    inline void *bytes();

    bool resize(Zone *zone, size_t newLength);

    static inline size_t SizeForElement(ArrayType *type) {
        if (type->contained()->isTraceable())
            return sizeof(ke::Object *);
        if (type->contained()->isInt32())
            return sizeof(int);
        if (type->contained()->primitive() == PrimitiveType_Char)
            return sizeof(char);
        assert(type->contained()->isFloat());
        return sizeof(float);
    }

    inline size_t objSize(ArrayMap *map);

    int readInt32(size_t index) {
        assert(index < length());
        return int32Vec()[index];
    }
    void writeInt32(size_t index, int i) {
        assert(index < length());
        int32Vec()[index] = i;
    }
    char readChar(size_t index) {
        assert(index < length());
        return chars()[index];
    }
    void writeChar(size_t index, char c) {
        assert(index < length());
        chars()[index] = c;
    }
    float readFloat(size_t index) {
        assert(index < length());
        return floatVec()[index];
    }
    void writeFloat(size_t index, float f) {
        assert(index < length());
        floatVec()[index] = f;
    }
    Object *readObject(size_t index) {
        return FixedArray::cast(objelements_)->at(index);
    }
    void writeObject(Zone *zone, size_t index, Object *ptr) {
        FixedArray::cast(objelements_)->set(zone, index, ptr);
    }

    // GC Descriptor.
    static inline size_t offsetOfElements() {
        return offsetof(Array, objelements_);
    }
    // End GC Descriptor.

    static Array *cast(Object *obj) {
        assert(!obj ||
               obj->is(MapKind_Array) ||
               obj->is(MapKind_DependentArray));
        return reinterpret_cast<Array *>(obj);
    }
};

class DependentArray : public Array
{
    Barriered<Array> root_;

  public:
    static Array *New(Zone *zone, Handle<Array> source, Handle<ArrayMap> map, unsigned index);

    // GC Descriptor.
    static inline size_t offsetOfRoot() {
        return offsetof(DependentArray, root_);
    }
    // End GC Descriptor.

    static DependentArray *cast(Object *obj) {
        assert(!obj || obj->is(MapKind_DependentArray));
        return reinterpret_cast<DependentArray *>(obj);
    }
};

class ArrayMap : public Map
{
    Barriered<ArrayType> type_;

  public:
    static ArrayMap *New(Zone *zone, Handle<ArrayType> type);

    // DependentArray maps are never attached, and are just free-floating,
    // rooted ultimately by the bytecode. A :TODO: that we might need to
    // cache these, or attach them somewhere saner like ArrayType, which
    // itself will eventually be cached.
    static ArrayMap *NewDependent(Zone *zone, Handle<ArrayType> type);

    ArrayType *type() {
        return type_;
    }

    // GC Descriptor.
    static inline size_t offsetOfType() {
        return OFFSETOF(ArrayMap, type_);
    }
    // End GC Descriptor.
    
    static ArrayMap *cast(Object *obj) {
        assert(!obj || obj->is(MapKind_MetaArray));
        return reinterpret_cast<ArrayMap *>(obj);
    }
};

inline void *
Array::bytes()
{
    assert(!type()->contained()->isTraceable());
    assert(type()->hasInlineElements() ||
           type()->isExternalArray() ||
           is(MapKind_DependentArray) ||
           !length() ||
           ByteArray::cast((Object *)elements_));

    return Address(elements_) + ByteArray::offsetToElements();
}

inline int *
Array::int32Vec()
{
    assert(type()->contained()->isInt32());
    return reinterpret_cast<int *>(bytes());
}

inline float *
Array::floatVec()
{
    assert(type()->contained()->isFloat());
    return reinterpret_cast<float *>(bytes());
}

inline char *
Array::chars()
{
    assert(type()->isCharArray());
    return reinterpret_cast<char *>(bytes());
}

inline ArrayType *
Array::type()
{
    return ArrayMap::cast(map())->type();
}

inline size_t
Array::objSize(ArrayMap *map)
{
    assert(this->map() == map);
    if (map->type()->hasInlineElements())
        return sizeof(Array) + Array::SizeForElement(map->type()) * length();
    return sizeof(Array);
}

}

#endif // _include_jitcraft_array_h_
