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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// * Copyright (c) 2023
// *
// * This project is dual-licensed under the MIT and Apache licenses.
// *
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// ** APACHE 2.0 LICENSE
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// ** MIT LICENSE
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// *
// * Permission is hereby granted, free of charge, to any person obtaining a
// * copy
// * of this software and associated documentation files (the "Software"), to
// * deal
// * in the Software without restriction, including without limitation the
// * rights
// * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// * copies of the Software, and to permit persons to whom the Software is
// * furnished to do so, subject to the following conditions:
// *
// * The above copyright notice and this permission notice shall be included in
// * all
// * copies or substantial portions of the Software.
// *
// * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// * FROM,
// * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// * THE
// * SOFTWARE.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

use crate::{
    Byte,
    Instruction,
    Program,
    VirtualMachineBuilder,
};

/// `VirtualMachine` is a struct representing a Virtual Machine capable of
/// interpreting a `BrainFuck` program and tracking its state.
///
/// # Fields
///
/// * `tape`: A vector of `Byte` values representing the memory of the machine.
///  Each `Byte` in the vector is a cell in the memory tape.
/// * `program`: A `Program` instance representing the Brainfuck program that
/// the machine is executing.
/// * `memory_pointer`: A `usize` value representing the current position of
/// the memory pointer. The memory pointer points to a given cell in the memory
/// tape.
/// * `program_counter`: A `usize` that represents which instruction of the
/// `Program` is being executed right now.
///
/// # Example
///
/// ```
/// use brainfoamkit_lib::VirtualMachine;
///
/// let machine = VirtualMachine::default();
/// ```
#[allow(clippy::module_name_repetitions)]
pub struct VirtualMachine {
    tape:            Vec<Byte>,
    program:         Program,
    memory_pointer:  usize,
    program_counter: usize,
}

#[allow(dead_code)]
#[allow(clippy::len_without_is_empty)]
impl VirtualMachine {
    pub(crate) fn new(
        tape_size: usize,
        program: Program,
        memory_pointer: usize,
        program_counter: usize,
    ) -> Self {
        Self {
            tape: vec![Byte::default(); tape_size],
            program,
            memory_pointer,
            program_counter,
        }
    }

    /// Return the length of the "memory" or the `tape_size` of the
    /// `VirtualMachine`.
    ///
    /// This method is an alias for the [`length`](#method.length) method.
    ///
    /// # Returns
    ///
    /// A `usize` value representing the length of the `VirtualMachine`.
    ///
    /// # Example
    ///
    /// ```
    /// use brainfoamkit_lib::VirtualMachine;
    ///
    /// let machine = VirtualMachine::builder().tape_size(10).build();
    /// assert_eq!(machine.length(), 10);
    /// ```
    ///
    /// # See Also
    ///
    /// * [`length`](#method.length)
    /// * [`memory_pointer`](#method.memory_pointer)
    /// * [`program_counter`](#method.program_counter)
    #[must_use]
    pub(crate) fn tape_size(&self) -> usize {
        self.length()
    }

    /// Return the `Program` of the `VirtualMachine`.
    ///
    /// This method returns the `Program` of the `VirtualMachine`.
    ///
    /// # Returns
    ///
    /// A `Program` instance representing the `Program` of the `VirtualMachine`.
    ///
    /// # Example
    ///
    /// ```
    /// use brainfoamkit_lib::{
    ///     Program,
    ///     VirtualMachine,
    /// };
    ///
    /// let machine = VirtualMachine::builder().build();
    /// assert_eq!(machine.program(), Program::default());
    /// ```
    #[must_use]
    pub fn program(&self) -> Program {
        self.program.clone()
    }

    /// Create a new instance of `VirtualMachine` using `VirtualMachineBuilder`.
    ///
    /// This method provides a convenient way to create a new instance of
    /// `VirtualMachine` using `VirtualMachineBuilder`. This method returns
    /// a `VirtualMachineBuilder` instance that can be used to configure the
    /// `VirtualMachine` before building it.
    ///
    /// # Returns
    ///
    /// A `VirtualMachineBuilder` instance that can be used to configure the
    /// `VirtualMachine` before building it.
    ///
    /// # Example
    ///
    /// ```
    /// use brainfoamkit_lib::VirtualMachine;
    ///
    /// let machine = VirtualMachine::builder().build();
    /// ```
    ///
    /// # See Also
    ///
    /// * [`VirtualMachineBuilder`](struct.VirtualMachineBuilder.html)
    #[must_use]
    pub const fn builder() -> VirtualMachineBuilder {
        VirtualMachineBuilder::new()
    }

    /// Returns the length of the `tape` inside the `VirtualMachine`.
    ///
    /// This method returns the length of the `tape` vector of the
    /// `VirtualMachine`.
    ///
    /// # Returns
    ///
    /// A `usize` value representing the length of the `VirtualMachine`.
    ///
    /// # Example
    ///
    /// ```
    /// use brainfoamkit_lib::VirtualMachine;
    ///
    /// let machine = VirtualMachine::builder().tape_size(10).build();
    /// assert_eq!(machine.length(), 10);
    /// ```
    #[must_use]
    pub fn length(&self) -> usize {
        self.tape.len()
    }

    /// Returns the current position of the memory pointer.
    ///
    /// This method returns the current position of the memory pointer in the
    /// `VirtualMachine`.
    ///
    /// # Returns
    ///
    /// A `usize` value representing the current position of the memory pointer.
    ///
    /// # Example
    ///
    /// ```
    /// use brainfoamkit_lib::VirtualMachine;
    ///
    /// let machine = VirtualMachine::builder().build();
    /// assert_eq!(machine.memory_pointer(), 0);
    /// ```
    #[must_use]
    pub const fn memory_pointer(&self) -> usize {
        self.memory_pointer
    }

    /// Returns the current position of the program counter.
    ///
    /// This method returns the current position of the program counter in the
    /// `VirtualMachine`.
    ///
    /// # Returns
    ///
    /// A `usize` value representing the current position of the program
    /// counter.
    ///
    /// # Example
    ///
    /// ```
    /// use brainfoamkit_lib::VirtualMachine;
    ///
    /// let machine = VirtualMachine::builder().build();
    /// assert_eq!(machine.program_counter(), 0);
    /// ```
    #[must_use]
    pub const fn program_counter(&self) -> usize {
        self.program_counter
    }

    /// Returns the current instruction of the `VirtualMachine`.
    ///
    /// This method returns the instruction at the current position of the
    /// program counter in the program. If the program counter is out of
    /// bounds of the program, this method returns `None`.
    ///
    /// # Returns
    ///
    /// An `Option` that contains the current instruction if the program counter
    /// is within the bounds of the program, or `None` if the program
    /// counter is out of bounds.
    ///
    /// # Example
    ///
    /// ```
    /// use brainfoamkit_lib::{
    ///     Instruction,
    ///     Program,
    ///     VirtualMachine,
    /// };
    ///
    /// let program = Program::from(vec![
    ///     Instruction::IncrementPointer,
    ///     Instruction::IncrementValue,
    /// ]);
    /// let mut machine = VirtualMachine::builder().program(program).build();
    /// assert_eq!(
    ///     machine.get_instruction(),
    ///     Some(Instruction::IncrementPointer)
    /// );
    /// machine.execute_instruction();
    /// assert_eq!(machine.get_instruction(), Some(Instruction::IncrementValue));
    /// machine.execute_instruction();
    /// assert_eq!(machine.get_instruction(), None);
    /// ```
    #[must_use]
    pub fn get_instruction(&self) -> Option<Instruction> {
        self.program.get_instruction(self.program_counter)
    }

    /// Executes the current instruction of the `VirtualMachine`.
    ///
    /// This method executes the instruction at the current position of the
    /// memory pointer in the program. If the memory pointer is out of bounds of
    /// the program, this method does nothing.
    ///
    /// # Example
    ///
    /// ```
    /// use brainfoamkit_lib::{
    ///     Instruction,
    ///     Program,
    ///     VirtualMachine,
    /// };
    ///
    /// let program = Program::from(vec![
    ///     Instruction::IncrementPointer,
    ///     Instruction::IncrementValue,
    /// ]);
    /// let mut machine = VirtualMachine::builder().program(program).build();
    /// assert_eq!(machine.memory_pointer(), 0);
    /// machine.execute_instruction();
    /// assert_eq!(machine.memory_pointer(), 1);
    /// machine.execute_instruction();
    /// assert_eq!(machine.memory_pointer(), 1);
    /// ```
    pub fn execute_instruction(&mut self) {
        let current_instruction = self.get_instruction().unwrap_or(Instruction::NoOp);
        match current_instruction {
            Instruction::IncrementPointer => self.increment_pointer(),
            Instruction::DecrementPointer => self.decrement_pointer(),
            Instruction::IncrementValue => self.increment_value(),
            Instruction::DecrementValue => self.decrement_value(),
            Instruction::OutputValue => self.output_value(),
            Instruction::InputValue => self.input_value(),
            Instruction::JumpForward => self.jump_forward(),
            Instruction::JumpBackward => self.jump_backward(),
            Instruction::NoOp => {}
        }
        self.program_counter += 1;
    }

    fn increment_pointer(&mut self) {
        self.memory_pointer += 1;
    }

    fn decrement_pointer(&mut self) {
        self.memory_pointer -= 1;
    }

    fn increment_value(&mut self) {
        self.tape[self.memory_pointer].increment();
    }

    fn decrement_value(&mut self) {
        self.tape[self.memory_pointer].decrement();
    }

    fn output_value(&mut self) {
        todo!("Implement output_value")
    }

    fn input_value(&mut self) {
        todo!("Implement input_value")
    }

    fn jump_forward(&mut self) {
        todo!("Implement jump_forward")
    }

    fn jump_backward(&mut self) {
        todo!("Implement jump_backward")
    }
}

impl Default for VirtualMachine {
    fn default() -> Self {
        Self::builder().build()
    }
}

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

    #[test]
    fn test_machine_get_instruction() {
        let instructions = vec![
            Instruction::IncrementPointer,
            Instruction::DecrementPointer,
            Instruction::IncrementValue,
            Instruction::DecrementValue,
            Instruction::OutputValue,
            Instruction::InputValue,
            Instruction::JumpForward,
            Instruction::JumpBackward,
            Instruction::NoOp,
        ];
        let program = Program::from(instructions);
        let machine = VirtualMachine::builder().program(program).build();
        assert_eq!(
            machine.get_instruction(),
            Some(Instruction::IncrementPointer)
        );
    }

    #[test]
    fn test_machine_execute_instruction() {
        let program = Program::from(vec![
            Instruction::IncrementPointer,
            Instruction::IncrementValue,
            Instruction::DecrementValue,
            Instruction::DecrementPointer,
        ]);
        let mut machine = VirtualMachine::builder().program(program).build();

        machine.execute_instruction();
        assert_eq!(
            machine.memory_pointer(),
            1,
            "Memory pointer should be incremented"
        );
        assert_eq!(
            machine.program_counter(),
            1,
            "Program counter should be incremented"
        );

        machine.execute_instruction();
        assert_eq!(
            machine.tape[1],
            Byte::from_u8(0b0000_0001),
            "Value at memory pointer should be incremented"
        );
        assert_eq!(
            machine.memory_pointer(),
            1,
            "Memory pointer should not be changed"
        );
        assert_eq!(
            machine.program_counter(),
            2,
            "Program counter should be incremented"
        );

        machine.execute_instruction();
        assert_eq!(
            machine.tape[1],
            Byte::from_u8(0),
            "Value at memory pointer should be decremented"
        );
        assert_eq!(
            machine.memory_pointer(),
            1,
            "Memory pointer should not be decremented"
        );
        assert_eq!(
            machine.program_counter(),
            3,
            "Program counter should be incremented"
        );

        machine.execute_instruction();
        assert_eq!(
            machine.memory_pointer(),
            0,
            "Memory pointer should be decremented"
        );
        assert_eq!(
            machine.program_counter(),
            4,
            "Program counter should be incremented"
        );
    }

    #[test]
    fn test_memory_pointer() {
        let machine = VirtualMachine::builder().build();
        assert_eq!(
            machine.memory_pointer(),
            0,
            "Memory pointer should be initialized to 0"
        );
    }

    #[test]
    fn test_program_counter() {
        let machine = VirtualMachine::builder().build();
        assert_eq!(
            machine.program_counter(),
            0,
            "Program counter should be initialized to 0"
        );
    }

    #[test]
    fn test_increment_pointer() {
        let mut machine = VirtualMachine::default();
        machine.increment_pointer();
        assert_eq!(
            machine.memory_pointer(),
            1,
            "Memory pointer should be incremented"
        );
    }

    #[test]
    fn test_decrement_pointer() {
        let mut machine = VirtualMachine::new(100, Program::default(), 1, 0);
        machine.decrement_pointer();
        assert_eq!(
            machine.memory_pointer(),
            0,
            "Memory pointer should be decremented"
        );
    }

    #[test]
    fn test_increment_value() {
        let mut machine = VirtualMachine::default();
        let increment_result = Byte::from_u8(1);

        machine.increment_value();
        assert_eq!(
            machine.tape[0], increment_result,
            "Value at memory pointer should be incremented"
        );
    }

    #[test]
    fn test_decrement_value() {
        let mut machine = VirtualMachine::default();
        machine.tape[0] = Byte::from_u8(1);
        machine.decrement_value();
        assert_eq!(
            machine.tape[0],
            Byte::from_u8(0),
            "Value at memory pointer should be decremented"
        );
    }

    #[test]
    #[should_panic(expected = "not yet implemented")]
    fn test_output_value() {
        let mut machine = VirtualMachine::default();
        machine.output_value();
    }

    #[test]
    #[should_panic(expected = "not yet implemented")]
    fn test_input_value() {
        let mut machine = VirtualMachine::default();
        machine.input_value();
    }

    #[test]
    #[should_panic(expected = "not yet implemented")]
    fn test_jump_forward() {
        let mut machine = VirtualMachine::default();
        machine.jump_forward();
    }

    #[test]
    #[should_panic(expected = "not yet implemented")]
    fn test_jump_backward() {
        let mut machine = VirtualMachine::default();
        machine.jump_backward();
    }
}