/*
 * 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/.
 * 
 * File:   polymorphcompiler.h
 * Author: pgess <v.melnychenko@xreate.org>
 *
 * Created on October 7, 2017
 */

#ifndef POLYMORPHCOMPILER_H
#define POLYMORPHCOMPILER_H

#include "pass/compilepass.h"

namespace xreate { namespace polymorph {

typedef Expression Guard;    
    
template <class Parent>
class PolymorphCodeScopeUnit: public Parent{
public:
    PolymorphCodeScopeUnit(CodeScope* codeScope, compilation::IFunctionUnit* f, CompilePass* compilePass)
            : Parent(codeScope, f, compilePass) {}

protected:
    compilation::ICallStatement* findFunction(const Expression& opCall) override {
        const std::string& keyAnnotationGuard = "callguard";
        if (!opCall.tags.count(keyAnnotationGuard)) return Parent::findFunction(opCall);
        
        const Expression& annotationGuard = opCall.tags.at(keyAnnotationGuard);
        assert(annotationGuard.operands.size()==1);
        const Expression& guardSelected = annotationGuard.operands.at(0);

        std::map<Guard, ManagedFnPtr> indexSpecs;
        const std::string& nameCallee = opCall.getValueString();
        const std::list<ManagedFnPtr>& specializations = Parent::pass->man->root->getFunctionSpecializations(nameCallee);
        for(ManagedFnPtr specialization: specializations){
            indexSpecs.emplace(specialization->guard, specialization);
        }
        
        assert(indexSpecs.count(guardSelected));
        return new compilation::CallStatementRaw(Parent::pass->getFunctionUnit(indexSpecs.at(guardSelected))->compile(), Parent::pass->man->llvm);
    }
};

#endif /* POLYMORPHCOMPILER_H */

