1 //! Format match expression.
5 use syntax::source_map::{BytePos, Span};
6 use syntax::{ast, ptr};
8 use crate::comment::{combine_strs_with_missing_comments, rewrite_comment};
9 use crate::config::lists::*;
10 use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
12 format_expr, is_empty_block, is_simple_block, is_unsafe_block, prefer_next_line, rewrite_cond,
15 use crate::lists::{itemize_list, write_list, ListFormatting};
16 use crate::rewrite::{Rewrite, RewriteContext};
17 use crate::shape::Shape;
18 use crate::source_map::SpanUtils;
19 use crate::spanned::Spanned;
21 contains_skip, extra_offset, first_line_width, inner_attributes, last_line_extendable, mk_sp,
22 semicolon_for_expr, trimmed_last_line_width, unicode_str_width,
25 /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
26 struct ArmWrapper<'a> {
28 /// `true` if the arm is the last one in match expression. Used to decide on whether we should
29 /// add trailing comma to the match arm when `config.trailing_comma() == Never`.
31 /// Holds a byte position of `|` at the beginning of the arm pattern, if available.
32 beginning_vert: Option<BytePos>,
35 impl<'a> ArmWrapper<'a> {
36 fn new(arm: &'a ast::Arm, is_last: bool, beginning_vert: Option<BytePos>) -> ArmWrapper<'a> {
45 impl<'a> Spanned for ArmWrapper<'a> {
46 fn span(&self) -> Span {
47 if let Some(lo) = self.beginning_vert {
48 mk_sp(lo, self.arm.span().hi())
55 impl<'a> Rewrite for ArmWrapper<'a> {
56 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
57 rewrite_match_arm(context, self.arm, shape, self.is_last)
61 pub(crate) fn rewrite_match(
62 context: &RewriteContext<'_>,
67 attrs: &[ast::Attribute],
69 // Do not take the rhs overhead from the upper expressions into account
70 // when rewriting match condition.
71 let cond_shape = Shape {
72 width: context.budget(shape.used_width()),
76 let cond_shape = match context.config.indent_style() {
77 IndentStyle::Visual => cond_shape.shrink_left(6)?,
78 IndentStyle::Block => cond_shape.offset_left(6)?,
80 let cond_str = cond.rewrite(context, cond_shape)?;
81 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
82 let block_sep = match context.config.control_brace_style() {
83 ControlBraceStyle::AlwaysNextLine => alt_block_sep,
84 _ if last_line_extendable(&cond_str) => " ",
86 _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => alt_block_sep,
90 let nested_indent_str = shape
92 .block_indent(context.config)
93 .to_string(context.config);
95 let inner_attrs = &inner_attributes(attrs);
96 let inner_attrs_str = if inner_attrs.is_empty() {
100 .rewrite(context, shape)
101 .map(|s| format!("{}{}\n", nested_indent_str, s))?
104 let open_brace_pos = if inner_attrs.is_empty() {
105 let hi = if arms.is_empty() {
112 .span_after(mk_sp(cond.span.hi(), hi), "{")
114 inner_attrs[inner_attrs.len() - 1].span.hi()
118 let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
119 if snippet.trim().is_empty() {
120 Some(format!("match {} {{}}", cond_str))
122 // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
123 Some(context.snippet(span).to_owned())
126 let span_after_cond = mk_sp(cond.span.hi(), span.hi());
128 "match {}{}{{\n{}{}{}\n{}}}",
133 rewrite_match_arms(context, arms, shape, span_after_cond, open_brace_pos)?,
134 shape.indent.to_string(context.config),
139 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
140 if is_last && config.trailing_comma() == SeparatorTactic::Never {
142 } else if config.match_block_trailing_comma() {
144 } else if let ast::ExprKind::Block(ref block, _) = body.node {
145 if let ast::BlockCheckMode::Default = block.rules {
155 /// Collect a byte position of the beginning `|` for each arm, if available.
156 fn collect_beginning_verts(
157 context: &RewriteContext<'_>,
160 ) -> Vec<Option<BytePos>> {
161 let mut beginning_verts = Vec::with_capacity(arms.len());
162 let mut lo = context.snippet_provider.span_after(span, "{");
164 let hi = arm.pat.span.lo();
165 let missing_span = mk_sp(lo, hi);
166 beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
167 lo = arm.span().hi();
172 fn rewrite_match_arms(
173 context: &RewriteContext<'_>,
177 open_brace_pos: BytePos,
178 ) -> Option<String> {
179 let arm_shape = shape
180 .block_indent(context.config.tab_spaces())
181 .with_max_width(context.config);
183 let arm_len = arms.len();
184 let is_last_iter = repeat(false)
185 .take(arm_len.saturating_sub(1))
186 .chain(repeat(true));
187 let beginning_verts = collect_beginning_verts(context, arms, span);
188 let items = itemize_list(
189 context.snippet_provider,
192 .zip(beginning_verts.into_iter())
193 .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
196 |arm| arm.span().lo(),
197 |arm| arm.span().hi(),
198 |arm| arm.rewrite(context, arm_shape),
203 let arms_vec: Vec<_> = items.collect();
204 // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
205 let fmt = ListFormatting::new(arm_shape, context.config)
207 .preserve_newline(true);
209 write_list(&arms_vec, &fmt)
212 fn rewrite_match_arm(
213 context: &RewriteContext<'_>,
217 ) -> Option<String> {
218 let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
219 if contains_skip(&arm.attrs) {
220 let (_, body) = flatten_arm_body(context, &arm.body, None);
221 // `arm.span()` does not include trailing comma, add it manually.
224 context.snippet(arm.span()),
225 arm_comma(context.config, body, is_last),
228 let missing_span = mk_sp(arm.attrs[arm.attrs.len() - 1].span.hi(), arm.pat.span.lo());
229 (missing_span, arm.attrs.rewrite(context, shape)?)
231 (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
236 let pat_shape = shape.sub_width(5)?;
237 let pats_str = arm.pat.rewrite(context, pat_shape)?;
240 let block_like_pat = trimmed_last_line_width(&pats_str) <= context.config.tab_spaces();
241 let new_line_guard = pats_str.contains('\n') && !block_like_pat;
242 let guard_str = rewrite_guard(
246 trimmed_last_line_width(&pats_str),
250 let lhs_str = combine_strs_with_missing_comments(
253 &format!("{}{}", pats_str, guard_str),
259 let arrow_span = mk_sp(arm.pat.span.hi(), arm.body.span().lo());
265 guard_str.contains('\n'),
271 fn block_can_be_flattened<'a>(
272 context: &RewriteContext<'_>,
274 ) -> Option<&'a ast::Block> {
276 ast::ExprKind::Block(ref block, _)
277 if !is_unsafe_block(block)
278 && !context.inside_macro()
279 && is_simple_block(block, Some(&expr.attrs), context.source_map) =>
288 // @extend: true if the arm body can be put next to `=>`
289 // @body: flattened body, if the body is block with a single expression
290 fn flatten_arm_body<'a>(
291 context: &'a RewriteContext<'_>,
293 opt_shape: Option<Shape>,
294 ) -> (bool, &'a ast::Expr) {
296 |expr| !context.config.force_multiline_blocks() && can_flatten_block_around_this(expr);
298 if let Some(ref block) = block_can_be_flattened(context, body) {
299 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
300 if let ast::ExprKind::Block(..) = expr.node {
301 flatten_arm_body(context, expr, None)
303 let cond_becomes_muti_line = opt_shape
304 .and_then(|shape| rewrite_cond(context, expr, shape))
305 .map_or(false, |cond| cond.contains('\n'));
306 if cond_becomes_muti_line {
309 (can_extend(expr), &*expr)
316 (can_extend(body), &*body)
320 fn rewrite_match_body(
321 context: &RewriteContext<'_>,
322 body: &ptr::P<ast::Expr>,
328 ) -> Option<String> {
329 let (extend, body) = flatten_arm_body(
332 shape.offset_left(extra_offset(pats_str, shape) + 4),
334 let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block, _) = body.node {
337 is_empty_block(block, Some(&body.attrs), context.source_map),
343 let comma = arm_comma(context.config, body, is_last);
344 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
346 let combine_orig_body = |body_str: &str| {
347 let block_sep = match context.config.control_brace_style() {
348 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
352 Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
355 let next_line_indent = if !is_block || is_empty_block {
356 shape.indent.block_indent(context.config)
361 let forbid_same_line =
362 (has_guard && pats_str.contains('\n') && !is_empty_block) || !body.attrs.is_empty();
364 // Look for comments between `=>` and the start of the body.
365 let arrow_comment = {
366 let arrow_snippet = context.snippet(arrow_span).trim();
367 // search for the arrow starting from the end of the snippet since there may be a match
368 // expression within the guard
369 let arrow_index = arrow_snippet.rfind("=>").unwrap();
371 let comment_str = arrow_snippet[arrow_index + 2..].trim();
372 if comment_str.is_empty() {
375 rewrite_comment(comment_str, false, shape, &context.config)?
379 let combine_next_line_body = |body_str: &str| {
380 let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
383 let mut result = pats_str.to_owned();
384 result.push_str(" =>");
385 if !arrow_comment.is_empty() {
386 result.push_str(&nested_indent_str);
387 result.push_str(&arrow_comment);
389 result.push_str(&nested_indent_str);
390 result.push_str(&body_str);
394 let indent_str = shape.indent.to_string_with_newline(context.config);
395 let (body_prefix, body_suffix) =
396 if context.config.match_arm_blocks() && !context.inside_macro() {
397 let comma = if context.config.match_block_trailing_comma() {
402 let semicolon = if context.config.version() == Version::One {
405 if semicolon_for_expr(context, body) {
411 ("{", format!("{}{}}}{}", semicolon, 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),
453 || (!body_str.contains('\n')
454 && unicode_str_width(body_str) <= body_shape.width) =>
456 return combine_orig_body(body_str);
463 let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
465 // Try putting body on the next line and see if it looks better.
466 let next_line_body_shape = Shape::indented(next_line_indent, context.config);
467 let next_line_body = nop_block_collapse(
468 format_expr(body, ExprType::Statement, context, next_line_body_shape),
469 next_line_body_shape.width,
471 match (orig_body, next_line_body) {
472 (Some(ref orig_str), Some(ref next_line_str))
473 if prefer_next_line(orig_str, next_line_str, RhsTactics::Default) =>
475 combine_next_line_body(next_line_str)
477 (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
478 combine_orig_body(orig_str)
480 (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
481 combine_next_line_body(next_line_str)
483 (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
484 (None, None) => None,
485 (Some(ref orig_str), _) => combine_orig_body(orig_str),
489 // The `if ...` guard on a match arm.
491 context: &RewriteContext<'_>,
492 guard: &Option<ptr::P<ast::Expr>>,
494 // The amount of space used up on this line for the pattern in
495 // the arm (excludes offset).
496 pattern_width: usize,
497 multiline_pattern: bool,
498 ) -> Option<String> {
499 if let Some(ref guard) = *guard {
500 // First try to fit the guard string on the same line as the pattern.
501 // 4 = ` if `, 5 = ` => {`
502 let cond_shape = shape
503 .offset_left(pattern_width + 4)
504 .and_then(|s| s.sub_width(5));
505 if !multiline_pattern {
506 if let Some(cond_shape) = cond_shape {
507 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
508 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
509 return Some(format!(" if {}", cond_str));
515 // Not enough space to put the guard after the pattern, try a newline.
516 // 3 = `if `, 5 = ` => {`
517 let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
519 .and_then(|s| s.sub_width(5));
520 if let Some(cond_shape) = cond_shape {
521 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
524 cond_shape.indent.to_string_with_newline(context.config),
536 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
537 debug!("nop_block_collapse {:?} {}", block_str, budget);
538 block_str.map(|block_str| {
539 if block_str.starts_with('{')
541 && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
550 fn can_flatten_block_around_this(body: &ast::Expr) -> bool {
552 // We do not allow `if` to stay on the same line, since we could easily mistake
553 // `pat => if cond { ... }` and `pat if cond => { ... }`.
554 ast::ExprKind::If(..) => false,
555 // We do not allow collapsing a block around expression with condition
556 // to avoid it being cluttered with match arm.
557 ast::ExprKind::ForLoop(..) | ast::ExprKind::While(..) => false,
558 ast::ExprKind::Loop(..)
559 | ast::ExprKind::Match(..)
560 | ast::ExprKind::Block(..)
561 | ast::ExprKind::Closure(..)
562 | ast::ExprKind::Array(..)
563 | ast::ExprKind::Call(..)
564 | ast::ExprKind::MethodCall(..)
565 | ast::ExprKind::Mac(..)
566 | ast::ExprKind::Struct(..)
567 | ast::ExprKind::Tup(..) => true,
568 ast::ExprKind::AddrOf(_, ref expr)
569 | ast::ExprKind::Box(ref expr)
570 | ast::ExprKind::Try(ref expr)
571 | ast::ExprKind::Unary(_, ref expr)
572 | ast::ExprKind::Index(ref expr, _)
573 | ast::ExprKind::Cast(ref expr, _) => can_flatten_block_around_this(expr),