]> git.lizzy.rs Git - rust.git/commitdiff
Merge pull request #1647 from topecongiro/refactor-impl-format
authorNick Cameron <nrc@ncameron.org>
Mon, 12 Jun 2017 23:55:33 +0000 (11:55 +1200)
committerGitHub <noreply@github.com>
Mon, 12 Jun 2017 23:55:33 +0000 (11:55 +1200)
Refactor impl format

Configurations.md
src/expr.rs
src/items.rs
src/lib.rs
src/lists.rs
tests/source/configs-fn_call_style-block.rs
tests/target/comments-fn.rs
tests/target/configs-fn_call_style-block-trailing-comma.rs
tests/target/configs-fn_call_style-block.rs
tests/target/configs-struct_lit_style-visual.rs

index 73e7cb101c7b0431bf0049a276dd6fa760a38c3f..82f50dc66727e4f8d94ac1d53c140fea9f72206e 100644 (file)
@@ -1442,7 +1442,7 @@ let lorem = Lorem {
 
 ```rust
 let lorem = Lorem { ipsum: dolor,
-        sit: amet, };
+                    sit: amet, };
 ```
 
 See also: [`struct_lit_multiline_style`](#struct_lit_multiline_style), [`struct_lit_style`](#struct_lit_style).
index 04778b6ddcab1dae55848ca83539be70fe1e86b5..40c678174a8c08698a86f50c21bed0a847ca8ffa 100644 (file)
@@ -1721,6 +1721,20 @@ fn rewrite_call_inner(context: &RewriteContext,
                                                    nested_shape,
                                                    one_line_width,
                                                    force_trailing_comma)
+        .or_else(|| if context.use_block_indent() {
+                     rewrite_call_args(context,
+                                       args,
+                                       args_span,
+                                       Shape::indented(shape
+                                                           .block()
+                                                           .indent
+                                                           .block_indent(context.config),
+                                                       context.config),
+                                       0,
+                                       force_trailing_comma)
+                 } else {
+                     None
+                 })
         .ok_or(Ordering::Less)?;
 
     if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
@@ -1734,9 +1748,12 @@ fn rewrite_call_inner(context: &RewriteContext,
                                   force_trailing_comma);
     }
 
+    let args_shape = shape
+        .sub_width(last_line_width(&callee_str))
+        .ok_or(Ordering::Less)?;
     Ok(format!("{}{}",
                callee_str,
-               wrap_args_with_parens(context, &list_str, extendable, shape, nested_shape)))
+               wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)))
 }
 
 fn need_block_indent(s: &str, shape: Shape) -> bool {
@@ -1906,14 +1923,23 @@ fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len:
     }
 }
 
+fn paren_overhead(context: &RewriteContext) -> usize {
+    if context.config.spaces_within_parens() {
+        4
+    } else {
+        2
+    }
+}
+
 fn wrap_args_with_parens(context: &RewriteContext,
                          args_str: &str,
                          is_extendable: bool,
                          shape: Shape,
                          nested_shape: Shape)
                          -> String {
-    if !context.use_block_indent() || (context.inside_macro && !args_str.contains('\n')) ||
-       is_extendable {
+    if !context.use_block_indent() ||
+       (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 {
             format!("( {} )", args_str)
         } else {
index 6b9e1e411f1e4f0eebae45f250d89b71acfd2db9..020f04e30f392fa5ad79a9deb917d472534c91c9 100644 (file)
@@ -1919,6 +1919,7 @@ fn rewrite_fn_base(context: &RewriteContext,
 
                 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));
             }
         }
@@ -1936,7 +1937,12 @@ fn rewrite_fn_base(context: &RewriteContext,
 
     result.push_str(&where_clause_str);
 
-    Some((result, force_new_line_for_brace))
+    force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
+    return Some((result, force_new_line_for_brace));
+}
+
+fn last_line_contains_single_line_comment(s: &str) -> bool {
+    s.lines().last().map_or(false, |l| l.contains("//"))
 }
 
 fn rewrite_args(context: &RewriteContext,
index b7edc1836183021e40253cb0a5da72b256b34733..6488c83e9831fa260e0bd0e88726188fcd9fce8f 100644 (file)
@@ -427,9 +427,10 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
 
 // Formatting which depends on the AST.
 fn format_ast<F>(krate: &ast::Crate,
-                 parse_session: &ParseSess,
+                 mut parse_session: &mut ParseSess,
                  main_file: &Path,
                  config: &Config,
+                 codemap: &Rc<CodeMap>,
                  mut after_file: F)
                  -> Result<(FileMap, bool), io::Error>
     where F: FnMut(&str, &mut StringBuffer) -> Result<bool, io::Error>
@@ -449,12 +450,19 @@ fn format_ast<F>(krate: &ast::Crate,
         if config.verbose() {
             println!("Formatting {}", path);
         }
-        let mut visitor = FmtVisitor::from_codemap(parse_session, config);
-        visitor.format_separate_mod(module);
+        {
+            let mut visitor = FmtVisitor::from_codemap(parse_session, config);
+            visitor.format_separate_mod(module);
 
-        has_diff |= after_file(path, &mut visitor.buffer)?;
+            has_diff |= after_file(path, &mut visitor.buffer)?;
 
-        result.push((path.to_owned(), visitor.buffer));
+            result.push((path.to_owned(), visitor.buffer));
+        }
+        // Reset the error count.
+        if parse_session.span_diagnostic.has_errors() {
+            parse_session.span_diagnostic =
+                Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
+        }
     }
 
     Ok((result, has_diff))
@@ -612,9 +620,10 @@ pub fn format_input<T: Write>(input: Input,
 
     match format_ast(
         &krate,
-        &parse_session,
+        &mut parse_session,
         &main_file,
         config,
+        &codemap,
         |file_name, file| {
             // For some reason, the codemap does not include terminating
             // newlines so we must add one on for each file. This is sad.
index 978d9dbaceb3212fb57ba8466e29ae2eef57ba77..ec4427032e5937d837e94d21bcadd13a5775abc4 100644 (file)
@@ -529,7 +529,8 @@ pub fn struct_lit_shape(shape: Shape,
                         -> Option<(Option<Shape>, Shape)> {
     let v_shape = match context.config.struct_lit_style() {
         IndentStyle::Visual => {
-            try_opt!(try_opt!(shape.shrink_left(prefix_width)).sub_width(suffix_width))
+            try_opt!(try_opt!(shape.visual_indent(0).shrink_left(prefix_width))
+                         .sub_width(suffix_width))
         }
         IndentStyle::Block => {
             let shape = shape.block_indent(context.config.tab_spaces());
index 2068216d18e7e9bd6eee3c1ef1b5fd06cbb70e38..ee6178c1902bb28bd068c8c8ff9ef351af1b7456 100644 (file)
@@ -125,3 +125,9 @@ fn issue1581() {
         },
     );
 }
+
+fn issue1651() {
+    {
+        let type_list: Vec<_> = try_opt!(types.iter().map(|ty| ty.rewrite(context, shape)).collect());
+    }
+}
index fa607e131eaa5cdb0e5d9e0205cfad01f3045e61..87b32f2915d91c278dc8629329e5f79a586181c9 100644 (file)
@@ -19,3 +19,7 @@ fn foo<F, G>(a: aaaaaaaaaaaaa, // A comment
 fn bar<F /* comment on F */, G /* comment on G */>() {}
 
 fn baz() -> Baz /* Comment after return type */ {}
+
+fn some_fn<T>() where T: Eq // some comment
+{
+}
index ebdf41d0e3b3c9d13c511fc4c23d120131949d7d..b6eb94eb67766ec5448353f94ffebf5083f210fb 100644 (file)
@@ -3,7 +3,9 @@
 
 // rustfmt should not add trailing comma when rewriting macro. See #1528.
 fn a() {
-    panic!("this is a long string that goes past the maximum line length causing rustfmt to insert a comma here:");
+    panic!(
+        "this is a long string that goes past the maximum line length causing rustfmt to insert a comma here:"
+    );
     foo(
         oooptoptoptoptptooptoptoptoptptooptoptoptoptptoptoptoptoptpt(),
     );
index ddead8ce5a857043e2c2ddeb1ae58899a25e57fb..dfc8daef6d9034fd044096a294a8f9c724bad44f 100644 (file)
@@ -145,3 +145,10 @@ fn issue1581() {
         }
     });
 }
+
+fn issue1651() {
+    {
+        let type_list: Vec<_> =
+            try_opt!(types.iter().map(|ty| ty.rewrite(context, shape)).collect());
+    }
+}
index 685ded59aad6c7269842303dbdabf949eeb5d2ef..eb470e1e29c09da602aa01c8dcca0aec23dd1adb 100644 (file)
@@ -3,5 +3,5 @@
 
 fn main() {
     let lorem = Lorem { ipsum: dolor,
-            sit: amet, };
+                        sit: amet, };
 }