From 0bb5ae95b90ebc1275e0a3ff2038d191846cc463 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 14 Aug 2025 02:01:39 +0800 Subject: [PATCH] convert repl to use error-type returns The main benefit of this is we don't have to remember to call the "abort" function post-amble in case of an error: you can just return an error type. I took a pass at trying to convert all the argument parsing using "idiomatic" rust. In some cases, it's nice. But in some cases it's pretty clunky and hard to follow. I think the clunkiness is outweighed by never having to forget to call the abort function, and one can avoid the whole... map_err().and_then() madness by just using more traditional if/else with returns. I think that's a fine choice to make. --- baremetal/src/repl.rs | 356 ++++++++++++++++++++---------------------- 1 file changed, 168 insertions(+), 188 deletions(-) diff --git a/baremetal/src/repl.rs b/baremetal/src/repl.rs index 879846448..02ad626de 100644 --- a/baremetal/src/repl.rs +++ b/baremetal/src/repl.rs @@ -1,3 +1,4 @@ +#[allow(unused_imports)] use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; @@ -7,6 +8,15 @@ use utralib::*; #[cfg(any(feature = "artybio", feature = "nto-bio"))] use xous_bio_bdma::*; +pub struct Error { + pub message: Option<&'static str>, +} +impl Error { + pub fn none() -> Self { Self { message: None } } + + pub fn help(message: &'static str) -> Self { Self { message: Some(message) } } +} + pub struct Repl { cmdline: String, do_cmd: bool, @@ -41,9 +51,9 @@ impl Repl { } } - pub fn process(&mut self) { + pub fn process(&mut self) -> Result<(), Error> { if !self.do_cmd { - return; + return Err(Error::none()); } // crate::println!("got {}", self.cmdline); @@ -88,100 +98,91 @@ impl Repl { } "peek" => { if args.len() == 1 || args.len() == 2 { - if let Ok(addr) = usize::from_str_radix(&args[0], 16) { - let count = if args.len() == 2 { - if let Ok(count) = u32::from_str_radix(&args[1], 10) { count } else { 1 } - } else { - 1 - }; - // safety: it's not safe to do this, the user peeks at their own risk - let peek = unsafe { core::slice::from_raw_parts(addr as *const u32, count as usize) }; - for (i, &d) in peek.iter().enumerate() { - if (i % COLUMNS) == 0 { - crate::print!("\n\r{:08x}: ", addr + i * size_of::()); - } - crate::print!("{:08x} ", d); - } - crate::println!(""); + let addr = usize::from_str_radix(&args[0], 16) + .map_err(|_| Error::help("Peek address is in hex"))?; + + let count = if args.len() == 2 { + if let Ok(count) = u32::from_str_radix(&args[1], 10) { count } else { 1 } } else { - crate::println!("Peek address is in hex"); + 1 + }; + // safety: it's not safe to do this, the user peeks at their own risk + let peek = unsafe { core::slice::from_raw_parts(addr as *const u32, count as usize) }; + for (i, &d) in peek.iter().enumerate() { + if (i % COLUMNS) == 0 { + crate::print!("\n\r{:08x}: ", addr + i * size_of::()); + } + crate::print!("{:08x} ", d); } + crate::println!(""); } else { - crate::println!("Help: peek [count], addr is in hex, count in decimal"); + return Err(Error::help("Help: peek [count], addr is in hex, count in decimal")); } } "poke" => { if args.len() == 2 || args.len() == 3 { - if let Ok(addr) = u32::from_str_radix(&args[0], 16) { - if let Ok(value) = u32::from_str_radix(&args[1], 16) { - let count = if args.len() == 3 { - if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } else { 1 } - } else { - 1 - }; - // safety: it's not safe to do this, the user pokes at their own risk - let poke = - unsafe { core::slice::from_raw_parts_mut(addr as *mut u32, count as usize) }; - for d in poke.iter_mut() { - *d = value; - } - crate::println!("Poked {:x} into {:x}, {} times", value, addr, count); - } else { - crate::println!("Poke value is in hex"); - } + let addr = u32::from_str_radix(&args[0], 16) + .map_err(|_| Error::help("Poke address is in hex"))?; + + let value = + u32::from_str_radix(&args[1], 16).map_err(|_| Error::help("Poke value is in hex"))?; + let count = if args.len() == 3 { + if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } else { 1 } } else { - crate::println!("Poke address is in hex"); + 1 + }; + // safety: it's not safe to do this, the user pokes at their own risk + let poke = unsafe { core::slice::from_raw_parts_mut(addr as *mut u32, count as usize) }; + for d in poke.iter_mut() { + *d = value; } + crate::println!("Poked {:x} into {:x}, {} times", value, addr, count); } else { - crate::println!( - "Help: poke [count], addr/value is in hex, count in decimal" - ); + return Err(Error::help( + "Help: poke [count], addr/value is in hex, count in decimal", + )); } } #[cfg(feature = "cramium-soc")] "rram" => { if args.len() == 2 || args.len() == 3 { - if let Ok(addr) = usize::from_str_radix(&args[0], 16) { - if addr < utralib::HW_RERAM_MEM_LEN { - if let Ok(value) = u32::from_str_radix(&args[1], 16) { - let count = if args.len() == 3 { - if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } else { 1 } - } else { - 1 - } - .min(utralib::HW_RRC_MEM_LEN as u32); // limit count to length of RRAM - let mut poke = Vec::new(); - for _ in 0..count { - poke.push(value); - } - // safety: this is safe because all elements are valid between the two - // representations, there are no alignment - // issues downcasting to a u8, and the underlying representation - // is in fact the data we're hoping to access. - let poke_inner = unsafe { - core::slice::from_raw_parts( - poke.as_ptr() as *const u8, - poke.len() * core::mem::size_of::(), - ) - }; - let mut rram = cramium_hal::rram::Reram::new(); - rram.write_slice(addr, poke_inner); - crate::println!("RRAM written {:x} into {:x}, {} times", value, addr, count); - } else { - crate::println!("RRAM value is in hex"); - } + let addr = usize::from_str_radix(&args[0], 16) + .map_err(|_| Error::help("RRAM address is in hex"))?; + if addr < utralib::HW_RERAM_MEM_LEN { + let value = u32::from_str_radix(&args[1], 16) + .map_err(|_| Error::help("RRAM value is in hex"))?; + let count = if args.len() == 3 { + if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } else { 1 } } else { - crate::println!( - "RRAM addresses are relative to base of RRAM, max 4M, and in hex" - ); + 1 } + .min(utralib::HW_RRC_MEM_LEN as u32); // limit count to length of RRAM + let mut poke = Vec::new(); + for _ in 0..count { + poke.push(value); + } + // safety: this is safe because all elements are valid between the two + // representations, there are no alignment + // issues downcasting to a u8, and the underlying representation + // is in fact the data we're hoping to access. + let poke_inner = unsafe { + core::slice::from_raw_parts( + poke.as_ptr() as *const u8, + poke.len() * core::mem::size_of::(), + ) + }; + let mut rram = cramium_hal::rram::Reram::new(); + rram.write_slice(addr, poke_inner); + crate::println!("RRAM written {:x} into {:x}, {} times", value, addr, count); } else { - crate::println!("RRAM address is in hex"); + return Err(Error::help( + "RRAM addresses are relative to base of RRAM, max 4M, and in hex", + )); } } else { - crate::println!( - "Help: rram [count], addr/value is in hex, count in decimal" - ); + return Err(Error::help( + "Help: rram [count], addr/value is in hex, count in decimal", + )); } } #[cfg(feature = "cramium-soc")] @@ -365,26 +366,17 @@ impl Repl { "clocks" => { use cramium_hal::udma; if args.len() == 1 { - let freq = match u32::from_str_radix(&args[0], 10) { - Ok(f) => { - if f >= 100 && f <= 1600 { - f * 1_000_000 - } else { - crate::println!("{} should be a number from 100-1600", args[0]); - self.abort_cmd(); - return; - } - } - _ => { - crate::println!("{} should be a number from 100-1600", args[0]); - self.abort_cmd(); - return; - } - }; - crate::println!("Setting clock to: {} MHz", freq / 1_000_000); + let f = u32::from_str_radix(&args[0], 10) + .map_err(|_| Error::help("clock , where freq is a number from 100-1600")) + .and_then(|f| { + (f >= 100 && f <= 1600) + .then_some(f * 1_000_000) + .ok_or(Error::help("frequency should be a number from 100-1600")) + })?; + crate::println!("Setting clock to: {} MHz", f / 1_000_000); // reset the baud rate on the console UART - let perclk = unsafe { crate::platform::init_clock_asic(freq) }; + let perclk = unsafe { crate::platform::init_clock_asic(f) }; let uart_buf_addr = crate::platform::UART_IFRAM_ADDR; #[cfg(feature = "nto-evb")] let mut udma_uart = unsafe { @@ -413,7 +405,7 @@ impl Repl { crate::println!("clock set done, perclk is {} MHz", perclk / 1_000_000); udma_uart.write("console up with clocks\r\n".as_bytes()); } else { - crate::println!("clocks ") + return Err(Error::help("clocks ")); } } #[cfg(feature = "cramium-soc")] @@ -517,10 +509,7 @@ impl Repl { "pin" => { // We need at least a subcommand. if args.is_empty() { - crate::println!("Usage: pin ..."); - self.do_cmd = false; - self.cmdline.clear(); - return; + return Err(Error::help("Usage: pin ...")); } let subcommand = args[0].as_str(); @@ -533,47 +522,39 @@ impl Repl { match subcommand { "set" => { if args.len() < 3 || args.len() > 4 { - crate::println!("Usage: pin set [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; + return Err(Error::help("Usage: pin set [core]")); } // Arg 1: Pin Number - let pin = match u32::from_str_radix(&args[1], 10) { - Ok(p) if p < 32 => p, - _ => { - crate::println!("Invalid pin number. Must be 0-31."); - crate::println!("Usage: pin set [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; - } - }; + let pin = u32::from_str_radix(&args[1], 10).map_err(|_| { + Error::help( + "Invalid pin number. Must be 0-31.\n\rUsage: pin set [core]", + ) + })?; // Arg 2: State - let state_str = args[2].as_str(); + let state_str = args[2].as_str().to_lowercase(); if state_str != "on" && state_str != "off" { - crate::println!("Invalid state. Use 'on' or 'off'."); - crate::println!("Usage: pin set [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; + return Err(Error::help( + "Invalid state. Use 'on' or 'off'.\n\rUsage: pin set [core]", + )); } let state_bool = state_str == "on"; // Arg 3 (Optional): Core ID let target_core: Option = if args.len() == 4 { - match u32::from_str_radix(&args[3], 10) { - Ok(c) if c < 4 => Some(BioCore::from(c as usize)), - _ => { - crate::println!("Invalid core ID. Must be 0-3."); - crate::println!("Usage: pin set [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; - } - } + Some(BioCore::from( + usize::from_str_radix(&args[3], 10).map_err(|_| { + Error::help( + "Invalid core ID. Must be 0-3.\n\rUsage: pin set [core]", + ) + }) + .and_then(|c| { + (c < 4) + .then_some(c) + .ok_or(Error::help("Core ID must be 0-3.")) + })? + )) } else { None // `set_pin` function handles the default core. }; @@ -590,45 +571,42 @@ impl Repl { } "pwm" => { if args.len() < 3 || args.len() > 4 { - crate::println!("Usage: pin pwm [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; + return Err(Error::help("Usage: pin pwm [core]")); } // Arg 1: Pin Number - let pin = match u32::from_str_radix(&args[1], 10) { - Ok(p) if p < 32 => p, - _ => { - crate::println!("Invalid pin number. Must be 0-31."); - crate::println!("Usage: pin pwm [core]"); - self.cmdline.clear(); - return; - } - }; + let pin = u32::from_str_radix(&args[1], 10) + .map_err( |_| Error::help( + "Invalid pin number. Must be 0-31.\n\rUsage: pin pwm [core]") + ) + .and_then(|n| { + (n < 32) + .then_some(n) + .ok_or(Error::help("Pin number out of range. Must be 0-31.")) + })?; // Arg 2: State - let state = args[2].as_str(); + let state = args[2].as_str().to_lowercase(); if state != "on" && state != "off" { - crate::println!("Invalid state. Use 'on' or 'off'."); - crate::println!("Usage: pin pwm [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; + return Err(Error::help( + "Invalid state. Use 'on' or 'off'.\n\rUsage: pin pwm [core]", + )); } // Arg 3 (Optional): Core ID - let target_core = if args.len() == 4 { - match u32::from_str_radix(&args[3], 10) { - Ok(c) if c < 4 => BioCore::from(c as usize), - _ => { - crate::println!("Invalid core number. Must be 0-3."); - crate::println!("Usage: pin pwm [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; - } - } + let target_core: BioCore = if args.len() == 4 { + BioCore::from( + usize::from_str_radix(&args[3], 10).map_err(|_| { + Error::help( + "Invalid core ID. Must be 0-3.\n\rUsage: pin pwm [core]", + ) + }) + .and_then(|c| { + (c < 4) + .then_some(c) + .ok_or(Error::help("Core ID must be 0-3.")) + })? + ) } else { BioCore::Core0 // Default to Core0 if not specified }; @@ -646,36 +624,36 @@ impl Repl { "read" => { // Validate arguments: must have a pin number, core is optional. if args.len() < 2 || args.len() > 3 { - crate::println!("Usage: pin read [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; + return Err(Error::help("Usage: pin read [core]")); } // Arg 1: Parse the pin number. - let pin = match u32::from_str_radix(&args[1], 10) { - Ok(p) if p < 32 => p, - _ => { - crate::println!("Invalid pin number. Must be 0-31."); - crate::println!("Usage: pin read [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; - } - }; + let pin = u32::from_str_radix(&args[1], 10) + .map_err(|_| { + Error::help( + "Invalid pin number. Must be 0-31.\n\rUsage: pin read [core]", + ) + }) + .and_then(|n| { + (n < 32) + .then_some(n) + .ok_or(Error::help("Pin number out of range. Must be 0-31.")) + })?; // Arg 2 (Optional): Parse the core ID. - let target_core = if args.len() == 3 { - match u32::from_str_radix(&args[2], 10) { - Ok(c) if c < 4 => BioCore::from(c as usize), - _ => { - crate::println!("Invalid core number. Must be 0-3."); - crate::println!("Usage: pin read [core]"); - self.do_cmd = false; - self.cmdline.clear(); - return; - } - } + let target_core: BioCore = if args.len() == 4 { + BioCore::from( + usize::from_str_radix(&args[3], 10).map_err(|_| { + Error::help( + "Invalid core ID. Must be 0-3.\n\rUsage: pin set [core]", + ) + }) + .and_then(|c| { + (c < 4) + .then_some(c) + .ok_or(Error::help("Core ID must be 0-3.")) + })? + ) } else { BioCore::Core0 // Default to Core0 if not specified }; @@ -715,17 +693,17 @@ impl Repl { } // reset for next loop - self.do_cmd = false; - self.cmdline.clear(); + self.abort_cmd(); + Ok(()) } - #[allow(dead_code)] - fn abort_cmd(&mut self) { + pub fn abort_cmd(&mut self) { self.do_cmd = false; self.cmdline.clear(); } } +#[cfg(feature = "nto-bio")] #[rustfmt::skip] bio_code!(simple_test_code, SIMPLE_TEST_START, SIMPLE_TEST_END, "li sp, 0x800", @@ -741,6 +719,7 @@ bio_code!(simple_test_code, SIMPLE_TEST_START, SIMPLE_TEST_END, "j 10b" ); +#[cfg(feature = "nto-bio")] #[rustfmt::skip] bio_code!(ldst_code, LDST_START, LDST_END, "sw x0, 0x20(x0)", @@ -751,6 +730,7 @@ bio_code!(ldst_code, LDST_START, LDST_END, "j 10b" ); +#[cfg(feature = "nto-bio")] fn debug_bio(bio_ss: &BioSharedState) { crate::println!( "c0:{:04x} c1:{:04x} c2:{:04x} c3:{:04x}",