Beispiel #1
0
def main(infile_path: str, outfile_path: str):
    print(infile_path)
    vm_files = [path for path in glob.glob(infile_path + "/*.vm")]
    code_writer = CodeWriter(filepath=outfile_path)
    code_writer.write_init()
    for filepath in vm_files:
        print(filepath)
        parser = Parser(filepath=filepath)
        code_writer.set_file_path(filepath)
        while parser.hasMoreCommands():
            cmd = parser.commandType()
            if cmd == C_ARITHMETIC:
                code_writer.writeArithmetic(parser.arithmetic())
            elif cmd == C_PUSH or cmd == C_POP:
                code_writer.writePushPop(cmd,
                                         parser.arg1(),
                                         index=int(parser.arg2()))
            elif cmd == C_LABEL:
                code_writer.writeLabel(parser.arg1())
            elif cmd == C_GOTO:
                code_writer.writeGoto(parser.arg1())
            elif cmd == C_IF:
                code_writer.writeIf(parser.arg1())
            elif cmd == C_FUNCTION:
                code_writer.writeFunction(parser.arg1(), parser.arg2())
            elif cmd == C_RETURN:
                code_writer.writeReturn()
            elif cmd == C_CALL:
                code_writer.writeCall(parser.arg1(), parser.arg2())
            parser.advance()
    code_writer.close()
def main(input_file):
    if len(input_file.split('.')) == 1:
        if input_file[-1] == '/':
            input_file = input_file[:-1]
        output_file = join(input_file, input_file.split('/')[-1])
        input_files = [
            join(input_file, f) for f in listdir(input_file)
            if f.split('.')[1] == 'vm' and f != 'Sys.vm'
            and isfile(join(input_file, f))
        ]
        input_files.insert(0, join(input_file, 'Sys.vm'))
        print('Input files: {}'.format(input_files))
    else:
        input_files = [input_file]
        directory = '/'.join(input_file.split('/')[:-1])
        output_file = join(directory, input_file.split('/')[-1].split('.')[0])

    code_writer = CodeWriter(output_file)
    code_writer.write_init()

    for input_file in input_files:
        parser = Parser(input_file)
        code_writer.set_filename(input_file)
        n = 0
        while parser.advance():
            com_type = parser.command_type()
            print('LINE {}'.format(n))
            print('\tcom type: {}'.format(com_type))
            print('\tcommand: {}'.format(parser.command))
            if com_type != parser.c_return:
                arg1 = parser.arg1()
                if com_type in [
                        parser.c_push, parser.c_pop, parser.c_function,
                        parser.c_call
                ]:
                    arg2 = parser.arg2()

            if com_type == parser.c_arithmetic:
                code_writer.write_arithmetic(arg1)
            elif com_type in [parser.c_pop, parser.c_push]:
                code_writer.write_push_pop(com_type, arg1, int(arg2))
            elif com_type == parser.c_label:
                code_writer.write_label(arg1)
            elif com_type == parser.c_goto:
                code_writer.write_goto(arg1)
            elif com_type == parser.c_if:
                code_writer.write_if(arg1)
            elif com_type == parser.c_function:
                code_writer.write_function(arg1, arg2)
            elif com_type == parser.c_return:
                code_writer.write_return()
            elif com_type == parser.c_call:
                code_writer.write_call(arg1, arg2)
            n += 1
    code_writer.close()
Beispiel #3
0
def translate(vmfiles, asmfile):
    w = CodeWriter(asmfile)

    for fn in vmfiles:
        print 'Parsing %s...' % fn
        p = Parser(fn)
        w.set_filename(os.path.splitext(os.path.split(fn)[-1])[0])

        # Insert Code Here

    print 'Writing %s...' % asmfile
    w.close()
Beispiel #4
0
def translate(vmfiles, asmfile):
    w = CodeWriter(asmfile)
    
    for fn in vmfiles:
        print 'Parsing %s...'%fn
        p = Parser(fn)
        w.set_filename( os.path.splitext( os.path.split(fn)[-1] )[0] )
    
        # Insert Code Here
            
    print 'Writing %s...'%asmfile
    w.close()
Beispiel #5
0
def main():
	filename = sys.argv[1].split('.')[0]
	parser = Parser(filename)
	code = CodeWriter(filename)
	while(parser.has_more_commands()):
		parser.advance()

		command_type = parser.command_type()

		if command_type == 'C_ARITHMETIC':
			code.write_arithmetic(parser.arg1())

		elif command_type == 'C_PUSH' or command_type == 'C_POP':
			code.write_push_pop(parser.command(), parser.arg1(), parser.arg2())

		# print(parser.current_command)
	parser.close()
	code.close()
Beispiel #6
0
def main():
    vm_filename = sys.argv[1]
    asm_filename = vm_filename.replace('.vm', '.asm')
    vm_file = open(vm_filename, 'r')
    asm_file = open(asm_filename, 'a')

    parser = Parser(vm_file)
    code_writer = CodeWriter(asm_file)

    while parser.has_more_commands():
        parser.advance()
        if parser.command_type() == C_ARITHMETIC:
            code_writer.write_arithmetic(parser.arg1())
        elif parser.command_type() == C_PUSH:
            code_writer.write_push_pop(C_PUSH, parser.arg1(), parser.arg2())
        elif parser.command_type() == C_POP:
            code_writer.write_push_pop(C_POP, parser.arg1(), parser.arg2())

    vm_file.close()
    code_writer.close()
Beispiel #7
0
def main():
    argument = sys.argv[1]
    if argument.endswith('.vm'):
        asm_filename = argument.replace('.vm', '.asm')
        asm_file = open(asm_filename, 'a')
        code_writer = CodeWriter(asm_file)
        open_vm_file(argument, code_writer)
        code_writer.close()
    else:
        if argument.endswith('/'):
            argument = argument[0:-1]
        foldername = os.path.basename(argument)
        asm_file = open('%s/%s.asm' % (argument, foldername), 'a')
        code_writer = CodeWriter(asm_file)
        code_writer.write_comment('write init')
        code_writer.write_init()
        files = glob.glob('%s/*.vm' % argument)
        for file in files:
            open_vm_file(file, code_writer)
        code_writer.close()
def main():

    # If there is an invalid number of arguments the program stops.
    if len(sys.argv) != 2:
        print("ERROR: Invalid number of arguments. Expected: file_name.vm ")
        exit(1)
    # The VM translator accepts directories or vm files to be translated into assembly files.
    elif not os.path.isdir(sys.argv[1]) and sys.argv[1][-3:] != ".vm":
        print("ERROR: Invalid argument. Expected: directory or vm file")
        exit(1)

    # Get the name of the file to be parsed from the arguments.
    input_file = sys.argv[1]

    if os.path.isdir(input_file):
        # Split the file path
        file_path = input_file.split("/")
        if input_file.endswith("/"):
            # Creates the code writer with the given directory
            code_writer = CodeWriter("{}/{}".format(input_file, file_path[-2]))
            read_directory(input_file, code_writer)
            code_writer.close()
        else:
            # Creates the code writer with the given directory
            code_writer = CodeWriter("{}/{}".format(input_file, file_path[-1]))
            read_directory(input_file, code_writer)
            code_writer.close()
    else:
        # Creates the code writer with the input file excluding the .vm part
        code_writer = CodeWriter(input_file[0:-3])
        read_file(input_file, code_writer)
        code_writer.close()
Beispiel #9
0
def main():
    file_name = parse_args()
    file_name_noext, _ = path.splitext(file_name)

    raw_data = None
    with open(file_name, "r") as stream:
        raw_data = stream.readlines()

    parser = Parser(raw_data)

    code_writer = CodeWriter()
    code_writer.set_file_name(file_name_noext.split("/")[-1] + ".asm")

    while parser.has_more_commands():
        parser.advance()

        if parser.command_type == C_ARITHMETIC:
            code_writer.writer_arithmetic(parser.operator)
        elif parser.command_type == C_PUSH:
            code_writer.write_push_pop(parser.operator, parser.arg1(),
                                       parser.arg2())
        elif parser.command_type == C_POP:
            code_writer.write_push_pop(parser.operator, parser.arg1(),
                                       parser.arg2())
        elif parser.command_type == C_LABEL:
            pass
        elif parser.command_type == C_GOTO:
            pass
        elif parser.command_type == C_IF:
            pass
        elif parser.command_type == C_FUNCTION:
            pass
        elif parser.command_type == C_RETURN:
            pass
        elif parser.command_type == C_CALL:
            pass
        else:
            pass

    code_writer.close()
Beispiel #10
0
   def translate(self):
      code_writer = CodeWriter(self.destination_file)

      # for each source filename
      for source_filename in self.source_filenames:
         parser = Parser(source_filename)
         code_writer.set_filename(source_filename)

         # parse each command
         while parser.has_more_commands():
            # advance to the next command
            parser.advance()

            # parse the command type
            command_type = parser.command_type()
            if command_type == "C_ARITHMETIC":
               code_writer.write_arithemtic(parser.arg1())
            elif command_type in ["C_POP", "C_PUSH"]:
               code_writer.write_push_pop(command_type, parser.arg1(), parser.arg2())
            elif command_type == "C_LABEL":
               code_writer.write_label(parser.arg1())
            elif command_type == "C_GOTO":
               code_writer.write_goto(parser.arg1())
            elif command_type == "C_IF":
               code_writer.write_if(parser.arg1())
            elif command_type == "C_FUNCTION":
               code_writer.write_function(parser.arg1(), parser.arg2())
            elif command_type == "C_RETURN":
               code_writer.write_return()
            elif command_type == "C_CALL":
               code_writer.write_call(parser.arg1(), parser.arg2())
            else:
               raise Exception("Not implemented: command type " + command_type)


      # close the output file
      code_writer.close()
Beispiel #11
0
   def translate(self):
      code_writer = CodeWriter(self.destination_file)

      # for each source filename
      for source_filename in self.source_filenames:
         parser = Parser(source_filename)
         code_writer.set_filename(source_filename)

         # parse each command
         while parser.has_more_commands():
            # advance to the next command
            parser.advance()

            # parse the command type
            command_type = parser.command_type()
            if command_type == "C_ARITHMETIC":
               code_writer.write_arithemtic(parser.arg1())
            elif command_type in ["C_POP", "C_PUSH"]:
               code_writer.write_push_pop(command_type, parser.arg1(), parser.arg2())
            else:
               raise Error("Not implemented: command type " + command_type)

      # close the output file
      code_writer.close()
Beispiel #12
0
def main():

    # If there is an invalid number of arguments the program stops.
    if len(sys.argv) != 2:
        print("ERROR: Invalid number of arguments. Expected: file_name.vm ")
        exit(1)
    # the VM translator only accepts vm files to be translated into assembly files.
    elif sys.argv[1][-3:] != ".vm":
        print("ERROR: Invalid file type. Expected: vm file")
        exit(1)

    # Get the name of the file to be parsed from the arguments.
    input_file = sys.argv[1]

    # Creates a new parser to parse the file.
    parser = Parser(input_file)
    # Creates the code writer with the input file excluding the .vm part
    code_writer = CodeWriter(input_file[0:-3])

    # Reads the whole file.
    while parser.has_more_commands():
        parser.advance()
        # Gets the command type from the current command.
        command_type = parser.command_type()
        # If the command type is C_ARITHMETIC parses it to get the command and passes it to the code writer to add it to the output file
        if command_type == "C_ARITHMETIC":
            command = parser.arg1()
            code_writer.write_arithmetic(command)
        # If the command type is C_PUSH or C_POP parses it to get the segment and the index and passes it to the code writer to add it to the output file
        elif command_type == "C_PUSH" or command_type == "C_POP":
            segment = parser.arg1()
            index = parser.arg2()
            code_writer.write_push_pop(command_type, segment, index)

    del parser
    code_writer.close()
Beispiel #13
0
                command = p.command_type()
                arg_1 = p.arg_1()
                arg_2 = p.arg_2()
                if command in ['C_PUSH', 'C_POP']:
                    c.write_push_pop(command, arg_1, arg_2)

                if command == 'C_ARITHMETIC':
                    c.write_arithmetic(arg_1)

                if command == 'C_GOTO':
                    c.write_goto(arg_1)

                if command == 'C_IF':
                    c.write_if(arg_1)

                if command == 'C_LABEL':
                    c.write_label(arg_1)

                if command == 'C_FUNCTION':
                    c.write_function(arg_1, arg_2)

                if command == 'C_RETURN':
                    c.write_return()

                if command == 'C_CALL':
                    c.write_call(arg_1, arg_2)

    c.close()


Beispiel #14
0
except IndexError:
    example_usage('improper arguments')

if '.vm' in input:
    if input in os.listdir():
        vm_files = [input]
    else:
        example_usage('file not found')
else:
    if input in os.getcwd():
        vm_files = get_all_VM_files(os.getcwd())
        if len(vm_files) == 0:
            example_usage('no vm files found')
    else:
        try:
            os.chdir(input)
            vm_files = get_all_VM_files(os.getcwd())
            if len(vm_files) == 0:
                example_usage('no vm files in specified directory')
        except FileNotFoundError:
            example_usage('no such directory')

# create a CodeWriter instance
cw = CodeWriter(vm_files, output, boot)

# perform translation
cw.translate()

# close the output of the CodeWriter
cw.close()
Beispiel #15
0
def main(path):
    """Entry point for the vm translator."""
    vm_files_paths = get_vm_files(path)

    if not os.path.exists(path):
        print("invalid file path")
        sys.exit(1)

    if os.path.isdir(path):
        dirname = os.path.dirname(path)
        name = os.path.basename(dirname)
        path = f"{dirname}/{name}"
        isdir = True
    else:
        path = os.path.splitext(path)[0]
        isdir = False

    # Create single code write module
    code_writer = CodeWriter(f"{path}.asm")

    if isdir:
        code_writer.writeInit()

    for vm_file_path in vm_files_paths:
        filestream = open(vm_file_path, "r")
        parser = Parser(filestream)
        filestream.close()

        # write to assembly file
        code_writer.setFileName(os.path.basename(vm_file_path))

        while parser.hasMoreCommands():
            parser.advance()
            command_type = parser.commandType()

            if (command_type == CommandType.C_PUSH or
                    command_type == CommandType.C_POP):
                segment = parser.arg1()
                index = parser.arg2()
                code_writer.writePushPop(
                    command_type,
                    segment,
                    int(index)
                )
            elif command_type == CommandType.C_ARITHMETIC:
                command = parser.arg1()
                code_writer.writeArithmetic(command)
            elif command_type == CommandType.C_LABEL:
                label = parser.arg1()
                code_writer.writeLabel(label)
            elif command_type == CommandType.C_GOTO:
                label = parser.arg1()
                code_writer.writeGoto(label)
            elif command_type == CommandType.C_IF:
                label = parser.arg1()
                code_writer.writeIf(label)
            elif command_type == CommandType.C_FUNCTION:
                label = parser.arg1()
                number_of_locals = int(parser.arg2())
                code_writer.writeFunction(label, number_of_locals)
            elif command_type == CommandType.C_RETURN:
                code_writer.writeReturn()
            elif command_type == CommandType.C_CALL:
                functioname = parser.arg1()
                number_of_args = int(parser.arg2())
                code_writer.writeCall(functioname, number_of_args)

        print(code_writer.filestream.get_global_counter())
    code_writer.close()
Beispiel #16
0
        elif parser.command_type() == 'C_RETURN':
            code_writer.write_return()

        elif parser.command_type() == 'C_CALL':
            function_name = parser.arg1()
            num_args = int(parser.arg2())
            code_writer.write_call(function_name, num_args)


if __name__ == '__main__':
    input_file = sys.argv[1]

    if path.isfile(input_file):
        src_vm_files = [input_file]
        asm_file = path.splitext(input_file)[0] + ".asm"
    else:
        src_vm_files = glob.glob(path.join(sys.argv[1], '*.vm'))
        asm_file = path.split(input_file.rstrip('/') + ".asm")[1]
        asm_file = path.join(input_file, asm_file)

    code_writer = CodeWriter(asm_file)

    if len(src_vm_files) != 1:
        code_writer.write_init()

    for src_vm_file in src_vm_files:
        parse_and_write(code_writer, src_vm_file)

    code_writer.close()