Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Convert This code of python: #!/usr/local/bin/python3 import Parser, Code, SymbolTable, sys # Usage: Assembler.py file.asm # Reads file.asm and outputs file.hack - the assembled machine

Convert This code of python:

#!/usr/local/bin/python3
import Parser, Code, SymbolTable, sys
# Usage: Assembler.py file.asm
# Reads file.asm and outputs file.hack - the assembled machine code as a text file.
class Assembler(object):
def __init__(self):
self.symbols = SymbolTable.SymbolTable()
self.symbol_addr = 16
# First pass: determine memory locations of label definitions: (LABEL)
def pass0(self, file):
parser = Parser.Parser(file)
cur_address = 0
while parser.has_more_commands():
parser.advance()
cmd = parser.command_type()
if cmd == parser.A_COMMAND or cmd == parser.C_COMMAND:
cur_address += 1
elif cmd == parser.L_COMMAND:
self.symbols.add_entry( parser.symbol(), cur_address )
# Second pass: generate code and write result to output file.
def pass1(self, infile, outfile):
parser = Parser.Parser(infile)
outf = open( outfile, 'w' )
code = Code.Code()
while parser.has_more_commands():
parser.advance()
cmd = parser.command_type()
if cmd == parser.A_COMMAND:
outf.write( code.gen_a(self._get_address(parser.symbol())) + ' ' )
elif cmd == parser.C_COMMAND:
outf.write( code.gen_c(parser.dest(), parser.comp(), parser.jmp()) + ' ' )
elif cmd == parser.L_COMMAND:
pass
outf.close()
# Lookup an address - may be symbolic, or already numeric
def _get_address(self, symbol):
if symbol.isdigit():
return symbol
else:
if not self.symbols.contains(symbol):
self.symbols.add_entry(symbol, self.symbol_addr)
self.symbol_addr += 1
return self.symbols.get_address(symbol)
# Drive the assembly process
def assemble(self, file):
self.pass0( file )
self.pass1( file, self._outfile(file) )
def _outfile(self, infile):
if infile.endswith( '.asm' ):
return infile.replace( '.asm', '.hack' )
else:
return infile + '.hack'
main():
if len(sys.argv) != 2:
print( "Usage: Assembler file.asm" )
else:
infile = sys.argv[1]
asm = Assembler()
asm.assemble( infile )

main()

Make it look like this in java:

import java.io.FileWriter;

import java.io.IOException;

import java.lang.reflect.InvocationTargetException;

import javax.swing.JFileChooser;

import javax.swing.SwingUtilities;

import javax.swing.UIManager;

import javax.swing.filechooser.FileNameExtensionFilter;

public class Assembler {

public static void main(String[] args) {

// If there's a command line argument, assume it's an ASM file and

// assemble it.

if (args.length != 0) {

new Assembler().assemble(args[0]);

return;

}

// else -statement here

// Otherwise, pop-up a JFileChooser to allow the user to use a GUI

// to select the ASM file.

JFileChooser fc = new JFileChooser();

//Schedule a job for the event dispatch thread:

//creating and showing the assembler's JFileChooser.

// Wait for the job to finish before continuing.

try {

SwingUtilities.invokeAndWait(new Runnable() {

public void run() {

//Turn off metal's use of bold fonts

UIManager.put("swing.boldMetal", Boolean.FALSE);

// Only allow the selection of files with an extension of .asm.

fc.setFileFilter(new FileNameExtensionFilter("ASM files", "asm"));

// Uncomment the following to allow the selection of files and

// directories. The default behavior is to allow only the selection

// of files.

//fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

if (fc.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) {

System.out.println("No file selected; terminating.");

System.exit(1);

}

}

});

} catch (Exception e) {

e.printStackTrace();

return;

}

new Assembler().assemble(fc.getSelectedFile().getPath());

}

private void assemble(String asmFile) {

// ASM file name without the .asm extension.

String basename = new String(asmFile.substring(0, asmFile.indexOf('.')));

Parser parser = new Parser(asmFile);

// Uncomment each of the following after you implement each

// class.

//Code code = new Code();

//SymbolTable symbolTable = new SymbolTable();

// Output file

FileWriter hackFile;

// Memory location of next assembly command.

int nextCommandLoc = 0;

// Memory location of next variable

int nextVariableLoc = 16;

// Your code for the first pass goes here.

// Prepare for the second pass.

parser = new Parser(asmFile);

try {

hackFile = new FileWriter(basename + ".hack");

// Your code for the second pass goes here.

// Uncomment the following to confirm that the Hack file

// is being written.

//hackFile.write("Hello world ");

hackFile.close();

} catch (IOException e) {

e.printStackTrace();

System.exit(1);

}

}

// You might find this useful.

// Convert the decimal value val to a 15 bit binary string. Assume that

// val's value lies between 0 and 32,767, inclusive. In other words, assume

// that val is non-negative and will fit into a 15 bit number.

private String toImmediate(int val) {

String field = "";

for (int i = 0; i < 15; i++) {

field = (val % 2) + field;

val /= 2;

}

return field;

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Spatial Databases A Tour

Authors: Shashi Shekhar, Sanjay Chawla

1st Edition

0130174807, 978-0130174802

More Books

Students also viewed these Databases questions

Question

How do modern Dashboards differ from earlier implementations?

Answered: 1 week ago