#include "for_var_rewrite.h"
#include "assert.h"
#include "ctinfo.h"
#include "dbug.h"
#include "memory.h"
#include "symbol_table.h"
#include "traverse.h"
#include "tree_basic.h"
#include "mymacros.h"


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

    struct st_entry*     for_var_entry = FOR_STLINK(arg_node)->child_syms->head;
    struct symbol_table* fun_st        = (struct symbol_table*)arg_info;

    /* moves the entire head->->->tail chain */
    st_append_symtabs(FOR_STLINK(arg_node)->child_syms, fun_st);

    FOR_STLINK(arg_node)->child_syms = NULL; // these have all been moved, so don't free them

    FOR_STLINK(arg_node)    = NULL;
    FOR_VARSTLINK(arg_node) = for_var_entry;

    // Reserve space for limit and step
    for_var_entry->frameoffset += 2;
    fun_st->n_vars += 2;

    TO(FOR_BLOCK);

    DBUG_RETURN(arg_node);
}

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

    arg_info = (info*)(FUNDEF_STLINK(arg_node)->child_syms);

    TO(FUNDEF_BODY);

    DBUG_RETURN(arg_node);
}

node* FVRdoRewrite(node* syntaxtree)
{
    DBUG_ENTER("FVRdoRewrite");

    TRAVpush(TR_fvr);
    syntaxtree = TRAVdo(syntaxtree, NULL);
    TRAVpop();

    st_print(PROGRAM_SYMBOLTABLE(syntaxtree), "", 0);

    DBUG_RETURN(syntaxtree);
}