From e0522cb2d5b0f2ee9fa93a85f0a0d904d802b61a Mon Sep 17 00:00:00 2001 From: PaulDotSH <84643540+PaulDotSH@users.noreply.github.com> Date: Wed, 5 Jun 2024 06:28:08 -0400 Subject: [PATCH] Apply clippy lints for code readability --- sailfish-compiler/src/compiler.rs | 8 +++---- sailfish-compiler/src/config.rs | 4 ++-- sailfish-compiler/src/error.rs | 4 ++-- sailfish-compiler/src/parser.rs | 4 ++-- sailfish-compiler/src/procmacro.rs | 10 ++++---- sailfish-compiler/src/resolver.rs | 14 ++++-------- sailfish-compiler/src/translator.rs | 34 ++++++++++++++-------------- sailfish-compiler/src/util.rs | 4 ++-- sailfish/src/runtime/escape/avx2.rs | 8 +++---- sailfish/src/runtime/escape/naive.rs | 2 +- sailfish/src/runtime/escape/sse2.rs | 4 ++-- sailfish/src/runtime/filter.rs | 8 +++---- sailfish/src/runtime/render.rs | 14 ++++++------ sailfish/src/runtime/size_hint.rs | 6 +++++ 14 files changed, 63 insertions(+), 61 deletions(-) diff --git a/sailfish-compiler/src/compiler.rs b/sailfish-compiler/src/compiler.rs index 16a39d6..dd9622d 100644 --- a/sailfish-compiler/src/compiler.rs +++ b/sailfish-compiler/src/compiler.rs @@ -38,7 +38,7 @@ impl Compiler { let content = read_to_string(input) .chain_err(|| format!("Failed to open template file: {:?}", input))?; - let stream = parser.parse(&*content); + let stream = parser.parse(&content); translator.translate(stream) } @@ -47,7 +47,7 @@ impl Compiler { input: &Path, ) -> Result<(TranslatedSource, CompilationReport), Error> { let include_handler = Arc::new(|child_file: &Path| -> Result<_, Error> { - Ok(self.translate_file_contents(&*child_file)?.ast) + Ok(self.translate_file_contents(child_file)?.ast) }); let resolver = Resolver::new().include_handler(include_handler); @@ -85,7 +85,7 @@ impl Compiler { .chain_err(|| format!("Failed to create artifact: {:?}", output))?; writeln!(f, "// Template compiled from: {}", input.display()) .chain_err(|| format!("Failed to write artifact into {:?}", output))?; - writeln!(f, "{}", rustfmt_block(&*string).unwrap_or(string)) + writeln!(f, "{}", rustfmt_block(&string).unwrap_or(string)) .chain_err(|| format!("Failed to write artifact into {:?}", output))?; drop(f); @@ -95,7 +95,7 @@ impl Compiler { compile_file(tsource, output) .chain_err(|| "Failed to compile template.") .map_err(|mut e| { - e.source = fs::read_to_string(&*input).ok(); + e.source = fs::read_to_string(input).ok(); e.source_file = Some(input.to_owned()); e }) diff --git a/sailfish-compiler/src/config.rs b/sailfish-compiler/src/config.rs index 90389e5..3083a5b 100644 --- a/sailfish-compiler/src/config.rs +++ b/sailfish-compiler/src/config.rs @@ -45,7 +45,7 @@ mod imp { if path.is_file() { let config_file = - ConfigFile::read_from_file(&*path).map_err(|mut e| { + ConfigFile::read_from_file(&path).map_err(|mut e| { e.source_file = Some(path.to_owned()); e })?; @@ -132,7 +132,7 @@ mod imp { while let Some((i, c)) = iter.next() { match c { - '$' if found == false => { + '$' if !found => { if let Some((_, cc)) = iter.next() { if cc == '{' { found = true; diff --git a/sailfish-compiler/src/error.rs b/sailfish-compiler/src/error.rs index 27194ff..f13b8cf 100644 --- a/sailfish-compiler/src/error.rs +++ b/sailfish-compiler/src/error.rs @@ -26,8 +26,8 @@ impl fmt::Display for ErrorKind { ErrorKind::ConfigError(ref e) => write!(f, "Invalid configuration ({})", e), ErrorKind::ParseError(ref msg) => write!(f, "Parse error ({})", msg), ErrorKind::AnalyzeError(ref msg) => write!(f, "Analyzation error ({})", msg), - ErrorKind::Unimplemented(ref msg) => f.write_str(&**msg), - ErrorKind::Other(ref msg) => f.write_str(&**msg), + ErrorKind::Unimplemented(ref msg) => f.write_str(msg), + ErrorKind::Other(ref msg) => f.write_str(msg), } } } diff --git a/sailfish-compiler/src/parser.rs b/sailfish-compiler/src/parser.rs index 0bf84ec..5bb7a46 100644 --- a/sailfish-compiler/src/parser.rs +++ b/sailfish-compiler/src/parser.rs @@ -196,7 +196,7 @@ impl<'a> ParseStream<'a> { } // find closing bracket - if let Some(pos) = find_block_end(&self.source[start..], &*self.block_delimiter.1) + if let Some(pos) = find_block_end(&self.source[start..], &self.block_delimiter.1) { // closing bracket was found self.take_n(start); @@ -221,7 +221,7 @@ impl<'a> ParseStream<'a> { let end = self .source .find(&*self.block_delimiter.0) - .unwrap_or_else(|| self.source.len()); + .unwrap_or(self.source.len()); let token = Token { content: self.take_n(end), offset, diff --git a/sailfish-compiler/src/procmacro.rs b/sailfish-compiler/src/procmacro.rs index 983c1c5..c189e85 100644 --- a/sailfish-compiler/src/procmacro.rs +++ b/sailfish-compiler/src/procmacro.rs @@ -27,7 +27,7 @@ struct DeriveTemplateOptions { } impl DeriveTemplateOptions { - fn parser<'s>(&'s mut self) -> impl Parser + 's { + fn parser(&mut self) -> impl Parser + '_ { move |s: ParseStream| -> ParseResult<()> { while !s.is_empty() { let key = s.parse::()?; @@ -161,7 +161,7 @@ fn derive_template_impl(tokens: TokenStream) -> Result "Internal error: environmental variable `CARGO_MANIFEST_DIR` is not set.", )); - Config::search_file_and_read(&*manifest_dir) + Config::search_file_and_read(&manifest_dir) .map_err(|e| syn::Error::new(Span::call_site(), e))? }; @@ -186,7 +186,7 @@ fn derive_template_impl(tokens: TokenStream) -> Result let path = all_options.path.as_ref().ok_or_else(|| { syn::Error::new(Span::call_site(), "`path` option must be specified.") })?; - resolve_template_file(&*path.value(), &*config.template_dirs) + resolve_template_file(&path.value(), &config.template_dirs) .and_then(|path| path.canonicalize().ok()) .ok_or_else(|| { syn::Error::new( @@ -204,9 +204,9 @@ fn derive_template_impl(tokens: TokenStream) -> Result // re-used if they exist. let mut output_file = PathBuf::from(env!("OUT_DIR")); output_file.push("templates"); - output_file.push(filename_hash(&*input_file, &config)); + output_file.push(filename_hash(&input_file, &config)); - std::fs::create_dir_all(&output_file.parent().unwrap()).unwrap(); + std::fs::create_dir_all(output_file.parent().unwrap()).unwrap(); // This makes sure max 1 process creates a new file, "create_new" check+create is an // atomic operation. Cargo sometimes runs multiple macro invocations for the same diff --git a/sailfish-compiler/src/resolver.rs b/sailfish-compiler/src/resolver.rs index ce05a54..b436b58 100644 --- a/sailfish-compiler/src/resolver.rs +++ b/sailfish-compiler/src/resolver.rs @@ -23,9 +23,10 @@ macro_rules! return_if_some { }; } +pub type IncludeHandler<'h> = Arc Result>; #[derive(Clone)] pub struct Resolver<'h> { - include_handler: Arc Result>, + include_handler: IncludeHandler<'h>, } impl<'h> Resolver<'h> { @@ -40,10 +41,7 @@ impl<'h> Resolver<'h> { } #[inline] - pub fn include_handler( - mut self, - new: Arc Result>, - ) -> Resolver<'h> { + pub fn include_handler(mut self, new: IncludeHandler<'h>) -> Resolver<'h> { self.include_handler = new; self } @@ -78,7 +76,7 @@ struct ResolverImpl<'h> { path_stack: Vec, deps: Vec, error: Option, - include_handler: Arc Result>, + include_handler: IncludeHandler<'h>, } impl<'h> ResolverImpl<'h> { @@ -124,7 +122,7 @@ impl<'h> ResolverImpl<'h> { }; // parse and translate the child template - let mut blk = (*self.include_handler)(&*child_template_file).chain_err(|| { + let mut blk = (*self.include_handler)(&child_template_file).chain_err(|| { format!("Failed to include {:?}", child_template_file.clone()) })?; @@ -157,7 +155,6 @@ impl<'h> VisitMut for ResolverImpl<'h> { Ok(e) => *i = Stmt::Expr(e, None), Err(e) => { self.error = Some(e); - return; } } } @@ -176,7 +173,6 @@ impl<'h> VisitMut for ResolverImpl<'h> { Ok(e) => *i = e, Err(e) => { self.error = Some(e); - return; } } } diff --git a/sailfish-compiler/src/translator.rs b/sailfish-compiler/src/translator.rs index 86047f0..924a1f8 100644 --- a/sailfish-compiler/src/translator.rs +++ b/sailfish-compiler/src/translator.rs @@ -24,9 +24,9 @@ impl Translator { self } - pub fn translate<'a>( + pub fn translate( &self, - token_iter: ParseStream<'a>, + token_iter: ParseStream<'_>, ) -> Result { let original_source = token_iter.original_source; @@ -34,7 +34,7 @@ impl Translator { ps.reserve(original_source.len()); ps.feed_tokens(token_iter)?; - Ok(ps.finalize()?) + ps.finalize() } } @@ -95,7 +95,7 @@ impl SourceBuilder { self.source.reserve(additional); } - fn write_token<'a>(&mut self, token: &Token<'a>) { + fn write_token(&mut self, token: &Token<'_>) { let entry = SourceMapEntry { original: token.offset(), new: self.source.len(), @@ -105,14 +105,14 @@ impl SourceBuilder { self.source.push_str(token.as_str()); } - fn write_code<'a>(&mut self, token: &Token<'a>) -> Result<(), Error> { + fn write_code(&mut self, token: &Token<'_>) -> Result<(), Error> { // TODO: automatically add missing tokens (e.g. ';', '{') self.write_token(token); self.source.push('\n'); Ok(()) } - fn write_text<'a>(&mut self, token: &Token<'a>) -> Result<(), Error> { + fn write_text(&mut self, token: &Token<'_>) -> Result<(), Error> { use std::fmt::Write; // if error has occured at the first byte of `render_text!` macro, it @@ -130,17 +130,17 @@ impl SourceBuilder { Ok(()) } - fn write_buffered_code<'a>( + fn write_buffered_code( &mut self, - token: &Token<'a>, + token: &Token<'_>, escape: bool, ) -> Result<(), Error> { self.write_buffered_code_with_suffix(token, escape, "") } - fn write_buffered_code_with_suffix<'a>( + fn write_buffered_code_with_suffix( &mut self, - token: &Token<'a>, + token: &Token<'_>, escape: bool, suffix: &str, ) -> Result<(), Error> { @@ -172,7 +172,7 @@ impl SourceBuilder { }; self.source.push_str("sailfish::runtime::filter::"); - self.source.push_str(&*name); + self.source.push_str(&name); self.source.push('('); // arguments to filter function @@ -189,7 +189,7 @@ impl SourceBuilder { if let Some(extra_args) = extra_args { self.source.push_str(", "); - self.source.push_str(&*extra_args); + self.source.push_str(&extra_args); } } @@ -204,7 +204,7 @@ impl SourceBuilder { Ok(()) } - pub fn feed_tokens<'a>(&mut self, token_iter: ParseStream<'a>) -> Result<(), Error> { + pub fn feed_tokens(&mut self, token_iter: ParseStream<'_>) -> Result<(), Error> { let mut it = token_iter.peekable(); while let Some(token) = it.next() { let token = token?; @@ -225,7 +225,7 @@ impl SourceBuilder { let mut concatenated = String::new(); concatenated.push_str(token.as_str()); - while let Some(&Ok(ref next_token)) = it.peek() { + while let Some(Ok(next_token)) = it.peek() { match next_token.kind() { TokenKind::Text => { concatenated.push_str(next_token.as_str()); @@ -238,7 +238,7 @@ impl SourceBuilder { } } - let new_token = Token::new(&*concatenated, offset, TokenKind::Text); + let new_token = Token::new(&concatenated, offset, TokenKind::Text); self.write_text(&new_token)?; } } @@ -249,14 +249,14 @@ impl SourceBuilder { pub fn finalize(mut self) -> Result { self.source.push_str("\n}"); - match syn::parse_str::(&*self.source) { + match syn::parse_str::(&self.source) { Ok(ast) => Ok(TranslatedSource { ast, source_map: self.source_map, }), Err(synerr) => { let span = synerr.span(); - let original_offset = into_offset(&*self.source, span) + let original_offset = into_offset(&self.source, span) .and_then(|o| self.source_map.reverse_mapping(o)); let mut err = diff --git a/sailfish-compiler/src/util.rs b/sailfish-compiler/src/util.rs index 8e25e69..736a747 100644 --- a/sailfish-compiler/src/util.rs +++ b/sailfish-compiler/src/util.rs @@ -49,7 +49,7 @@ pub fn rustfmt_block(source: &str) -> io::Result { new_source.push_str(source); let mut child = Command::new(rustfmt) - .args(&["--emit", "stdout", "--color", "never", "--quiet"]) + .args(["--emit", "stdout", "--color", "never", "--quiet"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) @@ -82,5 +82,5 @@ pub fn filetime(input: &Path) -> filetime::FileTime { use filetime::FileTime; fs::metadata(input) .and_then(|metadata| metadata.modified()) - .map_or(FileTime::zero(), |time| FileTime::from_system_time(time)) + .map_or(FileTime::zero(), FileTime::from_system_time) } diff --git a/sailfish/src/runtime/escape/avx2.rs b/sailfish/src/runtime/escape/avx2.rs index 3a13635..d4282e1 100644 --- a/sailfish/src/runtime/escape/avx2.rs +++ b/sailfish/src/runtime/escape/avx2.rs @@ -53,7 +53,7 @@ pub unsafe fn escape(feed: &str, buffer: &mut Buffer) { ); buffer.push_str(std::str::from_utf8_unchecked(slc)); } - push_escaped_str(*ESCAPED.get_unchecked(c), buffer); + push_escaped_str(ESCAPED.get_unchecked(c), buffer); start_ptr = ptr2.add(1); } } @@ -82,7 +82,7 @@ pub unsafe fn escape(feed: &str, buffer: &mut Buffer) { ); buffer.push_str(std::str::from_utf8_unchecked(slc)); } - push_escaped_str(*ESCAPED.get_unchecked(c), buffer); + push_escaped_str(ESCAPED.get_unchecked(c), buffer); start_ptr = ptr2.add(1); } } @@ -129,7 +129,7 @@ unsafe fn escape_small(feed: &str, buffer: &mut Buffer) { slice::from_raw_parts(start_ptr, ptr2 as usize - start_ptr as usize); buffer.push_str(std::str::from_utf8_unchecked(slc)); } - push_escaped_str(*ESCAPED.get_unchecked(c), buffer); + push_escaped_str(ESCAPED.get_unchecked(c), buffer); start_ptr = ptr2.add(1); } } @@ -153,7 +153,7 @@ unsafe fn escape_small(feed: &str, buffer: &mut Buffer) { ); buffer.push_str(std::str::from_utf8_unchecked(slc)); } - push_escaped_str(*ESCAPED.get_unchecked(c), buffer); + push_escaped_str(ESCAPED.get_unchecked(c), buffer); start_ptr = ptr2.add(1); } } diff --git a/sailfish/src/runtime/escape/naive.rs b/sailfish/src/runtime/escape/naive.rs index f6fe85c..bd3a29a 100644 --- a/sailfish/src/runtime/escape/naive.rs +++ b/sailfish/src/runtime/escape/naive.rs @@ -39,7 +39,7 @@ pub(super) unsafe fn proceed( slice::from_raw_parts(start_ptr, ptr as usize - start_ptr as usize); buffer.push_str(std::str::from_utf8_unchecked(slc)); } - push_escaped_str(*ESCAPED.get_unchecked(idx), buffer); + push_escaped_str(ESCAPED.get_unchecked(idx), buffer); start_ptr = ptr.add(1); ptr = ptr.add(1); } diff --git a/sailfish/src/runtime/escape/sse2.rs b/sailfish/src/runtime/escape/sse2.rs index 750026d..0c1cb0c 100644 --- a/sailfish/src/runtime/escape/sse2.rs +++ b/sailfish/src/runtime/escape/sse2.rs @@ -46,7 +46,7 @@ pub unsafe fn escape(feed: &str, buffer: &mut Buffer) { ); buffer.push_str(std::str::from_utf8_unchecked(slc)); } - push_escaped_str(*ESCAPED.get_unchecked(c), buffer); + push_escaped_str(ESCAPED.get_unchecked(c), buffer); start_ptr = ptr2.add(1); } } @@ -75,7 +75,7 @@ pub unsafe fn escape(feed: &str, buffer: &mut Buffer) { ); buffer.push_str(std::str::from_utf8_unchecked(slc)); } - push_escaped_str(*ESCAPED.get_unchecked(c), buffer); + push_escaped_str(ESCAPED.get_unchecked(c), buffer); start_ptr = ptr2.add(1); } } diff --git a/sailfish/src/runtime/filter.rs b/sailfish/src/runtime/filter.rs index e151948..593dc33 100644 --- a/sailfish/src/runtime/filter.rs +++ b/sailfish/src/runtime/filter.rs @@ -68,7 +68,7 @@ impl<'a, T: Render + ?Sized> Render for Upper<'a, T> { let content = b.as_str().get(old_len..).ok_or(RenderError::BufSize)?; let s = content.to_uppercase(); unsafe { b._set_len(old_len) }; - b.push_str(&*s); + b.push_str(&s); Ok(()) } @@ -78,7 +78,7 @@ impl<'a, T: Render + ?Sized> Render for Upper<'a, T> { let s = b.as_str()[old_len..].to_uppercase(); unsafe { b._set_len(old_len) }; - b.push_str(&*s); + b.push_str(&s); Ok(()) } } @@ -112,7 +112,7 @@ impl<'a, T: Render + ?Sized> Render for Lower<'a, T> { let content = b.as_str().get(old_len..).ok_or(RenderError::BufSize)?; let s = content.to_lowercase(); unsafe { b._set_len(old_len) }; - b.push_str(&*s); + b.push_str(&s); Ok(()) } @@ -122,7 +122,7 @@ impl<'a, T: Render + ?Sized> Render for Lower<'a, T> { let s = b.as_str()[old_len..].to_lowercase(); unsafe { b._set_len(old_len) }; - b.push_str(&*s); + b.push_str(&s); Ok(()) } } diff --git a/sailfish/src/runtime/render.rs b/sailfish/src/runtime/render.rs index e9b3f70..357911c 100644 --- a/sailfish/src/runtime/render.rs +++ b/sailfish/src/runtime/render.rs @@ -78,13 +78,13 @@ pub trait Render { impl Render for String { #[inline] fn render(&self, b: &mut Buffer) -> Result<(), RenderError> { - b.push_str(&**self); + b.push_str(self); Ok(()) } #[inline] fn render_escaped(&self, b: &mut Buffer) -> Result<(), RenderError> { - escape::escape_to_buf(&**self, b); + escape::escape_to_buf(self, b); Ok(()) } } @@ -128,13 +128,13 @@ impl Render for PathBuf { #[inline] fn render(&self, b: &mut Buffer) -> Result<(), RenderError> { // TODO: speed up on Windows using OsStrExt - b.push_str(&*self.to_string_lossy()); + b.push_str(&self.to_string_lossy()); Ok(()) } #[inline] fn render_escaped(&self, b: &mut Buffer) -> Result<(), RenderError> { - escape::escape_to_buf(&*self.to_string_lossy(), b); + escape::escape_to_buf(&self.to_string_lossy(), b); Ok(()) } } @@ -143,13 +143,13 @@ impl Render for Path { #[inline] fn render(&self, b: &mut Buffer) -> Result<(), RenderError> { // TODO: speed up on Windows using OsStrExt - b.push_str(&*self.to_string_lossy()); + b.push_str(&self.to_string_lossy()); Ok(()) } #[inline] fn render_escaped(&self, b: &mut Buffer) -> Result<(), RenderError> { - escape::escape_to_buf(&*self.to_string_lossy(), b); + escape::escape_to_buf(&self.to_string_lossy(), b); Ok(()) } } @@ -388,7 +388,7 @@ impl RenderError { impl fmt::Display for RenderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - RenderError::Msg(ref s) => f.pad(&**s), + RenderError::Msg(ref s) => f.pad(s), RenderError::Fmt(ref e) => fmt::Display::fmt(e, f), RenderError::BufSize => f.pad("buffer size shrinked while rendering"), } diff --git a/sailfish/src/runtime/size_hint.rs b/sailfish/src/runtime/size_hint.rs index 030ac1d..bc6c02e 100644 --- a/sailfish/src/runtime/size_hint.rs +++ b/sailfish/src/runtime/size_hint.rs @@ -36,6 +36,12 @@ impl SizeHint { } } +impl Default for SizeHint { + fn default() -> Self { + Self::new() + } +} + #[test] fn test_update() { let hint = SizeHint::new();