Processor conceived
You might remember I was playing around with a Forth implementation. But of course, I first need an underlying machine. Here is a minimal scaffolding.
The memory
We have an undefined amount of memory. Each memory cell is of arbitrary size. The memory can be saved. At a later point in time we can add profiling information (#memory accesses)
class Memory:
def __init__(self, mem = {}):
# We hold the memory content in a dictionary
self.mem = mem
print(f"{len(self.mem)} memory cells initialized")
def peek(self, adr):
if adr in self.mem:
return self.mem[adr]
else:
print(f"Read from undefined memory at address {adr}")
return 'X'
def poke(self, adr, val):
self.mem[adr] = val
The processor
The machine consists of eight registers, some of them have a special purpose.
- R[0] is the program counter (PC)
- R[1] is the stack pointer (SP)
PC = 0
SP = 1
The processor only supports a few opcodes.
- NOP do nothing (besides incrementing program counter)
- HALT stop the machine
- PYTHON call the python function in the following cell
NOP = 0
HALT = 1
PYTHON = 2
class VirtualMachine:
def setHALT(self):
self.HALT = True
def callPython(self):
pycode = self.mem.peek(self.R[PC] + 1)
self.R[PC] = self.R[PC] + 1
pycode()
def __init__(self, mem = {}):
self.HALT = False
self.R = [0,0,0,0,0,0,0,0]
self.mem = Memory(mem)
self.opcode = {}
self.opcode[NOP] = lambda: None
self.opcode[HALT] = self.setHALT
self.opcode[PYTHON] = self.callPython
def step(self):
op = self.mem.peek(self.R[PC]) # FETCH
if op in self.opcode:
self.opcode[op]() # EXECUTE
self.R[PC] = self.R[PC] + 1
else:
print(str(op) + ' - unknown opcode')
self.HALT = True
def run(self, pc = 0):
self.R[PC] = pc
self.HALT = False
while not self.HALT:
self.step()
Example run
Try all available commands.
def say_hi():
print("Hi!")
mem = {}
mem[0] = PYTHON
mem[1] = say_hi
mem[2] = NOP
mem[3] = HALT
vm = VirtualMachine(mem)
vm.run()