]> git.lizzy.rs Git - rust.git/commitdiff
Format if-else expressions
authorMarcus Klaas <mail@marcusklaas.nl>
Sun, 19 Jul 2015 21:42:54 +0000 (23:42 +0200)
committerMarcus Klaas <mail@marcusklaas.nl>
Sun, 19 Jul 2015 21:42:54 +0000 (23:42 +0200)
src/comment.rs
src/expr.rs
src/imports.rs
src/issues.rs
src/items.rs
src/utils.rs
tests/source/expr.rs
tests/source/struct_lits_visual.rs
tests/target/expr.rs
tests/target/struct_lits_visual.rs

index 7e4119880c30518afef876ec213a228719cd8aad..6d453bd5c88454576f0efbcdb43fd87ea529e264 100644 (file)
@@ -17,9 +17,11 @@ pub fn rewrite_comment(orig: &str, block_style: bool, width: usize, offset: usiz
     let s = orig.trim();
 
     // Edge case: block comments. Let's not trim their lines (for now).
-    let opener = if block_style { "/* " } else { "// " };
-    let closer = if block_style { " */" } else { "" };
-    let line_start = if block_style { " * " } else { "// " };
+    let (opener, closer, line_start) = if block_style {
+        ("/* ", " */", " * ")
+    } else {
+        ("// ", "", "// ")
+    };
 
     let max_chars = width.checked_sub(closer.len()).unwrap_or(1)
                          .checked_sub(opener.len()).unwrap_or(1);
index e0a76308b4423bd87c6177aae448bce222cbe345..89846527cfff905913de629b169092e2fb04735d 100644 (file)
@@ -76,6 +76,17 @@ fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Opti
                     format!("{}loop {}", rewrite_label(label), result)
                 })
             }
+            ast::Expr_::ExprBlock(ref block) => {
+                block.rewrite(context, width, offset)
+            }
+            ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
+                rewrite_if_else(context,
+                                cond,
+                                if_block,
+                                else_block.as_ref().map(|e| &**e),
+                                width,
+                                offset)
+            }
             _ => context.codemap.span_to_snippet(self.span).ok()
         }
     }
@@ -108,6 +119,29 @@ fn rewrite_label(label: Option<ast::Ident>) -> String {
     }
 }
 
+fn rewrite_if_else(context: &RewriteContext,
+                   cond: &ast::Expr,
+                   if_block: &ast::Block,
+                   else_block: Option<&ast::Expr>,
+                   width: usize,
+                   offset: usize)
+                   -> Option<String> {
+    // FIXME: missing comments between control statements and blocks
+    let cond_string = try_opt!(cond.rewrite(context, width - 3 - 2, offset + 3));
+    let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
+
+    match else_block {
+        Some(else_block) => {
+            else_block.rewrite(context, width, offset).map(|else_block_string| {
+                format!("if {} {} else {}", cond_string, if_block_string, else_block_string)
+            })
+        }
+        None => {
+            Some(format!("if {} {}", cond_string, if_block_string))
+        }
+    }
+}
+
 fn rewrite_string_lit(context: &RewriteContext,
                       s: &str,
                       span: Span,
@@ -229,6 +263,8 @@ enum StructLitField<'a> {
     let field_iter = fields.into_iter().map(StructLitField::Regular)
                            .chain(base.into_iter().map(StructLitField::Base));
 
+    let inner_context = &RewriteContext { block_indent: indent, ..*context };
+
     let items = itemize_list(context.codemap,
                              Vec::new(),
                              field_iter,
@@ -250,13 +286,13 @@ enum StructLitField<'a> {
                              |item| {
                                  match *item {
                                      StructLitField::Regular(ref field) => {
-                                         rewrite_field(context, &field, h_budget, indent)
+                                         rewrite_field(inner_context, &field, h_budget, indent)
                                             .unwrap_or(context.codemap.span_to_snippet(field.span)
                                                                       .unwrap())
                                      },
                                      StructLitField::Base(ref expr) => {
                                          // 2 = ..
-                                         expr.rewrite(context, h_budget - 2, indent + 2)
+                                         expr.rewrite(inner_context, h_budget - 2, indent + 2)
                                              .map(|s| format!("..{}", s))
                                              .unwrap_or(context.codemap.span_to_snippet(expr.span)
                                                                        .unwrap())
index 1973115cd435046baac35eddb18f2a6fb1837b71..66bf26b041d0c3cf85f97dcae373a350ae424311 100644 (file)
@@ -60,7 +60,11 @@ pub fn rewrite_use_list(&self,
         }
 
         // 2 = ::
-        let path_separation_w = if path_str.len() > 0 { 2 } else { 0 };
+        let path_separation_w = if path_str.len() > 0 {
+            2
+        } else {
+            0
+        };
         // 5 = "use " + {
         let indent = path_str.len() + 5 + path_separation_w + vis.len();
 
@@ -106,7 +110,11 @@ pub fn rewrite_use_list(&self,
         // FIXME: Make more efficient by using a linked list? That would
         // require changes to the signatures of itemize_list and write_list.
         let has_self = move_self_to_front(&mut items);
-        let first_index = if has_self { 0 } else { 1 };
+        let first_index = if has_self {
+            0
+        } else {
+            1
+        };
 
         if self.config.reorder_imports {
             items[1..].sort_by(|a, b| a.item.cmp(&b.item));
index 31f544605b590a77e0ebf6457003d8e629a1d258..34d5b8ab2c440b7aaabd0791dff06f1d9778991d 100644 (file)
@@ -70,7 +70,11 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
             IssueType::Todo => "TODO",
             IssueType::Fixme => "FIXME",
         };
-        let details = if self.missing_number { " without issue number" } else { "" };
+        let details = if self.missing_number {
+            " without issue number"
+        } else {
+            ""
+        };
 
         write!(fmt, "{}{}", msg, details)
     }
@@ -177,7 +181,7 @@ fn inspect_number(&mut self,
                       issue: Issue,
                       mut part: NumberPart)
                       -> IssueClassification {
-        if ! issue.missing_number || c == '\n' {
+        if !issue.missing_number || c == '\n' {
             return IssueClassification::Bad(issue);
         } else if c == ')' {
             return if let NumberPart::CloseParen = part {
index b3f4a0a63a4ca614833e8450c3ea2ece7ea234ee..3c35b20fb3fff6c722be55a239842a220972b5a6 100644 (file)
@@ -446,7 +446,11 @@ fn visit_variant(&mut self, field: &ast::Variant, last_field: bool, next_span_st
                                  + field.node.name.to_string().len()
                                  + 1; // Open paren
 
-                    let comma_cost = if self.config.enum_trailing_comma { 1 } else { 0 };
+                    let comma_cost = if self.config.enum_trailing_comma {
+                        1
+                    } else {
+                        0
+                    };
                     let budget = self.config.ideal_width - indent - comma_cost - 1; // 1 = )
 
                     let fmt = ListFormatting {
@@ -520,7 +524,11 @@ fn format_struct(&self,
             ast::StructFieldKind::UnnamedField(..) => true
         };
 
-        let (opener, terminator) = if is_tuple { ("(", ")") } else { (" {", "}") };
+        let (opener, terminator) = if is_tuple {
+            ("(", ")")
+        } else {
+            (" {", "}")
+        };
 
         let generics_str = match generics {
             Some(g) => self.format_generics(g,
@@ -565,7 +573,11 @@ fn format_struct(&self,
             result.push_str(&indentation);
         }
 
-        let tactic = if break_line { ListTactic::Vertical } else { ListTactic::Horizontal };
+        let tactic = if break_line {
+            ListTactic::Vertical
+        } else {
+            ListTactic::Horizontal
+        };
 
         // 1 = ,
         let budget = self.config.ideal_width - offset + self.config.tab_spaces - 1;
index 47203a0754f18336581074b4442ab6e9c33e737a..246f7cb2dc3d9649085dc2b9cd9177629d6b6ddd 100644 (file)
@@ -24,7 +24,9 @@ pub fn span_after(original: Span, needle: &str, codemap: &CodeMap) -> BytePos {
 
 #[inline]
 pub fn prev_char(s: &str, mut i: usize) -> usize {
-    if i == 0 { return 0; }
+    if i == 0 {
+        return 0;
+    }
 
     i -= 1;
     while !s.is_char_boundary(i) {
@@ -35,7 +37,9 @@ pub fn prev_char(s: &str, mut i: usize) -> usize {
 
 #[inline]
 pub fn next_char(s: &str, mut i: usize) -> usize {
-    if i >= s.len() { return s.len(); }
+    if i >= s.len() {
+        return s.len();
+    }
 
     while !s.is_char_boundary(i) {
         i += 1;
index 373e42d67c5e00cc3101ede1312f9da78f4878e7..d26c57ebbd007cd1b5c1a52b4168c1c0d07f264f 100644 (file)
@@ -12,5 +12,16 @@ fn foo() -> bool {
                                                      - 50000 * sqrt(-1),
                                                      trivial_value);
     (((((((((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + a +
-             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaa)))))))))
+             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaa)))))))));
+
+     if  1  + 2 > 0  { let result = 5; result } else { 4};
+
+    if cond() {
+        something();
+    } else  if different_cond() {
+        something_else();
+    } else {
+        // Check subformatting
+        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+    }
 }
index b629ffa1263ede7390138f707ff7b7f53202376e..f14a56397ec834fd2d5177d31596c91228a4fe97 100644 (file)
@@ -22,6 +22,8 @@ fn main() {
     Foo { a:Bar,
           b:foo() };
 
+    Quux { x: if cond { bar(); }, y: baz() };
+
     A { 
     // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor.
     first: item(),
index 25c84511c415030da3b28992d8ee6563b4bd96ec..3a8605b7c42927d26e485fc6322aa0536ddc30f2 100644 (file)
@@ -13,5 +13,22 @@ fn foo() -> bool {
                                                          trivial_value);
     (((((((((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
              a + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
-             aaaaa)))))))))
+             aaaaa)))))))));
+
+    if 1 + 2 > 0 {
+        let result = 5;
+        result
+    } else {
+        4
+    };
+
+    if cond() {
+        something();
+    } else if different_cond() {
+        something_else();
+    } else {
+        // Check subformatting
+        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
+        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+    }
 }
index 651cd2b883b10cf1d2cd44c9a5d35b0e7ded2d46..248839cb8698bcee85cfeb7db08f261674657388 100644 (file)
@@ -35,6 +35,11 @@ fn main() {
 
     Foo { a: Bar, b: foo() };
 
+    Quux { x: if cond {
+               bar();
+           },
+           y: baz(), };
+
     A { // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit
         // amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante
         // hendrerit. Donec et mollis dolor.