/**
   ****************************************************************************

  Project:	STACK-MACHINE SIMULATOR
  Filename:	CodeSegment.java
  Written by:	Ettore Pasquini, 1999

Il Code Segment è un'area di memoria dove risiede il codice del programma che si intende eseguire. Il programma è formato da istruzioni eseguite in sequenza dal processore, che vi accede attraverso un registro di segmento CS e un program counter PC.

 ******************************************************************************
*/


import java.util.*;
import StackMachine;
import MachineSignal;

abstract class Segment{
  private int base;
  public int base(){ return base; }
  public void setBase(int newbase){ base = newbase; }
  public abstract int length();
  public abstract void init(); 
}

public class CodeSegment extends Segment{
  private CodeVector theprogram;
 
  /**
  *   costruttori
  */

  public CodeSegment(){
	setBase(0);
	theprogram = new CodeVector();	// inizialmente creo un vettore vuoto
  }
  public CodeSegment( int codebase ){
	setBase( codebase ); 
	theprogram = new CodeVector();
  }

  /**
  *   metodi istanza
  */

  public int length(){ return theprogram.size(); } //è anche il DS base-addr
  public void init() { 
	theprogram.removeAllElements();
	setBase(0);
  }
  public Instruction read( ProgramCounter PC ) throws 
					InvalidCodeReadAddressException{
	return theprogram.readInstructionAt(PC.contents());
  }
  public CodeVector getCodeVector(){ return theprogram;}

  public String toString(){
	return  "\t" + "CS base=\t"   + Integer.toString(base()) +  
		"\t" + "CS length=\t" + theprogram.size() + "\n  CS:" +
		theprogram.stringView(this) +"\n";
  }
}//CodeSegment


/*********/


class CodeVector extends Vector{

  public CodeVector(){ super(0); }
  public CodeVector( int initcapacity){ super(initcapacity); }

  public Instruction readInstructionAt( int addr )
				    throws InvalidCodeReadAddressException{
	try{
		return (Instruction) elementAt(addr);
	}
	catch( ArrayIndexOutOfBoundsException aioobe ){
		throw new InvalidCodeReadAddressException();
	}
  }

  public String stringView(CodeSegment CS){
	int lung= this.size();
	int i=0;
	int baseaddr= CS.base();
	String s= " ADDR\tINSTR\tOPs\n ----\t-------\t---";
	while (i<lung){
		s = s + "\n " + Integer.toString( i+baseaddr ) + "\t"
		      + this.elementAt(i).toString();
		i++;
	}
	return s;
  }
}//CodeVector

