+/TECS
git clone https://git.julia.blue/+/TECS
91f6f51
master
1# VM to ASM translator by Joseph Ryan 2import sys 3import os 4from codeparser import CodeParser 5from codewriter import CodeWriter 6 7if len (sys .argv )> 1 : 8files = [] 9fName = sys .argv [- 1 ].replace ('\\' ,'/' ) 10tempName = fName .split ('.' )[0 ] 11if fName .endswith (".vm" ): 12files .append (fName ) 13fName = tempName 14else : 15for i in os .listdir (fName ): 16if i .endswith (".vm" ): 17files .append (fName + '/' + i ) 18fName = tempName + '/' + tempName .split ('/' )[- 1 ] 19if "-m" not in sys .argv : 20"Parsing " + str (len (files ))+ " file(s)" 21cw = CodeWriter (fName ) 22if "-b" not in sys .argv : 23cw .writeInit () 24for f in files : 25p = CodeParser (f ) 26cw .setFile (f ) 27if "-m" not in sys .argv : 28"Translating " + f .split ('/' )[- 1 ] 29while p .hasMoreCommands (): 30c = p .commandType () 31if "-c" in sys .argv : 32cw .f .write ("\n//\t\t\t\t" + p .lines [p .currentLine ]+ '\n' ) 33if c == "C_ARITHMETIC" : 34cw .writeArithmetic (p .arg1 ()) 35elif c in {"C_PUSH" ,"C_POP" }: 36cw .writePushPop (c ,p .arg1 (),p .arg2 ()) 37elif c == "C_LABEL" : 38cw .writeLabel (p .arg1 ()) 39elif c == "C_GOTO" : 40cw .writeGoto (p .arg1 ()) 41elif c == "C_IF" : 42cw .writeIf (p .arg1 ()) 43elif c == "C_FUNCTION" : 44cw .writeFunction (p .arg1 (),p .arg2 ()) 45elif c == "C_CALL" : 46cw .writeCall (p .arg1 (),p .arg2 ()) 47elif c == "C_RETURN" : 48cw .writeReturn () 49p .advance () 50cw .close () 51if "-l" in sys .argv : 52lineNum = 0 53with open (fName + ".asm" ,'r' )as src : 54with open (fName + ".debug" ,'w' )as dest : 55for line in src : 56if not line .startswith ('(' )and not line .startswith ('//' )and not line == '\n' : 57dest .write (str (lineNum )+ '\t\t' ) 58lineNum += 1 59dest .write (line ) 60if "-m" not in sys .argv : 61"Translation Complete" 62else : 63"usage: vmtranslator.py [options] source[.vm]\n\tsourceFile(s) may be file or directory.\noptions:\n\t-m mutes status messages\n\t-c writes vm commands as comments in .asm file\n\t-b doesn't generate bootstrap code\n\t-l creates source.debug with adjusted line numbers"