Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 7 additions & 16 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@ edition = "2024"
publish = false

[dependencies]
clap = { version = "4.5", features = ["cargo", "color", "wrap_help", "suggestions"] }
itertools = "0.14"
clap = { version = "4.5", features = ["cargo", "color", "suggestions", "wrap_help"] }

[dev-dependencies]
paste = "1.0"

46 changes: 46 additions & 0 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use crate::{interpreter, program};
use clap::{Command, crate_name, crate_version};
use std::env;

mod run;
mod util;

#[derive(Debug)]
pub enum CliError {
IoError(std::io::Error),
ParsingError(program::Error),
Interpreter(interpreter::Error),
}

impl From<std::io::Error> for CliError {
fn from(error: std::io::Error) -> Self {
CliError::IoError(error)
}
}

impl From<program::Error> for CliError {
fn from(error: program::Error) -> Self {
CliError::ParsingError(error)
}
}

impl From<interpreter::Error> for CliError {
fn from(error: interpreter::Error) -> Self {
CliError::Interpreter(error)
}
}

pub fn run() -> Result<(), CliError> {
let matches = Command::new(crate_name!())
.version(crate_version!())
.about("Brainfuck interpreter")
.arg_required_else_help(true)
.subcommand_required(true)
.subcommand(run::build_command())
.get_matches();

match matches.subcommand() {
Some(("run", matches)) => run::execute(matches),
_ => unreachable!(),
}
}
77 changes: 77 additions & 0 deletions src/cli/run.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use super::CliError;
use crate::{cli::util, interpreter, program::Program};
use clap::{Arg, ArgAction, ArgMatches, Command, value_parser};
use std::{fs, io, time::Instant};

const DEFAULT_MEMORY_SIZE: usize = 32768;
const ARG_INPUT_FILE: &str = "input";
const ARG_MEMORY: &str = "memory";
const ARG_RUN_TIME: &str = "time";
const ARG_RUN_TIME_OPTIONS: [&str; 3] = ["total", "exec", "parse"];

pub fn build_command() -> Command {
Command::new("run")
.about("Parses Brainfuck in the specified file and interprets it")
.arg(
Arg::new(ARG_INPUT_FILE)
.help("The file to parse")
.index(1)
.required(true),
)
.arg(
Arg::new(ARG_MEMORY)
.help(format!(
"Sets the number of memory cells, defaults to {DEFAULT_MEMORY_SIZE:?}"
))
.long(ARG_MEMORY)
.value_parser(value_parser!(u32)),
)
.arg(
Arg::new(ARG_RUN_TIME)
.help("Prints time of various metrics")
.long(ARG_RUN_TIME)
.value_parser(ARG_RUN_TIME_OPTIONS)
.action(ArgAction::Append),
)
}

pub fn execute(matches: &ArgMatches) -> Result<(), CliError> {
let input_file = matches
.get_one::<String>(ARG_INPUT_FILE)
.expect("Input file is required");
let memory = *matches.get_one(ARG_MEMORY).unwrap_or(&DEFAULT_MEMORY_SIZE);
let time_metrics: Vec<&str> = matches
.get_many::<String>(ARG_RUN_TIME)
.unwrap_or_default()
.map(String::as_str)
.collect();

let total_start = Instant::now();
let contents = fs::read_to_string(input_file)?;
let program = Program::parse(&contents)?;
let program = program.optimized();
let parse_elapsed = total_start.elapsed();

let mut input = io::stdin();
let mut output = io::stdout();
let mut tape = interpreter::Tape::new(&mut input, &mut output, memory);

let exec_start = Instant::now();
tape.execute(&program)?;
let exec_elapsed = exec_start.elapsed();
let total_elapsed = total_start.elapsed();

if !time_metrics.is_empty() {
println!();
if time_metrics.contains(&"parse") {
println!("Parsing time: {}", util::format_duration(parse_elapsed));
}
if time_metrics.contains(&"exec") {
println!("Execution time: {}", util::format_duration(exec_elapsed));
}
if time_metrics.contains(&"total") {
println!("Total time: {}", util::format_duration(total_elapsed));
}
}
Ok(())
}
15 changes: 15 additions & 0 deletions src/cli/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use std::time::Duration;

pub fn format_duration(d: Duration) -> String {
let nanos = d.as_nanos();
[
(1_000_000_000, "s"),
(1_000_000, "ms"),
(1_000, "µs"),
(1, "ns"),
]
.iter()
.find(|&&(factor, _)| nanos >= factor)
.map(|&(factor, unit)| format!("{:.1}{unit}", nanos as f64 / factor as f64))
.unwrap_or_else(|| "pretty quick".to_string())
}
108 changes: 0 additions & 108 deletions src/interpreter.rs

This file was deleted.

Loading