1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Format match expression.
13 use std::iter::repeat;
16 use syntax::codemap::{BytePos, Span};
17 use syntax::{ast, ptr};
19 use codemap::SpanUtils;
20 use comment::combine_strs_with_missing_comments;
21 use config::{Config, ControlBraceStyle, IndentStyle};
22 use expr::{format_expr, is_empty_block, is_simple_block, is_unsafe_block, prefer_next_line,
23 rewrite_multiple_patterns, ExprType, RhsTactics, ToExpr};
24 use lists::{itemize_list, write_list, ListFormatting};
25 use rewrite::{Rewrite, RewriteContext};
28 use utils::{contains_skip, extra_offset, first_line_width, inner_attributes, last_line_extendable,
29 mk_sp, ptr_vec_to_ref_vec, trimmed_last_line_width};
31 /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
32 struct ArmWrapper<'a> {
33 pub arm: &'a ast::Arm,
34 /// True if the arm is the last one in match expression. Used to decide on whether we should add
35 /// trailing comma to the match arm when `config.trailing_comma() == Never`.
37 /// Holds a byte position of `|` at the beginning of the arm pattern, if available.
38 pub beginning_vert: Option<BytePos>,
41 impl<'a> ArmWrapper<'a> {
45 beginning_vert: Option<BytePos>,
55 impl<'a> Spanned for ArmWrapper<'a> {
56 fn span(&self) -> Span {
57 if let Some(lo) = self.beginning_vert {
58 mk_sp(lo, self.arm.span().hi())
65 impl<'a> Rewrite for ArmWrapper<'a> {
66 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
67 rewrite_match_arm(context, self.arm, shape, self.is_last, self.beginning_vert)
72 context: &RewriteContext,
77 attrs: &[ast::Attribute],
79 // Do not take the rhs overhead from the upper expressions into account
80 // when rewriting match condition.
81 let cond_shape = Shape {
82 width: context.budget(shape.used_width()),
86 let cond_shape = match context.config.indent_style() {
87 IndentStyle::Visual => cond_shape.shrink_left(6)?,
88 IndentStyle::Block => cond_shape.offset_left(6)?,
90 let cond_str = cond.rewrite(context, cond_shape)?;
91 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
92 let block_sep = match context.config.control_brace_style() {
93 ControlBraceStyle::AlwaysNextLine => alt_block_sep,
94 _ if last_line_extendable(&cond_str) => " ",
96 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => alt_block_sep,
100 let nested_indent_str = shape
102 .block_indent(context.config)
103 .to_string(context.config);
105 let inner_attrs = &inner_attributes(attrs);
106 let inner_attrs_str = if inner_attrs.is_empty() {
110 .rewrite(context, shape)
111 .map(|s| format!("{}{}\n", nested_indent_str, s))?
114 let open_brace_pos = if inner_attrs.is_empty() {
115 let hi = if arms.is_empty() {
122 .span_after(mk_sp(cond.span.hi(), hi), "{")
124 inner_attrs[inner_attrs.len() - 1].span().hi()
128 let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
129 if snippet.trim().is_empty() {
130 Some(format!("match {} {{}}", cond_str))
132 // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
133 Some(context.snippet(span).to_owned())
136 let span_after_cond = mk_sp(cond.span.hi(), span.hi());
138 "match {}{}{{\n{}{}{}\n{}}}",
143 rewrite_match_arms(context, arms, shape, span_after_cond, open_brace_pos)?,
144 shape.indent.to_string(context.config),
149 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
150 if is_last && config.trailing_comma() == SeparatorTactic::Never {
152 } else if config.match_block_trailing_comma() {
154 } else if let ast::ExprKind::Block(ref block) = body.node {
155 if let ast::BlockCheckMode::Default = block.rules {
165 /// Collect a byte position of the beginning `|` for each arm, if available.
166 fn collect_beginning_verts(
167 context: &RewriteContext,
170 ) -> Vec<Option<BytePos>> {
171 let mut beginning_verts = Vec::with_capacity(arms.len());
172 let mut lo = context.snippet_provider.span_after(span, "{");
174 let hi = arm.pats[0].span.lo();
175 let missing_span = mk_sp(lo, hi);
176 beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
177 lo = arm.span().hi();
182 fn rewrite_match_arms(
183 context: &RewriteContext,
187 open_brace_pos: BytePos,
188 ) -> Option<String> {
189 let arm_shape = shape
190 .block_indent(context.config.tab_spaces())
191 .with_max_width(context.config);
193 let arm_len = arms.len();
194 let is_last_iter = repeat(false)
195 .take(arm_len.checked_sub(1).unwrap_or(0))
196 .chain(repeat(true));
197 let beginning_verts = collect_beginning_verts(context, arms, span);
198 let items = itemize_list(
199 context.snippet_provider,
202 .zip(beginning_verts.into_iter())
203 .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
206 |arm| arm.span().lo(),
207 |arm| arm.span().hi(),
208 |arm| arm.rewrite(context, arm_shape),
213 let arms_vec: Vec<_> = items.collect();
214 let fmt = ListFormatting {
215 tactic: DefinitiveListTactic::Vertical,
216 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
218 trailing_separator: SeparatorTactic::Never,
219 separator_place: SeparatorPlace::Back,
221 ends_with_newline: true,
222 preserve_newline: true,
223 config: context.config,
226 write_list(&arms_vec, &fmt)
229 fn rewrite_match_arm(
230 context: &RewriteContext,
234 beginning_vert: Option<BytePos>,
235 ) -> Option<String> {
236 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
237 if contains_skip(&arm.attrs) {
238 let (_, body) = flatten_arm_body(context, &arm.body);
239 // `arm.span()` does not include trailing comma, add it manually.
242 context.snippet(arm.span()),
243 arm_comma(context.config, body, is_last),
246 let missing_span = mk_sp(
247 arm.attrs[arm.attrs.len() - 1].span.hi(),
248 arm.pats[0].span.lo(),
250 (missing_span, arm.attrs.rewrite(context, shape)?)
252 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
254 let pats_str = rewrite_match_pattern(
256 &ptr_vec_to_ref_vec(&arm.pats),
258 beginning_vert.is_some(),
260 ).and_then(|pats_str| {
261 combine_strs_with_missing_comments(
280 fn rewrite_match_pattern(
281 context: &RewriteContext,
283 guard: &Option<ptr::P<ast::Expr>>,
284 has_beginning_vert: bool,
286 ) -> Option<String> {
290 let pat_shape = shape
292 .offset_left(if has_beginning_vert { 2 } else { 0 })?;
293 let pats_str = rewrite_multiple_patterns(context, pats, pat_shape)?;
294 let beginning_vert = if has_beginning_vert { "| " } else { "" };
297 let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
299 Some(format!("{}{}{}", beginning_vert, pats_str, guard_str))
303 // @extend: true if the arm body can be put next to `=>`
304 // @body: flattened body, if the body is block with a single expression
305 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
307 ast::ExprKind::Block(ref block)
308 if !is_unsafe_block(block)
309 && is_simple_block(block, Some(&body.attrs), context.codemap) =>
311 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
313 !context.config.force_multiline_blocks() && can_flatten_block_around_this(expr),
321 !context.config.force_multiline_blocks() && body.can_be_overflowed(context, 1),
327 fn rewrite_match_body(
328 context: &RewriteContext,
329 body: &ptr::P<ast::Expr>,
334 ) -> Option<String> {
335 let (extend, body) = flatten_arm_body(context, body);
336 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
339 is_empty_block(block, Some(&body.attrs), context.codemap),
345 let comma = arm_comma(context.config, body, is_last);
346 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
348 let combine_orig_body = |body_str: &str| {
349 let block_sep = match context.config.control_brace_style() {
350 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
354 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
357 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
358 let next_line_indent = if !is_block || is_empty_block {
359 shape.indent.block_indent(context.config)
363 let combine_next_line_body = |body_str: &str| {
368 next_line_indent.to_string_with_newline(context.config),
373 let indent_str = shape.indent.to_string_with_newline(context.config);
374 let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
375 let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
376 let comma = if context.config.match_block_trailing_comma() {
381 ("{", format!("{}}}{}", indent_str, comma))
383 ("", String::from(","))
386 let block_sep = match context.config.control_brace_style() {
387 ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
388 _ if body_prefix.is_empty() => "".to_owned(),
389 _ if forbid_same_line => format!("{}{}", alt_block_sep, body_prefix),
390 _ => format!(" {}", body_prefix),
391 } + &nested_indent_str;
395 pats_str, block_sep, body_str, body_suffix
399 // Let's try and get the arm body on the same line as the condition.
401 let orig_body_shape = shape
402 .offset_left(extra_offset(pats_str, shape) + 4)
403 .and_then(|shape| shape.sub_width(comma.len()));
404 let orig_body = if let Some(body_shape) = orig_body_shape {
405 let rewrite = nop_block_collapse(
406 format_expr(body, ExprType::Statement, context, body_shape),
414 || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
416 return combine_orig_body(body_str);
423 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
425 // Try putting body on the next line and see if it looks better.
426 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
427 let next_line_body = nop_block_collapse(
428 format_expr(body, ExprType::Statement, context, next_line_body_shape),
429 next_line_body_shape.width,
431 match (orig_body, next_line_body) {
432 (Some(ref orig_str), Some(ref next_line_str))
434 || prefer_next_line(orig_str, next_line_str, RhsTactics::Default) =>
436 combine_next_line_body(next_line_str)
438 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
439 combine_orig_body(orig_str)
441 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
442 combine_next_line_body(next_line_str)
444 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
445 (None, None) => None,
446 (Some(ref orig_str), _) => combine_orig_body(orig_str),
450 // The `if ...` guard on a match arm.
452 context: &RewriteContext,
453 guard: &Option<ptr::P<ast::Expr>>,
455 // The amount of space used up on this line for the pattern in
456 // the arm (excludes offset).
457 pattern_width: usize,
458 ) -> Option<String> {
459 if let Some(ref guard) = *guard {
460 // First try to fit the guard string on the same line as the pattern.
461 // 4 = ` if `, 5 = ` => {`
462 let cond_shape = shape
463 .offset_left(pattern_width + 4)
464 .and_then(|s| s.sub_width(5));
465 if let Some(cond_shape) = cond_shape {
466 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
467 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
468 return Some(format!(" if {}", cond_str));
473 // Not enough space to put the guard after the pattern, try a newline.
474 // 3 = `if `, 5 = ` => {`
475 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
477 .and_then(|s| s.sub_width(5));
478 if let Some(cond_shape) = cond_shape {
479 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
482 cond_shape.indent.to_string_with_newline(context.config),
494 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
495 debug!("nop_block_collapse {:?} {}", block_str, budget);
496 block_str.map(|block_str| {
497 if block_str.starts_with('{') && budget >= 2
498 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
507 fn can_flatten_block_around_this(body: &ast::Expr) -> bool {
509 // We do not allow `if` to stay on the same line, since we could easily mistake
510 // `pat => if cond { ... }` and `pat if cond => { ... }`.
511 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
512 // We do not allow collapsing a block around expression with condition
513 // to avoid it being cluttered with match arm.
514 ast::ExprKind::ForLoop(..) | ast::ExprKind::While(..) | ast::ExprKind::WhileLet(..) => {
517 ast::ExprKind::Loop(..)
518 | ast::ExprKind::Match(..)
519 | ast::ExprKind::Block(..)
520 | ast::ExprKind::Closure(..)
521 | ast::ExprKind::Array(..)
522 | ast::ExprKind::Call(..)
523 | ast::ExprKind::MethodCall(..)
524 | ast::ExprKind::Mac(..)
525 | ast::ExprKind::Struct(..)
526 | ast::ExprKind::Tup(..) => true,
527 ast::ExprKind::AddrOf(_, ref expr)
528 | ast::ExprKind::Box(ref expr)
529 | ast::ExprKind::Try(ref expr)
530 | ast::ExprKind::Unary(_, ref expr)
531 | ast::ExprKind::Cast(ref expr, _) => can_flatten_block_around_this(expr),