Krolyxon
Commit 2441729

Branches

Tags

Refs →

bench512441729

add jmp, jz

Author
krolxon
Date
2026-01-04 19:06 +0530
Parent
798ac8c
Commit
244172960fff86e147a8e20cf19773026cbed96f

+37 −11

2 files changed

  1. M src/cpu.rs +24 −3
  2. M src/main.rs +13 −8
M src/cpu.rs View
@@ -18,7 +18,7 @@ pub struct CPU{
1818 }
1919
2020 impl CPU {
21− pub fn inc_cp(&mut self) {
21+ pub fn inc_pc(&mut self) {
2222 self.pc += 1;
2323 }
2424
@@ -27,8 +27,8 @@ impl CPU {
2727 }
2828
2929 pub fn mov(&mut self, mem: &mut Memory) {
30− let reg = mem.read(self.pc); self.inc_cp();
31− let val = mem.read(self.pc); self.inc_cp();
30+ let reg = mem.read(self.pc); self.inc_pc();
31+ let val = mem.read(self.pc); self.inc_pc();
3232
3333 match reg {
3434 0 => self.a = val,
@@ -132,4 +132,25 @@ impl CPU {
132132 self.carry = borrow;
133133 }
134134
135+ pub fn jmp(&mut self, mem: &mut Memory) {
136+ let low = mem.read(self.pc) as u16; self.inc_pc();
137+ let high = mem.read(self.pc) as u16; self.inc_pc();
138+
139+ let addrs = (high << 8) | low;
140+
141+ self.pc = addrs;
142+ }
143+
144+ pub fn jz(&mut self, mem: &mut Memory) {
145+ let low = mem.read(self.pc) as u16; self.inc_pc();
146+ let high = mem.read(self.pc) as u16; self.inc_pc();
147+
148+ let addrs = (high << 8) | low;
149+
150+ if self.zero {
151+ self.pc = addrs;
152+ }
153+
154+ }
155+
135156 }
M src/main.rs View
@@ -20,31 +20,36 @@ fn main() {
2020 // b = 2
2121 mem.write(0x0003, Instruction::MOV as u8);
2222 mem.write(0x0004, 1);
23− mem.write(0x0005, 1);
23+ mem.write(0x0005, 5);
2424
2525 // a = a + b
2626 mem.write(0x0006, Instruction::SUB as u8);
2727 mem.write(0x0007, 0);
2828 mem.write(0x0008, 1);
2929
30+ // JMP to halt
31+ mem.write(0x0009, Instruction::JZ as u8);
32+ mem.write(0x000a, 0x0f); // Low
33+ mem.write(0x000b, 0x00); // High
34+
3035 // set b = 0
31− mem.write(0x0009, Instruction::MOV as u8);
32− mem.write(0x000a, 1);
33− mem.write(0x000b, 0);
36+ mem.write(0x000c, Instruction::MOV as u8);
37+ mem.write(0x000d, 1);
38+ mem.write(0x000e, 0);
3439
3540 // halt
36− mem.write(0x000c, Instruction::HLT as u8);
41+ mem.write(0x000f, Instruction::HLT as u8);
3742
3843 while !cpu.halted {
3944 let opcode = mem.read(cpu.pc);
40− cpu.inc_cp();
45+ cpu.inc_pc();
4146
4247 match opcode {
4348 x if x == Instruction::MOV as u8 => cpu.mov(&mut mem),
4449 x if x == Instruction::ADD as u8 => cpu.add(&mut mem),
4550 x if x == Instruction::SUB as u8 => cpu.sub(&mut mem),
46− x if x == Instruction::JMP as u8 => {}
47− x if x == Instruction::JZ as u8 => {}
51+ x if x == Instruction::JMP as u8 => cpu.jmp(&mut mem),
52+ x if x == Instruction::JZ as u8 => cpu.jz(&mut mem),
4853 x if x == Instruction::HLT as u8 => cpu.halt(),
4954 _ => panic!("Unknown opcode {:02X}", opcode),
5055 }