예제 #1
0
    def runSingleFile(self, isWrite=True):
        parser = VMParser(self.content)
        codeWriter = VMCodeWriter(self.className)
        asmCmds = self.asmCmds
        while(parser.hasMoreCommands()):
            parser.advance()
            commandType = parser.commandType()

            if commandType in ['C_PUSH','C_POP']: 
                segment,index = parser.arg1(),parser.arg2()
                asmCmds += codeWriter.writePushPop(commandType, segment, index)

            elif commandType == 'C_ARITHMETIC':
                cmd = parser.arg1()
                asmCmds += codeWriter.writeArithmetic(cmd)

            elif commandType == 'C_LABEL':
                cmd = parser.arg1()
                asmCmds += codeWriter.writeLabel(cmd)

            elif commandType == 'C_GOTO':
                cmd = parser.arg1()
                asmCmds += codeWriter.writeGoto(cmd)

            elif commandType == 'C_IF':
                cmd = parser.arg1()
                asmCmds += codeWriter.writeIf(cmd)

            elif commandType == 'C_FUNCTION':
                functionName,numVars = parser.arg1(),parser.arg2()
                asmCmds += codeWriter.writeFunction(functionName, numVars)

            elif commandType == 'C_CALL':
                functionName,numArgs = parser.arg1(),parser.arg2()
                asmCmds += codeWriter.writeCall(functionName, numArgs)

            elif commandType == 'C_RETURN':
                asmCmds += codeWriter.writeReturn()
            
        if isWrite:
            with open(self.outputPath, 'w') as f:
                f.write(''.join(asmCmds))
예제 #2
0
def main():
    readPaths: List[Path]
    writePath: Path
    inputPath = Path(sys.argv[1])

    if inputPath.is_dir():
        readPaths = [p for p in inputPath.iterdir() if p.suffix == ".vm"]
        writePath = (inputPath / inputPath.stem).with_suffix(".asm")
    else:
        assert inputPath.suffix == ".vm", "Invalid input file: must have .vm extension"
        readPaths = [inputPath]
        writePath = inputPath.with_suffix(".asm")

    with open(writePath, "w+") as writeFile:
        writer = VMCodeWriter(writeFile)
        writer.writeInit()
        for p in readPaths:
            parser = VMParser(p, writer)  # sets up the VMParser
            while parser.hasMoreCommands():
                parser.writeNextCommand()
예제 #3
0
 def __init__(self):
     self.parser = VMParser()
     self.coder = CodeWriter()
     self.myPath = Path(sys.argv[1])
     self.initParameters()