about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorNick Cameron <nrc@ncameron.org>2018-10-18 19:56:17 +1300
committerGitHub <noreply@github.com>2018-10-18 19:56:17 +1300
commite633f2b3f530404a6cab0fb9dd4dc351b8e6bc7e (patch)
tree98ddde2682a0034dcf0f485367244144e8172155 /src
parent750b25261380b776de2518fd6863fe63f98d2722 (diff)
parent30c06da78124dad8341689a15d6ccfe1450c5ab9 (diff)
Merge pull request #3109 from scampi/issue-3038
force a newline after the `if` condition if there is a different indentation level
Diffstat (limited to 'src')
-rw-r--r--src/expr.rs43
1 files changed, 42 insertions, 1 deletions
diff --git a/src/expr.rs b/src/expr.rs
index 15ffb842ee4..fbbc592e547 100644
--- a/src/expr.rs
+++ b/src/expr.rs
@@ -801,6 +801,20 @@ impl<'a> ControlFlow<'a> {
     }
 }
 
+/// Returns true if the last line of pat_str has leading whitespace and it is wider than the
+/// shape's indent.
+fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
+    let mut leading_whitespaces = 0;
+    for c in pat_str.chars().rev() {
+        match c {
+            '\n' => break,
+            _ if c.is_whitespace() => leading_whitespaces += 1,
+            _ => leading_whitespaces = 0,
+        }
+    }
+    leading_whitespaces > start_column
+}
+
 impl<'a> ControlFlow<'a> {
     fn rewrite_pat_expr(
         &self,
@@ -885,7 +899,8 @@ impl<'a> ControlFlow<'a> {
             .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
         let force_newline_brace = (pat_expr_string.contains('\n')
             || pat_expr_string.len() > one_line_budget)
-            && !last_line_extendable(&pat_expr_string);
+            && (!last_line_extendable(&pat_expr_string)
+                || last_line_offsetted(shape.used_width(), &pat_expr_string));
 
         // Try to format if-else on single line.
         if self.allow_single_line
@@ -1977,3 +1992,29 @@ pub fn is_method_call(expr: &ast::Expr) -> bool {
         _ => false,
     }
 }
+
+#[cfg(test)]
+mod test {
+    use super::last_line_offsetted;
+
+    #[test]
+    fn test_last_line_offsetted() {
+        let lines = "one\n    two";
+        assert_eq!(last_line_offsetted(2, lines), true);
+        assert_eq!(last_line_offsetted(4, lines), false);
+        assert_eq!(last_line_offsetted(6, lines), false);
+
+        let lines = "one    two";
+        assert_eq!(last_line_offsetted(2, lines), false);
+        assert_eq!(last_line_offsetted(0, lines), false);
+
+        let lines = "\ntwo";
+        assert_eq!(last_line_offsetted(2, lines), false);
+        assert_eq!(last_line_offsetted(0, lines), false);
+
+        let lines = "one\n    two      three";
+        assert_eq!(last_line_offsetted(2, lines), true);
+        let lines = "one\n two      three";
+        assert_eq!(last_line_offsetted(2, lines), false);
+    }
+}