Skip to content

Instantly share code, notes, and snippets.

@danilomo
Created August 31, 2018 12:14
Show Gist options
  • Save danilomo/d2bd752ffebc04ff1a32b71d51d10d96 to your computer and use it in GitHub Desktop.
Save danilomo/d2bd752ffebc04ff1a32b71d51d10d96 to your computer and use it in GitHub Desktop.
instruction_set = {}
import string
def command( func ):
def exec_(regbank, op, val = None ):
if(val):
pc = func(regbank, op, val)
else:
pc = func(regbank, op)
if(not pc):
next_pc = regbank["___PC___"] + 1
else:
next_pc = pc
return next_pc
instruction_set[func.__name__] = exec_
@command
def mov(regbank, op, val):
try:
value = int(val)
except:
value = regbank[val]
regbank[op] = value
@command
def inc(regbank, op ):
regbank[op] += 1
@command
def dec(regbank, op ):
regbank[op] += -1
@command
def jnz(regbank, op, val):
try:
value = int(op)
except:
value = regbank[op]
if(value):
next_pc = regbank["___PC___"] + int(val)
return next_pc
def parse_instruction( str_ , regbank ):
parsed = str_.split()
if(len(parsed) == 2):
parsed.append(None)
inst, op, val = tuple(parsed)
instruction = instruction_set[inst]
def parsed_instruction():
return instruction( regbank, op, val )
return parsed_instruction
def parse_instructions(program, regbank):
return [ parse_instruction(element, regbank) for element in program ]
def simple_assembler(program):
regbank = {"___PC___": 0}
instruction_list = parse_instructions( program, regbank )
pc = 0
while( pc < len(instruction_list) ):
pc = instruction_list[pc]()
regbank["___PC___"] = pc
del regbank["___PC___"]
return regbank
code = '''\
mov a 5
inc a
dec a
dec a
jnz a -1
inc a'''
print(simple_assembler(code.splitlines()))
code = '''\
mov c 12
mov b 0
mov a 200
dec a
inc b
jnz a -2
dec c
mov a b
jnz c -5
jnz 0 1
mov c a'''
print(simple_assembler(code.splitlines()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment