summary refs log tree commit diff
path: root/src/utility.rs
blob: 58ac3e29c8df463491c8af6188185afecd79f40a (plain) (blame)
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
//! Utility functions for working with the Brainfuck interpreter.

use std::path::Path;

use crate::{constants::TapeInner, lex, parse, Error, Executor};

/// Utility function to execute a Brainfuck file. Lexes, parses and executes the
/// input file.
///
/// # Errors
///
/// This function will return an error if reading the input file, parsing or
/// execution fails. See documentation for [`crate::parser::parse`] and
/// [`crate::executor::execute`].
pub fn execute_from_file(path: impl AsRef<Path>, tape: &mut [TapeInner]) -> Result<(), Error> {
	let input = fs_err::read_to_string(path.as_ref())?;

	let operator_codes = lex(&input);

	let instructions = parse(&input, &operator_codes)?;

	let mut data_pointer = 0;

	Executor::execute(&instructions, tape, &mut data_pointer)?;

	Ok(())
}

/// Utility function to execute Brainfuck code. Lexes, parses and executes the
/// input.
///
/// # Errors
///
/// This function will return an error if parsing or
/// execution fails. See documentation for [`crate::parser::parse`] and
/// [`crate::executor::execute`].
pub fn execute_from_str(input: &str, tape: &mut [TapeInner]) -> Result<(), Error> {
	let operator_codes = lex(input);

	let instructions = parse(input, &operator_codes)?;

	let mut data_pointer = 0;

	Executor::execute(&instructions, tape, &mut data_pointer)?;

	Ok(())
}