diff --git a/src/lib.rs b/src/lib.rs index 1dcb265..8f03b19 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,21 @@ mod machine; 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), + } + } +} diff --git a/src/machine.rs b/src/machine.rs index ab1acfd..8b485a3 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -1,40 +1,53 @@ use std::{collections::HashMap, num::NonZeroUsize}; -use crate::tape::{Tape, TapeSymbol}; +use crate::{ + TuringMachineError, + tape::{Tape, TapeSymbol}, +}; -struct TuringMachine { - state_table: HashMap<(StateNumberType, TapeSymbol), MachineAction>, - current_state: MachineState, +pub struct TuringMachine { + state_table: HashMap<(StateId, TapeSymbol), Action>, + current_state: NextState, tape: Tape, } -impl TuringMachine { - fn with_state_entries( - state_entries: impl Iterator, - initial_state: MachineState, - ) -> Self { +impl<'a> TuringMachine { + pub fn with_state_entries( + state_entries: impl Iterator, + initial_state: &str, + ) -> Result { + let current_state = NextState::State(StateId::try_from(initial_state)?); 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); } - TuringMachine { + Ok(TuringMachine { state_table, - current_state: initial_state, + current_state, tape: Tape::default(), - } + }) } +} - fn step(&mut self) { +impl TuringMachine { + pub fn step(&mut self) { let state_number = match self.current_state { - MachineState::Halt => return, - MachineState::StateNumber(n) => n, + NextState::Halt => return, + NextState::State(id) => id, }; let symbol = self.tape.get_symbol(); match self.state_table.get(&(state_number, symbol)) { None => { - self.current_state = MachineState::Halt; + self.current_state = NextState::Halt; } - Some(MachineAction { + Some(Action { tape_write, movement, 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 { + 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)] -enum MachineState { - Halt, - StateNumber(StateNumberType), +struct StateId(NonZeroUsize); + +impl TryFrom<&str> for StateId { + type Error = TuringMachineError; + + fn try_from(value: &str) -> Result { + 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, - movement: MachineMovement, - new_state: MachineState, + movement: Movement, + new_state: NextState, } -pub enum MachineMovement { +impl TryFrom<&str> for Action { + type Error = TuringMachineError; + + fn try_from(value: &str) -> Result { + 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, Right, } + +impl TryFrom<&str> for Movement { + type Error = TuringMachineError; + + fn try_from(value: &str) -> Result { + 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 { + match value { + "-HALT-" => Ok(NextState::Halt), + v => Ok(NextState::State(StateId::try_from(v)?)), + } + } +} diff --git a/src/tape.rs b/src/tape.rs index 7a269bf..e0f5349 100644 --- a/src/tape.rs +++ b/src/tape.rs @@ -1,4 +1,4 @@ -use crate::machine::MachineMovement; +use crate::{TuringMachineError, machine::Movement}; pub struct Tape { left_half: Vec, @@ -17,9 +17,9 @@ impl Default for Tape { } impl Tape { - pub fn move_head(&mut self, direction: &MachineMovement) { + pub fn move_head(&mut self, direction: &Movement) { match &direction { - MachineMovement::Left => { + Movement::Left => { if self.head.is_right_side() { if self.head.index == 0 { self.head.side = TapeSide::Left; @@ -33,7 +33,7 @@ impl Tape { } } } - MachineMovement::Right => { + Movement::Right => { if self.head.is_left_side() { if self.head.index == 0 { 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 { + match value { + "0" => Ok(TapeSymbol::Zero), + "1" => Ok(TapeSymbol::One), + s => Err(TuringMachineError::StateEntryParsing(format!( + "tape symbol: {}", + s + ))), + } + } +} + #[derive(Default)] struct HeadPosition { side: TapeSide,