Skip to content

Commit

Permalink
fix: fix clippy issues
Browse files Browse the repository at this point in the history
Signed-off-by: lxl66566 <lxl66566@gmail.com>
  • Loading branch information
lxl66566 committed Jul 25, 2024
1 parent 03c6be2 commit bcdfe98
Show file tree
Hide file tree
Showing 14 changed files with 116 additions and 97 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())
})
}

}
24 changes: 7 additions & 17 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use std::process::Command;

#[derive(Parser, Clone, Debug)]
#[command(version, arg_required_else_help(true))]
#[derive(Default)]
pub struct Cli {
input: Option<PathBuf>,
output: Option<PathBuf>,
Expand All @@ -38,17 +39,6 @@ pub struct Cli {
disable_format: bool
}

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

fn main() -> Result<(), Box<dyn Error>> {
let cli = Cli::parse();
Expand All @@ -68,8 +58,8 @@ fn handle_compile(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 Down Expand Up @@ -102,8 +92,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 @@ -127,8 +117,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 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
9 changes: 4 additions & 5 deletions src/modules/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,11 @@ impl BashFormatter {
pub fn get_available() -> Option<BashFormatter> {
Self::get_all()
.iter()
.find(|fmt| fmt.is_available())
.map(|fmt| *fmt)
.find(|fmt| fmt.is_available()).copied()
}

/// Check if current formatter is present in $PATH
pub fn is_available(self: &Self) -> bool {
pub fn is_available(&self) -> bool {
match self {
BashFormatter::shfmt =>
Command::new("shfmt")
Expand All @@ -42,14 +41,14 @@ impl BashFormatter {
}

#[allow(dead_code)] // used in tests
pub fn as_cmd<T: From<&'static str>>(self: &Self) -> T {
pub fn as_cmd<T: From<&'static str>>(&self) -> T {
match self {
BashFormatter::shfmt => "shfmt".into()
}
}

/// Format code using the formatter
pub fn format(self: &Self, code: String) -> String {
pub fn format(&self, code: String) -> String {
match self {
BashFormatter::shfmt => {
let mut command = Command::new("shfmt")
Expand Down
10 changes: 4 additions & 6 deletions src/modules/function/declaration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl FunctionDeclaration {
{
return String::new()
}
return " ".to_string();
" ".to_string()
}

fn render_function_signature(&self, meta: &ParserMetadata, doc_index: usize) -> Result<String, Failure> {
Expand All @@ -73,7 +73,7 @@ impl FunctionDeclaration {
let mut before = String::new();
loop {
let cur_token = meta.context.expr.get(index);
let cur_word = cur_token.map_or_else(|| String::new(), |v| v.word.clone());
let cur_word = cur_token.map_or_else(String::new, |v| v.word.clone());
if !result.is_empty() {
result.push_str(&self.get_space(parentheses, &before, &cur_word))
}
Expand Down Expand Up @@ -181,10 +181,8 @@ impl SyntaxModule<ParserMetadata> for FunctionDeclaration {
optional = true;
let mut expr = Expr::new();
syntax(meta, &mut expr)?;
if arg_type != Type::Generic {
if arg_type != expr.get_type() {
return error!(meta, name_token, "Optional argument does not match annotated type");
}
if arg_type != Type::Generic && arg_type != expr.get_type() {
return error!(meta, name_token, "Optional argument does not match annotated type");
}
self.arg_optionals.push(expr);
},
Expand Down
2 changes: 1 addition & 1 deletion src/modules/function/declaration_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub fn is_functions_comment_doc(meta: &mut ParserMetadata) -> bool {
if tok.word.starts_with("///") {
is_comment_doc = true;
}
if tok.word.starts_with("\n") {
if tok.word.starts_with('\n') {
if is_comment_doc {
is_comment_doc = false;
last_line = tok.pos.0;
Expand Down
2 changes: 1 addition & 1 deletion src/modules/imports/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl Import {

fn resolve_import(&mut self, meta: &ParserMetadata) -> Result<String, Failure> {
if self.path.value.starts_with("std/") {
match stdlib::resolve(&self.path.value.replace("std/", "")) {
match stdlib::resolve(self.path.value.replace("std/", "")) {
Some(v) => Ok(v),
None => error!(meta, self.token_path.clone(),
format!("Standard library module '{}' does not exist", self.path.value))
Expand Down
2 changes: 1 addition & 1 deletion src/modules/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ impl TranslateModule for Main {
let quote = meta.gen_quote();
let dollar = meta.gen_dollar();
let args = self.args.clone().map_or_else(
|| String::new(),
String::new,
|name| format!("{name}=({quote}{dollar}@{quote})")
);
format!("{args}\n{}", self.block.translate(meta))
Expand Down
12 changes: 6 additions & 6 deletions src/modules/statement/comment_doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ impl SyntaxModule<ParserMetadata> for CommentDoc {
meta.increment_index();
while let Some(token) = meta.get_current_token() {
let is_token_underneeth = token.pos.0 == col + 1;
let last_char = self.value.chars().last().unwrap_or_else(|| '\n');
let last_char = self.value.chars().last().unwrap_or('\n');
// If the token is a newline, we add a newline to the comment
if token.word.starts_with("\n") {
self.value.push_str("\n");
if token.word.starts_with('\n') {
self.value.push('\n');
meta.increment_index();
continue;
}
Expand All @@ -39,7 +39,7 @@ impl SyntaxModule<ParserMetadata> for CommentDoc {
col = token.pos.0;
meta.increment_index();
// If the comment signifies a paragrah break, we add two newlines
if token.word[3..].trim().len() == 0 {
if token.word[3..].trim().is_empty() {
if last_char == '\n' {
continue;
}
Expand All @@ -54,10 +54,10 @@ impl SyntaxModule<ParserMetadata> for CommentDoc {
}
Ok(())
} else {
return Err(Failure::Quiet(PositionInfo::from_token(meta, meta.get_current_token())))
Err(Failure::Quiet(PositionInfo::from_token(meta, meta.get_current_token())))
}
}
None => return Err(Failure::Quiet(PositionInfo::from_token(meta, meta.get_current_token())))
None => Err(Failure::Quiet(PositionInfo::from_token(meta, meta.get_current_token())))
}
}
}
Expand Down
Loading

0 comments on commit bcdfe98

Please sign in to comment.