Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. def get_ops():
  2.     """ Builds an opcode name <-> value dictionary """
  3.     li = ["EOF","ADD","SUB","MUL","DIV","POW","BITAND","BITOR","CMP","GET", \
  4.           "SET","NUMBER","STRING","GGET","GSET","MOVE","DEF","PASS",  \
  5.           "JUMP","CALL","RETURN","IF","DEBUG","EQ","LE","LT","DICT",  \
  6.           "LIST","NONE","LEN","LINE","PARAMS","IGET","FILE","NAME",   \
  7.           "NE","HAS","RAISE","SETJMP","MOD","LSH","RSH","ITER","DEL", \
  8.           "REGS","BITXOR", "IFN", "NOT", "BITNOT"]
  9.     dic = {}
  10.     for i in li:
  11.         dic[i] = li.index(i)
  12.     return dic
  13.  
  14. def prepare(x):
  15.     """ Prepares the line for processing by breaking it into tokens,
  16.        removing empty tokens and stripping whitespace """
  17.     try:
  18.         ind = x.index('"')
  19.     except:
  20.         ind = -1
  21.     if ind != -1:
  22.         d = x[ind:]
  23.         x = x[:ind]
  24.     x = x.split(' ')
  25.     tmp = []
  26.     final = []
  27.     for i in x:
  28.         if i:
  29.             if i[0] != ':':
  30.                 tmp.append(i)
  31.     for i in tmp[:4]:
  32.         final.append(i)
  33.     if not d:
  34.         d = "".join(tmp[4:])
  35.     final.append(d.strip())
  36.     return final
  37.  
  38. def dequote(x):
  39.     """ Removes outermost quotes from a string, if they exist """    
  40.     if x[0] == '"' and x[len(x)-1] == '"':
  41.         return x[1:len(x)-1]
  42.     return x
  43.  
  44. def assemble(asmc):    
  45.     asmc = asmc.strip()
  46.     asmc = asmc.split('\n')
  47.     bc = []
  48.     ops = get_ops()
  49.     for line in asmc:
  50.         current = prepare(line)
  51.         i,a,b,c,d = current
  52.         a = int(a)
  53.         b = int(b)
  54.         c = int(c)
  55.         bc.append(chr(ops[i]))
  56.         bc.append(chr(a))
  57.         bc.append(chr(b))
  58.         bc.append(chr(c))
  59.         if i == "LINE":
  60.             n = a * 4
  61.             d = dequote(d)
  62.             text = d
  63.             text += chr(0) * (n - len(d))
  64.             bc.append(text)
  65.         if i == "STRING":
  66.             d = dequote(d)
  67.             text = d + "\0"*(4-len(d)%4)
  68.             bc.append(text)
  69.         elif i == "NUMBER":
  70.             d = int(d)
  71.             bc.append(fpack(d))
  72.     bc = "".join(bc)
  73.     return bc
  74.    
  75. if __name__ == '__main__':
  76.     asmc = load(ARGV[1])
  77.     bc = assemble(asmc)
  78.     save(ARGV[2], bc)
  79.