def ldi(cond, flag, Rd: str, Rn: str, op2) -> int: k = getConst(Rn) dest = mapRegister(Rd) if dest < 16: throwError(6, True, (Rd, "r16-r31")) opcode = 0xE000 kh = (k & 0xF0) << 4 kl = k & 0xF dest = (dest - 16) << 4 return opcode + kh + dest + kl
def getConst(c: str, bit_length=8, lower=0, upper=0) -> int: if upper == 0: upper = (2**bit_length - 1) try: int(c.replace("#", "")) except (ValueError) as e: throwError(6, True, c.replace("#", "")) c = int(c.replace("#", "")) if c < lower or c > upper: throwError(7, True, ("#{}".format(c), bit_length, c.bit_length())) return c
def adiw(cond, flag, Rd: str, Rn, op2) -> int: Rd_input = Rd Rd: int = _parse16BitReg(Rd) if Rd > 4 or Rd < 0: throwError(3, True, (Rd_input, 2, "Bit", Rd.bit_length(), "Bit")) if int(Rn) < 0 or int(Rn) > 0x40: throwError(3, True, (Rd_input, 6, "Bit", int(Rn).bit_length(), "Bit")) Rn = int(Rn) # 1001 0110 KKdd KKKK opcode = (0x96 << 8) # 38400 dd = (Rd << 4) # 16 KK = ((Rn >> 4) << 6) # 192 KKKK = (Rn & 0xF) # 12 return opcode + KK + dd + KKKK
def main(): if len(sys.argv) < 2: throwError(1, False) filePath: str = sys.argv[1] lines: List[int] = [] for nLine, line in sourceCodeGenerator(filePath): LineRev.setLine(nLine, line) lines.append(compileOp(parseLine(line))) printAsHex(lines) outputFileName = filePath if outputFileName.find(".") != -1: outputFileName = outputFileName[0:outputFileName.find(".")] + ".out" asBin(lines, outputFileName)
def sourceCodeGenerator(file: str) -> Iterator[Tuple[int, str]]: lines: List[str] = [] try: with open(file) as fd: lines = fd.readlines() except(OSError, IOError) as e: throwError(2, False, (file, e)) nLine = 0 for line in lines: nLine += 1 # filter for comments if line.find("//") != -1: line = line[0:line.find("//")] if line.replace("\n", "").replace(" ", "") == "": continue yield (nLine, line.strip())
def mapRegister(r: str) -> int: if r in registerMap: return registerMap[r] else: throwError(5, True, r)
def instructionMapping(op: str) -> Callable[[str, str, str, str, str], int]: if op not in instructions: throwError(4, True, op) return instructions[op]