This repository was archived by the owner on Nov 10, 2024. It is now read-only.
forked from bloominstituteoftechnology/Computer-Architecture
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpu.py
103 lines (80 loc) · 2.64 KB
/
cpu.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
"""CPU functionality."""
import sys
class CPU:
"""Main CPU class."""
def __init__(self):
"""Construct a new CPU."""
self.ram = [0] * 256
self.reg = [0] * 8
self.pc = 0
def load(self, file=""):
"""Load a program into memory."""
address = 0
# If no file given, just hardcode a program:
if file == "":
program = [
# From print8.ls8
0b10000010, # LDI R0,8
0b00000000,
0b00001000,
0b01000111, # PRN R0
0b00000000,
0b00000001, # HLT
]
# If file given, load file
else:
program = []
f = open(file, "r")
for line in f:
if line[0] != "#":
program.append(int(line[:8], 2))
for instruction in program:
self.ram[address] = instruction
address += 1
def alu(self, op, reg_a, reg_b):
"""ALU operations."""
if op == "ADD":
self.reg[reg_a] += self.reg[reg_b]
#elif op == "SUB": etc
else:
raise Exception("Unsupported ALU operation")
def ram_read(self, address):
return self.ram[address]
def ram_write(self, address, value):
self.reg[address] = value
def trace(self):
"""
Handy function to print out the CPU state. You might want to call this
from run() if you need help debugging.
"""
print(f"TRACE: %02X | %02X %02X %02X |" % (
self.pc,
#self.fl,
#self.ie,
self.ram_read(self.pc),
self.ram_read(self.pc + 1),
self.ram_read(self.pc + 2)
), end='')
for i in range(8):
print(" %02X" % self.reg[i], end='')
print()
def run(self):
"""Run the CPU."""
running = True
HLT = 0b00000001
LDI = 0b10000010
MUL = 0b10100010
PRN = 0b01000111
while running:
if self.ram_read(self.pc) == LDI:
self.ram_write(self.ram_read(self.pc + 1), self.ram_read(self.pc + 2))
self.pc += 3
elif self.ram_read(self.pc) == MUL:
self.trace()
self.ram_write(self.ram_read(self.pc + 1), (self.reg[self.ram_read(self.pc + 1)] * self.reg[self.ram_read(self.pc + 2)]))
self.pc += 3
elif self.ram_read(self.pc) == PRN:
print(self.reg[self.ram_read(self.pc + 1)])
self.pc += 2
elif self.ram_read(self.pc) == HLT:
running = False