]> git.lizzy.rs Git - rust.git/blobdiff - src/matches.rs
Merge pull request #3401 from topecongiro/rustcap
[rust.git] / src / matches.rs
index 2295535b1215c902bf6e4a5e5895cc83e860316f..15ff7dbb8fe72b3352cab8cb953192ee9b4b1b63 100644 (file)
 
 use std::iter::repeat;
 
-use config::lists::*;
 use syntax::source_map::{BytePos, Span};
 use syntax::{ast, ptr};
 
-use comment::{combine_strs_with_missing_comments, rewrite_comment};
-use config::{Config, ControlBraceStyle, IndentStyle};
-use expr::{
-    format_expr, is_empty_block, is_simple_block, is_unsafe_block, prefer_next_line,
+use crate::comment::{combine_strs_with_missing_comments, rewrite_comment};
+use crate::config::lists::*;
+use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
+use crate::expr::{
+    format_expr, is_empty_block, is_simple_block, is_unsafe_block, prefer_next_line, rewrite_cond,
     rewrite_multiple_patterns, ExprType, RhsTactics,
 };
-use lists::{itemize_list, write_list, ListFormatting};
-use rewrite::{Rewrite, RewriteContext};
-use shape::Shape;
-use source_map::SpanUtils;
-use spanned::Spanned;
-use utils::{
+use crate::lists::{itemize_list, write_list, ListFormatting};
+use crate::rewrite::{Rewrite, RewriteContext};
+use crate::shape::Shape;
+use crate::source_map::SpanUtils;
+use crate::spanned::Spanned;
+use crate::utils::{
     contains_skip, extra_offset, first_line_width, inner_attributes, last_line_extendable, mk_sp,
-    ptr_vec_to_ref_vec, trimmed_last_line_width,
+    ptr_vec_to_ref_vec, semicolon_for_expr, trimmed_last_line_width,
 };
 
 /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
@@ -67,13 +67,13 @@ fn span(&self) -> Span {
 }
 
 impl<'a> Rewrite for ArmWrapper<'a> {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         rewrite_match_arm(context, self.arm, shape, self.is_last)
     }
 }
 
 pub fn rewrite_match(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     cond: &ast::Expr,
     arms: &[ast::Arm],
     shape: Shape,
@@ -168,7 +168,7 @@ fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
 
 /// Collect a byte position of the beginning `|` for each arm, if available.
 fn collect_beginning_verts(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     arms: &[ast::Arm],
     span: Span,
 ) -> Vec<Option<BytePos>> {
@@ -184,7 +184,7 @@ fn collect_beginning_verts(
 }
 
 fn rewrite_match_arms(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     arms: &[ast::Arm],
     shape: Shape,
     span: Span,
@@ -224,14 +224,14 @@ fn rewrite_match_arms(
 }
 
 fn rewrite_match_arm(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     arm: &ast::Arm,
     shape: Shape,
     is_last: bool,
 ) -> Option<String> {
     let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
         if contains_skip(&arm.attrs) {
-            let (_, body) = flatten_arm_body(context, &arm.body);
+            let (_, body) = flatten_arm_body(context, &arm.body, None);
             // `arm.span()` does not include trailing comma, add it manually.
             return Some(format!(
                 "{}{}",
@@ -247,56 +247,46 @@ fn rewrite_match_arm(
     } else {
         (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
     };
-    let pats_str =
-        rewrite_match_pattern(context, &ptr_vec_to_ref_vec(&arm.pats), &arm.guard, shape)
-            .and_then(|pats_str| {
-                combine_strs_with_missing_comments(
-                    context,
-                    &attrs_str,
-                    &pats_str,
-                    missing_span,
-                    shape,
-                    false,
-                )
-            })?;
 
-    let arrow_span = mk_sp(arm.pats.last().unwrap().span.hi(), arm.body.span.lo());
-    rewrite_match_body(
-        context,
-        &arm.body,
-        &pats_str,
-        shape,
-        arm.guard.is_some(),
-        arrow_span,
-        is_last,
-    )
-}
-
-fn rewrite_match_pattern(
-    context: &RewriteContext,
-    pats: &[&ast::Pat],
-    guard: &Option<ast::Guard>,
-    shape: Shape,
-) -> Option<String> {
     // Patterns
     // 5 = ` => {`
     let pat_shape = shape.sub_width(5)?;
-    let pats_str = rewrite_multiple_patterns(context, pats, pat_shape)?;
+    let pats_str = rewrite_multiple_patterns(context, &ptr_vec_to_ref_vec(&arm.pats), pat_shape)?;
 
     // Guard
+    let block_like_pat = trimmed_last_line_width(&pats_str) <= context.config.tab_spaces();
+    let new_line_guard = pats_str.contains('\n') && !block_like_pat;
     let guard_str = rewrite_guard(
         context,
-        guard,
+        &arm.guard,
         shape,
         trimmed_last_line_width(&pats_str),
-        pats_str.contains('\n'),
+        new_line_guard,
     )?;
 
-    Some(format!("{}{}", pats_str, guard_str))
+    let lhs_str = combine_strs_with_missing_comments(
+        context,
+        &attrs_str,
+        &format!("{}{}", pats_str, guard_str),
+        missing_span,
+        shape,
+        false,
+    )?;
+
+    let arrow_span = mk_sp(arm.pats.last().unwrap().span.hi(), arm.body.span.lo());
+    rewrite_match_body(
+        context,
+        &arm.body,
+        &lhs_str,
+        shape,
+        guard_str.contains('\n'),
+        arrow_span,
+        is_last,
+    )
 }
 
 fn block_can_be_flattened<'a>(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     expr: &'a ast::Expr,
 ) -> Option<&'a ast::Block> {
     match expr.node {
@@ -313,16 +303,27 @@ fn block_can_be_flattened<'a>(
 // (extend, body)
 // @extend: true if the arm body can be put next to `=>`
 // @body: flattened body, if the body is block with a single expression
-fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
+fn flatten_arm_body<'a>(
+    context: &'a RewriteContext<'_>,
+    body: &'a ast::Expr,
+    opt_shape: Option<Shape>,
+) -> (bool, &'a ast::Expr) {
     let can_extend =
         |expr| !context.config.force_multiline_blocks() && can_flatten_block_around_this(expr);
 
     if let Some(ref block) = block_can_be_flattened(context, body) {
         if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
             if let ast::ExprKind::Block(..) = expr.node {
-                flatten_arm_body(context, expr)
+                flatten_arm_body(context, expr, None)
             } else {
-                (can_extend(expr), &*expr)
+                let cond_becomes_muti_line = opt_shape
+                    .and_then(|shape| rewrite_cond(context, expr, shape))
+                    .map_or(false, |cond| cond.contains('\n'));
+                if cond_becomes_muti_line {
+                    (false, &*body)
+                } else {
+                    (can_extend(expr), &*expr)
+                }
             }
         } else {
             (false, &*body)
@@ -333,7 +334,7 @@ fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bo
 }
 
 fn rewrite_match_body(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     body: &ptr::P<ast::Expr>,
     pats_str: &str,
     shape: Shape,
@@ -341,7 +342,11 @@ fn rewrite_match_body(
     arrow_span: Span,
     is_last: bool,
 ) -> Option<String> {
-    let (extend, body) = flatten_arm_body(context, body);
+    let (extend, body) = flatten_arm_body(
+        context,
+        body,
+        shape.offset_left(extra_offset(pats_str, shape) + 4),
+    );
     let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block, _) = body.node {
         (
             true,
@@ -374,7 +379,9 @@ fn rewrite_match_body(
     // Look for comments between `=>` and the start of the body.
     let arrow_comment = {
         let arrow_snippet = context.snippet(arrow_span).trim();
-        let arrow_index = arrow_snippet.find("=>").unwrap();
+        // search for the arrow starting from the end of the snippet since there may be a match
+        // expression within the guard
+        let arrow_index = arrow_snippet.rfind("=>").unwrap();
         // 2 = `=>`
         let comment_str = arrow_snippet[arrow_index + 2..].trim();
         if comment_str.is_empty() {
@@ -406,7 +413,16 @@ fn rewrite_match_body(
             } else {
                 ""
             };
-            ("{", format!("{}}}{}", indent_str, comma))
+            let semicolon = if context.config.version() == Version::One {
+                ""
+            } else {
+                if semicolon_for_expr(context, body) {
+                    ";"
+                } else {
+                    ""
+                }
+            };
+            ("{", format!("{}{}}}{}", semicolon, indent_str, comma))
         } else {
             ("", String::from(","))
         };
@@ -483,7 +499,7 @@ fn rewrite_match_body(
 }
 
 impl Rewrite for ast::Guard {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         match self {
             ast::Guard::If(ref expr) => expr.rewrite(context, shape),
         }
@@ -492,7 +508,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 
 // The `if ...` guard on a match arm.
 fn rewrite_guard(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     guard: &Option<ast::Guard>,
     shape: Shape,
     // The amount of space used up on this line for the pattern in
@@ -544,9 +560,9 @@ fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String
             && budget >= 2
             && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
         {
-            "{}".to_owned()
+            String::from("{}")
         } else {
-            block_str.to_owned()
+            block_str
         }
     })
 }