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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/*
    Appellation: programs <module>
    Contrib: FL03 <jo3mccain@icloud.com>
    Description: ... summary ...
*/
use super::instructions::{Head, Instruction};
use super::{Alphabet, State, Symbolic};
use contained_core::{states::Stateful, Include, Insert};
use serde::{Deserialize, Serialize};
use std::{
    mem::replace,
    ops::{Index, IndexMut},
};

pub trait Contract<S: Symbolic>:
    Clone
    + IndexMut<usize, Output = Instruction<S>>
    + Include<Instruction<S>>
    + Insert<usize, Instruction<S>>
{
    fn alphabet(&self) -> Box<dyn Alphabet<S>>;
    fn final_state(&self) -> State;

    /// Given some [Head], find the coresponding [Instruction]
    fn get(&self, head: Head<S>) -> Option<&Instruction<S>> {
        // TODO: Reimplement the checks for getting a head value
        if head.state() > self.final_state() {
            return None;
        }
        self.instructions()
            .iter()
            .find(|inst: &&Instruction<S>| inst.head() == head)
    }
    /// Try to insert a new [Instruction] into the program; if the instruction is invalid, return None
    /// Otherwise, return the previous instruction at the same [Head] if it exists
    fn insert(&mut self, inst: Instruction<S>) -> Option<Instruction<S>> {
        // TODO: Reimplement the checks for insertion
        if inst.head().state() == State::Invalid {
            return None;
        }
        if self.final_state() < inst.head().state() || self.final_state() < inst.tail().state() {
            return None;
        }
        if !self.alphabet().is_viable(&inst.head().symbol())
            || !self.alphabet().is_viable(&inst.tail().symbol())
        {
            return None;
        }

        match self
            .instructions()
            .iter()
            .position(|cand: &Instruction<S>| cand.head() == inst.head())
        {
            Some(index) => Some(replace(&mut self.instructions_mut()[index], inst)),
            None => {
                self.instructions_mut().push(inst.clone());
                Some(inst)
            }
        }
    }

    fn instructions(&self) -> &Vec<Instruction<S>>;
    fn instructions_mut(&mut self) -> &mut Vec<Instruction<S>>;
}

#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct Program<S: Symbolic> {
    pub alphabet: Vec<S>,
    instructions: Vec<Instruction<S>>,
    final_state: State,
}

impl<S: Symbolic> Program<S> {
    pub fn new(alphabet: impl IntoIterator<Item = S>, final_state: State) -> Self {
        let alphabet = Vec::from_iter(alphabet);
        let s: i64 = final_state.into();
        let capacity = alphabet.len() * s as usize;
        let instructions = Vec::with_capacity(capacity);

        Self {
            alphabet,
            instructions,
            final_state,
        }
    }
    /// Returns an owned instance of the current program's alphabet
    pub fn alphabet(&self) -> &Vec<S> {
        &self.alphabet
    }
    /// Returns an owned instance of the current [Instruction] set
    pub fn instructions(&self) -> &Vec<Instruction<S>> {
        &self.instructions
    }
    /// Returns an owned instance of the final state
    pub fn final_state(&self) -> &State {
        &self.final_state
    }
    /// Given some [Head], find the coresponding [Instruction]
    pub fn get(&self, head: Head<S>) -> Option<&Instruction<S>> {
        if head.state() > *self.final_state() {
            return None;
        }
        self.instructions()
            .iter()
            .find(|inst: &&Instruction<S>| inst.head() == head)
    }
    /// Try to insert a new [Instruction] into the program; if the instruction is invalid, return None
    /// Otherwise, return the previous instruction at the same [Head] if it exists
    pub fn insert(&mut self, inst: Instruction<S>) -> Option<Instruction<S>> {
        // TODO: Reimplement the checks for insertion
        if inst.head().state() == State::Invalid {
            return None;
        }
        if *self.final_state() < inst.head().state() || *self.final_state() < inst.tail().state() {
            return None;
        }
        if !self.alphabet().is_viable(&inst.head().symbol())
            || !self.alphabet().is_viable(&inst.tail().symbol())
        {
            return None;
        }

        match self
            .instructions()
            .iter()
            .position(|cand: &Instruction<S>| cand.head() == inst.head())
        {
            Some(index) => Some(replace(&mut self.instructions[index], inst)),
            None => {
                self.instructions.push(inst.clone());
                Some(inst)
            }
        }
    }
    fn check_instruction(&self, inst: &Instruction<S>) -> bool {
        if inst.head().state() == State::Invalid {
            return false;
        }
        if *self.final_state() < inst.head().state() || *self.final_state() < inst.tail().state() {
            return false;
        }
        if !self.alphabet().is_viable(&inst.head().symbol())
            || !self.alphabet().is_viable(&inst.tail().symbol())
        {
            return false;
        }
        true
    }
}

impl<S: Symbolic> Alphabet<S> for Program<S> {
    fn is_viable(&self, symbol: &S) -> bool {
        self.alphabet.is_viable(symbol)
    }
    fn default_symbol(&self) -> S {
        self.alphabet.default_symbol()
    }
}

impl<S: Symbolic> Extend<Instruction<S>> for Program<S> {
    fn extend<T: IntoIterator<Item = Instruction<S>>>(&mut self, iter: T) {
        for i in iter {
            self.insert(i);
        }
    }
}

impl<S: Symbolic> Include<Instruction<S>> for Program<S> {
    fn include(&mut self, inst: Instruction<S>) {
        if self.check_instruction(&inst) {
            match self
                .instructions()
                .iter()
                .position(|cand: &Instruction<S>| cand.head() == inst.head())
            {
                Some(index) => {
                    let _ = std::mem::replace(&mut self.instructions[index], inst);
                }
                None => {
                    self.instructions.push(inst.clone());
                }
            }
        }
    }
}

// impl<S: Symbolic> Insert<usize, Instruction<S>> for Program<S> {
//     fn insert(&mut self, index: usize, inst: Instruction<S>) {
//         if self.check_instruction(&inst) {
//             self.instructions.insert(index, inst);
//         }
//     }
// }

impl<S: Symbolic> Index<usize> for Program<S> {
    type Output = Instruction<S>;

    fn index(&self, index: usize) -> &Self::Output {
        &self.instructions[index]
    }
}

impl<S: Symbolic> IndexMut<usize> for Program<S> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.instructions[index]
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::instructions::Move;

    #[test]
    fn test_program() {
        let inst = Instruction::from((State::valid(), "a", State::valid(), "b", Move::Right));
        let mut program = Program::new(vec!["a", "b", "c"], State::invalid());

        assert!(program.insert(inst.clone()).is_some());
        assert!(program.get(inst.head().clone()).is_some())
    }
}