add jmp, jz

This commit is contained in:
krolxon 2026-01-04 19:06:42 +05:30
parent 798ac8ce75
commit 244172960f
2 changed files with 37 additions and 11 deletions

View File

@ -18,7 +18,7 @@ pub struct CPU{
} }
impl CPU { impl CPU {
pub fn inc_cp(&mut self) { pub fn inc_pc(&mut self) {
self.pc += 1; self.pc += 1;
} }
@ -27,8 +27,8 @@ impl CPU {
} }
pub fn mov(&mut self, mem: &mut Memory) { pub fn mov(&mut self, mem: &mut Memory) {
let reg = mem.read(self.pc); self.inc_cp(); let reg = mem.read(self.pc); self.inc_pc();
let val = mem.read(self.pc); self.inc_cp(); let val = mem.read(self.pc); self.inc_pc();
match reg { match reg {
0 => self.a = val, 0 => self.a = val,
@ -132,4 +132,25 @@ impl CPU {
self.carry = borrow; self.carry = borrow;
} }
pub fn jmp(&mut self, mem: &mut Memory) {
let low = mem.read(self.pc) as u16; self.inc_pc();
let high = mem.read(self.pc) as u16; self.inc_pc();
let addrs = (high << 8) | low;
self.pc = addrs;
}
pub fn jz(&mut self, mem: &mut Memory) {
let low = mem.read(self.pc) as u16; self.inc_pc();
let high = mem.read(self.pc) as u16; self.inc_pc();
let addrs = (high << 8) | low;
if self.zero {
self.pc = addrs;
}
}
} }

View File

@ -20,31 +20,36 @@ fn main() {
// b = 2 // b = 2
mem.write(0x0003, Instruction::MOV as u8); mem.write(0x0003, Instruction::MOV as u8);
mem.write(0x0004, 1); mem.write(0x0004, 1);
mem.write(0x0005, 1); mem.write(0x0005, 5);
// a = a + b // a = a + b
mem.write(0x0006, Instruction::SUB as u8); mem.write(0x0006, Instruction::SUB as u8);
mem.write(0x0007, 0); mem.write(0x0007, 0);
mem.write(0x0008, 1); mem.write(0x0008, 1);
// JMP to halt
mem.write(0x0009, Instruction::JZ as u8);
mem.write(0x000a, 0x0f); // Low
mem.write(0x000b, 0x00); // High
// set b = 0 // set b = 0
mem.write(0x0009, Instruction::MOV as u8); mem.write(0x000c, Instruction::MOV as u8);
mem.write(0x000a, 1); mem.write(0x000d, 1);
mem.write(0x000b, 0); mem.write(0x000e, 0);
// halt // halt
mem.write(0x000c, Instruction::HLT as u8); mem.write(0x000f, Instruction::HLT as u8);
while !cpu.halted { while !cpu.halted {
let opcode = mem.read(cpu.pc); let opcode = mem.read(cpu.pc);
cpu.inc_cp(); cpu.inc_pc();
match opcode { match opcode {
x if x == Instruction::MOV as u8 => cpu.mov(&mut mem), x if x == Instruction::MOV as u8 => cpu.mov(&mut mem),
x if x == Instruction::ADD as u8 => cpu.add(&mut mem), x if x == Instruction::ADD as u8 => cpu.add(&mut mem),
x if x == Instruction::SUB as u8 => cpu.sub(&mut mem), x if x == Instruction::SUB as u8 => cpu.sub(&mut mem),
x if x == Instruction::JMP as u8 => {} x if x == Instruction::JMP as u8 => cpu.jmp(&mut mem),
x if x == Instruction::JZ as u8 => {} x if x == Instruction::JZ as u8 => cpu.jz(&mut mem),
x if x == Instruction::HLT as u8 => cpu.halt(), x if x == Instruction::HLT as u8 => cpu.halt(),
_ => panic!("Unknown opcode {:02X}", opcode), _ => panic!("Unknown opcode {:02X}", opcode),
} }