/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * typeinference.cpp
 *
 * Author: pgess <v.melnychenko@xreate.org>
 * Created on April 16, 2017, 10:13 AM
 */

/**
 *  \file typeinference.h
 *  \brief Type inference analysis
 */

#include "typeinference.h"
#include "llvmlayer.h"

#include "llvm/IR/Function.h"
#include "llvm/IR/DerivedTypes.h"
#include "transcendlayer.h"

using namespace std;

namespace xreate{
namespace typeinference{

//TODO type conversion:
//a)    automatically expand types int -> bigger int; int -> floating
//b)    detect exact type of `num` based on max used numeral / function type
//c)    warning if need to truncate (allow/dissalow based on annotations)

llvm::Value*
doAutomaticTypeConversion(llvm::Value* source, llvm::Type* tyTarget, llvm::IRBuilder<>& builder) {
    if(tyTarget->isIntegerTy() && source->getType()->isIntegerTy()) {
        llvm::IntegerType* tyTargetInt = llvm::dyn_cast<llvm::IntegerType>(tyTarget);
        llvm::IntegerType* tySourceInt = llvm::dyn_cast<llvm::IntegerType>(source->getType());

        if(tyTargetInt->getBitWidth() < tySourceInt->getBitWidth()) {
            return builder.CreateCast(llvm::Instruction::Trunc, source, tyTarget);
        }

        if(tyTargetInt->getBitWidth() > tySourceInt->getBitWidth()) {
            return builder.CreateCast(llvm::Instruction::SExt, source, tyTarget);
        }
    }

    if(source->getType()->isIntegerTy() && tyTarget->isFloatingPointTy()) {
        return builder.CreateCast(llvm::Instruction::SIToFP, source, tyTarget);
    }

    return source;
}

ExpandedType
getType(const Expression& expression, const AST& ast) {
    if(expression.type.isValid()) {
        return ast.expandType(expression.type);
    }

    if(expression.__state == Expression::IDENT) {
        Symbol s = Attachments::get<IdentifierSymbol>(expression);
        return getType(CodeScope::getDefinition(s), ast);
    }

    if(Attachments::exists<TypeInferred>(expression)) {
        return Attachments::get<TypeInferred>(expression);
    }

    if(expression.__state == Expression::NUMBER) {
        return ExpandedType(TypeAnnotation(TypePrimitive::I32));
    }


    assert(false && "Type can't be determined for an expression");
}

TypeAnnotation collapseColumn(const std::list<Gringo::Symbol>& symbols);

TypeAnnotation
collapseFnGroup(const std::list<Gringo::Symbol>& symbols) {
    Gringo::Symbol symbolAny = symbols.front();
    size_t operandsCount = symbolAny.args().size;

    TypeAnnotation resultT;
    resultT.__operands.reserve(operandsCount);

    for(size_t operandId = 0; operandId < operandsCount; ++operandId) {
        std::list<Gringo::Symbol> column;

        for(const Gringo::Symbol& row : symbols) {
            column.push_back(row.args()[operandId]);
        }

        TypeAnnotation operandT = collapseColumn(column);
        resultT.__operands.push_back(operandT);
    }

    if(resultT.__operands.size() == 1) {
        return resultT.__operands.front();
    }

    if(resultT.__operands.size() > 1) {
        resultT.__operator = TypeOperator::LIST_NAMED;
        return resultT;
    }

    return resultT;
}

TypeAnnotation
collapseColumn(const std::list<Gringo::Symbol>& symbols) {
    TypeAnnotation resultT;
    if(!symbols.size()) return resultT;

    Gringo::Symbol symbolAny = symbols.front();

    switch(symbolAny.type()) {
    case Gringo::SymbolType::Num:
    {
        return TypeAnnotation(TypePrimitive::Num);
    }

    case Gringo::SymbolType::Str:
    {
        return TypeAnnotation(TypePrimitive::String);
    }

    case Gringo::SymbolType::Fun:
    {
        map<string, list < Gringo::Symbol>> fnGroups;

        for(const Gringo::Symbol& row : symbols) {
            fnGroups[row.name().c_str()].push_back(row);
        }

        TypeAnnotation resultT;
        resultT.__operands.reserve(fnGroups.size());
        resultT.bindings.reserve(fnGroups.size());

        for(const auto& group : fnGroups) {
            if(!group.second.size()) continue;

            TypeAnnotation variantT = collapseFnGroup(group.second);
            Gringo::Symbol symbolAny = group.second.front();
            string variantName = symbolAny.name().c_str();
            resultT.fields.push_back(variantName);
            resultT.__operands.push_back(variantT);
        }

        resultT.__operator = TypeOperator::VARIANT;
        if(resultT.__operands.size() == 1) {
            return resultT.__operands.front();
        }
        return resultT;
    }

    case Gringo::SymbolType::Inf:
    case Gringo::SymbolType::Special:
    case Gringo::SymbolType::Sup:
    {
        break;
    }
    }

    assert(false);
    return TypeAnnotation();
}

ExpandedType
dereferenceSlaveType(ExpandedType t, const TranscendLayer* transcend) {
    assert(t->__operator == TypeOperator::SLAVE);
    const string& domain = t->__valueCustom;
    StaticModel model = transcend->query(domain);
    if(!model.size()) return ExpandedType(TypeAnnotation());

    std::list<Gringo::Symbol> symbols;
    for(auto row : model) {
        symbols.push_back(row.second);
    }
    return ExpandedType(collapseFnGroup(symbols));
}

}
} //end of namespace xreate::typeinference
