]> git.lizzy.rs Git - rust.git/commitdiff
Merge pull request #1765 from topecongiro/v-alignment/struct-field
authorNick Cameron <nrc@ncameron.org>
Wed, 5 Jul 2017 00:11:52 +0000 (12:11 +1200)
committerGitHub <noreply@github.com>
Wed, 5 Jul 2017 00:11:52 +0000 (12:11 +1200)
Add vertical alignment option for struct fields

src/bin/rustfmt.rs
src/expr.rs
tests/source/configs-closure_block_indent_threshold--1.rs [new file with mode: 0644]
tests/source/expr.rs
tests/target/configs-closure_block_indent_threshold--1.rs [new file with mode: 0644]
tests/target/expr-block.rs
tests/target/expr.rs
tests/target/tuple.rs

index 4d2f1cdc041c6408d86801fc29c7c3430264d075..d2f2f3d761b74fec5129311bb48b659f3e93bcaf 100644 (file)
@@ -78,7 +78,7 @@ fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
                     format!("Invalid write-mode: {}", write_mode),
                 ));
             }
-        } else {
+        } else if !matches.opt_present("no-warn-write-mode") {
             println!(
                 "Warning: the default write-mode for Rustfmt will soon change to overwrite \
                  - this will not leave backups of changed files."
@@ -120,6 +120,12 @@ fn make_opts() -> Options {
     opts.optflag("h", "help", "show this message");
     opts.optflag("V", "version", "show version information");
     opts.optflag("v", "verbose", "print verbose output");
+    // Suppress warning. Remove this option after the default write mode changed to overwrite.
+    opts.optflag(
+        "w",
+        "no-warn-write-mode",
+        "inhibit warning about write-mode change",
+    );
     opts.optopt(
         "",
         "write-mode",
index d9d20b1092cbdcc80db6005084a36c9e515fc6a7..dd0499ebb81701f6de69c8141adcf7afeb0492dd 100644 (file)
@@ -751,7 +751,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().with_max_width(context.config);
+    let block_shape = shape.block();
     let block_str = try_opt!(block.rewrite(&context, block_shape));
     Some(format!("{} {}", prefix, block_str))
 }
@@ -2405,9 +2405,10 @@ pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_l
             context.use_block_indent() ||
                 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
         }
+        ast::ExprKind::Array(..) |
         ast::ExprKind::Call(..) |
-        ast::ExprKind::MethodCall(..) |
         ast::ExprKind::Mac(..) |
+        ast::ExprKind::MethodCall(..) |
         ast::ExprKind::Struct(..) |
         ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
         ast::ExprKind::AddrOf(_, ref expr) |
@@ -2502,31 +2503,53 @@ fn rewrite_index(
     };
 
     let offset = expr_str.len() + lbr.len();
-    if let Some(index_shape) = shape.visual_indent(offset).sub_width(offset + rbr.len()) {
-        if let Some(index_str) = index.rewrite(context, index_shape) {
+    let orig_index_rw = shape
+        .visual_indent(offset)
+        .sub_width(offset + rbr.len())
+        .and_then(|index_shape| index.rewrite(context, index_shape));
+
+    // Return if everything fits in a single line.
+    match orig_index_rw {
+        Some(ref index_str) if !index_str.contains('\n') => {
             return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
         }
+        _ => (),
     }
 
+    // Try putting index on the next line and see if it fits in a single line.
     let indent = shape.indent.block_indent(&context.config);
-    let indent = indent.to_string(&context.config);
-    // FIXME this is not right, since we don't take into account that shape.width
-    // might be reduced from max_width by something on the right.
-    let budget = try_opt!(
-        context
-            .config
-            .max_width()
-            .checked_sub(indent.len() + lbr.len() + rbr.len())
-    );
-    let index_str = try_opt!(index.rewrite(context, Shape::legacy(budget, shape.indent)));
-    Some(format!(
-        "{}\n{}{}{}{}",
-        expr_str,
-        indent,
-        lbr,
-        index_str,
-        rbr
-    ))
+    let rhs_overhead = context
+        .config
+        .max_width()
+        .checked_sub(shape.used_width() + shape.width)
+        .unwrap_or(0);
+    let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
+    let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
+    let new_index_rw = index.rewrite(context, index_shape);
+    match (orig_index_rw, new_index_rw) {
+        (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => {
+            Some(format!(
+                "{}\n{}{}{}{}",
+                expr_str,
+                indent.to_string(&context.config),
+                lbr,
+                new_index_str,
+                rbr
+            ))
+        }
+        (None, Some(ref new_index_str)) => {
+            Some(format!(
+                "{}\n{}{}{}{}",
+                expr_str,
+                indent.to_string(&context.config),
+                lbr,
+                new_index_str,
+                rbr
+            ))
+        }
+        (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
+        _ => None,
+    }
 }
 
 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
diff --git a/tests/source/configs-closure_block_indent_threshold--1.rs b/tests/source/configs-closure_block_indent_threshold--1.rs
new file mode 100644 (file)
index 0000000..166f825
--- /dev/null
@@ -0,0 +1,5 @@
+// rustfmt-closure_block_indent_threshold: -1
+
+fn issue1755() {
+    b.iter(|| dfkljdklgjdlkfgjdlkgjldkjfgkdjgldjfgkljdfklgjlkdjfgkljdflkgjlkdfjgdjfsas::expect("parse"));
+}
index 80e4f2b623f8605b0ea571b4c829e47c0cecf0f5..3d54e68c4093beac1bbc75a0207fc4e76cd27a20 100644 (file)
@@ -308,3 +308,16 @@ fn issue1714() {
     v = &mut {v}[mid..];
     let (left, right) = {v}.split_at_mut(mid);
 }
+
+// Multi-lined index should be put on the next line if it fits in one line.
+fn issue1749() {
+    {
+        {
+            {
+                if self.shape[(r as f32 + self.x_offset) as usize][(c as f32 + self.y_offset) as usize] != 0 {
+                    // hello
+                }
+            }
+        }
+    }
+}
diff --git a/tests/target/configs-closure_block_indent_threshold--1.rs b/tests/target/configs-closure_block_indent_threshold--1.rs
new file mode 100644 (file)
index 0000000..3a62e6a
--- /dev/null
@@ -0,0 +1,7 @@
+// rustfmt-closure_block_indent_threshold: -1
+
+fn issue1755() {
+    b.iter(|| {
+        dfkljdklgjdlkfgjdlkgjldkjfgkdjgldjfgkljdfklgjlkdjfgkljdflkgjlkdfjgdjfsas::expect("parse")
+    });
+}
index bbefa62b30115de81968124ef19b6b3382b5988c..953935baec985690df9a53aaf8dd4ec2bc0185e3 100644 (file)
@@ -96,14 +96,12 @@ fn arrays() {
         1,
     ];
 
-    let a = WeightedChoice::new(
-        &mut [
-            Weighted { weight: x, item: 0 },
-            Weighted { weight: 1, item: 1 },
-            Weighted { weight: x, item: 2 },
-            Weighted { weight: 1, item: 3 },
-        ],
-    );
+    let a = WeightedChoice::new(&mut [
+        Weighted { weight: x, item: 0 },
+        Weighted { weight: 1, item: 1 },
+        Weighted { weight: x, item: 2 },
+        Weighted { weight: 1, item: 3 },
+    ]);
 
     let z = [
         xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
index b650904071430c7340d2255f91c734e293cef8ad..3b275d30f4ced3b7ec6e2a2562ba41ab56549f50 100644 (file)
@@ -224,26 +224,24 @@ fn arrays() {
         1,
     ];
 
-    let a = WeightedChoice::new(
-        &mut [
-            Weighted {
-                weightweight: x,
-                item: 0,
-            },
-            Weighted {
-                weightweight: 1,
-                item: 1,
-            },
-            Weighted {
-                weightweight: x,
-                item: 2,
-            },
-            Weighted {
-                weightweight: 1,
-                item: 3,
-            },
-        ],
-    );
+    let a = WeightedChoice::new(&mut [
+        Weighted {
+            weightweight: x,
+            item: 0,
+        },
+        Weighted {
+            weightweight: 1,
+            item: 1,
+        },
+        Weighted {
+            weightweight: x,
+            item: 2,
+        },
+        Weighted {
+            weightweight: 1,
+            item: 3,
+        },
+    ]);
 
     let z = [
         xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
@@ -367,3 +365,18 @@ fn issue1714() {
     v = &mut { v }[mid..];
     let (left, right) = { v }.split_at_mut(mid);
 }
+
+// Multi-lined index should be put on the next line if it fits in one line.
+fn issue1749() {
+    {
+        {
+            {
+                if self.shape[(r as f32 + self.x_offset) as usize]
+                    [(c as f32 + self.y_offset) as usize] != 0
+                {
+                    // hello
+                }
+            }
+        }
+    }
+}
index 0b82e4821364868f4d125b3210da873ca54df61b..954fe011f141d8cd61881a686a9f0f8821ae64e9 100644 (file)
@@ -62,20 +62,18 @@ fn issue550() {
 
 fn issue775() {
     if indent {
-        let a = mk_object(
-            &[
-                ("a".to_string(), Boolean(true)),
-                (
-                    "b".to_string(),
-                    Array(vec![
-                        mk_object(
-                            &[("c".to_string(), String("\x0c\r".to_string()))],
-                        ),
-                        mk_object(&[("d".to_string(), String("".to_string()))]),
-                    ]),
-                ),
-            ],
-        );
+        let a = mk_object(&[
+            ("a".to_string(), Boolean(true)),
+            (
+                "b".to_string(),
+                Array(vec![
+                    mk_object(
+                        &[("c".to_string(), String("\x0c\r".to_string()))],
+                    ),
+                    mk_object(&[("d".to_string(), String("".to_string()))]),
+                ]),
+            ),
+        ]);
     }
 }