Skip to content

Commit

Permalink
lint(all): rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
hanmindev committed Feb 19, 2024
1 parent 4631b80 commit 9e40044
Show file tree
Hide file tree
Showing 14 changed files with 127 additions and 65 deletions.
2 changes: 1 addition & 1 deletion src/back/code_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@ pub fn flatten_to_hmasm(generated_code: &GeneratedCode) -> String {

#[cfg(test)]
mod tests {
use camino::Utf8PathBuf;
use crate::back::code_generator::{flatten_to_hmasm, generate_code};
use crate::front::file_system::fs::FileSystem;
use crate::front::file_system::mock_fs::MockFileSystem;
use crate::front::mergers::program::ProgramMerger;
use camino::Utf8PathBuf;

// TODO: these tests don't do anything at the moment, you should review it and make sure the output is correct.
// TODO: should add a mcfunction interpreter to test the output of the code generator
Expand Down
1 change: 0 additions & 1 deletion src/cli/arg_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ impl Display for CliMessage {
}
}


pub trait ArgRunner {
fn run(&self) -> CliMessage;
}
46 changes: 30 additions & 16 deletions src/cli/build.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use std::{fs, io};
use std::fs::File;
use std::io::{Error, Read, Write};
use camino::Utf8PathBuf;
use crate::cli::arg_runner::{ArgRunner, CliMessage};
use clap::Args;
use toml::{Table, Value};
use crate::back::code_generator::flatten_to_hmasm;
use crate::back::code_generator::generate_code;
use crate::cli::arg_runner::{ArgRunner, CliMessage};
use crate::front::file_system::fs::FileSystem;
use crate::front::file_system::system_fs::SystemFs;
use crate::front::mergers::program::ProgramMerger;
use crate::middle::passes::delete_unused::DeleteUnused;
use crate::middle::passes::optimize;
use crate::back::code_generator::flatten_to_hmasm;
use crate::front::file_system::fs::FileSystem;
use crate::front::file_system::system_fs::SystemFs;
use camino::Utf8PathBuf;
use clap::Args;
use std::fs::File;
use std::io::{Read, Write};
use std::{fs, io};
use toml::{Table, Value};

#[derive(Debug, Args)]
pub struct BuildArgs {
Expand All @@ -27,7 +27,10 @@ impl ArgRunner for BuildArgs {
let env_path = match Utf8PathBuf::try_from(std::env::current_dir().unwrap()) {
Ok(p) => p,
Err(e) => {
return CliMessage::Error(format!("Could not parse current directory, perhaps there is a non-Utf8 character?: {}", e));
return CliMessage::Error(format!(
"Could not parse current directory, perhaps there is a non-Utf8 character?: {}",
e
));
}
};

Expand Down Expand Up @@ -55,7 +58,9 @@ impl ArgRunner for BuildArgs {
return CliMessage::Error("Could not read the blastf.toml file.".to_string());
}
} else {
return CliMessage::Error("Could not find blastf.toml file, are you in the right directory?".to_string());
return CliMessage::Error(
"Could not find blastf.toml file, are you in the right directory?".to_string(),
);
}

let package_name = if let Ok(toml) = buf.parse::<Table>() {
Expand All @@ -67,10 +72,15 @@ impl ArgRunner for BuildArgs {
return CliMessage::Error("The name field in the package section of the blastf.toml file is not a string.".to_string());
}
} else {
return CliMessage::Error("The package section of the blastf.toml file does not have a name field.".to_string());
return CliMessage::Error(
"The package section of the blastf.toml file does not have a name field."
.to_string(),
);
}
} else {
return CliMessage::Error("The blastf.toml file does not have a package section.".to_string());
return CliMessage::Error(
"The blastf.toml file does not have a package section.".to_string(),
);
}
} else {
return CliMessage::Error("The blastf.toml file is not a valid toml file.".to_string());
Expand All @@ -89,11 +99,15 @@ impl ArgRunner for BuildArgs {
if let Err(e) = fs::create_dir(&abs_path.join("target")) {
match e.kind() {
io::ErrorKind::AlreadyExists => {}
_ => return CliMessage::Error(format!("Could not create directory 'target'. Error: {}", e)),
_ => {
return CliMessage::Error(format!(
"Could not create directory 'target'. Error: {}",
e
))
}
}
}


let target = abs_path.join(format!("target/{package_name}.hmasm"));

return if let Ok(mut fs) = File::create(&target) {
Expand Down
47 changes: 35 additions & 12 deletions src/cli/new.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::fs::File;
use std::io::Write;
use crate::cli::arg_runner::{ArgRunner, CliMessage};
use camino::Utf8PathBuf;
use clap::Args;
use std::fs::File;
use std::io::Write;

#[derive(Debug, Args)]
pub struct NewArgs {
Expand All @@ -19,12 +19,18 @@ impl ArgRunner for NewArgs {
let path = match Utf8PathBuf::try_from(std::env::current_dir().unwrap()) {
Ok(p) => p,
Err(e) => {
return CliMessage::Error(format!("Could not parse current directory, perhaps there is a non-Utf8 character?: {}", e));
return CliMessage::Error(format!(
"Could not parse current directory, perhaps there is a non-Utf8 character?: {}",
e
));
}
};

if self.path.extension() != None {
return CliMessage::Error(format!("The path specified is not a directory: {:?}", self.path));
return CliMessage::Error(format!(
"The path specified is not a directory: {:?}",
self.path
));
}

let abs_path = if self.path.is_relative() {
Expand All @@ -46,29 +52,46 @@ impl ArgRunner for NewArgs {
if abs_path.try_exists().unwrap_or(false) {
if let Ok(files) = abs_path.read_dir() {
if files.count() > 0 {
return CliMessage::Error(format!("The directory specified is not empty: {:?}", abs_path));
return CliMessage::Error(format!(
"The directory specified is not empty: {:?}",
abs_path
));
}
} else {
return CliMessage::Error(format!("Could not read the directory specified: {:?}", abs_path));
return CliMessage::Error(format!(
"Could not read the directory specified: {:?}",
abs_path
));
}
} else {
if let Err(_) = std::fs::create_dir(&abs_path) {
return CliMessage::Error(String::from("Could not create the directory specified. Check permissions and try again."));
return CliMessage::Error(String::from(
"Could not create the directory specified. Check permissions and try again.",
));
}
}


let mut file = File::create(abs_path.join("blastf.toml")).unwrap();
if let Err(_) = file.write_all(format!("[package]\nname = \"{name}\"\nversion = \"0.1.0\"").as_ref()) {
if let Err(_) =
file.write_all(format!("[package]\nname = \"{name}\"\nversion = \"0.1.0\"").as_ref())
{
return CliMessage::Error(String::from("[ERROR]: Could not write blastf.toml."));
}
if let Err(_) = std::fs::create_dir(&abs_path.join("./src")) {
return CliMessage::Error(String::from("Could not create the directory specified. Check permissions and try again."));
return CliMessage::Error(String::from(
"Could not create the directory specified. Check permissions and try again.",
));
}

let mut file = File::create(abs_path.join("./src/main.ing")).unwrap();
if let Err(_) = file.write("pub fn main() {\n\tlet a: int = 5;\n\tprintln!(a);\n}".to_string().as_ref()) {
return CliMessage::Error(String::from("Could not write to file. Check permissions and try again."));
if let Err(_) = file.write(
"pub fn main() {\n\tlet a: int = 5;\n\tprintln!(a);\n}"
.to_string()
.as_ref(),
) {
return CliMessage::Error(String::from(
"Could not write to file. Check permissions and try again.",
));
}

CliMessage::Message(format!("Created new project {:?} at: {:?}", name, abs_path))
Expand Down
2 changes: 1 addition & 1 deletion src/front.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ pub mod mergers;

#[cfg(test)]
mod tests {
use camino::Utf8PathBuf;
use crate::front::file_system::fs::FileSystem;
use crate::front::file_system::mock_fs::MockFileSystem;
use crate::front::mergers::program::ProgramMerger;
use camino::Utf8PathBuf;

#[test]
fn test_simple_program() {
Expand Down
2 changes: 1 addition & 1 deletion src/front/ast_retriever/reader/lexical/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ impl Lexer {
let mut ident = String::new();

// read word and set to ident
while self.curr.is_alphanumeric() || self.curr == '_' || self.curr == '-'{
while self.curr.is_alphanumeric() || self.curr == '_' || self.curr == '-' {
ident.push(self.eat());
}

Expand Down
12 changes: 8 additions & 4 deletions src/front/ast_retriever/retriever.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ impl<T: FileSystem> FileRetriever<T> {

let module_path = file_path_ext.with_extension("");

if self.file_system.enter_dir(module_path.clone()).unwrap_or(false) {
if self
.file_system
.enter_dir(module_path.clone())
.unwrap_or(false)
{
self.read_nodes_rec(&mut module);
self.file_system.exit_dir();
}
Expand Down Expand Up @@ -119,10 +123,10 @@ impl<T: FileSystem> FileRetriever<T> {

#[cfg(test)]
mod tests {
use camino::Utf8PathBuf;
use super::*;
use crate::front::ast_retriever::retriever::ModuleNode;
use crate::front::file_system::mock_fs::MockFileSystem;
use camino::Utf8PathBuf;

#[test]
fn test_read_rec() {
Expand All @@ -147,15 +151,15 @@ mod tests {
assert_eq!(
file_retriever.modules.get("/root/test"),
Some(&ModuleNode {
file_path: Utf8PathBuf::from("test.ing"),
file_path: Utf8PathBuf::from("test.ing"),
submodules: HashMap::from([("/root/test/example".to_string(), None)]),
module: None,
})
);
assert_eq!(
file_retriever.modules.get("/root/test/example"),
Some(&ModuleNode {
file_path: Utf8PathBuf::from("test/example.ing"),
file_path: Utf8PathBuf::from("test/example.ing"),
submodules: HashMap::new(),
module: None,
})
Expand Down
6 changes: 4 additions & 2 deletions src/front/file_system/fs.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use camino::Utf8PathBuf;
use crate::front::file_system::byte_stream::ByteStream;
use camino::Utf8PathBuf;

pub type AbsUtf8PathBuf = Utf8PathBuf;
pub type RelUtf8PathBuf = Utf8PathBuf;
Expand All @@ -17,7 +17,9 @@ pub type FileSystemResult<T> = Result<T, FileSystemError>;
pub trait FileSystem {
// paths must be relative to root
// the absolute root should never be returned
fn new(root: AbsUtf8PathBuf) -> FileSystemResult<Self> where Self: Sized;
fn new(root: AbsUtf8PathBuf) -> FileSystemResult<Self>
where
Self: Sized;
fn ls_files_with_extension(&self, extension: &str) -> Vec<RelUtf8PathBuf>;
fn read_file(&self, file_path: RelUtf8PathBuf) -> FileSystemResult<ByteStream>;
fn check_dir(&self, path: RelUtf8PathBuf) -> FileSystemResult<bool>;
Expand Down
21 changes: 15 additions & 6 deletions src/front/file_system/mock_fs.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::front::file_system::byte_stream::{ByteStream, StringReader};
use crate::front::file_system::fs::{AbsUtf8PathBuf, FileSystem, FileSystemError, FileSystemResult, RelUtf8PathBuf};
use std::collections::{HashMap, HashSet};
use crate::front::file_system::fs::{
AbsUtf8PathBuf, FileSystem, FileSystemError, FileSystemResult, RelUtf8PathBuf,
};
use camino::Utf8PathBuf;
use std::collections::{HashMap, HashSet};

pub struct MockFileSystem {
rel_dir: RelUtf8PathBuf,
Expand All @@ -23,7 +25,8 @@ impl FileSystem for MockFileSystem {
for (path, _) in self.files.iter() {
match path.strip_prefix(&self.rel_dir) {
Ok(stripped_path) => {
if stripped_path.extension() == Some(extension) && stripped_path.parent() == Some(&Utf8PathBuf::new())
if stripped_path.extension() == Some(extension)
&& stripped_path.parent() == Some(&Utf8PathBuf::new())
{
files.push(path.clone());
}
Expand All @@ -37,7 +40,9 @@ impl FileSystem for MockFileSystem {
}

fn read_file(&self, file_path: RelUtf8PathBuf) -> FileSystemResult<ByteStream> {
if !file_path.is_relative() { return Err(FileSystemError::NotRelative); }
if !file_path.is_relative() {
return Err(FileSystemError::NotRelative);
}

match self.files.get(&file_path) {
Some(content) => Ok(ByteStream::new(Box::new(StringReader::new(
Expand All @@ -48,13 +53,17 @@ impl FileSystem for MockFileSystem {
}

fn check_dir(&self, path: RelUtf8PathBuf) -> FileSystemResult<bool> {
if !path.is_relative() { return Err(FileSystemError::NotRelative); }
if !path.is_relative() {
return Err(FileSystemError::NotRelative);
}

Ok(self.dirs.contains(&path))
}

fn enter_dir(&mut self, path: RelUtf8PathBuf) -> FileSystemResult<bool> {
if !path.is_relative() { return Err(FileSystemError::NotRelative); }
if !path.is_relative() {
return Err(FileSystemError::NotRelative);
}

Ok(if self.dirs.contains(&path) {
self.rel_dir = path;
Expand Down
21 changes: 16 additions & 5 deletions src/front/file_system/system_fs.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::front::file_system::byte_stream::{ByteStream, ByteStreamable};
use crate::front::file_system::fs::{FileSystem, FileSystemError, FileSystemResult, AbsUtf8PathBuf, RelUtf8PathBuf};
use crate::front::file_system::fs::{
AbsUtf8PathBuf, FileSystem, FileSystemError, FileSystemResult, RelUtf8PathBuf,
};
use std::fs;
use std::fs::File;
use std::io::Read;
Expand Down Expand Up @@ -50,9 +52,14 @@ impl SystemFs {
}
impl FileSystem for SystemFs {
fn new(root: AbsUtf8PathBuf) -> FileSystemResult<SystemFs> {
if !root.is_absolute() { return Err(FileSystemError::NotAbsolute); }
if !root.is_absolute() {
return Err(FileSystemError::NotAbsolute);
}

Ok(SystemFs { root_dir: root, current_dir: RelUtf8PathBuf::new() })
Ok(SystemFs {
root_dir: root,
current_dir: RelUtf8PathBuf::new(),
})
}

fn ls_files_with_extension(&self, extension: &str) -> Vec<RelUtf8PathBuf> {
Expand All @@ -79,13 +86,17 @@ impl FileSystem for SystemFs {
}

fn check_dir(&self, path: RelUtf8PathBuf) -> FileSystemResult<bool> {
if !path.is_relative() { return Err(FileSystemError::NotRelative); }
if !path.is_relative() {
return Err(FileSystemError::NotRelative);
}

Ok(self.root_dir.join(&path).is_dir())
}

fn enter_dir(&mut self, path: RelUtf8PathBuf) -> FileSystemResult<bool> {
if !path.is_relative() { return Err(FileSystemError::NotRelative); }
if !path.is_relative() {
return Err(FileSystemError::NotRelative);
}

Ok(if self.check_dir(path.clone())? {
self.current_dir = path;
Expand Down
6 changes: 4 additions & 2 deletions src/front/mergers/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,9 +594,9 @@ mod tests {
Address, AddressOrigin, CompareOp, Cond, IrScoreOperationType, IrStatement,
};
use crate::middle::format::types::GlobalName;
use camino::Utf8PathBuf;
use std::collections::HashMap;
use std::ops::Deref;
use camino::Utf8PathBuf;

fn test_calculation(
run_function: &str,
Expand Down Expand Up @@ -736,7 +736,9 @@ mod tests {
fn test_convert_simple() {
let mut mock_file_system = MockFileSystem::new(Utf8PathBuf::new()).unwrap();
mock_file_system.insert_file(
Utf8PathBuf::from("main.ing"), "pub fn main() { let a: int = 1; }");
Utf8PathBuf::from("main.ing"),
"pub fn main() { let a: int = 1; }",
);

let mut program_merger = ProgramMerger::new("pkg");

Expand Down
Loading

0 comments on commit 9e40044

Please sign in to comment.