Skip to content

Commit

Permalink
fix: fix clippy issues (#349)
Browse files Browse the repository at this point in the history
Signed-off-by: lxl66566 <lxl66566@gmail.com>
  • Loading branch information
lxl66566 authored Jul 26, 2024
1 parent 1f7dc08 commit 226f725
Show file tree
Hide file tree
Showing 16 changed files with 139 additions and 120 deletions.
82 changes: 54 additions & 28 deletions src/compiler.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
extern crate chrono;
use chrono::prelude::*;
use crate::docs::module::DocumentationModule;
use itertools::Itertools;
use crate::modules::block::Block;
use crate::modules::formatter::BashFormatter;
use crate::{rules, Cli};
use crate::translate::check_all_blocks;
use crate::translate::module::TranslateModule;
use crate::utils::{ParserMetadata, TranslateMetadata};
use std::fs::File;
use std::io::Write;
use crate::{rules, Cli};
use chrono::prelude::*;
use colored::Colorize;
use heraclitus_compiler::prelude::*;
use itertools::Itertools;
use std::env;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, ExitStatus};
use std::time::Instant;
Expand All @@ -25,22 +25,22 @@ const AMBER_DEBUG_TIME: &str = "AMBER_DEBUG_TIME";
pub struct AmberCompiler {
pub cc: Compiler,
pub path: Option<String>,
pub cli_opts: Cli
pub cli_opts: Cli,
}

impl AmberCompiler {
pub fn new(code: String, path: Option<String>, cli_opts: Cli) -> AmberCompiler {
AmberCompiler {
cc: Compiler::new("Amber", rules::get_rules()),
path,
cli_opts
cli_opts,
}
.load_code(AmberCompiler::strip_off_shebang(code))
}

fn strip_off_shebang(code: String) -> String {
if code.starts_with("#!") {
code.split("\n").into_iter().skip(1).collect_vec().join("\n")
code.split('\n').skip(1).collect_vec().join("\n")
} else {
code
}
Expand Down Expand Up @@ -89,7 +89,11 @@ impl AmberCompiler {
}
}

pub fn parse(&self, tokens: Vec<Token>, is_docs_gen: bool) -> Result<(Block, ParserMetadata), Message> {
pub fn parse(
&self,
tokens: Vec<Token>,
is_docs_gen: bool,
) -> Result<(Block, ParserMetadata), Message> {
let code = self.cc.code.as_ref().expect(NO_CODE_PROVIDED).clone();
let mut meta = ParserMetadata::new(tokens, self.path.clone(), Some(code));
meta.is_docs_gen = is_docs_gen;
Expand Down Expand Up @@ -119,13 +123,21 @@ impl AmberCompiler {
}
}

pub fn get_sorted_ast_forest(&self, block: Block, meta: &ParserMetadata) -> Vec<(String, Block)> {
pub fn get_sorted_ast_forest(
&self,
block: Block,
meta: &ParserMetadata,
) -> Vec<(String, Block)> {
let imports_sorted = meta.import_cache.topological_sort();
let imports_blocks = meta
.import_cache
.files
.iter()
.map(|file| file.metadata.as_ref().map(|meta| (file.path.clone(), meta.block.clone())))
.map(|file| {
file.metadata
.as_ref()
.map(|meta| (file.path.clone(), meta.block.clone()))
})
.collect::<Vec<Option<(String, Block)>>>();
let mut result = vec![];
for index in imports_sorted.iter() {
Expand Down Expand Up @@ -153,27 +165,39 @@ impl AmberCompiler {
time.elapsed().as_millis()
);
}

let mut res = result.join("\n");

if !self.cli_opts.disable_format {
if let Some(formatter) = BashFormatter::get_available() {
res = formatter.format(res);
}
}

let header = [
include_str!("header.sh"),
&("# version: ".to_owned() + option_env!("CARGO_PKG_VERSION").unwrap().to_string().as_str()),
&("# date: ".to_owned() + Local::now().format("%Y-%m-%d %H:%M:%S").to_string().as_str())
].join("\n");
&("# version: ".to_owned() + env!("CARGO_PKG_VERSION").to_string().as_str()),
&("# date: ".to_owned()
+ Local::now()
.format("%Y-%m-%d %H:%M:%S")
.to_string()
.as_str()),
]
.join("\n");
format!("{}\n{}", header, res)
}

pub fn document(&self, block: Block, meta: ParserMetadata, output: String) {
let base_path = PathBuf::from(meta.get_path().expect("Input file must exist in docs generation"));
let base_dir = fs::canonicalize(base_path)
.map(|val| val.parent().expect("Parent dir must exist in docs generation").to_owned().clone());
let base_path = PathBuf::from(
meta.get_path()
.expect("Input file must exist in docs generation"),
);
let base_dir = fs::canonicalize(base_path).map(|val| {
val.parent()
.expect("Parent dir must exist in docs generation")
.to_owned()
.clone()
});
if let Err(err) = base_dir {
Message::new_err_msg("Couldn't get the absolute path to the provided input file")
.comment(err.to_string())
Expand All @@ -186,12 +210,12 @@ impl AmberCompiler {
let dep_path = {
let dep_path = fs::canonicalize(PathBuf::from(path.clone()));
if dep_path.is_err() {
continue
continue;
}
let dep_path = dep_path.unwrap();

if !dep_path.starts_with(&base_dir) {
continue
continue;
}

dep_path
Expand All @@ -204,9 +228,11 @@ impl AmberCompiler {
format!("{}/{output}/{}", base_dir.to_string_lossy(), parent)
};
if let Err(err) = fs::create_dir_all(dir_path.clone()) {
Message::new_err_msg(format!("Couldn't create directory `{dir_path}`. Do you have sufficient permissions?"))
.comment(err.to_string())
.show();
Message::new_err_msg(format!(
"Couldn't create directory `{dir_path}`. Do you have sufficient permissions?"
))
.comment(err.to_string())
.show();
std::process::exit(1);
}
let filename = dep_path.file_stem().unwrap().to_string_lossy();
Expand All @@ -224,16 +250,17 @@ impl AmberCompiler {

pub fn execute(code: String, flags: &[String]) -> Result<ExitStatus, std::io::Error> {
let code = format!("set -- {};\n\n{}", flags.join(" "), code);
Ok(Command::new("/usr/bin/env")
Command::new("/usr/bin/env")
.arg("bash")
.arg("-c")
.arg(code)
.spawn()?
.wait()?)
.wait()
}

pub fn generate_docs(&self, output: String) -> Result<(), Message> {
self.tokenize().and_then(|tokens| self.parse(tokens, true))
self.tokenize()
.and_then(|tokens| self.parse(tokens, true))
.map(|(block, meta)| self.document(block, meta, output))
}

Expand All @@ -249,5 +276,4 @@ impl AmberCompiler {
Ok(String::from_utf8_lossy(&child.stdout).to_string())
})
}

}
54 changes: 22 additions & 32 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
mod compiler;
mod docs;
mod modules;
mod rules;
mod stdlib;
mod translate;
mod docs;
mod utils;
mod stdlib;

#[cfg(test)]
pub mod tests;
Expand All @@ -21,6 +21,7 @@ use std::process::Command;

#[derive(Parser, Clone, Debug)]
#[command(version, arg_required_else_help(true))]
#[derive(Default)]
pub struct Cli {
#[arg(help = "'-' to read from stdin")]
input: Option<PathBuf>,
Expand All @@ -37,19 +38,7 @@ pub struct Cli {

/// Don't format the output file
#[arg(long)]
disable_format: bool
}

impl Default for Cli {
fn default() -> Self {
Self {
input: None,
output: None,
eval: None,
docs: false,
disable_format: false
}
}
disable_format: bool,
}

fn main() -> Result<(), Box<dyn Error>> {
Expand All @@ -64,20 +53,20 @@ fn main() -> Result<(), Box<dyn Error>> {
Ok(())
}

fn handle_compile(cli: Cli) -> Result<(), Box<dyn Error>> {
fn handle_compile(cli: Cli) -> Result<(), Box<dyn Error>> {
if let Some(input) = cli.input.clone() {
let input = String::from(input.to_string_lossy().trim());
let code = {
if input == "-" {
let mut buf = String::new();
match stdin().read_to_string(&mut buf) {
Ok(_) => buf,
Err(err) => handle_err(err)
Err(err) => handle_err(err),
}
} else {
match fs::read_to_string(&input) {
Ok(code) => code,
Err(err) => handle_err(err)
Err(err) => handle_err(err),
}
}
};
Expand All @@ -88,11 +77,11 @@ fn handle_compile(cli: Cli) -> Result<(), Box<dyn Error>> {
if let Some(output) = cli.output {
let output = String::from(output.to_string_lossy());
if output == "--silent" {
return Ok(())
return Ok(());
}
if output == "-" {
print!("{code}");
return Ok(())
return Ok(());
}
match fs::File::create(&output) {
Ok(mut file) => {
Expand All @@ -107,8 +96,8 @@ fn handle_compile(cli: Cli) -> Result<(), Box<dyn Error>> {
}
// Execute the code
else {
(!messages.is_empty()).then(|| render_dash());
let exit_status = AmberCompiler::execute(code, &vec![])?;
(!messages.is_empty()).then(render_dash);
let exit_status = AmberCompiler::execute(code, &[])?;
std::process::exit(exit_status.code().unwrap_or(1));
}
}
Expand All @@ -126,8 +115,8 @@ fn handle_eval(code: String, cli: Cli) -> Result<(), Box<dyn Error>> {
match AmberCompiler::new(code, None, cli).compile() {
Ok((messages, code)) => {
messages.iter().for_each(|m| m.show());
(!messages.is_empty()).then(|| render_dash());
let exit_status = AmberCompiler::execute(code, &vec![])?;
(!messages.is_empty()).then(render_dash);
let exit_status = AmberCompiler::execute(code, &[])?;
std::process::exit(exit_status.code().unwrap_or(1));
}
Err(err) => {
Expand All @@ -145,13 +134,11 @@ fn handle_docs(cli: Cli) -> Result<(), Box<dyn Error>> {
String::from(out.to_string_lossy())
};
match fs::read_to_string(&input) {
Ok(code) => {
match AmberCompiler::new(code, Some(input), cli).generate_docs(output) {
Ok(_) => Ok(()),
Err(err) => {
err.show();
std::process::exit(1);
}
Ok(code) => match AmberCompiler::new(code, Some(input), cli).generate_docs(output) {
Ok(_) => Ok(()),
Err(err) => {
err.show();
std::process::exit(1);
}
},
Err(err) => {
Expand All @@ -160,7 +147,10 @@ fn handle_docs(cli: Cli) -> Result<(), Box<dyn Error>> {
}
}
} else {
Message::new_err_msg("You need to provide a path to an entry file to generate the documentation").show();
Message::new_err_msg(
"You need to provide a path to an entry file to generate the documentation",
)
.show();
std::process::exit(1);
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/modules/builtin/nameof.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use heraclitus_compiler::prelude::*;
use crate::docs::module::DocumentationModule;
use crate::modules::types::{Type, Typed};
use crate::modules::variable::variable_name_extensions;
use crate::translate::module::TranslateModule;
use crate::utils::{ParserMetadata, TranslateMetadata};
use crate::modules::types::{Type, Typed};
use heraclitus_compiler::prelude::*;

#[derive(Debug, Clone)]
pub struct Nameof {
name: String
name: String,
}

impl Typed for Nameof {
Expand All @@ -21,7 +21,7 @@ impl SyntaxModule<ParserMetadata> for Nameof {

fn new() -> Self {
Nameof {
name: String::new()
name: String::new(),
}
}

Expand All @@ -30,12 +30,12 @@ impl SyntaxModule<ParserMetadata> for Nameof {
let name = variable(meta, variable_name_extensions())?;
match meta.get_var(&name) {
Some(var_decl) => {
self.name = var_decl.name.clone();
self.name.clone_from(&var_decl.name);
if let Some(id) = var_decl.global_id {
self.name = format!("__{id}_{}", self.name);
}
Ok(())
},
}
None => {
let tok = meta.get_current_token();
error!(meta, tok, format!("Variable '{name}' not found"))
Expand Down
14 changes: 6 additions & 8 deletions src/modules/condition/failed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,13 @@ impl TranslateModule for Failed {
&clear_return,
ret,
"fi"].join("\n")
} else if &block == ":" {
"__AS=$?".into()
} else {
if &block == ":" {
"__AS=$?".into()
} else {
["__AS=$?;",
"if [ $__AS != 0 ]; then",
&block,
"fi"].join("\n")
}
["__AS=$?;",
"if [ $__AS != 0 ]; then",
&block,
"fi"].join("\n")
}
} else {
String::new()
Expand Down
2 changes: 1 addition & 1 deletion src/modules/expression/literal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub fn parse_interpolated_region(meta: &mut ParserMetadata, letter: char) -> Res
word.starts_with(letter)
&& word.ends_with(letter)
&& word.len() > 1
&& !is_escaped(&word, letter)
&& !is_escaped(word, letter)
}) {
let stripped = word.chars().take(word.chars().count() - 1).skip(1).collect::<String>();
strings.push(stripped);
Expand Down
Loading

0 comments on commit 226f725

Please sign in to comment.