]> git.lizzy.rs Git - rust.git/commitdiff
Formatting fallout
authorNick Cameron <ncameron@mozilla.com>
Mon, 6 Mar 2017 20:40:08 +0000 (09:40 +1300)
committerNick Cameron <ncameron@mozilla.com>
Mon, 6 Mar 2017 20:50:41 +0000 (09:50 +1300)
Also fixes a minor bug when we break a line after `if` and used to leave a trailing space

15 files changed:
src/bin/cargo-fmt.rs
src/bin/rustfmt.rs
src/chains.rs
src/codemap.rs
src/comment.rs
src/expr.rs
src/imports.rs
src/items.rs
src/lib.rs
src/lists.rs
src/missed_spans.rs
src/patterns.rs
src/types.rs
src/utils.rs
tests/system.rs

index cf476edf7ca5e7c02da0903a1e27800956d41c9b..ceb6af93825126e2657b2c33856544fb1574f7e9 100644 (file)
@@ -147,7 +147,10 @@ fn get_targets() -> Result<Vec<Target>, std::io::Error> {
         // None of the unwraps should fail if output of `cargo read-manifest` is correct
         let data = &String::from_utf8(output.stdout).unwrap();
         let json = Json::from_str(data).unwrap();
-        let jtargets = json.find("targets").unwrap().as_array().unwrap();
+        let jtargets = json.find("targets")
+            .unwrap()
+            .as_array()
+            .unwrap();
         for jtarget in jtargets {
             targets.push(target_from_json(jtarget));
         }
@@ -162,8 +165,14 @@ fn get_targets() -> Result<Vec<Target>, std::io::Error> {
 
 fn target_from_json(jtarget: &Json) -> Target {
     let jtarget = jtarget.as_object().unwrap();
-    let path = PathBuf::from(jtarget.get("src_path").unwrap().as_string().unwrap());
-    let kinds = jtarget.get("kind").unwrap().as_array().unwrap();
+    let path = PathBuf::from(jtarget.get("src_path")
+                                 .unwrap()
+                                 .as_string()
+                                 .unwrap());
+    let kinds = jtarget.get("kind")
+        .unwrap()
+        .as_array()
+        .unwrap();
     let kind = match kinds[0].as_string().unwrap() {
         "bin" => TargetKind::Bin,
         "lib" | "dylib" | "staticlib" | "cdylib" | "rlib" => TargetKind::Lib,
index 52d1a8f9f15c9d505d721106102c043e1640abc7..69a18d14cb56d646715627d1f5edf4aac2f4d2ba 100644 (file)
@@ -223,7 +223,10 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
             let options = try!(CliOptions::from_matches(&matches));
 
             // Add any additional files that were specified via `--file-lines`.
-            files.extend(options.file_lines.files().cloned().map(PathBuf::from));
+            files.extend(options.file_lines
+                             .files()
+                             .cloned()
+                             .map(PathBuf::from));
 
             let mut config = Config::default();
             let mut path = None;
@@ -354,7 +357,10 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
     }
 
     // We append files from `--file-lines` later in `execute()`.
-    let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
+    let files: Vec<_> = matches.free
+        .iter()
+        .map(PathBuf::from)
+        .collect();
 
     Ok(Operation::Format {
            files: files,
index a2c69b2cb425a34b08e8cb0be7b607db04adf0df..4918ebd3cac3ae78cfe084782d0b1bea97aa6d54 100644 (file)
@@ -158,9 +158,9 @@ pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -
                      .collect::<Option<Vec<_>>>());
 
     // Total of all items excluding the last.
-    let almost_total = rewrites[..rewrites.len() - 1]
-        .iter()
-        .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
+    let almost_total = rewrites[..rewrites.len() - 1].iter().fold(0, |a, b| {
+        a + first_line_width(b)
+    }) + parent_rewrite.len();
 
     let veto_single_line = if subexpr_list.len() > context.config.chain_one_line_max - 1 {
         // -1 above because subexpr_list does not include the parent.
@@ -425,9 +425,8 @@ fn rewrite_method_call(method_name: ast::Ident,
     let (lo, type_str) = if types.is_empty() {
         (args[0].span.hi, String::new())
     } else {
-        let type_list: Vec<_> = try_opt!(types.iter()
-                                             .map(|ty| ty.rewrite(context, shape))
-                                             .collect());
+        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 {
             format!("::< {} >", type_list.join(", "))
@@ -435,7 +434,11 @@ fn rewrite_method_call(method_name: ast::Ident,
             format!("::<{}>", type_list.join(", "))
         };
 
-        (types.last().unwrap().span.hi, type_str)
+        (types.last()
+             .unwrap()
+             .span
+             .hi,
+         type_str)
     };
 
     let callee_str = format!(".{}{}", method_name, type_str);
index d04169c936e0f25e27f9ccd242000e36a54fda7b..602ab5c98be57ef1f55ba6ee4119f46ddc9a3459 100644 (file)
@@ -26,7 +26,10 @@ pub struct LineRange {
 
 impl LineRange {
     pub fn file_name(&self) -> &str {
-        self.file.as_ref().name.as_str()
+        self.file
+            .as_ref()
+            .name
+            .as_str()
     }
 }
 
index 3f85dd27ac9d4db9c8729db5410f7510e4b654cf..e4f9db9f1584be4b3bda0360ea9970783f0f1f05 100644 (file)
@@ -96,7 +96,10 @@ pub fn rewrite_comment(orig: &str,
         config: config,
     };
 
-    let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
+    let line_breaks = orig.trim_right()
+        .chars()
+        .filter(|&c| c == '\n')
+        .count();
     let lines = orig.lines()
         .enumerate()
         .map(|(i, mut line)| {
@@ -594,8 +597,9 @@ fn changed_comment_content(orig: &str, new: &str) -> bool {
     // Cannot write this as a fn since we cannot return types containing closures
     let code_comment_content = |code| {
         let slices = UngroupedCommentCodeSlices::new(code);
-        slices.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
-            .flat_map(|(_, _, s)| CommentReducer::new(s))
+        slices.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment).flat_map(|(_, _, s)| {
+            CommentReducer::new(s)
+        })
     };
     let res = code_comment_content(orig).ne(code_comment_content(new));
     debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
index a64e1aafffd3fbdac70761e5e84bb9b37a4090a0..7f5d88d3f684b1d46310759c17d88f1a5cc2766e 100644 (file)
@@ -300,10 +300,9 @@ pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
 
     // Re-evaluate the rhs because we have more space now:
     let infix = infix.trim_right();
-    let lhs_budget = try_opt!(context.config
-                                  .max_width
-                                  .checked_sub(shape.used_width() + prefix.len() +
-                                               infix.len()));
+    let lhs_budget = try_opt!(context.config.max_width.checked_sub(shape.used_width() +
+                                                                   prefix.len() +
+                                                                   infix.len()));
     let rhs_shape = try_opt!(shape.sub_width(suffix.len() + prefix.len()))
         .visual_indent(prefix.len());
 
@@ -893,15 +892,19 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             " "
         };
 
-        let mut result =
-            format!("{}{}{}{}{}{}",
-                    label_string,
-                    self.keyword,
-                    between_kwd_cond_comment.as_ref()
-                        .map_or(if pat_expr_string.is_empty() { "" } else { " " }, |s| &**s),
-                    pat_expr_string,
-                    after_cond_comment.as_ref().map_or(block_sep, |s| &**s),
-                    block_str);
+        let mut result = format!("{}{}{}{}{}{}",
+                                 label_string,
+                                 self.keyword,
+                                 between_kwd_cond_comment.as_ref().map_or(if
+            pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
+                                                                              ""
+                                                                          } else {
+                                                                              " "
+                                                                          },
+                                                                          |s| &**s),
+                                 pat_expr_string,
+                                 after_cond_comment.as_ref().map_or(block_sep, |s| &**s),
+                                 block_str);
 
         if let Some(else_block) = self.else_block {
             // Since this is an else block, we should not indent for the assignment preceding
@@ -944,15 +947,15 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 
             let between_kwd_else_block =
                 mk_sp(self.block.span.hi,
-                      context.codemap
-                          .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"));
+                      context.codemap.span_before(mk_sp(self.block.span.hi, else_block.span.lo),
+                                                  "else"));
             let between_kwd_else_block_comment =
                 extract_comment(between_kwd_else_block, context, shape);
 
-            let after_else =
-                mk_sp(context.codemap
-                          .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
-                      else_block.span.lo);
+            let after_else = mk_sp(context.codemap.span_after(mk_sp(self.block.span.hi,
+                                                                    else_block.span.lo),
+                                                              "else"),
+                                   else_block.span.lo);
             let after_else_comment = extract_comment(after_else, context, shape);
 
             let between_sep = match context.config.control_brace_style {
@@ -966,8 +969,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             };
             try_opt!(write!(&mut result,
                             "{}else{}",
-                            between_kwd_else_block_comment.as_ref()
-                                .map_or(between_sep, |s| &**s),
+                            between_kwd_else_block_comment.as_ref().map_or(between_sep, |s| &**s),
                             after_else_comment.as_ref().map_or(after_sep, |s| &**s))
                              .ok());
             result.push_str(&try_opt!(rewrite));
@@ -1094,8 +1096,8 @@ fn rewrite_match(context: &RewriteContext,
     let arm_shape = shape.block_indent(context.config.tab_spaces);
     let arm_indent_str = arm_shape.indent.to_string(context.config);
 
-    let open_brace_pos = context.codemap
-        .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
+    let open_brace_pos = context.codemap.span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
+                                                    "{");
 
     for (i, arm) in arms.iter().enumerate() {
         // Make sure we get the stuff between arms.
@@ -1245,8 +1247,11 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         // Let's try and get the arm body on the same line as the condition.
         // 4 = ` => `.len()
         if shape.width > pat_width + comma.len() + 4 {
-            let arm_shape =
-                shape.shrink_left(pat_width + 4).unwrap().sub_width(comma.len()).unwrap().block();
+            let arm_shape = shape.shrink_left(pat_width + 4)
+                .unwrap()
+                .sub_width(comma.len())
+                .unwrap()
+                .block();
             let rewrite = nop_block_collapse(body.rewrite(context, arm_shape), arm_shape.width);
             let is_block = if let ast::ExprKind::Block(..) = body.node {
                 true
@@ -1338,7 +1343,10 @@ fn rewrite_guard(context: &RewriteContext,
         // 4 = ` if `, 5 = ` => {`
         let overhead = pattern_width + 4 + 5;
         if overhead < shape.width {
-            let cond_shape = shape.shrink_left(pattern_width + 4).unwrap().sub_width(5).unwrap();
+            let cond_shape = shape.shrink_left(pattern_width + 4)
+                .unwrap()
+                .sub_width(5)
+                .unwrap();
             let cond_str = guard.rewrite(context, cond_shape);
             if let Some(cond_str) = cond_str {
                 return Some(format!(" if {}", cond_str));
@@ -1469,7 +1477,10 @@ fn string_requires_rewrite(context: &RewriteContext,
                            string: &str,
                            shape: Shape)
                            -> bool {
-    if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
+    if context.codemap
+           .lookup_char_pos(span.lo)
+           .col
+           .0 != shape.indent.width() {
         return true;
     }
 
@@ -1584,10 +1595,10 @@ fn rewrite_call_inner<R>(context: &RewriteContext,
         }
     }
 
-    let tactic = definitive_tactic(&item_vec,
-                                   ListTactic::LimitedHorizontalVertical(context.config
-                                                                             .fn_call_width),
-                                   remaining_width);
+    let tactic =
+        definitive_tactic(&item_vec,
+                          ListTactic::LimitedHorizontalVertical(context.config.fn_call_width),
+                          remaining_width);
 
     // Replace the stub with the full overflowing last argument if the rewrite
     // succeeded and its first line fits with the other arguments.
@@ -1709,8 +1720,7 @@ enum StructLitField<'a> {
                              |item| match *item {
                                  StructLitField::Regular(field) => field.span.lo,
                                  StructLitField::Base(expr) => {
-        let last_field_hi = fields.last()
-            .map_or(span.lo, |field| field.span.hi);
+        let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
         let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
         let pos = snippet.find_uncommented("..").unwrap();
         last_field_hi + BytePos(pos as u32)
@@ -1728,8 +1738,7 @@ enum StructLitField<'a> {
             }
             StructLitField::Base(expr) => {
                 // 2 = ..
-                expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
-                    .map(|s| format!("..{}", s))
+                expr.rewrite(context, try_opt!(v_shape.shrink_left(2))).map(|s| format!("..{}", s))
             }
         }
     },
@@ -1823,12 +1832,11 @@ fn rewrite_field(context: &RewriteContext, field: &ast::Field, shape: Shape) ->
             Some(e) => Some(format!("{}{}{}", name, separator, e)),
             None => {
                 let expr_offset = shape.indent.block_indent(context.config);
-                let expr = field.expr
-                    .rewrite(context,
-                             Shape::legacy(try_opt!(context.config
+                let expr = field.expr.rewrite(context,
+                                              Shape::legacy(try_opt!(context.config
                                                         .max_width
                                                         .checked_sub(expr_offset.width())),
-                                           expr_offset));
+                                                            expr_offset));
                 expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
             }
         }
@@ -1894,11 +1902,10 @@ pub fn rewrite_unary_suffix<R: Rewrite>(context: &RewriteContext,
                                         rewrite: &R,
                                         shape: Shape)
                                         -> Option<String> {
-    rewrite.rewrite(context, try_opt!(shape.sub_width(suffix.len())))
-        .map(|mut r| {
-                 r.push_str(suffix);
-                 r
-             })
+    rewrite.rewrite(context, try_opt!(shape.sub_width(suffix.len()))).map(|mut r| {
+                                                                              r.push_str(suffix);
+                                                                              r
+                                                                          })
 }
 
 fn rewrite_unary_op(context: &RewriteContext,
index 0b432d072afee8e64c21ad0ff06e52b0a88f2934..65d8366ea22d049bcdcee1780bc102d760cded12 100644 (file)
@@ -29,7 +29,10 @@ fn path_of(a: &ast::ViewPath_) -> &ast::Path {
 }
 
 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
-    a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
+    a.identifier
+        .name
+        .as_str()
+        .cmp(&b.identifier.name.as_str())
 }
 
 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
@@ -43,8 +46,14 @@ fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
 }
 
 fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Ordering {
-    let a_name_str = &*a.node.name.name.as_str();
-    let b_name_str = &*b.node.name.name.as_str();
+    let a_name_str = &*a.node
+                           .name
+                           .name
+                           .as_str();
+    let b_name_str = &*b.node
+                           .name
+                           .name
+                           .as_str();
     let name_ordering = if a_name_str == "self" {
         if b_name_str == "self" {
             Ordering::Equal
@@ -139,7 +148,11 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                 // 4 = " as ".len()
                 let budget = try_opt!(shape.width.checked_sub(ident_str.len() + 4));
 
-                let path_str = if path.segments.last().unwrap().identifier.to_string() == "self" &&
+                let path_str = if path.segments
+                       .last()
+                       .unwrap()
+                       .identifier
+                       .to_string() == "self" &&
                                   path.segments.len() > 1 {
                     let path = &ast::Path {
                                     span: path.span.clone(),
@@ -158,7 +171,10 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                                           Shape::legacy(budget, shape.indent)))
                 };
 
-                Some(if path.segments.last().unwrap().identifier == ident {
+                Some(if path.segments
+                            .last()
+                            .unwrap()
+                            .identifier == ident {
                          path_str
                      } else {
                          format!("{} as {}", path_str, ident_str)
@@ -175,7 +191,11 @@ pub fn format_imports(&mut self, use_items: &[ptr::P<ast::Item>]) {
         let pos_before_first_use_item = use_items.first()
             .map(|p_i| {
                 cmp::max(self.last_pos,
-                         p_i.attrs.iter().map(|attr| attr.span.lo).min().unwrap_or(p_i.span.lo))
+                         p_i.attrs
+                             .iter()
+                             .map(|attr| attr.span.lo)
+                             .min()
+                             .unwrap_or(p_i.span.lo))
             })
             .unwrap_or(self.last_pos);
         // Construct a list of pairs, each containing a `use` item and the start of span before
index 60a06f3dc5fd31afe71cb29189aac15c4fb674e9..91fd91ef958d079e83655799b12d2dd39e4eab35 100644 (file)
@@ -40,9 +40,8 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         // 1 = ;
         let pattern_width = try_opt!(shape.width.checked_sub(pattern_offset.width() + 1));
 
-        let pat_str = try_opt!(self.pat
-                                   .rewrite(&context,
-                                            Shape::legacy(pattern_width, pattern_offset)));
+        let pat_str = try_opt!(self.pat.rewrite(&context,
+                                                Shape::legacy(pattern_width, pattern_offset)));
         result.push_str(&pat_str);
 
         // String that is placed within the assignment pattern and expression.
@@ -106,7 +105,10 @@ fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Ite
             keyword: "",
             abi: abi,
             vis: None,
-            body: fm.items.iter().map(|i| BodyElement::ForeignItem(i)).collect(),
+            body: fm.items
+                .iter()
+                .map(|i| BodyElement::ForeignItem(i))
+                .collect(),
             span: span,
         }
     }
@@ -455,12 +457,10 @@ fn format_variant(&self, field: &ast::Variant) -> Option<String> {
         }
 
         let indent = self.block_indent;
-        let mut result = try_opt!(field.node
-                                      .attrs
-                                      .rewrite(&self.get_context(),
-                                               Shape::legacy(self.config.max_width -
-                                                             indent.width(),
-                                                             indent)));
+        let mut result = try_opt!(field.node.attrs.rewrite(&self.get_context(),
+                                                           Shape::legacy(self.config.max_width -
+                                                                         indent.width(),
+                                                                         indent)));
         if !result.is_empty() {
             result.push('\n');
             result.push_str(&indent.to_string(self.config));
@@ -784,9 +784,7 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
                 Density::Tall
             };
 
-        let where_budget = try_opt!(context.config
-                                        .max_width
-                                        .checked_sub(last_line_width(&result)));
+        let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
         let where_clause_str = try_opt!(rewrite_where_clause(context,
                                                              &generics.where_clause,
                                                              context.config,
@@ -1000,9 +998,8 @@ fn format_tuple_struct(context: &RewriteContext,
                                                          mk_sp(span.lo, body_lo)));
             result.push_str(&generics_str);
 
-            let where_budget = try_opt!(context.config
-                                            .max_width
-                                            .checked_sub(last_line_width(&result)));
+            let where_budget =
+                try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
             try_opt!(rewrite_where_clause(context,
                                           &generics.where_clause,
                                           context.config,
@@ -1093,9 +1090,7 @@ pub fn rewrite_type_alias(context: &RewriteContext,
 
     result.push_str(&generics_str);
 
-    let where_budget = try_opt!(context.config
-                                    .max_width
-                                    .checked_sub(last_line_width(&result)));
+    let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
     let where_clause_str = try_opt!(rewrite_where_clause(context,
                                                          &generics.where_clause,
                                                          context.config,
@@ -1117,8 +1112,7 @@ pub fn rewrite_type_alias(context: &RewriteContext,
         .unwrap_or(0);
     let type_indent = indent + line_width;
     // Try to fit the type on the same line
-    let ty_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, type_indent))
-                              .or_else(|| {
+    let ty_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, type_indent)).or_else(|| {
         // The line was too short, try to put the type on the next line
 
         // Remove the space after '='
@@ -1126,9 +1120,8 @@ pub fn rewrite_type_alias(context: &RewriteContext,
         let type_indent = indent.block_indent(context.config);
         result.push('\n');
         result.push_str(&type_indent.to_string(context.config));
-        let budget = try_opt!(context.config
-                                  .max_width
-                                  .checked_sub(type_indent.width() + ";".len()));
+        let budget = try_opt!(context.config.max_width.checked_sub(type_indent.width() +
+                                                                   ";".len()));
         ty.rewrite(context, Shape::legacy(budget, type_indent))
     }));
     result.push_str(&ty_str);
@@ -1158,11 +1151,10 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 
         let name = self.ident;
         let vis = format_visibility(&self.vis);
-        let mut attr_str = try_opt!(self.attrs
-                                        .rewrite(context,
-                                                 Shape::legacy(context.config.max_width -
-                                                               shape.indent.width(),
-                                                               shape.indent)));
+        let mut attr_str = try_opt!(self.attrs.rewrite(context,
+                                                       Shape::legacy(context.config.max_width -
+                                                                     shape.indent.width(),
+                                                                     shape.indent)));
         if !attr_str.is_empty() {
             attr_str.push('\n');
             attr_str.push_str(&shape.indent.to_string(context.config));
@@ -1289,8 +1281,9 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             ast::FunctionRetTy::Default(_) => Some(String::new()),
             ast::FunctionRetTy::Ty(ref ty) => {
                 let inner_width = try_opt!(shape.width.checked_sub(3));
-                ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
-                    .map(|r| format!("-> {}", r))
+                ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3)).map(|r| {
+                    format!("-> {}", r)
+                })
             }
         }
     }
@@ -1299,9 +1292,8 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 impl Rewrite for ast::Arg {
     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         if is_named_arg(self) {
-            let mut result = try_opt!(self.pat
-                                          .rewrite(context,
-                                                   Shape::legacy(shape.width, shape.indent)));
+            let mut result = try_opt!(self.pat.rewrite(context,
+                                                       Shape::legacy(shape.width, shape.indent)));
 
             if self.ty.node != ast::TyKind::Infer {
                 if context.config.space_before_type_annotation {
@@ -1478,11 +1470,10 @@ fn rewrite_fn_base(context: &RewriteContext,
 
     // Note that if the width and indent really matter, we'll re-layout the
     // return type later anyway.
-    let ret_str = try_opt!(fd.output
-                               .rewrite(&context,
-                                        Shape::legacy(context.config.max_width -
-                                                      indent.width(),
-                                                      indent)));
+    let ret_str = try_opt!(fd.output.rewrite(&context,
+                                             Shape::legacy(context.config.max_width -
+                                                           indent.width(),
+                                                           indent)));
 
     let multi_line_ret_str = ret_str.contains('\n');
     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
@@ -1528,9 +1519,7 @@ fn rewrite_fn_base(context: &RewriteContext,
     }
 
     // A conservative estimation, to goal is to be over all parens in generics
-    let args_start = generics.ty_params
-        .last()
-        .map_or(span.lo, |tp| end_typaram(tp));
+    let args_start = generics.ty_params.last().map_or(span.lo, |tp| end_typaram(tp));
     let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
                           span_for_return(&fd.output).lo);
     let arg_str = try_opt!(rewrite_args(context,
@@ -1731,7 +1720,12 @@ enum ArgumentKind<'a> {
         }
 
         let variadic_arg = if variadic {
-            let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
+            let variadic_span = mk_sp(args.last()
+                                          .unwrap()
+                                          .ty
+                                          .span
+                                          .hi,
+                                      span.hi);
             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
             Some(ArgumentKind::Variadic(variadic_start))
         } else {
@@ -1826,7 +1820,10 @@ fn compute_budgets_for_args(context: &RewriteContext,
         if !newline_brace {
             used_space += 2;
         }
-        let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
+        let one_line_budget = context.config
+            .max_width
+            .checked_sub(used_space)
+            .unwrap_or(0);
 
         if one_line_budget > 0 {
             // 4 = "() {".len()
@@ -1884,8 +1881,8 @@ fn rewrite_generics(context: &RewriteContext,
 
     // Strings for the generics.
     let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, Shape::legacy(h_budget, offset)));
-    let ty_strs = tys.iter()
-        .map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset)));
+    let ty_strs =
+        tys.iter().map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset)));
 
     // Extract comments between generics.
     let lt_spans = lifetimes.iter().map(|l| {
index 4c4c56bb2f3788d3bb606d3bee673fff0366d6d8..f37466bebfc04363413c3b675647ad734d303e11 100644 (file)
@@ -394,7 +394,10 @@ fn new() -> FormatReport {
     }
 
     pub fn warning_count(&self) -> usize {
-        self.file_error_map.iter().map(|(_, errors)| errors.len()).fold(0, |acc, x| acc + x)
+        self.file_error_map
+            .iter()
+            .map(|(_, errors)| errors.len())
+            .fold(0, |acc, x| acc + x)
     }
 
     pub fn has_warnings(&self) -> bool {
index 8ba54ab4ccb9c2a184bd84fbe37d1d6814074dae..5c25c8b1cea07ee29c0924481ce90d1916460daa 100644 (file)
@@ -147,9 +147,8 @@ pub fn definitive_tactic<I, T>(items: I, tactic: ListTactic, width: usize) -> De
     where I: IntoIterator<Item = T> + Clone,
           T: AsRef<ListItem>
 {
-    let pre_line_comments = items.clone()
-        .into_iter()
-        .any(|item| item.as_ref().has_line_pre_comment());
+    let pre_line_comments =
+        items.clone().into_iter().any(|item| item.as_ref().has_line_pre_comment());
 
     let limit = match tactic {
         _ if pre_line_comments => return DefinitiveListTactic::Vertical,
@@ -275,7 +274,10 @@ pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
 
         if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
             // 1 = space between item and comment.
-            let width = formatting.shape.width.checked_sub(item_last_line_width + 1).unwrap_or(1);
+            let width = formatting.shape
+                .width
+                .checked_sub(item_last_line_width + 1)
+                .unwrap_or(1);
             let mut offset = formatting.shape.indent;
             offset.alignment += item_last_line_width + 1;
             let comment = item.post_comment.as_ref().unwrap();
@@ -475,9 +477,9 @@ fn calculate_width<I, T>(items: I) -> (usize, usize)
     where I: IntoIterator<Item = T>,
           T: AsRef<ListItem>
 {
-    items.into_iter()
-        .map(|item| total_item_width(item.as_ref()))
-        .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
+    items.into_iter().map(|item| total_item_width(item.as_ref())).fold((0, 0), |acc, l| {
+        (acc.0 + 1, acc.1 + l)
+    })
 }
 
 fn total_item_width(item: &ListItem) -> usize {
index 61efbddeb1c0ebee48acbea19020fdbe9e6943bc..767a81120e5c262920cab0f3de9dda1919f4c9e0 100644 (file)
@@ -75,12 +75,19 @@ fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
         // Get a snippet from the file start to the span's hi without allocating.
         // We need it to determine what precedes the current comment. If the comment
         // follows code on the same line, we won't touch it.
-        let big_span_lo = self.codemap.lookup_char_pos(span.lo).file.start_pos;
+        let big_span_lo = self.codemap
+            .lookup_char_pos(span.lo)
+            .file
+            .start_pos;
         let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
         let local_end = self.codemap.lookup_byte_offset(span.hi);
         let start_index = local_begin.pos.to_usize();
         let end_index = local_end.pos.to_usize();
-        let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
+        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);
@@ -105,9 +112,7 @@ fn write_snippet_inner<F>(&mut self,
         let mut rewrite_next_comment = true;
 
         fn replace_chars(string: &str) -> String {
-            string.chars()
-                .map(|ch| if ch.is_whitespace() { ch } else { 'X' })
-                .collect()
+            string.chars().map(|ch| if ch.is_whitespace() { ch } else { 'X' }).collect()
         }
 
         let replaced = match self.config.write_mode {
@@ -154,9 +159,10 @@ fn replace_chars(string: &str) -> String {
 
                     if let Some('/') = subslice.chars().skip(1).next() {
                         // check that there are no contained block comments
-                        if !subslice.split('\n')
-                                .map(|s| s.trim_left())
-                                .any(|s| s.len() > 2 && &s[0..2] == "/*") {
+                        if !subslice.split('\n').map(|s| s.trim_left()).any(|s| {
+                                                                                s.len() > 2 &&
+                                                                                &s[0..2] == "/*"
+                                                                            }) {
                             // Add a newline after line comments
                             self.buffer.push_str("\n");
                         }
index cbaa29a456904e797bfec4d45e4b5d12f2c84572..601506b4954dfcad20706cdb1eee6c49489471fe 100644 (file)
@@ -36,10 +36,10 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                 let sub_pat = match *sub_pat {
                     Some(ref p) => {
                         // 3 - ` @ `.
-                        let width = try_opt!(shape.width
-                                                 .checked_sub(prefix.len() + mut_infix.len() +
-                                                              id_str.len() +
-                                                              3));
+                        let width = try_opt!(shape.width.checked_sub(prefix.len() +
+                                                                     mut_infix.len() +
+                                                                     id_str.len() +
+                                                                     3));
                         format!(" @ {}",
                                 try_opt!(p.rewrite(context, Shape::legacy(width, shape.indent))))
                     }
@@ -90,15 +90,15 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
                 // Rewrite all the sub-patterns.
                 let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
-                let slice_pat =
-                    slice_pat.as_ref()
-                        .map(|p| Some(format!("{}..", try_opt!(p.rewrite(context, shape)))));
+                let slice_pat = slice_pat.as_ref().map(|p| {
+                                                           Some(format!("{}..",
+                                                            try_opt!(p.rewrite(context, shape))))
+                                                       });
                 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
 
                 // Munge them together.
-                let pats: Option<Vec<String>> = prefix.chain(slice_pat.into_iter())
-                    .chain(suffix)
-                    .collect();
+                let pats: Option<Vec<String>> =
+                    prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
 
                 // Check that all the rewrites succeeded, and if not return None.
                 let pats = try_opt!(pats);
index 7f6e8e68576356b6276e8581b245bc600fed6a4c..39f9d40a627f41a7a485e1d6ae454dc3568deecc 100644 (file)
@@ -165,10 +165,10 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                     TypeDensity::Compressed => format!("{}=", binding.ident),
                 };
                 let budget = try_opt!(shape.width.checked_sub(result.len()));
-                let rewrite =
-                    try_opt!(binding.ty
-                                 .rewrite(context,
-                                          Shape::legacy(budget, shape.indent + result.len())));
+                let rewrite = try_opt!(binding.ty.rewrite(context,
+                                                          Shape::legacy(budget,
+                                                                        shape.indent +
+                                                                        result.len())));
                 result.push_str(&rewrite);
                 Some(result)
             }
@@ -208,7 +208,10 @@ fn rewrite_segment(path_context: PathContext,
                     .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
                     .collect::<Vec<_>>();
 
-                let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
+                let next_span_lo = param_list.last()
+                    .unwrap()
+                    .get_span()
+                    .hi + BytePos(1);
                 let list_lo = context.codemap.span_after(codemap::mk_sp(*span_lo, span_hi), "<");
                 let separator = if path_context == PathContext::Expr {
                     "::"
@@ -445,9 +448,8 @@ fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
     if bounds.len() == 0 {
         Some(result)
     } else {
-        let appendix: Vec<_> = try_opt!(bounds.into_iter()
-                                            .map(|b| b.rewrite(context, shape))
-                                            .collect());
+        let appendix: Vec<_> =
+            try_opt!(bounds.into_iter().map(|b| b.rewrite(context, shape)).collect());
         let colon = type_bound_colon(context);
         let result = format!("{}{}{}", result, colon, appendix.join(" + "));
         wrap_str(result, context.config.max_width, shape)
@@ -485,9 +487,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             TypeDensity::Compressed => "+",
             TypeDensity::Wide => " + ",
         };
-        let strs: Vec<_> = try_opt!(self.iter()
-                                        .map(|b| b.rewrite(context, shape))
-                                        .collect());
+        let strs: Vec<_> = try_opt!(self.iter().map(|b| b.rewrite(context, shape)).collect());
         wrap_str(strs.join(joiner), context.config.max_width, shape)
     }
 }
@@ -543,10 +543,10 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             // 6 is "for<> ".len()
             let extra_offset = lifetime_str.len() + 6;
             let max_path_width = try_opt!(shape.width.checked_sub(extra_offset));
-            let path_str = try_opt!(self.trait_ref
-                                        .rewrite(context,
-                                                 Shape::legacy(max_path_width,
-                                                               shape.indent + extra_offset)));
+            let path_str = try_opt!(self.trait_ref.rewrite(context,
+                                                           Shape::legacy(max_path_width,
+                                                                         shape.indent +
+                                                                         extra_offset)));
 
             Some(if context.config.spaces_within_angle_brackets && lifetime_str.len() > 0 {
                      format!("for< {} > {}", lifetime_str, path_str)
@@ -592,11 +592,10 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                     format!("&{} {}{}",
                             lt_str,
                             mut_str,
-                            try_opt!(mt.ty
-                                         .rewrite(context,
-                                                  Shape::legacy(budget,
-                                                                shape.indent + 2 + mut_len +
-                                                                lt_len))))
+                            try_opt!(mt.ty.rewrite(context,
+                                                   Shape::legacy(budget,
+                                                                 shape.indent + 2 + mut_len +
+                                                                 lt_len))))
                 }
                          None => {
                     let budget = try_opt!(shape.width.checked_sub(1 + mut_len));
index da48831e672e12301876b199ee23ee47f2314919..999e1192b5d27e39eff66ba64cb2544800aabbce 100644 (file)
@@ -278,7 +278,11 @@ pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, shape: Shape) -> Option<S
             // indentation.
             // A special check for the last line, since the caller may
             // place trailing characters on this line.
-            if snippet.lines().rev().next().unwrap().len() > shape.indent.width() + shape.width {
+            if snippet.lines()
+                   .rev()
+                   .next()
+                   .unwrap()
+                   .len() > shape.indent.width() + shape.width {
                 return None;
             }
         }
index 257b1ec46bf9640051318d21382e08eb2fccb5cf..2f5258df235fd604296ef6cd4d7cbf9c90508c15 100644 (file)
@@ -84,8 +84,7 @@ fn assert_output(source: &str, expected_filename: &str) {
 
     let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
     let mut expected_text = String::new();
-    expected_file.read_to_string(&mut expected_text)
-        .expect("Failed reading target");
+    expected_file.read_to_string(&mut expected_text).expect("Failed reading target");
 
     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
     if compare.len() > 0 {
@@ -101,9 +100,8 @@ fn assert_output(source: &str, expected_filename: &str) {
 #[test]
 fn idempotence_tests() {
     // Get all files in the tests/target directory.
-    let files = fs::read_dir("tests/target")
-        .expect("Couldn't read target dir")
-        .map(get_path_string);
+    let files =
+        fs::read_dir("tests/target").expect("Couldn't read target dir").map(get_path_string);
     let (_reports, count, fails) = check_files(files);
 
     // Display results.