feat: add error handling

This commit is contained in:
leonhard committed 2026-11-17 17:24:41 +01:00
1 parent 7fc4d12eef
commit 12a506029b
3 files changed
+167 -29

No files matched your search

+19
View File
@@ -1,2 +1,21 @@
mod machine; mod machine;
mod tape; mod tape;
use std::fmt::Display;
pub use machine::TuringMachine;
enum TuringMachineError {
DuplicateStateEntryKey(String),
StateEntryParsing(String),
}
impl Display for TuringMachineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use TuringMachineError::*;
match self {
DuplicateStateEntryKey(key) => write!(f, "duplicate key in state table: {}", key),
StateEntryParsing(entry) => write!(f, "could not parse state entry: {}", entry),
}
}
}
+129 -25
View File
@@ -1,40 +1,53 @@
use std::{collections::HashMap, num::NonZeroUsize}; use std::{collections::HashMap, num::NonZeroUsize};
use crate::tape::{Tape, TapeSymbol}; use crate::{
TuringMachineError,
tape::{Tape, TapeSymbol},
};
struct TuringMachine { pub struct TuringMachine {
state_table: HashMap<(StateNumberType, TapeSymbol), MachineAction>, state_table: HashMap<(StateId, TapeSymbol), Action>,
current_state: MachineState, current_state: NextState,
tape: Tape, tape: Tape,
} }
impl TuringMachine { impl<'a> TuringMachine {
fn with_state_entries( pub fn with_state_entries(
state_entries: impl Iterator<Item = (StateNumberType, TapeSymbol, MachineAction)>, state_entries: impl Iterator<Item = &'a str>,
initial_state: MachineState, initial_state: &str,
) -> Self { ) -> Result<Self, TuringMachineError> {
let current_state = NextState::State(StateId::try_from(initial_state)?);
let mut state_table = HashMap::new(); let mut state_table = HashMap::new();
for (state, symbol, action) in state_entries { for state_entry in state_entries {
let StateEntry((state, symbol, action)) = state_entry.try_into()?;
if state_table.contains_key(&(state, symbol)) {
return Err(TuringMachineError::DuplicateStateEntryKey(format!(
"key of {} is duplicate",
state_entry
)));
}
state_table.insert((state, symbol), action); state_table.insert((state, symbol), action);
} }
TuringMachine { Ok(TuringMachine {
state_table, state_table,
current_state: initial_state, current_state,
tape: Tape::default(), tape: Tape::default(),
})
} }
} }
fn step(&mut self) { impl TuringMachine {
pub fn step(&mut self) {
let state_number = match self.current_state { let state_number = match self.current_state {
MachineState::Halt => return, NextState::Halt => return,
MachineState::StateNumber(n) => n, NextState::State(id) => id,
}; };
let symbol = self.tape.get_symbol(); let symbol = self.tape.get_symbol();
match self.state_table.get(&(state_number, symbol)) { match self.state_table.get(&(state_number, symbol)) {
None => { None => {
self.current_state = MachineState::Halt; self.current_state = NextState::Halt;
} }
Some(MachineAction { Some(Action {
tape_write, tape_write,
movement, movement,
new_state, new_state,
@@ -47,21 +60,112 @@ impl TuringMachine {
} }
} }
type StateNumberType = NonZeroUsize; const ALPHABET: [char; 26] = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
struct StateEntry((StateId, TapeSymbol, Action));
impl TryFrom<&str> for StateEntry {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let fields = value.split('|');
let state_id = StateId::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("empty entry".to_owned()),
)?)?;
let tape_symbol = TapeSymbol::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("missing field for tape symbol".to_owned()),
)?)?;
let action = Action::try_from(fields.next().ok_or(TuringMachineError::StateEntryParsing(
"missing field for action".to_owned(),
))?)?;
Ok((state_id, tape_symbol, action))
}
}
#[derive(Eq, Hash, PartialEq, Clone, Copy)] #[derive(Eq, Hash, PartialEq, Clone, Copy)]
enum MachineState { struct StateId(NonZeroUsize);
Halt,
StateNumber(StateNumberType), impl TryFrom<&str> for StateId {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let mut id: usize = 0;
for c in value.chars() {
let digit = ALPHABET.iter().position(|letter| *letter == c).ok_or(
TuringMachineError::StateEntryParsing(format!("state id: {}", value)),
)? + 1;
id = id * 26 + digit;
}
Ok(StateId(NonZeroUsize::new(id).ok_or(
TuringMachineError::StateEntryParsing(format!("state id: {}", value)),
)?))
}
} }
struct MachineAction { struct Action {
tape_write: TapeSymbol, tape_write: TapeSymbol,
movement: MachineMovement, movement: Movement,
new_state: MachineState, new_state: NextState,
} }
pub enum MachineMovement { impl TryFrom<&str> for Action {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let fields = value.split(';');
let tape_write = TapeSymbol::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("empty action".to_owned()),
)?)?;
let movement = Movement::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("missing field for movement".to_owned()),
)?)?;
let new_state = NextState::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("missing field for next state".to_owned()),
)?)?;
Ok(Action {
tape_write,
movement,
new_state,
})
}
}
pub enum Movement {
Left, Left,
Right, Right,
} }
impl TryFrom<&str> for Movement {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"L" => Ok(Movement::Left),
"R" => Ok(Movement::Right),
s => Err(TuringMachineError::StateEntryParsing(format!(
"machine movement: {}",
s
))),
}
}
}
#[derive(Eq, Hash, PartialEq, Clone, Copy)]
enum NextState {
Halt,
State(StateId),
}
impl TryFrom<&str> for NextState {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"-HALT-" => Ok(NextState::Halt),
v => Ok(NextState::State(StateId::try_from(v)?)),
}
}
}
+19 -4
View File
@@ -1,4 +1,4 @@
use crate::machine::MachineMovement; use crate::{TuringMachineError, machine::Movement};
pub struct Tape { pub struct Tape {
left_half: Vec<TapeSymbol>, left_half: Vec<TapeSymbol>,
@@ -17,9 +17,9 @@ impl Default for Tape {
} }
impl Tape { impl Tape {
pub fn move_head(&mut self, direction: &MachineMovement) { pub fn move_head(&mut self, direction: &Movement) {
match &direction { match &direction {
MachineMovement::Left => { Movement::Left => {
if self.head.is_right_side() { if self.head.is_right_side() {
if self.head.index == 0 { if self.head.index == 0 {
self.head.side = TapeSide::Left; self.head.side = TapeSide::Left;
@@ -33,7 +33,7 @@ impl Tape {
} }
} }
} }
MachineMovement::Right => { Movement::Right => {
if self.head.is_left_side() { if self.head.is_left_side() {
if self.head.index == 0 { if self.head.index == 0 {
self.head.side = TapeSide::Right; self.head.side = TapeSide::Right;
@@ -116,6 +116,21 @@ impl Default for TapeSymbol {
} }
} }
impl TryFrom<&str> for TapeSymbol {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"0" => Ok(TapeSymbol::Zero),
"1" => Ok(TapeSymbol::One),
s => Err(TuringMachineError::StateEntryParsing(format!(
"tape symbol: {}",
s
))),
}
}
}
#[derive(Default)] #[derive(Default)]
struct HeadPosition { struct HeadPosition {
side: TapeSide, side: TapeSide,