1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
    Appellation: head <module>
    Contrib: FL03 <jo3mccain@icloud.com>
    Description:
        The instruction head is a two-tuple (State, Symbol)
*/
use crate::{machine::Driver, Scope, State, Symbolic};
use contained_core::states::Stateful;
use decanter::prelude::Hashable;
use serde::{Deserialize, Serialize};

#[derive(
    Clone, Debug, Default, Deserialize, Eq, Hash, Hashable, Ord, PartialEq, PartialOrd, Serialize,
)]
pub struct Head<S: Symbolic = String> {
    state: State,
    symbol: S,
}

impl<S: Symbolic> Head<S> {
    pub fn new(state: State, symbol: S) -> Self {
        Self { state, symbol }
    }
    pub fn symbol(&self) -> S {
        self.symbol.clone()
    }
}

impl<S: Symbolic> Stateful<State> for Head<S> {
    fn state(&self) -> State {
        self.state
    }

    fn update_state(&mut self, state: State) {
        self.state = state;
    }
}

impl<S: Symbolic> std::fmt::Display for Head<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {})", self.state, self.symbol)
    }
}

impl<S: Symbolic> From<Driver<S>> for Head<S> {
    fn from(value: Driver<S>) -> Self {
        Self::new(value.state(), value.current())
    }
}

impl<S: Symbolic> From<Head<S>> for (State, S) {
    fn from(v: Head<S>) -> (State, S) {
        (v.state(), v.symbol())
    }
}

impl<S: Symbolic> From<(State, S)> for Head<S> {
    fn from(value: (State, S)) -> Self {
        Self::new(value.0, value.1)
    }
}