User:Ashmanskas/p364/sasm.py

From LaPET electronics

Jump to: navigation, search

sasm.py

#
# sasm.py
# coded 2010-11-11 by Bill Ashmanskas, ashmansk@hep.upenn.edu
# simple assembler for instruction set of simple_cpu.v
#

import sys, string

def main():
    ptext = []
    addr = 0x00
    labeladdr = {}
    for l in open(sys.argv[1]):
        l = l.strip()
        if "#" in l: l = l.split("#")[0]
        w = l.strip().split()
        if len(w)==0: continue
        if w[0][-1]==":":
            label = w[0][:-1]
            labeladdr[label] = addr
            p = w[1:]
        else:
            p = w[:]
        if len(p)>0:
            p = ["%02x"%(addr)]+p
            ptext.append(p)
            addr += 1
    addrlabel = dict([(labeladdr[k],k) for k in labeladdr])
    nulllabel = " "*(2+max([len(k) for k in labeladdr]))
    for p in ptext:
        addr = int(p[0],16)
        mnemonic = p[1].lower()
        if len(p)>2:
            argument = p[2]
        else:
            argument = "0"
        if argument in labeladdr: 
            harg = labeladdr[argument]
        else:
            harg = int(argument,16)
        hbyte = harg & 0xff
        instrs = "load store jump jumpz jumpn add sub mul out".split()
        if mnemonic==".data":
            instr = harg
        elif mnemonic in instrs:
            instr = instrs.index(mnemonic)*0x0100 + hbyte
        else:
            raise ValueError, "unknown mnemonic "+mnemonic
        label = nulllabel
        if addr in addrlabel:
            label = addrlabel[addr]+": "+nulllabel
            label = label[:len(nulllabel)]
        print "        mem['h%02x] = 'h%04x;  //  %s %-5s"%( \
            addr, instr, label, p[1]), \
            " ".join(p[2:])

if __name__=="__main__":
    main()
Personal tools