package rebelsky.pal;

/**
 * Registers for PAL, the pseudo-assembly language.  You can not create
 * your own registers.  Instead, you should use the constants given
 * in the class (pc, sp, fp, ...).
 *
 * @author Samuel A. Rebelsky
 * @version 1.1 of December 2002
 */
public class Register
  extends Variable
{
  // +-----------+---------------------------------------------------------
  // | Constants |
  // +-----------+

  /** The program counter. */
  public static Register pc = new Register("pc");

  /** The stack pointer. */
  public static Register sp = new Register("sp");

  /** The frame pointer. */
  public static Register fp = new Register("fp");


  // +--------+------------------------------------------------------------
  // | Fields |
  // +--------+

  /** The name of the register. */
  String name;


  // +--------------+------------------------------------------------------
  // | Constructors |
  // +--------------+

  Register(String name) {
    this.name = name;
  } // Register(String)


  // +---------+-----------------------------------------------------------
  // | Methods |
  // +---------+

  /** 
   * Get the integer stored in this register. 
   *
   * @exception Exception
   *   If the register is invalid.
   */
  public int iget(Computer hal)
    throws Exception
  {
    if (this == pc) return hal.pc;
    else if (this == sp) return hal.sp;
    else if (this == fp) return hal.fp;
    else throw new Exception("Invalid register: %" + this.name);
  } // iget(Computer)

  /**
   * Store an integer in this register.
   *
   * @exception Exception
   *   If the register is invalid.
   */
  public void iset(Computer hal, int newval)
    throws Exception
  {
    if (this.name == "pc") hal.pc = newval;
    else if (this.name == "sp") hal.sp = newval;
    else if (this.name == "fp") hal.fp = newval;
    else throw new Exception("Invalid register: %" + this.name);
  } // iset(Computer,int)

  /**
   * Convert to a string (e.g., for printing).
   */
  public String toString() {
    return "%" + this.name;
  } // toString()
} // class Register

