From e77e125f967f5847f7420fae8899bfefa9d3d86e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Autin?= Date: Sat, 25 Mar 2023 15:57:28 +0100 Subject: [PATCH] :recycle: Error management and simplification Modified methods - load_instruction - store_instruction --- src/simulator/machine.rs | 38 +++++++++++++++----------------------- 1 file changed, 15 insertions(+), 23 deletions(-) diff --git a/src/simulator/machine.rs b/src/simulator/machine.rs index a43b06c..5ba058b 100644 --- a/src/simulator/machine.rs +++ b/src/simulator/machine.rs @@ -340,47 +340,39 @@ impl Machine { /// Executes RISC-V Load Instructions on the machine fn load_instruction(&mut self, inst: Instruction) -> Result<(), MachineError> { + let mut set_reg = |rd, size| { + let val = self.read_memory(size, (self.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64; + self.int_reg.set_reg(rd, val); + Ok(()) + }; + match inst.funct3 { - RISCV_LD_LB | RISCV_LD_LBU => { - let tmp = self.read_memory(1, (self.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64; - self.int_reg.set_reg(inst.rd, tmp); - }, - RISCV_LD_LH | RISCV_LD_LHU => { - let tmp = self.read_memory(2, (self.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64; - self.int_reg.set_reg(inst.rd, tmp); - }, - RISCV_LD_LW | RISCV_LD_LWU => { - let tmp = self.read_memory(4, (self.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64; - self.int_reg.set_reg(inst.rd, tmp); - }, - RISCV_LD_LD => { - let tmp = self.read_memory(8, (self.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64; - self.int_reg.set_reg(inst.rd, tmp); - }, - _ => panic!("In LD switch case, this should never happen... Instr was {}", inst.value) + RISCV_LD_LB | RISCV_LD_LBU => set_reg(inst.rd, 1), + RISCV_LD_LH | RISCV_LD_LHU => set_reg(inst.rd, 2), + RISCV_LD_LW | RISCV_LD_LWU => set_reg(inst.rd, 4), + RISCV_LD_LD => set_reg(inst.rd, 8), + _ => Err(MachineError::new(format!("In LD switch case, this should never happen... Instr was {}", inst.value).as_str())) } - Ok(()) } /// Executes RISC-V Store Instructions on the machine fn store_instruction(&mut self, inst: Instruction) -> Result<(), MachineError> { - - let mut store = |size| + let mut store = |size| { self.write_memory( size, (self.int_reg.get_reg(inst.rs1) + inst.imm12_S_signed as i64) as usize, self.int_reg.get_reg(inst.rs2) as u64 ); + Ok(()) + }; match inst.funct3 { RISCV_ST_STB => store(1), RISCV_ST_STH => store(2), RISCV_ST_STW => store(4), RISCV_ST_STD => store(8), - _ => panic!("In ST switch case, this should never happen... Instr was {}", inst.value) + _ => Err(MachineError::new(format!("In ST switch case, this should never happen... Instr was {}", inst.value).as_str())) } - - Ok(()) } /// Executes RISC-V Integer Register-Immediate Instructions on the machine