/* 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 "Types.h"
#include "Zone.h"
#include "Strings.h"
#include "Structures.h"
#include "Heap-inl.h"

using namespace ke;

Type *
Type::NewVoid(Zone *zone)
{
    Local<Type> type(zone, Type::cast(zone->allocate(MapKind_Type, sizeof(Type), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    type->kind_ = VOID;
    return type;
}

Type *
Type::NewUnchecked(Zone *zone)
{
    Local<Type> type(zone, Type::cast(zone->allocate(MapKind_Type, sizeof(Type), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    type->kind_ = UNCHECKED;
    return type;
}

Type *
Type::NewPrimitive(Zone *zone, PrimitiveType prim)
{
    Local<Type> type(zone, Type::cast(zone->allocate(MapKind_Type, sizeof(Type), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    type->kind_ = PRIMITIVE;
    type->name_ = NULL;
     type->primitive_ = prim;
    return type;
}

ArrayType *
ArrayType::New(Zone *zone, Handle<Type> contained, int elements)
{
    Local<ArrayType> type(zone, ArrayType::cast(zone->allocate(MapKind_ArrayType, sizeof(ArrayType), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    type->kind_ = ARRAY;
    type->name_ = NULL;
    type->contained_ = contained;
    type->elements_ = elements;
    if (!contained->isArray())
        type->levels_ = 1;
    else
        type->levels_ = ArrayType::cast(contained)->levels() + 1;
    return type;
}

ArrayType *
ArrayType::NewExternal(Zone *zone, Handle<Type> contained)
{
    Local<ArrayType> type(zone, ArrayType::cast(zone->allocate(MapKind_ArrayType, sizeof(ArrayType), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    assert(contained->isPrimitive());

    type->kind_ = EXTERNAL_ARRAY;
    type->name_ = NULL;
    type->contained_ = contained;
    type->elements_ = DYNAMIC_ARRAY_SIZE;
    type->levels_ = 1;
    return type;
}

Type *
Type::NewReference(Zone *zone, Handle<Type> contained, bool isConst)
{
    Local<Type> type(zone, Type::cast(zone->allocate(MapKind_Type, sizeof(Type), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    type->kind_ = REFERENCE;
    type->name_ = NULL;
    type->const_ = isConst;
    return type;
}

Type *
Type::NewEnum(Zone *zone, Handle<String> name)
{
    Local<Type> type(zone, Type::cast(zone->allocate(MapKind_Type, sizeof(Type), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    type->kind_ = ENUM;
    type->name_ = name;
    return type;
}

#if 0
Type *
Type::NewNative(Zone *zone, Handle<Type> returnType, Handle<FixedArray> parameters,
                Handle<FixedArray> defaults, bool variadic)
{
    Local<Type> type(zone, Type::cast(zone->allocate(MapKind_Type, sizeof(Type), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    type->kind_ = NATIVE;
    type->name_ = NULL;
    type->contained_ = NULL;
    type->fields_ = NULL;
    type->newMap_ = NULL;
    type->returnType_ = returnType;
    type->parameters_ = parameters;
    type->defaults_ = defaults;
    type->variadicNative_ = variadic;
    return type;
}
#endif

bool
Type::Compare(Type *left, Type *right)
{
    if (left == right)
        return true;

    if (left->kind() != right->kind())
        return false;

    switch (left->kind()) {
      case Type::PRIMITIVE:
        return left->primitive() == right->primitive();

      case Type::ARRAY:
      {
        ArrayType *aleft = ArrayType::cast(left);
        ArrayType *aright = ArrayType::cast(right);
        if (aleft->levels() != aright->levels())
            return false;
        if (aleft->isFixedLength() != aright->isFixedLength())
            return false;
        if (aleft->isFixedLength() && aleft->fixedLength() != aright->fixedLength())
            return false;
        return Compare(aleft->contained(), aright->contained());
      }

      case Type::FUNCTION:
      {
        FunctionType *fleft = FunctionType::cast(left);
        FunctionType *fright = FunctionType::cast(right);
        if (!Compare(fleft->returnType(), fright->returnType()))
            return false;
        if (fleft->parameters()->length() != fright->parameters()->length())
            return false;
        if (fleft->isNative() != fright->isNative())
            return false;
        if (fleft->isNative() && (fleft->isNativeVariadic() != fright->isNativeVariadic()))
            return false;
        for (unsigned i = 0; i < fleft->parameters()->length(); i++) {
            Type *leftparam = fleft->parameterAt(i);
            Type *rightparam = fright->parameterAt(i);
            if (!Compare(leftparam, rightparam))
                return false;
        }
        return true;
      }

      case Type::ENUM:
        return false;

      case Type::VOID:
      	return true;

      default:
        assert(left->kind() == Type::REFERENCE);
        return Compare(left->contained_ref(), right->contained_ref());
    }
}


StructType *
StructType::New(Zone *zone, Handle<String> name, Handle<FixedArray> fields)
{
    Local<StructType> type(zone, StructType::cast(zone->allocate(MapKind_StructType, sizeof(StructType), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    type->kind_ = STRUCT;
    type->name_ = name;
    type->newMap_ = NULL;
    type->fields_ = fields;

    // Fill in field offsets.
    StructureBufferBuilder builder;
    Local<Type> fieldType(zone);
    for (size_t i = 0; i < fields->length(); i++) {
        Descriptor *desc = Descriptor::cast(fields->at(i));
        fieldType = desc->type();

        unsigned offset;
        if (!builder.add(fieldType, &offset))
            return NULL;
        desc->setOffset(offset);
    }

    Local<StructMap> map(zone, StructMap::New(zone, builder, type));
    if (!map)
        return NULL;

    type->newMap_ = map;

    return type;
}

Descriptor *
StructType::lookupField(Handle<String> name, unsigned *index)
{
    for (unsigned i = 0; i < fields_->length(); i++) {
        Descriptor *desc = Descriptor::cast(fields_->at(i));
        if (desc->name() == name) {
            if (index)
                *index = i;
            return desc;
        }
    }

    return NULL;
}

FunctionType *
FunctionType::New(Zone *zone, TokenKind token)
{
    Local<FunctionType> type(zone, FunctionType::cast(zone->allocate(MapKind_FunctionType, sizeof(FunctionType), Heap::Tenure_Old)));
    if (!type)
        return NULL;

    type->kind_ = FUNCTION;
    type->name_ = NULL;
    type->parameters_ = NULL;
    type->defaults_ = NULL;
    type->returnType_ = NULL;
    type->token_ = token;
    return type;
}

// :TODO: this leaks an interior pointer.
const char *
ke::GetTypeName(Type *type)
{
    if (type->isArray())
        return "array";
    if (type->isFunction())
        return "function";
    if (type->isVoid())
        return "void";
    if (type->isEnum() || type->isStruct())
        return type->name()->chars();
    if (type->isReference())
        type = type->contained_ref();
    switch (type->primitive()) {
      case PrimitiveType_Bool:
        return "bool";
      case PrimitiveType_Char:
        return "String";
      case PrimitiveType_Int32:
        return "int";
      case PrimitiveType_Float:
        return "Float";
      default:
        return "<unknown>";
    }
}

