#include "bool_con_dis_rewrite.h"
#include "assert.h"
#include "dbug.h"
#include "memory.h"
#include "symbol_table.h"
#include "traverse.h"
#include "tree_basic.h"
#include "mymacros.h"
#include "free.h"

struct INFO
{
};

static info* info_init(void)
{
    info* result;
    DBUG_ENTER("info_init");

    result = (info*)MEMmalloc(sizeof(struct INFO));

    DBUG_RETURN(result);
}

static void info_free(info* arg_info) { MEMfree(arg_info); }

node* BCDRbinop(node* arg_node, info* arg_info)
{
    DBUG_ENTER("BCDRbinop");

    binop bo_type = BINOP_OP(arg_node);


    if (IS_LOG_OP(bo_type))
    {
        node* cond_expr;
        if (bo_type & BO_and)
            cond_expr =
                TBmakeCondexpr(BINOP_LEFT(arg_node), BINOP_RIGHT(arg_node), TBmakeBool(false));
        else // BO_or
            cond_expr =
                TBmakeCondexpr(BINOP_LEFT(arg_node), TBmakeBool(true), BINOP_RIGHT(arg_node));

        CONDEXPR_PREDEXPR(cond_expr)  = TRAVopt(CONDEXPR_PREDEXPR(cond_expr), arg_info);
        CONDEXPR_TRUEEXPR(cond_expr)  = TRAVopt(CONDEXPR_TRUEEXPR(cond_expr), arg_info);
        CONDEXPR_FALSEEXPR(cond_expr) = TRAVopt(CONDEXPR_FALSEEXPR(cond_expr), arg_info);
        CONDEXPR_TYPE(cond_expr) = TY_bool;

        BINOP_LEFT(arg_node) = BINOP_RIGHT(arg_node) = NULL;
        FREEdoFreeTree(arg_node);

        DBUG_RETURN(cond_expr);
    }
    else
    {
        TO(BINOP_LEFT);
        TO(BINOP_RIGHT);

        DBUG_RETURN(arg_node);
    }
}

node* BCDRdoRewrite(node* syntaxtree)
{
    DBUG_ENTER("BCDRdoRewrite");
    info* arg_info = info_init();

    TRAVpush(TR_bcdr);
    syntaxtree = TRAVdo(syntaxtree, arg_info);
    TRAVpop();

    info_free(arg_info);

    DBUG_RETURN(syntaxtree);
}