Skip to content

Commit

Permalink
Added more verbose output
Browse files Browse the repository at this point in the history
  • Loading branch information
Naapperas committed Feb 11, 2024
1 parent c26ab16 commit 8ec0b0b
Show file tree
Hide file tree
Showing 7 changed files with 167 additions and 120 deletions.
3 changes: 1 addition & 2 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ use verbosity::Verbosity;

use serde::Deserialize;
use std::{fs, path::Path};
use toml;

#[derive(Default, Deserialize)]
pub struct Config {
pub verbosity: Verbosity,
}

pub static CONFIG_FILE_PATH: &'static str = "~/.config/crusterfuck/config.toml";
pub static CONFIG_FILE_PATH: &str = "~/.config/crusterfuck/config.toml";

pub fn parse<P>(path: P) -> Result<Config, ConfigErr>
where
Expand Down
12 changes: 6 additions & 6 deletions src/config/verbosity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ use serde::Deserialize;
#[derive(Default, Debug, Deserialize)]
pub enum VerbosityLevel {
#[default]
NONE,
None,

LOW,
Low,

MEDIUM,
Medium,

HIGH,
High,
}

#[derive(Default, Deserialize)]
pub struct Verbosity {
enabled: bool,
level: VerbosityLevel,
pub enabled: bool,
pub level: VerbosityLevel,
}
44 changes: 29 additions & 15 deletions src/interpreter/mod.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
use std::fmt;

use self::{ast::Token, io::IO};

pub mod ast;
mod io;
pub mod parser;

const BUFFER_SIZE: usize = 30000;

pub struct Interpreter {
data: [u8; 30000],
data: [u8; BUFFER_SIZE],
pointer: usize,
io: IO,
}

pub struct ProgramError {}

impl fmt::Display for ProgramError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
todo!()
}
}

impl Interpreter {
pub fn new() -> Self {
Interpreter {
data: [0; 30000],
data: [0; BUFFER_SIZE],
pointer: 0,
io: IO::new(),
}
Expand All @@ -25,8 +35,20 @@ impl Interpreter {
match token {
Token::Inc => self.data[self.pointer] += 1,
Token::Dec => self.data[self.pointer] -= 1,
Token::MoveLeft => self.pointer -= 1, // TODO: bounds checks
Token::MoveRight => self.pointer += 1, // TODO: bounds checks
Token::MoveLeft => {
if self.pointer == 0 {
return Err(ProgramError {});
}

self.pointer -= 1;
}
Token::MoveRight => {
if self.pointer == BUFFER_SIZE - 1 {
return Err(ProgramError {});
}

self.pointer += 1;
}
Token::Print => {
let current_byte = self.data[self.pointer];

Expand All @@ -39,11 +61,7 @@ impl Interpreter {

self.data[self.pointer] = character as u8;
}
Token::Loop(loop_tokens) => {
if let Err(err) = self.run_loop(loop_tokens) {
return Err(err);
}
}
Token::Loop(loop_tokens) => self.run_loop(loop_tokens)?,
};

Ok(())
Expand All @@ -52,9 +70,7 @@ impl Interpreter {
// TODO: see if we need to expose a non-mutable API
pub fn run(&mut self, tokens: parser::ParseResult) -> Result<(), ProgramError> {
for token in tokens {
if let Err(err) = self.process_token(token) {
return Err(err);
}
self.process_token(token)?
}

Ok(())
Expand All @@ -67,9 +83,7 @@ impl Interpreter {
}

for token in loop_tokens.clone() {
if let Err(err) = self.process_token(token) {
return Err(err);
}
self.process_token(token)?
}
}

Expand Down
76 changes: 34 additions & 42 deletions src/interpreter/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,56 +61,48 @@ impl Parser {
let mut line = 1;
let mut col = 1;

loop {
match token_stream.next() {
Some(token) => {
match token {
'+' | '-' | '>' | '<' | '.' | ',' => match self.process_op(token) {
Some(op_token) => tokens.push(op_token),
None => {
continue;
}
},
'[' => {
// Start loop construct

match self.parse_loop(token_stream.borrow_mut()) {
Ok((loop_token, line_delta, col_delta)) => {
// update current consumption location
if line_delta == 0 {
col += col_delta;
} else {
col = col_delta;
line += line_delta;
}

tokens.push(loop_token)
}
Err(e) => return Err(e),
while let Some(token) = token_stream.next() {
match token {
'+' | '-' | '>' | '<' | '.' | ',' => match self.process_op(token) {
Some(op_token) => tokens.push(op_token),
None => {
continue;
}
},
'[' => {
// Start loop construct

match self.parse_loop(token_stream.borrow_mut()) {
Ok((loop_token, line_delta, col_delta)) => {
// update current consumption location
if line_delta == 0 {
col += col_delta;
} else {
col = col_delta;
line += line_delta;
}
}
']' => {
// End loop construct

// We should never reach this execution path if the program is syntactically correct (because the loop parsing code consumes the closing bracket).
// It is correct to immediately return an error once we get here.

return Err(ParseError::SyntaxError(line, col, token));
tokens.push(loop_token)
}
'\n' => {
line += 1;
col = 0;
}
_ => {} // other characters are ignored
Err(e) => return Err(e),
}
}
']' => {
// End loop construct

col += 1;
// We should never reach this execution path if the program is syntactically correct (because the loop parsing code consumes the closing bracket).
// It is correct to immediately return an error once we get here.

return Err(ParseError::SyntaxError(line, col, token));
}
None => {
// We reached the end of the character stream, stop processing.
break;
'\n' => {
line += 1;
col = 0;
}
_ => {} // other characters are ignored
}

col += 1;
}

Ok(tokens)
Expand Down
43 changes: 36 additions & 7 deletions src/log.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,42 @@
use crate::config::{verbosity::Verbosity, Config};
use std::fmt;

pub struct Logger {
verbosity: Verbosity,
use crate::config::{verbosity::VerbosityLevel, Config};

pub struct Logger<'a> {
config: &'a Config,
}

impl Logger {
pub fn new_for(config: Config) -> Logger {
Logger {
verbosity: config.verbosity,
macro_rules! _log {
($name:ident, $levels:pat) => {
pub fn $name<M>(&self, message: M)
where
M: fmt::Display,
{
if self.config.verbosity.enabled {
return;
}

match self.config.verbosity.level {
$levels => {
println!("{}", message);
}
_ => {}
}
}
};
}

impl<'a> Logger<'a> {
pub fn new_for(config: &'a Config) -> Logger {
Logger { config }
}

_log!(high, VerbosityLevel::High);

_log!(medium, VerbosityLevel::High | VerbosityLevel::Medium);

_log!(
low,
VerbosityLevel::High | VerbosityLevel::Medium | VerbosityLevel::Low
);
}
22 changes: 15 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,35 @@ fn main() {

let config = match config::parse(args.config) {
Ok(config) => config,
Err(error) => match error {
config::err::ConfigErr::InvalidConfigValue(_, _) => todo!(),
},
Err(error) => {
eprintln!("{}", error);

exit(1)
}
};

let logger = log::Logger::new_for(config);
let logger = log::Logger::new_for(&config);

let parser = interpreter::parser::Parser::new();

logger.medium(format!("Parsing file: {}", args.input));

let tokens = match parser.parse_file(args.input) {
Ok(tokens) => tokens,
Err(err) => {
eprintln!("{}", err);
logger.high(format!("Error parsing file: {}", err));

exit(1);
exit(2);
}
};

logger.medium("Running Brainfuck program");

let mut interpreter = interpreter::Interpreter::new();

if let Err(err) = interpreter.run(tokens) {
exit(1); // TODO: better error handling
logger.high(format!("Error while running Brainfuck code: {}", err));

exit(3);
}
}
Loading

0 comments on commit 8ec0b0b

Please sign in to comment.