tapir_bf/
lib.rs

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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//! Tapir is a one-function, zero-dependency Brainfuck interpreter.

#![warn(
    clippy::all,
    clippy::restriction,
    clippy::pedantic,
    clippy::nursery,
    clippy::cargo
)]

use crate::TapirError::*;
use std::fmt::{Debug, Display, Formatter};
use std::io::{self, Write};
use std::iter;

fn match_right(index: usize, program: &[u8], lma: usize, lmv: usize) -> (usize, usize, usize) {
    if lma == index {
        return (lmv, lma, lmv);
    }

    let lma = index;
    let mut index = index;

    let mut depth = 0;
    while index < program.len() {
        if program[index] as char == '[' {
            depth += 1;
        } else if program[index] as char == ']' {
            depth -= 1;
        }
        if depth == 0 {
            break;
        }
        index += 1;
    }
    if depth != 0 {
        return (0, lma, lmv);
    }
    (index, lma, index)
}

fn match_left(
    index: usize,
    program: &[u8],
    lma: usize,
    lmv: usize,
) -> (Option<usize>, usize, usize) {
    if lma == index {
        return (Some(lmv), lma, lmv);
    }

    let lma = index;
    let origin = index;
    let mut index = index;
    let mut depth = 0;

    while index <= origin {
        if program[index] as char == '[' {
            depth += 1;
        } else if program[index] as char == ']' {
            depth -= 1;
        }
        if depth == 0 {
            break;
        }
        index -= 1;
    }
    if depth != 0 {
        return (None, lma, lmv);
    }

    (Some(index), lma, index)
}

fn enhanced(s: &[u8]) -> Result<Vec<u8>, String> {
    let mut bytes: Vec<u8> = Vec::with_capacity(s.len());

    let byte_input = s;

    let mut i = 0;
    let input_len = byte_input.len();
    while i < input_len {
        if byte_input[i] as char == '\\' {
            if i + 1 < input_len {
                i += 1;
                bytes.push(match byte_input[i] {
                    b'n' => b'\n' as u8,
                    b'r' => b'\r' as u8,
                    b't' => b'\t' as u8,
                    b'\\' => b'\\' as u8,
                    b'#' => b'#' as u8,
                    _ => {
                        return Err(format!(
                            "expected an escape code but found '{}'",
                            byte_input[i] as char
                        ));
                    }
                });
            } else {
                return Err("expected an escape code but found nothing".to_string());
            }
        } else if byte_input[i] as char == '#' {
            if i + 3 < input_len {
                let mut res: u8 = 0;
                for j in 1..4 {
                    if byte_input[i + j].is_ascii_digit() {
                        res += (byte_input[i + j] - 48) * 10_u8.pow(3 - j as u32);
                    } else {
                        return Err(format!(
                            "expected a digit but found '{}'",
                            byte_input[i + j] as char
                        ));
                    }
                }
                bytes.push(res);
                i += 3;
            } else {
                return Err("expected a byte literal but didn't find enough digits".to_string());
            }
        } else {
            bytes.push(byte_input[i]);
        }
        i += 1;
    }

    debug_assert!(
        !bytes.is_empty(),
        "This function should only ever be called on non-empty arguments."
    );

    Ok(bytes)
}

pub fn enhanced_input<I, E>(input: I) -> impl Iterator<Item = Result<u8, EnhancedInputError<E>>>
where
    I: IntoIterator<Item = Result<u8, E>>,
{
    let mut input = input.into_iter();

    let mut line: Vec<u8> = Vec::new();

    iter::from_fn(move || match input.next() {
        Some(Ok(b'\n')) => {
            let r = Some(Some(Ok(line.clone())));
            line.clear();
            r
        }
        Some(Ok(c)) => {
            line.push(c);
            Some(None)
        }
        Some(Err(e)) => Some(Some(Err(EnhancedInputError::InputException(e)))),
        None => None,
    })
    .filter_map(|x| match x {
        None => None,
        Some(Ok(line)) => match enhanced(&line) {
            Ok(u8s) => Some(Ok(u8s)),
            Err(e) => Some(Err(EnhancedInputError::MalformedInput(e))),
        },
        Some(Err(e)) => Some(Err(e)),
    })
    .flat_map(|result| match result {
        Ok(vec) => vec.into_iter().map(Ok).collect::<Vec<_>>().into_iter(),
        Err(e) => std::iter::once(Err(e)).collect::<Vec<_>>().into_iter(),
    })
}

#[derive(Debug)]
pub enum EnhancedInputError<E> {
    MalformedInput(String),
    InputException(E),
}

impl<E: Display> Display for EnhancedInputError<E> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MalformedInput(s) => write!(f, "Malformed input: {}", s),
            Self::InputException(e) => write!(f, "{}", e),
        }
    }
}

#[derive(Debug)]
pub enum TapirError<E> {
    BracketError,
    MemPtrUnderflowError,
    InputExceptionError(E),
    MissingInputError,
    OutputError(io::Error),
}

impl<I: Display> Display for TapirError<I> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            InputExceptionError(e) => write!(f, "InputExceptionError: {}", e),
            OutputError(e) => write!(f, "OutputError: {}", e),
            BracketError => write!(f, "BracketError"),
            MemPtrUnderflowError => write!(f, "MemPtrUnderflowError"),
            MissingInputError => write!(f, "MissingInputError"),
        }
    }
}

impl<E> Into<i32> for TapirError<E> {
    fn into(self) -> i32 {
        match self {
            BracketError => 2,
            MemPtrUnderflowError => 3,
            InputExceptionError(_) => 5,
            MissingInputError => 6,
            OutputError(_) => 7,
        }
    }
}

#[inline]
pub fn interpret<I, E, O>(
    mem: &mut Vec<u8>,
    program: &[u8],
    input: I,
    mut output: O,
    eof_retry: bool,
) -> Result<(), (TapirError<E>, usize)>
where
    I: IntoIterator<Item = Result<u8, E>>,
    O: Write,
{
    let mut mem_ptr: usize = 0;
    let mut ins_ptr: usize = 0;

    let mut last_match_left_arg = 0;
    let mut last_match_left_val = 0;
    let mut last_match_right_arg = usize::MAX;
    let mut last_match_right_val = 0;

    if mem.is_empty() {
        mem.push(0);
    } // ensure that mem_ptr starts at a valid cell

    let mut input = input.into_iter();

    while ins_ptr < program.len() {
        match program[ins_ptr] as char {
            '>' => {
                mem_ptr += 1;
                if mem_ptr == mem.len() {
                    mem.push(0);
                    ins_ptr += 1;
                    continue;
                }
                debug_assert!(mem_ptr < mem.len(), "if we somehow increment by > 1");
            }
            '<' => {
                let new_mem_ptr = mem_ptr - 1;
                if new_mem_ptr > mem_ptr {
                    return Err((MemPtrUnderflowError, ins_ptr));
                }
                mem_ptr = new_mem_ptr;
            }
            '+' => mem[mem_ptr] += 1,
            '-' => mem[mem_ptr] -= 1,
            '.' => {
                print!("{}", mem[mem_ptr] as char);
            }
            ',' => {
                if let Err(e) = output.flush() {
                    return Err((OutputError(e), ins_ptr));
                }

                // I'll have to write some tests for this.
                // Retries getting input until it succeeds (or forever)
                // Pretend you didn't see this.
                let incoming_byte: u8 = match input.next() {
                    Some(Err(e)) => return Err((InputExceptionError(e), ins_ptr)),
                    Some(Ok(val)) => val,
                    None => {
                        if eof_retry {
                            match (|| loop {
                                match input.next() {
                                    Some(Ok(val)) => return Ok(val),
                                    Some(Err(e)) => return Err(InputExceptionError(e)),
                                    None => (),
                                }
                            })() {
                                Ok(val) => val,
                                Err(e) => return Err((e, ins_ptr)),
                            }
                        } else {
                            return Err((MissingInputError, ins_ptr));
                        }
                    }
                };

                mem[mem_ptr] = incoming_byte;
            }
            '[' => {
                if mem[mem_ptr] == 0 {
                    match match_right(ins_ptr, program, last_match_right_arg, last_match_right_val)
                    {
                        (0, _, _) => return Err((BracketError, ins_ptr)),
                        (n, lma, lmv) => {
                            ins_ptr = n;
                            last_match_right_arg = lma;
                            last_match_right_val = lmv;
                        }
                    }
                }
            }
            ']' => {
                if mem[mem_ptr] != 0 {
                    match match_left(ins_ptr, program, last_match_left_arg, last_match_left_val) {
                        (None, _, _) => return Err((BracketError, ins_ptr)),
                        (Some(n), lma, lmv) => {
                            ins_ptr = n;
                            last_match_left_arg = lma;
                            last_match_left_val = lmv;
                        }
                    }
                }
            }
            _ => {}
        }
        ins_ptr += 1;
    }

    if let Err(e) = output.flush() {
        return Err((OutputError(e), ins_ptr));
    }

    Ok(())
}