Skip to content

Commit

Permalink
feat: replace panic with custom exception macro
Browse files Browse the repository at this point in the history
  • Loading branch information
dxrcy committed Nov 28, 2024
1 parent 227a524 commit ba1fa03
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use core::panic;
use std::{
cmp::Ordering,
i16,
Expand All @@ -11,6 +10,16 @@ use colored::Colorize;
use console::Term;
use miette::Result;

macro_rules! exception {
( $fmt:literal $($tt:tt)* ) => {{
eprintln!(
concat!("exception: ", $fmt, ", exiting")
$($tt)*
);
std::process::exit(0xEE);
}};
}

/// LC3 can address 128KB of memory.
const MEMORY_MAX: usize = 0x10000;

Expand Down Expand Up @@ -53,7 +62,7 @@ impl RunState {
pub fn from_raw(raw: &[u16]) -> Result<RunState> {
let orig = raw[0] as usize;
if orig as usize + raw.len() > MEMORY_MAX {
panic!("Assembly file is too long and cannot fit in memory.");
exception!("assembly file is too long and cannot fit in memory");
}

let mut mem = [0; MEMORY_MAX];
Expand Down Expand Up @@ -99,7 +108,7 @@ impl RunState {
break; // Halt was triggered
}
if self.pc >= 0xFE00 {
panic!("Program counter entered device address space");
exception!("entered protected memory area >= 0xFE00");
}
let instr = self.mem[self.pc as usize];
let opcode = (instr >> 12) as usize;
Expand Down Expand Up @@ -376,7 +385,10 @@ impl RunState {
println!("-----------------------");
}
// unknown
_ => panic!("You called a trap with an unknown vector of {}", trap_vect),
_ => exception!(
"called a trap with an unknown vector of 0x{:02x}",
trap_vect
),
}
}
}
Expand All @@ -403,7 +415,7 @@ mod test {
fn expect(input: u16, bits: u32, expected: u16) {
let actual = RunState::s_ext(input, bits);
if actual != expected {
std::panic!(
panic!(
"\ns_ext(0x{input:04x}, {bits})\n Expected: 0x{expected:04x}\n Actual: 0x{actual:04x}\n"
);
}
Expand Down

0 comments on commit ba1fa03

Please sign in to comment.