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
use std::{fmt, str::FromStr};
use thiserror::Error;

pub type CellAddress = usize;
pub type CellValue = i64;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Operand {
    Number(CellValue),               // =x
    ValueInCell(CellAddress),        // x
    ValueOfValueInCell(CellAddress), // ^x
}

#[derive(Error, Debug, PartialEq, Eq)]
#[error("Operand {0} is not a valid operand")]
pub struct InvalidOperandError(String);

#[derive(Error, Debug, PartialEq, Eq)]
pub enum OperandParseError {
    #[error("Operand {0} is not a valid operand for keyword `{1}`")]
    InvalidOperand(String, String),
    #[error("Expected operand for keyword `{0}`, found nothing")]
    OperandNotFound(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CellOperand {
    AddressOfCell(CellAddress),       // x
    AddressOfCellInCell(CellAddress), // ^x
}

#[derive(Error, Debug, PartialEq, Eq)]
pub enum ExpandError {
    #[error("Value `{0}` in cell `{1}` could not be converted to a tape index.")]
    ConvertError(CellValue, CellAddress),
    #[error("Tried reading from cell with address `{0}`, which was never set.")]
    ValueNotSet(CellAddress),
}

impl Operand {
    pub fn expand<'a>(
        &'a self,
        tape: &'a [Option<CellValue>],
    ) -> Result<&'a CellValue, ExpandError> {
        use Operand::*;
        match self {
            Number(v) => Ok(v),
            ValueInCell(cell) => Ok(tape
                .get(*cell)
                .and_then(|val| val.as_ref())
                .ok_or(ExpandError::ValueNotSet(*cell))?),
            ValueOfValueInCell(cell) => tape
                .get(
                    CellAddress::try_from(
                        tape.get(*cell)
                            .ok_or(ExpandError::ValueNotSet(*cell))?
                            .ok_or(ExpandError::ValueNotSet(*cell))?,
                    )
                    .map_err(|_| {
                        ExpandError::ConvertError(
                            tape.get(*cell).expect("Would've failed before").unwrap(),
                            *cell,
                        )
                    })?,
                )
                .and_then(|val| val.as_ref())
                .ok_or_else(|| {
                    ExpandError::ValueNotSet(
                        CellAddress::try_from(
                            tape.get(*cell).expect("Would've failed before").unwrap(),
                        )
                        .expect("Would've failed before"),
                    )
                }),
        }
    }
}

impl CellOperand {
    pub fn expand(&self, tape: &[Option<CellValue>]) -> Result<CellAddress, ExpandError> {
        use CellOperand::*;
        match self {
            AddressOfCell(cell) => Ok(*cell),
            AddressOfCellInCell(cell) => CellAddress::try_from(
                tape.get(*cell)
                    .ok_or(ExpandError::ValueNotSet(*cell))?
                    .ok_or(ExpandError::ValueNotSet(*cell))?,
            )
            .map_err(|_| {
                ExpandError::ConvertError(
                    tape.get(*cell).expect("Didn't fail previously").unwrap(),
                    *cell,
                )
            }),
        }
    }
}

macro_rules! parse {
    ($e:expr) => {
        $e.parse().expect("Already checked if can be parsed")
    };
}

fn is_number(s: &str) -> bool {
    s.parse::<CellValue>().is_ok()
}

fn is_positive_number(s: &str) -> bool {
    s.parse::<CellAddress>().is_ok()
}

fn is_operand_number(s: &str) -> bool {
    s.starts_with('=') && is_number(&s[1..])
}

fn is_operand_value_in_cell(s: &str) -> bool {
    is_positive_number(s)
}

fn is_operand_value_of_value_in_cell(s: &str) -> bool {
    s.starts_with('^') && is_positive_number(&s[1..])
}
fn is_operand_address_of_cell(s: &str) -> bool {
    is_operand_value_in_cell(s)
}

fn is_operand_address_of_cell_in_cell(s: &str) -> bool {
    is_operand_value_of_value_in_cell(s)
}

impl FromStr for Operand {
    type Err = InvalidOperandError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            s if is_operand_number(s) => Ok(Self::Number(parse!(s[1..]))),
            s if is_operand_value_in_cell(s) => Ok(Self::ValueInCell(parse!(s))),
            s if is_operand_value_of_value_in_cell(s) => {
                Ok(Self::ValueOfValueInCell(parse!(s[1..])))
            }
            _ => Err(InvalidOperandError(s.to_owned())),
        }
    }
}

impl TryFrom<(Option<&str>, &str)> for Operand {
    type Error = OperandParseError;
    fn try_from((s, keyword): (Option<&str>, &str)) -> Result<Self, Self::Error> {
        match s {
            Some(s) => Operand::from_str(s)
                .map_err(|err| OperandParseError::InvalidOperand(err.0, keyword.to_owned())),
            None => Err(OperandParseError::OperandNotFound(keyword.to_owned())),
        }
    }
}

impl FromStr for CellOperand {
    type Err = InvalidOperandError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            s if is_operand_address_of_cell(s) => Ok(Self::AddressOfCell(parse!(s))),
            s if is_operand_address_of_cell_in_cell(s) => {
                Ok(Self::AddressOfCellInCell(parse!(s[1..])))
            }
            _ => Err(InvalidOperandError(s.to_owned())),
        }
    }
}

impl TryFrom<(Option<&str>, &str)> for CellOperand {
    type Error = OperandParseError;
    fn try_from((s, keyword): (Option<&str>, &str)) -> Result<Self, Self::Error> {
        match s {
            Some(s) => CellOperand::from_str(s)
                .map_err(|err| OperandParseError::InvalidOperand(err.0, keyword.to_owned())),
            None => Err(OperandParseError::OperandNotFound(keyword.to_owned())),
        }
    }
}

impl fmt::Display for Operand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Operand::Number(value) => write!(f, "={}", value),
            Operand::ValueInCell(address) => write!(f, "{}", address),
            Operand::ValueOfValueInCell(address) => write!(f, "^{}", address),
        }
    }
}

impl fmt::Display for CellOperand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CellOperand::AddressOfCell(address) => write!(f, "{}", address),
            CellOperand::AddressOfCellInCell(address) => write!(f, "^{}", address),
        }
    }
}