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::source_map::{BytePos, Span};
17 use syntax::{ast, ptr};
19 use comment::{combine_strs_with_missing_comments, rewrite_comment};
20 use config::{Config, ControlBraceStyle, IndentStyle};
22 format_expr, is_empty_block, is_simple_block, is_unsafe_block, prefer_next_line,
23 rewrite_multiple_patterns, ExprType, RhsTactics, ToExpr,
25 use lists::{itemize_list, write_list, ListFormatting};
26 use rewrite::{Rewrite, RewriteContext};
28 use source_map::SpanUtils;
31 contains_skip, extra_offset, first_line_width, inner_attributes, last_line_extendable, mk_sp,
32 ptr_vec_to_ref_vec, trimmed_last_line_width,
35 /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
36 struct ArmWrapper<'a> {
37 pub arm: &'a ast::Arm,
38 /// True if the arm is the last one in match expression. Used to decide on whether we should add
39 /// trailing comma to the match arm when `config.trailing_comma() == Never`.
41 /// Holds a byte position of `|` at the beginning of the arm pattern, if available.
42 pub beginning_vert: Option<BytePos>,
45 impl<'a> ArmWrapper<'a> {
49 beginning_vert: Option<BytePos>,
59 impl<'a> Spanned for ArmWrapper<'a> {
60 fn span(&self) -> Span {
61 if let Some(lo) = self.beginning_vert {
62 mk_sp(lo, self.arm.span().hi())
69 impl<'a> Rewrite for ArmWrapper<'a> {
70 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
71 rewrite_match_arm(context, self.arm, shape, self.is_last)
76 context: &RewriteContext,
81 attrs: &[ast::Attribute],
83 // Do not take the rhs overhead from the upper expressions into account
84 // when rewriting match condition.
85 let cond_shape = Shape {
86 width: context.budget(shape.used_width()),
90 let cond_shape = match context.config.indent_style() {
91 IndentStyle::Visual => cond_shape.shrink_left(6)?,
92 IndentStyle::Block => cond_shape.offset_left(6)?,
94 let cond_str = cond.rewrite(context, cond_shape)?;
95 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
96 let block_sep = match context.config.control_brace_style() {
97 ControlBraceStyle::AlwaysNextLine => alt_block_sep,
98 _ if last_line_extendable(&cond_str) => " ",
100 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => alt_block_sep,
104 let nested_indent_str = shape
106 .block_indent(context.config)
107 .to_string(context.config);
109 let inner_attrs = &inner_attributes(attrs);
110 let inner_attrs_str = if inner_attrs.is_empty() {
114 .rewrite(context, shape)
115 .map(|s| format!("{}{}\n", nested_indent_str, s))?
118 let open_brace_pos = if inner_attrs.is_empty() {
119 let hi = if arms.is_empty() {
126 .span_after(mk_sp(cond.span.hi(), hi), "{")
128 inner_attrs[inner_attrs.len() - 1].span().hi()
132 let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
133 if snippet.trim().is_empty() {
134 Some(format!("match {} {{}}", cond_str))
136 // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
137 Some(context.snippet(span).to_owned())
140 let span_after_cond = mk_sp(cond.span.hi(), span.hi());
142 "match {}{}{{\n{}{}{}\n{}}}",
147 rewrite_match_arms(context, arms, shape, span_after_cond, open_brace_pos)?,
148 shape.indent.to_string(context.config),
153 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
154 if is_last && config.trailing_comma() == SeparatorTactic::Never {
156 } else if config.match_block_trailing_comma() {
158 } else if let ast::ExprKind::Block(ref block, _) = body.node {
159 if let ast::BlockCheckMode::Default = block.rules {
169 /// Collect a byte position of the beginning `|` for each arm, if available.
170 fn collect_beginning_verts(
171 context: &RewriteContext,
174 ) -> Vec<Option<BytePos>> {
175 let mut beginning_verts = Vec::with_capacity(arms.len());
176 let mut lo = context.snippet_provider.span_after(span, "{");
178 let hi = arm.pats[0].span.lo();
179 let missing_span = mk_sp(lo, hi);
180 beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
181 lo = arm.span().hi();
186 fn rewrite_match_arms(
187 context: &RewriteContext,
191 open_brace_pos: BytePos,
192 ) -> Option<String> {
193 let arm_shape = shape
194 .block_indent(context.config.tab_spaces())
195 .with_max_width(context.config);
197 let arm_len = arms.len();
198 let is_last_iter = repeat(false)
199 .take(arm_len.saturating_sub(1))
200 .chain(repeat(true));
201 let beginning_verts = collect_beginning_verts(context, arms, span);
202 let items = itemize_list(
203 context.snippet_provider,
206 .zip(beginning_verts.into_iter())
207 .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
210 |arm| arm.span().lo(),
211 |arm| arm.span().hi(),
212 |arm| arm.rewrite(context, arm_shape),
217 let arms_vec: Vec<_> = items.collect();
218 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
219 let fmt = ListFormatting::new(arm_shape, context.config)
221 .preserve_newline(true);
223 write_list(&arms_vec, &fmt)
226 fn rewrite_match_arm(
227 context: &RewriteContext,
231 ) -> Option<String> {
232 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
233 if contains_skip(&arm.attrs) {
234 let (_, body) = flatten_arm_body(context, &arm.body);
235 // `arm.span()` does not include trailing comma, add it manually.
238 context.snippet(arm.span()),
239 arm_comma(context.config, body, is_last),
242 let missing_span = mk_sp(
243 arm.attrs[arm.attrs.len() - 1].span.hi(),
244 arm.pats[0].span.lo(),
246 (missing_span, arm.attrs.rewrite(context, shape)?)
248 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
251 rewrite_match_pattern(context, &ptr_vec_to_ref_vec(&arm.pats), &arm.guard, shape)
252 .and_then(|pats_str| {
253 combine_strs_with_missing_comments(
263 let arrow_span = mk_sp(arm.pats.last().unwrap().span.hi(), arm.body.span.lo());
275 fn rewrite_match_pattern(
276 context: &RewriteContext,
278 guard: &Option<ast::Guard>,
280 ) -> Option<String> {
283 let pat_shape = shape.sub_width(5)?;
284 let pats_str = rewrite_multiple_patterns(context, pats, pat_shape)?;
287 let guard_str = rewrite_guard(
291 trimmed_last_line_width(&pats_str),
292 pats_str.contains('\n'),
295 Some(format!("{}{}", pats_str, guard_str))
298 fn block_can_be_flattened<'a>(
299 context: &RewriteContext,
301 ) -> Option<&'a ast::Block> {
303 ast::ExprKind::Block(ref block, _)
304 if !is_unsafe_block(block)
305 && is_simple_block(block, Some(&expr.attrs), context.source_map) =>
314 // @extend: true if the arm body can be put next to `=>`
315 // @body: flattened body, if the body is block with a single expression
316 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
317 if let Some(ref block) = block_can_be_flattened(context, body) {
318 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
319 if let ast::ExprKind::Block(..) = expr.node {
320 flatten_arm_body(context, expr)
322 let can_extend_expr =
323 !context.config.force_multiline_blocks() && can_flatten_block_around_this(expr);
324 (can_extend_expr, &*expr)
331 !context.config.force_multiline_blocks() && body.can_be_overflowed(context, 1),
337 fn rewrite_match_body(
338 context: &RewriteContext,
339 body: &ptr::P<ast::Expr>,
345 ) -> Option<String> {
346 let (extend, body) = flatten_arm_body(context, body);
347 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block, _) = body.node {
350 is_empty_block(block, Some(&body.attrs), context.source_map),
356 let comma = arm_comma(context.config, body, is_last);
357 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
359 let combine_orig_body = |body_str: &str| {
360 let block_sep = match context.config.control_brace_style() {
361 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
365 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
368 let next_line_indent = if !is_block || is_empty_block {
369 shape.indent.block_indent(context.config)
374 let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
376 // Look for comments between `=>` and the start of the body.
377 let arrow_comment = {
378 let arrow_snippet = context.snippet(arrow_span).trim();
379 let arrow_index = arrow_snippet.find("=>").unwrap();
381 let comment_str = arrow_snippet[arrow_index + 2..].trim();
382 if comment_str.is_empty() {
385 rewrite_comment(comment_str, false, shape, &context.config)?
389 let combine_next_line_body = |body_str: &str| {
390 let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
393 let mut result = pats_str.to_owned();
394 result.push_str(" =>");
395 if !arrow_comment.is_empty() {
396 result.push_str(&nested_indent_str);
397 result.push_str(&arrow_comment);
399 result.push_str(&nested_indent_str);
400 result.push_str(&body_str);
404 let indent_str = shape.indent.to_string_with_newline(context.config);
405 let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
406 let comma = if context.config.match_block_trailing_comma() {
411 ("{", format!("{}}}{}", indent_str, comma))
413 ("", String::from(","))
416 let block_sep = match context.config.control_brace_style() {
417 ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
418 _ if body_prefix.is_empty() => "".to_owned(),
419 _ if forbid_same_line || !arrow_comment.is_empty() => {
420 format!("{}{}", alt_block_sep, body_prefix)
422 _ => format!(" {}", body_prefix),
423 } + &nested_indent_str;
425 let mut result = pats_str.to_owned();
426 result.push_str(" =>");
427 if !arrow_comment.is_empty() {
428 result.push_str(&indent_str);
429 result.push_str(&arrow_comment);
431 result.push_str(&block_sep);
432 result.push_str(&body_str);
433 result.push_str(&body_suffix);
437 // Let's try and get the arm body on the same line as the condition.
439 let orig_body_shape = shape
440 .offset_left(extra_offset(pats_str, shape) + 4)
441 .and_then(|shape| shape.sub_width(comma.len()));
442 let orig_body = if forbid_same_line || !arrow_comment.is_empty() {
444 } else if let Some(body_shape) = orig_body_shape {
445 let rewrite = nop_block_collapse(
446 format_expr(body, ExprType::Statement, context, body_shape),
452 if is_block || (!body_str.contains('\n') && body_str.len() <= body_shape.width) =>
454 return combine_orig_body(body_str);
461 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
463 // Try putting body on the next line and see if it looks better.
464 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
465 let next_line_body = nop_block_collapse(
466 format_expr(body, ExprType::Statement, context, next_line_body_shape),
467 next_line_body_shape.width,
469 match (orig_body, next_line_body) {
470 (Some(ref orig_str), Some(ref next_line_str))
471 if prefer_next_line(orig_str, next_line_str, RhsTactics::Default) =>
473 combine_next_line_body(next_line_str)
475 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
476 combine_orig_body(orig_str)
478 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
479 combine_next_line_body(next_line_str)
481 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
482 (None, None) => None,
483 (Some(ref orig_str), _) => combine_orig_body(orig_str),
487 impl Rewrite for ast::Guard {
488 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
490 ast::Guard::If(ref expr) => expr.rewrite(context, shape),
495 // The `if ...` guard on a match arm.
497 context: &RewriteContext,
498 guard: &Option<ast::Guard>,
500 // The amount of space used up on this line for the pattern in
501 // the arm (excludes offset).
502 pattern_width: usize,
503 multiline_pattern: bool,
504 ) -> Option<String> {
505 if let Some(ref guard) = *guard {
506 // First try to fit the guard string on the same line as the pattern.
507 // 4 = ` if `, 5 = ` => {`
508 let cond_shape = shape
509 .offset_left(pattern_width + 4)
510 .and_then(|s| s.sub_width(5));
511 if !multiline_pattern {
512 if let Some(cond_shape) = cond_shape {
513 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
514 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
515 return Some(format!(" if {}", cond_str));
521 // Not enough space to put the guard after the pattern, try a newline.
522 // 3 = `if `, 5 = ` => {`
523 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
525 .and_then(|s| s.sub_width(5));
526 if let Some(cond_shape) = cond_shape {
527 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
530 cond_shape.indent.to_string_with_newline(context.config),
542 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
543 debug!("nop_block_collapse {:?} {}", block_str, budget);
544 block_str.map(|block_str| {
545 if block_str.starts_with('{')
547 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
556 fn can_flatten_block_around_this(body: &ast::Expr) -> bool {
558 // We do not allow `if` to stay on the same line, since we could easily mistake
559 // `pat => if cond { ... }` and `pat if cond => { ... }`.
560 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
561 // We do not allow collapsing a block around expression with condition
562 // to avoid it being cluttered with match arm.
563 ast::ExprKind::ForLoop(..) | ast::ExprKind::While(..) | ast::ExprKind::WhileLet(..) => {
566 ast::ExprKind::Loop(..)
567 | ast::ExprKind::Match(..)
568 | ast::ExprKind::Block(..)
569 | ast::ExprKind::Closure(..)
570 | ast::ExprKind::Array(..)
571 | ast::ExprKind::Call(..)
572 | ast::ExprKind::MethodCall(..)
573 | ast::ExprKind::Mac(..)
574 | ast::ExprKind::Struct(..)
575 | ast::ExprKind::Tup(..) => true,
576 ast::ExprKind::AddrOf(_, ref expr)
577 | ast::ExprKind::Box(ref expr)
578 | ast::ExprKind::Try(ref expr)
579 | ast::ExprKind::Unary(_, ref expr)
580 | ast::ExprKind::Cast(ref expr, _) => can_flatten_block_around_this(expr),