/* 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/.
 * 
 * Author: pgess <v.melnychenko@xreate.org>
 * 
 * compilepass.h
 */

#ifndef COMPILEPASS_H
#define COMPILEPASS_H

#include "abstractpass.h"

#include "llvm/IR/Function.h"

namespace xreate {
    class TranscendLayer;
    class CompilePass;
    class LLVMLayer;
    
    namespace interpretation{
        class TargetInterpretation;
    }
}

namespace xreate { namespace compilation {

class ICodeScopeUnit;
class IFunctionUnit;
class TransformationsManager;

/** \brief Holds current position in %AST while traversing*/
struct Context{
    ICodeScopeUnit* scope;
    IFunctionUnit* function;
    CompilePass* pass;
};

/** \brief Interface to specify custom way of function invocation 
 *  \details Default implementation is xreate::compilation::RawFnInvocation
 */
class IFnInvocation {
public:
    /** \brief Returns result of custom function invocation for given arguments*/
    virtual llvm::Value* operator() (std::vector<llvm::Value *>&& args, const std::string& hintDecl="") = 0;
};

/** \brief Default IFnInvocation implementation */
class BruteFnInvocation: public IFnInvocation{
public:
    BruteFnInvocation(llvm::Function* callee, LLVMLayer* l)
        : __callee(callee), __calleeTy(callee->getFunctionType()), llvm(l) {}
    BruteFnInvocation(llvm::Value* callee, llvm::FunctionType* ty, LLVMLayer* l)
        : __callee(callee), __calleeTy(ty), llvm(l) {}
    
    /** \brief Makes type conversions and returns LLVM call statement with given arguments*/
    llvm::Value* operator() (std::vector<llvm::Value *>&& args, const std::string& hintDecl="");
        
protected:
    llvm::Value* __callee;        
    llvm::FunctionType* __calleeTy;
    LLVMLayer* llvm;
};

/** \brief Interface to allow modification of CodeScope compilation
 *  \details Default implementation defined in xreate::compilation::DefaultCodeScopeUnit
 */
class ICodeScopeUnit{
public:
    CompilePass* const pass;
    IFunctionUnit* const function;
    const CodeScope* const scope;
    llvm::BasicBlock* currentBlockRaw;
    
    ICodeScopeUnit(const CodeScope* const codeScope, IFunctionUnit* f, CompilePass* compilePass);
    virtual ~ICodeScopeUnit();

    virtual llvm::Value* compile(const std::string& hintBlockDecl="")=0;
    virtual llvm::Value* processSymbol(const Symbol& s, std::string hintRetVar="")=0;
    virtual llvm::Value* process(const Expression& expr, const std::string& hintVarDecl="")=0;
    
    virtual Symbol bindArg(llvm::Value* value, std::string&& alias)=0;
    virtual void bindArg(llvm::Value* value, const ScopedSymbol& s)=0;
    virtual void reset() = 0;
protected:
    virtual IFnInvocation* findFunction(const Expression& opCall)=0;
};

/** \brief Minimal useful ICodeScopeUnit implementation suited for inheritance */
class BasicCodeScopeUnit: public ICodeScopeUnit{
public:
    BasicCodeScopeUnit(const CodeScope* const codeScope, IFunctionUnit* f, CompilePass* compilePass);

    llvm::Value* processSymbol(const Symbol& s, std::string hintRetVar="") override;
    llvm::Value* process(const Expression& expr, const std::string& hintVarDecl="") override;
    llvm::Value* compile(const std::string& hintBlockDecl="") override;
    
protected:
    IFnInvocation* findFunction(const Expression& opCall) override;
};

/** \brief Interface to specify compilation of %Function */
class IFunctionUnit{
public:
   IFunctionUnit(ManagedFnPtr f, CompilePass* p): function(f), pass(p) {}
   virtual ~IFunctionUnit();

    llvm::Function* compile();

    ICodeScopeUnit* getEntry();
    ICodeScopeUnit* getScopeUnit(const CodeScope * const scope);
    ICodeScopeUnit* getScopeUnit(ManagedScpPtr scope);

    virtual llvm::Type* prepareResult() = 0;
    
    ManagedFnPtr function;
    llvm::Function* raw = nullptr;
    
protected:
    CompilePass* pass=nullptr;
    
    virtual std::string prepareName() = 0;
    virtual std::vector<llvm::Type*>  prepareSignature() = 0;
    virtual llvm::Function::arg_iterator prepareBindings() = 0;
    
private:
    std::map<const CodeScope * const, std::weak_ptr<ICodeScopeUnit>> __scopes;
    std::list<std::shared_ptr<ICodeScopeUnit>> __orphanedScopes;
};

/** \brief Minimal useful IFunctionUnit implementation suited for inheritance */
class BasicFunctionUnit: public IFunctionUnit{
public:
    BasicFunctionUnit(ManagedFnPtr f, CompilePass* p)
    : IFunctionUnit(f, p) {}

protected:
    std::string prepareName() override;
    virtual std::vector<llvm::Type*>  prepareSignature() override;
    virtual llvm::Type* prepareResult() override;
    virtual llvm::Function::arg_iterator prepareBindings() override;
};
} // end of namespace compilation

class CompilePass : public AbstractPass<void> {
    friend class compilation::BasicCodeScopeUnit;
    friend class compilation::IFunctionUnit;

public:
    compilation::TransformationsManager* managerTransformations;
    interpretation::TargetInterpretation* targetInterpretation;
    
    CompilePass(PassManager* manager): AbstractPass<void>(manager) {}
    /** \brief Executes compilation process */
    void run() override;
    
    /**\brief Returns compiled specified %Function
     * \details Executes function compilation or read cache if it's already done
     */
    compilation::IFunctionUnit* getFunctionUnit(const ManagedFnPtr& function);
    
    /**\brief Returns compiled main(entry) %Function in program */
    llvm::Function* getEntryFunction();
    
    /** \brief Initializes queries required by compiler. See xreate::IQuery, xreate::TranscendLayer */
    static void prepareQueries(TranscendLayer* transcend);
    
    
    
protected:
    virtual compilation::IFunctionUnit* buildFunctionUnit(const ManagedFnPtr& function)=0;
    virtual compilation::ICodeScopeUnit* buildCodeScopeUnit(const CodeScope* const scope, compilation::IFunctionUnit* function)=0;
    
private:
    //TODO free `functions` in destructor
    std::map<unsigned int, compilation::IFunctionUnit*> functions;
    llvm::Function* entry = 0;
};

namespace compilation{

/** \brief Constructs compiler with desired %Function and %Code Scope decorators. See adaptability in xreate::CompilePass*/    
template<class FUNCTION_DECORATOR=void, class SCOPE_DECORATOR=void>
class CompilePassCustomDecorators: public ::xreate::CompilePass{
public:
    CompilePassCustomDecorators(PassManager* manager): ::xreate::CompilePass(manager) {}
    
    virtual compilation::IFunctionUnit* buildFunctionUnit(const ManagedFnPtr& function) override{
        return new FUNCTION_DECORATOR(function, this);
    }
    
    virtual compilation::ICodeScopeUnit* buildCodeScopeUnit(const CodeScope* const scope, IFunctionUnit* function) override{
        return new SCOPE_DECORATOR(scope, function, this);
    }        
};

template<>
compilation::IFunctionUnit* 
CompilePassCustomDecorators<void, void>::buildFunctionUnit(const ManagedFnPtr& function);

template<>
compilation::ICodeScopeUnit*
CompilePassCustomDecorators<void, void>::buildCodeScopeUnit(const CodeScope* const scope, IFunctionUnit* function);

}} //end of namespace xreate::compilation

#endif // COMPILEPASS_H
