Created
May 1, 2012 06:59
-
-
Save WideWord/2565790 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from sys import argv | |
import struct | |
prefix = "0000"; | |
def addrb(x): | |
return { | |
"a" : "000", | |
"b" : "001", | |
"c" : "010", | |
"d" : "011", | |
"e" : "100", | |
"f" : "101", | |
"m" : "110", | |
"pc": "111" | |
}[x] | |
def opcodeb(x): | |
return { | |
"set":"00001", | |
"add":"00011", | |
"sub":"00101", | |
"mul":"00111", | |
"div":"01001", | |
"and":"01011", | |
"or" :"01101", | |
"ife":"01111", | |
"ifn":"10001", | |
"inv":"00100", | |
"const":"00010", | |
}[x] | |
def convnum (num): | |
return ('%04X' % int(num)) | |
def convdat (data): | |
return convnum(data) | |
def assemble (inp, out): | |
labels = {} | |
lines = inp.readlines() | |
offset = 0 | |
for s in lines: | |
if len(s.split()) == 0: | |
continue | |
cmd = s.split(";")[0].split() | |
opcode = [0]; | |
if opcode[0] == ":": | |
labels[cmd[1]] = offset | |
continue | |
if opcode == "const": | |
offset += 2 | |
continue | |
if opcode == "dat": | |
offset += len(convdat(s.split(";")[0][4:])) / 5 | |
for s in lines: | |
if len(s.split()) == 0: | |
continue | |
cmd = s.split(";")[0].split() | |
opcode = cmd[0]; | |
flag = "0" | |
if opcode[-1] == "f": | |
flag = "1" | |
opcode = opcode[:len(opcode)-1] | |
if opcode in "set,add,sub,mul,div,and,or,ife,ifn".split(","): | |
out.write('%04X' % int(prefix + flag + addrb(cmd[1]) + addrb(cmd[2]) + opcodeb(opcode),2) + " ") | |
continue | |
if opcode == "const": | |
if cmd[2][0] == "@": | |
out.write('%04X' % int(prefix + flag + addrb(cmd[1]) + "000" + opcodeb(opcode),2) + " " + ('%04X' % labels[cmd[2]]) + " ") | |
else: | |
out.write('%04X' % int(prefix + flag + addrb(cmd[1]) + "000" + opcodeb(opcode),2) + " " + convnum(cmd[2]) + " ") | |
continue | |
if opcode == "dat": | |
out.write(convdat(s.split(";")[0][4:]) + " ") | |
continue | |
if opcode == "inv": | |
out.write('%04X' % int(prefix + flag + "000000" + opcodeb(opcode),2)) | |
continue | |
print "<<" + s + ">> error, opcode:'" + opcode + "'" + " opcode[-1]:'" + opcode[-1] + "'" + " flag:'" + flag + "'" | |
for path in argv[1:]: | |
try: | |
fd_inp = file(path, "r") | |
path_out = ".".join(path.split(".")[:-1]) + ".out" | |
fd_out = file(path_out, "w") | |
fd_out.write("v2.0 raw\n\r") | |
assemble(fd_inp, fd_out) | |
except IOError: | |
print "File not found" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment