-// Copyright 2018 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.
-
//! Format match expression.
use std::iter::repeat;
-use config::lists::*;
-use syntax::source_map::{BytePos, Span};
-use syntax::{ast, ptr};
+use rustc_ast::{ast, ptr};
+use rustc_span::{BytePos, Span};
-use comment::{combine_strs_with_missing_comments, rewrite_comment};
-use config::{Config, ControlBraceStyle, IndentStyle};
-use expr::{
+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,
+ 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,
+ semicolon_for_expr, trimmed_last_line_width, unicode_str_width,
};
/// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
struct ArmWrapper<'a> {
- pub arm: &'a ast::Arm,
- /// True if the arm is the last one in match expression. Used to decide on whether we should add
- /// trailing comma to the match arm when `config.trailing_comma() == Never`.
- pub is_last: bool,
+ arm: &'a ast::Arm,
+ /// `true` if the arm is the last one in match expression. Used to decide on whether we should
+ /// add trailing comma to the match arm when `config.trailing_comma() == Never`.
+ is_last: bool,
/// Holds a byte position of `|` at the beginning of the arm pattern, if available.
- pub beginning_vert: Option<BytePos>,
+ beginning_vert: Option<BytePos>,
}
impl<'a> ArmWrapper<'a> {
- pub fn new(
- arm: &'a ast::Arm,
- is_last: bool,
- beginning_vert: Option<BytePos>,
- ) -> ArmWrapper<'a> {
+ fn new(arm: &'a ast::Arm, is_last: bool, beginning_vert: Option<BytePos>) -> ArmWrapper<'a> {
ArmWrapper {
arm,
is_last,
impl<'a> Spanned for ArmWrapper<'a> {
fn span(&self) -> Span {
if let Some(lo) = self.beginning_vert {
+ let lo = std::cmp::min(lo, self.arm.span().lo());
mk_sp(lo, self.arm.span().hi())
} else {
self.arm.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,
+pub(crate) fn rewrite_match(
+ context: &RewriteContext<'_>,
cond: &ast::Expr,
arms: &[ast::Arm],
shape: Shape,
.snippet_provider
.span_after(mk_sp(cond.span.hi(), hi), "{")
} else {
- inner_attrs[inner_attrs.len() - 1].span().hi()
+ inner_attrs[inner_attrs.len() - 1].span.hi()
};
if arms.is_empty() {
""
} else if config.match_block_trailing_comma() {
","
- } else if let ast::ExprKind::Block(ref block, _) = body.node {
+ } else if let ast::ExprKind::Block(ref block, _) = body.kind {
if let ast::BlockCheckMode::Default = block.rules {
""
} else {
/// 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>> {
let mut beginning_verts = Vec::with_capacity(arms.len());
let mut lo = context.snippet_provider.span_after(span, "{");
for arm in arms {
- let hi = arm.pats[0].span.lo();
+ let hi = arm.pat.span.lo();
let missing_span = mk_sp(lo, hi);
beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
lo = arm.span().hi();
}
fn rewrite_match_arms(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
arms: &[ast::Arm],
shape: Shape,
span: Span,
}
fn rewrite_match_arm(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
arm: &ast::Arm,
shape: Shape,
is_last: bool,
arm_comma(context.config, body, is_last),
));
}
- let missing_span = mk_sp(
- arm.attrs[arm.attrs.len() - 1].span.hi(),
- arm.pats[0].span.lo(),
- );
+ let missing_span = mk_sp(arm.attrs[arm.attrs.len() - 1].span.hi(), arm.pat.span.lo());
(missing_span, arm.attrs.rewrite(context, shape)?)
} 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 = arm.pat.rewrite(context, 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,
+ )?;
+
+ let lhs_str = combine_strs_with_missing_comments(
+ context,
+ &attrs_str,
+ &format!("{}{}", pats_str, guard_str),
+ missing_span,
+ shape,
+ false,
)?;
- Some(format!("{}{}", pats_str, guard_str))
+ let arrow_span = mk_sp(arm.pat.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 {
+ match expr.kind {
ast::ExprKind::Block(ref block, _)
if !is_unsafe_block(block)
- && is_simple_block(block, Some(&expr.attrs), context.source_map) =>
+ && !context.inside_macro()
+ && is_simple_block(context, block, Some(&expr.attrs)) =>
{
Some(&*block)
}
// @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,
+ context: &'a RewriteContext<'_>,
body: &'a ast::Expr,
opt_shape: Option<Shape>,
) -> (bool, &'a ast::Expr) {
|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 {
+ if let ast::StmtKind::Expr(ref expr) = block.stmts[0].kind {
+ if let ast::ExprKind::Block(..) = expr.kind {
flatten_arm_body(context, expr, None)
} else {
let cond_becomes_muti_line = opt_shape
}
fn rewrite_match_body(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
body: &ptr::P<ast::Expr>,
pats_str: &str,
shape: Shape,
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,
- is_empty_block(block, Some(&body.attrs), context.source_map),
- )
+ let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block, _) = body.kind {
+ (true, is_empty_block(context, block, Some(&body.attrs)))
} else {
(false, false)
};
shape.indent
};
- let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
+ let forbid_same_line =
+ (has_guard && pats_str.contains('\n') && !is_empty_block) || !body.attrs.is_empty();
// 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() {
}
let indent_str = shape.indent.to_string_with_newline(context.config);
- let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
- let comma = if context.config.match_block_trailing_comma() {
- ","
+ let (body_prefix, body_suffix) =
+ if context.config.match_arm_blocks() && !context.inside_macro() {
+ let comma = if context.config.match_block_trailing_comma() {
+ ","
+ } else {
+ ""
+ };
+ let semicolon = if context.config.version() == Version::One {
+ ""
+ } else {
+ if semicolon_for_expr(context, body) {
+ ";"
+ } else {
+ ""
+ }
+ };
+ ("{", format!("{}{}}}{}", semicolon, indent_str, comma))
} else {
- ""
+ ("", String::from(","))
};
- ("{", format!("{}}}{}", indent_str, comma))
- } else {
- ("", String::from(","))
- };
let block_sep = match context.config.control_brace_style() {
ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
match rewrite {
Some(ref body_str)
- if is_block || (!body_str.contains('\n') && body_str.len() <= body_shape.width) =>
+ if is_block
+ || (!body_str.contains('\n')
+ && unicode_str_width(body_str) <= body_shape.width) =>
{
return combine_orig_body(body_str);
}
}
}
-impl Rewrite for ast::Guard {
- fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
- match self {
- ast::Guard::If(ref expr) => expr.rewrite(context, shape),
- }
- }
-}
-
// The `if ...` guard on a match arm.
fn rewrite_guard(
- context: &RewriteContext,
- guard: &Option<ast::Guard>,
+ context: &RewriteContext<'_>,
+ guard: &Option<ptr::P<ast::Expr>>,
shape: Shape,
// The amount of space used up on this line for the pattern in
// the arm (excludes offset).
&& 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
}
})
}
fn can_flatten_block_around_this(body: &ast::Expr) -> bool {
- match body.node {
+ match body.kind {
// We do not allow `if` to stay on the same line, since we could easily mistake
// `pat => if cond { ... }` and `pat if cond => { ... }`.
- ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
+ ast::ExprKind::If(..) => false,
// We do not allow collapsing a block around expression with condition
// to avoid it being cluttered with match arm.
- ast::ExprKind::ForLoop(..) | ast::ExprKind::While(..) | ast::ExprKind::WhileLet(..) => {
- false
- }
+ ast::ExprKind::ForLoop(..) | ast::ExprKind::While(..) => false,
ast::ExprKind::Loop(..)
| ast::ExprKind::Match(..)
| ast::ExprKind::Block(..)
| ast::ExprKind::Array(..)
| ast::ExprKind::Call(..)
| ast::ExprKind::MethodCall(..)
- | ast::ExprKind::Mac(..)
+ | ast::ExprKind::MacCall(..)
| ast::ExprKind::Struct(..)
| ast::ExprKind::Tup(..) => 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)
+ | ast::ExprKind::Index(ref expr, _)
| ast::ExprKind::Cast(ref expr, _) => can_flatten_block_around_this(expr),
_ => false,
}