#include "builtins/builtins.h"
#include "common.h"

using namespace goose::sema;

namespace goose::builtins
{
    class BuiltinFuncInvocationRule : public BaseFuncInvocationRule
    {
        public:
            Value invoke( Context& c, LocationId loc, const Value& callee, const Term& args, const Term& typeCheckedCallPat, TypeCheckingContext& tcc ) const final
            {
                auto callDecomp = Decompose( typeCheckedCallPat,
                    Val< pvec >()
                );

                const auto& typeCheckedRType = callDecomp->get()->terms().front();
                auto typeCheckedArgs = DropVectorTerm( typeCheckedCallPat, 1 );
                auto argCount = VecSize( typeCheckedArgs );
                auto argsInstrSeq = BuildArgsInstrSeq( typeCheckedArgs );

                return BuildComputedValue( typeCheckedRType, argsInstrSeq, callee, cir::Call( argCount, loc ) );
            }

            Value prepareFunc( const Context& c, LocationId funcValLocation, const Value& callee, const Term& typeCheckedCallPat, TypeCheckingContext& tcc ) const final
            {
                return callee;
            }
    };

    const ptr< InvocationRule >& GetBuiltinFuncInvocationRule()
    {
        static ptr< InvocationRule > pRule = make_shared< BuiltinFuncInvocationRule >();
        return pRule;
    }

    void SetupBuiltinFuncInvocationRule( Env& e )
    {
        e.invocationRuleSet()->addRule(
            ValueToEIR( ValuePattern( ANYTERM( _ ),

                ValueToEIR( Value( TypeType(), VEC( TSID( func ),
                TSID( builtin ),
                ANYTERM( _ ), ANYTERM( _ ),
                ANYTERM( _ ), ANYTERM( _ ) ) ) ),

                ANYTERM( _ ) ) ),
            GetBuiltinFuncInvocationRule() );
    }
}
