#!/usr/bin/env python """ assembler.py: rather primitive two-pass assembler. Get the labels, then assemble the instructions. """ import re import sys import optparse symbols = {} instructions = [] relocations = [] class AssemblerError(Exception): pass class AssemblerSyntaxError(AssemblerError): def __init__(self,line,reason): self.line = line self.reason = reason def __str__(self): return "Syntax error on line %d: %s" % (self.line,self.reason) class AssemblerRangeError(AssemblerError): def __init__(self,line,reason): self.line = line self.reason = reason def __str__(self): return "Range error on line %d: %s" % (self.line,self.reason) labelre = re.compile(r"""^(?P.*:)?(?P[^:]*)$""") commentre = re.compile(r"""^(?P[^#]*)(?P#.*)?$""") alnumunderre = re.compile(r"""^\w+$""") rtype_re = re.compile(r'''^(?P(or|and|add|sub|slt|sltu|addu|subu))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))$''') new_re = re.compile(r'''^(?P(bitpal|lfsr))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))$''') shift_re = re.compile(r'''^(?P(sll|srl|sra))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))\s+(?P-?(0x)?[0-9a-fA-F]+)$''') immed_re = re.compile(r'''^(?P(ori|addiu|andi))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|sp|fp|ra))\s+(?P-?(0x)?[0-9a-fA-F]+)$''') lui_re = re.compile(r'''^(?Plui)\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))\s+(?P-?(0x)?[0-9a-fA-F]+)$''') mem_re = re.compile(r'''^(?P(lw|sw|lb|lbu|sb))\s+(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))\s+(?P-?(0x)?[0-9a-fA-F]+)\s*\(\s*(?P\$(0|zero|at|v[0,1]|a[0-3]|t[0-9]|s[0-7]|k[0-1]|gp|fp|sp|ra))\s*\)$''') j_re = re.compile(r'''^(?P(j|jal))\s+(?P