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.
This commit is contained in:
bunnie 2025-08-14 02:01:39 +08:00
parent 38193077c5
commit 0bb5ae95b9

View file

@ -1,3 +1,4 @@
#[allow(unused_imports)]
use alloc::format; use alloc::format;
use alloc::string::{String, ToString}; use alloc::string::{String, ToString};
use alloc::vec::Vec; use alloc::vec::Vec;
@ -7,6 +8,15 @@ use utralib::*;
#[cfg(any(feature = "artybio", feature = "nto-bio"))] #[cfg(any(feature = "artybio", feature = "nto-bio"))]
use xous_bio_bdma::*; 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 { pub struct Repl {
cmdline: String, cmdline: String,
do_cmd: bool, 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 { if !self.do_cmd {
return; return Err(Error::none());
} }
// crate::println!("got {}", self.cmdline); // crate::println!("got {}", self.cmdline);
@ -88,100 +98,91 @@ impl Repl {
} }
"peek" => { "peek" => {
if args.len() == 1 || args.len() == 2 { if args.len() == 1 || args.len() == 2 {
if let Ok(addr) = usize::from_str_radix(&args[0], 16) { let addr = usize::from_str_radix(&args[0], 16)
let count = if args.len() == 2 { .map_err(|_| Error::help("Peek address is in hex"))?;
if let Ok(count) = u32::from_str_radix(&args[1], 10) { count } else { 1 }
} else { let count = if args.len() == 2 {
1 if let Ok(count) = u32::from_str_radix(&args[1], 10) { count } 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::<u32>());
}
crate::print!("{:08x} ", d);
}
crate::println!("");
} else { } 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::<u32>());
}
crate::print!("{:08x} ", d);
} }
crate::println!("");
} else { } else {
crate::println!("Help: peek <addr> [count], addr is in hex, count in decimal"); return Err(Error::help("Help: peek <addr> [count], addr is in hex, count in decimal"));
} }
} }
"poke" => { "poke" => {
if args.len() == 2 || args.len() == 3 { if args.len() == 2 || args.len() == 3 {
if let Ok(addr) = u32::from_str_radix(&args[0], 16) { let addr = u32::from_str_radix(&args[0], 16)
if let Ok(value) = u32::from_str_radix(&args[1], 16) { .map_err(|_| Error::help("Poke address is in hex"))?;
let count = if args.len() == 3 {
if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } else { 1 } let value =
} else { u32::from_str_radix(&args[1], 16).map_err(|_| Error::help("Poke value is in hex"))?;
1 let count = if args.len() == 3 {
}; if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } 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");
}
} else { } 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 { } else {
crate::println!( return Err(Error::help(
"Help: poke <addr> <value> [count], addr/value is in hex, count in decimal" "Help: poke <addr> <value> [count], addr/value is in hex, count in decimal",
); ));
} }
} }
#[cfg(feature = "cramium-soc")] #[cfg(feature = "cramium-soc")]
"rram" => { "rram" => {
if args.len() == 2 || args.len() == 3 { if args.len() == 2 || args.len() == 3 {
if let Ok(addr) = usize::from_str_radix(&args[0], 16) { let addr = usize::from_str_radix(&args[0], 16)
if addr < utralib::HW_RERAM_MEM_LEN { .map_err(|_| Error::help("RRAM address is in hex"))?;
if let Ok(value) = u32::from_str_radix(&args[1], 16) { if addr < utralib::HW_RERAM_MEM_LEN {
let count = if args.len() == 3 { let value = u32::from_str_radix(&args[1], 16)
if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } else { 1 } .map_err(|_| Error::help("RRAM value is in hex"))?;
} else { let count = if args.len() == 3 {
1 if let Ok(count) = u32::from_str_radix(&args[2], 10) { count } 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::<u32>(),
)
};
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");
}
} else { } else {
crate::println!( 1
"RRAM addresses are relative to base of RRAM, max 4M, and in hex"
);
} }
.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::<u32>(),
)
};
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 { } 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 { } else {
crate::println!( return Err(Error::help(
"Help: rram <addr> <value> [count], addr/value is in hex, count in decimal" "Help: rram <addr> <value> [count], addr/value is in hex, count in decimal",
); ));
} }
} }
#[cfg(feature = "cramium-soc")] #[cfg(feature = "cramium-soc")]
@ -365,26 +366,17 @@ impl Repl {
"clocks" => { "clocks" => {
use cramium_hal::udma; use cramium_hal::udma;
if args.len() == 1 { if args.len() == 1 {
let freq = match u32::from_str_radix(&args[0], 10) { let f = u32::from_str_radix(&args[0], 10)
Ok(f) => { .map_err(|_| Error::help("clock <freq>, where freq is a number from 100-1600"))
if f >= 100 && f <= 1600 { .and_then(|f| {
f * 1_000_000 (f >= 100 && f <= 1600)
} else { .then_some(f * 1_000_000)
crate::println!("{} should be a number from 100-1600", args[0]); .ok_or(Error::help("frequency should be a number from 100-1600"))
self.abort_cmd(); })?;
return; crate::println!("Setting clock to: {} MHz", f / 1_000_000);
}
}
_ => {
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);
// reset the baud rate on the console UART // 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; let uart_buf_addr = crate::platform::UART_IFRAM_ADDR;
#[cfg(feature = "nto-evb")] #[cfg(feature = "nto-evb")]
let mut udma_uart = unsafe { let mut udma_uart = unsafe {
@ -413,7 +405,7 @@ impl Repl {
crate::println!("clock set done, perclk is {} MHz", perclk / 1_000_000); crate::println!("clock set done, perclk is {} MHz", perclk / 1_000_000);
udma_uart.write("console up with clocks\r\n".as_bytes()); udma_uart.write("console up with clocks\r\n".as_bytes());
} else { } else {
crate::println!("clocks <CPU freq in MHz>") return Err(Error::help("clocks <CPU freq in MHz, 100-1600>"));
} }
} }
#[cfg(feature = "cramium-soc")] #[cfg(feature = "cramium-soc")]
@ -517,10 +509,7 @@ impl Repl {
"pin" => { "pin" => {
// We need at least a subcommand. // We need at least a subcommand.
if args.is_empty() { if args.is_empty() {
crate::println!("Usage: pin <set|pwm|read> ..."); return Err(Error::help("Usage: pin <set|pwm|read> ..."));
self.do_cmd = false;
self.cmdline.clear();
return;
} }
let subcommand = args[0].as_str(); let subcommand = args[0].as_str();
@ -533,47 +522,39 @@ impl Repl {
match subcommand { match subcommand {
"set" => { "set" => {
if args.len() < 3 || args.len() > 4 { if args.len() < 3 || args.len() > 4 {
crate::println!("Usage: pin set <pin#> <on|off> [core]"); return Err(Error::help("Usage: pin set <pin#> <on|off> [core]"));
self.do_cmd = false;
self.cmdline.clear();
return;
} }
// Arg 1: Pin Number // Arg 1: Pin Number
let pin = match u32::from_str_radix(&args[1], 10) { let pin = u32::from_str_radix(&args[1], 10).map_err(|_| {
Ok(p) if p < 32 => p, Error::help(
_ => { "Invalid pin number. Must be 0-31.\n\rUsage: pin set <pin#> <on|off> [core]",
crate::println!("Invalid pin number. Must be 0-31."); )
crate::println!("Usage: pin set <pin#> <on|off> [core]"); })?;
self.do_cmd = false;
self.cmdline.clear();
return;
}
};
// Arg 2: State // 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" { if state_str != "on" && state_str != "off" {
crate::println!("Invalid state. Use 'on' or 'off'."); return Err(Error::help(
crate::println!("Usage: pin set <pin#> <on|off> [core]"); "Invalid state. Use 'on' or 'off'.\n\rUsage: pin set <pin#> <on|off> [core]",
self.do_cmd = false; ));
self.cmdline.clear();
return;
} }
let state_bool = state_str == "on"; let state_bool = state_str == "on";
// Arg 3 (Optional): Core ID // Arg 3 (Optional): Core ID
let target_core: Option<BioCore> = if args.len() == 4 { let target_core: Option<BioCore> = if args.len() == 4 {
match u32::from_str_radix(&args[3], 10) { Some(BioCore::from(
Ok(c) if c < 4 => Some(BioCore::from(c as usize)), usize::from_str_radix(&args[3], 10).map_err(|_| {
_ => { Error::help(
crate::println!("Invalid core ID. Must be 0-3."); "Invalid core ID. Must be 0-3.\n\rUsage: pin set <pin#> <on|off> [core]",
crate::println!("Usage: pin set <pin#> <on|off> [core]"); )
self.do_cmd = false; })
self.cmdline.clear(); .and_then(|c| {
return; (c < 4)
} .then_some(c)
} .ok_or(Error::help("Core ID must be 0-3."))
})?
))
} else { } else {
None // `set_pin` function handles the default core. None // `set_pin` function handles the default core.
}; };
@ -590,45 +571,42 @@ impl Repl {
} }
"pwm" => { "pwm" => {
if args.len() < 3 || args.len() > 4 { if args.len() < 3 || args.len() > 4 {
crate::println!("Usage: pin pwm <pin#> <on|off> [core]"); return Err(Error::help("Usage: pin pwm <pin#> <on|off> [core]"));
self.do_cmd = false;
self.cmdline.clear();
return;
} }
// Arg 1: Pin Number // Arg 1: Pin Number
let pin = match u32::from_str_radix(&args[1], 10) { let pin = u32::from_str_radix(&args[1], 10)
Ok(p) if p < 32 => p, .map_err( |_| Error::help(
_ => { "Invalid pin number. Must be 0-31.\n\rUsage: pin pwm <pin#> <on|off> [core]")
crate::println!("Invalid pin number. Must be 0-31."); )
crate::println!("Usage: pin pwm <pin#> <on|off> [core]"); .and_then(|n| {
self.cmdline.clear(); (n < 32)
return; .then_some(n)
} .ok_or(Error::help("Pin number out of range. Must be 0-31."))
}; })?;
// Arg 2: State // Arg 2: State
let state = args[2].as_str(); let state = args[2].as_str().to_lowercase();
if state != "on" && state != "off" { if state != "on" && state != "off" {
crate::println!("Invalid state. Use 'on' or 'off'."); return Err(Error::help(
crate::println!("Usage: pin pwm <pin#> <on|off> [core]"); "Invalid state. Use 'on' or 'off'.\n\rUsage: pin pwm <pin#> <on|off> [core]",
self.do_cmd = false; ));
self.cmdline.clear();
return;
} }
// Arg 3 (Optional): Core ID // Arg 3 (Optional): Core ID
let target_core = if args.len() == 4 { let target_core: BioCore = if args.len() == 4 {
match u32::from_str_radix(&args[3], 10) { BioCore::from(
Ok(c) if c < 4 => BioCore::from(c as usize), usize::from_str_radix(&args[3], 10).map_err(|_| {
_ => { Error::help(
crate::println!("Invalid core number. Must be 0-3."); "Invalid core ID. Must be 0-3.\n\rUsage: pin pwm <pin#> <on|off> [core]",
crate::println!("Usage: pin pwm <pin#> <on|off> [core]"); )
self.do_cmd = false; })
self.cmdline.clear(); .and_then(|c| {
return; (c < 4)
} .then_some(c)
} .ok_or(Error::help("Core ID must be 0-3."))
})?
)
} else { } else {
BioCore::Core0 // Default to Core0 if not specified BioCore::Core0 // Default to Core0 if not specified
}; };
@ -646,36 +624,36 @@ impl Repl {
"read" => { "read" => {
// Validate arguments: must have a pin number, core is optional. // Validate arguments: must have a pin number, core is optional.
if args.len() < 2 || args.len() > 3 { if args.len() < 2 || args.len() > 3 {
crate::println!("Usage: pin read <pin#> [core]"); return Err(Error::help("Usage: pin read <pin#> [core]"));
self.do_cmd = false;
self.cmdline.clear();
return;
} }
// Arg 1: Parse the pin number. // Arg 1: Parse the pin number.
let pin = match u32::from_str_radix(&args[1], 10) { let pin = u32::from_str_radix(&args[1], 10)
Ok(p) if p < 32 => p, .map_err(|_| {
_ => { Error::help(
crate::println!("Invalid pin number. Must be 0-31."); "Invalid pin number. Must be 0-31.\n\rUsage: pin read <pin#> [core]",
crate::println!("Usage: pin read <pin#> [core]"); )
self.do_cmd = false; })
self.cmdline.clear(); .and_then(|n| {
return; (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. // Arg 2 (Optional): Parse the core ID.
let target_core = if args.len() == 3 { let target_core: BioCore = if args.len() == 4 {
match u32::from_str_radix(&args[2], 10) { BioCore::from(
Ok(c) if c < 4 => BioCore::from(c as usize), usize::from_str_radix(&args[3], 10).map_err(|_| {
_ => { Error::help(
crate::println!("Invalid core number. Must be 0-3."); "Invalid core ID. Must be 0-3.\n\rUsage: pin set <pin#> <on|off> [core]",
crate::println!("Usage: pin read <pin#> [core]"); )
self.do_cmd = false; })
self.cmdline.clear(); .and_then(|c| {
return; (c < 4)
} .then_some(c)
} .ok_or(Error::help("Core ID must be 0-3."))
})?
)
} else { } else {
BioCore::Core0 // Default to Core0 if not specified BioCore::Core0 // Default to Core0 if not specified
}; };
@ -715,17 +693,17 @@ impl Repl {
} }
// reset for next loop // reset for next loop
self.do_cmd = false; self.abort_cmd();
self.cmdline.clear(); Ok(())
} }
#[allow(dead_code)] pub fn abort_cmd(&mut self) {
fn abort_cmd(&mut self) {
self.do_cmd = false; self.do_cmd = false;
self.cmdline.clear(); self.cmdline.clear();
} }
} }
#[cfg(feature = "nto-bio")]
#[rustfmt::skip] #[rustfmt::skip]
bio_code!(simple_test_code, SIMPLE_TEST_START, SIMPLE_TEST_END, bio_code!(simple_test_code, SIMPLE_TEST_START, SIMPLE_TEST_END,
"li sp, 0x800", "li sp, 0x800",
@ -741,6 +719,7 @@ bio_code!(simple_test_code, SIMPLE_TEST_START, SIMPLE_TEST_END,
"j 10b" "j 10b"
); );
#[cfg(feature = "nto-bio")]
#[rustfmt::skip] #[rustfmt::skip]
bio_code!(ldst_code, LDST_START, LDST_END, bio_code!(ldst_code, LDST_START, LDST_END,
"sw x0, 0x20(x0)", "sw x0, 0x20(x0)",
@ -751,6 +730,7 @@ bio_code!(ldst_code, LDST_START, LDST_END,
"j 10b" "j 10b"
); );
#[cfg(feature = "nto-bio")]
fn debug_bio(bio_ss: &BioSharedState) { fn debug_bio(bio_ss: &BioSharedState) {
crate::println!( crate::println!(
"c0:{:04x} c1:{:04x} c2:{:04x} c3:{:04x}", "c0:{:04x} c1:{:04x} c2:{:04x} c3:{:04x}",