#include "cir/cir.h"

namespace goose::cir
{
    bool Instruction::canBeExecuted() const
    {
        return visit( []< typename ET >( const ET& e )
        {
            if constexpr( is_same_v< ET, monostate > )
                return false;
            else if constexpr( is_same_v< ET, ptr< CFG > > )
                return e->canBeExecuted();
            else
                return e.canBeExecuted();
        }, m_content );
    }

    bool Instruction::canBeEagerlyEvaluated() const
    {
        return visit( []< typename ET >( const ET& e )
        {
            if constexpr( is_same_v< ET, monostate > )
                return false;
            else if constexpr( is_same_v< ET, ptr< CFG > > )
                return e->canBeEagerlyEvaluated();
            else
                return e.canBeEagerlyEvaluated();
        }, m_content );
    }

    ostream& operator<<( ostream& out, const Instruction& inst )
    {
        return visit( [&]< typename ET >( const ET& e ) -> ostream&
        {
            if constexpr( is_same_v< ET, monostate > )
                return out << "NIL";
            else if constexpr( is_same_v< ET, ptr< CFG > > )
                return out << "NESTED_CFG";
            else
                return out << e;
        }, inst.m_content );
    }

    ostream& operator<<( ostream& out, const Select& ins )
    {
        out << "SELECT(" << ins.m_memberIndex << ", ";
        if( ins.m_baseAddr )
            out << *ins.m_baseAddr;
        else
            out << "null" ;
         return out << ')';
    }

    ostream& operator<<( ostream& out, const Load& ins )
    {
        out << "LOAD(";
        if( ins.m_addr )
            out << *ins.m_addr;
        else
            out << "null";
         return out << ", " << ins.m_type << ')';
    }

    ostream& operator<<( ostream& out, const Store& ins )
    {
        out << "STORE(";
        if( ins.m_addr )
            out << *ins.m_addr;
        else
            out << "null";
        return out << ", " << ins.m_val << ')';
    }

    bool Store::canBeEagerlyEvaluated() const
    {
        return m_addr && CanValueBeEagerlyEvaluated( m_val );
    }
}
