]> Witch of Git - jade-mouse/blob - toolchain/src/cpu.rs
Minor ISA changes
[jade-mouse] / toolchain / src / cpu.rs
1 use crate::inst::{Inst, Reg};
2 use std::ops::{Index, IndexMut};
3
4 #[cfg(test)]
5 mod test;
6
7 struct RegFile {
8 values: [u8; 4],
9 }
10
11 pub struct Cpu {
12 init: bool,
13 pc: u16,
14 reg: RegFile,
15 memory: Vec<u8>,
16 }
17
18 impl Cpu {
19 pub fn new() -> Self {
20 Cpu {
21 init: false,
22 pc: 0,
23 reg: RegFile { values: [0; 4] },
24 memory: vec![0; 1 << 16],
25 }
26 }
27
28 pub fn reg(&self, reg: Reg) -> u8 {
29 self.reg[reg]
30 }
31
32 pub fn mem(&self) -> &[u8] {
33 &self.memory[..]
34 }
35
36 pub fn mem_mut(&mut self) -> &mut [u8] {
37 &mut self.memory[..]
38 }
39
40 pub fn run_inst(&mut self, inst: &Inst) {
41 match *inst {
42 Inst::Move(dst, src) => self.reg[dst] = self.reg[src],
43 _ => todo!(),
44 }
45 }
46 }
47
48 impl Index<Reg> for RegFile {
49 type Output = u8;
50 fn index(&self, index: Reg) -> &u8 {
51 match index {
52 Reg::R0 => &self.values[0],
53 Reg::R1 => &self.values[1],
54 Reg::R2 => &self.values[2],
55 Reg::R3 => &self.values[3],
56 }
57 }
58 }
59
60 impl IndexMut<Reg> for RegFile {
61 fn index_mut(&mut self, index: Reg) -> &mut u8 {
62 match index {
63 Reg::R0 => &mut self.values[0],
64 Reg::R1 => &mut self.values[1],
65 Reg::R2 => &mut self.values[2],
66 Reg::R3 => &mut self.values[3],
67 }
68 }
69 }
70
71 impl std::fmt::Debug for RegFile {
72 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
73 fmt.debug_struct("RegFile")
74 .field("r0", &self[Reg::R0])
75 .field("r1", &self[Reg::R1])
76 .field("r2", &self[Reg::R2])
77 .field("r3", &self[Reg::R3])
78 .finish()
79 }
80 }
81
82 impl std::fmt::Debug for Cpu {
83 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
84 fmt.debug_struct("Cpu")
85 .field("init", &self.init)
86 .field("pc", &self.pc)
87 .field("reg", &self.reg)
88 .field("mem", &format_args!("[...]"))
89 .finish()
90 }
91 }