Skip to content

Commit

Permalink
linting fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Ph0enixKM committed Sep 28, 2023
1 parent b1759f1 commit f44481d
Show file tree
Hide file tree
Showing 26 changed files with 54 additions and 76 deletions.
2 changes: 1 addition & 1 deletion src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ impl AmberCompiler {
pub fn parse(&self, tokens: Vec<Token>) -> 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));
if let Err(Failure::Loud(err)) = check_all_blocks(&mut meta) {
if let Err(Failure::Loud(err)) = check_all_blocks(&meta) {
return Err(err);
}
let mut block = Block::new();
Expand Down
4 changes: 2 additions & 2 deletions src/modules/command/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl SyntaxModule<ParserMetadata> for CommandExpr {
}
Ok(())
},
Err(Failure::Loud(err)) => return Err(Failure::Loud(err)),
Err(Failure::Loud(err)) => Err(Failure::Loud(err)),
Err(Failure::Quiet(_)) => {
let tok = meta.get_current_token();
(self.strings, self.interps) = parse_interpolated_region(meta, '$')?;
Expand All @@ -71,7 +71,7 @@ impl TranslateModule for CommandExpr {
.map(|item| item.translate(meta))
.collect::<Vec<String>>();
let failed = self.failed.translate(meta);
let silent = self.is_silent_expr.then(|| " 2>/dev/null").unwrap_or("");
let silent = if self.is_silent_expr { " 2>/dev/null" } else { "" };
if failed.is_empty() {
let translation = translate_interpolated_region(self.strings.clone(), interps, false);
meta.gen_subprocess(&(translation + silent))
Expand Down
2 changes: 1 addition & 1 deletion src/modules/command/modifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl SyntaxModule<ParserMetadata> for CommandModifier {
match meta.get_current_token() {
Some(tok) => {
sequence.push_str(tok.word.as_str());
sequence.push_str(" ");
sequence.push(' ');
match tok.word.as_str() {
"unsafe" => {
self.is_unsafe = true;
Expand Down
18 changes: 6 additions & 12 deletions src/modules/condition/failed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl SyntaxModule<ParserMetadata> for Failed {

fn parse(&mut self, meta: &mut ParserMetadata) -> SyntaxResult {
let tok = meta.get_current_token();
if let Ok(_) = token(meta, "?") {
if token(meta, "?").is_ok() {
if !meta.context.is_fun_ctx && !meta.context.is_main_ctx && !meta.context.is_unsafe_ctx {
return error!(meta, tok, "The '?' operator can only be used in the main block or function body")
}
Expand Down Expand Up @@ -76,9 +76,7 @@ impl TranslateModule for Failed {
fn translate(&self, meta: &mut TranslateMetadata) -> String {
if self.is_parsed {
let block = self.block.translate(meta);
let ret = self.is_main
.then(|| "exit $__AMBER_STATUS")
.unwrap_or("return $__AMBER_STATUS");
let ret = if self.is_main { "exit $__AMBER_STATUS" } else { "return $__AMBER_STATUS" };
// the condition of '$?' clears the status code thus we need to store it in a variable
if self.is_question_mark {
// if the failed expression is in the main block we need to clear the return value
Expand All @@ -88,20 +86,16 @@ impl TranslateModule for Failed {
} else {
String::new()
};
vec![
"__AMBER_STATUS=$?;",
["__AMBER_STATUS=$?;",
"if [ $__AMBER_STATUS != 0 ]; then",
&clear_return,
ret,
"fi"
].join("\n")
"fi"].join("\n")
} else {
vec![
"__AMBER_STATUS=$?;",
["__AMBER_STATUS=$?;",
"if [ $__AMBER_STATUS != 0 ]; then",
&block,
"fi"
].join("\n")
"fi"].join("\n")
}
} else {
String::new()
Expand Down
4 changes: 1 addition & 3 deletions src/modules/condition/ifchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,7 @@ impl SyntaxModule<ParserMetadata> for IfChain {
return Ok(())
}
// Handle end of the if chain
if let Err(err) = syntax(meta, &mut cond) {
return Err(err)
}
syntax(meta, &mut cond)?;
match token(meta, "{") {
Ok(_) => {
syntax(meta, &mut block)?;
Expand Down
2 changes: 1 addition & 1 deletion src/modules/expression/literal/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl SyntaxModule<ParserMetadata> for Array {
Err(Failure::Quiet(_)) => {
loop {
let tok = meta.get_current_token();
if let Ok(_) = token(meta, "[") {
if token(meta, "[").is_ok() {
return error!(meta, tok, "Arrays cannot be nested due to the Bash limitations")
}
// Parse array value
Expand Down
2 changes: 1 addition & 1 deletion src/modules/expression/literal/bool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ impl SyntaxModule<ParserMetadata> for Bool {
}

fn parse(&mut self, meta: &mut ParserMetadata) -> SyntaxResult {
let value = token_by(meta, |value| vec!["true", "false"].contains(&value.as_str()))?;
let value = token_by(meta, |value| ["true", "false"].contains(&value.as_str()))?;
self.value = value == "true";
Ok(())
}
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 @@ -146,7 +146,7 @@ pub fn translate_interpolated_region(strings: Vec<String>, interps: Vec<String>,
match value {
Some(translated) => {
if is_even {
if translated.starts_with("\"") && translated.ends_with("\"") {
if translated.starts_with('\"') && translated.ends_with('\"') {
result.push(translated.get(1..translated.len() - 1).unwrap().to_string());
} else {
result.push(translated);
Expand Down
2 changes: 1 addition & 1 deletion src/modules/expression/literal/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ impl SyntaxModule<ParserMetadata> for Status {

impl TranslateModule for Status {
fn translate(&self, _meta: &mut TranslateMetadata) -> String {
format!("$__AMBER_STATUS")
"$__AMBER_STATUS".to_string()
}
}
2 changes: 1 addition & 1 deletion src/modules/expression/unop/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl SyntaxModule<ParserMetadata> for Cast {
}

fn parse(&mut self, meta: &mut ParserMetadata) -> SyntaxResult {
parse_left_expr(meta, &mut *self.expr, "as")?;
parse_left_expr(meta, &mut self.expr, "as")?;
let tok = meta.get_current_token();
token(meta, "as")?;
self.kind = parse_type(meta)?;
Expand Down
6 changes: 3 additions & 3 deletions src/modules/function/declaration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl SyntaxModule<ParserMetadata> for FunctionDeclaration {
self.is_public = true;
}
if let Err(err) = token(meta, "fun") {
if flags.len() > 0 {
if !flags.is_empty() {
return error!(meta, tok, "Compiler flags can only be used in function declarations")
}
return Err(err)
Expand Down Expand Up @@ -145,7 +145,7 @@ impl SyntaxModule<ParserMetadata> for FunctionDeclaration {
arg_refs: self.arg_refs.clone(),
returns: self.returns.clone(),
is_public: self.is_public,
is_failable: is_failable
is_failable
}, ctx)?;
// Restore the compiler flags
swap(&mut meta.context.cc_flags, &mut flags);
Expand All @@ -167,7 +167,7 @@ impl TranslateModule for FunctionDeclaration {
meta.fun_name = Some((self.name.clone(), self.id, index));
// Parse the function body
result.push(format!("function {name} {{"));
if let Some(args) = self.set_args_as_variables(meta, &function, &self.arg_refs) {
if let Some(args) = self.set_args_as_variables(meta, function, &self.arg_refs) {
result.push(args);
}
result.push(function.block.translate(meta));
Expand Down
4 changes: 2 additions & 2 deletions src/modules/function/invocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ impl SyntaxModule<ParserMetadata> for FunctionInvocation {

impl FunctionInvocation {
fn get_variable(&self, meta: &TranslateMetadata, name: &str, dollar_override: bool) -> String {
let dollar = dollar_override.then(|| "$").unwrap_or_else(|| meta.gen_dollar());
let dollar = dollar_override.then_some("$").unwrap_or_else(|| meta.gen_dollar());
if matches!(self.kind, Type::Array(_)) {
let quote = meta.gen_quote();
format!("{quote}{dollar}{{{name}[@]}}{quote}")
Expand All @@ -118,7 +118,7 @@ impl TranslateModule for FunctionInvocation {
// If the argument is an array, we have to get just the "name[@]" part
(translation.starts_with("\"${") && translation.ends_with("[@]}\""))
.then(|| translation.get(3..translation.len() - 2).unwrap().to_string())
.unwrap_or_else(|| translation)
.unwrap_or(translation)
}
}).collect::<Vec<String>>().join(" ");
meta.stmt_queue.push_back(format!("{name} {args}{silent}"));
Expand Down
9 changes: 4 additions & 5 deletions src/modules/function/invocation_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ fn run_function_with_args(meta: &mut ParserMetadata, mut fun: FunctionDecl, args
// Create a sub context for new variables
meta.push_scope();
for (kind, name, is_ref) in izip!(args, &fun.arg_names, &fun.arg_refs) {
meta.add_param(name, kind.clone(), is_ref.clone());
meta.add_param(name, kind.clone(), *is_ref);
}
// Set the expected return type if specified
if fun.returns != Type::Generic {
Expand All @@ -73,9 +73,9 @@ fn run_function_with_args(meta: &mut ParserMetadata, mut fun: FunctionDecl, args
fun.returns = ctx.fun_ret_type.clone().unwrap_or_else(|| Type::Null);
};
// Set the new argument types
fun.arg_types = args.iter().cloned().collect();
fun.arg_types = args.to_vec();
// Persist the new function instance
Ok((fun.returns.clone(), meta.add_fun_instance(fun.to_interface(), block)))
Ok((fun.returns.clone(), meta.add_fun_instance(fun.into_interface(), block)))
}

pub fn handle_function_reference(meta: &ParserMetadata, tok: Option<Token>, name: &str) -> Result<usize, Failure> {
Expand Down Expand Up @@ -112,6 +112,5 @@ pub fn handle_function_parameters(meta: &mut ParserMetadata, id: usize, fun: Fun
fn handle_similar_function(meta: &ParserMetadata, name: &str) -> Option<String> {
let vars = Vec::from_iter(meta.get_fun_names());
find_best_similarity(name, &vars)
.map(|(match_name, score)| (score >= 0.75).then(|| format!("Did you mean '{match_name}'?")))
.flatten()
.and_then(|(match_name, score)| (score >= 0.75).then(|| format!("Did you mean '{match_name}'?")))
}
4 changes: 2 additions & 2 deletions src/modules/function/ret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ impl TranslateModule for Return {
let result = self.expr.translate_eval(meta, false);
let result = matches!(self.expr.get_type(), Type::Array(_))
.then(|| format!("({result})"))
.unwrap_or_else(|| result);
.unwrap_or(result);
meta.stmt_queue.push_back(format!("__AMBER_FUN_{name}{id}_v{variant}={result}"));
format!("return 0")
"return 0".to_string()
}
}
6 changes: 2 additions & 4 deletions src/modules/loops/infinite_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,9 @@ impl SyntaxModule<ParserMetadata> for InfiniteLoop {

impl TranslateModule for InfiniteLoop {
fn translate(&self, meta: &mut TranslateMetadata) -> String {
vec![
"while :".to_string(),
["while :".to_string(),
"do".to_string(),
self.block.translate(meta),
"done".to_string()
].join("\n")
"done".to_string()].join("\n")
}
}
14 changes: 5 additions & 9 deletions src/modules/loops/iter_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl SyntaxModule<ParserMetadata> for IterLoop {
fn parse(&mut self, meta: &mut ParserMetadata) -> SyntaxResult {
token(meta, "loop")?;
self.iter_name = variable(meta, variable_name_extensions())?;
if let Ok(_) = token(meta, ",") {
if token(meta, ",").is_ok() {
self.iter_index = Some(self.iter_name.clone());
self.iter_name = variable(meta, variable_name_extensions())?;
}
Expand Down Expand Up @@ -79,22 +79,18 @@ impl TranslateModule for IterLoop {
meta.increase_indent();
let indent = meta.gen_indent();
meta.decrease_indent();
vec![
format!("{index}=0;"),
[format!("{index}=0;"),
format!("for {name} in {iterable}"),
"do".to_string(),
self.block.translate(meta),
format!("{indent}let {index}=${{{index}}}+1"),
"done".to_string()
].join("\n")
"done".to_string()].join("\n")
},
None => {
vec![
format!("for {name} in {iterable}"),
[format!("for {name} in {iterable}"),
"do".to_string(),
self.block.translate(meta),
"done".to_string()
].join("\n")
"done".to_string()].join("\n")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/modules/statement/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ impl TranslateModule for Statement {
// This is a workaround that handles $(...) which cannot be used as a statement
let translated = (matches!(self.value, Some(StatementType::Expr(_))) || translated.starts_with("$(") || translated.starts_with("\"$("))
.then(|| format!("echo {} > /dev/null 2>&1", translated))
.unwrap_or_else(|| translated);
.unwrap_or(translated);
// Get all the required supplemental statements
let indentation = meta.gen_indent();
let statements = meta.stmt_queue.drain(..).map(|st| indentation.clone() + &st + ";\n").join("");
Expand Down
3 changes: 2 additions & 1 deletion src/modules/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ pub trait Typed {
// Tries to parse the type - if it fails, it fails loudly
pub fn parse_type(meta: &mut ParserMetadata) -> Result<Type, Failure> {
let tok = meta.get_current_token();
try_parse_type(meta).or_else(|_| error!(meta, tok, "Expected a data type"))
try_parse_type(meta)
.map_err(|_| Failure::Loud(Message::new_err_at_token(meta, tok).message("Expected a data type")))
}

// Tries to parse the type - if it fails, it fails quietly
Expand Down
4 changes: 1 addition & 3 deletions src/modules/variable/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ impl TranslateModule for VariableInit {
if let Type::Array(_) = self.expr.get_type() {
expr = format!("({expr})");
}
let local = self.is_fun_ctx
.then(|| "local ")
.unwrap_or_else(|| "");
let local = if self.is_fun_ctx { "local " } else { "" };
match self.global_id {
Some(id) => format!("__{id}_{name}={expr}"),
None => format!("{local}{name}={expr}")
Expand Down
3 changes: 1 addition & 2 deletions src/modules/variable/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ pub fn handle_variable_reference(meta: &ParserMetadata, tok: Option<Token>, name
fn handle_similar_variable(meta: &ParserMetadata, name: &str) -> Option<String> {
let vars = Vec::from_iter(meta.get_var_names());
find_best_similarity(name, &vars)
.map(|(match_name, score)| (score >= 0.75).then(|| format!("Did you mean '{match_name}'?")))
.flatten()
.and_then(|(match_name, score)| (score >= 0.75).then(|| format!("Did you mean '{match_name}'?")))
}

pub fn handle_identifier_name(meta: &ParserMetadata, name: &str, tok: Option<Token>) -> Result<(), Failure> {
Expand Down
2 changes: 1 addition & 1 deletion src/modules/variable/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl TranslateModule for VariableSet {
.map(|index| format!("[{}]", self.is_ref
.then(|| index.translate_eval(meta, true))
.unwrap_or_else(|| index.translate(meta))))
.unwrap_or_else(|| String::new());
.unwrap_or_default();
let mut expr = self.is_ref
.then(|| self.value.translate_eval(meta, true))
.unwrap_or_else(|| self.value.translate(meta));
Expand Down
6 changes: 3 additions & 3 deletions src/utils/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub struct FunctionDecl {
}

impl FunctionDecl {
pub fn to_interface(self) -> FunctionInterface {
pub fn into_interface(self) -> FunctionInterface {
FunctionInterface {
id: Some(self.id),
name: self.name,
Expand Down Expand Up @@ -145,9 +145,9 @@ impl Context {
self
}

pub fn file_import(mut self, trace: &Vec<PositionInfo>, position: PositionInfo) -> Self {
pub fn file_import(mut self, trace: &[PositionInfo], position: PositionInfo) -> Self {
// Initialize the trace
self.trace = trace.clone();
self.trace = trace.to_vec();
// Push the position to the trace
self.trace.push(position);
self
Expand Down
4 changes: 2 additions & 2 deletions src/utils/function_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub struct FunctionInterface {
}

impl FunctionInterface {
pub fn as_fun_declaration(self, id: usize) -> FunctionDecl {
pub fn into_fun_declaration(self, id: usize) -> FunctionDecl {
let is_args_typed = self.arg_types.iter().all(|t| t != &Type::Generic);
FunctionDecl {
name: self.name,
Expand All @@ -31,7 +31,7 @@ impl FunctionInterface {
}
}

pub fn as_fun_instance(self, block: Block) -> FunctionInstance {
pub fn into_fun_instance(self, block: Block) -> FunctionInstance {
FunctionInstance {
variant_id: 0,
args: self.arg_types,
Expand Down
5 changes: 2 additions & 3 deletions src/utils/import_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ impl ImportCache {
// If so add it to the graph
Some(dst_path_id) => {
self.import_graph[src_path_id].push(dst_path_id);
(!self.contains_cycle(src_path_id)).then(|| dst_path_id)
(!self.contains_cycle(src_path_id)).then_some(dst_path_id)
}
// If not add it to the graph and create a new import entry
None => {
Expand All @@ -93,8 +93,7 @@ impl ImportCache {

pub fn get_import_pub_funs(&mut self, path: Option<String>) -> Option<Vec<FunctionDecl>> {
self.get_path_id(&Self::get_path(path))
.map(|path_id| self.files[path_id].metadata.as_ref().map(|meta| meta.pub_funs.clone()))
.flatten()
.and_then(|path_id| self.files[path_id].metadata.as_ref().map(|meta| meta.pub_funs.clone()))
}

fn topological_sort_util(&self, v: usize, visited: &mut Vec<bool>, stack: &mut Vec<usize>) {
Expand Down
Loading

0 comments on commit f44481d

Please sign in to comment.