]> git.lizzy.rs Git - rust.git/blobdiff - src/closures.rs
Merge commit 'c4416f20dcaec5d93077f72470e83e150fb923b1' into sync-rustfmt
[rust.git] / src / closures.rs
index 153f3413f105a459775984a72b041437963976f4..e688db1c39d7c79209178ef2c1ae108fa909647d 100644 (file)
@@ -1,26 +1,17 @@
-// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use config::lists::*;
-use syntax::parse::classify;
-use syntax::source_map::Span;
-use syntax::{ast, ptr};
-
-use expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
-use items::{span_hi_for_arg, span_lo_for_arg};
-use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
-use overflow::OverflowableItem;
-use rewrite::{Rewrite, RewriteContext};
-use shape::Shape;
-use source_map::SpanUtils;
-use utils::{last_line_width, left_most_sub_expr, stmt_expr};
+use rustc_ast::{ast, ptr};
+use rustc_span::Span;
+
+use crate::attr::get_attrs_from_stmt;
+use crate::config::lists::*;
+use crate::config::Version;
+use crate::expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
+use crate::items::{span_hi_for_param, span_lo_for_param};
+use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
+use crate::overflow::OverflowableItem;
+use crate::rewrite::{Rewrite, RewriteContext};
+use crate::shape::Shape;
+use crate::source_map::SpanUtils;
+use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt};
 
 // This module is pretty messy because of the rules around closures and blocks:
 // FIXME - the below is probably no longer true in full.
 //     statement without needing a semi-colon), then adding or removing braces
 //     can change whether it is treated as an expression or statement.
 
-pub fn rewrite_closure(
+pub(crate) fn rewrite_closure(
     capture: ast::CaptureBy,
-    asyncness: ast::IsAsync,
+    is_async: &ast::Async,
     movability: ast::Movability,
     fn_decl: &ast::FnDecl,
     body: &ast::Expr,
     span: Span,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
 ) -> Option<String> {
     debug!("rewrite_closure {:?}", body);
 
     let (prefix, extra_offset) = rewrite_closure_fn_decl(
-        capture, asyncness, movability, fn_decl, body, span, context, shape,
+        capture, is_async, movability, fn_decl, body, span, context, shape,
     )?;
     // 1 = space between `|...|` and body.
     let body_shape = shape.offset_left(extra_offset)?;
 
-    if let ast::ExprKind::Block(ref block, _) = body.node {
+    if let ast::ExprKind::Block(ref block, _) = body.kind {
         // The body of the closure is an empty block.
-        if block.stmts.is_empty() && !block_contains_comment(block, context.source_map) {
+        if block.stmts.is_empty() && !block_contains_comment(context, block) {
             return body
                 .rewrite(context, shape)
                 .map(|s| format!("{} {}", prefix, s));
         }
 
         let result = match fn_decl.output {
-            ast::FunctionRetTy::Default(_) => {
+            ast::FnRetTy::Default(_) if !context.inside_macro() => {
                 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
             }
             _ => None,
@@ -81,7 +72,7 @@ pub fn rewrite_closure(
 fn try_rewrite_without_block(
     expr: &ast::Expr,
     prefix: &str,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
     body_shape: Shape,
 ) -> Option<String> {
@@ -97,12 +88,13 @@ fn try_rewrite_without_block(
 fn get_inner_expr<'a>(
     expr: &'a ast::Expr,
     prefix: &str,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
 ) -> &'a ast::Expr {
-    if let ast::ExprKind::Block(ref block, _) = expr.node {
+    if let ast::ExprKind::Block(ref block, _) = expr.kind {
         if !needs_block(block, prefix, context) {
-            // block.stmts.len() == 1
-            if let Some(expr) = stmt_expr(&block.stmts[0]) {
+            // block.stmts.len() == 1 except with `|| {{}}`;
+            // https://github.com/rust-lang/rustfmt/issues/3844
+            if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
                 return get_inner_expr(expr, prefix, context);
             }
         }
@@ -112,15 +104,20 @@ fn get_inner_expr<'a>(
 }
 
 // Figure out if a block is necessary.
-fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext) -> bool {
+fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
+    let has_attributes = block.stmts.first().map_or(false, |first_stmt| {
+        !get_attrs_from_stmt(first_stmt).is_empty()
+    });
+
     is_unsafe_block(block)
         || block.stmts.len() > 1
-        || block_contains_comment(block, context.source_map)
+        || has_attributes
+        || block_contains_comment(context, block)
         || prefix.contains('\n')
 }
 
 fn veto_block(e: &ast::Expr) -> bool {
-    match e.node {
+    match e.kind {
         ast::ExprKind::Call(..)
         | ast::ExprKind::Binary(..)
         | ast::ExprKind::Cast(..)
@@ -136,30 +133,44 @@ fn veto_block(e: &ast::Expr) -> bool {
 }
 
 // Rewrite closure with a single expression wrapping its body with block.
+// || { #[attr] foo() } -> Block { #[attr] foo() }
 fn rewrite_closure_with_block(
     body: &ast::Expr,
     prefix: &str,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
 ) -> Option<String> {
     let left_most = left_most_sub_expr(body);
-    let veto_block = veto_block(body) && !classify::expr_requires_semi_to_be_stmt(left_most);
+    let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
     if veto_block {
         return None;
     }
 
     let block = ast::Block {
         stmts: vec![ast::Stmt {
-            id: ast::NodeId::new(0),
-            node: ast::StmtKind::Expr(ptr::P(body.clone())),
+            id: ast::NodeId::root(),
+            kind: ast::StmtKind::Expr(ptr::P(body.clone())),
             span: body.span,
         }],
-        id: ast::NodeId::new(0),
+        id: ast::NodeId::root(),
         rules: ast::BlockCheckMode::Default,
-        span: body.span,
-        recovered: false,
+        tokens: None,
+        span: body
+            .attrs
+            .first()
+            .map(|attr| attr.span.to(body.span))
+            .unwrap_or(body.span),
+        could_be_bare_literal: false,
     };
-    let block = ::expr::rewrite_block_with_visitor(context, "", &block, None, None, shape, false)?;
+    let block = crate::expr::rewrite_block_with_visitor(
+        context,
+        "",
+        &block,
+        Some(&body.attrs),
+        None,
+        shape,
+        false,
+    )?;
     Some(format!("{} {}", prefix, block))
 }
 
@@ -167,18 +178,19 @@ fn rewrite_closure_with_block(
 fn rewrite_closure_expr(
     expr: &ast::Expr,
     prefix: &str,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
 ) -> Option<String> {
     fn allow_multi_line(expr: &ast::Expr) -> bool {
-        match expr.node {
+        match expr.kind {
             ast::ExprKind::Match(..)
+            | ast::ExprKind::Async(..)
             | ast::ExprKind::Block(..)
             | ast::ExprKind::TryBlock(..)
             | ast::ExprKind::Loop(..)
             | ast::ExprKind::Struct(..) => true,
 
-            ast::ExprKind::AddrOf(_, ref expr)
+            ast::ExprKind::AddrOf(_, _, ref expr)
             | ast::ExprKind::Box(ref expr)
             | ast::ExprKind::Try(ref expr)
             | ast::ExprKind::Unary(_, ref expr)
@@ -207,7 +219,7 @@ fn allow_multi_line(expr: &ast::Expr) -> bool {
 fn rewrite_closure_block(
     block: &ast::Block,
     prefix: &str,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
 ) -> Option<String> {
     Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
@@ -216,50 +228,50 @@ fn rewrite_closure_block(
 // Return type is (prefix, extra_offset)
 fn rewrite_closure_fn_decl(
     capture: ast::CaptureBy,
-    asyncness: ast::IsAsync,
+    asyncness: &ast::Async,
     movability: ast::Movability,
     fn_decl: &ast::FnDecl,
     body: &ast::Expr,
     span: Span,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
 ) -> Option<(String, usize)> {
-    let is_async = if asyncness.is_async() { "async " } else { "" };
-    let mover = if capture == ast::CaptureBy::Value {
-        "move "
+    let immovable = if movability == ast::Movability::Static {
+        "static "
     } else {
         ""
     };
-    let immovable = if movability == ast::Movability::Static {
-        "static "
+    let is_async = if asyncness.is_async() { "async " } else { "" };
+    let mover = if capture == ast::CaptureBy::Value {
+        "move "
     } else {
         ""
     };
     // 4 = "|| {".len(), which is overconservative when the closure consists of
     // a single expression.
     let nested_shape = shape
-        .shrink_left(is_async.len() + mover.len() + immovable.len())?
+        .shrink_left(immovable.len() + is_async.len() + mover.len())?
         .sub_width(4)?;
 
     // 1 = |
-    let argument_offset = nested_shape.indent + 1;
-    let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
-    let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
+    let param_offset = nested_shape.indent + 1;
+    let param_shape = nested_shape.offset_left(1)?.visual_indent(0);
+    let ret_str = fn_decl.output.rewrite(context, param_shape)?;
 
-    let arg_items = itemize_list(
+    let param_items = itemize_list(
         context.snippet_provider,
         fn_decl.inputs.iter(),
         "|",
         ",",
-        |arg| span_lo_for_arg(arg),
-        |arg| span_hi_for_arg(context, arg),
-        |arg| arg.rewrite(context, arg_shape),
+        |param| span_lo_for_param(param),
+        |param| span_hi_for_param(context, param),
+        |param| param.rewrite(context, param_shape),
         context.snippet_provider.span_after(span, "|"),
         body.span.lo(),
         false,
     );
-    let item_vec = arg_items.collect::<Vec<_>>();
-    // 1 = space between arguments and return type.
+    let item_vec = param_items.collect::<Vec<_>>();
+    // 1 = space between parameters and return type.
     let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
     let tactic = definitive_tactic(
         &item_vec,
@@ -267,21 +279,21 @@ fn rewrite_closure_fn_decl(
         Separator::Comma,
         horizontal_budget,
     );
-    let arg_shape = match tactic {
-        DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
-        _ => arg_shape,
+    let param_shape = match tactic {
+        DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1)?,
+        _ => param_shape,
     };
 
-    let fmt = ListFormatting::new(arg_shape, context.config)
+    let fmt = ListFormatting::new(param_shape, context.config)
         .tactic(tactic)
         .preserve_newline(true);
     let list_str = write_list(&item_vec, &fmt)?;
-    let mut prefix = format!("{}{}{}|{}|", is_async, immovable, mover, list_str);
+    let mut prefix = format!("{}{}{}|{}|", immovable, is_async, mover, list_str);
 
     if !ret_str.is_empty() {
         if prefix.contains('\n') {
             prefix.push('\n');
-            prefix.push_str(&argument_offset.to_string(context.config));
+            prefix.push_str(&param_offset.to_string(context.config));
         } else {
             prefix.push(' ');
         }
@@ -295,25 +307,26 @@ fn rewrite_closure_fn_decl(
 
 // Rewriting closure which is placed at the end of the function call's arg.
 // Returns `None` if the reformatted closure 'looks bad'.
-pub fn rewrite_last_closure(
-    context: &RewriteContext,
+pub(crate) fn rewrite_last_closure(
+    context: &RewriteContext<'_>,
     expr: &ast::Expr,
     shape: Shape,
 ) -> Option<String> {
-    if let ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) =
-        expr.node
+    if let ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) =
+        expr.kind
     {
-        let body = match body.node {
+        let body = match body.kind {
             ast::ExprKind::Block(ref block, _)
                 if !is_unsafe_block(block)
-                    && is_simple_block(block, Some(&body.attrs), context.source_map) =>
+                    && !context.inside_macro()
+                    && is_simple_block(context, block, Some(&body.attrs)) =>
             {
                 stmt_expr(&block.stmts[0]).unwrap_or(body)
             }
             _ => body,
         };
         let (prefix, extra_offset) = rewrite_closure_fn_decl(
-            capture, asyncness, movability, fn_decl, body, expr.span, context, shape,
+            capture, is_async, movability, fn_decl, body, expr.span, context, shape,
         )?;
         // If the closure goes multi line before its body, do not overflow the closure.
         if prefix.contains('\n') {
@@ -324,20 +337,23 @@ pub fn rewrite_last_closure(
 
         // We force to use block for the body of the closure for certain kinds of expressions.
         if is_block_closure_forced(context, body) {
-            return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
+            return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
                 |body_str| {
-                    // If the expression can fit in a single line, we need not force block closure.
-                    if body_str.lines().count() <= 7 {
-                        match rewrite_closure_expr(body, &prefix, context, shape) {
-                            Some(ref single_line_body_str)
-                                if !single_line_body_str.contains('\n') =>
-                            {
-                                Some(single_line_body_str.clone())
+                    match fn_decl.output {
+                        ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
+                            // If the expression can fit in a single line, we need not force block
+                            // closure.  However, if the closure has a return type, then we must
+                            // keep the blocks.
+                            match rewrite_closure_expr(body, &prefix, context, shape) {
+                                Some(single_line_body_str)
+                                    if !single_line_body_str.contains('\n') =>
+                                {
+                                    single_line_body_str
+                                }
+                                _ => body_str,
                             }
-                            _ => Some(body_str),
                         }
-                    } else {
-                        Some(body_str)
+                        _ => body_str,
                     }
                 },
             );
@@ -345,9 +361,9 @@ pub fn rewrite_last_closure(
 
         // When overflowing the closure which consists of a single control flow expression,
         // force to use block if its condition uses multi line.
-        let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
-            .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
-            .unwrap_or(false);
+        let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
+            cond.contains('\n') || cond.len() > body_shape.width
+        });
         if is_multi_lined_cond {
             return rewrite_closure_with_block(body, &prefix, context, body_shape);
         }
@@ -358,42 +374,54 @@ pub fn rewrite_last_closure(
     None
 }
 
-/// Returns true if the given vector of arguments has more than one `ast::ExprKind::Closure`.
-pub fn args_have_many_closure(args: &[OverflowableItem]) -> bool {
+/// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
+pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
     args.iter()
-        .filter(|arg| {
-            arg.to_expr()
-                .map(|e| match e.node {
-                    ast::ExprKind::Closure(..) => true,
-                    _ => false,
-                })
-                .unwrap_or(false)
-        })
+        .filter_map(OverflowableItem::to_expr)
+        .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
         .count()
         > 1
 }
 
-fn is_block_closure_forced(context: &RewriteContext, expr: &ast::Expr) -> bool {
+fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
     // If we are inside macro, we do not want to add or remove block from closure body.
     if context.inside_macro() {
         false
     } else {
-        is_block_closure_forced_inner(expr)
+        is_block_closure_forced_inner(expr, context.config.version())
     }
 }
 
-fn is_block_closure_forced_inner(expr: &ast::Expr) -> bool {
-    match expr.node {
-        ast::ExprKind::If(..)
-        | ast::ExprKind::IfLet(..)
-        | ast::ExprKind::While(..)
-        | ast::ExprKind::WhileLet(..)
-        | ast::ExprKind::ForLoop(..) => true,
-        ast::ExprKind::AddrOf(_, ref expr)
+fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
+    match expr.kind {
+        ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop(..) => true,
+        ast::ExprKind::Loop(..) if version == Version::Two => true,
+        ast::ExprKind::AddrOf(_, _, ref expr)
         | ast::ExprKind::Box(ref expr)
         | ast::ExprKind::Try(ref expr)
         | ast::ExprKind::Unary(_, ref expr)
-        | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr),
+        | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),
         _ => false,
     }
 }
+
+/// Does this expression require a semicolon to be treated
+/// as a statement? The negation of this: 'can this expression
+/// be used as a statement without a semicolon' -- is used
+/// as an early-bail-out in the parser so that, for instance,
+///     if true {...} else {...}
+///      |x| 5
+/// isn't parsed as (if true {...} else {...} | x) | 5
+// From https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/classify.rs.
+fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
+    match e.kind {
+        ast::ExprKind::If(..)
+        | ast::ExprKind::Match(..)
+        | ast::ExprKind::Block(..)
+        | ast::ExprKind::While(..)
+        | ast::ExprKind::Loop(..)
+        | ast::ExprKind::ForLoop(..)
+        | ast::ExprKind::TryBlock(..) => false,
+        _ => true,
+    }
+}