Solved

Assembler

Posted on 2009-07-10
13
360 Views
Last Modified: 2012-05-07
This is basically about assembler (.java) for reading a define file that has extension (.src) and writing it or the output is file extension is (.xxx)... The Assembler has a role during the execuation which are:
1- Invalid opcode
2- Missing opcode
3- Illegal comment
4- Illegal constant
5- Illegal memory address.

I have done so far number 1. 3 and 5 but i want to develop my code and do 2- Missing opcode and 4- Illegal constant...

The code is show below and the main running code is attached
import java.util.Scanner;

import java.lang.String;
 

class Code

{

	private String opcodeSource;

	private String comment;

	private int operand;

	private int opcode;

	private Boolean errorStatus = false;

	private String errorMessage;

	public Code(String codeLine)

	{

		Scanner in = new Scanner(codeLine);
 

		opcodeSource = in.next().trim();
 

		if(!opcodeSource.toLowerCase().equals("stop"))

		{

			if(!opcodeSource.equals(" "))

			{
 

				opcode = inputDecoder(opcodeSource);

				try // this try-catch block is supposed to catch missing opcode but it does not work properly

				{

					operand = in.nextInt();

					comment = in.nextLine().trim();

				}

				catch (Exception e)

				{

					opcodeSource = " ";

					String junk = in.nextLine();

					System.out.println(junk);

					errorStatus = true;

					errorMessage ="Missing opcode";

				}
 

			}

		}

		else  // if opcode is STOP

		{

			operand = 0;

			comment = "; end program";

			opcode = 15;

		}

		if(opcode == 12)  // checks for invalid opcode

		{

			errorStatus = true;

			errorMessage = "Invalid opcode";

		}

		if(!comment.startsWith(";")) //checks for illegal comments

		{

			errorStatus = true;

			errorMessage = "Illegal comment";

		}

		if(opcode == 1 | opcode == 2 | opcode == 3 | opcode == 4 ) // checks for illegal memory address

		{

			if(operand < 0)

			{

				errorStatus = true;

				errorMessage = "Illegal memory address";

			}

		}

	}
 

	public void setOperand(int opcode)

	{

		this.opcode = opcode;

	}
 

	public Boolean getErrorStatus()

	{

		return errorStatus;

	}
 

	public String getErrorMessage()

	{

		return errorMessage;

	}
 

	public String getOpcodeSource()

	{

		return opcodeSource;

	}
 

	public int getOperand()

	{

		return operand;

	}
 

	public String getComment()

	{

		return comment;

	}
 

	public int getOpcode()

	{

		return opcode;

	}
 

	public int inputDecoder(String temp)

	{

		int result;

		temp = temp.toLowerCase();
 

		if(temp.equals("nop"))

			result = 0;
 

		else if(temp.equals("load"))

			result = 1;
 

		else if(temp.equals("store"))

			result = 2;
 

		else if(temp.equals("add"))

			result = 3;
 

		else if(temp.equals("sub"))

			result = 4;
 

		else if(temp.equals("loadi"))

			result = 5;
 

		else if(temp.equals("addi"))

			result = 6;
 

		else if(temp.equals("subi"))

			result = 7;
 

		else if(temp.equals("brz"))

			result = 8;
 

		else if(temp.equals("brn"))

			result = 9;
 

		else if(temp.equals("brp"))

			result = 10;
 

		else if(temp.equals("bra"))

			result = 11;
 

		else if(temp.equals("trap"))

			result = 14;
 

		else if(temp.equals("stop"))

			result = 15;
 

		else

			result = 12;
 

		return result;

	}

}

Open in new window

main.doc
0
Comment
Question by:adam_prog
  • 7
  • 6
13 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 24829752
Please give examples of good input and bad input
0
 

Author Comment

by:adam_prog
ID: 24829901
i have attached the example
0
 

Author Comment

by:adam_prog
ID: 24829903
read the file that has exension .src  and the date contains in that file as following way:

LOADI      0
STORE      499
TRAP      0
STORE      498
LOAD      498
SUBI      0
BRP      2
BRA      14
LOAD      499
ADD       498
STORE       499
LOAD      498
SUBI      1
STORE      498
BRA      -22
LOAD      499
TRAP      1
STOP      0
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24829978
>>i have attached the example

Nope - all you attached was a small app concerned with RMARepair.

So you've just posted a good sample. What bad sample are you trying to protect against?
0
 

Author Comment

by:adam_prog
ID: 24829983
bad example if the opcode is missing should print option 1- Invalid opcode
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24829995
Because you're using a Scanner and because of its default delimiters, that's relatively tricky - you'll only find a missing int code when you try to parse an instruction (since the number is missing) as an int.

I would be inclined to read lines and split into a 2-element array. You can then count the elements and take action if < 2 and !stop
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:adam_prog
ID: 24830010
can you code it or what my code should be?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24830028
Essentially just:
in.useDelimiter("[\r\n]");

...
 

String[] instAndOpCode = in.nextLine().split("\\s+");

Open in new window

0
 

Author Comment

by:adam_prog
ID: 24830035
how the array could be done
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24839451
You'll find it even easier using this:

http://technojeeves.com/joomla/index.php/free/74-string-list

>>how the array could be done

Check the element count - it will tell you if the opcode is missing (or at least either instruction or opcode)
0
 

Author Comment

by:adam_prog
ID: 24899938
I tried to put the array but it still only print one line... I only want to print or write the all content on the file... as anyone can help or can fix my code...i appreciate... thanks.. here is the code


import java.io.InputStreamReader;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.*;

import java.util.ArrayList;

import java.util.Scanner;

class CSE340Project1

{
 

	public static void main(String args[])

	{

		ArrayList inputList= new ArrayList();

		String filename,line,fileToSave;

		Boolean check = false;

		Boolean cont = false;

		Scanner scan = new Scanner(System.in);
 
 

					

		System.out.println("Enter the file name");

		filename = scan.next();

		//filename BufferReader.next();

		filename = filename.toLowerCase();
 

		try

		{

			check = checkFilename(filename);

			cont = true;

		}

		catch(Exception e)

		{

			System.out.println("Assembily not complete - Illegal file name");

		}

		if(cont)

		{

			try

			{

				

				FileInputStream fstream = new FileInputStream(filename);

				BufferedReader readLine = new BufferedReader (new InputStreamReader(System.in));

				DataInputStream in = new DataInputStream(fstream);

				int count = 0;

				//line = in.readLine();

				//count++;

				while ( in.available() !=0)

				{

					line = in.readLine();

					//inputList.add(new Code(line));

						

					String line1[]= line.split("\\s+");

					count++;

				}
 

				in.close();

		        

			}

			

			catch (Exception e)

			

			{

				System.err.println("Assembily not complete - File does not exist");

				cont = false;

			}

			if(cont)

			{

				fileToSave = filename.replace(".src",".");

				cont = createListingFile(inputList,fileToSave);

				cont =	createExecutableFile(inputList,fileToSave);

			}

			if(cont)

			{

				System.out.println("Assembly complete. No errors");

			}
 

		}

	}
 

	public static Boolean createListingFile(ArrayList list, String fileToSave)

	{

		FileOutputStream out; 			// declare a file output object

		PrintStream p; 					// declare a print stream object

		int lineCount = 0;

		Boolean result = true;
 

		try

		{

			// Create a new file output stream

			out = new FileOutputStream(fileToSave + "lis");
 

			// Connect print stream to the output stream

			p = new PrintStream( out );
 

			//p.println ("This is written to a file");

			p.println("Loc\tOpCode\tOperand");

			for(int index = 0; index < list.size(); index++)

			{

				Code temp = (Code)list.get(index);

				lineCount++;

				//prints one line for current code object

				p.println(2*index+"\t"+temp.getOpcode()+"\t"+temp.getOperand()+"\t"+

				(index+1)+".\t"+temp.getOpcodeSource()+"\t"+temp.getOperand()+"\t"+

				temp.getComment());

				if(temp.getErrorStatus())

				{

					p.println("Error: "+temp.getErrorMessage());

					System.out.print("Error: "+temp.getErrorMessage()+"\nOccured at line number: "+lineCount+"\n");

					throw new Exception();

				}

			}

			p.close();
 

		}

		catch (Exception e)

		{

			System.err.println ("Assembily error");

			result = false;

		}

		return result;

	}

	public static Boolean createExecutableFile(ArrayList list, String fileToSave)

	{
 

		FileOutputStream out; // declare a file output object

		PrintStream p; // declare a print stream object

		int lineCount = 0;

		Boolean result = true;
 

		try

		{

			// Create a new file output stream

			out = new FileOutputStream(fileToSave + "xxx");
 

			// Connect print stream to the output stream

			p = new PrintStream( out );
 

			for(int index = 0; index < list.size(); index++)

			{

				Code temp = (Code)list.get(index);

				lineCount++;

				if(temp.getErrorStatus())

				{

					System.out.print("Error: "+temp.getErrorMessage()+"\nOccured at line number: "+lineCount+"\n");

					throw new Exception();

				}

				else

				{

					p.println(temp.getOpcode());

					p.println(temp.getOperand());

				}

			}

			//p.println ("This is written to a file");

			p.close();
 

		}

		catch (Exception e)

		{

			System.err.println ("Assembily error");

			result = false;

		}

		return result;

	}

	public static Boolean checkFilename(String filename) throws Exception

	{

		Boolean result = false;

		if(filename.endsWith(".src"))

			result = true;

		else

			throw new Exception();

		return result;

	}

}

Open in new window

0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 24902079
Replace

>>
        FileInputStream fstream = new FileInputStream(filename);
        BufferedReader readLine = new BufferedReader(new InputStreamReader(
                    System.in));
        DataInputStream in = new DataInputStream(fstream);
        int count = 0;

        //line = in.readLine();
        //count++;
        while (in.available() != 0) {
            line = in.readLine();

            //inputList.add(new Code(line));
            String[] line1 = line.split("\\s+");
            count++;
        }

        in.close();
>>

by
        BufferedReader readLine = new BufferedReader(new FileReader(filename));

        int count = 0;

        String line = null;

        while ((line = in.readLine()) != null) {

            String[] line1 = line.split("\\s+");

            count++;

            System.out.printf("Number of tokens on line %d is %d\n", count, line1.length);

        }

        in.close();

Open in new window

0
 

Author Closing Comment

by:adam_prog
ID: 31602366
very good
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
This is about my first experience with programming Arduino.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now