]> git.lizzy.rs Git - rust.git/commitdiff
Blockify multiline match arms
authorMarcus Klaas <mail@marcusklaas.nl>
Fri, 20 Nov 2015 20:05:10 +0000 (21:05 +0100)
committerMarcus Klaas <mail@marcusklaas.nl>
Fri, 20 Nov 2015 20:05:10 +0000 (21:05 +0100)
src/comment.rs
src/expr.rs
src/items.rs
src/missed_spans.rs
tests/system.rs
tests/target/match.rs

index eb6c5fc75ec364bbe72f68734bd46ceaad985719..0f118ca5d294a72cc64201d7d9a3d49836538eaa 100644 (file)
@@ -127,12 +127,14 @@ fn find_uncommented(&self, pat: &str) -> Option<usize> {
                 None => {
                     return Some(i - pat.len());
                 }
-                Some(c) => match kind {
-                    CodeCharKind::Normal if b == c => {}
-                    _ => {
-                        needle_iter = pat.chars();
+                Some(c) => {
+                    match kind {
+                        CodeCharKind::Normal if b == c => {}
+                        _ => {
+                            needle_iter = pat.chars();
+                        }
                     }
-                },
+                }
             }
         }
 
@@ -233,33 +235,39 @@ fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
         let item = try_opt!(self.base.next());
         let chr = item.get_char();
         self.status = match self.status {
-            CharClassesStatus::LitString => match chr {
-                '"' => CharClassesStatus::Normal,
-                '\\' => CharClassesStatus::LitStringEscape,
-                _ => CharClassesStatus::LitString,
-            },
+            CharClassesStatus::LitString => {
+                match chr {
+                    '"' => CharClassesStatus::Normal,
+                    '\\' => CharClassesStatus::LitStringEscape,
+                    _ => CharClassesStatus::LitString,
+                }
+            }
             CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
-            CharClassesStatus::LitChar => match chr {
-                '\\' => CharClassesStatus::LitCharEscape,
-                '\'' => CharClassesStatus::Normal,
-                _ => CharClassesStatus::LitChar,
-            },
+            CharClassesStatus::LitChar => {
+                match chr {
+                    '\\' => CharClassesStatus::LitCharEscape,
+                    '\'' => CharClassesStatus::Normal,
+                    _ => CharClassesStatus::LitChar,
+                }
+            }
             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
             CharClassesStatus::Normal => {
                 match chr {
                     '"' => CharClassesStatus::LitString,
                     '\'' => CharClassesStatus::LitChar,
-                    '/' => match self.base.peek() {
-                        Some(next) if next.get_char() == '*' => {
-                            self.status = CharClassesStatus::BlockCommentOpening(1);
-                            return Some((CodeCharKind::Comment, item));
-                        }
-                        Some(next) if next.get_char() == '/' => {
-                            self.status = CharClassesStatus::LineComment;
-                            return Some((CodeCharKind::Comment, item));
+                    '/' => {
+                        match self.base.peek() {
+                            Some(next) if next.get_char() == '*' => {
+                                self.status = CharClassesStatus::BlockCommentOpening(1);
+                                return Some((CodeCharKind::Comment, item));
+                            }
+                            Some(next) if next.get_char() == '/' => {
+                                self.status = CharClassesStatus::LineComment;
+                                return Some((CodeCharKind::Comment, item));
+                            }
+                            _ => CharClassesStatus::Normal,
                         }
-                        _ => CharClassesStatus::Normal,
-                    },
+                    }
                     _ => CharClassesStatus::Normal,
                 }
             }
@@ -271,10 +279,12 @@ fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
                     return Some((CodeCharKind::Comment, item));
                 }
                 self.status = match self.base.peek() {
-                    Some(next) if next.get_char() == '/' && chr == '*' =>
-                        CharClassesStatus::BlockCommentClosing(deepness - 1),
-                    Some(next) if next.get_char() == '*' && chr == '/' =>
-                        CharClassesStatus::BlockCommentOpening(deepness + 1),
+                    Some(next) if next.get_char() == '/' && chr == '*' => {
+                        CharClassesStatus::BlockCommentClosing(deepness - 1)
+                    }
+                    Some(next) if next.get_char() == '*' && chr == '/' => {
+                        CharClassesStatus::BlockCommentOpening(deepness + 1)
+                    }
                     _ => CharClassesStatus::BlockComment(deepness),
                 };
                 return Some((CodeCharKind::Comment, item));
index 8b5fa9fa7870f7c78a7322858986806ae7045802..3247e98c13a162edb2f8f9c5ec6ea52eb0b5af9a 100644 (file)
@@ -571,13 +571,15 @@ fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Opt
         let inner_offset = offset + self.keyword.len() + label_string.len();
 
         let pat_expr_string = match self.cond {
-            Some(cond) => try_opt!(rewrite_pat_expr(context,
-                                                    self.pat,
-                                                    cond,
-                                                    self.matcher,
-                                                    self.connector,
-                                                    inner_width,
-                                                    inner_offset)),
+            Some(cond) => {
+                try_opt!(rewrite_pat_expr(context,
+                                          self.pat,
+                                          cond,
+                                          self.matcher,
+                                          self.connector,
+                                          inner_width,
+                                          inner_offset))
+            }
             None => String::new(),
         };
 
@@ -711,6 +713,8 @@ fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
 }
 
 // Checks that a block contains no statements, an expression and no comments.
+// FIXME: incorrectly returns false when comment is contained completely within
+// the expression.
 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
     block.stmts.is_empty() && block.expr.is_some() && !block_contains_comment(block, codemap)
 }
@@ -936,6 +940,11 @@ fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Opt
 
         let comma = arm_comma(body);
 
+        // let body = match *body {
+        //     ast::ExprBlock(ref b) if is_simple_block(b, context.codemap) => b.expr,
+        //     ref x => x,
+        // };
+
         // Let's try and get the arm body on the same line as the condition.
         // 4 = ` => `.len()
         let same_line_body = if context.config.max_width > line_start + comma.len() + 4 {
@@ -944,12 +953,13 @@ fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Opt
             let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
 
             match rewrite {
-                Some(ref body_str) if body_str.len() <= budget || comma.is_empty() =>
+                Some(ref body_str) if body_str.len() <= budget || comma.is_empty() => {
                     return Some(format!("{}{} => {}{}",
                                         attr_str.trim_left(),
                                         pats_str,
                                         body_str,
-                                        comma)),
+                                        comma));
+                }
                 _ => rewrite,
             }
         } else {
@@ -961,26 +971,34 @@ fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Opt
             return None;
         }
 
-        let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
-        let indent = context.block_indent.block_indent(context.config);
-        let inner_context = &RewriteContext { block_indent: indent, ..*context };
-        let next_line_body = nop_block_collapse(body.rewrite(inner_context, body_budget, indent),
-                                                body_budget);
+        let mut result = format!("{}{} =>", attr_str.trim_left(), pats_str);
 
-        let body_str = try_opt!(match_arm_heuristic(same_line_body.as_ref().map(|x| &x[..]),
-                                                    next_line_body.as_ref().map(|x| &x[..])));
-
-        let spacer = match same_line_body {
-            Some(ref body) if body == body_str => " ".to_owned(),
-            _ => format!("\n{}",
-                         offset.block_indent(context.config).to_string(context.config)),
+        match same_line_body {
+            // FIXME: also take this branch is expr is block
+            Some(ref body) if !body.contains('\n') => {
+                result.push(' ');
+                result.push_str(&body);
+            }
+            _ => {
+                let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
+                let indent = context.block_indent.block_indent(context.config);
+                let inner_context = &RewriteContext { block_indent: indent, ..*context };
+                let next_line_body = try_opt!(nop_block_collapse(body.rewrite(inner_context,
+                                                                              body_budget,
+                                                                              indent),
+                                                                 body_budget));
+
+                result.push_str(" {\n");
+                let indent_str = offset.block_indent(context.config).to_string(context.config);
+                result.push_str(&indent_str);
+                result.push_str(&next_line_body);
+                result.push('\n');
+                result.push_str(&offset.to_string(context.config));
+                result.push('}');
+            }
         };
 
-        Some(format!("{}{} =>{}{},",
-                     attr_str.trim_left(),
-                     pats_str,
-                     spacer,
-                     body_str))
+        Some(result)
     }
 }
 
@@ -1396,8 +1414,9 @@ enum StructLitField<'a> {
 
     match (context.config.struct_lit_style,
            context.config.struct_lit_multiline_style) {
-        (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget =>
-            format_on_newline(),
+        (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget => {
+            format_on_newline()
+        }
         (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
         _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
     }
index c7cfc732fc1be2145a996f3f0c1eac265faef66b..60d08743a95210cace9f9ad35789d8c0e82b229e 100644 (file)
@@ -564,23 +564,26 @@ enum ArgumentKind<'a> {
                                           ")",
                                           |arg| {
                                               match *arg {
-                                                  ArgumentKind::Regular(arg) =>
-                                                      span_lo_for_arg(arg),
+                                                  ArgumentKind::Regular(arg) => {
+                                                      span_lo_for_arg(arg)
+                                                  }
                                                   ArgumentKind::Variadic(start) => start,
                                               }
                                           },
                                           |arg| {
                                               match *arg {
                                                   ArgumentKind::Regular(arg) => arg.ty.span.hi,
-                                                  ArgumentKind::Variadic(start) =>
-                                                      start + BytePos(3),
+                                                  ArgumentKind::Variadic(start) => {
+                                                      start + BytePos(3)
+                                                  }
                                               }
                                           },
                                           |arg| {
                                               match *arg {
                                                   ArgumentKind::Regular(..) => None,
-                                                  ArgumentKind::Variadic(..) =>
-                                                      Some("...".to_owned()),
+                                                  ArgumentKind::Variadic(..) => {
+                                                      Some("...".to_owned())
+                                                  }
                                               }
                                           },
                                           comment_span_start,
@@ -1118,8 +1121,9 @@ fn rewrite_where_clause(&self,
 
         let extra_indent = match self.config.where_indent {
             BlockIndentStyle::Inherit => Indent::empty(),
-            BlockIndentStyle::Tabbed | BlockIndentStyle::Visual =>
-                Indent::new(config.tab_spaces, 0),
+            BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => {
+                Indent::new(config.tab_spaces, 0)
+            }
         };
 
         let context = self.get_context();
index b83f07e05d768de1c921b998e815445809191153..727bc49a7422c2afc39721be04e87f7421eacf70 100644 (file)
@@ -103,10 +103,12 @@ fn replace_chars(string: &str) -> String {
         }
 
         let replaced = match self.write_mode {
-            Some(mode) => match mode {
-                WriteMode::Coverage => replace_chars(old_snippet),
-                _ => old_snippet.to_owned(),
-            },
+            Some(mode) => {
+                match mode {
+                    WriteMode::Coverage => replace_chars(old_snippet),
+                    _ => old_snippet.to_owned(),
+                }
+            }
             None => old_snippet.to_owned(),
         };
         let snippet = &*replaced;
index 4a924c578337a5dfcec8185165fc8ed3a1f2b41d..6d3c817256cae7443c0260d4c1ffa212ff0165eb 100644 (file)
@@ -249,8 +249,10 @@ fn handle_result(result: HashMap<String, String>,
 fn get_target(file_name: &str, target: Option<&str>, write_mode: WriteMode) -> String {
     let file_path = Path::new(file_name);
     let (source_path_prefix, target_path_prefix) = match write_mode {
-        WriteMode::Coverage => (Path::new("tests/coverage-source/"),
-                                "tests/coverage-target/"),
+        WriteMode::Coverage => {
+            (Path::new("tests/coverage-source/"),
+             "tests/coverage-target/")
+        }
         _ => (Path::new("tests/source/"), "tests/target/"),
     };
 
index 1d6842d358a20b136ccc0cf06f9f7fbd4334b1ae..28a5ce2d98cc001f062fb69b579445d27df8ee29 100644 (file)
@@ -13,8 +13,9 @@ fn foo() {
             foo()
         }
         // Perhaps this should introduce braces?
-        Foo(ref bar) =>
-            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
+        Foo(ref bar) => {
+            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+        }
         Pattern1 | Pattern2 | Pattern3 => false,
         Paternnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn |
         Paternnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn => {
@@ -29,8 +30,9 @@ fn foo() {
         Patternnnnnnnnnnnnnnnnnnn if looooooooooooooooooong_guard => meh,
 
         Patternnnnnnnnnnnnnnnnnnnnnnnnn |
-        Patternnnnnnnnnnnnnnnnnnnnnnnnn if looooooooooooooooooooooooooooooooooooooooong_guard =>
-            meh,
+        Patternnnnnnnnnnnnnnnnnnnnnnnnn if looooooooooooooooooooooooooooooooooooooooong_guard => {
+            meh
+        }
 
         // Test that earlier patterns can take the guard space
         (aaaa,
@@ -75,19 +77,24 @@ fn main() {
 // Test that one-line bodies align.
 fn main() {
     match r {
-        Variableeeeeeeeeeeeeeeeee => ("variable",
-                                      vec!["id", "name", "qualname", "value", "type", "scopeid"],
-                                      true,
-                                      true),
-        Enummmmmmmmmmmmmmmmmmmmm => ("enum",
-                                     vec!["id", "qualname", "scopeid", "value"],
-                                     true,
-                                     true),
-        Variantttttttttttttttttttttttt =>
+        Variableeeeeeeeeeeeeeeeee => {
+            ("variable",
+             vec!["id", "name", "qualname", "value", "type", "scopeid"],
+             true,
+             true)
+        }
+        Enummmmmmmmmmmmmmmmmmmmm => {
+            ("enum",
+             vec!["id", "qualname", "scopeid", "value"],
+             true,
+             true)
+        }
+        Variantttttttttttttttttttttttt => {
             ("variant",
              vec!["id", "name", "qualname", "type", "value", "scopeid"],
              true,
-             true),
+             true)
+        }
     }
 }
 
@@ -176,22 +183,28 @@ fn issue355() {
         // m comment
         m => vec!(3; 4),
         // Rewrite splits macro
-        nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn =>
-            println!("a", b),
+        nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn => {
+            println!("a", b)
+        }
         // Rewrite splits macro
-        oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo =>
-            vec![1, 2],
+        oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo => {
+            vec![1, 2]
+        }
         // Macro support fails to recognise this macro as splitable
         // We push the whole expr to a new line, TODO split this macro as well
-        pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp =>
-            vec!(3; 4),
+        pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp => {
+            vec!(3; 4)
+        }
         // q, r and s: Rewrite splits match arm
-        qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq =>
-            println!("a", b),
-        rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr =>
-            vec![1, 2],
-        ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss =>
-            vec!(3; 4),
+        qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq => {
+            println!("a", b)
+        }
+        rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr => {
+            vec![1, 2]
+        }
+        ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss => {
+            vec!(3; 4)
+        }
         // Funky bracketing styles
         t => println!{"a", b},
         u => vec![1, 2],
@@ -206,20 +219,24 @@ fn issue355() {
         wc => println!["a", b], // comment
         xc => vec![1, 2], // comment
         yc => vec![3; 4], // comment
-        yd => looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_func(aaaaaaaaaa,
-                                                                                bbbbbbbbbb,
-                                                                                cccccccccc,
-                                                                                dddddddddd),
+        yd => {
+            looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_func(aaaaaaaaaa,
+                                                                              bbbbbbbbbb,
+                                                                              cccccccccc,
+                                                                              dddddddddd)
+        }
     }
 }
 
 fn issue280() {
     {
         match x {
-            CompressionMode::DiscardNewline | CompressionMode::CompressWhitespaceNewline =>
-                ch == '\n',
-            ast::ItemConst(ref typ, ref expr) =>
-                self.process_static_or_const_item(item, &typ, &expr),
+            CompressionMode::DiscardNewline | CompressionMode::CompressWhitespaceNewline => {
+                ch == '\n'
+            }
+            ast::ItemConst(ref typ, ref expr) => {
+                self.process_static_or_const_item(item, &typ, &expr)
+            }
         }
     }
 }
@@ -253,12 +270,13 @@ fn issue496() {
         {
             {
                 match def {
-                    def::DefConst(def_id) | def::DefAssociatedConst(def_id) =>
+                    def::DefConst(def_id) | def::DefAssociatedConst(def_id) => {
                         match const_eval::lookup_const_by_id(cx.tcx, def_id, Some(self.pat.id)) {
                             Some(const_expr) => {
                                 x
                             }
-                        },
+                        }
+                    }
                 }
             }
         }
@@ -268,14 +286,15 @@ fn issue496() {
 fn issue494() {
     {
         match stmt.node {
-            hir::StmtExpr(ref expr, id) | hir::StmtSemi(ref expr, id) =>
+            hir::StmtExpr(ref expr, id) | hir::StmtSemi(ref expr, id) => {
                 result.push(StmtRef::Mirror(Box::new(Stmt {
                     span: stmt.span,
                     kind: StmtKind::Expr {
                         scope: cx.tcx.region_maps.node_extent(id),
                         expr: expr.to_ref(),
                     },
-                }))),
+                })))
+            }
         }
     }
 }