diff --git a/src/bin/cargo-fmt.rs b/src/bin/cargo-fmt.rs index 2c0ec3a84dcb..3d0a5589d37a 100644 --- a/src/bin/cargo-fmt.rs +++ b/src/bin/cargo-fmt.rs @@ -84,7 +84,7 @@ fn execute() -> i32 { let workspace_hitlist = WorkspaceHitlist::from_matches(&matches); - match format_crate(verbosity, workspace_hitlist) { + match format_crate(verbosity, &workspace_hitlist) { Err(e) => { print_usage(&opts, &e.to_string()); failure @@ -115,7 +115,7 @@ pub enum Verbosity { fn format_crate( verbosity: Verbosity, - workspace_hitlist: WorkspaceHitlist, + workspace_hitlist: &WorkspaceHitlist, ) -> Result { let targets = get_targets(workspace_hitlist)?; @@ -178,9 +178,9 @@ pub enum WorkspaceHitlist { } impl WorkspaceHitlist { - pub fn get_some<'a>(&'a self) -> Option<&'a [String]> { - if let &WorkspaceHitlist::Some(ref hitlist) = self { - Some(&hitlist) + pub fn get_some(&self) -> Option<&[String]> { + if let WorkspaceHitlist::Some(ref hitlist) = *self { + Some(hitlist) } else { None } @@ -196,9 +196,9 @@ impl WorkspaceHitlist { } // Returns a vector of all compile targets of a crate -fn get_targets(workspace_hitlist: WorkspaceHitlist) -> Result, std::io::Error> { +fn get_targets(workspace_hitlist: &WorkspaceHitlist) -> Result, std::io::Error> { let mut targets: Vec = vec![]; - if workspace_hitlist == WorkspaceHitlist::None { + if *workspace_hitlist == WorkspaceHitlist::None { let output = Command::new("cargo").arg("read-manifest").output()?; if output.status.success() { // None of the unwraps should fail if output of `cargo read-manifest` is correct @@ -229,7 +229,7 @@ fn get_targets(workspace_hitlist: WorkspaceHitlist) -> Result, std:: let data = &String::from_utf8(output.stdout).unwrap(); let json: Value = json::from_str(data).unwrap(); let json_obj = json.as_object().unwrap(); - let mut hitlist: HashSet<&String> = if workspace_hitlist != WorkspaceHitlist::All { + let mut hitlist: HashSet<&String> = if *workspace_hitlist != WorkspaceHitlist::All { HashSet::from_iter(workspace_hitlist.get_some().unwrap()) } else { HashSet::new() // Unused @@ -240,7 +240,7 @@ fn get_targets(workspace_hitlist: WorkspaceHitlist) -> Result, std:: .as_array() .unwrap() .into_iter() - .filter(|member| if workspace_hitlist == WorkspaceHitlist::All { + .filter(|member| if *workspace_hitlist == WorkspaceHitlist::All { true } else { let member_obj = member.as_object().unwrap(); @@ -248,7 +248,7 @@ fn get_targets(workspace_hitlist: WorkspaceHitlist) -> Result, std:: hitlist.take(&member_name.to_string()).is_some() }) .collect(); - if hitlist.len() != 0 { + if hitlist.is_empty() { // Mimick cargo of only outputting one spec. return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, diff --git a/src/bin/rustfmt.rs b/src/bin/rustfmt.rs index 5bb5190e810d..5b891dfd1db7 100644 --- a/src/bin/rustfmt.rs +++ b/src/bin/rustfmt.rs @@ -104,7 +104,7 @@ fn match_cli_path_or_file( let toml = Config::from_toml_path(config_file.as_ref())?; return Ok((toml, Some(config_file))); } - Config::from_resolved_toml_path(input_file).map_err(|e| FmtError::from(e)) + Config::from_resolved_toml_path(input_file).map_err(FmtError::from) } fn make_opts() -> Options { @@ -161,21 +161,21 @@ fn execute(opts: &Options) -> FmtResult { Operation::Help => { print_usage(opts, ""); Summary::print_exit_codes(); - Ok(Summary::new()) + Ok(Summary::default()) } Operation::Version => { print_version(); - Ok(Summary::new()) + Ok(Summary::default()) } Operation::ConfigHelp => { Config::print_docs(); - Ok(Summary::new()) + Ok(Summary::default()) } Operation::ConfigOutputDefault { path } => { let mut file = File::create(path)?; let toml = Config::default().all_options().to_toml()?; file.write_all(toml.as_bytes())?; - Ok(Summary::new()) + Ok(Summary::default()) } Operation::Stdin { input, config_path } => { // try to read config from local directory @@ -222,7 +222,7 @@ fn execute(opts: &Options) -> FmtResult { } } - let mut error_summary = Summary::new(); + let mut error_summary = Summary::default(); for file in files { if !file.exists() { println!("Error: file `{}` does not exist", file.to_str().unwrap()); @@ -354,7 +354,7 @@ fn determine_operation(matches: &Matches) -> FmtResult { return config_path_not_found(path.to_str().unwrap()); } } - path @ _ => path, + path => path, }; // If no path is given, we won't output a minimal config. diff --git a/src/chains.rs b/src/chains.rs index 27119dd6f0dd..411c3c7f45ff 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -256,7 +256,7 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) - "{}{}{}", parent_rewrite, first_connector, - join_rewrites(&rewrites, &subexpr_list, &connector) + join_rewrites(&rewrites, subexpr_list, &connector) ) }; let result = format!("{}{}", result, repeat_try(suffix_try_num)); @@ -475,7 +475,7 @@ fn rewrite_method_call( let type_list: Vec<_> = try_opt!(types.iter().map(|ty| ty.rewrite(context, shape)).collect()); - let type_str = if context.config.spaces_within_angle_brackets() && type_list.len() > 0 { + let type_str = if context.config.spaces_within_angle_brackets() && !type_list.is_empty() { format!("::< {} >", type_list.join(", ")) } else { format!("::<{}>", type_list.join(", ")) diff --git a/src/codemap.rs b/src/codemap.rs index e156f34015b6..f62bb16dfa22 100644 --- a/src/codemap.rs +++ b/src/codemap.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! This module contains utilities that work with the `CodeMap` from libsyntax / syntex_syntax. +//! This module contains utilities that work with the `CodeMap` from `libsyntax` / `syntex_syntax`. //! This includes extension traits and methods for looking up spans and line ranges for AST nodes. use std::rc::Rc; @@ -77,8 +77,9 @@ impl LineRangeUtils for CodeMap { let lo = self.lookup_char_pos(span.lo()); let hi = self.lookup_char_pos(span.hi()); - assert!( - lo.file.name == hi.file.name, + assert_eq!( + lo.file.name, + hi.file.name, "span crossed file boundary: lo: {:?}, hi: {:?}", lo, hi diff --git a/src/comment.rs b/src/comment.rs index aa078f4dbf7c..4cb8325d25ea 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -23,16 +23,14 @@ use utils::{first_line_width, last_line_width, wrap_str}; fn is_custom_comment(comment: &str) -> bool { if !comment.starts_with("//") { false + } else if let Some(c) = comment.chars().nth(2) { + !c.is_alphanumeric() && !c.is_whitespace() } else { - if let Some(c) = comment.chars().nth(2) { - !c.is_alphanumeric() && !c.is_whitespace() - } else { - false - } + false } } -#[derive(PartialEq, Eq)] +#[derive(Copy, Clone, PartialEq, Eq)] pub enum CommentStyle<'a> { DoubleSlash, TripleSlash, @@ -194,17 +192,15 @@ pub fn combine_strs_with_missing_comments( }; let second_sep = if missing_comment.is_empty() || next_str.is_empty() { String::new() + } else if missing_comment.starts_with("//") { + format!("\n{}", indent_str) } else { - if missing_comment.starts_with("//") { - format!("\n{}", indent_str) + one_line_width += missing_comment.len() + first_sep.len() + 1; + allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n'); + if prefer_same_line && allow_one_line && one_line_width <= shape.width { + String::from(" ") } else { - one_line_width += missing_comment.len() + first_sep.len() + 1; - allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n'); - if prefer_same_line && allow_one_line && one_line_width <= shape.width { - String::from(" ") - } else { - format!("\n{}", indent_str) - } + format!("\n{}", indent_str) } }; Some(format!( @@ -314,7 +310,7 @@ fn rewrite_comment_inner( line = line.trim(); // Drop old closer. if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") { - line = &line[..(line.len() - 2)].trim_right(); + line = line[..(line.len() - 2)].trim_right(); } line @@ -339,7 +335,7 @@ fn rewrite_comment_inner( } if config.wrap_comments() && line.len() > max_chars { - let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned()); + let rewrite = rewrite_string(line, &fmt).unwrap_or_else(|| line.to_owned()); result.push_str(&rewrite); } else { if line.is_empty() && result.ends_with(' ') { @@ -412,7 +408,7 @@ fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option< // `*` in `/*`. let first_non_whitespace = l.find(|c| !char::is_whitespace(c)); if let Some(fnw) = first_non_whitespace { - if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 { + if l.as_bytes()[fnw] == b'*' && fnw > 0 { &l[fnw - 1..] } else { &l[fnw..] @@ -432,7 +428,7 @@ fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str { line.starts_with("/** ") { &line[4..] - } else if let &CommentStyle::Custom(opener) = style { + } else if let CommentStyle::Custom(opener) = *style { if line.starts_with(opener) { &line[opener.len()..] } else { @@ -646,7 +642,7 @@ where _ => CharClassesStatus::Normal, }, CharClassesStatus::BlockComment(deepness) => { - assert!(deepness != 0); + assert_ne!(deepness, 0); self.status = match self.base.peek() { Some(next) if next.get_char() == '/' && chr == '*' => { CharClassesStatus::BlockCommentClosing(deepness - 1) @@ -901,10 +897,8 @@ impl<'a> Iterator for CommentReducer<'a> { if c == '*' { c = try_opt!(self.iter.next()); } - } else { - if c == '\n' { - self.at_start_line = true; - } + } else if c == '\n' { + self.at_start_line = true; } if !c.is_whitespace() { return Some(c); diff --git a/src/config.rs b/src/config.rs index 31eccf249419..30d79cdc5629 100644 --- a/src/config.rs +++ b/src/config.rs @@ -306,7 +306,7 @@ macro_rules! create_config { let table = parsed .as_table() .ok_or(String::from("Parsed config was not table"))?; - for (key, _) in table { + for key in table.keys() { match &**key { $( stringify!($i) => (), diff --git a/src/expr.rs b/src/expr.rs index ffab5b02f5ad..3cfbf023faf7 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -44,7 +44,7 @@ impl Rewrite for ast::Expr { } } -#[derive(PartialEq)] +#[derive(Copy, Clone, PartialEq)] pub enum ExprType { Statement, SubExpression, @@ -249,7 +249,7 @@ pub fn format_expr( } match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) { - (Some(ref lhs), Some(ref rhs)) => { + (Some(lhs), Some(rhs)) => { let sp_delim = if context.config.spaces_around_ranges() { format!(" {} ", delim) } else if needs_space_before_range(context, lhs) { @@ -257,23 +257,23 @@ pub fn format_expr( } else { delim.into() }; - rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape) + rewrite_pair(&*lhs, &*rhs, "", &sp_delim, "", context, shape) } - (None, Some(ref rhs)) => { + (None, Some(rhs)) => { let sp_delim = if context.config.spaces_around_ranges() { format!("{} ", delim) } else { delim.into() }; - rewrite_unary_prefix(context, &sp_delim, &**rhs, shape) + rewrite_unary_prefix(context, &sp_delim, &*rhs, shape) } - (Some(ref lhs), None) => { + (Some(lhs), None) => { let sp_delim = if context.config.spaces_around_ranges() { format!(" {}", delim) } else { delim.into() }; - rewrite_unary_suffix(context, &sp_delim, &**lhs, shape) + rewrite_unary_suffix(context, &sp_delim, &*lhs, shape) } (None, None) => wrap_str(delim.into(), context.config.max_width(), shape), } @@ -488,7 +488,7 @@ where let result = if context.config.array_layout() == IndentStyle::Visual || tactic == DefinitiveListTactic::Horizontal { - if context.config.spaces_within_square_brackets() && list_str.len() > 0 { + if context.config.spaces_within_square_brackets() && !list_str.is_empty() { format!("[ {} ]", list_str) } else { format!("[{}]", list_str) @@ -631,7 +631,7 @@ fn rewrite_closure( }; if no_return_type && !needs_block { // lock.stmts.len() == 1 - if let Some(ref expr) = stmt_expr(&block.stmts[0]) { + if let Some(expr) = stmt_expr(&block.stmts[0]) { if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) { return Some(rw); } @@ -651,7 +651,7 @@ fn rewrite_closure( } // Either we require a block, or tried without and failed. - rewrite_closure_block(&block, &prefix, context, body_shape) + rewrite_closure_block(block, &prefix, context, body_shape) } else { rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| { // The closure originally had a non-block expression, but we can't fit on @@ -715,7 +715,7 @@ fn rewrite_closure_block( // closure is large. let block_threshold = context.config.closure_block_indent_threshold(); if block_threshold >= 0 { - if let Some(block_str) = block.rewrite(&context, shape) { + if let Some(block_str) = block.rewrite(context, shape) { if block_str.matches('\n').count() <= block_threshold as usize && !need_block_indent(&block_str, shape) { @@ -729,7 +729,7 @@ fn rewrite_closure_block( // The body of the closure is big enough to be block indented, that // means we must re-format. let block_shape = shape.block(); - let block_str = try_opt!(block.rewrite(&context, block_shape)); + let block_str = try_opt!(block.rewrite(context, block_shape)); Some(format!("{} {}", prefix, block_str)) } @@ -1644,7 +1644,7 @@ fn rewrite_match_arm( fn rewrite_match_pattern( context: &RewriteContext, - pats: &Vec>, + pats: &[ptr::P], guard: &Option>, shape: Shape, ) -> Option { @@ -1722,9 +1722,9 @@ fn rewrite_match_body( has_guard: bool, is_last: bool, ) -> Option { - let (extend, body) = flatten_arm_body(context, &body); + let (extend, body) = flatten_arm_body(context, body); - let comma = arm_comma(&context.config, body, is_last); + let comma = arm_comma(context.config, body, is_last); let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config); let alt_block_sep = alt_block_sep.as_str(); let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node { @@ -1790,7 +1790,7 @@ fn rewrite_match_body( // Let's try and get the arm body on the same line as the condition. // 4 = ` => `.len() let orig_body_shape = shape - .offset_left(extra_offset(&pats_str, shape) + 4) + .offset_left(extra_offset(pats_str, shape) + 4) .and_then(|shape| shape.sub_width(comma.len())); let orig_body = if let Some(body_shape) = orig_body_shape { let rewrite = nop_block_collapse( @@ -1985,10 +1985,8 @@ fn string_requires_rewrite( if line.len() > shape.width { return true; } - } else { - if line.len() > shape.width + shape.indent.width() { - return true; - } + } else if line.len() > shape.width + shape.indent.width() { + return true; } } @@ -2049,7 +2047,7 @@ pub fn rewrite_call( }; rewrite_call_inner( context, - &callee, + callee, &args.iter().map(|x| &**x).collect::>(), span, shape, @@ -2076,7 +2074,7 @@ where } else { 1 }; - let used_width = extra_offset(&callee_str, shape); + let used_width = extra_offset(callee_str, shape); let one_line_width = shape .width .checked_sub(used_width + 2 * paren_overhead) @@ -2117,7 +2115,7 @@ where } let args_shape = shape - .sub_width(last_line_width(&callee_str)) + .sub_width(last_line_width(callee_str)) .ok_or(Ordering::Less)?; Ok(format!( "{}{}", @@ -2203,19 +2201,18 @@ fn try_overflow_last_arg<'a, T>( where T: Rewrite + Spanned + ToExpr + 'a, { - let overflow_last = can_be_overflowed(&context, args); + let overflow_last = can_be_overflowed(context, args); // Replace the last item with its first line to see if it fits with // first arguments. let placeholder = if overflow_last { let mut context = context.clone(); if let Some(expr) = args[args.len() - 1].to_expr() { - match expr.node { - ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true, - _ => (), + if let ast::ExprKind::MethodCall(..) = expr.node { + context.force_one_line_chain = true; } } - last_arg_shape(&context, &item_vec, shape, args_max_width).and_then(|arg_shape| { + last_arg_shape(&context, item_vec, shape, args_max_width).and_then(|arg_shape| { rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape) }) } else { @@ -2253,12 +2250,12 @@ where fn last_arg_shape( context: &RewriteContext, - items: &Vec, + items: &[ListItem], shape: Shape, args_max_width: usize, ) -> Option { let overhead = items.iter().rev().skip(1).fold(0, |acc, i| { - acc + i.item.as_ref().map_or(0, |s| first_line_width(&s)) + acc + i.item.as_ref().map_or(0, |s| first_line_width(s)) }); let max_width = min(args_max_width, shape.width); let arg_indent = if context.use_block_indent() { @@ -2413,7 +2410,7 @@ pub fn wrap_args_with_parens( (context.inside_macro && !args_str.contains('\n') && args_str.len() + paren_overhead(context) <= shape.width) || is_extendable { - if context.config.spaces_within_parens() && args_str.len() > 0 { + if context.config.spaces_within_parens() && !args_str.is_empty() { format!("( {} )", args_str) } else { format!("({})", args_str) @@ -2445,7 +2442,7 @@ fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> .and_then(|s| s.sub_width(paren_overhead)) ); - let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 { + let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && !s.is_empty() { format!("( {} )", s) } else { format!("({})", s) @@ -2505,7 +2502,7 @@ fn rewrite_index( (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!( "{}\n{}{}{}{}", expr_str, - indent.to_string(&context.config), + indent.to_string(context.config), lbr, new_index_str, rbr @@ -2513,7 +2510,7 @@ fn rewrite_index( (None, Some(ref new_index_str)) => Some(format!( "{}\n{}{}{}{}", expr_str, - indent.to_string(&context.config), + indent.to_string(context.config), lbr, new_index_str, rbr @@ -2556,7 +2553,7 @@ fn rewrite_struct_lit<'a>( path_shape, )); - if fields.len() == 0 && base.is_none() { + if fields.is_empty() && base.is_none() { return Some(format!("{} {{}}", path_str)); } @@ -2706,7 +2703,7 @@ pub fn rewrite_field( "{}{}:\n{}{}", attrs_str, name, - expr_offset.to_string(&context.config), + expr_offset.to_string(context.config), s ) }) @@ -2789,7 +2786,7 @@ where }; let list_str = try_opt!(write_list(&item_vec, &fmt)); - if context.config.spaces_within_parens() && list_str.len() > 0 { + if context.config.spaces_within_parens() && !list_str.is_empty() { Some(format!("( {} )", list_str)) } else { Some(format!("({})", list_str)) diff --git a/src/file_lines.rs b/src/file_lines.rs index 7df4dbb73994..704a89017d01 100644 --- a/src/file_lines.rs +++ b/src/file_lines.rs @@ -95,7 +95,7 @@ fn normalize_ranges(ranges: &mut HashMap>) { { let mut iter = ranges.into_iter().peekable(); while let Some(next) = iter.next() { - let mut next = next.clone(); + let mut next = *next; while let Some(&&mut peek) = iter.peek() { if let Some(merged) = next.merge(peek) { iter.next().unwrap(); @@ -166,7 +166,7 @@ impl FileLines { } } -/// FileLines files iterator. +/// `FileLines` files iterator. pub struct Files<'a>( Option<::std::collections::hash_map::Keys<'a, String, Vec>>, ); @@ -197,9 +197,9 @@ impl str::FromStr for FileLines { fn from_str(s: &str) -> Result { let v: Vec = json::from_str(s).map_err(|e| e.to_string())?; let mut m = HashMap::new(); - for js in v.into_iter() { + for js in v { let (s, r) = JsonSpan::into_tuple(js)?; - m.entry(s).or_insert(vec![]).push(r); + m.entry(s).or_insert_with(|| vec![]).push(r); } Ok(FileLines::from_ranges(m)) } diff --git a/src/imports.rs b/src/imports.rs index 04492665d70f..33efce19a40a 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -25,8 +25,8 @@ use visitor::FmtVisitor; fn path_of(a: &ast::ViewPath_) -> &ast::Path { match *a { - ast::ViewPath_::ViewPathSimple(_, ref p) => p, - ast::ViewPath_::ViewPathGlob(ref p) => p, + ast::ViewPath_::ViewPathSimple(_, ref p) | + ast::ViewPath_::ViewPathGlob(ref p) | ast::ViewPath_::ViewPathList(ref p, _) => p, } } @@ -54,12 +54,10 @@ fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Orde } else { Ordering::Less } + } else if b_name_str == "self" { + Ordering::Greater } else { - if b_name_str == "self" { - Ordering::Greater - } else { - a_name_str.cmp(&b_name_str) - } + a_name_str.cmp(b_name_str) }; if name_ordering == Ordering::Equal { match a.node.rename { @@ -137,7 +135,7 @@ fn rewrite_view_path_prefix( path.segments.len() > 1 { let path = &ast::Path { - span: path.span.clone(), + span: path.span, segments: path.segments[..path.segments.len() - 1].to_owned(), }; try_opt!(rewrite_path( diff --git a/src/items.rs b/src/items.rs index 8c81aed87e61..d5369e33ef8a 100644 --- a/src/items.rs +++ b/src/items.rs @@ -80,7 +80,7 @@ impl Rewrite for ast::Local { let pat_shape = try_opt!(shape.offset_left(4)); // 1 = ; let pat_shape = try_opt!(pat_shape.sub_width(1)); - let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape)); + let pat_str = try_opt!(self.pat.rewrite(context, pat_shape)); result.push_str(&pat_str); // String that is placed within the assignment pattern and expression. @@ -111,7 +111,7 @@ impl Rewrite for ast::Local { // 1 = trailing semicolon; let nested_shape = try_opt!(shape.sub_width(1)); - result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape)); + result = try_opt!(rewrite_assign_rhs(context, result, ex, nested_shape)); } result.push(';'); @@ -195,7 +195,7 @@ impl<'a> FmtVisitor<'a> { fn format_body_element(&mut self, element: &BodyElement) { match *element { - BodyElement::ForeignItem(ref item) => self.format_foreign_item(item), + BodyElement::ForeignItem(item) => self.format_foreign_item(item), } } @@ -321,7 +321,7 @@ impl<'a> FmtVisitor<'a> { if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) { let rewrite = { - if let Some(ref stmt) = block.stmts.first() { + if let Some(stmt) = block.stmts.first() { match stmt_expr(stmt) { Some(e) => { let suffix = if semicolon_for_expr(&self.get_context(), e) { @@ -568,10 +568,10 @@ pub fn format_impl( if try_opt!(is_impl_single_line( context, - &items, + items, &result, &where_clause_str, - &item, + item, )) { result.push_str(&where_clause_str); if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) { @@ -674,7 +674,7 @@ fn format_impl_ref_and_type( let mut result = String::with_capacity(128); result.push_str(&format_visibility(&item.vis)); - result.push_str(&format_defaultness(defaultness)); + result.push_str(format_defaultness(defaultness)); result.push_str(format_unsafety(unsafety)); result.push_str("impl"); @@ -707,7 +707,7 @@ fn format_impl_ref_and_type( let result_len = result.len(); if let Some(trait_ref_str) = rewrite_trait_ref( context, - &trait_ref, + trait_ref, offset, &generics_str, true, @@ -725,7 +725,7 @@ fn format_impl_ref_and_type( )); result.push_str(&try_opt!(rewrite_trait_ref( context, - &trait_ref, + trait_ref, offset, &generics_str, false, @@ -1079,7 +1079,7 @@ pub fn format_struct_struct( { result.push('\n'); result.push_str(&offset.to_string(context.config)); - result.push_str(&generics_str.trim_left()); + result.push_str(generics_str.trim_left()); } else { result.push_str(&generics_str); } @@ -1090,7 +1090,7 @@ pub fn format_struct_struct( // `struct S {}` } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') { // fix indent - result.push_str(&snippet.trim_right()); + result.push_str(snippet.trim_right()); result.push('\n'); result.push_str(&offset.to_string(context.config)); } else { @@ -1153,7 +1153,7 @@ fn format_tuple_struct( } else { // This is a dirty hack to work around a missing `)` from the span of the last field. let last_arg_span = fields[fields.len() - 1].span; - if context.snippet(last_arg_span).ends_with(")") { + if context.snippet(last_arg_span).ends_with(')') { last_arg_span.hi() } else { context @@ -1201,7 +1201,7 @@ fn format_tuple_struct( if snippet.is_empty() { // `struct S ()` } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') { - result.push_str(&snippet.trim_right()); + result.push_str(snippet.trim_right()); result.push('\n'); result.push_str(&offset.to_string(context.config)); } else { @@ -1401,7 +1401,7 @@ pub fn rewrite_struct_field( let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape); if let Some(ref ty) = ty_rewritten { if !ty.contains('\n') { - return Some(attr_prefix + &ty); + return Some(attr_prefix + ty); } } @@ -1422,17 +1422,17 @@ pub fn rewrite_struct_field( Some(ref new_ty) if !new_ty.contains('\n') => format!( "{}\n{}{}", prefix, - type_offset.to_string(&context.config), + type_offset.to_string(context.config), &new_ty ), - _ => prefix + &ty, + _ => prefix + ty, }, _ => { let ty = try_opt!(rewrite_type_in_next_line()); format!( "{}\n{}{}", prefix, - type_offset.to_string(&context.config), + type_offset.to_string(context.config), &ty ) } @@ -1515,7 +1515,7 @@ pub fn rewrite_associated_type( .map(|ty_bound| ty_bound.rewrite(context, shape)) .collect::>>() ); - if bounds.len() > 0 { + if !bounds.is_empty() { format!(": {}", join_bounds(context, shape, &bound_str)) } else { String::new() @@ -1755,7 +1755,7 @@ fn rewrite_fn_base( // return type later anyway. let ret_str = try_opt!( fd.output - .rewrite(&context, Shape::indented(indent, context.config)) + .rewrite(context, Shape::indented(indent, context.config)) ); let multi_line_ret_str = ret_str.contains('\n'); @@ -1783,26 +1783,24 @@ fn rewrite_fn_base( if one_line_budget == 0 { if snuggle_angle_bracket { result.push('('); + } else if context.config.fn_args_paren_newline() { + result.push('\n'); + result.push_str(&arg_indent.to_string(context.config)); + if context.config.fn_args_layout() == IndentStyle::Visual { + arg_indent = arg_indent + 1; // extra space for `(` + } + result.push('('); } else { - if context.config.fn_args_paren_newline() { + result.push_str("("); + if context.config.fn_args_layout() == IndentStyle::Visual { result.push('\n'); result.push_str(&arg_indent.to_string(context.config)); - if context.config.fn_args_layout() == IndentStyle::Visual { - arg_indent = arg_indent + 1; // extra space for `(` - } - result.push('('); - } else { - result.push_str("("); - if context.config.fn_args_layout() == IndentStyle::Visual { - result.push('\n'); - result.push_str(&arg_indent.to_string(context.config)); - } } } } else { result.push('('); } - if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') { + if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') { result.push(' ') } @@ -1857,10 +1855,10 @@ fn rewrite_fn_base( let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str); // Put the closing brace on the next line if it overflows the max width. // 1 = `)` - if fd.inputs.len() == 0 && used_width + 1 > context.config.max_width() { + if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() { result.push('\n'); } - if context.config.spaces_within_parens() && fd.inputs.len() > 0 { + if context.config.spaces_within_parens() && !fd.inputs.is_empty() { result.push(' ') } // If the last line of args contains comment, we cannot put the closing paren @@ -1881,7 +1879,7 @@ fn rewrite_fn_base( if let ast::FunctionRetTy::Ty(..) = fd.output { let ret_should_indent = match context.config.fn_args_layout() { // If our args are block layout then we surely must have space. - IndentStyle::Block if put_args_in_block || fd.inputs.len() == 0 => false, + IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false, _ if args_last_line_contains_comment => false, _ if result.contains('\n') || multi_line_ret_str => true, _ => { @@ -2024,9 +2022,10 @@ fn rewrite_fn_base( result.push_str(&where_clause_str); force_new_line_for_brace |= last_line_contains_single_line_comment(&result); - return Some((result, force_new_line_for_brace)); + Some((result, force_new_line_for_brace)) } +#[derive(Copy, Clone)] struct WhereClauseOption { suppress_comma: bool, // Force no trailing comma snuggle: bool, // Do not insert newline before `where` @@ -2074,7 +2073,7 @@ fn rewrite_args( let mut arg_item_strs = try_opt!( args.iter() .map(|arg| { - arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent)) + arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)) }) .collect::>>() ); @@ -2156,7 +2155,7 @@ fn rewrite_args( } let fits_in_one_line = !generics_str_contains_newline && - (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget); + (arg_items.is_empty() || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget); for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) { item.item = Some(arg); @@ -2441,7 +2440,7 @@ fn rewrite_trait_bounds( let bound_str = try_opt!( bounds .iter() - .map(|ty_bound| ty_bound.rewrite(&context, shape)) + .map(|ty_bound| ty_bound.rewrite(context, shape)) .collect::>>() ); Some(format!(": {}", join_bounds(context, shape, &bound_str))) diff --git a/src/lib.rs b/src/lib.rs index 8152973af43d..3c070d25c004 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -504,7 +504,7 @@ impl FormattingError { fn msg_suffix(&self) -> String { match self.kind { - ErrorKind::LineOverflow(..) if self.is_comment => format!( + ErrorKind::LineOverflow(..) if self.is_comment => String::from( "use `error_on_line_overflow_comments = false` to suppress \ the warning against line comments\n", ), @@ -802,9 +802,8 @@ fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &m last_wspace = Some(b); } } else if c == '/' { - match prev_char { - Some('/') => is_comment = true, - _ => (), + if let Some('/') = prev_char { + is_comment = true; } last_wspace = None; } else { @@ -869,7 +868,7 @@ pub fn format_input( config: &Config, mut out: Option<&mut T>, ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> { - let mut summary = Summary::new(); + let mut summary = Summary::default(); if config.disable_all_formatting() { return Ok((summary, FileMap::new(), FormatReport::new())); } diff --git a/src/lists.rs b/src/lists.rs index a9d705b4c649..301e9101c8f5 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -20,7 +20,7 @@ use rewrite::RewriteContext; use utils::{first_line_width, last_line_width, mk_sp}; /// Formatting tactic for lists. This will be cast down to a -/// DefinitiveListTactic depending on the number and length of the items and +/// `DefinitiveListTactic` depending on the number and length of the items and /// their comments. #[derive(Eq, PartialEq, Debug, Copy, Clone)] pub enum ListTactic { @@ -172,7 +172,7 @@ impl DefinitiveListTactic { } /// The type of separator for lists. -#[derive(Eq, PartialEq, Debug)] +#[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum Separator { Comma, VerticalBar, @@ -346,9 +346,9 @@ where if tactic == DefinitiveListTactic::Vertical { // We cannot keep pre-comments on the same line if the comment if normalized. - let keep_comment = if formatting.config.normalize_comments() { - false - } else if item.pre_comment_style == ListItemCommentStyle::DifferentLine { + let keep_comment = if formatting.config.normalize_comments() || + item.pre_comment_style == ListItemCommentStyle::DifferentLine + { false } else { // We will try to keep the comment on the same line with the item here. @@ -405,7 +405,7 @@ where formatting.config.max_width(), )); } - let overhead = if let &mut Some(max_width) = item_max_width { + let overhead = if let Some(max_width) = *item_max_width { max_width + 2 } else { // 1 = space between item and comment. @@ -548,8 +548,7 @@ where .chars() .rev() .take(comment_end + 1) - .find(|c| *c == '\n') - .is_some() + .any(|c| c == '\n') { ( Some(trimmed_pre_snippet.to_owned()), @@ -612,7 +611,7 @@ where } None => post_snippet .find_uncommented(self.terminator) - .unwrap_or(post_snippet.len()), + .unwrap_or_else(|| post_snippet.len()), }; if !post_snippet.is_empty() && comment_end > 0 { @@ -621,12 +620,14 @@ where // Everything from the separator to the next item. let test_snippet = &post_snippet[comment_end - 1..]; - let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len()); + let first_newline = test_snippet + .find('\n') + .unwrap_or_else(|| test_snippet.len()); // From the end of the first line of comments. let test_snippet = &test_snippet[first_newline..]; let first = test_snippet .find(|c: char| !c.is_whitespace()) - .unwrap_or(test_snippet.len()); + .unwrap_or_else(|| test_snippet.len()); // From the end of the first line of comments to the next non-whitespace char. let test_snippet = &test_snippet[..first]; @@ -747,7 +748,7 @@ pub fn struct_lit_shape( IndentStyle::Block => { let shape = shape.block_indent(context.config.tab_spaces()); Shape { - width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())), + width: context.budget(shape.indent.width()), ..shape } } diff --git a/src/macros.rs b/src/macros.rs index d9156e08e85a..4378febc2c37 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -224,7 +224,7 @@ pub fn rewrite_macro( // If we are rewriting `vec!` macro or other special macros, // then we can rewrite this as an usual array literal. // Otherwise, we must preserve the original existence of trailing comma. - if FORCED_BRACKET_MACROS.contains(&¯o_name.as_str()) { + if FORCED_BRACKET_MACROS.contains(¯o_name.as_str()) { context.inside_macro = false; trailing_comma = false; } @@ -355,8 +355,7 @@ fn indent_macro_snippet( fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize { let mut width = 0; - let mut iter = s.chars(); - while let Some(c) = iter.next() { + for c in s.chars() { match c { ' ' => width += 1, '\t' => width += context.config.tab_spaces(), diff --git a/src/missed_spans.rs b/src/missed_spans.rs index 43e81e12f714..301e1583029c 100644 --- a/src/missed_spans.rs +++ b/src/missed_spans.rs @@ -90,7 +90,7 @@ impl<'a> FmtVisitor<'a> { let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index]; let big_diff = (span.lo() - big_span_lo).to_usize(); - let snippet = self.snippet(span.clone()); + let snippet = self.snippet(span); debug!("write_snippet `{}`", snippet); @@ -180,7 +180,7 @@ impl<'a> FmtVisitor<'a> { last_wspace = None; line_start = offset + subslice.len(); - if let Some('/') = subslice.chars().skip(1).next() { + if let Some('/') = subslice.chars().nth(1) { // check that there are no contained block comments if !subslice .split('\n') diff --git a/src/patterns.rs b/src/patterns.rs index 70d94f4bee72..c3475dfba73a 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -139,7 +139,7 @@ fn rewrite_struct_pat( path_shape, )); - if fields.len() == 0 && !elipses { + if fields.is_empty() && !elipses { return Some(format!("{} {{}}", path_str)); } @@ -223,7 +223,7 @@ pub enum TuplePatField<'a> { impl<'a> Rewrite for TuplePatField<'a> { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option { match *self { - TuplePatField::Pat(ref p) => p.rewrite(context, shape), + TuplePatField::Pat(p) => p.rewrite(context, shape), TuplePatField::Dotdot(_) => Some("..".to_string()), } } @@ -232,15 +232,15 @@ impl<'a> Rewrite for TuplePatField<'a> { impl<'a> Spanned for TuplePatField<'a> { fn span(&self) -> Span { match *self { - TuplePatField::Pat(ref p) => p.span(), + TuplePatField::Pat(p) => p.span(), TuplePatField::Dotdot(span) => span, } } } pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool { - match pat { - &TuplePatField::Pat(ref pat) => match pat.node { + match *pat { + TuplePatField::Pat(pat) => match pat.node { ast::PatKind::Path(..) | ast::PatKind::Tuple(..) | ast::PatKind::Struct(..) => { context.use_block_indent() && len == 1 } @@ -250,7 +250,7 @@ pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len), _ => false, }, - &TuplePatField::Dotdot(..) => false, + TuplePatField::Dotdot(..) => false, } } @@ -288,7 +288,7 @@ fn rewrite_tuple_pat( } if pat_vec.is_empty() { - return Some(format!("{}()", path_str.unwrap_or(String::new()))); + return Some(format!("{}()", path_str.unwrap_or_default())); } let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape); @@ -313,12 +313,13 @@ fn rewrite_tuple_pat( if let Some(&TuplePatField::Dotdot(..)) = pat_vec.last() { context.inside_macro = true; } - let path_str = path_str.unwrap_or(String::new()); + let path_str = path_str.unwrap_or_default(); let mut pat_ref_vec = Vec::with_capacity(pat_vec.len()); for pat in pat_vec { pat_ref_vec.push(pat); } - return rewrite_call_inner( + + rewrite_call_inner( &context, &path_str, &pat_ref_vec[..], @@ -326,7 +327,7 @@ fn rewrite_tuple_pat( shape, shape.width, add_comma, - ).ok(); + ).ok() } fn count_wildcard_suffix_len( diff --git a/src/summary.rs b/src/summary.rs index 065e357ea956..7ca885a645c2 100644 --- a/src/summary.rs +++ b/src/summary.rs @@ -1,5 +1,5 @@ #[must_use] -#[derive(Debug, Clone)] +#[derive(Debug, Default, Clone)] pub struct Summary { // Encountered e.g. an IO error. has_operational_errors: bool, @@ -15,15 +15,6 @@ pub struct Summary { } impl Summary { - pub fn new() -> Summary { - Summary { - has_operational_errors: false, - has_parsing_errors: false, - has_formatting_errors: false, - has_diff: false, - } - } - pub fn has_operational_errors(&self) -> bool { self.has_operational_errors } diff --git a/src/types.rs b/src/types.rs index 86a6e4d3d726..027f9a9baffe 100644 --- a/src/types.rs +++ b/src/types.rs @@ -447,7 +447,7 @@ impl Rewrite for ast::WherePredicate { ); let bounds_str = join_bounds(context, ty_shape, &bounds); - if context.config.spaces_within_angle_brackets() && lifetime_str.len() > 0 { + if context.config.spaces_within_angle_brackets() && !lifetime_str.is_empty() { format!( "for< {} > {}{}{}", lifetime_str, @@ -635,7 +635,7 @@ impl Rewrite for ast::PolyTraitRef { )); Some( - if context.config.spaces_within_angle_brackets() && lifetime_str.len() > 0 { + if context.config.spaces_within_angle_brackets() && !lifetime_str.is_empty() { format!("for< {} > {}", lifetime_str, path_str) } else { format!("for<{}> {}", lifetime_str, path_str) @@ -812,7 +812,7 @@ fn rewrite_bare_fn( Some(result) } -pub fn join_bounds(context: &RewriteContext, shape: Shape, type_strs: &Vec) -> String { +pub fn join_bounds(context: &RewriteContext, shape: Shape, type_strs: &[String]) -> String { // Try to join types in a single line let joiner = match context.config.type_punctuation_density() { TypeDensity::Compressed => "+", diff --git a/src/utils.rs b/src/utils.rs index f99e1958f8c9..438bb027637e 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -123,7 +123,7 @@ pub fn last_line_contains_single_line_comment(s: &str) -> bool { #[inline] pub fn is_attributes_extendable(attrs_str: &str) -> bool { - !attrs_str.contains('\n') && !last_line_contains_single_line_comment(&attrs_str) + !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str) } // The width of the first line in s. diff --git a/src/vertical.rs b/src/vertical.rs index 600bdeaba3a0..f0cb887c59dc 100644 --- a/src/vertical.rs +++ b/src/vertical.rs @@ -284,13 +284,7 @@ fn group_aligned_items( .skip(1) .collect::>() .join("\n"); - let spacings = if snippet - .lines() - .rev() - .skip(1) - .find(|l| l.trim().is_empty()) - .is_some() - { + let spacings = if snippet.lines().rev().skip(1).any(|l| l.trim().is_empty()) { "\n" } else { "" diff --git a/src/visitor.rs b/src/visitor.rs index f31ebdb9033f..56c1783476aa 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -260,7 +260,7 @@ impl<'a> FmtVisitor<'a> { abi, vis, mk_sp(s.lo(), b.span.lo()), - &b, + b, ) } visit::FnKind::Method(ident, sig, vis, b) => { @@ -276,7 +276,7 @@ impl<'a> FmtVisitor<'a> { sig.abi, vis.unwrap_or(&ast::Visibility::Inherited), mk_sp(s.lo(), b.span.lo()), - &b, + b, ) } visit::FnKind::Closure(_) => unreachable!(), @@ -503,8 +503,8 @@ impl<'a> FmtVisitor<'a> { } ast::ItemKind::MacroDef(..) => { // FIXME(#1539): macros 2.0 - let snippet = Some(self.snippet(item.span)); - self.push_rewrite(item.span, snippet); + let mac_snippet = Some(self.snippet(item.span)); + self.push_rewrite(item.span, mac_snippet); } } } @@ -719,7 +719,7 @@ impl<'a> FmtVisitor<'a> { // next item for output. if self.config.reorder_imports() && is_use_item(&*items_left[0]) { let used_items_len = self.reorder_items( - &items_left, + items_left, &is_use_item, self.config.reorder_imports_in_group(), ); @@ -727,7 +727,7 @@ impl<'a> FmtVisitor<'a> { items_left = rest; } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) { let used_items_len = self.reorder_items( - &items_left, + items_left, &is_extern_crate, self.config.reorder_extern_crates_in_group(), ); @@ -863,10 +863,7 @@ impl Rewrite for ast::MetaItem { .unwrap_or(0), ..shape }; - format!( - "{}", - try_opt!(rewrite_comment(&value, false, doc_shape, context.config)) - ) + try_opt!(rewrite_comment(&value, false, doc_shape, context.config)) } else { format!("{} = {}", name, value) } @@ -923,7 +920,7 @@ impl<'a> Rewrite for [ast::Attribute] { { // Look at before and after comment and see if there are any empty lines. let comment_begin = comment.chars().position(|c| c == '/'); - let len = comment_begin.unwrap_or(comment.len()); + let len = comment_begin.unwrap_or_else(|| comment.len()); let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1; let mla = if comment_begin.is_none() { mlb diff --git a/tests/system.rs b/tests/system.rs index 9559b545cc65..ce575f9f4923 100644 --- a/tests/system.rs +++ b/tests/system.rs @@ -45,7 +45,7 @@ fn system_tests() { // Display results. println!("Ran {} system tests.", count); - assert!(fails == 0, "{} system tests failed", fails); + assert_eq!(fails, 0, "{} system tests failed", fails); } // Do the same for tests/coverage-source directory @@ -57,7 +57,7 @@ fn coverage_tests() { let (_reports, count, fails) = check_files(files); println!("Ran {} tests in coverage mode.", count); - assert!(fails == 0, "{} tests failed", fails); + assert_eq!(fails, 0, "{} tests failed", fails); } #[test] @@ -71,7 +71,7 @@ fn checkstyle_test() { // Helper function for comparing the results of rustfmt // to a known output file generated by one of the write modes. fn assert_output(source: &str, expected_filename: &str) { - let config = read_config(&source); + let config = read_config(source); let (file_map, _report) = format_file(source, &config); // Populate output by writing to a vec. @@ -86,7 +86,7 @@ fn assert_output(source: &str, expected_filename: &str) { .expect("Failed reading target"); let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE); - if compare.len() > 0 { + if !compare.is_empty() { let mut failures = HashMap::new(); failures.insert(source.to_string(), compare); print_mismatches(failures); @@ -106,7 +106,7 @@ fn idempotence_tests() { // Display results. println!("Ran {} idempotent tests.", count); - assert!(fails == 0, "{} idempotent tests failed", fails); + assert_eq!(fails, 0, "{} idempotent tests failed", fails); } // Run rustfmt on itself. This operation must be idempotent. We also check that @@ -126,15 +126,16 @@ fn self_tests() { // Display results. println!("Ran {} self tests.", count); - assert!(fails == 0, "{} self tests failed", fails); + assert_eq!(fails, 0, "{} self tests failed", fails); for format_report in reports { println!("{}", format_report); warnings += format_report.warning_count(); } - assert!( - warnings == 0, + assert_eq!( + warnings, + 0, "Rustfmt's code generated {} warnings", warnings ); @@ -149,7 +150,7 @@ fn stdin_formatting_smoke_test() { assert!(error_summary.has_no_errors()); for &(ref file_name, ref text) in &file_map { if file_name == "stdin" { - assert!(text.to_string() == "fn main() {}\n"); + assert_eq!(text.to_string(), "fn main() {}\n"); return; } } @@ -210,7 +211,7 @@ fn print_mismatches(result: HashMap>) { } fn read_config(filename: &str) -> Config { - let sig_comments = read_significant_comments(&filename); + let sig_comments = read_significant_comments(filename); // Look for a config file... If there is a 'config' property in the significant comments, use // that. Otherwise, if there are no significant comments at all, look for a config file with // the same name as the test file. @@ -241,8 +242,8 @@ fn format_file>(filepath: P, config: &Config) -> (FileMap, Form let filepath = filepath.into(); let input = Input::File(filepath); let (_error_summary, file_map, report) = - format_input::(input, &config, None).unwrap(); - return (file_map, report); + format_input::(input, config, None).unwrap(); + (file_map, report) } pub fn idempotent_check(filename: String) -> Result>> { @@ -273,7 +274,7 @@ fn get_config(config_file: Option<&str>) -> Config { None => return Default::default(), Some(file_name) => { let mut full_path = "tests/config/".to_owned(); - full_path.push_str(&file_name); + full_path.push_str(file_name); if !Path::new(&full_path).exists() { return Default::default(); }; @@ -296,7 +297,7 @@ fn read_significant_comments(file_name: &str) -> HashMap { let file = fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name)); let reader = BufReader::new(file); let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)"; - let regex = regex::Regex::new(&pattern).expect("Failed creating pattern 1"); + let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1"); // Matches lines containing significant comments or whitespace. let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)") @@ -305,7 +306,7 @@ fn read_significant_comments(file_name: &str) -> HashMap { reader .lines() .map(|line| line.expect("Failed getting line")) - .take_while(|line| line_regex.is_match(&line)) + .take_while(|line| line_regex.is_match(line)) .filter_map(|line| { regex.captures_iter(&line).next().map(|capture| { (