/*******************************************************************\

Module:

Author: Daniel Kroening, kroening@cs.cmu.edu

\*******************************************************************/

#include <algorithm>

#include "i2string.h"
#include "rename.h"

/*******************************************************************\

Function: get_new_name

  Inputs: symbol to be renamed, namespace

 Outputs: new symbol

 Purpose: automated variable renaming

\*******************************************************************/

void get_new_name(symbolt &symbol, const namespacet &ns)
{
  get_new_name(symbol.name, ns);
}

/*******************************************************************\

Function: get_new_name

  Inputs: symbol to be renamed, namespace

 Outputs: new symbol

 Purpose: automated variable renaming

\*******************************************************************/

void get_new_name(irep_idt &new_name, const namespacet &ns)
{
  const symbolt *symbol;
  if(ns.lookup(new_name, symbol))
    return;

  std::string prefix=id2string(new_name)+"_";

  new_name=prefix+i2string(ns.get_max(prefix)+1);
}

/*******************************************************************\

Function: rename

  Inputs: expression, old name, new name

 Outputs: modifies the expression
          returns false iff something was renamed

 Purpose: automated variable renaming

\*******************************************************************/

bool rename(exprt &expr, const irep_idt &old_name,
            const irep_idt &new_name)
{
  bool result=true;

  if(expr.id()=="symbol")
  {
    if(expr.get("identifier")==old_name)
    {
      expr.set("identifier", new_name);
      result=false;
    }
  }
  else
  {
    if(expr.id()=="address_of" ||
       expr.id()=="implicit_adress_of")
    {
      // TODO
    }
    else
      Forall_operands(it, expr)
        if(!rename(*it, old_name, new_name))
          result=false;
  }

  return result;
}
