Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply clippy lints for code readability #152

Merged
merged 1 commit into from
Jun 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions sailfish-compiler/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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);
Expand Down Expand Up @@ -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);

Expand All @@ -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
})
Expand Down
4 changes: 2 additions & 2 deletions sailfish-compiler/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
})?;
Expand Down Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions sailfish-compiler/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions sailfish-compiler/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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,
Expand Down
10 changes: 5 additions & 5 deletions sailfish-compiler/src/procmacro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Ident>()?;
Expand Down Expand Up @@ -161,7 +161,7 @@ fn derive_template_impl(tokens: TokenStream) -> Result<TokenStream, syn::Error>
"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))?
};

Expand All @@ -186,7 +186,7 @@ fn derive_template_impl(tokens: TokenStream) -> Result<TokenStream, syn::Error>
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(
Expand All @@ -204,9 +204,9 @@ fn derive_template_impl(tokens: TokenStream) -> Result<TokenStream, syn::Error>
// 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
Expand Down
14 changes: 5 additions & 9 deletions sailfish-compiler/src/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ macro_rules! return_if_some {
};
}

pub type IncludeHandler<'h> = Arc<dyn 'h + Fn(&Path) -> Result<Block, Error>>;
#[derive(Clone)]
pub struct Resolver<'h> {
include_handler: Arc<dyn 'h + Fn(&Path) -> Result<Block, Error>>,
include_handler: IncludeHandler<'h>,
}

impl<'h> Resolver<'h> {
Expand All @@ -40,10 +41,7 @@ impl<'h> Resolver<'h> {
}

#[inline]
pub fn include_handler(
mut self,
new: Arc<dyn 'h + Fn(&Path) -> Result<Block, Error>>,
) -> Resolver<'h> {
pub fn include_handler(mut self, new: IncludeHandler<'h>) -> Resolver<'h> {
self.include_handler = new;
self
}
Expand Down Expand Up @@ -78,7 +76,7 @@ struct ResolverImpl<'h> {
path_stack: Vec<PathBuf>,
deps: Vec<PathBuf>,
error: Option<Error>,
include_handler: Arc<dyn 'h + Fn(&Path) -> Result<Block, Error>>,
include_handler: IncludeHandler<'h>,
}

impl<'h> ResolverImpl<'h> {
Expand Down Expand Up @@ -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())
})?;

Expand Down Expand Up @@ -157,7 +155,6 @@ impl<'h> VisitMut for ResolverImpl<'h> {
Ok(e) => *i = Stmt::Expr(e, None),
Err(e) => {
self.error = Some(e);
return;
}
}
}
Expand All @@ -176,7 +173,6 @@ impl<'h> VisitMut for ResolverImpl<'h> {
Ok(e) => *i = e,
Err(e) => {
self.error = Some(e);
return;
}
}
}
Expand Down
34 changes: 17 additions & 17 deletions sailfish-compiler/src/translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,17 @@ impl Translator {
self
}

pub fn translate<'a>(
pub fn translate(
&self,
token_iter: ParseStream<'a>,
token_iter: ParseStream<'_>,
) -> Result<TranslatedSource, Error> {
let original_source = token_iter.original_source;

let mut ps = SourceBuilder::new(self.escape);
ps.reserve(original_source.len());
ps.feed_tokens(token_iter)?;

Ok(ps.finalize()?)
ps.finalize()
}
}

Expand Down Expand Up @@ -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(),
Expand All @@ -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
Expand All @@ -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> {
Expand Down Expand Up @@ -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
Expand All @@ -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);
}
}

Expand All @@ -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?;
Expand All @@ -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());
Expand All @@ -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)?;
}
}
Expand All @@ -249,14 +249,14 @@ impl SourceBuilder {

pub fn finalize(mut self) -> Result<TranslatedSource, Error> {
self.source.push_str("\n}");
match syn::parse_str::<Block>(&*self.source) {
match syn::parse_str::<Block>(&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 =
Expand Down
4 changes: 2 additions & 2 deletions sailfish-compiler/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub fn rustfmt_block(source: &str) -> io::Result<String> {
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())
Expand Down Expand Up @@ -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)
}
8 changes: 4 additions & 4 deletions sailfish/src/runtime/escape/avx2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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);
}
}
Expand All @@ -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);
}
}
Expand Down
2 changes: 1 addition & 1 deletion sailfish/src/runtime/escape/naive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
4 changes: 2 additions & 2 deletions sailfish/src/runtime/escape/sse2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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);
}
}
Expand Down
Loading
Loading