brainfoamkit 1.1.0

An interpreter for the brainf*** language
Documentation
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// SPDX-FileCopyrightText: 2023 - 2024 Ali Sajid Imami
//
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use std::{
    fmt::{
        self,
        Display,
        Formatter,
    },
    ops::Index,
};

use crate::Instruction;

/// Structure to hold the program.
///
/// A `Program` is a series if instructions stored in the program stack.
/// This struct allows us to conveniently read the program, modify it and save
/// it back.
///
/// # Examples
///
/// ## Loading a `Program` from a series of instructions
///
/// ```
/// use brainfoamkit_lib::{
///     Instruction,
///     Program,
/// };
///
/// let instructions = vec![
///     Instruction::IncrementPointer,
///     Instruction::IncrementValue,
///     Instruction::DecrementPointer,
///     Instruction::DecrementValue,
/// ];
/// let mut program = Program::from(instructions);
///
/// assert_eq!(program.length(), Some(4));
/// ```
///
/// ## Load a `Program` from a string
///
/// ```
/// // TODO: Verify this example
/// use brainfoamkit_lib::Program;
///
/// let program_string = ">>++<<--";
/// let program = Program::from(program_string);
///
/// assert_eq!(program.length(), Some(8));
/// ```
///
/// ## Get an instruction from a `Program`
///
/// ```
/// // TODO: Verify this example
/// use brainfoamkit_lib::{
///     Instruction,
///     Program,
/// };
///
/// let program_string = ">+<-";
///
/// let mut program = Program::from(program_string);
///
/// assert_eq!(
///     program.get_instruction(0),
///     Some(Instruction::IncrementPointer)
/// );
/// assert_eq!(
///     program.get_instruction(1),
///     Some(Instruction::IncrementValue)
/// );
/// assert_eq!(
///     program.get_instruction(2),
///     Some(Instruction::DecrementPointer)
/// );
/// assert_eq!(
///     program.get_instruction(3),
///     Some(Instruction::DecrementValue)
/// );
/// assert_eq!(program.get_instruction(4), None);
/// ```
#[derive(PartialEq, Debug, Eq, Clone)]
pub struct Program {
    /// The instructions for the program
    instructions: Vec<Instruction>,
}

impl Program {
    /// Get an instruction from a `Program` at a specific index
    ///
    /// This method gets an instruction from the program at a specific index.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the instruction to get
    ///
    /// # Examples
    ///
    /// ```
    /// use brainfoamkit_lib::{
    ///     Instruction,
    ///     Program,
    /// };
    ///
    /// let instructions = ">>++<<--";
    /// let program = Program::from(instructions);
    ///
    /// assert_eq!(
    ///     program.get_instruction(0),
    ///     Some(Instruction::IncrementPointer)
    /// );
    /// assert_eq!(
    ///     program.get_instruction(1),
    ///     Some(Instruction::IncrementPointer)
    /// );
    /// assert_eq!(
    ///     program.get_instruction(2),
    ///     Some(Instruction::IncrementValue)
    /// );
    /// assert_eq!(
    ///     program.get_instruction(3),
    ///     Some(Instruction::IncrementValue)
    /// );
    /// assert_eq!(
    ///     program.get_instruction(4),
    ///     Some(Instruction::DecrementPointer)
    /// );
    /// assert_eq!(
    ///     program.get_instruction(5),
    ///     Some(Instruction::DecrementPointer)
    /// );
    /// assert_eq!(
    ///     program.get_instruction(6),
    ///     Some(Instruction::DecrementValue)
    /// );
    /// assert_eq!(
    ///     program.get_instruction(7),
    ///     Some(Instruction::DecrementValue)
    /// );
    /// assert_eq!(program.get_instruction(8), None);
    /// ```
    ///
    /// # Returns
    ///
    /// The `Instruction` at the given index
    ///
    /// # See Also
    ///
    /// * [`length()`](#method.length): Get the length of the program
    #[must_use]
    pub fn get_instruction(&self, index: usize) -> Option<Instruction> {
        self.length().and_then(|length| {
            if index >= length {
                None
            } else {
                Some(self.instructions[index])
            }
        })
    }

    /// Find the matching `JumpBackward` instruction for the given `JumpForward`
    /// instruction
    ///
    /// This method allows us to identify the boundaries of a given loop.
    /// It will return the index of the matching `JumpBackward` instruction for
    /// the given `JumpForward` instruction. It returns `None` if no
    /// matching `JumpBackward` instruction is found or the instruction
    /// at the given index is not a `JumpForward` instruction.
    ///
    /// # Examples
    ///
    /// ```
    /// use brainfoamkit_lib::{
    ///     Instruction,
    ///     Program,
    /// };
    ///
    /// let instructions = "[[]]";
    /// let mut program = Program::from(instructions);
    ///
    /// assert_eq!(program.find_matching_bracket(0), Some(3));
    /// assert_eq!(program.find_matching_bracket(1), Some(2));
    /// ```
    ///
    /// # Returns
    ///
    /// The index of the matching bracket
    ///
    /// # See Also
    ///
    /// * [`length()`](#method.length): Get the length of the program
    /// * [`get_instruction()`](#method.get_instruction): Get an instruction
    ///   from a `Program`
    #[must_use]
    pub fn find_matching_bracket(&self, index: usize) -> Option<usize> {
        match self.get_instruction(index) {
            Some(Instruction::JumpForward) => {
                let mut bracket_counter = 0;
                let mut index = index;

                loop {
                    match self.instructions.get(index) {
                        Some(Instruction::JumpForward) => bracket_counter += 1,
                        Some(Instruction::JumpBackward) => bracket_counter -= 1,
                        _ => (),
                    }

                    if bracket_counter == 0 {
                        break;
                    }

                    index += 1;
                }

                Some(index)
            }
            _ => None,
        }
    }

    /// Get the length of the program
    ///
    /// This method returns the length of the program.
    ///
    /// # Examples
    ///
    /// ```
    /// use brainfoamkit_lib::Program;
    ///
    /// let program_string = ">>++<<--";
    /// let program = Program::from(program_string);
    ///
    /// assert_eq!(program.length(), Some(8));
    /// ```
    ///
    /// # Returns
    ///
    /// The length of the program
    #[must_use]
    pub fn length(&self) -> Option<usize> {
        if self.instructions.is_empty() {
            None
        } else {
            Some(self.instructions.len())
        }
    }
}

impl Default for Program {
    fn default() -> Self {
        Self::from(vec![Instruction::NoOp; 10])
    }
}

impl Display for Program {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        for (index, instruction) in self.instructions.iter().enumerate() {
            // Index should be zero padded to 4 digits
            writeln!(f, "{index:04}: {instruction}")?;
        }
        Ok(())
    }
}

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

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

impl From<&str> for Program {
    /// Load a `Program` from a string
    ///
    /// This method loads a `Program` from a string.
    ///
    /// # Arguments
    ///
    /// * `program` - A string containing the program to load
    ///
    /// # Examples
    ///
    /// ```
    /// use brainfoamkit_lib::Program;
    ///
    /// let program_string = ">>++<<--";
    /// let program = Program::from(program_string);
    ///
    /// assert_eq!(program.length(), Some(8));
    /// ```
    ///
    /// # See Also
    ///
    /// * [`from()`](#method.from): Create a new `Program` from a series of
    ///   instructions
    fn from(program: &str) -> Self {
        let mut instructions = Vec::new();

        for c in program.chars() {
            instructions.push(Instruction::from_char(c));
        }

        Self { instructions }
    }
}

impl From<Vec<Instruction>> for Program {
    /// Create a new `Program` from a series of instructions
    ///
    /// This method creates a new `Program` from a series of instructions.
    ///
    /// # Arguments
    ///
    /// * `instructions` - A vector of `Instruction`s to load into the `Program`
    ///
    /// # Examples
    ///
    /// ```
    /// use brainfoamkit_lib::{
    ///     Instruction,
    ///     Program,
    /// };
    ///
    /// let instructions = vec![
    ///     Instruction::IncrementPointer,
    ///     Instruction::IncrementValue,
    ///     Instruction::DecrementPointer,
    ///     Instruction::DecrementValue,
    /// ];
    /// let program: Program = Program::from(instructions);
    ///
    /// assert_eq!(program.length(), Some(4));
    /// ```
    ///
    /// # See Also
    ///
    /// * [`from()`](#method.from): Load a `Program` from a string
    fn from(instructions: Vec<Instruction>) -> Self {
        Self { instructions }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_program_from() {
        let instructions = vec![Instruction::NoOp];
        let program = Program::from(instructions);

        assert_eq!(program.instructions.len(), 1);
        assert_eq!(program.length(), Some(1));
    }

    #[test]
    fn test_program_load_from() {
        let instructions = ">>++<<--";
        let program = Program::from(instructions);

        assert_eq!(program.instructions.len(), 8);
        assert_eq!(program.length(), Some(8));
    }

    #[test]
    fn test_program_length() {
        let program = Program::from(">>++<<--");
        assert_eq!(program.length(), Some(8));

        let program = Program::from("");
        assert_eq!(program.length(), None);
    }

    #[test]
    fn test_program_default() {
        let program = Program::default();

        assert_eq!(program.instructions.len(), 10);
        assert_eq!(program.length(), Some(10));
    }

    #[test]
    fn test_program_display() {
        let instructions = vec![Instruction::NoOp];
        let program = Program::from(instructions);

        assert_eq!(program.to_string(), "0000: NOOP\n");

        let instructions = vec![Instruction::NoOp, Instruction::NoOp];
        let program = Program::from(instructions);
        assert_eq!(program.to_string(), "0000: NOOP\n0001: NOOP\n");
    }

    #[test]
    fn test_program_find_matching_bracket() {
        let instructions = "[]";
        let program = Program::from(instructions);

        assert_eq!(program.find_matching_bracket(0), Some(1));
    }

    #[test]
    fn test_program_find_matching_bracket_nested() {
        let instructions = "[[]]";
        let program = Program::from(instructions);

        assert_eq!(program.find_matching_bracket(0), Some(3));
    }

    // #[test]
    // fn test_find_matching_bracket_no_match() {
    //     let instructions = "[";
    //     let program = Program::from(instructions);

    //     assert_eq!(program.find_matching_bracket(0), None);
    // }

    #[test]
    fn test_find_matching_bracket_not_jump_forward() {
        let instructions = "]";
        let program = Program::from(instructions);

        assert_eq!(program.find_matching_bracket(0), None);
    }

    #[test]
    fn test_get_instruction() {
        let instructions = vec![
            Instruction::IncrementPointer,
            Instruction::IncrementPointer,
            Instruction::IncrementValue,
            Instruction::IncrementValue,
            Instruction::DecrementPointer,
            Instruction::DecrementPointer,
            Instruction::DecrementValue,
            Instruction::DecrementValue,
        ];
        let program = Program::from(instructions);

        assert_eq!(
            program.get_instruction(0),
            Some(Instruction::IncrementPointer)
        );
        assert_eq!(
            program.get_instruction(1),
            Some(Instruction::IncrementPointer)
        );
        assert_eq!(
            program.get_instruction(2),
            Some(Instruction::IncrementValue)
        );
        assert_eq!(
            program.get_instruction(3),
            Some(Instruction::IncrementValue)
        );
        assert_eq!(
            program.get_instruction(4),
            Some(Instruction::DecrementPointer)
        );
        assert_eq!(
            program.get_instruction(5),
            Some(Instruction::DecrementPointer)
        );
        assert_eq!(
            program.get_instruction(6),
            Some(Instruction::DecrementValue)
        );
        assert_eq!(
            program.get_instruction(7),
            Some(Instruction::DecrementValue)
        );
        assert_eq!(program.get_instruction(8), None);
    }

    #[test]
    fn test_find_matching_bracket() {
        let instructions = vec![
            Instruction::JumpForward,
            Instruction::JumpForward,
            Instruction::JumpBackward,
            Instruction::JumpBackward,
        ];
        let program = Program::from(instructions);

        assert_eq!(program.find_matching_bracket(0), Some(3));
        assert_eq!(program.find_matching_bracket(1), Some(2));
        assert_eq!(program.find_matching_bracket(2), None);
        assert_eq!(program.find_matching_bracket(3), None);
    }

    #[test]
    fn test_default() {
        let program = Program::default();
        assert_eq!(program.length(), Some(10));
        assert_eq!(program.get_instruction(0), Some(Instruction::NoOp));
        assert_eq!(program.get_instruction(9), Some(Instruction::NoOp));
    }

    #[test]
    fn test_index() {
        let program = Program::from(">>++<<--");

        assert_eq!(program[0], Instruction::IncrementPointer);
        assert_eq!(program[1], Instruction::IncrementPointer);
        assert_eq!(program[2], Instruction::IncrementValue);
        assert_eq!(program[3], Instruction::IncrementValue);
        assert_eq!(program[4], Instruction::DecrementPointer);
        assert_eq!(program[5], Instruction::DecrementPointer);
        assert_eq!(program[6], Instruction::DecrementValue);
        assert_eq!(program[7], Instruction::DecrementValue);
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_index_out_of_bounds() {
        let program = Program::from(">>++<<--");
        let _ = program[8];
    }
}